How can I require that browscap.ini / get_browser() is functioning before allow a my module to be installed?

Question: I have a module for my Drupal 7.x installation which needs browscap.ini / get_browser().
The module works perfectly, but I want to make sure the browscap.ini is installed before installing of enabling the module. That way the module will not work unless browscap is installed correctly.
How can I do this?
Comment: What is the name of the module that needs it?
Comment: Name of the module is: aserv_support. It's a self made module. I know it needs to be in the .install file, but I have no idea how.
Comment: Please post some code so we can debug better
Comment: Maybe I'm not understanding, but why don't you just declare a dependency on whichever module (browsecap) you need?
Answer: I fixed it using the following code:
<code>/**
 * Implementation of hook_requirements().
 *
 */
function aserv_support_requirements($phase) {
  $requirements = [];

  if ($phase == 'install' || $phase == 'runtime') {

    if (!get_cfg_var('browscap')) {
      $requirements['aserv_support'] = [
        'title'    => t('Browscap not installed'),
        'value'    => 'Browscap has not be installed. Please install Browscap before enabling this module.',
        'severity' => REQUIREMENT_ERROR,
      ];
    }
  }

  return $requirements;
}

/**
 *  Implementation of hook_enable()
 */
function aserv_support_enable() {
  if (!get_cfg_var('browscap')) {
    drupal_set_message(t('ERROR Enabling Aserv_Support: Browscap has not be installed. Please install Browscap before enabling this module.'), 'error');
    module_disable(['aserv_support']);
  }
}
</code>
Comment: You should keep in mind that there is a browscap drupal module, requiring a PHP module only when there is also a standard PHP version isn't a good idea. It would be better to require either one.


For all records in a table how to guarantee at least one record on a foreign key related table?

Question: Assume that there are two tables in a database. First one is X, second one is Y. Y table has a foreignkey on X table. So, if there is a record on Y table, it's foreignkey related column value must exist on X table. This is the default behavior.
   X         Y
-------   -------
  ID        ID
            XID <--- Foreignkey to X table.

Now, for all records in X table i want to guarantee that there must be at least one record on Y table. If there isn't, it should add one automatically. How can i do this?
Comment: Well you are setting up a foreign key in Y table from X. So each record you enter into Y table will have `XID` isn't it? (given that foreign key can't be null) So what's the issue? I assume you meant to say **"Now, for all records in Y table i want to guarantee that there must be at least one record on X table. If there isn't, it should add one automatically."**
Comment: I think i can't explain what i want. Think that there is a book, and i want to guarantee that there must be at least one page. Assume that book and page are tables in database.
Answer: To insert missed records into Y for existing data you can run something like
INSERT INTO Y(xid)
SELECT x.id
FROM x
WHERE NOT EXISTS(SELECT NULL FROM Y a WHERE a.xid = x.id);

To prevent such things in the future, write a procedure which inserts data in 2 tables, and prevent everyone from inserting data into tables directly (only through this procedure)
Answer: There are two different issues here.

Managing declarative constraints.
Managing inserts, updates, and deletes.

The "normal" way to guarantee a row exists in y for every row in x is to include foreign keys in both tables. Each table references the other.
create table x (
  x_id integer primary key,
  y_id integer not null
);

create table y (
  y_id integer primary key,
  x_id integer not null references x (x_id)
);

alter table x
add constraint one_to_one
foreign key (y_id)
  references y (y_id) deferrable initially deferred;

begin transaction;
insert into x values (1, 100);
insert into y values (100, 1);
commit;

Although this guarantees that every "x" has a "y", so to speak, it doesn't guarantee that every "x" has a different "y", or that every "x" has its own "y". I'm not sure whether that's your requirement.
This isn't quite what you're looking for, because you have a 1:N relationship between your two tables. You could make it work, but I think you'd have to write a trigger to manage changes to table "y". For example, if the user deletes from "y" the row that "x" holds a foreign key reference to, you'd need to update "x" to reference a different row in "y".
But this leads to the second issue: managing inserts, updates, and deletes. There are several ways to do that.

The client is responsible for providing all the statements necessary to keep the database consistent. (With the possible exception of that foreign key problem above, which might better be handled in a trigger on "y".)
Clients have no direct access to base tables. All changes are through stored procedures.
Clients have no direct access to base tables. All changes are through updatable views.

Stored procedures and updatable views can give you some degree of automatically adding a row in "y", but you have to write procedural code to do it.
Comment: Thanks for the answer. Storedprocs is the best approach as i see.


Find all function such that $f(x)-f(y) = (x -y)g(\sqrt{xy})$

Question: Find all functions $f, g$ that satisfy the functional equation
$$
f(x)-f(y)= (x -y)g(\sqrt{xy}) \quad \forall\ x,y>0.
$$
Comment: try it yourself
Comment: Try to obtain an equation that only involves $g$.
Comment: I do it and i have this equation: (x^2-1)g(x)-(y^2-1)g(y)=(x^2-y^2)g(xy).If  F(x)=(x^2-1)g(x) then we have the equation: ((X^2)*(y^2)-1)(F(x)-F(y))=(x^2-y^2)F(xy). I can't find any solution.Can you help me?
Answer: Hint: First fix $y=1$, this shows what $f$ has to be, in terms of $g$. Then fix another $y$ as well.
Comment: I do it and i have this equation: (x^2-1)g(x)-(y^2-1)g(y)=(x^2-y^2)g(xy).If F(x)=(x^2-1)g(x) then we have the equation: ((X^2)*(y^2)-1)(F(x)-F(y))=(x^2-y^2)F(xy). I can't find any solution.Can you help me
Answer: Since the functional equation is
 $\;f(x)-f(y)= (x -y)g(\sqrt{xy})\;\;\forall x,y>0\;$ we can write it as
 $\;g(x) = (f(x t)-f(x/t))/(x t-x/t).\;$ Assuming that $f(x):=\sum_{n=0}^\infty c_nx^n\;$ then the equation is
$$g(x)=c_1+c_2x(1/t+t)+c_3x^2(1/t^2+1+t^2)+c_4x^3(1/t^3+1/t+t+t^3)+\cdots.$$
The coefficients of $g(x)$ must be constants, so $\;c_n=0\;$ for all $n>1.$ Now $f(x)=c_0+c_1x.$


Why does this char not show the default char methods in the IDE?

Question: I am developing in Visual Studio 08 in the C# language, I am trying to loop over each char in a String after it has been converted to a char[]. The problem is that the IDE/C# does not acknowledge that my char is really a char, this picture explain it a little better.

As you can see on the left, the variable aChar which is of type char (presumably) does not show the same methods as what char. does on the right. Is there anything noticeably wrong with how I am trying to loop over the chars in the searchString?
Comment: Take a look [here](http://msdn.microsoft.com/en-us/library/system.char.aspx). The methods marked with an `S` are static and will be visible from the `char` struct name, but not from an instance of `char`. The one's without the `S` are visible from an instance of `char` but not the struct name itself.
Answer: The methods you see with char. are static methods and available with type name like char.ConvertFromUtf32.
Your variable aChar will only show instance methods.
As a side note: You don't have to call ToCharArray in foreach
foreach(char aChar in searchString)

is enough
Comment: @AnotherUser, you also don't have to call `ToCharArray` in foreach, `foreach(char aChar in searchString)` is enough
Comment: @Habib just wave your hands and say "I was talking about the IL; at the IL level, char is a class"
Comment: Ahhh... Wow, sometimes I surprise myself. `char.IsLetter(aChar)` is how to do it.
Comment: Splitting hairs, but `char` is a struct not a class.
Comment: @MattBurland, yes :) type name should have been there instead of class name
Answer: On the left, all methods are instance methods (for your aChar variable). On the right, the methods you see are class (char) static methods.
Answer: On the left, you are looking at member variables only since you're doing a dot operator on an instance of char. On the right, you're looking at static methods, since you're using the dot operator on a class.


How to enter in jazz theory

