How do you encrypt a string with BigInteger?

Question: I am attempting to take an alphanumeric string and encrypt it using big integer. My encryption and decryption work when I initialize BigInteger with a decimal value, such as 10. However when I initialize BigInteger using a string the decryption does not return the original BigInteger.
Here is the code I am using to generate my keys and encrypt/decrypt.
public static void main(String args[]) {
    int keySize = 32;

    BigInteger prime1 = new BigInteger(keySize / 2, 100, new SecureRandom());
    BigInteger prime2 = new BigInteger(keySize / 2, 100, new SecureRandom());

    BigInteger n = prime1.multiply(prime2);
    BigInteger totient = prime1.subtract(BigInteger.ONE).multiply(prime2.subtract(BigInteger.ONE));

    //create the private key
    BigInteger e;
    do e = new BigInteger(totient.bitLength(), new SecureRandom());
    while (e.compareTo(BigInteger.ONE) <= 0 || e.compareTo(totient) >= 0 || !e.gcd(totient).equals(BigInteger.ONE));

    //create public key
    BigInteger d = e.modInverse(totient);

    String original = "Hello World!";

    BigInteger enc = new BigInteger(original.getBytes());
    System.out.println("Original: " + enc.toString());

    //encrypt
    enc = enc.modPow(e, n);

    //decrypt
    BigInteger dec = enc;
    dec = dec.modPow(d, n);
    System.out.println("Result: " + dec.toString());
}

As I said, if I initialize enc to an integer value, say 10, my results would be...
Original: 10
Result: 10

However, when I initialize to a string, as in the code above, my results come out like this...
Original: 22405534230753928650781647905
Result: 1828948854

Did I implement my encryption wrong or is there something I am missing in converting the string to a BigInteger to encrypt?
Answer:
Did I implement my encryption wrong

Yes.
It looks like you're implementing RSA with a 32-bit keySize. This limits the size of your message to 32 bits as well; the message you're trying to encrypt is much larger than this.
Comment: Thank you, I kept the number small so I could easily view the numbers. I did not realize that could effect the encryption.


Listing properties of power-point charts and objects in excel

Question: I need some help here. So I have a power-point presentation with ~ 20 slides and each slide contains about 3-4 charts. Now, I need to jolt down the following in an excel sheet (using VBA macros):
 For each slide
 For each object
 1) Slide Name/Number
 2) Chart Name
 3) Chart type
 4) Chart height
 5) Chart width
 7) Chart - Position - Left
 7) Chart - Position - Top
Please help :)
Answer: This should get you started on your way.  i will represent the slide number.  You just need to write the variables to your excel sheet.
<code>For i = 1 to ActivePresentation.Slides(.Slides.Count).SlideNumber
   For Each s In ActivePresentation.Slides(i).Shapes
   Dim x, y, Z, a, b, C, D, e As String
    Let x =s.Name
    Let y = s.Type
    Let Z = s.Id
    Let a = s.OLEFormat.ProgID
    Let b = s.Height
    Let c = s.Width
    Let D = s.Left
    Let e = s.Top
Next s
Next i
</code>


Electric bass scale length and pickup angle

Question: While shopping for my first bass, I came across a combination I've never seen before: a used medium scale bass (32") with slanted pickups. A medium scale bass might be an easier transition for me since I play guitar, so I did some reading (see long, opinionated article) and learned that the shorter scale will affect the tone. I also learned that slanted, skewed, or angled pickups will change the tone of the strings relative to each other. The long scale basses (34") of this model do not have slanted pickups.
Was the slant put in to compensate for tonal changes from the shorter scale/is it likely that all medium scale basses of this model have slanted pickups? I imagine it would have been difficult for the original owner to change the orientation of the pickups. If I buy a medium scale bass, should I look for one with slanted pickups because their tone will be more similar to their long scale versions?
Now that I'm aware pickups can be slanted in either direction, I'll specify that this pickup is farther from the bridge on the E string side, and closer to the bridge on the G string side. Here's an image of one of the pickups, if it makes a difference:
If you compare the pickup angle with the little bit of the bridge that you can see in the lower left, the slant becomes more clear.
Comment: If any bass players are willing to glance at some pictures/make sure I'm not being ripped off with a problematic bass (possible rust?), I'd love to hop into a chat.
Comment: Bass guitars are not ordinary guitars that have been adapted.('easier transition'). A full sized bass is a different instrument, purpose built to do a job. It makes sense (to me at least) to get a 'proper' bass, and learn to use it in its own right. Since standard size is far more common, you'll be more comfortable eventually when you use someone else's more than likely standard bass, or trade up to a replacement. This doesn't answer the question, thus it's only a comment.
Answer: The pickups may simply be slanted because the manufacturer designed the instrument with a narrower string spacing, but also designed the instrument to use fairly standard off-the-shelf pickups. The pickups therefore need to be angled to get the pole pieces to match the tighter string spacing. Some manufacturers may adopt slanted pickups for tonal reasons. For example the Scott Whitley SWB-1 (now manufactured by Chowney basses) comes with two Jazz bass-style pickups, slanted so that the pickups sense the E and A strings nearer the bridge and the D and G strings nearer the neck. This will, on paper at least, keep the E and A sounding tighter and the D and G sounding fuller.
I personally think short and medium-scale basses have something of a bad rap for historical reasons. In the '60s and '70s, shorter-scale basses were either sold as budget-priced student/beginner instruments or were large hollow or semi-hollow affairs with idiosyncratic electronics. Combine that with the bass amps available, and the strings available, and you would quickly reach the conclusion that shorter-scale basses produce a muddy, undefined tone. I think that modern amplifier technology and modern bass string technology negate most, if not all, of the criticisms made of shorter-scale basses.
I will admit that I do have a horse in this race; I recently purchased a Fender Mustang bass. I don't consider it a less "proper" bass, simply because of the missing four inches of scale length. With a correctly balanced set of strings the bass is virtually indistinguishable from my Precision bass, but my shoulders, back and hands are a lot happier. For the record I'm just shy of six feet tall and have big hands, but wrestling my Precision bass seems like a lot of unnecessary work at times.
Comment: Isn't it uncommon for the long scale/medium scale versions of the same model to have different string spacing? The long scale version pickups are not slanted.
Comment: Though I guess it's really the chicken or the egg...were the pickups slanted to match tighter string spacing in the medium scale model, or did they have to tighten the string spacing to match the slanted pickups. Does string spacing affect tone?
Comment: I cannot think of too many production-line basses that are offered in both medium and long scale form. Lakland have done this, and Fender sometimes make medium or short scale Jazz basses. String spacing doesn't affect tone, but it does change the feel of the instrument, which some players prefer. Pickups may be slanted on a shorter-scale version of a full scale instrument to offset perceived tonal issues with shorter scale lengths, such as squeezing more fundamental bass or more bright-sounding harmonic overtones out of the design. It may, finally, just be an aesthetic choice!


Given a block_id, what would be the most reliable method to decide if the block was generated by Views?

Question: I would like to use hook_form_block_admin_configure_alter to add configuration options to the blocks admin, but only if the block is for a View. It's important to add the settings here rather than in the view settings itself, since it will grouped with other additional block settings that are not Views specific.
Thanks!
Answer: As Clive said, each block will contain the module name from which it was created in the block configuration. For views blocks, it's views module.
This module information will be available in the form structure itself, like below:
$form['module']['#value']

So you don't need to query the database to retrieve it.
Pseudo code:
function my_module_form_block_admin_configure_alter(&$form, &$form_state) {
  if ($form['module']['#value'] == 'views') {
    // ...
  }
}

Comment: Good call, that'll save an extra database hit
Answer: The module responsible for a block is listed as a column in the block table, so you can just do something like
$module = db_query('SELECT module FROM {block} WHERE bid = :bid', array(':bid' => $bid))->fetchField();
if ($module === 'views') {
  // ...
}


Not sure why I am getting [object Object] returned

Question: I finally was able to figure out how to remove the text from this element but save the button which was nested in it.
HTML:

This app will go through some of your markup to determmine if it could be more accessible.  We will start by checking the alt tags on your images, seeing if they exist, or if the tags are empty!

    lets get started!

JS:
EventUtility.addHandler(newBtnName, 'click', function(e) {

    var $noRemove = $('#output').find('#appButtonNextChecker'),
         text = 'flim-flam ' + $noRemove;
         console.log('next Checker, button!');

                $('#output').html(text);
});

I then tried to concatenate a new string with the button I saved, but to my surprise I received [object Object]?
I read somewhere it was a scoping issue, but I am not sure how that applies here?
Any help would be appreciated!
Comment: Use `var text = 'flim-flam ' + $noRemove.html();` instead.
Comment: $noRemove is an object, not a string
Answer: If you were doing .html( $noRemove ) that would have been fine, but the moment you want to concatenate a string, then you must get the html (string) to concatenate to the string. You cannot concatenate a string and an object.:
Use:
var text = 'flim-flam ' + $noRemove.html();

