How to compute the indefinite integral of $1/(1+x^2)$

Question: The manipulation of logarithms in $(*)$ doesn't hold over the complex numbers. I'm not deleting it, as the answers I got, and the rest of my post make no sense without it, but I also don't want to confuse anyone who may also be new to complex logarithms.
I know the integral upto addition of a constant is $\tan^{-1}(x).$ And, in fact it's not hard to show. However, I'm curious about the case where you start from $1/(1+x^2),$ and without knowing $d/dx\tan^{-1}(x)=1/(1+x^2)$ solving
$$\int \frac{1}{1+x^2}.$$
Let us work modulo constants, so we need not write them. Then
$$\int\frac{1}{1+x^2}=\int\left(\frac{1}{2i(x-i)}-\frac{1}{2i(x+i)}\right)$$
$$=\frac{1}{2i}\left(\ln(x-i)-\ln(x+i)\right)=\frac{\ln\left(\frac{x-i}{x+i}\right)}{2i}.\text{ }(*)$$
It should be clear now that our result is purely real, as $|(x-i)/(x+i)|=1.$ Moreover, it is clear that
$$\ln\left(\frac{x-i}{x+i}\right)=i\cdot\text{argument}\left(\frac{x-i}{x+i}\right).$$
Now, I know that
$$\frac{x-i}{x+i}=\frac{(x-i)^2}{{x^2+1}}=\frac{x^2-1}{{x^2+1}}-\frac{2xi}{{x^2+1}}.$$
This tells us
$$\tan\left(\text{argument}\left(\frac{x-i}{x+i}\right)\right)=-\frac{2x}{x^2-1}.$$
So we can deduce that
$$\int\frac{1}{1+x^2}=\frac{1}{2}\tan^{-1}\left(-\frac{2x}{x^2-1}\right).$$
From here I'm not quite sure how to proceed though. How would one show that modulo constants
$$\tan(x)^{-1}=\frac{1}{2}\tan^{-1}\left(\frac{-2x}{x^2-1}\right)?$$
I guess it is clear if you differentiate both, but that presumes we already had $\tan^{-1}(x)$ in mind.
Comment: $\arctan x+\arctan y=\arctan(\frac{x+y}{1-xy})$
Comment: Your analysis is not meaningful. Logarithms of complex numbers cannot be manipulated so easily. In particular it is not true that $log (ab)=log (a)+log(b)$ irrespective of which branch of logarithm you are using.
Comment: @zwim As it stands your comment already contains the essential idea. Perhaps promote it to a full answer?
Comment: @zwim Thank you, that's exactly the identity I needed.
Comment: @KaveRamaMurthy Okay, any ideas for how to proceed instead? We would have $\ln(a+bi)\equiv\ln|a+bi|+i\tan^{-1}(b/a),$ correct? This would gives us an indefinite integral of $-\tan^{-1}(1/x).$ Well, $\tan(x)=\sin(x)/\cos(x),$ so $-\tan^{-1}(1/x)=-\cot^{-1}(x)?$ Then $\cot(x)=\tan(\pi/2-x)$ gives us our result, right? Alternatively, I suppose we could just stop at $-\cot^{-1}(x),$ it's not the answer I was looking for, but it's simple enough that I would be happy if I found it as the indefinite integral.
Answer: $$\tan^{-1}(x)=\frac{1}{2}\tan^{-1}\left(\frac{-2x}{x^2-1}\right)?$$
Let $$\tan^{-1}\left(\frac{-2x}{x^2-1}\right)=\alpha$$
That is $$ \tan \alpha = \frac{2x}{1-x^2} = \frac {2\tan (\alpha /2)}{1-\tan ^2 (\alpha /2)}$$
With $$x= \tan (\alpha /2)$$ we get $$ \tan ^{-1} (x) = \alpha /2$$
Which is what we wanted to prove.
Comment: Since your are making it an answer, it would be better to make explicit why / there is / or there is not /  a multiple of $\pi$ after the "we get" line, especially when dealing with reciprocal of periodic functions.
Comment: I think you could have pointed how horribly wrong OP's use of logarithms is . This page is very misleading.
Comment: @KaviRamaMurthy I made a mistake there. I'll admit that. I'm not super used to complex logarithms. You don't have to say it is horribly wrong though. That kind of language is discouraging to people studying mathematics. Please be more respectful.
Comment: @Melody Very sorry. I had no intention to discourage you.My intention was to give clear warning to others young students reading this page. By no means was it meant to hurt you.
Comment: @KaviRamaMurthy Thank you. I appreciate the response.
Comment: @KaviRamaMurthy I see why you would want to give a warning. I put a disclaimer at the beginning of the post about that.
Comment: @Melody I really appreciate what you have done. You are very honest and straightforward.
Answer: We have that $$\frac12\arctan\left(\frac{2x}{1-x^2}\right)=\frac12\arctan\left(\frac{x+x}{1-xx}\right)=\frac12\left(\arctan x+\arctan x\right)=\frac12\left(2\arctan x\right)=\arctan x.$$


High Load Website. how to load balancing?

Question: i have the following problem:
 i have two servers (intel xeon 3,4 GHZ with 32GB RAM and RAID 10 (4x1TB Enterprise Harddiscs).
all servers are installed with vmware esxi 5.5 (free). webserver, dbserver all are virutal machines.
the first is a webserver with the newest debian x64 and apache 2. load: 50%
 the second server is a mysql database server with the newest debian x64. load : 95%
so now i have ordered two new server (i think i get the server on friday).
all four servers are internal connected via 1 gb lan.
the current website is:
 - a normal website with drupal and one ioncube application
 - with one mysql database
so i must setup a load balanced cluster, right?
so experts: do you have some informations or tutorials how i can setup the cluster fine?
the project starts in 2013, but now the website is so traffic intencive, ...
thank you very much!
many greets m.k.
Comment: We normally do not recommend off site ressources and provide beginner advice. Your servers do NOT look like database servers to me - which explains the high load on the mysql database server: the discs are pathetically crappy for a high use database server.... start looking there.
Comment: Hello TomTom, you mean my harddiscs to slow? better 4 x ssds in raid 10 or better 8 x 1 tb hds in raid 10? thanks
Comment: SSD. They blow the head out of anything. Raid 5 screams "hey, make me slow".
Answer: Bunch of things going on here.  In the general category of performance tuning, there are multiple levels/steps in the process.  You seem to be skipping to the last step first.  Generally this is how I approach it in my work:

User experience vs. Hardware statistics.

First rule:  if a site works fine for an end user, backend statistics are irrelevant.  They are useful for capacity planning but if a server is running 100% CPU and the site works fine, technically you do not have a performance problem.  You have a "no excess capacity if something goes wrong you're in trouble" kind of problem, but not a problem in the moment.
Conversely, if the servers are basically idle but the site is slow, then the fact the servers are idle is irrelevant - there is still something non-optimal in the mix.

Different layers in the application stack.

There are two layers here it appears:  the web server layer and the database server layer.  Load balancing web servers will not, for example, help if it is your database server that is having performance issues.

Optimizing individual layers.

You want to make sure each layer is configured to properly serve what is needed.  In this case the first poster's comment about disk performance is likely spot on.  Disk space is not sufficient for selecting a storage configuration, generally IOPS or throughput is the most important part.  Also, in the case of SATA vs. SAS, you want to use SAS disks because the storage interface supports more simultaneous connections.
For a CMS like Drupal, you're almost certainly using the database for everything, in which case you likely need far more physical disks to have the speed you need.  The specifics of that, unfortunately, are dependent on a number of variables including whether your site is mostly reads, mostly writes, or a combination, as well as how much data is being transferred in requests (if everyone gets the same front page, that's one transfer and things are likely cached vs. if everyone logs in and gets individual content, the data access will be all over the place).  You should start by optimizing your database server as much as possible, which will require looking at documentation specific to your database software and hardware.
In some cases optimizing the web server layer can be helpful.  Likely that is not a concern for you based on what I can see here.  (Technically, even tuning the "web server" layer has multiple places to optimize - e.g. do you put a proxy in front of it, separate static content, that kind of thing.  But I think you're not in a place to worry about that yet.)

Optimizing the whole environment.

Once you have each individual element tuned, then you look at things like load balancing.  In the case of having dozens of servers, using load balancing to share resources better is a viable approach.  In the case of a small number of servers as seems to be the case here, it is better to think of load balancing as strictly a failover/availability measure, not something to use to compensate for performance issues.
So basically, tune your stack outward from the data.  The information you gain from that process will likely guide you in the process of determining how or whether to implement a specific load balancing solution.
Comment: +1 for "Load balancing web servers will not, for example, help if it is your database server that is having performance issues." and "You seem to be skipping to the last step first"


Notification builder instructions not working

Question: I am creating a notification using some of the methods provided by NotificationBuilder.
I am testing it in real device and, from the following code, none of the methods that I am marking with ---> seems to be working:
long[] vibratePattern = new long[] {
                500, 1000,
                500, 1000};

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "my_channel01");
        notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setContentText(message);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        ---> notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.testProfilePic));
        notificationBuilder.setAutoCancel(true);
        ---> notificationBuilder.setColor(Color.parseColor("#aa0000"));
        ---> notificationBuilder.setVibrate(vibratePattern);
        notificationBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());

So, in words, there is no vibration, no large icon and no background color.
Answer: Try do this :
private static long[] vibratePattern = {500, 500, 500, 500, 500, 500, 500, 500, 500};
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

Notification notification = new Notification.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(context.getString(R.string.change_after_sync))
                .setStyle(new Notification.BigTextStyle().bigText(buildNotificationAfterSynchronizeText(dataResponse, context)))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setLargeIcon(Largeicon)
                .setContentIntent(pendingIntent)
                .setVibrate(vibratePattern)
                .setLights(Color.GREEN, 2000, 2000)
                .build();

Comment: thanks I will try, what is your "LargeIcon" in method `setLargeIcon`??
Comment: nop still not working and I also get a bunch of deprecated methods in your code `Notification.Builder`, `setSound` `setVibrate` and `setLights`


How to set Imageview as an object?

Question: I am working with carousel view. With one layout, I put four images.
And I want to set each image as an each object because I want to set a different method when each image is clicked.
    ImageButton product_photo = (ImageButton) l.findViewById(R.id.myoffer_image);

    product_photo.setImageResource(R.drawable.myoffers_0);

    product_photo.setImageResource(R.drawable.myoffers_1);

    product_photo.setImageResource(R.drawable.myoffers_2);

    product_photo.setImageResource(R.drawable.myoffers_3);

I tried like the code below..but surely it makes an error..
ImageButton one = product_photo.setImageResource(R.drawable.myoffers_0);