Question: I am self-learned amateur guitar player and I play for quite long time (around 10 years) and not playing jazz/blues bad but I feel not progressing for a very long time.
The reason is that I have no idea about theory of music like intervals, chord progressions etc.
My question is : How to enter to jazz theory ? Because there are lots of sources that are not accessible for me. Where can I start learning jazz theory by myself ?
Comment: Welcome to the site Optimal Control! Have you studied any music theory before? Jazz and Classical theory start with the same basics - understanding chord structures, harmonic tendencies etc.
Comment: Unfortunately no, I have never studied music theory before. Thanks for your comment :)
Answer: Basic classical theory is fairly easy to get into and uses almost the same exact building block that jazz theory uses. Most jazz theory classes someone would take require a basic music theory class as a prerequisite.
There are many sources to get you started in classical theory including MusicTheory.net's lessons which if you can learn and understand them you could dive into more intensive theory books that are geared towards jazz theory.
Comment: And Jazz theory developed out of and within a classical theory world. If you're just starting, get the basics of all western music first, then expand it with the area you're interested in.
Answer: To understand the theories that are used in jazz, it helps a LOT to first understand the basics, which are contained in what is known as classical theory. In order to appreciate altered chords and scales, it's easier when the original ones are known - the alterations start to make sense then! So start with basics, then branch out once they are known.
Answer: In short, I would recommend increased exposure, learning to play specific songs by ear, and having a reference book.
There are always a few different ways to go about learning a new style.  One of the more important things is to listen to that style as much as possible.  This will ingrain the feel of the style.  You can learn a lot of theory from books but that will only get you so far.  I have a whole lot of Classical theory (went to school for it) but my writing sounds nothing like it because I have not focused on it and don't listen overly frequently.  With that theory I could certainly write closer to that idiom but it takes a lot more thought to be able to.  Real point being that the more you listen to it, the more it becomes a part of your style.
The best way to further that sort of learning is to transcribe as much as you can.  By learning to play what the greats did, it really sinks into your hands.  It's also a much more involved way of listening.  It takes you from hearing and feeling, to knowing what notes and rhythms are typically used within the idiom that actually create that feel.
That being said, Jazz theory, while rooted in the same concepts as Classical, is fairly unique.  There are a lot of the rules of Classical music that are (somewhat by necessity) completely abandoned, voice leading for example.  So having a reference to the theory can be very helpful.  There are many books on Jazz theory but the one I am most familiar with and is used in the academic community is Mark Levine's 'Jazz Theory Book'.  I learned a great deal from it, personally.  A book can be very helpful to provide some insight to things like Extensions and Alterations, which you don't see a whole lot of outside Jazz, though they certainly do exist.
To best learn any style of music, you should try to fully immerse yourself.  Allow it to take over your musical world for a while.  You can still take some breaks to listen to or play other music but try to keep that to a minimum for a while.  I'd say that after a few weeks to a month of full immersion that it would be a good idea to kind of step away from it for a few days, then fully immerse again.  That will allow your brain a break and to get back in touch with other styles that you have enjoyed.  Then when you return to the Jazz studies you may find increased desire and a new outlook/perspective on the music itself and how to best replicate it.  Basically no matter what you are doing, it is always best to give yourself some breaks because it will actually improve your learning ability.
Lastly, even though it sounds like it may not be an option for you, I would very much recommend getting a teacher.  A good teacher can recognize what you are doing poorly and what steps to take next for the best approach to learning.
Answer: I would probably just be the contrarian here but I do not think there really is such a thing as 'Jazz Theory' as much as there is 'Baroque Theory' or 'Romantic Theory'
A proper understanding of the core principles of music theory and history opens the door up to any style you may want to pursue.
Comment: While I understand where you're coming from and partially agree, the mind set of someone who writes jazz is different then a standard classical and while the building blocks are typically the same there are different tools, methods, and ideas used that classical theory does not cover.
Answer: As everyone here has already said, the fundamentals are fundamentals.  Whether you choose jazz, pop, or hip hop, if you really want to be a better musician and understand music as a language, you must know the fundamentals.
"What are the fundamentals?"  Well, the Theory 1 class of Hunter music school defines the fundamentals as the following in their syllabus (see the full syllabus below for a more "classical" approach, i.e, counterpoint):
"Review of music fundamentals, including notation; treble and bass clefs; pitches
and their registers; durations and rests; simple and compound intervals; major and
minor scales; introduction to modal scales; simple and compound meters; triads;
and seventh chords."
Syllabus here
So basically, you should know all of those in order for you to "branch off" and focus on jazz.  Truthfully, you will also probably need to know some of the basic harmonic progressions as well in order to fully understand tonality (Dominant->Tonic, most core example).  Once you know these things, you will be able to effectively learn "jazz theory", which is based off of all this.
With that said, I imagine that most if not all "jazz theory" books out there will include all of the above and teach it to you before moving on to the jazz specific stuff.
Answer: how many lives do you have at your disposal?
In case you have only one and you are no more a student (students have or should have a lot of time, that's the point), my suggestion is to start from a Real Book. You'll start playing the pieces with very simple chords on your left hand and single notes on the right side: at the beginning they will sound quite similar to popular songs...not exactly jazzy. But quite soon you will fall in love with those "odd" symbols that go far beyond major and minor.
What you need as a baseline: how to stack up note to build major, minor and diminished chords according to classical theory (the simplest!), knowledge of the intervals. A "blues" pentatonic scale to start playing (or jocking!) with notes will help you to get more fun from the beginning both in minor and major chords as soon as you'll start improvising.
This recipe worked great with me: if you are curious and interested you'll find out dozens of things and quite soon you will become a jazz enthusiast.
Last but not least: listen, listen, listen. As soon as you become familiar with harmony, try to write down the pieces that you like more. One of the best practice, in my opinion, is applying this exercise to very slow and well-known ballads as they are played by famous [jazz] artists: you'll find out how many chords they add (!!) and how the piece still sounds familiar despite of this! Oh, it's great.
My best wishes
p.s.: few months ago I bought "Jazz Piano" by Mark Levine. It's really useful in case you have a lot of time to spend regularly on piano (at least one hour per day...just a dream for me). Intervals and chords are at the very beginning....

How to enter in jazz theory


smooth scroll to last tab in android horizontalscrollview

Question: I have eight tabs at bottom in the layout with horizontal scrollview.
Now what i want is at the start of that activity, i want to scroll whole tabs to last tab smoothly. so how can it be possible to scroll smoothly first tab to last tab in horizontal scrollview.
This is my layout file:
<HorizontalScrollView
    android:id="@+id/horizontalScrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:fadingEdge="none"
    android:overScrollMode="never"
    android:scrollbars="none" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="@drawable/divider_tab" />

</HorizontalScrollView>

I have tried few codes like:
final HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.horizontalScrollView);
sv.post(new Runnable() {
    public void run() {
        sv.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
    }
});

please help me to make this animation or scroll possible.
Answer: I have also made 9 tabs in my activity at the bottom of the screen.And I can scroll through all the tabs very smoothly.Try the below code in you XML:
<?xml version="1.0" encoding="utf-8"?>

<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="2dip"
            android:background="#696969" />

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dip"
                android:layout_marginRight="0dip" />
        </HorizontalScrollView>

    </LinearLayout>
</TabHost>

Hope it helps..


Get Translated Field Label for Entity

Question: I have a field I have translated. But I can not figure out how to get that translated field label programmatically. I've found a few posts on here, but none of them work for me.
Pretty easy to get the default field label:
<code>$fieldDefinition = $model->get($field)->getFieldDefinition();
$fieldLabel = $fieldDefinition->getLabel();
</code>
Does anyone know a way to get that in 2022?
I thought the answer might lie in here somewhere, but so far no luck. Just trying to grab the spanish translation right now...
<code>$language_manager = \Drupal::languageManager();

$language = $language_manager->getLanguage('es');
$original_language = $language_manager->getConfigOverrideLanguage();
$language_manager->setConfigOverrideLanguage($language);
</code>
Any help would be great.
Answer: Config translation works in the background as override. So you don't need to do anything.
Unless have a very specific use cases, like sending an email in a different language. Then you can change the config override language, like the code you've shown so far, and reset it after you've sent the email:
<code>use Drupal\Core\Field\Entity\BaseFieldOverride;
use Drupal\field\Entity\FieldConfig;

...

$language_manager = \Drupal::languageManager();

$language = $language_manager->getLanguage('es');
$original_language = $language_manager->getConfigOverrideLanguage();
$language_manager->setConfigOverrideLanguage($language);

// load a new field definition object instead of referencing the one stored in the entity
// in case of a translated base field:
$field_definition = BaseFieldOverride::loadByName($entity->getEntityTypeId(), $entity->bundle(), $field_name);
// in case of a translated configured field:
$field_definition = FieldConfig::loadByName($entity->getEntityTypeId(), $entity->bundle(), $field_name);

$field_label = $field_definition->getLabel();

$language_manager->setConfigOverrideLanguage($original_language);
</code>
Comment: Yeah, I'm creating a spec chart component. So that's created with code, and not just a rendered field. Something must not be clicking. The code I have doesn't get the translated field label. This `$fieldDefinition->getLabel()` is always the same - english. I wish it was easy like `$fieldDefinition->getTranslation('es')->getLabel()` but obviously that doesn't work.
Comment: Are you sure you have a translation stored in the config? See this topic how to get and set language overrides on a lower level: https://drupal.stackexchange.com/questions/282995/how-to-get-translated-field-storage-config. It could also help to export the config and check the config names and the language overrides (exported to sub directories).
Comment: I do see it in when I export the config. It's in there. But still, no matter what I do, it's in english. My `$fieldDefinition` which is `Drupal\Core\Field\Entity\BaseFieldOverride` always shows the `langcode  = "en"`. I just don't know where my disconnect is or what I'm not understanding. I really appreciate the help. I keep thinking something is going to click. It's super easy getting the field value though `$model->getTranslation($lang)->get($field)->getString()`.
Comment: Yes, this is a bit confusing. When loading a config with a language override the langcode is still the original language of the config object while the config values inside of the object are translated.
Comment: The field definition you get from the entity seems to be cached in memory. I edit the answer how to load the object in a different way.

Get Translated Field Label for Entity


Multiple IP on same NIC : when could be useful?

Question: I've been in a office where each workstation(Windows XP) have configured two static IP Address on the same NIC one for net : 192.168.3.0 and another for accessing net : 192.168.200.0 .
Since the IP address for net 192.168.200.0 is given only for accessing an Asterisk VoIP Server that has ip address : 192.168.200.125.
After seeing this type of configuration, i have some doubt ... it's not better adding a server with multiple ip address configured and then set a static route on the default gateway of the main network ?
Can achieve better performance with multiple IP Address or with a static route on default gateway?
When multiple IP Address on single NIC is a better choice ?
Answer: Multiple addresses on a single NIC is primarily used when you have multiple logical networks on a single physicle network. For example, Your primary workstations use 192.168.200.0/24 You have phones and a couple of workstations which should never talk to the world. Those you give addresses in 192.168.3.0/24. Now, your fileserver has an address of 192.168.200.253, these workstations need to access the file server. You could send them to your default gw, which will turn around and route them back to the file server, causing the packets to hit your network twice, or you can add 192.168.3.253 to your file server, allowing the local only systems to talk to it directly. and still letting you block all traffic not coming from 192.168.200.0/24 on your router. Make sense?
Comment: +1 for a good explanation, even though I think you got your subnets the wrong way around according to the OP's information.
Comment: yeah, looks like I did swap them, the basic concept is the same though.
Answer: Richard has given you a good answer for a reason in favour of multiple IP addresses per workstation. However, you should consider the overhead this introduces, as now each workstation has to have static IP addresses, which have to be configured individually and manually. As soon as you get to something like 50 workstations, this can become a real chore.
So, if your network is growing or already large, DHCP assigned IP addresses are the way to go. And for servers/services that shouldn't be accessible from the outside, create a DMZ with its own firewall and add some routes.
Answer: I would not recommend putting multiple IP addresses on a single NIC for multiple workstations in an organization. On a server there are many reasons for doing so: Hosting multiple websites and domains, bridging between two networks, etc. etc. For workstations, however, we want to keep the network configuration as simple as possible because there are more of these to maintain than servers and routers, and because we want end devices like workstations to be flexible and for infrastructure pieces like network and servers to be more stable and static (as a rule of thumb). If, as you say, there is only one Asterisk server justifying the workstations having accessibility to the second network, then I believe that it would be more appropriate to tackle the related security issues from the server device side rather than the workstation side. Specifically, the Asterisk VoIP server sounds like a great candidate for accessibility via a Firewall with NAT. It can keep its own network via NAT and be restricted to only your workstation traffic via the Firewall (assuming that there is a compelling reason to keep it on its own network).
Comment: The proposed configuration is adding multiple IPs to the server's NIC. There is no mention of doing as you have detailed for any workstation.
Comment: Your rational of keeping the workstations simple is right in line with wolfgangsz. Where if the focus of the identified overall configuration is to secure the network, then all workstations (as much as possible) should default to that protected state/posture and not have to require specific out-of-band configurations. If those specific workstations are to be more "heightened" security-wise, then additional configuration to obscure and/or further protect them is a good/prudent position.
Comment: His question starts with "I've been in a office where each workstation(Windows XP) have configured two static IP Address on the same NIC one for net : 192.168.3.0 and another for accessing net : 192.168.200.0 ." which implied to me that he's in an environment where the workstations already have multiple IPs configured on their single NICs.
Comment: "it's not better adding a server with multiple ip address configured and then set a static route on the default gateway of the main network ?" "edited 4 hours ago" it's getting edited along the way...