Or, to get all the html represented by $noRemove use:
var text = 'flim-flam ' + $('
').html( $noRemove ).html();

Or:
var text = 'flim-flam ' + $noRemove[0].outerHTML;
//WARNING -- works only if $noRemove.length equals 1

Comment: Second option might be what you're looking for.
Comment: Hey that worked! But that seems strange. Could you explain what `$('').html( $noRemove ).html();` is doing? Actually it really is the ``, I ask because it's not even in the `DOM` when I check it in the `developer tools`!!
Comment: `$('')` simply creates a `div` in memory; it could as well have been `` or `` or any other valid HTML tag. `` is the equivalent of `'. The trick simply enables you to access the complete HTML of the collection/object `$noRemove`, because you append the object to the `div` in memory and then get the `innerHTM` -- via `.html()` -- of the `div`. **In short that's how you get the `outerHTML` of a DOM element in jQuery, which means that `$noRemove[0].outerHTML` should work too.
Answer: How you want to concatenate string and button?! Do you want to get together the string and the button's value?
$noRemove is an object it is completely normal to get that message.
Comment: Great insight, but I guess that's as far as it goes?


How does a module tell Drupal which mail plugin should be used?

Question: How does a module tell Drupal which mail plugin should be used? The SMTP Authentication Support module uses the following code in the submission handler of its settings form.
$values = $form_state->getValues();
$config = $this->configFactory->getEditable('smtp.settings');
$mail_config = $this->configFactory->getEditable('system.mail');
$mail_system = $mail_config->get('interface');

// Updating config vars.
if (isset($values['smtp_password'])) {
  $config->set('smtp_password', $values['smtp_password']);
}
$config->set('smtp_on', $values['smtp_on'])
  ->set('smtp_host', $values['smtp_host'])
  ->set('smtp_hostbackup', $values['smtp_hostbackup'])
  ->set('smtp_port', $values['smtp_port'])
  ->set('smtp_protocol', $values['smtp_protocol'])
  ->set('smtp_username', $values['smtp_username'])
  ->set('smtp_from', $values['smtp_from'])
  ->set('smtp_fromname', $values['smtp_fromname'])
  ->set('smtp_allowhtml', $values['smtp_allowhtml'])
  ->set('smtp_debugging', $values['smtp_debugging'])
  ->save();

// If an address was given, send a test e-mail message.
if ($test_address = $values['smtp_test_address']) {
  $params['subject'] = t('Drupal SMTP test e-mail');
  $params['body'] = array(t('If you receive this message it means your site is capable of using SMTP to send e-mail.'));
  $account = \Drupal::currentUser();
  // If module is off, send the test message with SMTP by temporarily overriding.
  if (!$config->get('smtp_on')) {
    $original = $mail_config->get('interface');
    $mail_system['default'] = 'SMTPMailSystem';
    $mail_config->set('interface', $mail_system)->save();
  }
  \Drupal::service('plugin.manager.mail')->mail('smtp', 'smtp-test', $test_address, $account->getPreferredLangcode(), $params);
  if (!$config->get('smtp_on')) {
    $mail_config->set('interface', $original)->save();
  }
  drupal_set_message(t('A test e-mail has been sent to @email via SMTP. You may want to check the log for any error messages.', ['@email' => $test_address]));
}

This code is not working, since in the log set with the mail.log directive I see the following, where it is evident that Drupal is still using the mail plugin definined in PhpMail.php.

[11-Mar-2016 06:36:14 UTC] mail() on [/home/domain/public_html/core/lib/Drupal/Core/Mail/Plugin/Mail/PhpMail.php:101]: To: email@example.com -- Headers: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: 8Bit X-Mailer: Drupal Sender: email@example.com From: Edited <email@example.com>

I cleared the log before sending the test email from the administrative page of the SMTP Authentication Support module; so, I am sure the log is caused from sending the test email.
Since the method used from this module doesn't seem to work, what is the correct way to set the plugin Drupal uses to send emails?
Update
To make my question clearer, there are two things that are not clear to me in the code being used.

The code is setting the mail plugin Drupal should use, just for the test email, but as I can see that method doesn't work, since Drupal still uses the default plugin.
Apart from setting the mail plugin for the test email, the module doesn't change the mail plugin set by Drupal. How can Drupal know to use the mail plugin implemented by the module, then?
Comment: I think it is doing so appropriately though perhaps there's a `interface.MODULE_NAME` entry somewhere that's overriding it? I am also not sure if plugin ids can have capital letters or not.
Comment: I updated the question; I was missing a part of the code.
Comment: IMHO, modules like that shouldn't ever mess with that configuration directly.  Modules like that should rely on https://www.drupal.org/project/mailsystem which provides a UI to configure the used default or by module/key mail plugin. It also has its own separate configuration, so if you have that enabled, then the config changes above won't do anything.
Comment: @Berdir Still, that module needs to tell Drupal which mail plugin should be used. I am more interesting in how telling Drupal which mail plugin to use, rather than using a module. I looked at the code of that module just because it implements a mail plugin.
Comment: Someone has to do it, yes. My point is that it's not the module that should do it, because the way to do it can very based on whatever implementation of MailManager you happen to use. If you do not have mailsystem installed, it's in system.mail.yml. Either the default, or a per module or per module/key. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Mail%21MailManager.php/function/MailManager%3A%3AgetInstance/8.
Comment: But, if you have mailsystem installed, then the configuration lives in mailsystem.settings, because that module supports different configurations for formatting and actually sending the mail.
Comment: @Berdir So, as maintainer of a module implementing a mail plugin, I just annotate the plugin class with `@Mail{}`; as site maintainer, I set in the settings.php file the default mail plugin, in the same way I do for the cache backend. Alternatively, I use a module that set it for me. Did I get it correctly?
Answer: Basing on Mail backends are now annotated plugins, drupal_mail_service() has been removed and the documentation for the MailManagerInterface interface, a module implementing a mail plugin should not set its own plugin as default plugin because MailManagerInterface interface doesn't document any configuration key the classes implementing it should use; only the site maintainer eventually know which mail manager is being used, and which configuration keys that mail manager is using. This is similar to setting the cache handlers, which is done in the settings.php file.
The SMTP Authentication module is doing the correct thing when it doesn't set its plugin as default plugin for sending emails.
As for the code to send a test email, the correct one should not directly set the configuration keys, if it wants to be independent from the current implementation of the mail manager. Eventually, code similar to the following should be used.
$mailer = \Drupal::service('plugin.manager.mail')->createInstance($plugin_id);
$bool = $mailer->send($mailer->format($message));


What are common methods of intrusion into a Drupal website?

Question: I am running Drupal 6.28 that was recently hacked and there were scripts being executed out of the /tmp directory, apparently running a bitcoin mining server and other brute force scripts.
I would get random processes sometimes 2-4 at a time that would each consume over 100% cpu(core) for an indefinite period of time. Which would make sense if they were running some type of bitcoin mining operation or brute force attack.
To the best of my knowledge the attacker uploaded a file named 32.tar.gz to the site. Drupal moved this file to the /tmp directory, then attacker extracted into the same /tmp directory, which has 777 permissions.
I would gladly change the permissions on this folder to something more sane like 755, but in doing so, Drupal stops functioning properly.
All files/folders in my drupal install directory are owned like: myUser:www-data, where www-data is the user that PHP/Apache is running as.
The /tmp folder is owned by the same user and group, so I would think that it would be writable at 755, but that just isn't the case for some reason. Is there a way to harden the security of the site that would prevent this from happening?
Answer: The first question is how they are uploading and extracting the file. That is likely only possible via a vulnerable contributed module (probably an out of date one) or because they have credentials to your server (either at the drupal layer or the server - ie ssh or sftp layer).
The second question is why your tmp directory is in a publicly accessible location (is it?). If it's not then it seems more likely the problem is arbitrary code execution or credentials compromised.
Solutions: basically you have to "start over."

Audit every single account and permission
Audit every single file of code - download fresh copies from drupal.org and ensure the versions on your site match them exactly.
Install the security review and paranoia modules and read their documentation to ensure they are working properly. They will help audit your permissions and content.


ggplot Donut chart is not as desired

Question: I am trying to create a donut chart using ggplot2 with the following data (example).
    library(ggplot2)
    library(svglite)
    library(scales)

    # dataframe
    Sex = c('Male', 'Female')
    Number = c(125, 375)
    df = data.frame(Sex, Number)
    df

The code I used to generate donut chart is
    ggplot(aes(x= Sex, y = Number, fill = Sex), data = df) +
    geom_bar(stat = "identity") +
    coord_polar("y") +
    theme_void() +
    theme (legend.position="top") + # legend position
    geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
    ggtitle("Participants by Sex")

The above code generated the following chart. Some how not convinced with the chart.

For our purposes, the following chart would better communicate the message. How do I create a chart like this. Where am I doing wrong in my code? I have googled with out any success.
Thanks in advance for help.
Answer: They aren't in the same 'circle' because they have different x values. Imagine it as a normal plot first (i.e. without coord_polar("y")) and this will become clear. What you really want is them set at the same x value and then stacked. Here I set x to 2 because it then makes a nicely sized "donut".
donut <- ggplot(df, aes(x = 2, y = Number, fill = Sex)) +
  geom_col(position = "stack", width = 1) +
  geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
  xlim(0.5, 2.5) +
  ggtitle("Participants by Sex")

donut

donut +
  coord_polar("y") +
  theme_void() +
  theme(legend.position="top")

Comment: @ Jack Brookes, Thanks, It helped me.

ggplot Donut chart is not as desired


Exim4 mailer daemon address

Question: My exim4 mail server sends notification using the wrong extension, I mean:
Mail Delivery System <email@example.com>

This server is a multi-domain server and mydomain.err is one of managed domains but not the main one. I would like to set the main domain and the daemon address but I cannot find it in the configuration, I did a grep in all exim configuration looking for mydomain.err and I find it only here:
dc_other_hostnames='maindomain.com;mydomain.err;otherdomain.com'

Where can I change the daemon address and the main domain?
Answer: The variable you want is qualify_domain.  Depending on your configuration this may be read from /etc/mailname.
Comment: I found this note:  If MAIN_PRIMARY_HOSTNAME_AS_QUALIFY_DOMAIN is defined, the primary
# hostname is used. If not, but MAIN_QUALIFY_DOMAIN is set, the value
# of MAIN_QUALIFY_DOMAIN is used. If both macros are not defined,
# the first line of /etc/mailname is used.

Exim4 mailer daemon address


fancybox v2 with jQuery

Question: Please someone put me in the right direction, I can't get fancybox v2 to work at all.
it's working %100 on v1.34 but can't get it to work with v2.0.3
Firebug errors:

D.undelegate is not a function
[Break On This Error]
D.undelegate(selector, 'click.fb-st...ate(selector, 'click.fb-start', run);
jquery...ybox.js (line 1270)

and

$.isPlainObject is not a function
[Break On This Error]
coming = $.extend(true, {}, F.opts...ainObject(element) ? element : {}), {
jquery...ybox.js (line 468)

Here is my code:
html:
contact us

js code:
 $(document).ready(function() {

$("a.fmailto").click(function(event){
    var nr = jQuery(this).attr("id").substr(6);

    var arr = nr.split("_");
    var user_id = arr[0];
    var listing_id = arr[1];

    $.fancybox({
        type        : 'iframe',
        href        : '{/literal}{$live_site}{literal}/mailto.php?id='+user_id+'&ad_id='+listing_id,
        maxWidth    : 630,
        maxHeight   : 600,
        fitToView   : false,
        width       : '70%',
        height      : '70%',
        autoSize    : false,
        closeClick  : false,
        openEffect  : 'none',
        closeEffect : 'none'
    });
});
});

Comment: Are you using the correct jQuery library version for each fancybox?
Comment: oh man, you are right, stupid me how did i forget that. all fixed now. thanks buddy
Comment: no problem. I'll make my comment an answer that you can tick - I guess this is worth keeping around for other people with the same problem
Comment: Also remember that you can't use Fancybox 2 for commercial use without buying a license.
Answer: Make sure you use the correct version(s) of jQuery. The two versions probably need different ones.

fancybox v2 with jQuery


Find extrema of $f(x)=(1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\dots+\frac{x^n}{n!})e^{-x}$

Question: $f(x)=(1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\dots+\frac{x^n}{n!})e^{-x}$ where n ≥ 4 is a positive integer.
Discuss the extremum of $f(x)$.

My observations: Since $x$ is not very large we can't take it as $e^x$. If we had $n \to \infty$ then $f(x)$ would have been 1. How to proceed in this case where it not guaranteed that x is very large?
Comment: Hint: use the derivative.
Answer: Let $g(n,x)=\sum_{i=0}^n \frac{x^i}{i!}$.
So $f(x)=e^{-x}\cdot g(n,x)$, and $$\frac{d}{dx}f(x)=g(x,n-1)\cdot e^{-x}-g(x,n-1)\cdot e^{-x}$$ $$=e^{-x}\bigl( g(n-1,x)-g(n,x)\bigl)=-\frac{e^{-x}\cdot x^n}{n!}$$
To find the extremum - $$e^{-x}\cdot x^n\overset!=0 \Rightarrow x=0$$
Comment: There are two misprints in the first line of derivation.
Answer: Hint By the first derivative test, it's sufficient to find and classify the critical points (the solutions of $f'(x) = 0$) of $$f(x) = T_n(x) e^{-x},$$ where $$T_n(x) := 1 + x + \frac{1}{2!} x^2 + \cdots + \frac{1}{n!} x^n. $$
Now, it's straightforward to compute that $T_n' = T_{n - 1}$ (for $n > 1$).

Additional hint  It's also useful to observe that $T_n = T_{n - 1} + \frac{1}{n!} x^n$ (for $n \geq 1$).


Does an async callback function throw an event when it completes?

Question: I found a great page on making efficient asynchronous calls to web services with minimum effort here:
http://www.jaylee.org/post/2010/06/22/WP7Dev-Using-the-WebClient-with-Reactive-Extensions-for-Effective-Asynchronous-Downloads.aspx
What I'm confused about is where do I place the code that I want executed after the response is received from the server? Does the system raise an event when this happens? Simply placing the code after the call to the asyncdownload does not give this functionality.

I should've been more clear; I have this code in my project:
    private void SearchBarcode(object sender, EventArgs e)
    {
        WebClient wc = new WebClient();

        var o = Observable.FromEvent<DownloadStringCompletedEventArgs>(wc, "DownloadStringCompleted")

                          // Let's make sure that we're on the thread pool
                          .ObserveOn(Scheduler.ThreadPool)

                          // When the event fires, just select the string and make
                          // an IObservable<string> instead
                          .Select(newString => ProcessString(newString.EventArgs.Result))

                          // Now go back to the UI Thread
                          .ObserveOn(Scheduler.Dispatcher)

                          // Subscribe to the observable, and set the label text
                          .Subscribe(s => parserInput = s);

        wc.DownloadStringAsync(new Uri("http://api.search.live.net/xml.aspx?Appid=appidhere&query=barcodenumber&sources=web"));
    }

I don't see where I can place the DownloadCompleted event call. SearchBarcode is an onclick handler for an image; where does control go after SearchBarcode is executed? I want to manipulate the value of parserInput and call another xaml page passing these values. I've tried adding a void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e) but it doesn't get called, obviously. What am I missing here? :(
Comment: For reference, events are raised. Errors are thrown.
Comment: Whould you please explain more about what you want exactly? The code you put in the "DownloadCompleted" event handler will be run after the download completed. So what you want more than it? Or what is the problem about that?
Comment: Guys, I've edited my question to be more specific. Thanks for looking :D
Answer: You can put this logic at the end of the callback.
In the sample you linked that's what he's doing with the Dispatcher in DownloadCompleted.
This is a sample project I wrote demonstrating use of HttpWebRequest. At the end of ResponseCallback you will see...
Dispatcher.BeginInvoke(() => { httpWebRequestTextBlock.Text = contents; });

... to update the UI.
Feel free to ript this code and use your URL.
WebClient, HttpWebRequest and the UI Thread on Windows Phone 7
Comment: No worries, I've added a working sample project which you can plug your url/ui update logic into. Looks like you've picked up an Rx (Reactive Extensiosn) example though now.. was that part of your initial requirements?
Comment: The reason I went with Rx is because it accomplishes the same thing as HttpWebRequest (does not block UI thread). I went through your code and it seems very straightforward. while my project does not *require* Rx, I would like to not change things because they work :P The problem is, I still can't get the callback function to work. I've tried void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) and all its variants but still no luck :(
Comment: In the post your looking at, he's updating his UI with .Subscribe(s => myLabel.Text = s, e => myLabel.Text = "Error ! " + e.Message);
Comment: Yes, I understood that line. I just wanted to know if it is possible to replace the myLabel.Text = s bit with a function call.
Comment: @Freakishly - Don't think of Rx as "not blocking the UI thread", think of it as managing asynchrony.
Comment: I managed to get my app working with httpwebrequest, thanks for a great msdn post, mick :)
Answer: You can put you're code in the DownloadCompleted method, which is called with the result of your download. Be aware that any code will execute on the main thread. If you have heavy processing to do, I suggest HTTPWebRequest
Comment: Hiya Thomas, I'm not familiar with HTTPWebRequest and its usage in this context. Could I get a link, please?
Comment: It will work the same way as Webclient, but in the callback you'll have some more code to access the UI thread. doc : http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx example of use : http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8
Comment: Thanks... this is a nice page with a good clean example :) I will try adding a DownloadCompleted method and get it to work before marking your answer as the right one.
Comment: Thanks for everything Thomas, I converted my code to use httpwebrequest successfully, using Mick's example :)


c pipe: Program just stop before wait(NULL);

Question: The program can read all the data from the pipe. However, the program just stop. It cannot continue to process. I think it stop in the child process.
//I created two pipe before fork (fd[0] and fd[1]).
//child process
if(pid == 0){
    close(fd[a][1]);
    buf[6];
    int i;
    while ((i = read(fd[a][0], buf, 6)) > 0) {
        printf("%s", buf);
    }
    close(fd[a][0]);
exit(0);
}

//parent process
write(fd[a][1], "12", 2);
write(fd[a][1], "14", 2);
write(fd[a][1], "15", 2);
write(fd[b][1], "12", 2);
write(fd[b][1], "14", 2);
write(fd[b][1], "15", 2);
printf("done!\n");
close(fd[0][1]);
close(fd[1][1]);
wait(NULL);
printf("Really done!!!\n");
...                      // The program cannot run after wait(NULL);

--output--
121415done

Comment: Can you make a complete example? See http://sscce.org/
Comment: @Joachim Pileborg I have provided more detail of my program.
Answer: The two processes are caught in a deadlock, each one waiting for the other.
You want the child process to stop processing, but it waits for the parent process, because it doesn't "know" that the parent will not send any more data.
To make it clear to the child, close the writing end of the pipe:
write(fd[0][1], "12", 2);
write(fd[0][1], "14", 2);
write(fd[0][1], "15", 2);
printf("done!\n");
close(fd[0][1]);
wait(NULL);

Comment: It is already included close(fd[0][1]) in my code. However, i didn't show it out. Sorry.....
Answer: You are issuing read in a while loop, effectively blocking yourself until something goes wrong. If you need to read 6 characters, this is how you would write the child process:
char buf[7];
int left = 6;
int so_far = 0;   // instead of so_far, (6 - left) could also be used
while (left > 0)
     int num_read = read(fd[0][0], buf + so_far, left);
     left -= num_read;
     so_far += num_read;
}
buf[so_far] = '\0';
printf("%s\n", buf);

Comment: Thank you for your help. I edited my code. The problem can keep processing after wait(NULL);. However, it got want output like following (child only get the first write. And it got wrong data).

     2021

     done!

     Really done!!!
Comment: Thank you so much. I solved the problem. Your code is perfect. Actually, I made some stupid mistakes so that the program cannot run in last time.
Comment: I still have a little problem. How can I make a break line in the buf?
Comment: You mean a `'\n'`? Just where when you want: `buf[so_far] = '\n';` and then `++so_far`, but not `--left`. This is because you are generating data, so `so_far` goes ahead, but you still expect the same amount of data that is `left`
Comment: Don't forget to take an extra char in your buffer for the ending `'\0'` if you are planning on using the buffer as a string (for example for printing with `%s`
Answer: I suspect you haven't closed the "write" fd in the child process, hence the call to read will block, which in turn blocks wait in the parent process.
Also: if you've omitted something from your question, as in the response to @anatolyg's answer, you should edit the question. It's the same answer I would have given at first.
Comment: Thank you for your suggestion. I already add close fd in the child process. However, the problem still not solve.
Comment: @EricTang - you need to `close(fd[1])` or `[a][1]` (?) - the *write* file descriptor - in the child process *before* you start reading.
Comment: Oh, sorry I missed it. But the problem still here.


Require both LDAP authentication *and* ssh auth

Question: I would like to enable the following:
Linux ec2 instances in AWS that perform LDAP authentication of users who have no home directory currently on the box.  I have a working openLDAP in AWS for the task
Once LDAP authenticated:

The user's home directory will get created
The user's public ssh key is retrieved from their sshPublicKey attribute in LDAP and they can only log on if their local sshPrivateKey matches

I know how to do LDAP auth OR retrieval of public key via an ldapsearch but I want to do both.
The scenario I am trying to mitigate against is when an employee leaves the company: I can just disable their account in openLDAP and even if their public key exists on machines, they won't be able to use them because they will also fail ldap auth.
I've hunted round on StackExchanges and don't think I've found what I'm looking for. The closest I've come is
SSH key authentication using LDAP
Combination of SSH key auth, and two-factor authentication
Comment: What do you use to LDAPize your linux box? nslcd (nss-pam-ldapd), nss-pam-ldap or something else? You can easily disable user by changing `loginShell` to `/bin/false` or `/usr/sbin/nologin` in LDAP if you're reading this attribute.
Comment: Thanks @JakubJindra. I wanted to use ssh as well as ldapAuth to act as an additional factor of authentication so requiring ssh key as well as user/pass. Would disabling the user as you described apply in this scenario too?
My proof of concept with ldap auth only was nss-pam-ldap
Comment: If the user exists only in LDAP database and not in file database `/etc/passwd`, it will be the same.
He would be able to authenticate, but then his loginShell won't let him in.
Better approach is use one LDAP attribute to differentiate enabled and disabled users. And filter by this attribute. The user will simply disappear from the system.
Comment: Thanks, but I'm still not clear how I go about setting up both LDAP auth *and* the retrieval of the user's ssh public key . Sorry if I'm not asking the question in the right way. Basically is both authentication using LDAP user/pass and also ssh pub/priv key able to be applied together, if so how?
Comment: OK, I'll try to sumarize it in the answer for you.
Answer: Authentication
There's AuthorizedKeysCommand and AuthorizedKeysCommandUser in sshd_config(5) since OpenSSH 6.2. You need that to authenticate user against his/her sshPublicKey which is stored in LDAP. You don't even need ldapsearch to get the sshPublicKey - curl can do it too, since it's knows the ldap protocol.
When AuthorizedKeysCommand is defined but the command won't return any public key, openssh server continues with AuthorizedKeysFile and then with PasswordAuthentication.
On AWS EC2 the PasswordAuthentication is disabled so If You really want it, You need to enable it in config. But I wouldn't recommend PasswordAuthentication at all today.
Small recap: you want these options in /etc/ssh/sshd_config:
AuthorizedKeysFile, AuthorizedKeysCommand, AuthorizedKeysCommandUser and PasswordAuthentication.
Disabling user
As mentioned in discussion under the question: You can either use loginShell ldap attribute and modify it's value to /bin/false or /usr/sbin/nologin or use another attribute and add it into search query. This differs depending on Your setup.
What's Your setup? nslcd (nss-pam-ldapd), nss-pam-ldap, sssd or something else?
Comment: Thanks Jakub, but this still seems only to do ssh auth of the user. Not validating their user/password against ldap, followed by ssh auth on the retrieved key. Maybe what I'm considering just isn't possible
Comment: So You want to authenticate by pubkey from ldap even after that using using ldap password? I think It's possible using pam configuration. But editing pam can be dangerous.
Comment: Yes, as it says in the title
`Require both LDAP authentication *and* ssh auth`
Thanks for your suggestions
Comment: OK, then try following solution: https://security.stackexchange.com/a/130116/202480


Ubuntu SSL now broken after make installing openssl

Question: I was attempting to set up a Cisco VPN and had run into some issues, in the process of trying to correct those issues I made some changes to my certificates directory and ran several commands pertaining to setting up / modifying ssl certificates on my machine, it was a few months ago so I can't remember exactly what I ran but I know a few things I did were that I built openssl from source and installed it that way, I softlinked a few folders and moved some certificates from one folder to another. I can still access sites with https but there are just a few things that don't work with ssl anymore some examples are:
wget now returns the following regardless of the url:
--2022-08-25 22:46:09--  https://ubuntuforums.org/Resolving ubuntuforums.org (ubuntuforums.org)... 18.104.22.168, 22.214.171.124
Connecting to ubuntuforums.org (ubuntuforums.org)|22.214.171.124|:443... connected.
ERROR: cannot verify ubuntuforums.org's certificate, issued by 'CN=R3,O=Let's Encrypt,C=US':
  Unable to locally verify the issuer's authority.
To connect to ubuntuforums.org insecurely, use `--no-check-certificate'.

When I use gyazo, it now returns an error:
Traceback (most recent call last):    5: from /usr/bin/gyazo:116:in `'
    4: from /usr/lib/ruby/2.7.0/net/http.rb:932:in `start'
    3: from /usr/lib/ruby/2.7.0/net/http.rb:943:in `do_start'
    2: from /usr/lib/ruby/2.7.0/net/http.rb:1009:in `connect'
    1: from /usr/lib/ruby/2.7.0/net/protocol.rb:44:in `ssl_socket_connect'
/usr/lib/ruby/2.7.0/net/protocol.rb:44:in `connect_nonblock': SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate) (OpenSSL::SSL::SSLError)

And a project I'm working on that has separate servers for the UI and API now has stopped communicating between the two, citing an openssl error "UntrustedRoot"
I tried:

Reinstalling ca-certificates sudo apt-get install --reinstall ca-certificates

I tried sudo dpkg --purge --force-depends ca-certificates followed by sudo apt-get -f install and then sudo update-ca-certificates
I tried changing the default version of my openssl
I'd like to figure out a way to revert this all back to default without having to reinstall my operating system as I have a lot of configuration on here that I'd have to enter again.
Answer: This is the reason why packet managers exist and you shouldn't disturb their operation by installing software some other way.
Since there is no way for us to know what you did, we cannot tell you how to undo it.
Your best bet to revert your changes is your shell's history. Use it to look up the commands you issued when installing the self-built OpenSSL, and then find out how to do the opposite.
The best option to get a solid system back is reinstall, and then refraining from installing software manually.
Answer: The default (repository) trusted certs are in /etc/ssl/certs/.
If you compile openssl from source, then it looks for them in /usr/local/ssl/certs/, but the directory is empty.
The solution:
sudo rmdir /usr/local/ssl/certs
sudo ln -s /etc/ssl/certs /usr/local/ssl/certs

Poof! The problem goes away!
Comment: I am glad that this worked for you but it seems to be a solution to the specific problem of trusted certs not being found. When you hit problems with the libraries for the new version not being compatible with the applications linked to `libssl.so` then you'll have to dig deeper. Next step would be to recompile applications that link to the library, taking them out of package manager support. Now you are manually keeping up with updates to the library and one or more applications. Or is apache's mod_ssl library compatible with your new libssl.so? Now you're recompiling new libraries. :(


How does a piece of wood that blocks the trem system contribute or hamper tuning stability and tone?

Question: It is fairly well known that Eric Clapton used a piece of of wood to block his trem system. However, when I tried researching the why I only found what seemed to be a bunch of unsubstantiated claims (not all of them were unsubstantiated) on what it did or improved, that is, no one really offered a solid piece of evidence back their claim up. Generally these claims were, a) it improved the tuning stability and b) it changed (often positively) the tone. Accordingly, how does this piece wood improve or hamper the tuning stability? Furthermore, what changes does it make to the tone of the guitar if any? Is there other things this wood block changes?
Essentially, I am looking for answers that can give clear explanation of the pro and cons of this wood block and a explanation of the hows and whys it positively or negatively effects the guitar's tuning, tone and so forth. Physics/engineering concepts encouraged, but not required.
Comment: To take this further - does the type of wood - or any other material - make any more difference?
Comment: @Tim I don't think the type of wood used for the block has much effect, as long as it's solid and reasonably dense.  (I have a few scraps of maple from guitar building experiments which I've used for this, but I **guess** any hardwood will do.  I wouldn't use really soft pine, for example.)
Answer: Remember the rubber band guitar you made out of a shoebox when you were a kid? When you plucked the rubber band string, the walls of the shoebox got pulled inward from the rising tension of the rubber band.
The same thing happens when you pluck a guitar string. As it is pulled and vibrating, the tension increases. As that tension increases, it causes the tremolo to dip ever so slightly.
Want to test this out? Tune your low E string perfectly. Now, bend your high E string up a step or more without plucking it, and while holding that bend, pluck the low E and see what your tuner reads.
This does not happen on a guitar with a solid tail piece.
By jamming that piece of wood into that space, the tremolo cannot dip forward and will stay put, along with the strings. A similar effect can be achieved by installing all five springs and adjusting them to maximum tension.
Now, consider the fact that when the tremolo is enabled, the string energy at the bridge is transferred to the guitar body through the pivot points of the screws, but also through the springs, to a degree, the other end of this fulcrum. Springs are not good at transferring resonance. Jamming that piece of wood in there brings all the string energy straight to the guitar body.
Does any of this really matter? From experience I can tell you yes. When you play unplugged in your bedroom. The difference is definitely noticeable. However, plug in your guitar and turn it up to an enjoyable level, you'd have to be Clapton to really care. Turn up the distortion and you really shouldn't care even if you are him.
This sproingy boingy bridge problem is much more noticeable on floating bridges like a Floyd Rose, but even that is fixable by using lighter strings and a lighter touch. Haven't heard people complaining about Jeff Beck's tone and he floats his Strat's bridge.
Comment: I definitely agree about the tuning comment.  A "floating" bridge moves slightly when tension on a string changes, and this has a small effect on the remaining strings.  So it can be a little bit faster to tune on a fixed (or blocked) bridge.  Also if a string breaks, a fixed bridge will be less likely to pull all the remaining strings sharp.
Answer: I am not a Clapton listener actually so I do not know about his approach of wooden block. It may be affecting tone by increasing the vibration on body as the strings vibrate through the bridge. By doing that, it increases the sustain and sound I think.
As you know bridge has a direct impact on a guitars tuning. If your bridge is not stable, then you will not get a good tuning too. The wooden block stabilizes the bridge by immobilizing it. But of course, you unfortunately can not use the trem bar.