I don't know if my question is clear..but if you reply something to know more clear, I will explain it!
Here is pageadapter class!
public class Myoffers_PagerAdapter extends FragmentPagerAdapter implements
    ViewPager.OnPageChangeListener {

private Myoffers_LinearLayout cur = null;
private Myoffers_LinearLayout next = null;
private Myoffers context;
private FragmentManager fm;
private float scale;

public Myoffers_PagerAdapter(Myoffers context, FragmentManager fm) {
    super(fm);
    this.fm = fm;
    this.context = context;
}

@Override
public Fragment getItem(int position)
{
    // make the first pager bigger than others
    if (position == Myoffers.FIRST_PAGE)
        scale = Myoffers.BIG_SCALE;
    else
        scale = Myoffers.SMALL_SCALE;

    position = position % Myoffers.PAGES;
    return Myoffers_Fragment.newInstance(context, position, scale);
}

@Override
public int getCount()
{
    return Myoffers.PAGES * Myoffers.LOOPS;
}

//@Override
public void onPageScrolled(int position, float positionOffset,
        int positionOffsetPixels)
{
    if (positionOffset >= 0f && positionOffset <= 1f)
    {
        cur = getRootView(position);
        next = getRootView(position +1);

        cur.setScaleBoth(Myoffers.BIG_SCALE
                - Myoffers.DIFF_SCALE * positionOffset);
        next.setScaleBoth(Myoffers.SMALL_SCALE
                + Myoffers.DIFF_SCALE * positionOffset);
    }
}

//@Override
public void onPageSelected(int position) {}

//@Override
public void onPageScrollStateChanged(int state) {}

private Myoffers_LinearLayout getRootView(int position)
{
    return (Myoffers_LinearLayout)
            fm.findFragmentByTag(this.getFragmentTag(position))
            .getView().findViewById(R.id.root);
}

private String getFragmentTag(int position)
{
    return "android:switcher:" + context.pager.getId() + ":" + position;
}

}
Main class!
public class Myoffers extends FragmentActivity {
public final static int PAGES = 4;
public final static int LOOPS = 1000;
public final static int FIRST_PAGE = PAGES * LOOPS / 2;
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.5f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;

public Myoffers_PagerAdapter adapter;
public ViewPager pager;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myoffers);

    pager = (ViewPager) findViewById(R.id.myviewpager);

    adapter = new Myoffers_PagerAdapter(this, this.getSupportFragmentManager());
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(adapter);

    pager.setCurrentItem(FIRST_PAGE);

    pager.setOffscreenPageLimit(3);

    pager.setPageMargin(-100);
}

}
Fragment code
    public class Myoffers_Fragment extends Fragment {
protected static final String TAG = "Philips";
FileOutputStream mOutputStream;
private String id;

public static Fragment newInstance(Myoffers context, int pos, float scale)
{
    Bundle b = new Bundle();
    b.putInt("pos", pos);
    b.putFloat("scale", scale);

    return Fragment.instantiate(context, Myoffers_Fragment.class.getName(), b);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }

    LinearLayout l = (LinearLayout) inflater.inflate(R.layout.mf, container, false);

    int pos = this.getArguments().getInt("pos");
    TextView tv = (TextView) l.findViewById(R.id.text);
    tv.setText("Product " + pos);

    /*
     * Put images with Hard-Coding
     */
    {
    ImageButton product_photo = (ImageButton) l.findViewById(R.id.myoffer_image);

    product_photo.setImageResource(R.drawable.myoffers_0);

    product_photo.setImageResource(R.drawable.myoffers_1);

    product_photo.setImageResource(R.drawable.myoffers_2);

    product_photo.setImageResource(R.drawable.myoffers_3);

    }

    Myoffers_LinearLayout root = (Myoffers_LinearLayout) l.findViewById(R.id.root);
    float scale = this.getArguments().getFloat("scale");
    root.setScaleBoth(scale);

    return l;
    }

Thanks!
Answer: Your question is a little vague, but I will respond to the best of my ability--if I am misunderstanding anything, feel free to let me know and I will edit my answer accordingly.
Since 'carousel' is not part of the android SDK, it is a little difficult to be sure what you need to do (it would help if you showed what class/library you are using for this carousel). However, chances are that it will be using this class or a subclass of it in the implementation: AbsListView
Every listview-based class has some method that is called when an item is clicked (here, it is performItemClick). When it is called, it will in turn call the onItemClick method of the associated AdapterView. The adapter is something that you (or the library you are using) created, filled with your data to be displayed, and attached to the ListView.
By registering an AdapterView.OnClickListener, you can specify what behavior a click on a list item at any given index will cause.
Without more details about your carousel, I cannot provide any more code-specific help. However, if you post more info I would be happy to update my answer!
Comment: Really appreciate your reply!!!! Actually, i know my info is full of lack. But I couldnt post all my carousel related code here..that's why...I have three classes relative to carousel view which are main, pageadapter, linearlayout and fragment.
Comment: I just changed Button to ImageButton to put certain images i have. And I want to make method that if an image is clicked, the method would implement..
Comment: are you checking..now?..or..gone..?
Answer: ImageButton is a class, and you created an object of that type called 'product_photo'.  Then you create another called 'one'.  The problem is that you tried to assign a method to one rather than create a new ImageButton. Instead you should have
ImageButton one = new ImageButton();
one.setImageResource(R.drawable.myoffers_0);

Whether or not 'one' needs to be something in your layout that you get with findViewById or not (likely you do) is up to your application.

How to set Imageview as an object?


Help simplifying Bayes' theorem for multiple conditions