Python Pandas read_csv(): Incorectly loaded csv

Question: according to the Pandas documentation, pandas.read_csv (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) should support detection of bad lines though error_bad_lines and warn_bad_lines set to True.
So I have created a csv with bad format called test.csv:
aaa,bbb,ccc
ssdf,sdtf,aesrt,,,,
eart,erate
aert,aert,aert

and run read_csv:
>>> pd.read_csv('test.csv', error_bad_lines = True )
                      aaa  bbb  ccc
ssdf sdtf  aesrt NaN  NaN  NaN  NaN
eart erate NaN   NaN  NaN  NaN  NaN

As I understand the documentation, this should raise an Error, except it doesn't. Instead bad csv is loaded. Pandas seems to ignore all of error_bad_lines / warn_bad_lines.
Is my understanding of the documentation wrong, or is it really a bug in Pandas? Does anyone know of elegant work-around how to load only correct csv?
I'm working with Python 3.6.8, Pandas 0.25.0 and Ubuntu 18.04.
Answer: I made some tests and found that the second line will determine the number of columns to be expected in the rest of the file.
for example, the second line (ssdf,sdtf,aesrt,,,,) has 7 columns. So if all the following rows have less than 7 columns, then no errors!
If you modify one row to be 7 or more, then it will crash. The default value for error_bad_lines is true, so you don't need to specify it explicitly.
Example without an error :
data.csv :
0,jjjjjj
1,er,ate,, # 5 columns
2,bb,b
3,sdtf,aesrt,ll,sdfd # 5 columns, so no errors appear.
4,erate,
5,aert,aert

df1 = pd.read_csv('data.csv')
df1

Result : No error
0   jjjjjj
1   er  ate NaN NaN
2   bb  b   NaN NaN
3   sdtf    aesrt   ll  sdfd
4   erate   NaN NaN NaN
5   aert    aert    NaN NaN

Example with an error :
data.csv :
0,jjjjjj
1,er,ate,, # 5 columns
2,bb,b
3,sdtf,aesrt,ll,sdfd,sdf,sdf,sdf,sdf, # more than 5 columns
4,erate,
5,aert,aert

df1 = pd.read_csv('data.csv')
df1

Result : error !!
ParserError: Error tokenizing data. C error: Expected 5 fields in line 4, saw 10

Comment: @Michal, Yes, the error only occurred when the number of columns is more than the second line. I didn't find any documentation yet talking about that.
Comment: Indeed your are right, I really did not expected number of columns to be set by the second row, not the header (or first line in general). Also as I understand it now, this check doesn't apply when having less columns than in the second row?


How do I hide static media file URLs?

Question: I have developed a website in Drupal 7. Right now I have a requirement: A page should display a PDF file (already generated). Only authenticated users should have access to view or download this file, but anyone with direct access to this static file link can view it and download it.
Is there any method I can use to prevent this and redirect them to the login page? What kind of logical programming needs to be applied in this case?
Comment: You could use the private file system to store the file, and an approach like the R4032login module for the redirect
Comment: can you please help me understand in more detail ?
Comment: Here's a good start [File system settings](https://www.drupal.org/node/15368).
Answer: As @Clive and @prkos mentioned in comments above, Drupal has different stream wrappers for public and private file systems:
https://www.drupal.org/node/15368
I know you are using Drupal 7, but the Drupal 8 docs on the topic mention:

In Drupal 8, you can no longer set private file system via UI. You set it in your settings.php file.