How many matches will there be at Euro 2016

Question: I'm writing some software for recording stats about football tournaments and I need to know how many matches will there be at Euro 2016.
Also what is the largest number of matches that are likely to be played simultaneously.
Comment: I vote to close because it is possible to find the answer with a very simple search on the web
Comment: Based on previous attempts to close due to the question being ["easy to look up"](https://sports.stackexchange.com/questions/12722/ball-goes-through-the-strike-zone-but-the-catcher-doesnt-catch-the-ball#comment19370_12722) or ["too basic"](https://sports.stackexchange.com/questions/12860/if-the-pitcher-throws-to-1st-base-to-try-to-get-the-base-runner-out-is-the-runn?rq=1#comment19667_12860), it was determined that said reasons were not valid reasons to close.
Answer:
How many matches will there be at Euro 2016?

According to the UEFA EURO 2016 website, 51.

Group Stage - MD 1: 12
Group Stage - MD 2: 12
Group Stage - MD 3: 12
Round of 16: 8
Quarterfinals: 4
Semi-finals: 2
Finals: 1

What is the largest number of matches that are likely to be played simultaneously?

The largest number of matches that start at the same time is 2, found in Group Stage - MD 3. Within reason, the largest number of matches that are likely to be played simultaneously is 2.
In the event the earlier scheduled games run longer than three hours (I'm not sure how un/likely that is), then it is possible (if reasonable) that the largest number of matches that are likely to be played simultaneously is 4 (but it would be during the very end of the earlier scheduled games and during the very beginning of the later scheduled games, again, if reasonable).
Comment: @Ale You're correct, I didn't take note of the different days those matches are played. This has been corrected.
Comment: This is wrong because there it will never happen that 4 matches are played simultaneously: the largest number of matches played simultaneously is **2** (the last matches of each of 6 groups)
Answer: A simple search would have shown this Euro 2016 calendar.

36 matches for rounds
8 round of 16
4 quarterfinals
2 semifinals
1 final

total 51 matches
The largest number of matches played simultaneously is 2 (the last matches of each of 6 groups)


Apagando item de uma lista sem saber seu índice - Python

Question: Digamos que eu tenha a seguinte lista:
lista_de_dados = [['nome', 'prioridade', 'hora', 'consultório', 'Número na fila'],
                  ['Gabriel', 'Comum', '16:30', 'Dermatologia', 1]
                  ['Gabrielle', 'Preferencial', '16:31', 'Dermatologia', 2]]

E eu queira criar uma função para apagar uma dessas listas dentro da lista_de_dados sem apagar as outras. Por exemplo, supondo que eu queira apagar a lista que contem as informações de Gabrielle. Eu poderia fazer:
lista_de_dados = [['nome', 'prioridade', 'hora', 'consultório', 'Número na fila'],
                  ['Gabriel', 'Comum', '16:30', 'Dermatologia', 1],
                  ['Gabrielle', 'Preferencial', '16:31', 'Dermatologia', 2]]
lista_de_dados.__delitem__(2)
print(lista_de_dados)

Irá mostrar na tela:
[['nome', 'prioridade', 'hora', 'consultório', 'Número na fila'], ['Gabriel', 'Comum', '16:30', 'Dermatologia', 1]]

Contudo como eu posso apagar o mesmo item (a lista com as informações de Gabrielle) sem saber a posição dela na lista_de_dados? Por exemplo, eu sei apenas o que tem dentro da lista que contem as informações de Gabrielle mas não sei a posição dela em relação a lista_de_dados.
Answer: Você pode identificar o item que você está interessado pelo index e usar o try statement para lidar com o erro que surge quando ele não encontrar o item na sublista. Veja:
lista_de_dados = [['nome', 'prioridade', 'hora', 'consultório', 'Número na fila'],
                  ['Gabriel', 'Comum', '16:30', 'Dermatologia', 1],
                  ['Gabrielle', 'Preferencial', '16:31', 'Dermatologia', 2]]

ans = input('Por favor, me dê o nome cujo os dados você pretende apagar:')
for i in range(len(lista_de_dados)):
    try:
        lista_de_dados[i].index(ans)
        lista_de_dados.__delitem__(i)
        print('A sublista {} foi deletada'.format(i))

    except:
        print('A sublista {} permanece em lista_de_dados'.format(i))

print(lista_de_dados)

Answer: Você pode utilizar for loop e ir verificando se o primeiro item da lista de dados (nome) é igual ao nome que o usuário digitou. Se for igual, você pode apagar essa lista de dados utilizando o método de listas remove(value). Exemplo:
lista_de_dados = [['nome', 'prioridade', 'hora', 'consultório', 'Número na fila'],
                  ['Gabriel', 'Comum', '16:30', 'Dermatologia', 1],
                  ['Gabrielle', 'Preferencial', '16:31', 'Dermatologia', 2]]

nome = input('Nome do perfil que será apagado:')

for perfil in lista_de_dados:

    if perfil[0] == nome:
        lista_de_dados.remove(perfil)
        break

print(lista_de_dados)


Win32 c++ resize createwindow at runtime

Question: I write in win32 api c++, and use mingw.
I would like to resize a button when the main window is resized at runtime.
Here is my code:
<code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
 // BLA BLA BLA
    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        szClassName,
        "Main Window",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        800,        // width
        1000,       // height
        HWND_DESKTOP,
        NULL,
        hInstance,
        NULL
    );
  // BLA BLA BLA
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(Message)
    {
        case WM_CREATE:
        {
         RECT  rect;
        GetClientRect(hwnd, &rect);
        int width = rect.right - rect.left;
        width = width-20;

        HWND button = CreateWindowEx(BS_PUSHBUTTON, "BUTTON", "grafikon",
                           WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                           10, 10, width, 25,
                           hwnd,
                           (HMENU)ID_BUTTON,
                           GetModuleHandle(NULL),
                           0);
      // BLA BLA BLA
}
</code>
So I would like to resize the BUTTON at runtime. How can I do this?
thanks
Comment: What part are you having trouble with, resizing it or doing it when the main window is?
Answer: I think you search WM_SIZE MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632646.aspx


Não exibir valor null (01/01/0001) de um Datetime em uma DataGridView

Question: Minha DataGridView possui alguns campos DateTime com valor null (01/01/0001). Como faço para não exibir esses valores, deixando o campo em branco?
Atualmente:

Como eu gostaria que ficasse:

Estou utilizando WindowsForm, C# e .Net Framework 3.5.
Lembrando que utilizo databinding na minha DataGridView.
Comment: Voce utiliza colunas predefinidas do datagriview ou deixa que ele gera as colunas automaticamente?... caso for predefinido... e so editar a coluna... tem uma SUB-propriedade nela chamada NullValue... tente colocar null ou 01/01/0001
Comment: Você já tentou colocar essa coluna no seu BD como não obrigatória e usar o tipo `DateTime?` ao invés de `DateTime`? A diferença é que o primeiro aceita valores nulos diferentemente do segundo.
Answer: Resposta dada antes de o OP indicar que está usando WindowsForms.
Solução para WPF.
Utilize um ValueConverter para converter DateTime em string.
Ao fazer a conversão se o valor do DateTime é DateTime.MinValue retorna-se string.Empty; caso contrário retorna-se dateTime.ToString()
[ValueConversion(typeof(DateTime), typeof(string))]
public class DateTimeToString : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
        {
            var dateTime = (DateTime)value;
            if (dateTime == DateTime.MinValue)
            {
                return string.Empty;
            }
            return dateTime.ToString();
        }
        throw new ArgumentException("value");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var dateString = (string) value;
            if (string.IsNullOrEmpty(dateString))
            {
                return DateTime.MinValue;
            }
            return DateTime.Parse(dateString);
        }
        throw new ArgumentException("value");
    }
}