Question: I'm trying to use Bayes' theorem to calculate the likelihood, in my example, of religion H being true considering evidence for and against it. I think I understand Bayes' theorem well enough to do this in two steps, calculating the odds that H is true considering evidence against it, and then taking that result as a new prior probability to factor in evidence for it.
I'm sure there's a way to combine those two steps into one, but the explanations I found were not that clear and used a notation that I'm not very familiar with.
So for example prior probability H is true due to the number of possible true religions P(H) is 0.001, the likelihood we'd find particular arguments against it if it were true P(Aa|H) is 0.01, the likelihood that we'd find particular arguments against it if it were not true P(Aa|H') is 0.6, the likelihood we'd find particular arguments for it if it were true P(Af|H) is 0.8, and the likelihood that we'd find particular arguments for it if it were not true P(Af|H') is 0.2. And in my example the arguments against it and arguments for it are both observed.
So then I do the math in two stages, first considering arguments against it:
<code> P(H|Aa) = P(Aa|H) * P(H) / [P(Aa|H) * P(H) + P(Aa|H') * P(H')]
P(H|Aa) = 0.01 * 0.001 / [0.01 * 0.001 + 0.6 * 0.999]
P(H|Aa) = 0.000017
</code>
So now I take that and calculate considering arguments for it:
<code> P(H|Af) = P(Af|H) * P(H) / [P(Af|H) * P(H) + P(Af|H') * P(H')]
P(H|Af) = 0.8 * 0.000017 / [0.8 * 0.000017 + 0.2 * 0.999983]
P(H|Af) = 0.000068
</code>
This gives me a 0.0068% probability that the religion is true given the above assumptions. (I hope I didn't mess up that math.)
But what would be a single equation to do both steps at once?
Edit: I think I may have found the simplification:
<code>P(H|Aa, Af) = P(Aa|H) * P(Af|H) * P(H) / [P(Aa|H) * P(Af|H) * P(H) + P(Aa|H') * P(Af|H') * P(H')]

P(H|Aa, Af) = 0.01 * 0.8 * 0.001 / [0.01 * 0.8 * 0.001 + 0.6 * 0.2 * 0.999]

P(H|Aa, Af) = 0.000067
</code>
Which is the same result (slight difference probably due to my rounding in the intermediate step of the separate calculations). Is there any reason I shouldn't be doing this? I am looking at evidence for and against as "if H is true, how likely would I expect to see Aa? Not likely. But Aa is present, so that's new information."
Answer: Maybe this general formula for multiple conditions helps?
$$P(A|B, C)= \frac{P(B|A, C) * P(A|C)}{P(B|C)} $$
Comment: Can you explain that in terms of the arithmetic like my example above? How do you reach the values for P(B|A,C), P(A|C), P(B|C), and what do they represent?
Comment: @Aaliyah It's a general formula, so you could say $A = H$, $B=Aa$, and $C= Af$. Something like $P(H|Aa,Af)$ would then be the probability that the religion is true given both the arguments against and the arguments for it (which is what you are looking for, right?). Now, the tricky one is $P(Aa|H,Af)$, which you can't really derive from the others ... indeed, I strongly suspect you did something wrong in your calculations and treated a conditional probability as a kind of event: note how you first calculate $P(H|Aa)$, and then plug in that value for $P(H)$ later ... as if $H = H|Aa$ ...
Comment: Why can't I treat it as a kind of event? Isn't it adding new information? Whether I start with calculating with arguments against or I start with calculating for arguments for, I end up with the same ultimate result. (Well, I got 0.0067% instead of 0.0068%, but I will chalk the difference up to my rounding for intermediate steps.)
Comment: I think I may have found the simplification: P(H|Aa, Af) = P(Aa|H) * P(Af|H) * P(H) / [P(Aa|H) * P(Af|H) * P(H) + P(Aa|H') * P(Af|H') * P(H')]

P(H|Aa, Af) = 0.01 * 0.8 * 0.001 / [0.01 * 0.8 * 0.001 + 0.6 * 0.2 * 0.999]

P(H|Aa, Af) = 0.000067

Which is the same result. Is there any reason I shouldn't be doing this? I am looking at evidence for and against as "if H is true, how likely would I expect to see Aa? Not likely. But Aa is present, so that's new information."


Show div if multiple radio buttons checked

Question: So I'm trying to make a div id only appear only if multiple radio buttons are checked with Jquery, I found a solution that works if ONE button is checked, but I cannot find a solution that checks for multiple buttons being checked at once.
It's for a multiple choice quiz so let's say I have 4 questions with 3 answers I need it to check if the right answers are checked in all questions.
This is what I have to check if one radio button is checked which is currently working:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
        if($(this).attr("value")=="q1a1"){
            $("#div").show();
        }
        else{
            $("#div").hide();
        }
    });
});

q1a1 being the first answer in the first question.
my idea was to replace
if($(this).attr("value")=="q1a1")

with
if($('input[name="q1"]').attr("value")=="q1a1")

and have the IF statement check all 4 radio button names for their value with && but I can't seem to make it work. Am I replacing $(this) wrong or can you simply not do what I'm attempting to?
EDIT: live version of the code since JSfiddle is down atm: http://vendila.dk/formtest/
Comment: Why are you checking the value, wouldn't it be easier to just get the one that is checked ?
Comment: If you're actually checking for radio buttons, I don't think that's possible. Radio buttons are meant for a single choice. If you're using checkboxes, you may want to update your question.
Comment: And post your complete code please.
Comment: JSfiddle is down atm, will upload full code when it is up.
Comment: Everyone can view your script, so answers will not be secret. Consider using a server side check if this matters.
Answer: You can check for correct answers using the :checked selector.
if($('input[value=q1a1]:checked, input[value=q2a2]:checked, input[value=q3a3]:checked').length == 3){
  $("#div").show();
}else{
  $("#div").hide();
}

Comment: See the updated answer, I had a typo. Remove the interior quotes in the selector.
Comment: Fantastic. Code runs on live final version, thanx for your time.


Self-signed EV SSL certificate

Question: I have a ton of testing projects going on in my localhost apache server. I have SSL installed on my localhost. Call me a freak (and I wouldn't mind it because this is totally pointless), but I would like my localhost's SSL to be an EV SSL with the green bar. So how can i make a self-signed EV/Green Bar SSL certificate for my localhost? And how can i teach my FireFox to recognize it? Thanks in advance!
Answer: You can't.
EV certificates can only be issued by some certificate agencies which are hard coded inside the browser.
Comment: Technically, you can roll your own cert bundle by forking the browser.
Comment: @DeerHunter:  Sure, you could also change the source code of the browser to show the green bar whenever you like. But that probably wasn't the point of the question.
Comment: @SteffenUllrich Yes. It is crazy, but I want to make the browser just show the green bar.
Comment: You might also try to create a CA (and import it as trusted) with the right OID and then issue a certificate with this CA. See http://stackoverflow.com/questions/14705157/how-to-check-if-a-x509-certificate-has-extended-validation-switched-on which OIDs are used to detect EV.
Comment: Do you have a reference?
Comment: Here's an actual reference (showing how to build Firefox with support for your own EV cert): http://evssl-trust.sidstamm.com/firefox-evca.html

Self-signed EV SSL certificate


py.test - Error collecting when 2 conftest.py in different directories

Question: We using py.test. We try to put different conftest.py files in different folders to split our fixtures:
tests/api/
├── conftest.py
├── folder1
│   └── conftest.py
├── folder2
│   └── conftest.py

But when run the tests this error occurs:
____ ERROR collecting api/folder1/conftest.py ____
import file mismatch:
imported module 'conftest' has this __file__ attribute:
  /tests/api/folder2/conftest.py
which is not the same as the test file we want to collect:
  /tests/api/folder1/conftest.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

Why is that? How fix it?
PS. Removing __pycache__.pyc did not help.
PPS. __init__.py files already exist in each folder.
Comment: I think you want to run two different test runs, one for each subdirectory: `pytest folder1 && pytest folder2`.
Comment: We wanna run all tests `py.test tests/api`, and we wanna separate tests and fixtures by different functionalities.
Comment: I doubt you can have 2 different `conftest.py` during 1 test run. Either use one or do 2 test runs.
Comment: We have a lot of folders with tests `folder1 folder2 etc`. But `conftest.py` one for all this stuff and it is too big. We wanna split fixtures in `conftest.py` by folders with the group of tests.
Comment: Then you have to run tests in every directory separately.
Comment: Are your test files or conftest files importing the conftest module?
Also, does this answer help?: https://stackoverflow.com/questions/12582503/py-test-test-discovery-failure-when-tests-in-different-directories-are-called
Comment: What are you *trying* do to here? Do you really have to name all of your test files `conftest.py`? Is there harm in changing the basename to something other than `conftest`? It's python: at worst you can just blast over a pre-existing fixture.
Answer: I had the same issue. To solve this you need to create python packages instead of directories. Then pytest will look at the conftest.py in your package instead of root directory. Hope, this will help you.

tests/api/
├── conftest.py
├── package1     # not folder
│   └── conftest.py
├── package2     # not folder
│   └── conftest.py

Answer: Your use case sounds like this example in the pytest documentation. Because of that I think it's possible to use conftest.pys at different levels to override fixtures.
The errors you're seeing may be related to incorrect imports. Is your test code importing from conftest files directly? Are your conftest files importing from your tests? Are any of your imports relative instead of absolute? If any of these are true, that may be your issue. I recommend only using absolute imports, and avoid imports between conftest.pys and test files.
Answer: Rename one (or both) of the test files Pytest is complaining about. Pytest is telling you in the error message to do this (i.e. change the basename, meaning don't name all your test files conftest.py). For example, you can fix it by doing:
tests/api/
├── conftest.py
├── folder1
│   └── test_conf1.py
├── folder2
│   └── test_conf2.py

In your case, the module names conflict (you have three conftest.pys). This is a quirk of Pytest AFAIK. Pytest could get around this by managing full package/module paths: but it doesn't do this (probably for good reason, but I do not maintain/contribute to pytest so I can't shed light on the issue). Pytest is a fantastic framework (it's even telling you exactly why it can't run your tests): I'm sure they have a good reason for not supporting this behavior.
You claim that you want to:

separate tests and fixtures by different functionalities.

So do that. Separating the test fixtures/functionalities has nothing to do with what you name the files.
I commonly run into this error when splitting up unit/integration/acceptance tests. I split them up so I can run my (fast) unit tests without having to run my (potentially slow) integration/acceptance tests. I might have some module, call it Abc. And I have something like:
tests/
├── unit
│   └── test_abc.py
├── integration
│   └── test_abc.py

But then pytest barfs with the identical error you've shown, and so I just rename integration/test_abc.py to integration/test_abc_integration.py and move on with my day. Like this:
tests/
├── unit
│   └── test_abc.py
├── integration
│   └── test_abc_integration.py

Is it annoying? A little. How long does the fix take? 5 whole seconds.
P.S. You might have to remove __pycache__ directories or you .pyc files for the first run after you get the error you've posted about (if you don't you'll just get the same error again even if you rename).
P.S.S. You can stop the Cpython interpreter (and most others) from writing out __pycache__ and .pyc files by calling python -B -m pytest .... The -B option makes the interpreter not save the bytecode to your filesystem. This results in some performance penalty whenever you run your test suite, but the penalty is usually very small (milage may vary). I typically use this option because I don't like the clutter in my repositories and the performance loss is typically negligible.


gateway iptables dns redirect

Question: I'm having a problem with redirecting pc's dns requests to a local dns server. I want to block access to other dns services except my own. I've found different methods of doing this, none work here. So I must be doing something wrong.
A lot of people suggest using this:
 iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to 192.168.2.70:53

But in my config this blocks access to DNS. Also I cannot find why this should work in the first place. Since prerouting is for external users that want access to an internal service right?
I also tried specifying the internal lan interface -i eth1 but, this just cannot work since the internal servers are also on the same interface. That would make a loop right? Servers sends out packets for port 53 and the gateway sends it back to the same server.
Then I would also like to ONLY allow the dns servers on my internal network, to contact other external dns servers. Like:
iptables -A OUTPUT -p udp -s 192.168.2.70 -d 184.108.40.206 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 192.168.2.70 -d 220.127.116.11 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p udp -s 192.168.2.72 -d 184.108.40.206 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 192.168.2.72 -d 18.104.22.168 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT

But I'm guessing that the OUTPUT table is not correct. Since from what I learned, INPUT and OUTPUT are only for the local linux router no?
Information:
Internal dns servers: 192.168.2.70 and 192.168.2.72
External dns server: 22.214.171.124 and 188.8.131.52
LAN interface: ETH1
WAN interface: ETH0

My current firewall config without prerouting&forward rules except one to show how it's configed.
 #!/bin/sh -e
ifconfig eth1 192.168.2.1/24

echo 1 > /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

        #Flush table's
        iptables -F INPUT
        iptables -F OUTPUT
        iptables -F FORWARD
        iptables -t nat -F

        #toestaan SSH verkeer
        iptables -t nat -A PREROUTING -p tcp --dport 22 -i eth0 -j DNAT --to 192.168.2.1
        iptables -A INPUT -p tcp --dport 22 -j ACCEPT

        #Drop traffic and accept
        iptables -P FORWARD DROP
        iptables -P INPUT DROP
        iptables -P OUTPUT ACCEPT

        #verkeer naar buiten toe laten en nat aanzetten
        iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT
        iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
        iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

        iptables -A INPUT -p tcp -m state --syn --state NEW --dport 22 -m limit --limit 1/minute --limit-burst 1 -j ACCEPT
        iptables -A INPUT -p tcp -m state --syn --state NEW --dport 22 -j DROP

         #toestaan verkeer loopback
        iptables -A INPUT -i lo -j ACCEPT

        #toestaan lokaal netwerk
        iptables -A INPUT -i eth1 -j ACCEPT

        #accepteren established traffic
        iptables -A INPUT -i eth0 --match state --state RELATED,ESTABLISHED -j ACCEPT

        #droppen ICMP boodschappen
        iptables -A INPUT -p icmp -i eth0 -m limit --limit 10/minute -j ACCEPT
        iptables -A INPUT -p icmp -i eth0 -j REJECT

        #RDP forward voor windows servers
        iptables -t nat -A PREROUTING -p tcp --dport 3389 -i eth0 -j DNAT --to 192.168.2.73
        iptables -A FORWARD -p tcp --dport 3389 -j ACCEPT

Answer: You need to put these rules in FORWARD chain:
iptables -A FORWARD -p udp -s 192.168.2.70 -d 22.214.171.124 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -p tcp -s 192.168.2.70 -d 184.108.40.206 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -p udp -s 192.168.2.72 -d 188.8.131.52 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -p tcp -s 192.168.2.72 -d 220.127.116.11 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT

Give users local DNS servers addresses via DHCP and do not bother to redirect their DNS traffic to local servers - if they manipulate with their network configuration (DNS servers configuration), they will just fail.
Comment: Omg.. That is indeed correct. Totally forgot about the forward chain. DNS request to other dns servers indeed do not work anymore. Thanks!
Answer: I used these rules to force all DNS lookups to be done by dnsmasq on my DD-WRT router:
iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT
iptables -t nat -A PREROUTING -p tcp --dport 53 -j REDIRECT

Those can be stored in DD-WRT by going to Administration - Commands and then entering them in the box and hitting "Save Firewall".

gateway iptables dns redirect


C#: How to load a private key into RsaSecurityKey in .net Framework/Standard?

Question: I need to generate an RsaSecurityKey with a private key to sign a JWT.
I have code working in net5.0 but I need that code to work in a .net Standard/Framework library.
Here is the working code:
        private static RsaSecurityKey GetRsaKey(byte[] privateKey)
        {
            using RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);

            rsa.ImportRSAPrivateKey(new ReadOnlySpan<byte>(privateKey), out int _);
            RSAParameters @params = rsa.ExportParameters(true);

            return new RsaSecurityKey(@params);
        }

Unfortunately, rsa.ImportRSAPrivateKey is not available in .net Standard.
I have not been able to find how to replace that piece.
Would anyone know how we are meant to do that with .net Framework?
Thank you.
Comment: A convenient way is to use BouncyCastle and import the PKCS#1 key e.g. with `PemReader`.
Comment: You can define  `private key` in `Web.config` and get from it.
Comment: @MukarramJavid that only applies for .net framework asp.net, not for .net core
Comment: @DanielA.White It works in .NET 5.0 too. Read `Keys` from appSetting.json from `ConfigurationManager` class
Answer: The following code works in .net 4.0 and higher. I had the same requirement
the code uses bouncycastle and jose.jwt from nuget to generate a jwt.
This is the code fragment I found and tested it works.
GIT Link
In the  main function
claims2 gives you back the json payload you passed

jwt = token

you can test it on jwt.io
put the jwt in the section and the bottom paste the public and private .
If it is a valid signature will be valid
claims is the payload.
Hope this helps you


How can I replace an ANOVA with dependent variables in R?

Question: I am conducting a study on wildfires, and so I have made some measures on burned trees. I have 4 variables (level of damage at the base, level of damage on the bark, species and diameter of the tree). I have converted them into numerical values (categories from 1 to 3 depending on the severity of the burn, categories from 1 to 3 depending on te diameter and categories from 1 to 5 depending on the species). My data looks like that, with each line corresponding to a tree measured.
<code> ALIVE SPECIES DIAM BASE BARK
1     1   1      2    3    1
2     1   3      2    2    1
3     1   1      2    1    1
4     1   2      1    2    1
5     1   2      1    2    1
</code>
I have tried to run a 4-way ANOVA in  R to test which variable has the most impact on the survival of the trees, but I then realised that the variables needed to be independant, which they are not.
I then tried to run 4 one-way anova test, one for each variable and got these results for the base. I followed this method : https://www.scribbr.com/statistics/anova-in-r/
<code> Df Sum Sq Mean Sq F value   Pr(>F)
BASE          2  2.154  1.0770   9.721 8.31e-05 ***
Residuals   277 30.689  0.1108
</code>
Then, like the method said, i checked for homoscedasticity, but it does not seem like the results are as they should be (horizontal lines) :

But it seems strange to me to compare the variance of only 1 variable, which is what an homoscedasticity test does?
Do I need to use a different tool? Is there a method which could tell me what combination of variables has the most impact on the survival rate?
Thanks in advance! (sorry if unclear, english is not my first langage, and i am new to R)
Comment: "I have converted them into numerical values" Why? These should clearly be factor variables and not numeric. Also, correct me if I misunderstand, but shouldn't your dependent variable be binomial? That would mean you should be using logistic regression.
Answer: Your English is perfectly understandable.
A couple points: First, the predictor variables in an ANOVA do not need to be completely independent. They can't be exactly colinear, or the model will "blow up". How much colinearity is acceptable is debated, but there are guidelines related to either VIF or condition indexes. I prefer the latter, and a condition index over 10 is considered a bit problematic and over 30 quite problematic.
Second, converting diameter to a factor is probably a mistake. I'm also interested in how and why you converted the other variables (how is damage measured?) And, when you run ANOVA, it will assume that the levels of the variables are nominal, but they are ordinal. Ordinal IVs are tricky. (Species is nominal, of course).
Third, some of the odd pattern in your plots is due to the predictor variable (here base) taking on only a few values.
Finally, if, after working on the above, you still have heteroscedasticity and other issues with the residuals, you can consider quantile regression or robust regression.
Comment: Concerning why I converted all the variables to factors is because I got an error message when I kept them as text and every example i saw did it that way. I measured damage using 3 categories (not burned, mildly burned and strongly burned), depending on the % of the circumference that had traces of fire, on the depth of the damage and on the way the bark held onto the tree.
Comment: I used this to calculate the condition indexes, none is above 10 so I guess dependance is not a problem? '> condindex = cond.index(my_data)
> condindex
 [1] 1.000000 1.796077 1.826920 2.033940 2.069053 2.364880 2.539318 4.028966 4.717604
[10] 5.205287 8.712561' Thanks a lot for your help!
Comment: Well, I know nothing about measuring fire damage but I would have probably done some sort of factor analysis. But your method may be OK.   Diameter should be a number to start with. Collinearity looks like it is not a problem.


How is the product $c_I \alpha^I$ defined?

Question:
My Doubt:-
The author had pointed out the notations used by him. I have put that in a box. In the Proposition 3.29, the author used the notation for proving linear independence using $\sum c_{I}\alpha^{I}$. According to the paragraph in the box $c_I=(c_{i_1},...,c_{i_k})$ and $\alpha^I=\alpha_{i_1}\wedge ... \wedge \alpha_{i_k}$. On contradictory to the notation mentioned in the box auther had written $C_I \in \mathbb R$. How does the product $c_I \alpha^I$ defined?  From Diego's answer. I have one more doubt. How can I expand the summation?  For example, if the summation is like $\sum_{k=1}^n a_ic^i$. Then, without any confusion, I can expand it as $a_1c^1+...+a_nc^n$. Please help me.
Answer: Here $c_I$ isn't a tuple, but a number associated with the multi-index $I$. He specifically says so at "$c_I \in \mathbb{R}$".
Comment: How does the product $c_Iα^I$ defined?
Comment: Now I got one more doubt, How would the sum look like?
Comment: Is it like $\sum c_I\alpha^I=\sum_{i_1}\sum_{i_2}\sum_{i_3}...\sum_{i_k}c_{i_1,i_2,...,i_k}\alpha^{i_1}\wedge \alpha^{i_2}...\wedge \alpha^{i_k}$?
Comment: ....yes........


Import flat file to SQL server using C#

Question: I want to make a program in C# that imports two types of files to SQL Server: tab delimited and fixed columns. Actually, I need to download a file every day and import that file into my database. I could make a console app with batch script. I saw some examples like this, but I don´t know if it is the best object-oriented way to do it.
I could use StreamReader, Regex and so on, but I don't want to re-invent the wheel.
PS:
In VBA I used "QueryTables.Add".
Comment: Could you show the format for what the file is supposed to look like related to the SQL server?
Comment: Please note that Batch tag is "used for Windows batch file questions". Don't use it just because your question is related to "batch" word in any way...
Answer: You can import in fully managed code via SqlBulkCopy; all you need to do is pass SqlBulkCopy an IDataReader that handles TSV. Fortunately the FastCsvReader on codeproject can do exactly that.
Comment: I have some trash rows in my file. I need something like row patterns (Regex). I could create some file converter then use SQLBulk
Answer: If you don't want to reinvent the wheel, then you should look at the native tools that SQL Server provides for this, namely bcp. Here is a list of FAQs about bcp.
Answer: Sounds like a perfect job for SQL Server Integration Services (SSIS). You can easily define a data import task in SSIS and then schedule it to run by using a SQL job.
Comment: I'm using SQL Server 2008 express
Answer: bulk insert [dbo].[CoursesTemp]

from 'C:\Users\Public\Downloads\Courses.csv'
with (fieldterminator = ',', rowterminator = '\n')
go
insert [dbo].[Courses]
  (code, description, instructor, date, venue, duration)
select
   code, description, instructor, cast(date as date), venue,
   duration
from [dbo].[CoursesTemp]

Import flat file to SQL server using C#


how to solve a system with more equations than unkowns?

Question: In general, how do you solve a system with more equations than unknowns? I know that if I select the equations to match them with the number of unknowns, there may be zero or many solutions depending on our selection. Where can I go from there? And how does a "pseudo inverse" come in the picture? Thank you. -Cody
EDIT: I know overdetermined system usually have no solution, but in my case (triangulation matting, i.e filtering out the weatherman from the blue screen), I was told there is a solution and I need to find it using pseudo inverse.
Comment: Do you know how to solve via using an augmented matrix? Follow the same procedure and in the end, if you have $k$ variables, rows $k+1$ through $n$ should reduce to a row of zeroes. If not, then there is no solution.
Comment: Are your equations linear? If we're restricted to real numbers, then you can solve $\sum x_i ^2 = 0$.
Answer: I'm assuming you're referring to linear equations.
Although the linear system of equations $Ax = b$ might not have a solution when the system is overdetermined, you can always find a least-squares solution
$$\min_x \|Ax-b\|^2.$$
If the minimum value is $0$, a minimizer $x$ is a solution to the system. Otherwise, $x$ is the "closest possible" solution, in the sense of minimizing the residual error, to a system that has no solution.
To find a minimizer $x$, you take a derivative and set it equal to 0:
$$A^TAx -A^Tb = 0.$$
The matrix $A^TA$ might be singular, but $A^Tb$ always lies in its column space so this system always has a solution. You can find one such solution by calculating $x = A^{+}b$, where $A^{+}$ is the Moore-Penrose pseudoinverse of $A$.
So to find a solution to your overdetermined system, one approach is to compute(*) the pseudoinverse $A^{+}$, then calculate $x = A^{+}b$. You can check if $Ax=b$ to see if your overdetermined system did in fact have a solution.
(*): My favorite method, in terms of robustness and efficiency, for computing the pseudoinverse is to use the QR decomposition of $A$. The details are beyond the scope of this answer, but worth looking up if you're interested.
Answer: In general, there is no solution. (I am assuming you are talking about linear equations, but this is also sort of true for polynomial equations.)
However, it might be that some of your equations are a consequence of the others,
so they are not really independent equations, and there might be solutions.
In the case of linear equations, your system may be expressed as $Ax=B$,
where $A$ is the coefficient matrix of your variables, and $B$ is the constants.
Now, your system has (at least one) solution if $rank(A) = rank(A|B)$
i.e. the larger block matrix $A|B$ does not have larger rank than the matrix $A.$
If $rank(A)$ equals the number of variables, (and  $rank(A) = rank(A|B)$) then the system has a unique solution, and if less, you will have infinitely many solutions.
if the rank is less, then you even have infinitely many solutions.
Answer: You can think of an overdetermined system as a bunch of data points (rows of $A$) that you want to fit the best line (or plane, hyperplane, etc.) to ($x$). The solution probably won't even intersect any of the points, but it will be the best solution in that it will minimize the sum of squared errors of all of the points relative to the solution. (That's one way of thinking about it.)
A pseudoinverse is any $A^+$ that satisfies $A^+AA^+=A^+$ and $AA^+A=A$ (obviously a regular inverse satisfies these properties too). If you let $x^* = A^+B$ then $x^*$ will be the best fit for the normal to a hyperplane that estimates all the rows of $A$. That is, $\|Ax^*-B\|^2$ will be minimized.
So again, the pseudoinverse probably won't give you a solution, but it will give you the next best thing.
Most math packages have some kind of pinv function that will compute the pseudoinverse of a matrix, and will usually compute the Moore-Penrose pseudoinverse.
Answer: Consider the sample problem
$$
\begin{align}
 \mathbf{A} x &= b \\