So you might find it convenient that you can configure this in the Drupal 7 admin UI ( "Private file system path" under admin/config/media/file-system) without any edits to your site's codebase.
If you have configured the private stream wrapper correctly, you can prevent anonymous users from downloading those files and instead respond to their attempts with an HTTP error 403.
The remaining desired functionality is provided by the community-contributed module that @Clive mentioned:
https://www.drupal.org/project/r4032login
The module is available for Drupal 7, 8, and 9. Its project page will explain its usage, but basically it redirects users to the login page when they ask to access a restricted resource, and redirects them to their intended destination once they log in successfully.
Comment: your guidance worked. Thank you. Thing I noticed is if I create private folder inside sites/default/public/private, it never gonna work. Also I used anonymous_login ( https://www.drupal.org/project/anonymous_login ) which worked perfectly. Thank You !
Comment: Glad to hear that my answer was helpful! Please accept it by clicking on the green check mark. Otherwise, this answered question will continue to show up in lists of unanswered questions.

How do I hide static media file URLs?


Windows Server 2003 used as a Spam Relay

Question: We have a server running Windows Server 2003 and Matrix Control panel. We are continually used to relay spam, which fills the badmail folder and gets us blacklisted. The bad mail folder filled the c: drive last night and rendered the entire server unusable.
Matrix control panel generally sits on top of the windows services but for SMTP it uses its own service which seems extremely limited in config options.
The spammers are using one particular domain to bounce emails from, and the username part of the email address' that they are using is randomly generated so its not like they have a password for one of the genuine accounts.
What I would like to know is:
How are they able to send spam without a valid username and password?
Can I stop them?
Can I stop Bad Mails being saved on WinServer2003?
We are in the process of upgrading this ancient server but we need it to work for a few more weeks while the new one is prepared.
Thanks
Comment: Q: How are they able to send spam without a valid username and password? A: Your server is an open relay. Q: Can I stop them? A: Yes you can. Q: Can I stop Bad Mails being saved on WinServer2003? A: I believe so. Try setting the registry entries described in this article: http://support.microsoft.com/kb/884068
Comment: The registry entries should probably work. They're specific to the badmail folder of the SMTP service, not to Exchange.
Comment: Do you need to actually accept incoming email at all?  You should be able to adjust your firewall to permit outgoing messages, but not accept anything.
Comment: I saw that support article but unfortunately for me this server is not running exchange. This Matrix panel has its own noddy email server which I think is the route of the problem
Comment: @Zoredache Unfortunely yes, we lease space on the server to customers, and part of that lease includes some email addresses that match their web domain. Unless there is something that I'm missing I need to let them send and receive mail through our server
Answer: Probally your server accepts mail relay.
You should only allow mail relay from within your own domain...
http://support.microsoft.com/kb/324958/
(I really hope for you, that the person who is installing your new exchange server can help you with this, otherwise I'd think twice to let him do it...)
Comment: Well its me setting up the new server, so its on my head if this problem carries on lol.
Answer: "Possibly not the answer/an answer, but way too long/formatted for a comment"
I have no idea if this is the "Matrix Control Panel" you mean, but if it is see here: Matrix Control Panel Software Guide and is the Mail settings for SMTP Relay Status set to Enabled (Authenticated)?
Per the guide:

SMTP Relay Status: Should normally be set to allow local domains to
relay mail through the server.
Disabled: Stops SMTP traffic
Enabled (local domains only) : Will allow only mailboxes hosted on the server
to send emails
Enabled (Authenticated) : Is a more secure option for
your server as customers will also have to provide their mailbox
username and password to send email through your server.

I'm not sure what the software is for overall, but it would appear that you need to look at these settings and make sure they are setup correctly for your environment.
Comment: If the one I posted isn't it, then I would suggest contacting the company that made the software for support.  But as far as open relays go, the simplest answer is to disable SMTP relay unless you have LOB machines or similar that need to send without a real client software and human interaction (like Outlook/webmail/etc.)
Comment: Is Fasthosts the vendor/OEM?  Can they help?  Honestly, the steps to secure an open relay on any server (if required to do so) is really just to work on things like requiring authentication, only accepting email with valid from addresses, possibly locking down the SMTP server to only allow send connections from specific IPs or subnets (like internal only), etc.  You'll need to start by locking the software down as much as possible for your environment and then going from there.
Comment: If you have come across Plesk control panel before, its like that but worse. When I started working here about a month ago it was set to open, I changed to authenticated and thought that would be the end of it but we were hit again last night
Comment: Sorry, yes the one that you posted is the right one and those are the quotes from the doc that I have here. Trouble is that there is hardle any trace of these people on net
Answer: Turns out that Matrix uses port 25 and the default SMTP server was running on port 26 and that was relaying all of the spam. Shut that down and the problem has gone away.
Thanks to everyone who offered their useful advice


How to set permission for exposed filter in Views block

Question: I have a View with several blocks or displays. In one of these displays I have added the filter "Published" and made it exposed, so that user can switch between published and unpublished content.
Now I only want users with the administrator role to be able to see this filter, but I cannot figure out how to do this.
Can anyone give me a hint?
Thanks in advance
Answer: If you expose the filter as a block from within the view (Advanced - exposed form in block) then you could set the permissions on the exposed form block in the block system to Admin role users. Alternatively I can only think that you might need to use hook_form_alter to amend the permissions on that form if you want everyone others to see the view but not the exposed form.
Comment: Hello and thanks for your answer. The option 'Exposed form in block' requires the page display, and is not available for the block display. My view consists of 6 different blocks. There has to be a solution, but I still haven't found it.
Answer: I post the answer myself in case anyone is having the same problem. The solution was to use views-view--display_name.tpl.php and simply add a check if the user is admin or not for the exposed item... like this:
<?php global $user; ?>
<?php if (in_array('administrator', $user->roles)):?>
  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>
<?php endif; ?>


Graph theory cycle problems

Question: Question background: In each of the pictures below; there are line segments connecting black dots (7 line segments in the left picture and 12 line segments in the right picture).

Question asks to find out of "it's possible to draw a closed (cycle) continuous line that crosses each of these line segments exactly once; whilst staying inside the dashed rectangle".
My understanding of this question...
My understanding is that it's asking to treat each "region" as a vertex & then try to go through / over each existing line segment (once) until I return to the same region / vertex (if possible).
Comment: See, the graph in this case lies not within the black dots and lines, but rather in the space between them
Comment: If that comment seems too cryptic: I think what is being asked is wheter you can draw a line that **crosses** each of the segments (a segment here consists of two black dots at each end and a continuous line between them) exactly once and loops around. So in essence the vertices are the white polygons and the edges are the boundaries between them
Comment: You're not using any of the lines, you are drawing a new line and expected to cross each of the existing lines. Converting this into a more natural "path" is the crux of the solution.
Comment: Not using any of dashed lines, yes? Biggest problem is actually translating the presentation of these graphs.
Comment: Wait, it's not asking to trace over the existing edges; it's asking to use a region as a starting vertex & move over each existing line segment to see if I can return to the same region / vertex after crossing over each black line segment, yes?
Answer: Guide:
After you construct the graph by treating each region as a vertex and construct an edge between them for each line they share as boundary, the question is asking if there is an eulerian cycle.
An undirected graph has an Eulerian cycle if and only if every vertex has even degree, and all of its vertices with nonzero degree belong to a single connected component.
Comment: Correct. I finished this a few hours ago. The graph on the left doesn't have an Euler cycle (two vertices with odd degree of 3) & the graph on the right does have an Euler cycle.

Graph theory cycle problems


perl subroutine reference

Question: I have a set of fields with each field having different set of validation rules.
I have placed the subroutine reference for validating a hash-ref.
Currently its in my constructor, but I want to take it out of my constructor in a private sub.
I have done it as below
sub new {
my $class = shift;
my $self  = {@_};

$class = (ref($class)) ? ref $class : $class;
bless($self, $class);

$self->{Validations} = {
  Field1 => {name => sub{$self->checkField1(@_);},args => [qw(a b c)]}
  Field2 => {name => sub{$self->checkField2(@_);},args => {key1, val1}}
..
..
..
..
};

return $self;
}

Now I want to take out all this validation rules out of my constructor and want to do some thing like below, so that I have some better control over my validation rules based on types fields.(Say some rules are common in one set of fields and I can overwrite rules for other rules just by overwriting the values of fields.)
bless($self, $class);

  $self->{Validations} = $self->_getValidation($self->{type});

  return $self;
}
sub _getValidation{
     my ($self,$type) = @_;
     my $validation = {
     Field1  => {name => sub {$self->checkField1(@_);}, args => {key1 => val1}},};

     return $validation;
}

But I am getting Can't use string ("") as a subroutine ref while "strict refs" in use at... Can anybody tell me why is this behavior with sub ref. If I check my name key, its coming to be null or sub {DUMMY};
Comment: One more thing to add here, I have done it `Field1 => {name => sub{$self->checkField1(@_);}` this way as sometime, I have to validate individual fields also, and thought of calling individual field rules too like `$obj->checkField1('string',@args);` If there is a better way am ready to change my approach
Comment: Funny thing happened here, it works without any issue, actually, I defined the Keys starting Field1 and first field generated was Field0 :-( .. But this question is still open for any better approach.
Comment: Are the Validations actually different per-object that you're putting them in an attribute, or are you only doing it to capture `$self`? Because you don't need to...
Comment: @Hobbs, for current scenario, I have two files with say 50 and 60 fields respectively in each row. I have to validate each field for different set of rules. Based on type 1 or type 2 files, I am going to make my validation hash then apply rules on each field sequentially in a loop. while same fields also occur in other part of app too(but not all fields at a time). I was thinking to use same subroutines(which ever is applicable say 5 out of 60). That's why I was trying to keep it attached to object, I am not sure if this approach is going to give me any benefit or loss.
Answer: It looks to me like you are getting close to reinventing Moose poorly.  Consider using Moose instead of building something similar, but less useful.
The error message means that you are passing in a string in a place where your code expects a code reference.  Get a stack trace to figure out where the error is coming from.
You can do this by using Carp::Always, overriding the $SIG{__DIE__} handler to generate a stack trace, or inserting a Carp::confess into your code.
Here's a sigdie solution, stick this in your code where it will run before your module initialization:
$SIG{__DIE__} = sub { Carp::confess(@_) };

You may need to put it in a BEGIN block.
I'd really like to discourage you from taking this approach to building objects.  You happily bless any random crap passed in to the constructor as part of your object!  You blithely reach into your object internals.  Field validation rules *do not belong in the constructor--they belong in the attribute mutators.
If you must use a DIY object, clean up your practices:
# Here's a bunch of validators.
# I set them up so that each attribute supports:
#   Multiple validators per attribute
#   Distinct error message per attribute
my %VALIDATORS = (

    some_attribute  => [
        [ sub { 'foo1' }, 'Foo 1 is bad thing' ],
        [ sub { 'foo2' }, 'Foo 2 is bad thing' ],
        [ sub { 'foo3' }, 'Foo 3 is bad thing' ],
    ],
    other_attribute => [ [ sub { 'bar' }, 'Bar is bad thing' ] ],

);

sub new {
    my $class = shift;  # Get the invocant
    my %args = @_;      # Get named arguments

    # Do NOT make this a clone method as well

    my $self = {};
    bless $class, $self;

    # Initialize the object;
    for my $arg ( keys %args ) {

        # Make sure we have a sane error message on a bad argument.
        croak "Bogus argument $arg not allowed in $class\n"
            unless $class->can( $arg );

        $self->$arg( $args{$arg} );
    }

    return $self;
}

# Here's an example getter/setter method combined in one.
# You may prefer to separate get and set behavior.

sub some_attribute {
    my $self = shift;

    if( @_ ){
        my $val = shift;

        # Do any validation for the field
        $_->[0]->($val) or croak $_->[1]
            for @{ $VALIDATORS{some_attribute} || [] };

        $self->{some_attribute} = $val;
    }

    return $self->{some_attribute};

}

All this code is very nice, but you have to repeat your attribute code for every attribute.  This means a lot of error-prone boilerplate code.  You can get around this issue by learning to use closures or string eval to dynamically create your methods, or you can use one of Perl's many class generation libraries such as Class::Accessor, Class::Struct, Accessor::Tiny and so forth.
Or you can learn [Moose][3].  Moose is the new(ish) object library that has been taking over Perl OOP practice.  It provides a powerful set of features and dramatically reduces boilerplate over classical Perl OOP:
use Moose;

type 'Foo'
    => as 'Int'
    => where {
        $_ > 23 and $_ < 42
    }
    => message 'Monkeys flew out my butt';

has 'some_attribute' => (
    is  => 'rw',
    isa => 'Foo',
);

Comment: thanks daotoad, I am dying to use moose, but I can not use it in this project due to some crappy unavoidable constraints :-( ...
Answer: I haven't read everything you had, but this struck me:
sub new {
    my $class = shift;
    my $self  = {@_};

    $class = (ref($class)) ? ref $class : $class;
    bless($self, $class);

Normally, when you create a new object, the user doesn't pass $self as one of the objects. That's what you're creating.
You usually see something like this:
sub new {
    my $class = shift;   #Contains the class
    my %params = @_;     #What other parameters used

    my $self = {};       #You're creating the $self object as a reference to something
    foreach my $param (keys (%params)) {
       $self->{$param} = $params{$param};
    }

    bless ($self, $class)  #Class is provided. You don't have to check for it.
    return $self    #This is the object you created.
}

Now, $self doesn't have to be a reference to a hash as in the above example. It could be a reference to an array. Or maybe to a function. But, it's usually a reference. The main point, is that the user doesn't pass in $self because that's getting created by your new subroutine.
Nor, do you have to check the value of $class since that's given when the new subroutine is called.
If you want to do your verification in a private class (an excellent idea, by the way), you can do so after the bless:
sub new {
    my $class = shift;   #Contains the class
    my %params = @_;     #What other parameters used

    my $self = {};       #You're creating the $self object as a reference to something
    foreach my $param (keys (%params)) {
       $self->{$param} = $params{$param};
    }

    bless ($self, $class)  #Class is provided. You don't have to check for it.

    #Now you can run your verifications since you've blessed the object created
    if (not $self->_validate_parameters()) {
       croak qq(Invalid parameters passed in class $class);
    }
    return $self    #This is the object you created.
}

Comment: Thanks for correcting me. But here the requirement is more about fetching a set of rules based on one parameter type. say for id type is ladies, i want to use different validation rules and for Gents a separate set of validation rules.

perl subroutine reference


SgmlLinkExtractor and regular expression for match word in a string

Question: I'm using the SgmlLinkExtractor functionality in scrapy to parse specific urls.
I override start_requests function to crawl dynamic url.
this looks like:
start_requests(self):
.....
yield Requests(url.strip(), callbackA)
Callback A does nothing right now.
I also implemented process_value for the SgmlLinkExtractor but it never called.
This is the rule I'm using:
rules = [Rule(SgmlLinkExtractor(allow=()), callback=callbackB, follow=True),]
Again callbackB never called.
Comment: Welcome to Stack Overflow! Can you explain what you've tried so far?
Comment: This is what I want to achieve:
I want to scan all a and href tags in a site and do some logic to determine rather to jump to that URL.
The logic is as follows:
search if the link or the link description contain career | job (not case sensitive)
if so create a link to parse it. - the link may contain ../ so need to get rid of them.
Comment: okay, but what regular expression have you tried building already? Has your bot worked? If not, what error message did you get? Can you post a (small, very minimal!) example of input you want to parse and your expected output?
Comment: I don't have the regular expression.
my idea was to use SgmlLinkExtractor and to allow all link and pass
a callback function for process_value that will do all logic.
what do you think?
Comment: sorry, you're right, I misread.  However, you should post some code that you've tried so far and examples of input and output (such it's actually possible to do with scrapy). That's the best way to get help on SO.
Comment: see base question for clarifications
Answer: If your callbacks are declared in your spider, then they will not have global scope and you need to reference them as scoped to your class with self.:
rules = [
  Rule(SgmlLinkExtractor(), callback=self.callbackB, follow=True),
]


Linking slideshow thumbnail to slideshow views content

Question: I have a view containing pictures from a content type "Slideshow". When I click the Slideshow title in a view containing the slideshows, it takes me to the slides from that slideshow. However, I want to get rid of the title and be able to click the picture instead of the title so I can do the same thing. Could you please tell me how I could do that?
Comment: Are you using Views Slideshow or just Views to create a list of the "Slideshow" nodes?
Comment: Views to create a list of Slideshow nodes.
Answer: You will earn time by coding a small hook_block() that calls your JavaScript plugin for your slideshows. Then, you will be able to configure easily your module and your link.
Views can be really harmful when you try to do things like slideshows.
Just pick a jQuery plugin from the ones listed on 13 Super Useful jQuery Content Slider Scripts and Tutorials and the rest of the job will be easy.
Comment: But it surely can be done without writing code. I mean, it just needs to be linked to the parent node ID, but I don't know how to do that. I did have a normal table with objects whose names I linked to each of the objects details through NID. Something similar should be doable here as well, right?
Answer: If I understand your problem correctly you should be able to go to your view, edit the image field (the one that shows the Slideshow thumbnail), find the heading 'Link image to' and change it from the default 'Nothing' to 'Content'.


Calculation of $\int \frac{ A_0 + A_1\cos{(a_1x)} + A_2\cos{(a_2x)} }{ [ B_0 + B_1\cos{(a_1x)} + B_2\cos{(a_2x)} ]^2 } dx $

Question: Consider the integral
$$
I=
\int \frac{ A_0 + A_1\cos{(a_1x)} + A_2\cos{(a_2x)} }{  \big[ B_0 + B_1\cos{(a_1x)} + B_2\cos{(a_2x)} \big]^2  } dx
$$
where the constants $A_0,A_1,A_2,B_0,B_1,B_2,a_1,a_2$ are nonzero.
I have been trying to come up with a way to solve the integral without any success.
Since the integral originates from an engineering problem, I have worked through an approximate solution that performs fine for the problem, but I was wondering if
$I$ can be directly evaluated.
$\textbf{My attempt :}$
One can rewrite the integral as :
$$
\int \frac{ A_0 + A_1\cos{(a_1x)} + A_2\cos{(a_2x)} }{  \big[ B_0 + \delta f(x) \big]^2  } dx
$$
With the substitution $\delta f(x) \rightarrow \epsilon \cdot \delta f(x)$, one can expand the fraction with respect to $\epsilon$ in Taylor series up to a desired order. In the expanded quantity, I substitute back
$$
\delta f(x) = B_1\cos{(a_1x)} + B_2\cos{(a_2x)}
$$
Then the integral can be evaluated quite easily.
Thank you for your time.
$\textbf{Edit :}$ The constants $a_1$, $a_2$ must not be considered as rationals.
Comment: Probably a closed form exists for each particular case where $\frac{a_2}{a_1}$ is rational, but even the case $\frac{a_2}{a_1} = 2$ is pretty unpleasant, even after scaling to assume w.l.o.g., e.g., $A_0 = B_0 = a_1 = 1$.
Answer: One shouldn't expect a closed-form solution for general values of the parameters, but if $\frac{a_2}{a_1} $ is rational, say, then we can make a change of variable that rationalizes the integrand, whence we can in principle write antiderivative more or less explicitly.
In that case, scaling the variable $x$ of integration by an appropriate factor lets us rewrite the integral as a constant multiple of
$$\int \frac{A_0 + A_1 \cos m u + A_2 \cos n u}{(B_0 + B_1 \cos m u + B_2 \cos n u)^2} \,du$$ for some integers $m, n$, or just as well as
$$\int \frac{A_0 + A_1 T_m(\cos u) + A_2 T_n(\cos u)}{[B_0 + B_1 T_m(\cos u) + B_2 T_n(\cos u)]^2},$$
where $T_\ell(v)$ denotes the $\ell$th Chebyshev polynomial of the first kind. Applying the tangent half-angle substitution $u = 2 \arctan t$, $du = \frac{2 \,dt}{1 + t^2}$ then transforms the integral to one with a rational integrand, after which the usual techniques for integrating rational functions can be applied:
$$\int \frac{A_0' + A_1' T_m\left(\frac{1 - t^2}{1 + t^2}\right) + A_2' T_n\left(\frac{1 - t^2}{1 + t^2}\right)}{\left[B_0' + B_1' T_m\left(\frac{1 - t^2}{1 + t^2}\right) + B_2' T_n\left(\frac{1 - t^2}{1 + t^2}\right)\right]^2 (1 + t^2)} \,dt .$$ But after simplifying the denominator has degree $4 \max\{|m|, |n|\}$, making the function difficult generally unpleasant to integrate for all but the smallest values of $m, n$.
The special case $a_1 = a_2$ (so, $m = n = 1$ in the above) is manageable: By scaling and relabeling may as well write the integral as a constant multiple of
$$\int \frac{A_0 + A_1 \cos u}{(B_0' + B_1' \cos u)^2} \,du .$$
The tangent half-angle substitution transforms it to
$$2 \int \frac{(A_0 - A_1) t^2 + (A_0 + A_1)}{[(B_0 - B_1) t^2 + (B_0 + B_1)]^2} \,dt,$$
and writing $A_\pm := A_0 \pm A_1$, $B_\pm := B_0 \pm B_1$, (and provided $B_- \neq 0$) decomposing using partial fractions gives
$$2 \int \left(\frac{A_-}{B_-} \frac{1}{B_- t^2 + B_+} + \frac{A_+ B_- - A_- B_+}{B_-} \frac{1}{(B_- t^2 + B_+)^2}\right) \,dt .$$
The form of the antiderivative depends on the sign of $\frac{B_+}{B_-}$.
Comment: Travis Willse, I thank you for your answer, but the problem is that both $a_1$ and $a_2$ are irrational in general. I've made appropriate edit in the question.
Comment: @MichaelGaitanas In the case covered in my answer, $a_1$ and $a_2$ can themselves be irrational---what matters is that the ratio $a_2 / a_1$ is rational. Like I wrote in my answer, if that ratio *isn't* rational, finding a closed-form expression for the antiderivative is probably hopeless.
Comment: Travis Willse, unfortunately, the ratio $a_2/a_1$ as well cannot be assumed to be rational...


How to remove duplicate values from datatable SQL

Question: Getting values duplicate:
╔══════╦══════╦═══════╦════════════╦═════════╦═════════╦══════╦═══════╗
║ ID   ║ Name ║ Class ║ Date       ║ Intime  ║ Outtime ║ INAM ║ OUTPM ║
╠══════╬══════╬═══════╬════════════╬═════════╬═════════╬══════╬═══════╣
║ 1001 ║ Paul ║ 1st   ║ 29-11-2022 ║ Holiday ║ Holiday ║ H    ║ H     ║
╠══════╬══════╬═══════╬════════════╬═════════╬═════════╬══════╬═══════╣
║ 1001 ║ Paul ║ 1st   ║ 29-11-2022 ║ Holiday ║ Holiday ║ H    ║ H     ║
╠══════╬══════╬═══════╬════════════╬═════════╬═════════╬══════╬═══════╣
║ 1001 ║ Paul ║ 1st   ║ 29-11-2022 ║ Holiday ║ Holiday ║ H    ║ H     ║
╚══════╩══════╩═══════╩════════════╩═════════╩═════════╩══════╩═══════╝

Code:
SELECT DISTINCT COALESCE(tt.ID,t1.ID) AS ID,
          COALESCE(tt.Name,t1.Name) AS Name,
          COALESCE(tt.Class,t1.Class) AS Class,tt.Date,
          COALESCE(tt.Intime,t1.Intime) AS Intime,
          COALESCE(tt.Outtime,t1.Outtime) AS Outtime,
          COALESCE(tt.INAM,t1.INAM) AS INAM,
          COALESCE(tt.OUTPM,t1.OUTPM) AS OUTPM
FROM stuattrecordAMPM AS t1
CROSS JOIN (SELECT * FROM stuattrecordAMPM  UNION ALL
            SELECT null,null,null,Date,Holiday_Name,Holiday_Name,Status,Status FROM HolidayList) AS tt
            order by [ID]
            DELETE FROM stuattrecordAMPM
WHERE Date IS NULL

In this code I'm getting duplicate values. How to avoid duplicates from datatable?
Comment: Please provide a [mre] and specify which DBMS you're using.
Comment: With `SELECT DISTINCT` you will not get any duplicated _rows_.
Comment: I'm using vb.net 2022 SQL
Comment: Your sample code and output results don't match. A `SELECT DISTINCT` would eliminate all the duplicates. Post sample input data that reproduces the issue when used with the posted sample code.
Answer: You can give a row number to each row grouped by all the columns, then delete the rows having row number greater than 1.
Query
with cte as(
  select *, row_number() over(
    partition by [id], [name], [class], [date], [intime], [outtime], [inam], [outpm]
    order by [id]
  ) as [rn]
  from [your_table_name]
)
delete * from cte
where [rn] > 1;


My Bot is having trouble changing nicknames on my server

Question: My Discord Bot, made in nodeJS, sometimes changing the nickname, sometimes not. All other functions are working properly, however when someone sends the Modal. There is a chance that their nickname will be changed according to the button they selected, which is described in the code, but there is an even greater chance that the person's nickname will not be changed. I wanted to know if it's an error in the code, or in my server. Bot role is set to admin
Some parts of the code are in Portuguese(BR)
Code:
client.on('interactionCreate', async (interaction) =>
{
    try {
        if(interaction.isButton()) //Every Button Pressed
            if(interaction.customId == process.env.FIRST_ROLE)
            {
                const role = interaction.guild.roles.cache.get(process.env.FIRST_ROLE)

                if(!role) //a
                {
                    return;
                }

                //If the member has the role.
                //const interactionMember = interaction.guild.members.cache.get(interaction.user.id); //Member that interact

                //Modal Part
                const modal = new ModalBuilder(
                    {
                        customId: `rolePMSetModal-${interaction.user.id}`,
                        title: 'Informações',
                    });

                const nameInput = new TextInputBuilder(
                    {
                        customId: 'nameInput',
                        label: process.env.FIRST_INPUT_TEXT,
                        style: TextInputStyle.Short,
                    });

                const idInput = new TextInputBuilder(
                    {
                        customId: 'idInput',
                        label: process.env.SECOND_INPUT_TEXT,
                        style: TextInputStyle.Short,
                    });

                const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
                const secondActionRow =  new ActionRowBuilder().addComponents(idInput);
                const nameThatUserSelected = null;
                const idThatUserSelected = null;

                modal.addComponents(firstActionRow, secondActionRow);

                await interaction.showModal(modal)
            }

            if(interaction.customId == process.env.SECOND_ROLE) //Butoes De Selecionar Set
            {
                const role = interaction.guild.roles.cache.get(process.env.SECOND_ROLE)

                if(!role) //s
                {
                    return;
                }

                //If the member has the role.
                //const interactionMember = interaction.guild.members.cache.get(interaction.user.id); //Member that interact

                //Modal
                const modal = new ModalBuilder(
                    {
                        customId: `roleExercitoSetModal-${interaction.user.id}`,
                        title: 'Informações',
                    });

                const nameInput = new TextInputBuilder(
                    {
                        customId: 'nameInput',
                        label: process.env.FIRST_INPUT_TEXT,
                        style: TextInputStyle.Short,
                    });

                const idInput = new TextInputBuilder(
                    {
                        customId: 'idInput',
                        label: process.env.SECOND_INPUT_TEXT,
                        style: TextInputStyle.Short,
                    });

                const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
                const secondActionRow =  new ActionRowBuilder().addComponents(idInput);

                modal.addComponents(firstActionRow, secondActionRow);

                await interaction.showModal(modal)
            }

        if(interaction.isModalSubmit)
        {
            if(interaction.customId == `roleExercitoSetModal-${interaction.user.id}`)
            {
                const role = interaction.guild.roles.cache.get(process.env.SECOND_ROLE)
                const nameValue = interaction.fields.getTextInputValue('nameInput')
                const idValue = interaction.fields.getTextInputValue('idInput')
                if(Number.isInteger(idValue)) return;
                if(nameValue.length > 12) return;
                try {
                    interaction.guild.members.cache.get(interaction.user.id).setNickname(`[AL SD | EB] ${nameValue} | ${idValue}`).catch(error => {console.log('There is a error to change nickname!')});
                    interaction.member.roles.add(process.env.SECOND_ROLE);
                    interaction.member.roles.add(process.env.MAIN_ROLE);
                    interaction.guild.channels.cache.get(process.env.LOG_CHANNEL).send(`Usuario: ${interaction.user}, Selecionou Uma Guarnição...\nGuarnição: ${role}\nId: **${idValue}**\nNome: **${nameValue}**`); //Log
                    const replyMsg = interaction.reply("```Usuario Setado!```");
                    if(replyMsg){
                        interaction.deleteReply(replyMsg);
                    } else {
                        console.log('Nao foi possivel Deletar A Mensagem.')
                    }
                } catch (error) {
                    console.log(error);
                }
            }

            if(interaction.customId == `rolePMSetModal-${interaction.user.id}`)
            {
                const role = interaction.guild.roles.cache.get(process.env.FIRST_ROLE)
                const nameValue = interaction.fields.getTextInputValue('nameInput')
                const idValue = interaction.fields.getTextInputValue('idInput')
                if(Number.isInteger(idValue)) return;
                if(nameValue.length > 12) return;
                try {
                    interaction.guild.members.cache.get(interaction.user.id).displayName.se(`[ALN | PMA] ${nameValue} | ${idValue}`).catch(error => {console.log('There is a error to change nickname!')});
                    interaction.member.roles.add(process.env.FIRST_ROLE);
                    interaction.member.roles.add(process.env.MAIN_ROLE);
                    interaction.guild.channels.cache.get(process.env.LOG_CHANNEL).send(`Usuario: ${interaction.user}, Selecionou Uma Guarnição...\nGuarnição: ${role}\nId: **${idValue}**\nNome: **${nameValue}**`); //Log
                    const replyMsg = interaction.reply("```Usuario Setado!```");
                    if(replyMsg){
                        interaction.deleteReply(replyMsg);
                    } else {
                        console.log('Nao foi possivel Deletar A Mensagem.')
                    }
                } catch (error) {
                    console.log(error);
                }
            }
        }
    } catch (error) {
        console.log(error);
    }
})

I am looking to know what is the problem with the Bot
Comment: check the role hierarchy, maybe the user's role is higher than the bot's highest role, which disables the bot from changing their nickname
Answer: You can try using the <GuildMember>.manageable property to determine if you are able to manage this members nickname. Note this will return false if used on the bot.
https://old.discordjs.dev/#/docs/discord.js/main/class/GuildMember?scrollTo=manageable
https://github.com/discordjs/discord.js/blob/main/packages/discord.js/src/structures/GuildMember.js#L265


Does a set become a proper class with $AC$ (or vice versa)?

Question: I hope the following questions are not fundamentally stupid to raise.
Let A be a class term in the form of $ A = \{ x | \phi \}$.
Claim $1$: $A$ is a proper class in ZFC if and only if it is also a proper class in ZF.
As I try to prove this, this claim came up:
Claim $2$: Let $x$ and $y$ be sets. Then $x \neq y$ in ZF if and only if $x \neq y$ in ZFC.
Are these claims true? Any hints?
Thanks!
Answer: The statement you're trying to prove is false: let $\varphi(x)$ be the formula $$(AC\wedge x\not=x)\vee \neg AC.$$ From AC, it follows that $\varphi$ defines a set (namely $\emptyset$), while from $\neg$AC it follows that $\varphi$ defines a proper class (namely everything). In particular, ZFC proves that $\varphi$ defines a set, while ZF does not.
Meanwhile, in your claim 2, you conflate theories and models. A specific set isn't in a theory. Rather, what you need to talk about are formulas defining sets. Then, as above, the claim is false: let $\psi$ be the formula "is the empty set" and $\theta$ be the formula "is the emptyset if AC holds, and is $\omega$ otherwise".
Comment: Does ZF proves that this is a proper class?
Comment: @KonformistLiberal No, it does not. ZFC proves that it isn't, ZF+$\neg$AC proves that it is, and so ZF leaves it undecided.
Answer: There is a difference between "in ZF" and "in a model of ZF". And that difference is huge.
You can talk about definitions for sets, e.g. $\{x\mid x=\varnothing\land\sf AC\}$ is a definition which ZF proves to be a set, but it is empty if and only if the axiom of choice fails. On the other hand, $\varnothing$ is defined as $\{x\mid x\in x\}$, and ZF proves that it is always empty.
On the other hand, if $x$ and $y$ are two elements of $M$, a model of ZF, then they are equal if and only if they are equal in any larger or smaller model which knows both of them (and it is transitive with respect to $M$'s membership relation). So that much would be true.
Of course, since classes are in fact "formulas" interpreted in some model, it is easy to write a formula which defines a set in some models and a class in others: e.g. $\{x\mid x=x\land\sf AC\}$. Which is a proper class if and only if the axiom of choice holds.


Debugging Module Show PHP Errors

Question: I saw in a YouTube video someone had made a configuration where if there was a PHP bug in their module, upon cache rebuild it would show the error underneath the "The Website Encountered an Unexpected Error" screen.
I've been running dual screens monitoring the php error log - but would actually prefer to consolidate it into that one screen.  Where is that configuration option found?
Answer: You need add $config['system.logging']['error_level'] = 'verbose';
in file
sites/default/settings.php

or in {example}.com/admin/config/development/logging
you checked in All messages after click to Save configuration

Debugging Module Show PHP Errors


Using actix-web with HTTP2 support in Heroku

Question: I am trying to deploy one of the actix-web examples that offers HTTP/2 support in Heroku, after having slightly modified it to listen at the provided $PORT number, as well as the way in which certs are loaded -- rather than read from a file, it obtains the public and private key from the environment.
The problem is that, on each request, the Heroku router logs that the connection is closed without a response.
heroku[router]:
at=error
code=H13
desc="Connection closed without response"
method=GET
status=503
bytes=0
protocol=https

As it worked locally, I suspect the issue is at my dyno's configuration, which is a Hobby ($7/mo), especially at the certs section. As the application expects to receive the cert info from the environmental variables and having that Heroku does not provide you access to their certificates (e.g cert for xxxxx.herokuapp.com), I bought a domain name with the hopes of generating my own. I did, using the following page.
With a self-generated cert, I've tried so far the following, resulting in any of cases in the following errors:

To provide the same pair of keys to the dyno and application. The logs yield the error mentioned above.
Not to provide SSL configuration to the dyno, but to the application. Therefore, https access is disabled and the dyno is not even hit.
Not to provide certs configuration to the app, but to the dyno. The app crashes on boot time.

However, if I remove the related rustls lines, everything works smoothly, but the protocol used is HTTP/1.1.
Therefore, I'd like to kindly ask you:

Is there anything fundamentally bad about having the application expecting to load the certs?
Should I try other providers? (e.g DigitalOcean, AWS, Google Cloud)
Do you have any idea what might make it work in Heroku?
Answer: I've just found that Heroku does not support HTTP/2 at the time (source):

HTTP/2 is not currently supported on Heroku although this may change in future. You can find out about our currently supported HTTP protocols here: https://devcenter.heroku.com/articles/http-routing#http-versions-supported
For any future developments we recommend subscribing to the Heroku Changelog. This will let you know about updates, improvements and deprecations ahead of time so that you can make any necessary adjustments.
Comment: Unbelievable that they don't support HTTP/2 yet


Sending webpage through email

Question: I've implemented hook_menu and in page callback there is a function in my module which retrieves some records randomly and theme them with theme_table. Now I want a button on the page for sending this page exactly as it is to a predefined email address without refreshing the page because of randomly selected records.
I placed a button through simple HTML code but don't know how I can implement it's onClick function. Or is there any better way to do that? Thanks
Answer: It is simple javascript... The returned value can easilly be sent through ajax (there are good tutorials on sending mails with ajax).
<button onClick="alert(document.getElementsByTagName('body').innerHTML())" value="serialize">

You might run into trouble though, at first email clients can have trouble accessing images from remote locations (eg. from your own url). So you might have to attach them to the mail.
Also most email clients are very picky when it comes to css. They refuse to load a remote sytlesheet. You will have to hardcode all css classes in the respective elements, the old fashioned way... By using the object style attribute.

So as you see it is harder then just sending the HTML to an email receipient. In fact you might want to have a look at HTML2Canvas (or other alternatives) to make a 'screenshot' of a webpage and just send one image.
Comment: Note, in Drupal 7, a link with a CSS class 'use-ajax' ( perhaps themed like a button ) will submit via Ajax automatically.
Comment: @David, Can you please give me a simple example for how to do that via AJAX?
Comment: Add a class 'use-ajax' to the link. i.e `My callback`
Comment: OK, but I just found a module mimemail http://drupal.org/project/mimemail, which I think will solve my problem in an easy way. Please suggest?

Sending webpage through email


General Form of Reflections and Glide Reflections

Question: I am reading a set of notes about isometries of the plane. The section about reflections and glide reflections says that the general form for these isometries is:
$$x'=x\cos\alpha+y\sin\alpha+h$$
$$y'=x\sin\alpha-y\cos\alpha+k$$
But, the notes don't given any explanation of what $\alpha$, $h$, and $k$ are. These equations seem similar to a rotation, with some sign changes, but I'm not seeing how they are related. If anyone can help that would be wonderful.
Thanks
Answer: A reflection across a line through the origin making an angle of $\alpha/2$ with the horizontal axis is given by
$$ \begin{align*} x' = x \cos \alpha + y \sin \alpha \\y'=x \sin\alpha - y \cos\alpha\end{align*}$$
You can check this by verifying that the basis vectors $(1,0)$ and $(0,1)$ are mapped to their reflected selves: a reflection, being linear, is entirely determined by where the basis vectors are sent.
Then, the transformation
$$ \begin{align*} x' = x + h\\y'=y + k\end{align*}$$
where $h,k$ are real numbers, is simply a translation.
Since a glide reflection can be expressed as a reflection across a line through the origin followed by a translation, the claim follows.
Answer: The equations that you write actually define the composition of three isometries of the plane:

A rotation around the origin by an angle $\alpha$
A reflection about the rotated $X$-axis (flip the $y'$ coordinate)
A translation over a vector $(h,k).$
Answer: A glide reflection is defined as reflection in a line plus a translation along that line.
Let $l$ be the line passing through $P_0(x_0,y_0)$ with direction vector $v=(\cos\theta,\sin\theta)$. Then, a glide reflection in $l$ is
$$P'=2((P-P_0)\cdot v)v+2P_0-P\color{red}{+}cv$$
Explicitly,
$$x'=\cos\alpha\,x+\sin\alpha\,y+h$$
$$y'=\sin\alpha\,x-\cos\alpha\,y+k$$
where
$$\small h=2x_0\sin^2\theta-2y_0\cos\theta\sin\theta +c\cos\theta$$
$$\small k=-2x_0\sin\theta\cos\theta+2y_0\cos^2\theta +c\sin\theta$$
and $\alpha=2\theta.$


Number of anagrams of 'AABBCCDD' that have no repeated letters.

Question: I am seeking to find the number of anagrams of 'AABBCCDD' (that is strings with 2 A's, 2 B's, 2 C's and 2 D's). That have no repeated letters. So far my thoughts have been to find the total number of anagrams and subtract it from the number of anagrams that do have repeated letters. Now my calculation for the total number of anagrams for this eight letter string is:
$8! / 16$
I got this from taking the generic $8!$ number of anagrams for an eight letter string and dividing out by $(2! * 2! * 2! *2!)$ to account for the 4 letters that have repetition. I am stuck at this point because I am unsure how to count the number of anagrams that do have repeated letters.
Comment: Hint: Try Inclusion/Exclusion.
Answer: Hint: Try Inclusion/Exclusion.
To continue with your approach, let us count the "bad" strings.
First count how many strings have AA. Think of this as a single letter. The number of strings with AA is $\frac{7!}{2^3}$.
If we multiply by $4$, we get our first estimate of the number of bads, which is $4\cdot \frac{7!}{2^3}$. Note that it is wildly off. But it's a start.
However, $4\cdot \frac{7!}{2^3}$ double counts the bad strings that have, for example, an AA and a BB. Count these. There are $\frac{6!}{2^2}$ of them. There are $\binom{4}{2}$ ways of choosing two doubled letters, so our new estimate of the number of bads is $4\cdot \frac{7!}{2^3}-\binom{4}{2}\frac{6!}{2^2}$.
But we have subtracted too much, for we have subtracted one too many times the words that have three doubled letters. Continue, its almost over.


Only one month left, need help with establishing a preparation plan for these topics

Question: I am going back to school and preparing my first-semester course which is so-called "engineering maths". I used to be a physics major 5 years ago and had ok-ish knowledge in calculus, but now the part of my calculus brain is shiny as a piece of metal; I have forgotten 90% of it.
I have exactly a month left to prepare for it, but I am a bit confused about where to start and where are these topics lie in;
*Vector calculus, including Gauss' and Stokes' Theorems;
*sequences and series;
*Fourier series, Laplace transforms;
*systems of homogeneous ordinary differential equations, including phase plane and linearization for nonlinear systems;
*second-order partial differential equations and separation of variables.
Given only one month time, where is the best to start and what is the best materials for learning and practising? I am doing the single variable course from MIT, but it's taking too long and makes me want to hurry to vector calculus; ironically I worry about the sort of gap among these topics and a single variable. I know it is not realistic given a short period but at least I would want to study in a correct order that covers all the topic above.
I am both excited and worried about studying maths again because I want to do well instead of just passing with Bs as I did in undergraduate.
Thanks for reading and you're much appreciated!
Comment: sequences and series were covered in my single variable calculus class, is that not the case with MIT's course?
Answer: If you can find a copy of Engineering Mathematics by A.J.M. Spencer (and others) (Van Nostrand, 1977), don't hesitate to get it. It was my undergraduate text in my 3rd year of my elec. eng. degree course back in the early 1980s. It has everything you need, not just for your 1 month re-acquaintance with the material, but should be a constant companion over the rest of your course.
If it had not been for this book, I would have failed my exam on 2nd-order partial differential equations.
I recently got a second-hand copy of it, replacing the old one I had, and it is just as good as I remember it.
There may be newer (and hence more modern) books available nowadays, but I won't be able to comment on them.


capturar valor de outro input com jQuery

Question: Galera montei um sisteminha que ao digitar o nome do usuário em um input, o jQuery captura o nome e chama um arquivo php. Que por sua vez faz uma consulta no BD e preenche um select list.
Bom a estrutura esta assim:

function buscar_f_pagamento() {
  var id = $('#cliente').val();
  if (id) {
    var url = 'Busca/Casas.php?id=' + id;
    $.get(url, function(dataReturn) {
      $('#load_f_pagamento').html(dataReturn);
    });
  }
}
<input type='text' id='nome' name="nome" value='1'>

<input name="cliente" id="cliente" onchange="buscar_f_pagamento()">

<select name='casa' id="load_f_pagamento"></select>

Bom o que preciso fazer é quando eu chamar o buscar_f_pagamento no input cliente o valor que tem que ser passado no jQuery tem que ser o do input nome
Comment: da mesma forma que recebe o `$("#cliente").val()` você faz com `$("#nome").val()`
Comment: vlw muito obrigado deu certo ;)
Answer: Só alterar a linha
var id = $('#cliente').val();

Para
var id = $('#nome').val();

Não se esqueça de definir o type do seu input cliente.
Comment: vlw muito obrigado deu certo ;)


Hover effect with html5, no javascript or css

Question: I am trying to do a hover->highlight effect on the cells of the table in this fiddle, so they will appear to look like buttons.  I can't use any javascript or CSS, but I can use HTML5.  Does anyone know how to do it.  I know there is an onmouseover attribute in HTML5, just not much experience yet.
Thanks!
Comment: `onmouseover` is JavaScript. And why can't you use CSS?
Comment: They do, you just have to click 'Edit HTML' or something similar, then add `style="
Comment: That's not possible. Why can't you use CSS though?
Comment: The reason i can't use JS or CSS is that I am trying to make custom content for a website which i am trying to build on sites.google.com.  They do not allow you to add JS or CSS to the page.
Comment: @ShaquinTrifonoff Even then you cannot change pseudoclasses though – which you'd need to change the hover effect.
Comment: I just realized that - you can still insert a `
Comment: google sites does not allow inserting
Comment: Have you tried using the JavaScript `onmouseover` like this: [jsfiddle.net/JWhkn/](http://jsfiddle.net/JWhkn/)?
Comment: @ShaquinTrifonoff - that looks good, but it looks like google sites blocks that too.
Comment: I don't have a Google site (I use [000Webhost](http://000webhost.com) and hand code my site), so I can't test if `onmouseover` works. Have you tried `onmouseover` yourself?
Comment: I mean, i see it work on jsfiddle, I usually use jQuery for all hover effects.
Answer: You can't. If you want to change the appearance of a given element based on user's behavior you have to use JavaScript (event based) or the CSS pseudo class :hover.
However, if you can edit the HTML of your content, then you should be able to insert a custom


Making part of a triad chord sharper, but is it counted as minor?

Question: I'm confused about the transitioning from Major triad chord to Minor triad chord ("Triad Chord" means playing 3 notes/keys at once to form a chord)
So in band (Not those type of Rock Band,the one that is close to Orchestra) for example, to play concert C triad Chord, we play the 1st, 3rd and 5th in the Concert C Major scale.
Sometimes we play 2nd, 4th and 6th,then 3rd, 5th and 7th,then 4th, 6th and 8th. On some of these triad chords, my conductor told the one who is playing the middle note in the triad chord to go sharper by 15 cents (Indicated by the triangle in the tuner) so that it comes a "correct" minor chord. 2 questions here.

Q1: Which triad chord (Assuming in C Major Scale) is it and why?
Q2: In C Major Scale, the minor chord would be C,Eb and G. Instead, we played D,F and A but made F sharper by roughly 15 cents. Is this considered a minor chord? Why?

And apologies for calling it a "Triad Chord" instead of "Triadic Chord". I got used to that term.
Comment: Without getting into what a triad is or even what "triadic" means, this question could be stated much more simply along the lines of "Why does my conductor ask players to sharpen the thirds of minor chords by 15 cents?".
Comment: @ministic2001 You did not mention the instrument that was asked to change their pitch. With woodwinds and brass that rely on harmonics to achieve many notes, compensation is sometimes needed to bring the note in tune with the key being played in.
Answer: Well, regardless of whether you're used to it or not, "triad chord" is not the proper term and you should get used to something else. "Triadic chord" is slightly better, but you should really just call one of these chords a "triad."
There are four kinds of triad: major, minor, diminished and augmented. You don't need to refer to scales to talk about triads, just the distance between the three notes. If there are four half steps between the bottom two notes (e.g. C–E) and three half steps between the top two notes (e.g. E–G), it's a major triad. If you reverse that (3 half steps on bottom like C–Eb and 4 on top like Eb–G) then it's a minor triad. I won't worry about the other two triadic qualities for this answer, but you can look them up easily.
In your question, you were mostly talking about the triads that happen naturally when you use only the notes of the C major scale—these are called the "diatonic triads." Three of them will automatically be major: C–E–G, F–A–C, and G–B–D. In fact, in any major key, the triads that you can build on the first, fourth and fifth scale degrees will be major triads. In C major, three of the triads will naturally be minor: D–F–A, E–G–B and A–C–E. In fact, in any major key, the triads you can build on the second, third and sixth scale degrees will always be minor. (The chord built on the seventh scale degree, B–D–F in C major, will be diminished)
But to answer your question about tuning triads, it's easier to focus on a major and a minor triad with the same root. As you point out in your question, C–Eb–G would be a minor triad and C–E–G would be major. If you play these notes exactly as a standard tuner says they should be, the distance between the third of the minor triad (Eb) and the third of the major triad (E) is 100 cents, so micro tunings like you're talking about won't change the fundamental chord quality. The problem is that both minor and major triads tuned exactly according to the tuner (this is called equal temperament) don't sound as pure and powerful. This is because of something called the harmonic overtone series, and you can find tons of information here by searching for that term and the phrase "just intonation." You're right that raising the third of a minor triad by about 15 cents will make the minor triad more purely "in tune." However, it's just as important to lower the middle note of a major triad by 15 cents. So, to get a pure C major chord, you would play C–E–G with the E about 15 cents lower according to a tuner, and to play a C minor triad you would play C–Eb–G with the Eb about 15 cents higher. Although you're right that this makes the middle notes of the two triads closer together, it's not nearly enough to make the major triad become minor or vice versa. There's no set number, but I'd say you'd have to raise the third of a minor triad at least 60 cents before it starts truly sounding like a major triad. But the beauty of this is that you start to learn just how much range and nuance there is between notes that are supposedly "right next to each other."
Answer: To both it's still a minor triad. A minor chord is defined as a root, minor third, and perfect fifth which both chords have. The diffrence is the temperment. In just intonation, the minor third is about 15 cents higher than the equal temperment minor third. This is a good explanation  9f how the minor chords differ with temperment.


Leitura de Arquivo txt incorreta

Question: Bom estou lendo a seguinte informação de um txt
0016009993|GuilhermeLima|Azul|4|21|basico+completo|6

após ler estou separando os conteudos usando os delimitadores "|" para separar em memos, com o código abaixo.
  begin
    Linha.Delimiter:='|';
    Linha.DelimitedText:=Texto[i];
    cod:=Linha.Strings[0];
    nome:=Linha.Strings[1];
    cor:=Linha.Strings[2];
    codv := linha.strings[3];
    idadade:=Linha.Strings[4];
    tipo:=Linha.Strings[5];
    id:=Linha.Strings[6];
    try
      memo1.lines.add(cod);
      memo2.lines.add(nome);
      memo3.lines.add(cor);
      memo7.Lines.Add(codv);
      memo4.Lines.Add(idade);
      memo5.Lines.Add(tipo);
      memo6.Lines.Add(id);
    except
      ShowMessage('Erro!!! A base de dados não está no padrão correto!');

Até ai tudo bem, porem se no txt estiver dessa maneira
0016009993|Guilherme Lima|Azul|4|21|basico+completo|6

(um espaço no nome, o que seria o correto)
os valores vão errados para os memos, por que isso ocorre?
Answer: Se estivesse utilizando uma versão atual do Delphi poderia utilizar o Linha.StrictDelimiter, porém no delphi7 não é possível.
Como alternativa, você pode fazer dessa forma:
linha.DelimitedText := '"' + StringReplace(Texto[i], linha.Delimiter, '"' + linha.Delimiter + '"', [rfReplaceAll]) + '"';

Fizeram essa pergunta parecida no SOEn, acredito que a resposta serve para seu caso.
Comment: Linha.StrictDelimiter := True;

resolveu o meu problema.
Comment: Qual a versão do seu delphi?
Answer: tive um problema parecido, porem utilizo outra forma e te recomendo utilizar o procedimento split
procedure Split(const Delimiter: Char;Input: string; const Strings: TStrings);
begin
Assert(Assigned(Strings)) ;
Strings.Clear;
Strings.Delimiter       := Delimiter;
strings.StrictDelimiter := True;
Strings.DelimitedText   := Input;
end;

deixando o "StrictDelimiter" como true ele ignora os espaços em branco e só separa a variavel com o caracter informado.
chame da seguinte forma:
Split([caracter de referencia],[variavel de origem], [stringlist que irá receber os valores]);

ou seja irá chamar o split da seguinte forma:
Split('|', '0016009993|GuilhermeLima|Azul|4|21|basico+completo|6', Linha);

e como dica, como vc esta repassando os valores para diferentes memos, nao salve em variaveis, faça um FOR ou um WHILE que leia a stringlist ate o final e já salve o valor no memo, vai dar uma agilizada no seu trabalho.
E se precisar utilizar este valor posteriormente pegue direto do memo.
espero ter ajudado!

Leitura de Arquivo txt incorreta


How to find the order of these groups?

Question: I don't know why but I just cannot see how to find the orders of these groups:
$YXY^{-1}=X^2$
$YXY^{-1}=X^4$
$YXY^{-1}=X^3$
With the property that $X^5 = 1$ and $Y^4 =1$
How would I go about finding the order? The questions asks me to find which of these groups are isomorphic.
Thanks.
Answer: Hint: You should treat those relations as a rule on how to commute $Y$ past $X$, for example the first can be written:
$$YX = X^2Y$$
Then you know that every element can be written in the form $X^nY^m$ for some $n$ and $m$.  Use the orders of $X$ and $Y$ to figure out how many elements there are of this form.
Comment: @Lolwat You don't need to commute all the possible elements - you just need to understand how powers of Y move to the right past powers of X.
Comment: Can you help with say an example of this done on the first group? I'm still struggling to understand this. Won't it take quite a long time to commute all the possible elements?

How to find the order of these groups?


Node Create/Edit Form - Multistep with dynamic fields

Question: Our site has different type of articles. Based on the type selected, the fields displayed to the user are varied. The ask is to create a multi-step form and include type field on step 1. Based on the type, subsequent steps and fields included in those steps need to vary.
An important ask is that they need the ability to change the type of the article after it has been created. So on day 1 they might create an article with type "single page" but later change it to "multi page" (Multi-page article has all fields in single page plus additional fields).
I looked at Multistep, msnf, webform and webform_conditional modules etc, but they didn't seem to provide the functionality I need. Is creating this using Form API the best approach? Any suggestion?
UPDATE1
Another important requirement: An article could have multiple (0 or many) sections and each section could have multiple subsections. What is the best way to model the content type? Create content type Section and Subsection and then use node references (article will have a nod reference to section; section will have a node reference to subsection)? Using node references, can one to many relationship be implemented?
Comment: whats wrong with Multistep module?
Comment: Sounds like this will lead to primarily opinion based answers. A little bit more information would be helpful, too. What's wrong with the modules you mentioned? Are you good with code? You prefer having things written down? Do you prefer clicking stuff together in the backend?
Comment: Do you mean "task" when you say "ask" in question?
Answer: There are three module(may be two in your case), which can together to achieve what you want in D7. I have done this & client use it on daily basis..
Field Group
Multi Step
Then I have used Conditional Field module to have fields dependent on one another & it works great.
If you find any error in setup, please try the issue queue for patch.
Comment: Thanks for the tip. I will look into those modules. I would like to upvote your answer, but don't have enough points to do so.

BTW, I added one more requirement.
Comment: I saw your requirement. You can do this by help of field group & conditional field. You will need to plan it accordingly & put condition in same manner...

Please accept the answer if it solved your problem
Answer: You can start from the basic multiple step form using the Examples for Developers module in Drupal.

The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.

In the Example module, there is sub-module "form_example", that is for your need. => Tutorial 8: Basic multistep form
Answer: You can also try the following modules:

Multistep Nodeform
Conditional Fields
Field Group

I have used these modules in one of my project & it works great. Hope these modules works for you.
Note: Multistep Nodeform is module for node forms only but works very efficiently.
Comment: In my situation different field might show up based on taxonomy term selected in the first step , how can I handle it using these modules?
Answer: You need to use Multistep and Conditional fields modules for the tasks mentioned.
And yes Node reference supports one to many node reference, you just need to add a node reference field in your content type and select the option "Number of values" as per your requirement.
Answer: You can try the route module
Route module enables the construction of wizard like journeys using Panels. It's mostly useful for developers that require high levels of configurability and flexibility for their multistep forms. Use of Panels gives this flexibility.
To taste an example functionality, please enable route_example module and navigate to /route-example/step-one.


Why conditional probability $P(A \cap B) =P(A \mid B) \cdot P(B)$? It should be $=P(A \mid B) \cdot P(B)+P(B \mid A) \cdot P(A)$

Question: Why does not the order of occurrence of events make 2 cases?

case when $A$ occurs first then $B$
case when $B$ occurs first then $A$

Hence, $P(A \cap B) = \text{ case }1 + \text{ case }2 = P(A) \cdot P(B \mid A) + P(B) \cdot P(A \mid B)$.
Comment: Don't think of conditional probability as an order, think of $P(A|B)$ as the probability $A$ occurs when $B$ occurs.
Answer: It is because the definition of $P(A\,\vert\, B)$ is that it is the probability of the event '$A$ and $B$' relative to the probability of the event $B$:
$$P(A\,\vert\, B)=\frac{P(A\cap B)}{P(B)}.$$
Your second formula is  $\;2P(A\cap B)$.
Answer: Take a look at our daily language.
Lets consider the probability of taking an umbrella and presence of a rain $P(U,R)$.
The rain occuring with prob. $P(R)$ and after we look at the window to know weither it rains or not we take a decision $P(U|R)$ if to take an umbrella. So, the actual probability is $P(U,R) = P(R)P(U|R)$. There should not be any other term.


How does one prevent possible overwriting object attributes with illegal/illogical values?

Question: I'm familiarizing myself with Python, and I have a question on rewriting attributes with illegal values.
Suppose I have a class Human, with attribute limbs, like so:
class Human:
    def __init__(self, limbs):
        if limbs > 4:
           raise ValueError('Humans dont have more than 4 limbs.')
        self.limbs = limbs

h1 = Human(5)       # Raises error - good.
h2 = Human(4)
h2.limbs = 5         # How do I protect against this?

Setting the limbs attribute to 5 would be caught via the constructor, but it is allowed via direct assignment. Is there a way to enforce error checking on attribute assignment? Should I be using an immutable string/tuple?
Again, I'm very new so I apologize if this is a silly question. Thanks!
Comment: getter and setter functions I think...
Answer: You could use the property decorator to make getters and setters for your property.
class Human(object):

    def __init__(self, limbs):
        self.limbs = limbs

    @property
    def limbs(self):
        return self._limbs

    @limbs.setter
    def limbs(self, new_value):
        if new_value > 4:
            raise ValueError("Humans don't have more than 4 limbs.")
        self._limbs = new_value

human = Human(4)
human.limbs = 5  # This will raise an exception

That said, if someone really wants to change this, they can still set self._limbs to whatever they want.
EDIT: Updated the example to use the setter in the constructor per @chepner's comment.
Comment: You can use `self.limbs = limbs` in `__init__` and let the setter handle the assignment.


Solve for coefficients of $y = A(1 - e^{-x/B})$ given two points

Question: I have the equation $y = A(1 - e^{-x/B})$, and two $(x,y)$ pairs. How can I solve for $A$ and $B$? This should be simple, but I've been banging my head against the algebra for a while to no avail.
I should probably mention that this is not homework.
Comment: Do you have particular values for the pairs, or are they arbitrary?
Comment: Consider $$\frac{y_1}{y_2}=\frac{1-e^{-\frac {x_1}B}}{1-e^{-\frac {x_2}B}}$$ and how one might manipulate it around to isolate $B$
Comment: Also note [this question](http://math.stackexchange.com/questions/241433/find-expotential-function-from-two-points)
Answer: If you have two particular points, $(x_1, y_1)$, and $(x_2, y_2)$, then you have two equations and two unknowns: $$A=\frac{y_1}{1-e^{-x_1/B}}$$ $$B=-x_2\left(\ln\left(\frac{y_2-A}{-A}\right)\right)^{-1}$$
Since $x_1$, $y_1$, $x_2$, and $y_2$ are constants, this is like solving an a regular two equation to unknown algebra problem, albeit a nasty one.
Comment: I was able to get something like that, but I couldn't figure out how to proceed. Unfortunately my notes are at work, so I can't recall exactly how far I got.
Comment: I would probably plug in what we have for $B$ in the first equation  with $A$. That way we get some potential cancellations with the $e$ and the $ln$... Also remember all the exponent rules! Good luck!
Comment: I just end up with $A = \frac{y_1}{1-(\frac{y_2-A}{-A})^{x_1/x_2}}$