Para usar o ValueConverter deve primeiro declará-lo na secção <Windos.Resources> da sua Window.
<Window.Resources>
    <local:DateTimeToString x:Key="DateTimeToString" />
</Window.Resources>

Depois atribua-o ao atributo Converter do Binding da DataGridTextColumn
<DataGrid.Columns>
    <DataGridTextColumn Header="Data" Binding="{Binding data, Converter={StaticResource DateTimeToString}" />
</DataGrid.Columns>

Answer: EDIT:
Foi mal, não tinha visto que estava usando o databinding, nesse caso acho que a minha solução não se aplica, porém é válida para outros casos.
Você pode fazer algo do tipo:
if (data != DateTime.MinValue)
   tabela[indexColuna, indexLinha].Value = data;

ou
if (data.Year  != 0001)
   tabela[indexColuna, indexLinha].Value = data;

isso deve funcionar
Comment: Você pode verificar tbm se o `data.Year == 0001` e se for não definir o valor da célula.


Part of the notes sound off (Scott Joplin - The Entertainer sheet music for Piano)

Question: I am practicing Scott Joplin - The Entertainer, based on this score from 8notes.com.
It all sounds fine, except for this segment:

The red marked segment sounds off when I play it. It sounds nothing like the sound file on 8notes.com. Is there maybe a misprint or something else wrong with it? Or does it sound and look fine to you?
Comment: If you think that the 8notes.com recording sounds OK, but your playing doesn't sound like it, then logically, you must be doing something wrong. Consider uploading an excerpt of your playing to [YouTube](https://youtube.com) or [clyp](https://clyp.it).
Comment: In addition to the other answers, the "recording" on that website plays the right hand at a *piano* dynamic level while the left hand continues at *forte*. This softens the dissonance (quite literally) on beat 4 and makes it less obvious, something one wouldn't do when performing this piece.
Answer: This is not the original score but a simplified version of it.  The original uses a bass/chord pattern of E-c-C-c7 (and fuller chords) so you might want to change the third quarter note E to C and add a b flat to the chord on the fourth quarter note (this fits the movement into the next chord as written).
Doing this will make for a less "stuck" appearance of the second half of that measure and will have better leading into the next measure.
You might want to ditch that simplified version.  The first prints of Joplin should be out of copyright so you should be able to get copies of the original comparatively easily, and it's not that much more difficult to play.
And messing up fine points of the harmonic and melodic developments and bass lines like this really distracts from the original flow of the piece.
Comment: I disagree with your assessment that the original is not that much difficult: it has more chords in the right hand, and the left hand jumps around a lot. I'd like to point out, though, that the original's tempo indication is "Not fast", yet the 8notes.com version says "Presto", which is totally not "Not fast"!
Comment: Thanks for the input. Still, no matter how I twist or turn it, the F-sharp just sounds weird in it.
Answer: You can get an accurate score here: https://www.mutopiaproject.org/cgibin/piece-info.cgi?id=263 , and you can hear a public domain recorded performance here: https://en.wikipedia.org/wiki/The_Entertainer_(rag) (box on the right). Here's the part you're talking about:

The score you're working from is simplified, and in this particular bar it's inaccurate. The left hand doesn't have a G on the final 8th note of the bar, it has the chord Bb C E. Joplin presumably didn't include a G in this chord for exactly the reason that it bugged you -- a prominent clash with the melody.
Answer: We can't hear your playing, but if you are at the stage where you are playing this type of simplified arrangement, I would guess the problem is that you haven't yet learned that the dynamic level of every individual note in each chord is important.
The G F# G in the right hand are marked "p" (soft) but you need to play the G and C in the left hand even quieter than the F# in the right hand.
As another answer said, its worth looking at the original version here. In particular, including the original B flat in that chord will make a lot of difference to the overall effect. Try changing the C to a Bb if you don't want to increase the number of notes you play.
Answer: First I wrote the following as a comment, but then I realized that it is in fact an answer and therefore should not go in the comments section but instead be posted as an answer:
Well, it actually sounds fine the way it is written in that score, BUT when you practice it in a slow practice tempo the F♯ will sound weird because you have a G in the left hand at the same time. There are many pieces of music where there will be sections which will often sound weird when you practice it in a slow tempo. Once you get the tempo faster it turns out OK.
Comment: This interpretation would be more plausible if the score the OP was working from didn't simply have a wrong chord at that spot. And Joplin always insisted that his work wasn't supposed to be played fast.
Comment: @BenCrowell I actually I did NOT say you should play it fast. I talked about practicing in a slow practice tempo and then you can later play it faster than that and it will sound OK. This particular score will sound OK, but of course the closer you get to the original the better off you are.
Answer: You can get away with most 'off sounding notes' in ragtime just because of the speed of resolution. Most rags uses a lot of chromatic notes that clashes with the melody or harmony unless you play it fast enough. There are a lot of walking bass lines with chromatic movements and if played slow they can clash with the harmony or vice versa, but if you play it at a normal speed and they resolve fast enough back to a diatonic tone, it gives more like a 'color' to the song instead of an off-sounding feeling.
Other than that, I know that 8notes has a lot of scores, sadly they are more often than not not too accurate. They are probably fine for simple songs like hymns, but not that great for more advanced scores, because they often have mistakes in them.
Especially for ragtime, I would always search for an original score. Because many of them are already in public domain (copyright free, because they were written before 1929), you'll find a lot of copies of the original scores online. Here is for example just the first page of the song you're looking for. If this version is too hard to play for you, you can just simplify them yourself ;)
Comment: Just read your comment. Thanks for elaborating posting the notes, it helps!
Answer: Thanks for all the helpful answers. Indeed, it must sound off due to my slow playing speed and the simplified version of notes.
I found this person on youtube who plays the exact notes I posted (

). Indeed, it sounds ok at the pace he's playing, and he definitely includes the F-sharp.


list comprehension to create list and for no-data value feed default value

Question: Would anybody tell me how to create a list using list comprehension, having default values for no-data values like the below problem.
I have a triangular data set, which I want to feed to 2-D list using list comprehension.
I want to feed 0's instead of no-data values.
input form...
   3
  7 4
 2 4 6
8 5 9 3

output form.
3 0 0 0
7 4 0 0
2 4 6 0
8 5 9 3

Can anybody help me. thanks in advance.
Comment: You will *have* to loop at least twice then; once to get the length. hcwhsa's answer below does loop twice, hidden in the `*` parameter expansions.
Comment: Did you try anything yourself yet? Why does it *have* to be a list comprehension? Do you know the maximum length of a row up front?
Comment: No.. I dont know the max lenght of list... I have tried bt It seems that there is no way using only list comprehension.. or if there is a way it will be very complex... :)
Answer: You can use itertools.izip_longest:
>>> from itertools import izip_longest
>>> strs = """   3
  7 4
 2 4 6
8 5 9 3"""
>>> lis = [s.split() for s in strs.splitlines()]
>>> zip(*(izip_longest(*lis, fillvalue='0')))
[('3', '0', '0', '0'),
 ('7', '4', '0', '0'),
 ('2', '4', '6', '0'),
 ('8', '5', '9', '3')]