%  A
\left[
\begin{array}{cc}
 1 & 0 \\
 0 & 0 \\
\end{array}
\right]
%  x
\left[
\begin{array}{c}
 x_{1} \\
 x_{2}
\end{array}
\right]
%
&=
%  x
\left[
\begin{array}{c}
 b_{1} \\
 b_{2} \\
\end{array}
\right]
%
\end{align}
$$
If $b_{1}\ne 0$, a solution exists. If $b_{2} = 0$, the solution is unique:
$$
 x =
\left[
\begin{array}{c}
 x_{1} \\
 x_{2}
\end{array}
\right]
=
\left[
\begin{array}{c}
 b_{1} \\
 0
\end{array}
\right]
$$
Let's focus on the least squares case where $b_{1}\ne 0$, and $b_{2}\ne 0$. The least squares minimizers are defined as
$$
 x_{LS} = \left\{
x \in \mathbb{C}^{2} \colon
\lVert
 \mathbf{A} x - b
\rVert_{2}^{2}
\text{ is minimized}
\right\}
$$
The solution to the least squares problem is
$$
 x_{LS} = \color{blue}{\mathbf{A}^{\dagger} b} +
\color{red}{\left(
  \mathbf{I}_{2} - \mathbf{A}^{\dagger}\mathbf{A}
\right) y}, \qquad
y \in \mathbb{C}^{2}.
$$
Coloring separates $\color{blue}{range}$ spaces from $\color{red}{null}$ spaces. The diagram shows the point $ \color{blue}{\mathbf{A}^{\dagger} b}$ in the range space $\color{blue}{\mathcal{R}\left(\mathbf{A}\right)}$. The full solution is the affine space represented by the dashed red line.

The least squares solution for the example is
$$
 x_{LS} =
\color{blue}{
\left[
\begin{array}{c}
 b_{1} \\
 0
\end{array}
\right]
}
+
\alpha
\color{red}{
\left[
\begin{array}{c}
 0 \\
 1
\end{array}
\right]
}, \qquad \alpha \in \mathbb{C}
$$


Estou fazendo certo este exercício?

Question: Até então estou conseguindo fazê-lo, porém o método imprimiAgenda() está imprimindo, mas ao mesmo tempo dando null pointer. E também quero saber se minha lógica está indo bem. Se puderem me ajudar, agradeço! Uma outra dúvida, como faça para fazer os getters e setters de arrays? Pois o setter até consegui fazer, sem problema algum, já o getter dava problema, pois ele precisava de um retorno.
package exercicio;
public class Agenda {
     private String nome[] = new String [5];
     private int idade [] = new int [5];
     private float altura [] = new float [5];

public void armazenaAgenda (String nome, int idade, float altura) {
    for (int c=0; c<=5; c++) {
        if(this.nome[c] == null || this.nome[c].isEmpty()) {
        this.nome[c] = nome;
        this.idade[c] = idade;
        this.altura[c] = altura;
        break;
        }

    }
}

public void imprimiAgenda () {
    for (int c=0; c<=5; c++){
        System.out.println("Nome: " + this.nome[c]);
        System.out.println("Idade: " + this.idade[c]);
        System.out.println("Altura: " + this.altura[c]);
        System.out.println("------------------");

    }
}

public void buscarIndex(int i) {
    for (int c=0; c<=5; c++ ){
        if(this.nome[c] == this.nome[i]) {
            System.out.println("Nome: " + this.nome[i]);
            System.out.println("Idade: " + this.idade[i]);
            System.out.println("Altura: " + this.altura[i]);
            break;
        }
    }
}

public void buscarNome (String nome) {
    for (int c=0; c<=5; c++){
        if (this.nome[c] == nome) {
            System.out.println(nome + " esta na posicaçao: " + c);
            break;
        }
    }
}

Comment: Uma boa orientação a objeto poderia ser você criar uma classe, digamos, `Pessoa`. Dentro dela, você teria então os atributos `nome`, `idade` e `altura`, encapsulados com _getters_ e _setters_. Então, na classe `Agenda`, em vez de 1 _array_ para cada atributo, como é hoje, você teria um único _array_, de `Pessoa`. Com relação a sua lógica atual, você terá problemas nos `for` por causa da condição de parada dele. Veja se consegue entender por quê.
Comment: so uma coisa, nessa parte aqui:
     if(this.nome[c] == null || this.nome[c].isEmpty())
é para checar se o campo da string[indice] = esta vazia pra assim ser preenchida com this.nome[indice] = nome; entendeu ? como faço para checar se a String no indice X, esta vazia sem usar esses operadores == =!
Comment: sim, o Objects.equals. Porem ele verifica se sao iguais e nao nulas, mas eu quero ao contrario, eu quero saber se sao nulas, se for nulas, e vazias preencher...
Answer: Há alguns erros. O principal erro é que você não deve usar == ou != para comparar Strings. Use o método equals. para evitar ter que se preocupar com o caso de um deles ser null no método equals, você pode usar Objects.equals(a, b).
Assim sendo, no lugar disso:
        if(this.nome[c] == this.nome[i]) {

Você deveria usar isso:
        if (Objects.equals(this.nome[c], this.nome[i])) {

E também, no lugar disso:
        if (this.nome[c] == nome) {

Você usaria isso:
        if (Objects.equals(this.nome[c], nome)) {

Os seus laços também estão com os limites errados:
for (int c=0; c<=5; c++){

Era para ser isso:
for (int c = 0; c < 5; c++) {

Há ainda um outro problema. Você não deveria usar um for no método buscarIndex, afinal o índice já é lhe dado como parâmetro. Bastaria fazer isso:
public void buscarIndex(int i) {
    System.out.println("Nome: " + this.nome[i]);
    System.out.println("Idade: " + this.idade[i]);
    System.out.println("Altura: " + this.altura[i]);
}

Há outras coisas que poderia ser consideradas. Em especial seria uma boa ideia ter uma classe Contato com nome, idade e altura e também getters e setters e então fazer a Agenda ter uma List<Contato>, o que também te livra da restrição de ter o tamanho máximo da agenda fixo em 5 e também facilitaria bastante operações de adição, remoção e busca de contatos na agenda.
Comment: Não faço idéia do que seja isso. :D
Comment: @Aricuno Armazenaria os contatos numa lista e usaria `Optional` como retorno do método.
Comment: Talvez, verificar se o indice não é maior que o limite do array, já que o método e o proprio array fazem parte da mesma classe. Já evitaria arrayindexofboundexception.
Comment: Apesar de que eu faria essa verificação fora da agenda e não internamente.
Comment: @Articuno Na verdade eu faria um `return contatos.size() < i ? Optional.empty() : Optional.of(contato.get(i));` - mas o OP ainda está bem longe de poder entender isso.
Comment: Muito obrigado. Estou iniciando e aprendendo,muito importante a sua resposta para o meu desenvolvimento. No intuito de praticar, eu procurei exercícios na internet de java poo, a ideia era essa, cria uma agenda com o limite de 5, que teria os métodos getters e setters de nome,altura, idade e também um que armazene esses três atributos, removesse, procurasse pelo nome e procurasse pelo índice

Estou fazendo certo este exercício?


Is paired t-test valid for half-normal data?

Question: ok i am not a statistician.
I am doing paired comparison for several outcomes of cross validated interpolation results.
I have to consider only the absolute value in my analysis and so although original data follows a normal distribution the resultant absolute values are only half normal.
So is the t-test still valid and sound and in either case (yes/no) what is the reasoning behind it ?
Comment: Could you elaborate on why you are considering only absolute values?  That seems artificially restrictive, maybe even counterproductive.
Comment: the values i am considering are cross validation errors and i need to check whether the deviation from actual value is very high ( i am averaging them for summary) ...i have realized that perhaps i can perform the test using actual values too
Answer: It is not valid in general because the deduction of the distribution of the t-statistic depends on the assumption of normality.  In addtion,  the interpretration of testing the hypothesis of equality of means in the half-normal case is not clear because the mean depends on the parameters mu and sigma.  Therefore if the variance of the populations differs (even slightly),  you will reject the hypothesis more than you should even if the parameters mu1=mu2 (this is,  you are not getting the desired Type I error level).  Take a look at this code so you can verify it
rm(list=ls())
power = function(n,ns,mu1,mu2,s1,s2){
count = rep(0,n)
for(i in 1:n){
x = mu1 + abs(rnorm(ns,0,s1))
y = mu2 + abs(rnorm(ns,0,s2))
if(t.test(x,y,paired=TRUE)$p.value>0.05) count[i] = 1
}
return(1-mean(count))
}
power(10000,30,1,1,1,1.15)
power(10000,100,1,1,1,1.15)
power(10000,30,1,1.1,1,1)

Perhaps it would be helpful to plot the profile likelihood of the parameters of each population and take a look at the similarities between them.  Also you could use a likelihood ratio test instead.
I hope this helps.
Best wishes.
Answer: A paired t-test is equivalent to a one sample t-test of the differences being 0.
You could, therefore, take these differences and see if they are normally distributed or not. These differences could be normally distributed, even if the original values are not. e.g.
diff <- rnorm(100, 0, 1)
first <- diff + runif(100,10, 100)
second <- first - diff
qqnorm(diff)
qqnorm(first)
qqnorm(second)


When will a data provider annotation will be executed in testng

Question: I am running a Testng xml in selenium. It has
@BeforeSuite
@BeforeTest
@Dataprovider
@Test(2 methods)
@AfterTest
@AfterSuite

When will the data provider method will be executed, at which phase. Will it execute before BeforeSuite or BeforeTest ? will it be executed fully ?
Answer: You can call the @Dataprovider(name="testdata") from your @test annotation and not from other annotations like @beforesuite etc. You need to call the dataprovider from the @test annotation like @Test(dataProvider="testdata")
The @dataprovider will be executed whenever you call from your @test method
Comment: Suppose I have many variables and logic written in dataprovider. So I want to know how many the times dataprovider method will be invoked ? For each @Test annotation will it be invoked ?
Comment: It depends on your requirement and it won't be executed for each "@Test" annotation unless you call the Data Provider. It will be executed only if you call the "Data Provider" with its Name from your "@test" method. Please accept this answer if I have answered your question.


Hilbert transform and Fourier transform

Question: Assume the following relationship between the Hilbert and Fourier transforms:
$$
\mathcal{H}(f) = {\mathcal{F}^{-1}}(-i ~ \text{sgn}(\cdot) \cdot \mathcal{F}(f)),
$$
where $ \displaystyle [\mathcal{H}(f)](x) \stackrel{\text{def}}{=} \text{p.v.} \frac{1}{\pi} \int_{- \infty}^{\infty} \frac{f(t)}{x - t} ~ d{x} $.
What happens when $ f(x)$ is a distribution? We know that the Fourier transform exists for distributions, but what about the Hilbert transform?
For example, take $ f(x) = x^{n} $. Its Fourier transform exists as the $ n $-th derivative of the delta function $ \delta(x) $. However, the integral
$$
\text{p.v.} \frac{1}{\pi} \int_{- \infty}^{\infty} \frac{x^{n}}{x - t} ~ d{x}
$$
is divergent. :(
Comment: You have taken the Fourier transform of $x^n$ as a distribution, but why do you treat the Hilbert transform of $x^n$ as a function[thus it is divergent]?
Comment: is $isgn$ actually $sign$?
Comment: What is '$ w $', by the way?
Comment: @rschwieb $i$ is correct: see, e.g., [here](http://en.wikipedia.org/wiki/Hilbert_transform#Relationship_with_the_Fourier_transform).
Comment: @5pm  Oh :) I thought it might be a simple transposition. Good thing I didn't change it!
Answer: The Hilbert transform is anti-self-adjoint. Therefore, it is natural to define it on distribution by passing $\mathcal H$ to the test functions, similar to "pass the hat" definition of the Fourier transform. In fact, the Wikipedia article already says this.
Since the stated relation between $\mathcal{F}$ and $\mathcal H$ holds for test functions, the duality-based definition implies that it holds for distributions as well.
Comment: This is not correct, since the Hilbert transform does not stabilize the Schwartz space (not test functions). That is, there is no "definition by dualizing", unfortunately.
Answer: The multiplication by "sign" (with or without a constant "$i$" in front) does not map Schwartz functions to Schwartz functions, so that the otherwise-appealing notion of defining an automorphism on (tempered?) distributions by defining it on (Schwartz?) test functions does not succeed here.
Although in general it is ... very risky... to try to "multiply" distributions, a more delicate approach does allow multiplication when the "singular sets" are disjoint.
In the case at hand, multiplication of a distribution by "sign" would make sense, for example, if the singular support does not contain $0$. Thus, a tempered distribution whose Fourier transform has singular support not including $0$ has a Hilbert transform.

Hilbert transform and Fourier transform


How to support my smart watch application on Sony SmartWatch

Question: I have created a widget application for smart phone. Now i want to support the same application to sony SmartWatch. Any idea how to start or any sample code to refer.
Thanks in advance for Help.
Answer: You should have all the resources compatible to your smart watch. I mean resolution,density. Any android app will run on smartwatch.but the thing is that you can use only those apis that are supported for smart watch. You can run your app same as you are running on devices.


Want to go back to old git commit

Question: Ok, I think I've screwed things up, I am working on a project and using git as version control:
I think I screwed up somewhere along the lines and now when I say git status I get:
# Not currently on any branch.
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   Cocina/bin/Debug/Cocina.exe
#       modified:   Cocina/bin/Debug/Cocina.pdb
#       modified:   Cocina/obj/x86/Debug/Cocina.exe
#       modified:   Cocina/obj/x86/Debug/Cocina.pdb
#       modified:   Viernes 7.suo
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       Cocina/Info.cs
#       Cocina/bin/Debug/Cocina.vshost.exe.manifest
#       Viernes 7/Properties/DataSources/
#       Viernes 7/Table.cs
#       Viernes 7/bin/Debug/Viernes 7.vshost.exe.manifest
#       Viernes 7/obj/x86/Debug/ResolveAssemblyReference.cache
#       back/
#       tables/
no changes added to commit (use "git add" and/or "git commit -a")

I have everything I did [here][1], but it's a quite long, but maybe it help out.
The only thing I know for a fact is that in this commit I am sure everything is working as I wanted, and them everything started going south with the merges...
PS C:\Users\Trufa\Documents\Visual Studio 2010\Projects\Viernes 7> git commit -am "the lisview now saves indexes of allr
eady clicks and deletes when table closes"

Can I go back and check how the files where at that moment?

Sorry to the answerers I lost my Internet connexion right after I posted the question!
So UPDATE:
I had a copy of git gui from github that helped me visualize what the different commits.
There was some kind of a conflict with the .exe 's and it prevented me from doing more or less anything I couldn't merge and I couldn't commit and I couldn't check out so what I did was copied my non working but correct commit and put in into another project in the same solution.
So the question is what should I do now?
I would be happy to "start" over, I mean at this point the project is working as it should so I would like to commit it, so now, what should I do?
I guess the whole problem was for not using a complete gitignore file, what happens if I add it now?
So my question is what should I do now, I'm kind of afraid of braking things because I'm on a hurry, what is the simplest solution of all? Is it a big overkill to start the git repo from scratch, delete the git and start over from this point since It's working?
I know this sounds a little bit mediocre but I don't have much time so I really don't want to be playing around learning about git, I'll have time for that later, now I want an easy fix.
Comment: Please comment if the question is not clear enough
Comment: Are there clones of your repo outside, which are not under your control?
Comment: Then you can restart by using `git filterbranch` like in http://stackoverflow.com/questions/5677766/filter-branch-to-remove-extra-directory or http://stackoverflow.com/questions/4444091/git-filter-branch-to-delete-large-file
Answer: I see two problems with your log:

You have generated artifacts in your git repo, which are now obstacles when you want to change your active branch
You are currently in the detached head state.

Generated artifacts
You should not place generated files like *.exe into your repo, since these files cause trouble when you want to merge diverged development lines.
Also you have another problem, since you can't overwrite these files when they are open, so you need to close the running programs to overwrite *.exe files, and close visual studio to overwrite *.sou and *.pdb.
See .gitignore for Visual Studio Projects and Solutions for things better left out.
Detached Head
On line 232 you checked out a revision by its SHA1, which placed you in the so called detached head state. This means, that when you commit something atop of this commit, and check out some other branch, you will have a hard time to get back to the just created commit. See http://marklodato.github.com/visual-git-guide/index-en.html#detached for more details.
Comment: Hey thanks for the answer sorry for the delay, I had no Internet connexion until now! I'll kind of solved it in the middle of all this so I'll be updating my question because the situation has changed a little in the meantime, sorry and thanks!!
Answer: mm You are not in a branch in your Git folder. I think nothing wrong has happened to your files.
Have you tried?
$ git branch --> will list all your branches
This should list at least your master branch
$ git checkout master --> this will switch to master and you will be able to commit files again
Comment: Ok then you need to stash your files. Stashing wil just save them temporally assoicated with a name, then you can switch branches and then un-stage your files and finally commit them in your cocina branch. Personally I have not stash files using the command line but this article seems to explain it http://git-scm.com/book/en/Git-Tools-Stashing, the way I usually work with my stage files is using _TortoiseGit - Stash Save_
Comment: I already tested, just use `$ git stash` and after you switch your brances: `$ git stash apply` and you are done! =)
Comment: Hey thanks for the answer sorry for the delay, I had no Internet connexion until now! I'll kind of solved it in the middle of all this so I'll be updating my question because the situation has changed a little in the meantime, sorry and thanks!!
Answer: First of all, you can see a log of all your commits:
$ git log --online

(--online is not mandatory, but makes output less verbose). Output will be something like:
1fb3915 Fixed View page.
3f69344 Added new images.
d2f74d8 Fixed css.
0e516db Added some photos.
5b99592 Added all cart pages.

If d2f74d8 is the commit where everything was working. Just type:
$ git checkout d2f74d8

Now you can re-start from here. You just want to copy here some code and paste it in master? Copy code and type
$ git checkout master

You want to re-start to code from here? I suggest you to create a new branch:
$ git checkout -b new-branch-name

Make here your stuff. And when you are ready, you can merge code with your branch:
$ git checkout master
$ git merge new-branch-name

Comment: Hey thanks for the answer sorry for the delay, I had no Internet connexion until now! I'll kind of solved it in the middle of all this so I'll be updating my question because the situation has changed a little in the meantime, sorry and thanks!!

Want to go back to old git commit


How to increment the value of a structure with multiple thread in C

Question: i want to increment the value of a counter stored in a structure. 3 threads are coming into the fonction tattoo_shop to increment the number of people but for some reasons the value of number_of_people remain the same.
I tried to reproduce the case sequentially and it's working. Is there something special to do as i'm working with threads ? Thank you :)
typedef struct {
    int number_of_people;
}Queue;

void *tattoo_shop(void *arguments){
     Client *args = arguments;
     Queue the_queue;

     add_to_the_queue(&the_queue,args);
}

void add_to_the_queue(Queue *the_queue, Client *the_client) {

    pthread_mutex_lock(&mutex_queue);
    the_queue->number_of_people++;
    pthread_mutex_unlock(&mutex_queue);

    printf("The thread %d is changing the counter of the queue which is now %d \n",the_client->id,the_queue->number_of_people);
}

Output :
The thread 1 is changing the counter of the queue which is now 1
The thread 0 is changing the counter of the queue which is now 1
The thread 2 is changing the counter of the queue which is now 1

Comment: the_queue is a local variable, and every time you call the routine, it's intialized anew
Comment: It's not clear to me how your multiple threads end up sharing the same queue.
Comment: @OliverCharlesworth my threads are all going to the function tattoo_shop and from that they get to go in the function add_to_the_queue.
Comment: So each one creates its own queue.
Comment: `static Queue the_queue;` should help with multiple queues
Answer: Your code is nonsense since Queue the_queue; is a local variable, not a shared one.
But had it been allocated at file scope, or as static, the code is mostly fine. Pedantically, you should not read the shared object outside mutex guards, because writes to the object from elsewhere are not guaranteed to be atomic. Slight adjustment to fix this:
{
    pthread_mutex_lock(&mutex_queue);
    int people = the_queue->number_of_people++;
    pthread_mutex_unlock(&mutex_queue);

    printf("%d", people);
}

Comment: How could I make the_queue shared ? The thing is that I need to then get this data out of the function add_to_the_queue to perform tests in tattoo_shop.
Comment: @MaxUt: You define the queue outside the functions (file static variable).  That also initializes it to zero; your code increments an uninitialized variable, and you're just lucky that the memory happens to be zeroed (probably to prevent you prying at the data that a previous process stored in the same physical memory, but that is not guaranteed by any standard).  And all access to the queue needs to be mediated by the mutex (which, I note, is not defined/declared in the code shown, but must be a file scope variable).  Your printing code should be in scope of the mutex lock/unlock pair.


SQL query to find partial string match across 2 tables

Question: I'm trying to find any items in column address (users table) that have a match in Address (address_effect table). I'm testing this on my local system with XAMPP (using MariaDB)
user table
+------------------+-----------------+------------------+--------------------------+
|        ID        |    firstname    |  lastname        |    address               |
|                  |                 |                  |                          |
+----------------------------------------------------------------------------------+
|     1            |    john         |    doe           |james street, idaho, usa  |
|                  |                 |                  |                          |
+----------------------------------------------------------------------------------+
|     2            |    cindy        |   smith          |rollingwood av,lyn, canada|
|                  |                 |                  |                          |
+----------------------------------------------------------------------------------+
|     3            |    rita         |   chatsworth     |arajo ct, fremont, cali   |
|                  |                 |                  |                          |
+------------------+-----------------+---------------------+-----------------------+
|     4            |    randy        |   plies          |smith spring, lima, peru  |
|                  |                 |                  |                          |
+----------------------------------------------------------------------------------+
|     5            |    Matt         |   gwalio         |park lane, atlanta, usa   |
|                  |                 |                  |                          |
+------------------+-----------------+------------------+--------------------------+

address_effect table
+---------+----------------+
|idaho    |potato, tater   |
+--------------------------+
|canada   |cold, tundra    |
+--------------------------+
|fremont  | crowded        |
+--------------------------+
|peru     |alpaca          |
+--------------------------+
|atlanta  |peach, cnn      |
+--------------------------+
|usa      |big, hard       |
+--------+-----------------+

I've tried using inner join with LIKE to find matching string.
If I use this query it doesn't find any items:
SELECT users.firstname, users.lastname, users.address
FROM users
INNER JOIN db_name.address_effect
ON
(address_effect.Address LIKE '%' + users.address + '%'
OR users.address LIKE '%' || address_effect.Address || '%')

Then I tried the following query, it lists all the items from user table, instead of only those items that have a match in address_effect
SELECT DISTINCT users.firstname, users.lastname, users.address
FROM users
INNER JOIN db_name.address_effect
ON
(address_effect.Address LIKE '%' || users.address || '%'
OR users.address LIKE '%' || address_effect.Address || '%')

What am I missing here?
Thanks.
Comment: In your sample data, everything has a match.
Comment: You're right! I mistakenly added last few records in the address_effect table that shouldn't have been there.
@GMB query with find_in_set seems to work
Answer: As I understand your sample data, you want to match parts of users addresses against values in the other table.
You might want to try find_in_set(). It is more accurate that a LIKE match, since it matches on individual elements only:
SELECT u.firstname, u.lastname, u.address user_address, a.*
FROM users u
INNER JOIN address_effect a
    ON FIND_IN_SET(a.address, REPLACE(u.address, ', ', ','))

This matches if address_effect(address) can be found in the CSV list stored in users(address).
Comment: It worked.
I didn't know about find_in_set and it sure is handy and query runs much faster than with Like.
Thanks a lot.
Comment: Fyi, I asked an additional question to this query [here](https://stackoverflow.com/questions/62964855/updating-table-based-on-the-results-of-previous-table)


Can I create root level shares from AD User Accounts?

Question: Given a file structure for User accounts of \\file-server\students\grad-year\user-home-folder,  is it possible to create shares of \\file-server\user-name?
I have a Mac/Windows mixed environment. The Macs work much better with a root level share.
I can create the home folders in the users' directory in AD User Properties - Profile tab using \\file-server\students\grad-year\%username%. However, that seems to simply create the folder and not a true share. The file-server properties show the home folder as "Network Path: Not Shared".
I have about 2000 accounts to handle like this. So I'd like to find a way to automatically create true shares (like you'd create with Advanced Sharing).
Is that possible?
Comment: the profile tab in ADUC is a true share as \\server\students (then the remaining path is just a path within the share).  You map down to the username level with directory traversal, but only because the student accounts don't have rights at the "students" share level.
Comment: Oh yuck. That profile tab is a remnant from the Windows NT days. Avoid it!
Comment: Simple.  Use Samba.  Setting up a \\server\username share is trivial.
Answer: The actual answer to your question

Given a file structure for User accounts of \file-server\students\grad-year\user-home-folder
is it possible to create shares of \file-server\user-name

To answer your actual question, yes you can create one file share per student folder, and it will be mapped as \\file-server\user1 for user1's folder, but maintaining that many shares is crazy talk. The ADUC profile tab will not do this for you. You will have to script it or do it manually.
You can map subdirectories of a share if you need to, so if you map all users' home folders to H:\ you can just map H:\ for User1 as \\file-server\students\User1 if you follow my advice below, even though the User1 folder itself isn't explicitly shared. This is a feature of file shares - you can map any subfolder directly, even if it isn't explicitly shared, as long as it is implicitly shared by virtue of a parent folder being shared.
Continue reading below for recommendations that will make your life infinitely easier.

How you should consider laying out your file server

I have about 2000 accounts to handle like this. So I'd like to find a way to automatically create true shares (like you'd create with Advanced Sharing...).

You don't want to have to maintain a separate share with separate share permissions for each user. That's lunacy. Have \\file-server\students shared with Everyone - Full Control in the share permissions and Authenticated Users - Read - This folder only in the NTFS permissions. Then, consider ditching the grad-year approach, as it only adds complexity and just have your hierarchy look like this:
-Students (NTFS Permissions: Authenticated Users - Read - This Folder Only | Administrators - Full Control | System - Full Control || Share Permissions: Authenticated Users - Full Control)
---User1 (NTFS Permissions: User1 - Modify | Administrators - Full Control | System - Full Control)
---User2 (NTFS Permissions: User2 - Modify | Administrators - Full Control | System - Full Control)

Trust me, I've dealt with this in many higher education environments. It becomes a huge PITA when you're doing anything other than \\file-server\students\user1 and just sharing it out at students. Unless you have tens of thousands of student folders, you're overcomplicating it.

Many shares v. one share
You say

I have a Mac/Windows mixed environment. The Macs work much better with a root level share.

I've dealt very heavily in OS X/Windows mixed environments with OS X consuming Windows SMB shares and I've never heard of what you're describing. I'm going to assume that you're doing something crazy with permissions or have some nasty environmental stuff in play here, since how deep the folder is shouldn't matter one bit. There's really no benefit to having every single folder shared out. Really, stick to sharing the root folder and use NTFS permissions properly.

Regarding the profiles tab in ADUC
You also say

I  can create the home folders in the users' directory in AD User Properties - Profile tab using \file-server\students\grad-year\%username%.

Don't use the profiles tab in ADUC! It's from the Windows NT days! It's there for backwards compatibility and should not be used. You should use GPO for your Windows clients and WGM/MCX on your Macs to map these shares.
Comment: To add as an opinion.  I'd ditch the grad year as well and create the student accounts as LastnameStudentID# to avoid conflicts over the years and have a policy in place to kill off or empty the student's folder either after graduation or every year after school is out.
Comment: This depends wholly on your provisioning process. Having the folder named directly after the user allows for `%username%` to be used in scripts and GPOs, which is very very handy. As long as your accont provisioning policy is to never duplicate a previously used account name, this shouldn't be an issue. But, as always, YMMV.


Why are notes on the harmonica laid out the way they are?

Question: This is a chart of a standard ten hole diatonic harmonica in the key of G that I copied from Wikipedia:

              1 2 3  4 5 6 7  8 9 10
       blow: |G|B|D |G|B|D|G |B|D|G |
       draw: |A|D|F#|A|C|E|F#|A|C|E |

As you can see, blowing in the first seven holes will produce a lower note than when drawing through that some hole. The last three holes produce the opposite effect. I personally find this confusing, and although I'm sure all you good harp players are used to this by now, I'm wondering why anyone would have set it up like this to begin with.
Answer: Actually it's the last 4 holes that produce the opposite effect you describe.  I will explain why the original harmonica engineer set it up this way.  First thing to note, is the harmonica was not originally intended to be an instrument used to play single notes.  Had that been the case, the holes would be farther apart.  Instead they are so close as to make it easy to play two or three or four notes simultaneously but very difficult to play single notes.  Since you can either blow or draw, it only makes sense to make the adjoining blow notes and draw notes harmonize with one another, thus limiting which notes can go on the draw side and which notes can go on the blow side.  A diatonic harmonica is designed to play all the notes in a single key.  There are seven notes in each key so the G harp needs the notes G A B C D E and F#.  It takes 3 notes to make a full chord so it only makes sense to have at least 3 notes on either the blow side or draw side.  So the original mouth harp engineer set up the G harp such that no matter where you blow on it, if you blow any 3 notes you will be blowing a G a B and a D - the 3 notes of a G chord.  So no matter which 3 holes you blow into on a G harp, you are blowing a G chord (possibly an inversion but a G chord nonetheless).  Pretty cool.  Engineered so that you can't possibly blow anything but a G chord no matter how hard you try.  So if there are 3 of the notes in the scale on the blow side, the other 4 must be on the draw side.  If there are ten holes, it is impossible to line up a repeating string of 4 notes on one side with a repeating string of 3 notes on the other so they simply don't line up.  To make them line up would mean leaving out a note in the scale.  On the draw side on a G Harp we have A D   F# A C E  F# A C E  - a logical progression but unfortunately as noted above, they can't line up evenly with the repeating G B D pattern on the blow side.
Using A D & F# on the draw side of the first four holes allow you to play the V chord (D maj)in the key of G.  Drawing hole 3 4 and 5 (F# A C) gives you the 7 diminished chord in the key of G (F# dim) and drawing holes 4 5 and 6 or 8 9 and 10 give you the 2nd Minor (Am) of G.  The center position puts all 7 notes in the G scale together starting with the blow on hole 4 (G) then draw hole 4 (A) Blow hole 5 (B) Draw hole 5 (C) and so on through the F#.  There is not a way to play a true C chord (the IV chord in G) but you can approximate the C chord by drawing C and E in hole 9 and 10 and then immediately blowing the G on hole ten (one of the two holes that you can reliably hit a single note on). Given the logistics of how far apart the notes can be on the same hole and the need to create a harmonious series of adjoining blow and draw notes and given that there are an odd number of notes (7) and even number of holes (10 - so the we can start and end on the root note) and in an attempt to include the ability to play as many chords in the key as possible, there is no better more logical way to arrange the notes.  It would be set up differently if the harmonica was designed primarily for single note playing as is a trumpet and there was no provision for playing two or three notes at a time like a chord.  Hope that makes some sense.
Comment: You are absolutely right about the fact that folks who practice and have acrobatic tongues have been able to master single note riffs and tunes. (I gave your comment a +1.)  But I'm not sure whoever made the first harmonica envisioned this.  So original intent and creative adaptation may be different things here. Just like whoever invented the 6 string guitar probably never intended for it to be played with a glass or brass slide.  Yet creative folks found new ways to use the instrument.
Comment: @user6591 Nice and symmetrical yes - but no way to play a D chord which is the most important chord in the key of G other than the G chord.  So the D in the draw row is essential for playing in the key of G.
Comment: +1 for the theory behind it all. However, there are plenty of players who manage to get single note tunes - Larry Adler, Toots, Stevie Wonder come to mind. It's what your tongue's for! All harmonicas and blues harps have approx. the same hole spacings and blow/suck arrangement, including the chromatics. The 'suck' chord ends up as a dominant ninth without the root when all the holes are employed.
Comment: @Rockin my problem with this theory is that it ignores the repeated note found at the second hole draw and third hole blow. One we can repeat a note, we can put the notes in any combination to match seven tones to eight holes. Also, imagine this blow :G|B|D |G|B|D|G |B|D|G| draw: |F#|A|C|E|A|C|F#|A|C|E|. Now its all nice and symmetrical.
Answer: A harmonica is set up, well, "harmonically".  That would be rather tricky to reconcile when changing blow/draw orientation (man, it's worth having a bellows instrument just in order to be able to talk about push/pull instead) across octave changes.  Now an octave has seven notes.  If you are not going to change blow/draw when switching octaves, you have three notes on the blow as compared to four notes on the draw, at least in the part of the harmonica where you still have the full scale available.
And for accommodating a reasonable amount of songs, having two melodically useful octaves does not seem excessive.  The lowest notes are only for accompaniment: there the selection is a bit different, fitting harmony better than melody.
In other words: how else would you have done that?
Comment: It's the same arrangement for melodeons. Accordions have the same notes on the blow and draw.
Comment: Pretty sure it's the same arrangement for accordions, too.
Answer: The build of an instrument is dictated by the scales and tunings common in its culture or genre. These provide the 'target' towards which builders innovate.
In the case of the harmonica, innovation has been recent and conscious: an attempt to ease playability in various genres, facilitated by manufacturing advances.
In this sense, rather than trying to understand the instrument, listen to music from the genre it was built for, and what emotion or 'groove' players are trying to express.
The blues harp, for example, is a simple instrument built around the blues scale. If you understand this scale and are familiar with the blues 'groove', the layout of the instrument is more or less self-explanatory. Trust your ear, and all else will follow.
Orchestral or jazz harmonicas, on the other hand, are built around the notion of free play in any scale ('chromatic' harmonicas), leading to additional complexity - and challenges. High amongst these are the issues of coordination and breathing control, and, if with other classical players, reading music.
One of the more recent harmonica innovations are the 'Irish' harmonicas of Brendan Power. In themselves a simple advance, but vastly easing fast, rhythmic play in 'modal' Irish tunings.
That said, there are many types of harmonica. If nagged by the buying itch, rather than first looking for a harmonica, perhaps choose a musical genre that appeals, then look for the matching instrument..
Who knows. Maybe you'll discover an unexplored niche (Balkan? Chinese? Arabic?) in the world of harmonica design. ;-)
Trust. Your. Ear.
Postscript: for folk or traditional players, reading music is in many senses unnecessary ballast (and very few folk virtuosos can read a score). Try instead to play along with a slowed tune (using VLC or one of the many other audio/video tools), using an instrument of your own in the correct tuning (if necessary, ask another player for help getting this set up). You may be pleasantly surprised how quickly things fall into place.
A couple of weeks learning by ear and you will be playing your first tunes independently, and will have begun to develop the 'tunings intuition' that helps you hook up with others in a jam.
Try, on the other hand, to learn to read music and you'll be busy for the next year or two, but will have picked up little of the tension, speed and dynamics of the original recording. You may also have missed an opening in a local band..


How to Avoid Copying whole Values of a vector to the other container

Question: How do I avoid copying whole values of vector kws into req_kws (the vector of vectors) below, while keeping two containers kws and req_kws in my code?
 vector<vector<string>> req_kws;
 for (string& request : requests) {
    vector<string>& kws = req_kws.back(); //<-- define &kws to empty req_kws
    kws = split(kwsStr, ",");   //split is a parsing function upon string kwsStr
    req_kws.push_back(kws);
 }

I used in line number 3
vector<string>& kws = req_kws.back();

In this way, instead of storing all values of kws vector, only its reference is stored into req_kws.
But, I am getting a segmentation fault during the runtime.  Is there a way to fix it?
Thank you for your help.
Additional note;
Please note my constraint stated above that I need to keep both line number 4 (kws) and 5 (req_kws) intact, and want to use line number 3 of reference (&) or something similar to save the execution time from the same values being stored to both kws and req_kws. I have the other parts of the codes with the same problem, which are more complicate so that I can Not simply combine two lines of 4 and 5 into one.
Additional Question (Similar problem):
Thank you for your solution down below.  However, how about the following case, which is similar as above but more complicated.
vector<unordered_map<string, string>> ads_kwsBids;
for (const auto& kwBid : kwsBids) {
    …
    unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back(); //to prevent from being whole container copied
    for (unsigned j = 0; j < nsize; j++) {
        unsigned jdx = 2 * j;
        kwsBidsMap[splitedStr[jdx]] = splitedStr[jdx + 1];// constructing map kwsBidsMap
    }
    ads_kwsBids.push_back(kwsBidsMap);
}

In line number 4, that is,
unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back();

Because of the reference &, it yields the segmentation fault.  But, the reference is also the one that prevents kwsBidMap from being copied into ads_kwsBids.  Is there a way still to use the reference & on kwsBidMap and not get the segmentation fault?
Comment: As far as i can see in your code, req_kws is empty, calling "back" method on empty vector will produce undefined behavior.
Comment: You are right that the segmentation fault is caused by calling req_kws being empty.  However, is there a way to avoid the runtime failure?  Please note my contraint that I need to keep both line number 4 (kws) and 5 (req_kws) intact, and want to use line number 3 of reference (&) or something similar to save the execution time from the same values being stored to both kws and req_kws.
Answer: In the code shown, req_kws is an empty vector.  Calling back() on an empty vector is Undefined Behavior. You either need to add an element to the vector first, or rewrite the code to not depend on having a value present.
From what I can gather you are trying to do, I think a simple
req_kws.push_back(split(request, ","));

should suffice.
Alternatively, you can rewrite the loop as
for (string& request : requests) {
    req_kws.push_back(split(request, ","));
    vector<string>& kws = req_kws.back();
}

This will split the request string, store it in the req_kws vector, then create the kws reference to that newly added element.  Depending on what else you do with it, you may need to add req_kws.reserve(requests.size()); before the for loop to avoid reallocations when adding to the vector.
Comment: Thank you for your answer.  I raised a similar yet slightly more complicated question by editing the above.  Would you take a look at it?
Answer: This is my version of the solution to the problem.
vector<unordered_map<string, string>> ads_kwsBids;
for (const auto& kwBid : kwsBids) {
    …
    //Initialize the container with default value.
    ads_kwsBids.push_back(unordered_map<string, string>());
    //& used to prevent from being whole container copyed
    unordered_map<string, string>& kwsBidsMap = ads_kwsBids.back();
    for (unsigned j = 0; j < nsize; j++) {
        unsigned jdx = 2 * j;
        //Put kwsBids into a hash map
        kwsBidsMap[splitedStr[jdx]] = splitedStr[jdx + 1];// constructing map kwsBidsMap
    }
}


how to copy file to system folder in batch

Question: i want to copy a file to system32 folder using a batch file. but when i try to do this it says "Access denied" i also can not copy anything to my C:\ drive also. i tried using xcopy and copy to do this. i don't know what is the parameter to get the administrator permission. so, can anyone help me?
program:
@echo off
xcopy abc.dll "C:\Windows\System32\" -y
pause

output:
D:abc.dll
Access denied
Press any key to continue . . .

Comment: You are doing something that is not permitted for security reasons. Why are you trying to do it?
Answer: Should be doable one of two ways.
The first is to make a shortcut to your batch file, right click -> properties and on the Shortcut tab of the properties, click the Advanced button to find a checkable "run as admin" option.
The second (NOT TESTED) is to add a bunch of stuff to the top of your batch file (Reference) - I don't want to include it in the answer because I have not tested it.
Comment: You can't run a shortcut as admin unless you have admin permission to run as admin
Comment: I tested the second way. It works great on Windows 10.
Answer: @echo off
copy /Y abc.dll "C:\Windows\System32\"
pause

right click the batch file and run as administrator
and make sure the abc.dll is in the same folder as your batch file.
hope this helps.


Ativar HOVER sem clicar na mesma div

Question: Seguinte, eu tenho 2 tabelas, os itens da segunda tabela tem hover.
Preciso passar o mouse em 1 item da primeira tabela e ela ativar o hover do item respectivo da tabela 2, mas não posso puxar o mesmo id ou classe porque não quero puxar efeitos pra table 1, quero só ativar os efeitos do hover na table 2.
Cada tabela tem entre 8 e 32 dados, 1 = 1,  2 = 2, cada vez que passar o mouse no item 1 da primeira tabela, ativa o hover no item 1 da tabela 2

        #
        Posição do Pneu
        Pressão Atual
        Temperatura Atual
        Status

           <input id="sampleButtonDiv" type="button" value="2">

Comment: algum problema em usar jQuery por exemplo? Se pode user, é super facil...
Comment: Pode colocar o código completo das duas tabelas? E como o @balexandre mencionou, o uso de javascript vai facilitar bastante o seu problema. Se você tem duas tabelas, e quer que o hover nos filhos de uma altere o estados dos filhos da outra, CSS sozinho não resolve
Answer: Olha só, descobri que somente com CSS não dá, mas tem como fazer com JavaScript:

jQuery(function($) {
  $('.table-trigger tr')
    .on('mouseenter', function() {
      console.log(this);

     $('.'+$(this).attr('id'), '.table-trigger-target')
        .addClass('hover')
    })
    .on('mouseleave', function() {
        $('.'+$(this).attr('id'), '.table-trigger-target')
          .removeClass('hover')
    })
});
table#tabela1 tr:hover {
  background: #000;
  color: #fff;
  font-weight: 700;
}
#tabela1 tr:hover{
  cursor: pointer;
}

.table-trigger-target tr.hover{
  background: gold;
}

    Elemento1

    Elemento2

    Elemento3

    ReferenciaElemento1

    REferenciaElemento3

    ReferenciaElemento2

    REferenciaElemento3

JSFIDDLE
Comment: Ótimo exemplo, mas cabe destacar que você está utilizando jQuery e não JS puro. +1
Comment: É! Valeu pela edição, @PedroCamaraJunior

Ativar HOVER sem clicar na mesma div