Comment: http://stackoverflow.com/questions/19419154/getting-max-value-from-each-column-of-the-csv-file
Comment: @tailor_raj Please don't post unrelated comments.
Comment: NO.. it is a good question, and I have solved that also.. but I was trying to get efficient way of doing that.. because I am beginner...
Comment: @tailor_raj I am not saying that it is bad question. But that question is not related to this question anyhow, so you should not post comments like that. Read: [What should I do if no one answers my question?](http://stackoverflow.com/help/no-one-answers)


Como colocar paramentros para renomear aquivos no powershell?

Question: Estou tentando modificar o nome de um item no powershell, o problema é o seguinte:
existe varios arquivos com esses nomes
V0185M03.D15
C0185M03.D15
B0185M03.D15
inicialmente eu quero zipar todos esses acquivos com o codigo "0185" para "01851503.zip"
onde o "M" é o mês e ".D15" é o dia
o nome do aquivos tem que ficar "CodigoDiaMes"
eu ja fiz um meio codigo que ficou assim
Compress-Archive -Path "c:\codigos*0185* -destination "c:\codigos\0185.zip"
Alguem pode me ajudar?
Comment: O código tem sempre 4 digitos ou isso pode variar?
Comment: Pode ser também um arquivo bat ou tem que ser powershell?
Comment: Os dados estão sempre na posição exata como aparecem ai por exemplo código posição 2-5 (contando da esquerda) mês 7-8 dia 11-12 ?
Comment: Depois de zippados os arquivos originais devem ser deletados ou não?
Comment: Desculpa a demora Ricardo, mas vou responder agora
Sim, o código tem sempre 4 dígitos.
Eu prefiro powershell pq estou estudando a linguagem.
Sim, sempre são gerados nessa exata ordem.
Devem ser movidos para uma pasta com nome "Backup" mas só os arquivos .D (que eu ja consegui fazer).
Answer: Olá amigo parece que ficou faltando uma aspa após a fonte:
<code>Compress-Archive -Path "c:\codigos*0185*" -destination "c:\codigos\0185.zip"
</code>
Aqui está o código de um arquivo batch que chama o powershell para zipar os arquivos:
<code>@echo off
:: Informe o caminho para os codigos aqui:
set Fonte=Codigos
pushd "%Fonte%"
for /f "delims=" %%a in ('dir /b /a-d') do call :Zippar "%%~a"
powershell -NoProfile -NoLogo -ExecutionPolicy Unrestricted -File "%~dp0power.ps1"
del /q "%~dp0power.ps1
exit

:Zippar
set Codigo=%~1
set C4=%Codigo:~1,4%
set Mes=%Codigo:~6,2%
set Dia=%Codigo:~10,2%
echo compress-archive '%Codigo%' '%C4%%Dia%%Mes%.zip'>>"%~dp0power.ps1"
echo remove-item '%Codigo%'>>"%~dp0power.ps1"
goto :EOF
</code>


Virtual host "Forbidden You don't have permission to access / on this server" on debian

Question: Before I created a virtual host I could see "http://localhost", but when I created a virtual host I could not see "http://localhost" and my virtual host "http://test"
Here is my  virtualhost config file:
<VirtualHost test:80>

        ServerAdmin email@example.com
        ServerName  test
        ServerAlias test

  DocumentRoot "/home/javad/Public/test/public"
<Directory  "/home/javad/Public/test/public/" >
 Options Indexes FollowSymLinks
 MultiViews ExecCGI
 DirectoryIndex index.php
 AllowOverride all
 Order    allow,deny
 allow from all
</Directory>

  </VirtualHost>

so I ran a2ensite test
and added
127.0.0.1 test to /etc/hosts file and restart apapche2 fine
But after that I cannot access to http://test or even  http://localhost
i get
Forbidden You don't have permission to access / on this server.

When I delete my virtual host setting  I can access http://localhost
Answer: Once you activate virtualhost you need to reconfigure localhost as virtualhost.
You can simply copy-paste httpd.conf parameters.
Answer: probably no index file in the directory and directory listing is disabled? - cann you access files directly?
otherwise check read permissions for the webserver user.
it looks weird to me to have a directory statment inside virtualhost container, its usually not the case altough if you can start your webserver it seems to work.
you need to have a namevirtualhost directive in place in order for your config to work correctly.
<VirtualHost test:80> ... try using *:80 or ip:80 instead. the resolution may cause problems here and make the virtualhost ineffective.
Comment: i have index file ,and why i could access to http://localhost when delete setting of test irtual host
Comment: Without the vhost entry you can get to your server because you're accessing it via the default non-vhost setup.  Joe is probably right about the permissions issue, can you confirm that you checked that?
Comment: i ran "chmod -R 755 test" command to /home/javad/Public/test/public folder and /etc/www floders but still can not access to http://test or localhost
Comment: its not possible to reliably determine the problem here. please your configuration files (server config including all vhosts and other user specific files if any). please paste them to some external service to keep it tidy. also supply the output or your access and error logfile(s).
Answer: This is too long for a comment, so it's an answer I'll revise. Run this script and provide us with the output:
#!/bin/bash -x -e

cd /
ls -lhd .
cd home
ls -lhd .
cd javad
ls -lhd .
cd Public
ls -lhd .
cd test
ls -lhd .
cd public
ls -lhd .
ls -lh

Answer: When you create a vhost, you have to specify a vhost for your server as well, localhost in this case. See the highlighted section titled "Main host goes away"

Virtual host “Forbidden You don't have permission to access / on this server” on debian


If Statement With a Container Widget in Flutter

Question: I created a condition so that if the value is different from null I want the container with that information to appear, if the value is null I don't want to show anything but the problem is that a null text is appearing instead. What can be happening?
@override
  Widget build(BuildContext context) {
return Scaffold(
          backgroundColor: Colors.white,
          body: Column(
            children: [
            Container(
                child: ("$_info" != null)
                    ? Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 20,
                            vertical: 35),
                        child: Text(
                          "$_info",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontFamily: 'Montserrat',
                              fontSize: 14,
                              fontWeight: FontWeight.w500),
                        ),
                      )
                    : Container(),
                 ),
               ],
              ),
             };

Answer: You shouldn't create a new String from _info and test if it's different from null as in
"$_info" != null

This is always going to be true, because all Strings are different from null. So you're going to see the text "null" appearing on the screen because you have Text("$_info") later on.
Instead, you should just test if _info itself is different from null. So:
_info != null


Does restarting Samba corrupt files being transferred?

Question: Will restarting samba corrupt files that are being transfered at the time of restart ?
Does Samba first do a clean close on all files before restarting or simply restarts abruptly ?
Alternatively, is there a clean way to restart SAMBA such that no files are corrupted in the process ?
Answer: Restarting a service is sending a terminate signal to the process, which in turn should gracefully close and shutdown and then start again.
So, there should be no risk of corruption to files.
Comment: This is, unfortunately, not true. Consider an application that's in the middle of modifying a file. Even if samba closes gracefully, the application that's modifying the file may stop in the middle of the operation when it can't write to samba anymore.
Comment: The problem is that the application may not still be there when the Samba server restarts. For example, you may be in the middle of overwriting one instance of a file with a new instance of a file and wind up timing out with the file containing a bit of each.
Comment: Samba active connections are reconnected on restart. There might be some edge cases that might not comply.


CARP: two machines think they're the master, but only on one interface

Question: I have two machines, each configured identically as a firewall/load balancer for a busy website. I have set them up with CARP and pfsync on both the internal and external interfaces. The internal interface is behaving as expected (primary listed as MASTER and secondary listed as BACKUP)
On both machines, the network interfaces are as follows:

em0 - External interface
bge0 - Internal interface
bge1 - Crossover connection between both machines
carp0 - Shared external interface for CARP
carp1 - Shared internal interface for CARP

I've rewritten the IP addresses and MAC addresses below. The networks are as follows:

10.0.1.0/24 - External network
10.0.2.0/24 - Internal network
10.0.3.0/24 - Crossover network

Here's the output from ifconfig on the primary:
em0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=19b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4>
    ether [SNIP]
    inet 10.0.1.10 netmask 0xffffff00 broadcast 10.0.1.255
    media: Ethernet 100baseTX <full-duplex>
    status: active
bge0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
    ether [SNIP]
    inet 10.0.2.10 netmask 0xffffff00 broadcast 10.0.2.255
    media: Ethernet 1000baseT <full-duplex>
    status: active
bge1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
    ether [SNIP]
    inet 10.0.3.10 netmask 0xffffff00 broadcast 10.0.3.255
    media: Ethernet 1000baseT <full-duplex>
    status: active
lo0: flags=80c9<UP,LOOPBACK,RUNNING,NOARP,MULTICAST> metric 0 mtu 16384
    options=3<RXCSUM,TXCSUM>
    inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4
    inet6 ::1 prefixlen 128
    inet 127.0.0.1 netmask 0xff000000
pflog0: flags=141<UP,RUNNING,PROMISC> metric 0 mtu 33152
pfsync0: flags=0<> metric 0 mtu 1460
    pfsync: syncdev: bge1 syncpeer: 10.0.3.11 maxupd: 128
carp0: flags=49<UP,LOOPBACK,RUNNING> metric 0 mtu 1500
    inet 10.0.1.5 netmask 0xffffff00
    carp: MASTER vhid 1 advbase 1 advskew 0
carp1: flags=49<UP,LOOPBACK,RUNNING> metric 0 mtu 1500
    inet 10.0.2.5 netmask 0xffffff00
    carp: MASTER vhid 2 advbase 1 advskew 0

And here's the /etc/rc.conf excerpt from the primary:
defaultrouter="10.0.1.1"
network_interfaces="em0 bge0 bge1 lo0 pfsync0"
cloned_interfaces="carp0 carp1"
ifconfig_em0="inet 10.0.1.10 netmask 255.255.255.0 media 100BaseTX mediaopt full-duplex"
ifconfig_bge0="inet 10.0.2.10 netmask 255.255.255.0 media 1000BaseTX mediaopt full-duplex"
ifconfig_bge1="inet 10.0.3.10 netmask 255.255.255.0 media 1000BaseTX mediaopt full-duplex"
ifconfig_carp0="vhid 1 pass [SNIP] 10.0.1.5/24"
ifconfig_carp1="vhid 2 pass [SNIP] 10.0.2.5/24"
pfsync_enable="YES"
pfsync_syncdev="bge1"
pfsync_syncpeer="10.0.3.11"

And here's the output on the secondary:
em0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=19b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4>
    ether [SNIP]
    inet 10.0.1.11 netmask 0xffffff00 broadcast 10.0.1.255
    media: Ethernet 100baseTX <full-duplex>
    status: active
bge0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
    ether [SNIP]
    inet 10.0.2.11 netmask 0xffffff00 broadcast 10.0.2.255
    media: Ethernet 1000baseT <full-duplex>
    status: active
bge1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
    options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM>
    ether [SNIP]
    inet 10.0.3.11 netmask 0xffffff00 broadcast 10.0.3.255
    media: Ethernet 1000baseT <full-duplex>
    status: active
lo0: flags=80c9<UP,LOOPBACK,RUNNING,NOARP,MULTICAST> metric 0 mtu 16384
    options=3<RXCSUM,TXCSUM>
    inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4
    inet6 ::1 prefixlen 128
    inet 127.0.0.1 netmask 0xff000000
pflog0: flags=141<UP,RUNNING,PROMISC> metric 0 mtu 33152
pfsync0: flags=0<> metric 0 mtu 1460
    pfsync: syncdev: bge1 syncpeer: 10.0.3.10 maxupd: 128
carp0: flags=49<UP,LOOPBACK,RUNNING> metric 0 mtu 1500
    inet 10.0.1.5 netmask 0xffffff00
    carp: MASTER vhid 1 advbase 1 advskew 20
carp1: flags=49<UP,LOOPBACK,RUNNING> metric 0 mtu 1500
    inet 10.0.2.5 netmask 0xffffff00
    carp: BACKUP vhid 2 advbase 1 advskew 20

And here's the /etc/rc.conf excerpt from the secondary:
defaultrouter="10.0.1.1"
network_interfaces="em0 bge0 bge1 lo0 pfsync0"
cloned_interfaces="carp0 carp1"
ifconfig_em0="inet 10.0.1.11 netmask 255.255.255.0 media 100BaseTX mediaopt full-duplex"
ifconfig_bge0="inet 10.0.2.11 netmask 255.255.255.0 media 1000BaseTX mediaopt full-duplex"
ifconfig_bge1="inet 10.0.3.11 netmask 255.255.255.0 media 1000BaseTX mediaopt full-duplex"
ifconfig_carp0="vhid 1 pass [SNIP] advskew 20 10.0.1.5/24"
ifconfig_carp1="vhid 2 pass [SNIP] advskew 20 10.0.2.5/24"
pfsync_enable="YES"
pfsync_syncdev="bge1"
pfsync_syncpeer="10.0.3.10"

What I don't understand is, the carp status on carp0 is MASTER on both machines when the status on carp1 is as it should be (MASTER on the primary and BACKUP on the secondary). What am I missing? Where should I be looking for clues?
Answer: Are the machines able to ping each other over the external interface? Do you by any chance have another vhid 1 on your external network?
Comment: That would be correct. I think I had this issue before where the datacenter used VHID 1 on their VRRP setup of my WAN side, and I attempted to use VHID 1 as well.

Here's some better explanation and possibly a solution? - http://forum.pfsense.org/index.php?topic=752.0
Comment: The two machines are plugged into our external switch along with two other non-CARPed boxes. They can ping each other on the external interface, no problem with that at all.

The router (10.0.1.1 above) is provided by the datacentre and is outside of my control. I *think* it may be a pair of Cisco routers set up with VRRP. If that pair of VRRP routers had a VRID of 1, would it conflict with a CARP vhid of 1? Are the two protocols that similar?
Comment: Had the same problem with Arista switches that used VRRP. [CARP uses the same protocol number (112) as VRRP,](https://en.wikipedia.org/wiki/Common_Address_Redundancy_Protocol#Incompatibility_with_IANA_standards) probably on purpose.
Comment: That's right, if the two machines can't talk to each other for some reason then they both assume the master role.
Answer: Looks like the advskew on the primary is saying that (0|primary) should be MASTER versus (20|secondary) should be BACKUP. Implicating(?) a lack of communications between the two carp0 interfaces.
You may already have checked these, but some general diagnostics procedures on OpenBSD.

Configuration Files
Verify Carp Protocol is allowed in and out of the two machines
Verify pfsync protocol is allowed in and out of the two machines

As it seems you are using FreeBSD (i.e.not using OpenBSD) I hope my answer is clear enough for you to adjust and make useful.
--
1. Configuration Files
Do you have net.inet.carp settings similar to the below ?
File: /etc/sysctl.conf

net.inet.carp.allow=1
net.inet.carp.preempt=1
net.inet.carp.log=1

One CARP interface working, while the other doesn't seems to indicate that the correct system configurations have been made. It doesn't hurt to confirm, sometimes we make the changes with a command-line setting and forget to set in the system configurations.

net.inet.carp.allow accept incoming CARP packets or not. Default is yes, and not in /etc/sysctl.conf
net.inet.carp.preempt Allow hosts within group to preempt the master. Sets failover of all CARP interfaces on the failure of one interface. Disabled by default.
net.inet.carp.log Log bad CARP packets.
net.inet.carp.arpbalance Load balance traffic across group hosts. Default is disabled.

2. Carp Protocol
Carp packets need to be recieved for the firewall to adjudicate whether it needs to become MASTER/BACKUP
Revisit your firewall configuration to make sure that proto carp is passed in and out on both carp physical interfaces.
For example:

pass quick on { em0 bge0 } proto carp keep state (no-sync)

You can confirm through adding block log all at the beginning of your firewall ruleset, and then using tcpdump on the pflog0 interface to confirm whether the carp packets are being allowed through  or not.
2. pfsync protocol
An additional check, that pfsync packets are allowed through the firewalls, to ensure that firewall states are being shared between the two hosts.

pass quick on bge1 proto pfsync keep state (no-sync)


ESLint: fromEvent is defined but never used (no-unused-vars)

Question: import { Observable } from 'rxjs/Observable';
import { fromEvent } from 'rxjs/add/observable/fromEvent';
import { merge } from 'rxjs/add/observable/merge';

const touchstart = (input) => Observable.merge(
    Observable.fromEvent(input, 'pointerdown')
      .filter(event => event.pointerType === 'touch'),
    Observable.fromEvent(input, 'touchstart'));

I'm getting the following linting error:
    ESLint: fromEvent is defined but never used (no-unused-vars)
and the same on merge. The problem is that I need to import fromEvent and merge otherwise it doesn't include them.
Answer: Try just importing these modules, without assigning them to anything:
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/observable/merge';


Is partimento a good way to learn how to write a Baroque trio sonata in the style of Corelli?

Question: Who I am:
I am 16 years old and I play violin. I am a music student and I consider myself to have a very good ear and understanding of music theory. My piano-playing is however not very good. I really want to learn how to copy this style of composition because I believe it will provide a good framework for my understanding of counterpoint and harmony for classical music in general.
What I have done:
I have researched about partimento on YouTube and on Monuments of Partimento. I have played around with the 'rule of the octave' on my keyboard as well.
My question:
I have two main questions. Will learning partimento be an efficient and pragmatic effort to achieving my goal? If so, where should I start as a somewhat informed beginner? I currently feel a bit swamped with the vast number of links and websites talking about partimento and the rule of the octave on the internet.
Monuments of Partimento (https://web.archive.org/web/20160318110700/http://faculty-web.at.northwestern.edu/music/gjerdingen/partimenti/aboutParti/beginnersGuide.htm)
Corelli trio sonata score (

)
Answer: The question seems to be about two different things.  The title question says, "Is partimento a good way to learn how to write a trio sonata in the style of Corelli?"  Sure, if you want to learn how to imitate the specific style of that particular period, using historical pedagogical methods is probably the best approach, though you'd likely need a good teacher.  Partimento is only part of the types of training Italian musicians would have received at the time of Corelli (you'd also need to learn other patterns of imitation, melodic construction, traditional singing instruction which would have been very much a part of pedagogy, etc., etc.), but it's definitely closer than most modern pedagogical methods.  That's how young musicians learned stuff like that back then.  For an example of a modern young person raised in that method, search for Alma Deutscher.  Note that this method is traditionally very "hands on" and again requires a knowledgeable teacher who can improvise effectively in styles from around 1700.  There are very few people like this in the world.
But the rest of the question goes off of the premise that such study "will provide a good framework for my understanding of counterpoint and harmony for classical music in general."  I suppose that's likely true of classical music in the period of maybe 1675-1800, particularly Italianate styles.  (If you want to understand North German music from this period or French music, you'll need to look at related historical methods from such countries.)
But it's certainly not an "efficient and pragmatic" method, especially if the goal is to learn to communicate with other musicians about the way they think classical music works.
I certainly believe that partimento is more likely to give you a sense of how the music of that time (again, particularly in most Italian styles) was constructed than most modern music theory.  But it's something that would have been studied historically with a teacher over many years.
Modern music theory textbooks have created shortcuts of a sort intended to try to present a sort of grammar of classical harmony in 2-4 college semesters.  We can argue about how efficient or effective it is, but it's certainly shorter and the de facto way most musicians talk about music theory.
Answer: Partimenti are a perfectly fine way to learn Corelli's style, but not as good a way to learn "counterpoint and harmony for classical music generally."
Counterpoint and harmony teaching has advanced somewhat since the 1700s. Partimenti might be a fun project, and it might teach you what you want to know about counterpoint and harmony, but efficient and pragmatic, probably not, especially without a teacher (which by itself is neither efficient nor pragmatic). Tonality was only just being developed in Corelli's day. So for pragmatism, efficiency, and the broadest view of classical counterpoint and harmony, you might look for a more modern method.
This site doesn't offer recommendations, but if you browse around, you'll find many references to up-to-date ways of learning harmony and counterpoint.
Comment: "Tonality was only just being developed in Corelli's day. You might look for a more modern method": if the goal is to learn to write music in the style of Corelli then working from sources contemporaneous to Corelli is likely to lead to a better result.  Modern counterpoint texts typically cover late renaissance style counterpoint or cover a range of periods.  Also, meta, the prohibition is on questions _asking_ for recommendations.  That doesn't prohibit answers from _offering_ recommendations.
Comment: @phoog OP wants to improve their "understanding of counterpoint and harmony for classical music in general," not specifically in the style of Corelli.
Comment: The question title indicates a desire to "learn how to write a Baroque trio sonata in the style of Corelli," however.
Comment: @phoog Yes, there's a contradiction between the title and the body. I've addressed that in my update to my answer.


Why do I get Operation 'cond/IsVariableInitialized' has been marked as not fetchable

Question: So when I run the below code:
import tensorflow as tf
from keras import backend as K

tensor_a = K.variable([])
def return_zero():
    return 0
def get_mean():
    return K.get_value(K.tf.reduce_mean(tensor_a))

is_equal = tf.equal(tf.size(tensor_a), 0)
r = tf.cond(is_equal, return_zero, get_mean)

print(r)

I get the error:
ValueError: Operation 'cond/IsVariableInitialized' has been marked as not fetchable.

However, if this code is run, there is no error. What gives?
tensor_a = K.variable([])

print(
  K.get_value(
    tf.cond(
      tf.equal(tf.size(tensor_a), 0),
      lambda : tf.constant(0.0), lambda: tf.reduce_mean(tensor_a)
    )
  )
)

Answer: tf.cond takes operations as lambda functions.
Please read https://github.com/tensorflow/tensorflow/issues/4094 for more details on it


How to apply shooting method to boundary value problem with Neumann's boundaries?

Question: I have following boundary value problem with Neumann's boundaries
$$
\begin{cases}
  y'' = y + 8 + 3x(1 - x) \\
  y'(0) = -3 \\
  y'(1) = e - \frac{1}{e} + 3
\end{cases}
$$
I have tried to find in various sources how to solve this kind of problem, but all the sources I have found describe an algorithm for solving the boundary value problem for Dirichlet's boundaries.
I need some kind of clue as to how to apply Shooting method to this problem
Comment: You can find the general solution of the DE, then the boundary conditions give a linear system for the coefficients. If you use an elimination approach, using first the left boundary condition to remove one unknown coefficient, then solving for the right BC emulates the shooting approach.
Answer: Hints:

the general solution of the homogeneous equation $y''=y$ is given by $c_1e^x+c_2e^{-x}.$

a special solution of the equation $y'' = y + 8 + 3x(1 - x)$ has the form $y_s(x)=Ax^2+Bx+C.$ Determine $A,B,C.$

the general solution of $y'' = y + 8 + 3x(1 - x)$ is given by $y(x)=c_1e^x+c_2e^{-x}+y_s(x).$ Now invoke the boundary conditions .
Comment: Thanks,  I have improved it


Finf $f(x)$ which is a second degree polynomial, such that $f(1)=0$ and $f(x) = f(x-1)$

Question: I must find a function $f(x) = ax^2+bx+c$ such that:
$$f(1) = a+b+c=0\\f(x)=f(x-1)\implies ax^2+bx+c = a(x-1)^2+b(x-1)+c\implies\\ax^2+bx+c = ax^2+(-2a+b)x+a-b+c\implies\\a = a, b = -2a+b, c = a-b+c$$
but this results fo $a=b=c=0$. What am I doing wrong?
Comment: What's wrong with $a=b=c=0$? Doesn't that work?
Comment: The only polynomial (of any degree) satisfying that equation is the zero polynomial
Answer: Since $f(1) = 0$ and $f(x) = f(x-1)$, we have $f(2) = f(1) = 0$. Hence if $\deg f \leq 2$,
$$
f(x) = a(x-2)(x-1),
$$
and so
$$
a(x-2)(x-1) = a(x-3)(x-2) \\
a(x-1) = a(x-3)
$$
for all $x$. Hence, $a=0$, so $f = 0$.
Comment: nice proof :-) (+1) May be you should just precise that $\deg f=2$, otherwise $f(x)=a(x-2)(x-1)$ is wrong.
Answer: If $f$ is a polynomial and $f(1)=0$ together with $f(x)=f(x-1)$, then $$0=f(1)=f(2)=f(3)=f(4)=\ldots $$
and $f$ has an infinite number of real roots. That implies $f\equiv 0$.
Answer: You simply get that
$$\{f(x)=ax^2+bx+c\mid f(1)=0, f(x)=f(x-1)\}=\{0\}$$
which is actually correct.
But in other way, you can say that $$\{f(x)\in \mathbb R_2[x]\mid \deg f=2,\  f(1)=0,\  f(x)=f(x-1)\}=\emptyset$$
Answer: You're not doing anything wrong. Think about it this way: $f(x) = f(x-1)$ means that the graph of $f(x)$ stays the same when you shift it to the right by 1 unit. Is it possible for any parabola or line of nonzero slope to have this property?
Answer: If $f(x) = f(x-c)$
for all $x$,
where $c$ is a constant,
and $f$ is a polynomial,
then
$f$ is constant.
Proof:
Let
$g(x) = f(x)-f(0)$.
Then $g(0) = 0$.
Also,
$g(-nc) = g(0) = 0$
for all positive integers $n$.
Since a polynomial of
degree $d$ has at most $d$
distinct zeros,
and $g$ has an infinite
number of zeros,
$g$ must be zero.
Therefore
$f(x) = f(0)$
for all $x$.
(If there is anything
original here,
I apologize.)


Facebook Connect module

Question: I'm using Drupal 6 and FB Connect module, but I can't change Facebook login button design.
What it looks like, now.

What I want it to be.
Answer: A quick look at the code shows that this is being created via:
<code>function theme_fbconnect_login_button($text, $attr) {
  return '<fb:login-button ' . drupal_attributes($attr) . '>' . $text . '</fb:login-button>';
}
</code>
which shows that Facebook is creating the button, and thus suggesting you are stuck with what you got.  Now, there may be some hidden attribute incantation to change the button, but given how brand conscious Facebook is, I doubt they will allow you to change it up using their SDK.

Facebook Connect module


Inserir quebra de página ao gerar PDF com Snappy PDF no Laravel 5

Question: Estou gerando um PDF no Laravel usando o Snappy PDF. O problema é que não está quebrando a página no lugar que deveria.
Já tentei usar o page-break-after: always do CSS no local onde deveria existir a quebra de página mas não funcionou.
Answer: Resolvi o problema adicionando a classe:
.page-break{
   page-break-after: always;
}

no local onde eu queria a quebra.


Outbound SFTP forward proxy

Question: I have two web servers each with a public IP that make outbound SFTP connections to various SFTP servers to update content. I would like to setup a Forward proxy for SFTP outbound connections. Does such a proxy exist?
Comment: But... *why*???
Answer: You can proxy SSH connections (and thus also SFTP which is encapsulated within a SSH connection) by using a generic SOCKS proxy. I am not aware of any protocol-specific proxies for SSH/SFTP.
(It would be easier to answer if you gave a hint about your ultimate objective. What is the purpose of wanting to have the proxy?)
UPDATE
Using SSH to tunnel SSH through a proxy:

Install tsocks on the clients which are initiating the SFTP connections.
In your /etc/tsocks.conf set the following:
server = 127.0.0.1
server_type = 5
server_port = 1080

Open a background SSH connection to your SFTP proxy machine as follows:
ssh -D 1080 -f -n -N ssh-proxy.example.com

...or if you want it to close automatically after 5 minutes:
ssh -D 1080 -f -n ssh-proxy.example.com 'sleep 300'

(If you do this from a script, you probably need to add -i keyfile in the client and a put a corresponding entry in ~/.ssh/authorized_keys in the SFTP proxy server if you want to open the connection from a script without user attention.)
Run the SFTP operations through the proxy by using the tsocks wrapper:
tsocks sftp destination-host.example.com

(This SFTP connection will look in destination-host.example.com as if it was initiated from ssh-proxy.example.com.)

Alternative method with Dante:
Alternatively you could install dante-server (a SOCKS proxy server software) on the proxy machine and configure your /etc/tsocks.conf to connect there instead of 127.0.0.1. Then just run your SFTP operations with the tsocks wrapper as in the step 4 above. If you do this, you need to make sure that the dante server is configured so that it does not allow connections from unauthorized users.
Hope this helps!
Comment: My goal is to have all outbound SFTP connections look like they came from the same public IP, instead from the Public IP of the Web server that served the outbound SFTP connection.

Outbound SFTP forward proxy


Removing the space an element occupies without hiding it

Question: I know that I can hide an element without removing the space it would occupy by using visibility: hidden. What I want to do is the exact opposite: I want to render the rest of the page as if the element wasn't on the page, but keep the element visible.
The reason I'm asking is because I have a centered 950px-wide layout to which I want to add a little box on the left side of the screen. It would look kinda like this:

Right now I have a
 that holds the side box as the top element in my 950px page wrapper, which is also a
. To the side box I've applied position: relative and left: -200px (box width) to move it to the side, but that still leaves me with the main content being pushed down. Am I approaching the problem correctly? Is there a logical way to remove the vertical space that was left behind by the side box?
Answer: Just use position: absolute;. The element will no longer be part of the document flow, and you can position it relative to its closest non-statically positioned ancestor.
Comment: I set the page wrapper (its ancestor) to `position: relative` and the side box to `position: absolute`, which fixed my issue. Thanks!
Answer: Position relative will still occupy the space. Try position:absolute; It will place the element absolutely inside its parent but above all of its siblings.


Python upload PDF into MySQL database via PHP web service

Question: I'm trying to upload a file to a php script running on server via a python script:
PYTHON CODE:
<code>file = open(new_alert.alarmpdfurl, 'rb').read()
r = requests.post('https://www.firerun.at/dbadmin.php?'+data,files={'file':('alarmpdf.pdf', file)})
</code>
The problem is I can not find the file in the $_POST or $_SERVER variables.
The question is how do I get the file in the PHP script to upload it to my MySQL DB as BLOB.
Comment: As a general rule I'd say don't save PDFs into MySQL blobs, but if you must then it's an entirely different question you're asking. There's plenty of help that can be found online about writing BLOBs to MySQL tables. Google is your friend.
Comment: Have you checked `$_FILES`?
Comment: Yes the files seems to be there. but how do I get it into a blob in my database
Answer: $_FILES
http://php.net/manual/en/reserved.variables.files.php
Similar to $_POST, but specific to uploaded files.
Answer: Well, you need to read the contents of the uploaded file first, using a function like file_get_contents("absolute-path-to-uploaded-file").
The value of "absolute-path-to-uploaded-file" should be in the $_FILES array.
The value returned by file_get_contents function can be saved to the blob column in MySQL database


How to set value of struct indirectly in c?

Question: I would like to know, how to access first member of struct through pointer. I have tried this:
#include <stdio.h>
#include <stdlib.h>

struct foo
{
    int a;
    char *str;
};

int main()
{
    struct foo *p = malloc(sizeof(struct foo));
    int val = 10;
    *(int**)p = &val; //set the value of the first member of struct foo
    printf("%i\n",p->a);
}

but that print some garbage. How can I set it in similar manner?
Comment: I'm more curious about *why* you want to do something like this? What is the *actual* problem you need to solve? If it's just plain curiosity that's okay, but please state so in the question body.
Answer: What you're doing there is setting the value of p->a to the address of val (possibly truncated to 32 bits, depending on the implementation).
To access the field via a pointer, you have to take the field's address and then assign to the dereferenced pointer.
int *pa = &p->a;
*pa = val;

Of course you can also just write p->a = val. Note that p->a is just an abbreviation for (*p).a.
Comment: It's also worth noting that `*(int**)p` effectively treats `a` as an `int*` instead of an `int`, so it was doubly wrong in that way too.
Comment: Right, I completely missed that!
Answer: The assignment should be:
*(int*)p = val;

You want to assign to an int member, so the pointer has to be a pointer to int, not pointer to pointer to int. And the value being assigned must be int; &val is a pointer to int.
Comment: @Someprogrammerdude no. cast to the initial member of struct, explicitly allowed.
Comment: Downvoting because the cast is unnecessary and should be avoided.
Comment: Why is the cast unnecessary? The type of `p` is `struct foo *`, you can't use that to assign to just the `int` member.
Comment: It's unnecessary because it can be trivially avoided. See my answer for how.
Comment: I took the definition of `p` as a given, and the question is about how to use that to assign to a member.
Comment: If you want to use p instead of an int*, you should just write `p->a = val`. The cast is just a bad idea.
Comment: @MatthiasBerndt As I understand, the whole point of it is to do it without specifying the member by name.
Comment: There is no reason to do that.
Comment: @MatthiasBerndt Consider code that uses `offsetof()`. This is just a special case where the offset is `0`.
Comment: Sure, you can do it that way. In fact you can access all struct members using offsetof everywhere. But it's a bad idea to do it unless it is actually necessary, and hence shouldn't be encouraged.