Greyed out Folder in Finder (OSX) on Network SMB Share

Question: Bear with me, this is long and complicated, but TL;DR Where does OSX hide extra attributes on files (either on shares or local)?
We are having issues in our Enterprise environment.
We have an Oracle ZFS setup and our OSX machines are SMB mounting the volume.
A user attempted to move a folder between locations and cancelled this halfway through, this resulted in the folder in both locations being greyed out.
In Finder it shows a creation and modified date on the folder of 06/13/1943 06:13:00
From our linux workstations when we stat the file, it shows correct creation and modified dates.
We then touch the file from the linux workstation or an OSX workstation and through terminal we can see the folder and even use the open command on the folder. But through Finder it stays greyed out and unable to be opened. This affected all OSX workstations accessing this file. None of them could see it, but Windows and Linux were fine.
We ended up using the deprecated GetFileInfo and SetFile commands to resolve this.
My question to the community is, where are these attributes being stored, as they were not visible on the file using ls -la or stat. But were there when we looked at it with GetFileInfo. Does anyone know if OSX does some weird Samba caching and stores it on the server? or puts this in a stupid .DS_Store file?
HELP!!! PLZ
Comment: I believe .ds_store is only for special attributes like folder color in OSX.
Answer: OS X has a couple of ways to store its extra metadata on volumes that don't natively support them:

On things like FAT volumes, it'll store the metadata as a separate file with a "._" prefix on the filename, using AppleDouble format. For example, if the original file was "somefile.txt" and you copied it to a FAT32 volume, the data would be copied to "somefile.txt", and the metadata would be saved as "._somefile.txt".
On an NTFS volume mounted over SMB (if certain conditions I don't fully understand apply), it'll store the metadata as NTFS alternate data streams.

I'm not sure if your Oracle server's SMB implementation supports alternate data streams, but my guess is that it does, and the Mac is using them to store extra metadata (and the server is probably storing them as ZFS extended attributes). You could look for them directly on the server, or you might also try mounting the volume from a Windows client and see if streams.exe can see them.
Answer: I was getting Jan 24, 1984 3:00A, that's the easter egg (the day the first Mac was sold): during transit time stamp until the transfer is complete (where there was some glitch that didn't autofix that date when the copy was over)
assuming the greyed out folders are top level inside a spedific folder (otherwise, add "-recurse" to gci command and remove "-maxdepth 1" from the find command):
not ADS (on a WinOS machine powershell):
    gci -path 'd:\specificfolder' | % {$_.fullname} | gi -stream *

not AppleDouble (connect to the good specific folder, then the bad specific folder (i.e. bad folder will have "-1" appended), then in terminal):
    rm /Volumes/specificfolder-1/._*  && rm /Volumes/specificfolder-1/.DS_Store

Windows is fine with the bad folders (and sees dates correctly), and you're right about Mac's under the hood unix (or linux) seeing the right date with the ls -la command, and all MacOS see the greyed out syndrome, so it's not specific to the machine that you used to copy type-of-problem (and copying the file in Windows producing a greyed out copy, so WinOS surely knows how to transfer that hidden info!).
So I can only help pinpoint where the problem lies, and agree with your solution (but note that right-click and Get Info or select and command+i hasn't gone away in High Sierra, current OS as of this writing); however, if you have a bunch of folders greyed out: better automate; so, to add something, you could run the following two commands:
    find /Volumes/specificfolder/ -maxdepth 1 -type d -exec getfileinfo {} \; \
    | egrep "directory|created" | sed -e 's/directory: "\(.*\)"/\1/' \
    | sed -e 's/created: \(.*\)/\1/' \
    | sed -e 's#/Volumes/specificfolder#/Volumes/specificfolder-1#' > temp.txt

    while read oddline; do read evenline; setfile -d "$evenline" "$oddline"; \
    done < temp.txt


Is a Lie algebra a complex or a real vector space?

Question: I am trying to learn Lie theory and for this purpose I worked out the Lie algebras of some matrix groups. The examples I worked happened to be complex matrix groups and it lead me to wonder whether, when I try to determine a basis, I had to find a complex or a real basis.

Is there any convention, definition or otherwise a way to know whether
  a Lie algebra is to be understood as a complex or real vector space?
Answer: A real Lie algebra is a real vector space and a complex Lie algebra is a complex vector space. Standard notations for standard Lie algebras usually implicitly specify which is which; for example, $\mathfrak{gl}_n(\mathbb{R})$ is naturally a real Lie algebra while $\mathfrak{gl}_n(\mathbb{C})$ is naturally a complex Lie algebra. If the author does not specify then you need to figure out which is intended from context.
Two warnings: $\mathfrak{u}(n)$ is a real Lie algebra. It does not have a natural complex structure. And people frequently take complexifications $\mathfrak{g} \otimes_{\mathbb{R}} \mathbb{C}$ of real Lie algebras, e.g. when determining their complex representation theory.
Comment: @learner: probably, but keep in mind that $U(n)$, for example, is not a complex Lie group.
Comment: If it's not specified but the Lie groups are complex, like $SL_n(\mathbb C)$, should I assume that the Lie algebras are taken to be complex? (I was showing that two Lie algebras are isomorphic and it might not matter for this purpose...?)
Comment: Could you explain a bit about this notation "$⊗_ℝ ℂ$ "? Is this a tensor product $⊗$ and ℝ is for the ring or for the real number? (I find https://math.stackexchange.com/questions/181788/tensor-product-algebra-mathbbc-otimes-mathbbr-mathbbc)
Comment: Another question: () is a real Lie group. But () matrix representation is usually written in G$_$(ℂ) which seems generally a complex Lie group. So how do I digest the difference between () vs G$_$(ℂ)?
Comment: Many thanks!!! voted 1
Comment: Could you comment?
Answer: In general a Lie algebra is defined over an arbitrary field. For connection with $p$-groups, the field may be also a finite field $\mathbb{F}_q$ of characteristic $p>0$. Many results for Lie algebras, however, are only true over an algebraically closed field of characteristic zero, e.g., Lie's theorem for Lie algebras. Note that the classification of finite-dimensional simple Lie algebras in characteristic $p>0$ differs drastically from the one in characteristic $0$.
Comment: Another question: () is a real Lie group. But () matrix representation is usually written in G(ℂ) which seems generally a complex Lie group. So how do I digest the difference between () vs G(ℂ)? real Lie group vs complex Lie group?
Comment: Many thanks!!! voted 1


How to loop through a mysql array and create another array with its content depending on a variable $i

Question: I'm trying to make a loop in php that will go through a MySQL array and fetch some information depending on a variable.
The table in MySQL is like so: id,slot1,slot2,slot3,...slot12.
$max_player_slots = 5;

//***Create Inventory Array**//

    $inventory_info = "SELECT * from inventory where id = $player_id";
    $inventory_info2 = mysql_query($inventory_info) or die ("Couldn't get inventorys    stats");
    $inventory_info3 = mysql_fetch_array($inventory_info2);

//depending on max player slots insert that many values into &invSlots array

    for( $i = 1, $invSlots = array(); $i > $max_player_slots; $i++){

        $invSlots[$i] = $inventory_info3[$i]; //here is the problem i dont know how to insert the diferent values using $i

    }

        $json = $invSlots;
        $encoded = json_encode($json);
        die ($encoded);

I would expect the $invSlots array after this to contain:
$invSlots = array(slot1, slot2, slot3, slot4, slot5);

but I just get an error.
I think the reason is because the mysql array information is stored in an associative array and im trying to access it numericly? but I dont know how to solve it.
Comment: "but I just get an error."... what error?
Comment: I dont get an error message it just doesnt work it seems like it goes into an infinite loop.
Answer: shouldn't it be
for( $i = 1, $invSlots = array(); $i < $max_player_slots; $i++){

< instead of >?
Comment: Well this is very embarrasing...sry for wasting yout time I checked it so many times I just got blocked.
Comment: no problem ;) sometimes I have the same problem and waste hours for solving such simple things


Crash when opening Android window after using Unity ScrollRect component

Question: java.lang.Error: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Version '2020.3.14f1 (d0d1bb862f9d)', Build type 'Release', Scripting Backend 'mono', CPU 'armeabi-v7a'
Build fingerprint: 'HUAWEI/ANA-AN00/HWANA:10/HUAWEIANA-AN00/184.108.40.206C00:user/release-keys'
Revision: '0'
ABI: 'arm'
Timestamp: 2022-05-17 17:02:37+0800
pid: 11322, tid: 13025, name: UnityMain  >>> com.hwen.egg <<<
uid: 10270
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
Cause: null pointer dereference
r0  b7d0d000  r1  00ffffe9  r2  00000001  r3  00ffffdc
r4  00000000  r5  00000000  r6  00000010  r7  00420000
r8  00400001  r9  ec6eb17c  r10 00400011  r11 00001d10
ip  bbb87420  sp  ba47a8e8  lr  bade8ca1  pc  bb497e32
<code>backtrace:
      #00 pc 00953e32  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #01 pc 002a4c9d  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #02 pc 002a1307  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #03 pc 002a121d  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #04 pc 00399cc1  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #05 pc 000bbf4d  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #06 pc 001cb68f  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #07 pc 002f62cb  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #08 pc 002f6ae7  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #09 pc 0087ac77  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #10 pc 00877da3  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #11 pc 00874025  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #12 pc 00875d93  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #13 pc 00889a6b  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #14 pc 00889999  /data/app/com.hwen.egg-kLmp4gehHdP02YIKdyPSiw==/lib/arm/libunity.so
      #15 pc 000040d6  <anonymous:d197e000>
</code>
managed backtrace:
<code>#00 (wrapper managed-to-native) UnityEngine.TextGenerator:Populate_Internal_Injected (UnityEngine.TextGenerator,string,UnityEngine.Font,UnityEngine.Color&,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,int,int,bool,UnityEngine.TextAnchor,single,single,single,single,bool,bool,uint&)
      #01 UnityEngine.TextGenerator:Populate_Internal (string,UnityEngine.Font,UnityEngine.Color,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,int,int,bool,UnityEngine.TextAnchor,single,single,single,single,bool,bool,uint&) <0x1a7>
      #02 UnityEngine.TextGenerator:Populate_Internal (string,UnityEngine.Font,UnityEngine.Color,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,UnityEngine.VerticalWrapMode,UnityEngine.HorizontalWrapMode,bool,UnityEngine.TextAnchor,UnityEngine.Vector2,UnityEngine.Vector2,bool,bool,UnityEngine.TextGenerationError&) <0x207>
      #03 UnityEngine.TextGenerator:PopulateAlways (string,UnityEngine.TextGenerationSettings) <0x2d7>
      #04 UnityEngine.TextGenerator:PopulateWithError (string,UnityEngine.TextGenerationSettings) <0x20b>
      #05 UnityEngine.TextGenerator:PopulateWithErrors (string,UnityEngine.TextGenerationSettings,UnityEngine.GameObject) <0x10b>
      #06 UnityEngine.UI.Text:OnPopulateMesh (UnityEngine.UI.VertexHelper) <0x1c3>
      #07 UnityEngine.UI.Graphic:DoMeshGeneration () <0x127>
      #08 UnityEngine.UI.Graphic:UpdateGeometry () <0x2b>
      #09 UnityEngine.UI.Text:UpdateGeometry () <0x37>
      #10 UnityEngine.UI.Graphic:Rebuild (UnityEngine.UI.CanvasUpdate) <0x6b>
      #11 UnityEngine.UI.CanvasUpdateRegistry:PerformUpdate () <0x3fb>
      #12 (wrapper delegate-invoke) <Module>:invoke_void ()
      #13 UnityEngine.Canvas:SendWillRenderCanvases () <0x33>
      #14 UnityEngine.Canvas:ForceUpdateCanvases () <0xb>
      #15 UnityEngine.UI.ScrollRect:EnsureLayoutHasRebuilt () <0x2b>
      #16 UnityEngine.UI.ScrollRect:LateUpdate () <0x83>
      #17 (wrapper runtime-invoke) object:runtime_invoke_void__this__ (object,intptr,intptr,intptr)

    at libunity.0x953e32(Native Method)
    at libunity.0x2a4c9d(Native Method)
    at libunity.0x2a1307(Native Method)
    at libunity.0x2a121d(Native Method)
    at libunity.0x399cc1(Native Method)
    at libunity.0xbbf4d(Native Method)
    at libunity.0x1cb68f(Native Method)
    at libunity.0x2f62cb(Native Method)
    at libunity.0x2f6ae7(Native Method)
    at libunity.0x87ac77(Native Method)
    at libunity.0x877da3(Native Method)
    at libunity.0x874025(Native Method)
    at libunity.0x875d93(Native Method)
    at libunity.0x889a6b(Native Method)
    at libunity.0x889999(Native Method)
    at UnityEngine.TextGenerator.Populate_Internal_Injected (UnityEngine.TextGenerator,string,UnityEngine.Font,UnityEngine.Color&,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,int,int,bool,UnityEngine.TextAnchor,single,single,single,single,bool,bool,uint&)(Native Method)
    at UnityEngine.TextGenerator.Populate_Internal (string,UnityEngine.Font,UnityEngine.Color,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,int,int,bool,UnityEngine.TextAnchor,single,single,single,single,bool,bool,uint&)(0x1a7:423)
    at UnityEngine.TextGenerator.Populate_Internal (string,UnityEngine.Font,UnityEngine.Color,int,single,single,UnityEngine.FontStyle,bool,bool,int,int,UnityEngine.VerticalWrapMode,UnityEngine.HorizontalWrapMode,bool,UnityEngine.TextAnchor,UnityEngine.Vector2,UnityEngine.Vector2,bool,bool,UnityEngine.TextGenerationError&)(0x207:519)
    at UnityEngine.TextGenerator.PopulateAlways (string,UnityEngine.TextGenerationSettings)(0x2d7:727)
    at UnityEngine.TextGenerator.PopulateWithError (string,UnityEngine.TextGenerationSettings)(0x20b:523)
    at UnityEngine.TextGenerator.PopulateWithErrors (string,UnityEngine.TextGenerationSettings,UnityEngine.GameObject)(0x10b:267)
    at UnityEngine.UI.Text.OnPopulateMesh (UnityEngine.UI.VertexHelper)(0x1c3:451)
    at UnityEngine.UI.Graphic.DoMeshGeneration ()(0x127:295)
    at UnityEngine.UI.Graphic.UpdateGeometry ()(0x2b:43)
    at UnityEngine.UI.Text.UpdateGeometry ()(0x37:55)
    at UnityEngine.UI.Graphic.Rebuild (UnityEngine.UI.CanvasUpdate)(0x6b:107)
    at UnityEngine.UI.CanvasUpdateRegistry.PerformUpdate ()(0x3fb:1019)
    at <Module>.invoke_void ()(Native Method)
    at UnityEngine.Canvas.SendWillRenderCanvases ()(0x33:51)
    at UnityEngine.Canvas.ForceUpdateCanvases ()(0xb:11)
    at UnityEngine.UI.ScrollRect.EnsureLayoutHasRebuilt ()(0x2b:43)
    at UnityEngine.UI.ScrollRect.LateUpdate ()(0x83:131)
</code>
Comment: Unity Version is 2020.3.14f1
Comment: You have a null reference somewhere. You'll need to include the relevant code as well if we are going to have any chance of helping.
Answer: It is Unity bug.Upgrade my Unity 2020.3.14->2020.3.34 can fixed!


Devel kpr, dpr, dpm, etc. only print after cache flush

Question: I'm writing a small module and using the Devel print functions (dpr, kpr, dpm, etc.) to print out some values.
However, I only see the values in the page after I flush certain caches. if I just reload the page or go to it I see nothing. This is true for both the message-area and the regular debug print functions. Is this expected?
I am logged in as admin so I'd think ordinary page caching is off.
(This is in D7.)
Comment: From what I can remember from D6 all field widgets are cached so it's possible that this is expected behaviour.
Comment: It all depends on where your inserting your debug code as to whether or not it's cached. For example if your adding debug to a custom input filter then that will always be cached regardless of your admin user or not. Can you include an example function of where your adding the debug?
Comment: Thanks. It's in a hook: hook_field_widget_info_alter(). The idea is to augment an existing field widget. I'm just getting started, and am using the Devel print functions to see its arg.
Comment: _info is definely cache for sure
Answer: hook_field_widget_info_alter() is cached.  Follow these steps to Suppress caching (for development) or to use an external page cache

when developing for Drupal you might want to suppress all caching of
  data to make sure new hooks, theme functions, etc are recognized
  immediately.
This will have performance detriments, of course, so must not be used
  in production. To turn on this development mode, add the following to
  your Drupal 7 settings.php file:


How to subtract larger hex value from smaller hex value?

Question: In computers we use two's-complement to subtract and it works well, but how does it work for subtraction without two's-complement when subtracting a larger number from a smaller number?
<code>  0x0F
- 0x13
------
   -1C
</code>
Doesn't seem to work like subtracting decimal numbers would.
<code>  01
- 11
----
 -10
</code>
It works if I flip the numbers.
<code>  0x13
- 0x0F
------
    -4
</code>
What am I missing?
Answer: Your example for base 10 is poorly chosen. Try $3-12$. What you get is $3-2=1$ and $0-1=-1$ So the answer is $-1\cdot 10+1=-9$. You should apply the same to the hex base. $-10_{16}+B_{16}=-5_{16}$.
Answer: What you are missing is that the two numbers are $8$ bits each and so the subtraction results in the $8$ bit two's-complement number $0$xFC  which represents $-4$. If there were more bits, then the hex number would be sign extended with FFs on the left.


Not Skolem's Paradox - Part 2

Question: This is a followup to a previous question: Not Skolem's Paradox.
Assume we have a countable, non-standard model of Peano Arithmetic in ZFC.
Let $N^*$ be the universe of this model and let $p \in N^*$ be a non-standard natural number larger than any standard natural number. In ZFC we can define the set $X = \{x : x \in N^* \land x < p\}$. Let $Y = X \cup \{p\}$. $X$ and $Y$ are both countably infinite sets and we can easily define a bijection between $X$ and $Y$ in ZFC. For example, we can define the set of ordered pairs:
$F = \{(0,p), (1,0), (2,1), (3,2), ...\}$.
My question is why doesn't the bijection $F$ exist inside the model?
In my previous question there was some confusion about how I was defining sets inside the model. We can encode any "finite" set of natural numbers as a natural number using powers of 2. For example, we can encode the set $\{1,2,3\}$ as $2^1+2^2+2^3=14$. Similarly, we can encode a bijection as a natural number. First, we define a method to encode an ordered pair as a natural number. Encode $(a,a)$ as $2^a$. Encode $(a,b)$ as $2^{a+1} + 2^{b+1}$ if $a<b$. If $b<a$ encode $(a,b)$ as $2^{a+1} + 2^{b+1} + 1$. Now that we can encode ordered pairs, we can define a bijection between two sets of natural numbers using Godel's beta function.
My question becomes why doesn't some natural number in our model encode a function such that $F$ is an initial segment of this function?
Edit:
I want to thank Andres Caicedo for correcting my question. I do want to define my bijection as he suggests:
$F = \{(0,p)\} \cup \{(t+1,t) | t \in \aleph \} \cup \{ (s,s) | s \in X \backslash \aleph \}$
As he points out, I can't define $\aleph$, the set of standard natural numbers, inside the model. However, I can define $\aleph$ in my meta-theory. Can I come up a with beta function for $F$ inside ZFC? If so, does the encoding of this beta function exist in my model? If not, there is a natural number of the form $2^{a+1} + 2^{b+1} + 1$ that is missing from the model where $(a,b)$ is my beta function. If the encoding does exist in the model we have a definable violation of induction. Considering the alternatives, I am guessing there is some reason I can't define a beta function for $F$ in ZFC.
Answer: Before going any further, note that $F$, as written, is most likely not what you meant it to be. It appears as if $F$ is a bijection between the standard part $\mathbb N$ of $N^*$, and the set $\mathbb N\cup\{p\}$. Note that this is a bijection, and it is the initial segment of some bijection between $X$ and $Y$ (for example, the one in  paragraph 3). This is not a problem. The issue is that the initial segment that codes $F$ is not definable in the model, it is not itself coded. The thing is, if $G$ is a function coded in $N^*$, with domain an initial segment of $N^*$, then for any initial segment $I$ that is definable in $N^*$, we have that in $N^*$ there is a code for $G\upharpoonright I$. But $I$ in this case is $\mathbb N$, and this is not definable in $N^*$. In fact, the only definable initial segments are those of the form $\{y\mid y<t\}$ for some $t$, and $\mathbb N$ definitely does not have this form. (This is proved by induction: "For any proper initial segment there is a least number not in it." The problem is that there is no least non-standard integer: IF $K$ is infinite, so is $K-1$.) The obstacle here is the restriction to definable initial segments, but this is unavoidable: If $G\upharpoonright I$ is coded in $N^*$, certainly $I$ is definable in $N^*$.
I imagine this $F$ is not what you intended. Rather, you probably meant something like $F=\{(0,p)\}\cup\{(t+1,t)\mid t<p\}$. But note that $(p,p-1)\in F$, so $F$ is a bijection alright, and certainly one coded inside $N^*$, but it is just a bijection from $Y$ to itself, which again is not what you intended.
Or maybe you meant $F=\{(0,p)\}\cup\{(t+1,t)\mid t\in\mathbb N\}\cup\{(s,s)\mid s\in X\setminus\mathbb N\}$. This is definitely a bijection between $X$ and $Y$, but it is not definable in $N^*$, it is not encoded in there. If it were, we could from it define $\mathbb N$, and obtain a definable violation of induction.
In fact, no matter how we try, any bijection between $X$ and $Y$ cannot be coded within the model. This is because $N^*$, being a model of $\mathsf{PA}$, proves the appropriate facts about coded finite sets, such as there not being a bijection from a finite set to a proper superset. (This is proved by induction, of course.)
(If you find these explanations not quite satisfactory, and if you indicate any issues you may have, I'll try to clarify/expand/add as appropriate.)

Let me address your edit. The function $F$ in paragraph 3 is definitely an object in $\mathsf{ZFC}$. It is countable, so it can be coded as a set of numbers. However, we cannot code it inside the model. As Andreas Blass remarks, each value $(a,F(a))$ is certainly codable, but of course this is not enough. To have a coding of $F$ within $N^*$, via Gödel's approach or otherwise, we would need definability of $F$. As explained above, this gives us definability of $\mathbb N$ inside $N^*$. But this is impossible. In a sense, this is related to your previous question: $N^*$ can refer (via codes) only to sets that are fairly explicitly presented, and most sets are not. Even if "from the outside" we have a good understanding of $F$, this is simply an external object to our model $N^*$, it is "invisible" to it, and it is not possible to change this, because the induction schema prevents the presence of "Dedekind infinite integers".
Comment: Thanks. I see the problem with my bijection. I meant the bijection you give in paragraph 2. As you point out, this is a bijection from $Y$ to $Y$. Removing $(p,p1)$ would give a bijection from $X$ to $X$. I am not sure I understand why the the bijection in paragraph 3 can't be encoded. Are you assuming $Con(PA)$?
Comment: You are, I think. Otherwise, $N^*$ would not exist. Anyway, the point in paragraph 3 is that if $F$ were codable, then we could define $\mathbb N$ (since it is definable from $F$ as the set of $x$ in the domain of $F$ such that $F(x)\ne x$). But we argued in paragraph 1 that $\mathbb N$, being an initial segment of $N^*$, is not definable since it is not the set of predecessors of some number. Since $\mathbb N$ is not definable, we cannot have a way of coding $F$.
Comment: Thanks again. Actually, I am trying to "obtain a definable violation of induction". I like your answer, but I usually wait at least 24 hours before accepting an answer. I originally assumed the answer would involve [Tennenbaum's theorem](http://en.wikipedia.org/wiki/Tennenbaum%27s_theorem).
Answer: Addressing the edited version of the question, with the corrected version of $F$: The function $F$ exists in the ZFC universe, and (therefore) so does the corresponding set of codes in $N^*$ of the ordered pairs in $F$. But this subset of $N^*$ is not coded by any member of $N^*$, for the reason in Andres Caicedo's answer: If it were codable, then there would be a definable violation of induction, meaning that $N^*$ is not really a model of Peano Arithmetic.
Comment: If $F$ exists in ZFC, what prevents me from encoding it **IN ZFC** as, say, a beta function? If this code does not exist in the model then I can still prove $N^*$ is not a model of PA. I would be able to show there is a number of the form $2^{a+1} + 2^{b+1} + 1$ that is missing from the model.
Comment: @RussellEasterly (1) In ZFC, you can encode, via the beta function, finite sets of natural numbers as natural numbers. $F$ is, however, an infinite set in the ZC universe. (2) The "numbers" of the form $2^{a+1}+2^{b+1}+1$ that code ordered pairs are in the model; what is not available in the model is a code for the set of those ordered pairs that constitute $F$.
Comment: @Andeas Blass: Which sets of ordered pairs can I encode? How is this set different from any other set? There are lots of ways I can encode this bijection. I could use the Godel number of a Turing machine. I could encode it as a string of characters, "(0,p)(1,0),...,(p-1,p-1)". Are you saying none of these possible encodings exist as numbers in the model?
Comment: @RussellEasterly I was referring to the standard encoding, but in fact the same goes for any other reasonable encoding. If you allow unreasonable encodings then you could define a coding system where 0 is defined to be a code of the $F$ you want; but then the usual manipulations of codes (e.g., checking whether one given number is in the set coded by another given number) would not be definable in the model. As to which sets can be encoded, that depends on the particular model that you're working in, but in no case can you code something that would violate the induction axioms.

Not Skolem's Paradox - Part 2


Sql Server. Why field value of [almost] any type may be treated as quoted string in Query/DML?

Question: I discovered SUDDENLY that in SQL Server (2000) any field type value may be treated as quoted string (in query or DML).
Question:
Is it normal behavior or accidentally successful result?
Example:
CREATE TABLE [Test_table] (
    [int_field] [int] NULL ,
    [float_field] [float] NULL ,
    [date_field] [datetime] NULL ,
    [id] [int] NOT NULL
) ON [PRIMARY]
GO

update test_table set int_field = 100, float_field = 10.01, date_field = CAST('2013-11-10' AS DATETIME) where id = 1

update test_table set int_field = '200', float_field = '20.02', date_field = '2014-12-10' where id = '2'

select * from test_table where id in ('1', 2) -- WHY '1' DOES WORK!???

Why i need this?
It exists idea to send in one Stored Procedure over 270 parameters as integral text (XML or custom serialization by delimiters or like Len1+value1+len2+value2+..) then parse and extract all desired values and use them in UPDATE statement. This SO Question.
Q2: Is there any limitations for some types?
Q3: Is this reliable way or CAST anyway is recommended?
Answer: SQL Server, like most (all?) brands of SQL, automatically attempts to cast things to the correct type.  This is pretty standard behavior.
It should be reliable in the above cases.  In both the update and select statement, the type that must be converted to is known (from the column definitions of the tables).
However, automatic casting can introduce subtle issues when it is part of a more complex query.  Some kinds of SQL will have problems with statements like this:
select case when foo=1 then 0 else 'a' end from table

In this case, the result type won't necessarily be something that can accept all types of results, so it could fail when it tries to assign 'a'.  Be careful when relying on automatic conversion in complex statements.  It is probably better to make it explicit in such cases.
Another potential issue with passing everything in as strings is that there will be an error if you accidentally pass in a non-numeric value.
Comment: Your `CASE` example is wrong. The type of the result of a `CASE` expression is always fixed, and follows precedence rules between all possible types in `THEN` (and `ELSE`) clauses. The result of the expression you've shown can only ever be of type `int`. The interpreter doesn't "guess". So, it can only ever (in this case) produce `0` or a conversion error
Comment: @Damien_The_Unbeliever, thanks for the additional information.  I have changed it to remove assumptions about what the interpreter is actually doing.
Answer: If you check the CAST and CONVERT topic, you'll find a handy table:

You'll note that conversion from char and varchar is supported for every other type, and only a few of them require explicit casts. For some types, there's no obvious way to type a literal of that type, so allowing implicit conversions from a string makes sense.
(But oh, how I wish conversion to datetime required an explicit case with a format code...)


IPTables and SNAT for just two ports

Question: I want to set up some NAT policies so that certain machines will only have outbound access to http/https. They should not be able to do port scans or anything else from their machine.
Currently my NAT rules are:
-A PREROUTING -d 22.214.171.124 -j DNAT --to-destination 10.10.1.10
-A POSTROUTING -s 10.10.1.10 -j SNAT --to-source 18.104.22.168

And I have this shared rule:
-A POSTROUTING -o eth0 -j MASQUERADE

22.214.171.124 is a public IP, and 10.10.1.10 is an internal IP.
This allows all inbound and outbound access to NAT directly through.
I tried the following POSTROUTING rule instead of the one above:
-A POSTROUTING -s 10.10.1.10 -p tcp --dport 80 -j SNAT --to-source 184.108.40.206:80

However, that didn't seem to work. After adding that rule I could still use RDP from the workstation.
To recap, my goal is to allow certain workstations to only have http/https access to the Internet. All other outbound traffic should be blocked. All traffic should be allowed. I want all other workstations in the network to use the existing NAT policy to allow all outbound traffic to be NAT'ed.
Update
Based on @Zoredache's reply, I now have the following Postrouting rules.
-A POSTROUTING -s 10.10.1.10/32 -p tcp -m tcp --dport 80 -j SNAT --to-source 126.96.36.199:80
-A POSTROUTING -s 10.10.1.10/32 -p tcp -m tcp --dport 443 -j SNAT --to-source 126.96.36.199:443
-A POSTROUTING -s 10.10.1.10/32 -p tcp -m tcp --dport 53 -j SNAT --to-source 220.127.116.11:53
-A POSTROUTING -s 10.10.1.10/32 -p tcp -m udp --dport 53 -j SNAT --to-source 220.127.116.11:53
-A POSTROUTING -s 10.10.1.10/32 -j ACCEPT
-A POSTROUTING -o eth0 -j MASQUERADE

They don't quite work yet but they are getting close. More in my reply to @Zoredache below.
Comment: I suggest posting the (sanitized) output of `iptables-save` command. That way, we can easily see if there are any other rules that rendered your rules to be ineffectual.
Comment: Another question, for clarification: the `iptables` rules are located on a Linux gateway, that stands between the Internet and your LAN, and the workstations live in your LAN. Am I right? Please also indicate which interface connects to which side.
Comment: @pepoluan, I've added the rules now, and I'll reply with more details to zoredache.
Answer: The key to iptables is the first match wins.
Assuming the client machine is 10.10.1.10 then you just have to look at these rules in order.  If the first rule doesn't match it is going to pass down MASQ rule which it will match.
-A POSTROUTING -s 10.10.1.10 -p tcp --dport 80 -j SNAT --to-source 188.8.131.52:80
-A POSTROUTING -o eth0 -j MASQUERADE

If you were to add another rule before the final MASQUERADE rule should result in the NAT not happening.  Since the packets from 10.10.1.10 will that are not destined to tcp/80 or tcp/443 will match the ACCEPT rule, meaning that they will not be translated by the SNAT/MASQ rules.
-A POSTROUTING -s 10.10.1.10 -p tcp --dport 80 -j SNAT --to-source 22.214.171.124:80
-A POSTROUTING -s 10.10.1.10 -p tcp --dport 443-j SNAT --to-source 184.108.40.206:443
-A POSTROUTING -s 10.10.1.10 -j ACCEPT
-A POSTROUTING -o eth0 -j MASQUERADE

Comment: Thanks, that's exactly what I was looking for. It almost works, but something isn't quite working. I realize that I need DNS access too for a functioning web browsing machine, so I added ports 53 for TCP and UDP. (see my update on my original question) RDP is now blocked, so that's good, but pinging a new DNS name sometimes works and sometimes doesn't. What would cause that to be intermittent? Would it have something to do with udp and tcp using the same destination port?
Comment: First, I am kinda surprised PING is working.  Is there some reason why you are trying to force a particular source port in your `--to-source`?  That is probably wrong, I suggest removing the port
Comment: That did it! I dropped the port and everything appears to work perfectly. You're right, the ping itself didn't work, although it still let me know if it would resolve DNS. I also added a policy for ICMP and even that is working now.

IPTables and SNAT for just two ports


Finding inverse laplace of a rational polynomial function

Question: I've been looking at this problem for a few hours now and can't figure out a way to solve it.  Does anyone have any suggestions? Thanks for any help.
$$\mathscr{L}^{-1}\{\frac{(2s^2+9s+11)}{(s^3+5s^2+9s+5)}\}$$
Answer: Hint: Do a partial fraction expansion, yielding:
$$\mathcal{L}^{-1}\left({\dfrac{2s^2+9s+11}{s^3+5s^2+9s+5}} \right) = \mathcal{L}^{-1} \left( \dfrac{2}{s+1} + \dfrac{1}{s^2 + 4 s + 5}\right)$$
This reduces to:
$$\mathcal{L}^{-1} \left(\dfrac{2}{s+1} + \dfrac{1}{(s-(-2))^2 + 1^2}\right)$$
Now, use a Table of Laplace Transforms or use the definitions to find the inverse.
Comment: You are very welcome! Regards
Comment: @Amzoti: Have a very colorful slumber to night. Thanks.
Comment: Everything the OP needs, all in one post! TU w/G! +
Comment: I just noted my failure to actually click on the uparrow! Glad I noticed, as I missed your comment! Now corrected!


A question regarding probablity in basketball - Shoot the 2 to Tie or the 3 to Win?

Question: I recently read an old post regarding this question and have my doubt about the author's conclusion. You can find the original post here if you'd like to read the whole story.
[Original Post]
I would briefly state the question here:
At almost the end of the basketball game, there were only a few seconds left and your team had the ball. Your team was down by two and, you, as the coach, faced the choice to ask your player to go for a two-pointer to tie and then try to win in overtime, or ask them to try to make a last-second three-pointer to win the game.

The probability for making 2-point is 45%.
The probability for making 3-point is 33%.
The chance of either team winning in overtime is 50%.

The conclusion the author drew was that the three-pointer has higher chance to "win" because the probability for the team make a two-pointer and then winning in overtime is 22.5%, which is smaller than 33%, shot a three-pointer to win.
I found it's interesting because at first, I believe that the math here is fine for two-pointer to tie and then went for the overtime. The chance for that scenario is 22.5%, same as the author perceived.
However, considering that taking the three-pointer would have 67% chance lost the game, but taking the two-pointer the chance was 55%. After achieving a tie scenario by making a two-pointer, the chance to win would be 50%, which looks a good advice to me. I know this way I treat the overtime winning probability independently.
So here is the question, is it ok for me to look at the case this way? Is really a good advice based on the calculated probability to take the three-pointer to win, or should we try a two-pointer to tie and seek for 50% win scenario? What is the appropriate way to use probability helping on deciding a situation like this?
Thank you for your answering.
Comment: Ask yourself this: Which is better: (i) winning (ii) having a 50% chance of winning?
Comment: I don't understand why the down-vote. Did I ask the question in a wrong place? or using a wrong format? Asking a question here seems intimidating?
Comment: We were not meant to understand downvotes. Here it could be that you asked a question that it seems you really already know the answer to...
Answer: If you shoot the two point shot the chance of losing is $55\%$ that you miss the shot plus $\frac 12 \cdot 45\%$ that you hit the shot and lose in overtime.  This adds up to $77.5\%$.  As this is greater than the $67\%$ chance of losing if you shoot the three pointer, you should shoot the three.  This is just looking at the complementary event to winning, so it should give the same answer.  You need to add the two different ways to lose for the two point shot.
Comment: Omg. My probability knowledge is really getting rusty. Thank you very much for explaining.


Non-blocking TCP buffer issues

Question: I think I'm in a problem. I have two TCP apps connected to each other which use winsock I/O completion ports to send/receive data (non-blocking sockets).
Everything works just fine until there's a data transfer burst. The sender starts sending incorrect/malformed data.
I allocate the buffers I'm sending on the stack, and if I understand correctly, that's a wrong to do, because these buffers should remain as I sent them until I get the "write complete" notification from IOCP.
Take this for example:
void some_function()
{
    char cBuff[1024];

    // filling cBuff with some data

    WSASend(...); // sending cBuff, non-blocking mode

    // filling cBuff with other data

    WSASend(...); // again, sending cBuff

    // ..... and so forth!
}

If I understand correctly, each of these WSASend() calls should have its own unique buffer, and that buffer can be reused only when the send completes.
Correct?
Now, what strategies can I implement in order to maintain a big sack of such buffers, how should I handle them, how can I avoid performance penalty, etc'?
And, if I am to use buffers that means I should copy the data to be sent from the source buffer to the temporary one, thus, I'd set SO_SNDBUF on each socket to zero, so the system will not re-copy what I already copied. Are you with me? Please let me know if I wasn't clear.
Comment: First of all, on Windows, asynchronous I/O is distinct from non-blocking I/O.

Secondly, can you show in your code how you are using I/O completion ports? You're missing some very relevant parts of this equation.

Finally, disabling socket buffering is not recommended when using Windows sockets. See http://msdn.microsoft.com/en-us/magazine/cc302334.aspx
Comment: "nRet = WSASend(this->m_ClientSock, &mov->DataBuf[0], 1, NULL, dwFlags, (OVERLAPPED *) mov, NULL);". That's the real sending I'm using. As you can guess Aaron, I use GetQueuedCompletionStatus() later to get the result of this operation (unless WSASend() failed).
Answer: Take a serious look at boost::asio. Asynchronous IO is its specialty (just as the name suggests.) It's pretty mature library by now being in Boost since 1.35. Many people use it in production for very intensive networking. There's a wealth of examples in the documentation.
One thing for sure - it take working with buffers very seriously.
Edit:
Basic idea to handling bursts of input is queuing.

Create, say, three linked lists of pre-allocated buffers - one is for free buffers, one for to-be-processed (received) data, one for to-be-sent data.
Every time you need to send something - take a buffer off the free list (allocate a new one if free list is empty), fill with data, put it onto to-be-sent list.
Every time you need to receive something - take a buffer off the free list as above, give it to IO receive routine.
Periodically take buffers off to-be-sent queue, hand them off to send routine.
On send completion (inline or asynchronous) - put them back onto free list.
On receive completion - put buffer onto to-be-processed list.
Have your "business" routine take buffers off to-be-processed list.

The bursts will then fill that input queue until you are able to process them. You might want to limit the queue size to avoid blowing through all the memory.
Comment: I wouldn't say "wealth of examples" (: But yes, I've been wondering maybe I'm just "re-inventing" the wheel here and I better use ASIO. The question is if ASIO can handle a burst of data to be sent (and received). I'll probably have to write a mini-test client/server apps just to check that.... and of course, if you (or anyone else here) know the answer already or can give some pointers - I'd be EXTREMELY grateful!
Comment: Hmm, compared to other docs I've seen - yes, 73 distinct examples is *a lot*.
Comment: Thanks Nikolai I appriciate your support here. Well, I already have a to-be-processed queue. Also a free-pre-allocated-buffers queue. I do not have a to-be-sent queue, and that's because, and correct me if I'm wrong, I may post many "send" operations at once, and let the transport layer (winsock) really send them in the posting order, considering the ACKs it gets from the remote machine. Correct, or not? Tests show it's incorrect, and that's when I'm starting to question the whole "scalability" part of IOCP!
Comment: Just added: look at the bottom lines at the 'buffers' link you've provided; I quote: 'When you call an asynchronous read or write you need to ensure that the buffers for the operation are valid until the completion handler is called.'. So, how do you ensure that? For example, I know for sure that my "read" buffers are valid - never deallocated (app's life time, one per connection) and never used by anyone, except when a read operation is complete.
Comment: I also, as mentioned already, have "write" buffers which I post to winsock, and they are being pooled back only when the "write completed" notification has been arrived.
Comment: By the way, if I'm gonna have to pool these buffers with ASIO too then it gives me nothing new. What can I do, re-invented the wheel already (:
Comment: Well, I'm not a Windows guy, so can't comment on IOCP - but if the documentation doesn't explicitly say that async sends are done in-order, don't rely on it, do your own. Also if you use threads, all bets are off on the ordering - the outbound queue is a necessity.
Comment: So far so good, yet how would I determine the amount I can send the other side at a given time without flooding it? I mean, how do I know what is the limit to send at a time so that I will only queue the next send request(s)? Do I have to manually set it? Is there some indication? Some hint the receiver would give me?
Comment: TCP will rate-limit the sender. You don't have to worry about it.
Comment: Nikolai thank you very much. I understand now, yet I'm not sure how to get down to details. I've posted another question ( http://stackoverflow.com/questions/3034047/limiting-tcp-sends-with-a-to-be-sent-queue-and-other-design-issues ) and you're more than welcome to follow it and contribute your expertise. Thank you again.
Answer: I don't think it is a good idea to do a second send before the first send is finished.
Similarly, I don't think it is a good idea to change the buffer before the send is finished.
I would be inclined to store the data in some sort of queue.  One thread can keep adding data to the queue.  The second thread can work in a loop.  Do a send and wait for it to finish.  If there is more data do another send, else wait for more data.
You would need a critical section (or some such) to nicely share the queue between the threads and possibly an event or a semaphore for the sending thread to wait on if there is no data ready.
Comment: "I don't think it is a good idea to do a second send before the first send is finished" <<-- seem to be correct. Sadly, this gives a lot of overhead to the overall operation.
Answer:
Now, what strategies can I implement in order to maintain a big sack of such buffers, how should I handle them, how can I avoid performance penalty, etc'?

It's difficult to know the answer without knowing more about your specific design. In general I'd avoid maintaining your own "sack of buffers" and instead use the OS's built in sack of buffers - the heap.
But in any case, what I would do in the general case is expose an interface to the callers of your code that mirror what WSASend is doing for overlapped i/o. For example, suppose you are providing an interface to send a specific struct:
struct Foo
{
   int x;
   int y;
};

// foo will be consumed by SendFoo, and deallocated, don't use it after this call
void SendFoo(Foo* foo);

I would require users of SendFoo allocate a Foo instance with new, and tell them that after calling SendFoo the memory is no longer "owned" by their code and they therefore shouldn't use it.
You can enforce this even further with a little trickery:
// After this operation the resultant foo ptr will no longer point to
// memory passed to SendFoo
void SendFoo(Foo*& foo);

This allows the body of SendFoo to send the address of the memory down to WSASend, but modify the passed in pointer to NULL, severing the link between the caller's code and their memory. Of course, you can't really know what the caller is doing with that address, they may have a copy elsewhere.
This interface also enforces that a single block of memory will be used with each WSASend. You are really treading into more than dangerous territory trying to share one buffer between two WSASend calls.
Comment: he heap is exactly what I'm about to use, as it seems. As said, currently I send a buffer which is on the sending thread's stack, and it doesn't work well. Using new/delete is a real problem when having thousands of WSASend() calls in a second, so, I'll pool them. Get from the pool when needed, and release when needed. As for Foo struct, I'll flag it if it's being used or not, so, no problem with that.
Comment: What really bothers me is the fact that I'll need some sort of mutual exlusion mechanism in order to manage that pool of buffers, which slows things down. By the way, the heap also has a mutual exlusion mechanism. "You are really treading into more than dangerous territory trying to share one buffer between two WSASend calls" <<-- that's what I was thinking and this is why I posted this question.

Non-blocking TCP buffer issues


How to improve efficiency and time-complexity of AIO Cloud Cover solution

Question: Sorry for the noob question, but is there a less time expensive method to iterate through the input list, as upon submission I receive timeout errors. I tried changing the method of checking for the minimum answer by appending to a list and using min function, but as expected that didn't help at all.
Input:
6 3
3
6
4
2
5

Solution:
with open("cloudin.txt", "r") as input_file:
    n, covered = map(int, input_file.readline().split())
    ls = [None for i in range(100005)]
    for i in range(n-1):
        ls[i] = int(input_file.readline().strip())
ans = 1000000001
file = open("cloudout.txt", "w")
for i in range(n-covered):
    a = 0
    for j in range(covered):
        a += ls[i+j]
    if a < ans:
        ans = a
file.write(str(ans))

output:
11

https://orac2.info/problem/aio18cloud/

Note: Blue + White indicates timeout
Comment: Please provide the problem statement inside the question as opposed to including a link (since links can rot over time).
Comment: While IO can often be a cause for performance issues, another frequent cause is algorithms with poor complexity. You're using a quadratic time algorithm for a problem expecting linear time (computing the minimum sum subarray of a fixed size).
Comment: Thank you @kcsquared how would I do that? I'm unable to construct a linear time solution.
Comment: The name of the problem is 'range sum query'— preprocess an array, so that given a range in an array, you can compute its sum in constant time. One way to do this is with prefix sums. I'd recommend searching for 'range sum query' and similar. Also, BrokenBenchmark made a useful suggestion :)
Answer: The core logic of your code is contained in these lines:
ans = 1000000001
for i in range(n-covered):
    a = 0
    for j in range(covered):
        a += ls[i+j]
    if a < ans:
        ans = a

Let's break down what this code actually does. For each closed interval (i.e. including the endpoints) [left, right] from the list [0, covered-1], [1, covered], [2, covered+1], ..., [n-covered-1, n-2] (that is, all closed intervals containing exactly covered elements and that are subintervals of [0, n-2]), you are computing the range sum ls[left] + ls[left+1] + ... + ls[right]. Then you set ans to the minimum such range sum.
Currently, that nested loop takes O((n-covered)*covered)) steps, which is O(n^2) if covered is n/2, for example. You want a way to compute that range sum in constant time, eliminating the nested loop, to make the runtime O(n).
The easiest way to do this is with a prefix sum array. In Python, itertools.accumulate() is the standard/simplest way to generate those. To see how this helps:
Original Sum: ls[left] + ls[left+1] + ... + ls[right]

can be rewritten as the difference of prefix sums
   (ls[0] + ls[1] + ... + ls[right])
 - (ls[0] + ls[1] + ... + ls[left-1])

which is prefix_sum(0, right) - prefix_sum(0, left-1)
where are intervals are written in inclusive notation.

Pulling this into a separate range_sum() function, you can rewrite the original core logic block as:
prefix_sums = list(itertools.accumulate(ls, initial=0))

def range_sum(left: int, right: int) -> int:
    """Given indices left and right, returns the sum of values of
    ls in the inclusive interval [left, right].
    Equivalent to sum(ls[left : right+1])"""

    return prefix_sums[right+1] - prefix_sums[left]

ans = 1000000001
for i in range(n - covered):
    a = range_sum(left=i, right=i+covered-1)
    if a < ans:
        ans = a

The trickiest part of prefix sum arrays is just avoiding off-by-one errors in indexes. Notice that our prefix sum array of the length-n array ls has n+1 elements, since it starts with the empty initial prefix sum of 0, and so we add 1 to array accesses to prefix_sums compared to our formula.
Also, it's possible there may be an off-by-one error in your original code, as the value ls[n-1] is never accessed or used for anything after being set?


Dropdown not binding data fetch from two tables

Question: I have a dropdown list, and that list fetch it from database.But it's not binding to the dropdownlist.

In here the condition is 1 book have many BookTypes.

Here i have paste the codings.
  public List<BookModel> GetBooks(string bookId)
    {

            DatabaseProviderFactory factory = new DatabaseProviderFactory();
            Database db = factory.Create("DefaultConString");
            con.Open();

            String query = @"Select B.BookName,B.Author,BT.BookType
                             FROM VW_Book B
                             INNER JOIN VW_BookType BT
                             ON B.BookId = BT.BookId
                             WHERE BookId =: BookId";

           cmd = db.GetSqlStringCommand(query);
           db.AddInParameter(cmd, "BookId", DbType.String,bookId);

           var ds = db.ExecuteDataSet(cmd);

           var da = ds.Tables[0].AsEnumerable().Select(d => new StaffModel {
               bookname= d.Field<string>("BookName"), //From Book table
               authorname = d.Field<string>("AuthorName"), //From Book table
               booktype = d.Field<string>("BookType"); // From BookType table
           });
           var lst = da.ToList();
           return lst;

      }

My Controller
  [HttpPost]
    public string GetBookDetails(string bookId)
    {

           BookBusiness bk = new BookBusiness();
            List<BookModel> _book = bk.GetBookDetails("50000").ToList();
            return JsonConvert.SerializeObject(_book); //

    }

My Model
    Public class BookModel
{
public string BookId {get;set;}
public string BookName {get;set;}
public string BookType {get;set;}
}

Ajax Call
        $.ajax({
        url: '@Url.Action("GetBookDetails", "Books")',
        type: "POST",
        async: false,
        data: JSON.stringify({ BookId: BookId}),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (_book) {
            debugger;
            $('#bookdropdown').empty();

            $.each(_book, function () {
                $("#bookdropdown").append(
                    $('<option/>', {
                        value: this,
                        html: this
                    })
                );
            });
        }
    });

But the issue here i face is that Data not bind to the dropdownlist.
data comes like [{"HarryPotter"}] like json format.
Comment: what is the response your ajax call receiving from the `GetBookDetails` call ? Can you do a `console.log(_book)` inside the success event and paste the stringified version in your question ?
Comment: And your `GetBookDetails` method returns  a string ? You should return an array of items and loop through that in your client side code.
Comment: Something is amiss (in addition to what @Shyju has brought up). The `GetBooks` method signature returns a `List`, however, the implementation actually returns a `List`. Further, the ajax query is looking for a BookId, but the `GetBooks` method doesn't even set a BookId.
Answer: You ajax method expects json, so you need to change the controller method to
[HttpPost]
public JsonResult GetBookDetails(string bookId)
{
    BookBusiness bk = new BookBusiness();
    List<BookModel> _book = bk.GetBookDetails("50000").ToList();
    return Json(_book);
}

However its unclear which of the properties of BookModel you want in the view. Only 2 properties need to be returned, one for assigning to the options value attribute, and one for the options display text (and if they are the same, then only one property needs to be returned). There is no point sending additional data across the wire which is never used so assuming you want the BookId and BookName properties, the the controller method would be
[HttpPost]
public JsonResult GetBookDetails(string bookId)
{
    BookBusiness bk = new BookBusiness();
    var books = bk.GetBookDetails("50000").Select(b => new
    {
        value = b.BookId,
        text = b.BookName
    };
    return Json(books);
}

Then your script will be
var dropdown = $("#bookdropdown"); // cache it
$.ajax({
    url: '@Url.Action("GetBookDetails", "Books")',
    type: "POST",
    data: { BookId: BookId }, // no need to stringify and add contnetType
    dataType: "json",
    success: function (books) {
        debugger;
        dropdown.empty();
        $.each(books, function(index, item) {
            dropdown.append($('<option><option/>').val(item.value).text(item.text));
        });
    }
});

Side note. The code you have shown will not compile. Your GetBooks() method returns List<BookModel> but its code is creating List<StaffModel>. In addition the controller is calling a method named GetBookDetails(), not GetBooks() so I assume you have shown the wrong code. In addition you pass a parameter bookId to the controller but never use it.
Answer: Try this.

$.each( _book, function( i, val ) {
 $("#bookdropdown").append(
                    $('<option/>', {
                        value: val ,
                        text: val
                    });

});


How to automatically add http prefix to links in a form?

Question: I am trying to come up with a solution to fix the D8 Link module to allow URLs like example.com (the most common use case, imho). I was thinking it would be simple enough to modify the submit value during a custom validate function; but regardless of what I set the value to it still validates on the original value.
In a form alter I have done this:
$form['field_linktest']['widget'][0]['#element_validate'][] = '_fix_link_field_value';

and then in that validate function I set the url uri value:
function _fix_link_field_value(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = $form_state->getValue('field_linktest');
  $url[0]['uri'] = 'http://example.com';
  $form_state->setValue('field_linktest', $url);
}

But I still get the error: Manually entered paths should start with one of the following characters: / ? #
Comment: Best not to call other people's ideas silly. We're all working through text here, and we don't know the requirements of your system. It's not going to endear some people to want to help you further.
Comment: @jaypan, technically i wasn't calling NS's idea silly.. i was asking if he was suggesting the solution that the people on d.org seem to be suggesting.. and their idea of UX for this is pretty silly. But point taken. NS, i had tried just removing the validate and that didnt seem to do anything.. but i'll try your idea of just placing mine ahead. Thanks.
Comment: You need to also remove the original validation handler.
Comment: Try using `//example.com` and it should auto go to http if https isn't available.
Comment: @ns.. Do you mean adjust the input in my validate to add // or do you mean type it in the form? Because the 2nd idea is silly. Sorry, but that seems to be the approach on the various issues re: this on d.org; but who would ever enter a url like that?
Comment: @jaypan, yes, that's what i was thinking but i wasn't sure where that was. Do you mean in the original form_alter, is this in the #element_validate for that field? I think i tried that with no luck; but will have another look. Thanks.
Comment: i tried this in form alter:   unset($form["field_linktest"]["widget"][0]["uri"]["#element_validate"]); and i now get a different error: The URL google.com is not valid. where this is the value i enter in the form; not the value i set in the validate function.
Comment: Indeed add a validate function that runs before the default link validate, which removes the `http:` or `https:` part, and adds the `//` part if it's not there already. You can add it to the validate array as first value with `array_unshift($form['field_linktest']['widget'][0]['#element_validate'], '_fix_link_field_value');`
Comment: @NoSssweat, still not quite. I think the issue is that validate and submit in forms are no longer callbacks in D8 that i can simply add to. The existing #element_validate looks like this: 0 = {array} [2]
 0 = "Drupal\link\Plugin\Field\FieldWidget\LinkWidget"
 1 = "validateUriElement"
Comment: I am sure this is wrong; but only thing i have found to work so far: $form['field_linktest']['widget'][0]['#element_validate'][] = '_fix_link_field_value';
  array_unshift($form['field_linktest']['widget'][0]['uri']['#element_validate'][0], '_fix_link_field_value');
Comment: The `$form[$field_name]['widget'][0]['#element_validate'][] = '_fix_link_field_value';` line shouldn't be necessary when using **[array_unshift()](https://www.w3schools.com/php/func_array_unshift.asp)**. Test it again without it and flush cache just in case.
Answer: Thanks to those who provided answers; I couldn't quite get those to work, but they got me to my answer. My final solution ended up being this:
function my_module_form_alter(&$form, $form_state, $form_id) {
  // add a global validator to fix stupid Link fields - add to all Link fields
  // only worry about entity forms
  if (isset($form['#entity_type'])) {
    $bundle = $form_state->getFormObject()->getEntity()->bundle();
    $entity_type = $form['#entity_type'];
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);
    foreach ($fields as $field) {
      if ($field->getType() == 'link') {
        $field_name = $field->getName();
        $form[$field_name]['widget'][0]['#element_validate'][] = '_fix_link_field_value';
        array_unshift($form[$field_name]['widget'][0]['uri']['#element_validate'][0], '_fix_link_field_value');
        $form[$field_name]["widget"][0]["uri"]["#description"] = t('This must be an external URL such as http://example.com, https://example.com, example.com, www.example.com.');
      }
    }
  }
}

and then the validator/fixer:
function _fix_link_field_value(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = $form_state->getValue($element['#parents'][0]);
  $urlOriginal = $url[0]['uri'];
  if (!$urlOriginal) return;

  if (!stristr($url[0]['uri'], '//')) {
    $url[0]['uri'] = 'http://' . $url[0]['uri'];
  }
  if (filter_var($url[0]['uri'], FILTER_VALIDATE_URL) === FALSE) {
    $form_state->setErrorByName($element['#parents'][0], t('%url is not a valid URL format. This must be in a format like
      http://example.com, https://example.com, example.com, www.example.com.',
      ['%url' => $urlOriginal])
    );
  }
  else {
    $form_state->setValue($element['#parents'][0], $url);
  }
}

The array_unshift isn't right but doing an unset() didn't seem to cut it. I am sure all this is doing is preventing the original validator from running; which is good as the error message it generates is stupid. Not sure why 5 years into D8 they still don't have this fixed.
Also, this will need an extra loop if you are dealing with multi-valued fields.


4-point-like central finite difference for second partial derivatives

Question: To numerically approximate the second partial derivatives, and get the Hessian matrix, one may use "2-point" central finite difference formulas:
$$H_{xy}(x,y) \approx \frac{f(x+h,y+h)-f(x+h,y-h)-f(x-h,y+h)+f(x-h,y-h)}{4h^2}\tag{1}$$
for the off-diagonal elements, and
$$H_{xx}(x,y) \approx \frac{f(x+h,y)-2f(x,y)+f(x-h,y)}{h^2}\tag{2}$$
formulas for the diagonal elements. (I am simplifying here, this generalizes for any number of dimensions, and uses the same displacement for all variables)
It may be sometimes desirable to further improve the accuracy of these central difference formulas. For univariate functions this is conveniently done via the 4-point formula (aka. 5-point stencil in one dimension):
$$f''(x)     \approx \frac{-f(x+2 h)+16 f(x+h)-30 f(x) + 16 f(x-h) - f(x-2h)}{12 h^2}$$
However, I have been unable the find the "4-point" equivalent of $(1)$ and $(2)$ anywhere online.
Answer: For $H_{xx}$ it would be the same as the univariate $f''(x)$ you've posted, except for the extra argument for the other variable. $H_{yy}$ has the same form as $H_{xx}$ but with $x$ and $y$ swapped. The following assumes same step size for each dimension:
$$
\begin{aligned}
H_{xx}(x,y) &\approx \frac{-f(x+2h,y)+16f(x+h,y)-30f(x,y)+16f(x-h,y)-f(x-2h,y)}{12h^2} \\
H_{yy}(x,y) &\approx \frac{-f(x,y+2h)+16f(x,y+h)-30f(x,y)+16f(x,y-h)-f(x,y-2h)}{12h^2} \\
\end{aligned}
$$
For $H_{xy}$ it is
$$
H_{xy(x,y)} \approx
\frac{
\begin{array}{c}
-f(x+2h,y+2h)+16f(x+h,y+h)\\
+f(x+2h,y-2h)-16f(x+h,y-h)\\
+f(x-2h,y+2h)-16f(x-h,y+h)\\
-f(x-2h,y-2h)+16f(x-h,y-h)\\
\end{array}
}{48h^2}
$$

In case you're wondering where the formula comes from, you can derive it using Taylor series expansion.
$$
f(x+h)=f(x)+\frac{f'(x)}{1!}h+\frac{f''(x)}{2!}h^2
+\frac{f'''(x)}{3!}h^3+\cdots \tag{1}\label{eq1}
$$
Substituting $h\to -h$ inverts the sign of each odd term in $\eqref{eq1}$
$$
f(x-h)=f(x)-\frac{f'(x)}{1!}h+\frac{f''(x)}{2!}h^2
-\frac{f'''(x)}{3!}h^3+\cdots \tag{2}\label{eq2}
$$
Adding $\eqref{eq1}$ and $\eqref{eq2}$ together eliminates the odd terms
$$
f(x+h)+f(x-h)=2f(x)+2\frac{f''(x)}{2!}h^2
+2\frac{f^{(4)}(x)}{4!}h^4+\cdots \tag{3}\label{eq3}
$$
Rearranging the terms, we arrive at
$$
\begin{aligned}
f''(x)&=\frac{f(x+h)-2f(x)+f(x-h)}{h^2}-2\frac{f^{(4)}(x)}{4!}h^2+\cdots\\
&=\frac{f(x+h)-2f(x)+f(x-h)}{h^2}+O(h^2)
\end{aligned} \tag{4}\label{eq4}
$$
The terms from $f^{(4)}$ onwards are gathered into the truncation error term $O(h^2)$. This formulation is second-order accurate.
Substituting $h\to 2h$ in $\eqref{eq3}$ we get
$$
\begin{aligned}
f(x+2h)+f(x-2h)&=2f(x)+2\frac{f''(x)}{2!}(2h)^2
+2\frac{f^{(4)}(x)}{4!}(2h)^4+\cdots\\
&=2f(x)+8\frac{f''(x)}{2!}h^2
+32\frac{f^{(4)}(x)}{4!}h^4+\cdots
\end{aligned}\tag{5}\label{eq5}
$$
Combining $\eqref{eq3}$ and $\eqref{eq5}$ with suitable coefficients we can eliminate $f^{(4)}$ term
$$
16\eqref{eq3}-\eqref{eq5}=30f(x)+12h^2f''(x)-\frac{2}{15}h^6f^{(6)}(x)+\cdots  \tag{6}\label{eq6}
$$
which, after rearranging, we get a fourth-order accurate formulation for $f''$
$$
\begin{aligned}
f''(x)&=\frac{-f(x+2h)+16f(x+h)-30f(x)+16f(x-h)-f(x-2h)}{12h^2}-\frac{2}{15}f^{(4)}(x)h^4+\cdots\\
&=\frac{-f(x+2h)+16f(x+h)-30f(x)+16f(x-h)-f(x-2h)}{12h^2}+O(h^4)
\end{aligned}\tag{7}\label{eq7}
$$
For bivariate function $f(x,y)$ the series expansion need to be applied separately for each variable. Otherwise, the line of thinking is the same: we expand the function on some points around $(x,y)$ and find a combination of coefficients for each point that will eliminate as much error terms as possible. The order of accuracy for the formula of $H_{xy}$ given in the question is $O(h^2)$, while the one in this answer is $O(h^4)$.
It is interesting to note that a different formulation exists for $H_{xy}$ which reuses $H_{xx}$ and $H_{yy}$
$$
H_{xy}=\frac{f(x+h,y+h)-2f(x,y)+f(x-h,y-h)}{2h^2}-\frac{1}{2}H_{xx}-\frac{1}{2}H_{yy}+O(h^2)\tag{8}\label{eq8}
$$
Another one is
$$
H_{xy}=\frac{-f(x+h,y-h)+2f(x,y)-f(x-h,y+h)}{2h^2}+\frac{1}{2}H_{xx}+\frac{1}{2}H_{yy}+O(h^2)\tag{9}\label{eq9}
$$
while the 5-point stencil version is
$$
H_{xy}=\frac{\begin{array}{l}-f(x+2h,y+2h)+16f(x+h,y+h)\\-30f(x,y)\\
+16f(x-h,y-h)-f(x-2h,y-2h)\end{array}}{24h^2}-\frac{1}{2}H_{xx}-\frac{1}{2}H_{yy}+O(h^4)\tag{10}\label{eq10}
$$
and
$$
H_{xy}=\frac{\begin{array}{l}f(x+2h,y+2h)-16f(x+h,y+h)\\+30f(x,y)\\
-16f(x-h,y-h)+f(x-2h,y-2h)\end{array}}{24h^2}+\frac{1}{2}H_{xx}+\frac{1}{2}H_{yy}+O(h^4)\tag{11}\label{eq11}
$$
(in this case $H_{xx}$ and $H_{yy}$ need to be formulated using 5-point stencil as well) These formulations have the same order of accuracy, but the contents of the $O(h^2)$ and $O(h^4)$ are different, and may have slightly larger error. The benefit of using this alternative formulation is the reduced number of points required to calculate the Hessian (9 points reduced to 7 for second order, 17 points reduced to 13 points for fourth order accuracy).


stop exceuting other threads while cache refresh

Question: I have a functionality where need to run a job in background after defined time interval.
for this i used ScheduledExecutorService to execute the thread after certain time interval.
To store cache data i am using concurrent hash map.
ConcurrentHashMap
while the refresh is happening the other thread in app checks for cache and overwrites the map data.i have tried using synchroized but it didn't work.basically what i want to achieve is pause other process while cache refresh is happening.
Comment: Why is `synchronized` not working? Also you should show some code of what you have tried?
Comment: You do not need to pause the thread, in my opinion - a simple semaphore should do the trick and yes, that is synchronized.
Answer: You can use ReentrantReadWriteLock to synchronize your read and write operations. In ReentrantReadWriteLock, multiple threads are allowed read & only one thread is allowed to write to your shared resource which is map in your case. If a thread is writing to your shared resource then other threads will wait for read/ write requests.
<code>ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

readWriteLock.readLock().lock();

    // multiple readers can enter this section
    // if not locked for writing, and not writers waiting
    // to lock for writing.

readWriteLock.readLock().unlock();

readWriteLock.writeLock().lock();

    // only one writer can enter this section,
    // and only if no threads are currently reading.

readWriteLock.writeLock().unlock();
</code>
Hence while your cache is refreshing no other thread will be allowed to read/write to your map but when no thread is writing then multiple threads will be allowed to read map.


Creating a wrapper for a C# library in Python

Question: Main goal: Create a wrapper for a C# library, which can be used in Python (2.6).
UPDATE: Now, I have updates to the method I am using, which is however not working well.
The code for the simple C# class library:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace Test
{
    [Guid("8F38030D-52FA-4816-B587-A925FDD33302")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _TestClass
    {
        [DispId(1)]
        string Eureka();
    }

    [Guid("BC3F6BB3-42C4-4F30-869A-92EA45BF68D2")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("Test.TestClass")]
    public class TestClass : _TestClass
    {
        public TestClass()
        {
        }

        public string Eureka()
        {
            return "Hudson, we no longer have a problem!";
        }
    }
}

enter code here

In addition to this, I went into Project Properties and enabled the setting: Register for COM interop.
Also, in order to make the class library available to COM, I ticked Signing -> Sign the Assembly, and gave it a strong key.
Furthermore, whenever I compile, I unregister the old version with:
regasm -u Test /tlb:Test

And I register it with:

regasm Test.dll /tlb:Test

My problem is then, in the Python environment, I have the following main.py, which is not working:
import win32com.client

o = win32com.client.Dispatch("Test.TestClass")

The error is unforgiven.
thank you in advance!
Comment: possible duplicate of [How to load a C# dll in python?](http://stackoverflow.com/questions/2077870/how-to-load-a-c-dll-in-python)
Comment: I've read that, and it is the same topic, however I am not figuring out my problem though.
Answer: A alternative would be if you you use Python for .NET. There seem to be alpha releases for Windows CPython 2.6 and 2.7 available. You could run simply:
import clr
clr.AddReference("Your.Assembly.Name")
import Test
test = Test.TestClass()
print test.Eureka()

Comment: I see your answer, and I get that it is a valid solution, however I would like to make my library COM visible, because that will enable me to use it within PHP and other programming languages that has COM support.


Are there any infinite series which we know converges but do not know what it converges to?

Question: We have many ways of determining whether a series converges or diverges and we also have many series that we don't know the convergence there of. However, are there any series which we do know converges, but not what it converges to?
Comment: Arguably, $1 + \frac{1}{1!} + \ldots$, the series for $e$, converges but we do not know what it converges to. We know it's a number between $2$ and $3$, indeed, between $2.718$ and $2.719$, but as for *knowing* it? I'd say that we don't. On the other hand, we sure know a lot **about** it. If you want a better answer than that, you're going to have to say what "knowing" means, which isn't exactly mathematics.
Comment: There are uncountable many real numbers. The decimal fractions representing them can be considered as convergent series converging to them.
Comment: Let me add that what we "know" is closely linked to what we're familiar with. The Greeks didn't know about irrationals for some time, and regarded them as horrible monsters. (Presumably they hadn't been able to prove the irrationality of pi, or they've have had to reconsider.) The number $e$ is pretty weird...until you study calculus and work with it for a while, and then it's 'nice' and 'known', and we pick a new letter of the alphabet to reserve for it, like $\phi$ for the golden ratio.
Comment: I think an example would be:https://math.stackexchange.com/questions/3157371/does-this-have-a-known-closed-form
Answer: For example, take $e=1+\frac{1}{2!}+\frac{1}{3!}+\cdots.$ Now take some ridiculously big number, say $x:=3\uparrow\uparrow\uparrow \uparrow 3$ and try to evaluate $x\cdot e=x+\frac{x}{2!}+\frac{x}{3!}+\cdots$. While we know the answer is $xe$, to get the first digit is equivalent to finding the $x$'th digit of $e$, which is probably impossible given how big $x$ is.
Another example is (see Theorem 2 from On Equalities Involving Integrals of the Logarithm of the Riemann $\zeta$-Function and equivalent to the Riemann Hypothesis): take the non-trivial zeros of the Riemann zeta function: $\rho_k:=\sigma_k+it_k$. Prove that:
$$0=\sum_{\rho: \sigma_k\geq 1/2,t_k>0}\left(\frac{1}{\sigma_k^2+t_k^2}-\frac{1}{1/4+t_k^2}\right),$$
which is equivalent to the Riemann Hypothesis (notice the sum will be positive if the hypothesis is false). Note that the series must converge regardless.
Comment: Upvote for the second example. The first one doesn't really feel like a good example to me.
Comment: Hm. That is a valid answer, however I feel as though it is a bit... contrived (if that makes any sense?).


Will Data table sorting in C# and Order By sorting in SQL give the same result set?

Question: I want to know whether the Order By clause on Sql server and Datatable sorting will order the records in the same manner. I have tried both and found the records are ordered in different way. Can anyone clarify?
SELECT Top 10000
'Link' As [Link],
ODST.ID AS [ID],
ODST.Type1 AS [Type 1],
ODST.Type2 AS [Type 2],

COUNT(DISTINCT ODST.Col1) AS [Col 1],
COUNT(DISTINCT ODST.ID) AS [Col 2],
......
......
COUNT(DISTINCT ODST.Col11) AS [Col 11],
SUM(ODST.Col12) AS [Col 12],
.....
.....
SUM([Col35]) AS [Col 35]
FROM ABC ODST
WHERE id in
(Select id from
(select Top 10000 count(*) AS Line, id from ABC WHERE 1=1
group by id order by Line desc) t2) AND 1=1
GROUP BY ODST.id, ODST.Type1, ODST.Type2
ORDER BY ODST.Type1, ODST.Type2

I have used order by in the above query
The table which i am querying has million of records in it. It yields a result in an order and it is very slow in running
so we have decided to move the sorting part to c#. We have commented out the Order By from this query and returning the result to c#.
Getting the result in Dataset and trying to sort based on 2 columns.
Sorting code is
ds.Tables[0].DefaultView.Sort = "[Type 1],[Type 2] ASC";
ds1.Tables.Add(ds.Tables[0].DefaultView.ToTable());

It sorts the result in a different order
so, over all, i want to know whether both ordering works in same way or the other?
Comment: collation and culture make for very potent things...
Comment: Show your work please..
Comment: Show us your code which you have tried so far, please
Comment: Maybe you could show us two values which appear in opposite order?
Comment: please show what you have tried till now??
Comment: Did you find any of this helpful?
Answer: Basically it does not.
The SQL implementation of Order By can differ, since it is another library that performs the sorting.
In your datatable, or any kind of ORM (like entity framework), there can be some differences, because the objects can be converted to string, DateTime, (etc.).
The sorting performed in the .NET Framework will be based on the data type, usually through a IComparable interface. This might differ from the logic implemented in SQL. Although suppliers of these frameworks will try to keep things consistent, differences may occur.
You can see this happening (if it isn't already 'fixed') with entity framework.
If you query the database for a string with a .Contains somewhere, it is converted to a 'LIKE' in sql, which is likely to be case insensitive.
Perform this operation to a in memory C# List, it is likely to be case sensitive and, hence, might produce a different result.


Find the interest at the end of 30 years

Question: A sum of rupees 100 is invested at 8% per annum Simple Interset. Calculate the interest at the end of $1_{st}, 2_{nd}, 3_{rd} ....$ years. Is the sequence of interest an Arithmetic Progression. Find the interest at the end of 30 years.
Hint: Arithmetic Progression follows the rule of $a_n = a+(n-1)d$ where $n$ the term of the AP
My Problem: I am having problem in creating the Arithmetic Progression in this Question, because In this I am totally confused about concept.
Comment: You should get used to the idea of doing your own homework, or at the very least posting what you have tried so far so we know what you are struggling with.
Answer: Let's say you have 100 rupees at 8% a year:

At the end of the first year, the total interest is $100\cdot8\%$.
At the end of the second year, the interest is $100\cdot8\% +
   100\cdot8\%$

So, after $n$ years, you'll have a total interest owed as $n\cdot(100\cdot8\%)$.
Now, think about how much you would need to pay each year.

At the end of the first year, you'd pay $100 + 100\cdot8\%$ rupees.
At the end of the second year, you'd pay $100 + 100\cdot8\% + 100\cdot8\%$

Thus, at the end of the $n$th year, you'd pay $100 + 100\cdot8\%$ rupees.
$a$ is the starting value of the sequence, so $a=100$
$d$ is the "common difference" of the sequence--that's how much each term is greater than the last term.  Thus, $d = 100\cdot8\%=8$.
Thus, $$a_n=a + (n - 1)\cdot d$$
However, there is an offset--the sequence starts at 100, then 108, then 116, etc.  We want it to count 108, 116, 124, etc.  So, our altered series is $$a_n = a+n\cdot d$$
$$a_n=100+n\cdot8$$
Answer: Hint:  how much interest is there in one year?  For simple interest, that doesn't add to the principal, so the interest in each year is the same.


Is there a way to re-invoke #ajax on forms when the form itself is returned with ajax?

Question: I want to change the delete link on comments so that the delete confirmation is returned with Ajax and then the delete confirmation is executed with Ajax.
I have fixed the form so the delete confirmation at /comment/%cid/delete
so now the submit action is performed with ajax.
Here is the code I used to accomplish this:
function awesomesite_comments_form_comment_confirm_delete_alter(&$form, &$form_state, $form_id) {

  // Add the Ajax Submit Function
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'awesomesite_comments_ajax_delete',
    'progress' => false,
  );

}

function awesomesite_comments_ajax_delete($form, $form_state) {

  // Get rid of all of the messages that have been set
  drupal_get_messages();

  // Get the comment & node objects
  $comment = $form_state['comment'];

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Place the comment above the form
  $commands[] = ajax_command_remove('#comment-'.$comment->cid.', comment-'.$comment->cid.' + .comment');

  // Return the Ajax Commands Array
  return array('#type' => 'ajax', '#commands' => $commands);

 }

This works perfectly on the delete confirmation page, however, when I return the form with Ajax, the submit no longer is processed with Ajax and a standard page refresh takes place.
Here is the PHP code I have to for delivering the confirmation form via Ajax:
function awesomesite_comments_menu_alter(&$items) {
  $items['comment/%/delete/ajax'] = $items['comment/%/delete'];
  $items['comment/%/delete/ajax']['delivery callback'] = 'ajax_deliver';
  $items['comment/%/delete/ajax']['page callback'] = 'awesomesite_comments_ajax_confirm_delete_page';
}

function awesomesite_comments_ajax_confirm_delete_page($cid) {

  // Get the HTML of the detele page.
  $data = drupal_render(comment_confirm_delete_page($cid));

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Replace the HTML
  $commands[] = ajax_command_html('#comment-'.$cid.' + .comment', $data, array('effect' => 'fade'));

  return array('#type' => 'ajax', '#commands' => $commands);

}

And here is the Javascript I have for taking the "Delete" link on the comments and returning the form (from the callback above)
jQuery('a.ajax-link:not(.ajax-processed)').addClass('ajax-processed').each(function() {

        // Cret the element settings object
        var element_settings = {};

        // Get rid of the progress
        element_settings.progress = { 'type' : 'none' };

        // setup the click elements and add the href
        if (jQuery(this).attr('href')) {
            element_settings.url = jQuery(this).attr('href');
            element_settings.event = 'click';
        }

        element_settings.effect = 'fade';

        // Get the base
        var base = jQuery(this).attr('id');

        // Register the Ajax Request with Drupal
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);

    });

I believe what is happening is that Drupal is processing all the forms on the page for #ajax when the page is loaded, however, since the form is loaded via AJAX it isn't setting up the #ajax information (which I can confirm is present). How can you force Drupal to check for new forms after an Ajax request? Or am I missing something?
any help would be greatly appreciated!
Answer: I found the answer!
I simply was asking the wrong question. What I needed to do was re-attach the drupal behaviors with Drupal.attachBehaviors().
I added this code to my JavaScript code.
jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

Voilà! Everything works as it should.
Answer: To make things a bit more clear, for beginners like me, use it in this way:
(function($)  {

    $(document).ready(function(){

        ..the JS code here..

    });

jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

})(jQuery);

Clive and David, thank you SO much
Answer: I'd built a number of ajax forms before running into a problem like this, it was strange some ajax worked and other parts just didn't.
The answer I discovered after digging deep into ajax.js and the data structures returned by ajax calls was that ajax.js seemed to be dependent on one of two conditions.  Either your fapi ['#ajax'] enabled elements must be without any 'id' information, or they must provide both a fapi ['#id'] and a fapi ['#attributes']['id'].
Hopefully, for anyone running into this type of problem, can add this to the checklist to be sure.


Elements of odd order form a subgroup when the Sylow-$2$ subgroup is cyclic

Question: A problem which I've found quite difficult  it is the following:

Let $G$ be a group with order $2^n k$ with $k$ odd, and suppose there is an element of order $2^n$ (i.e. the Sylow-$2$ subgroup is cyclic). Prove that the elements of odd order in $G$ form a normal subgroup of order $k$.

One major difficulty is in $G$ not being abelian. I've seen one proof of it, which used induction on $n$ and the group action of $G$ on itself by multiplication, noting that a permutation $\lambda_g$ is odd iff $2^n$ divides the order of $g$.
However, I've not been able to find any other methods to prove it, even after learning more group theory than I had learned at the time. I thought about using the Sylow theorems, but that didn't result in anything.
Can anyone think of other ways to prove this result? Full proofs aren't necessary; any directions which are or could be fruitful are appreciated.
Comment: If you want an approach that uses some more group theory, the result follows directly from Burnside's transfer theorem, which states that if a $p$-Sylow subgroup is central in its normalizer then the group has a normal $p$-complement. That this is the case here follows from the normalizer/centralizer theorem.
Comment: [Here](https://math.stackexchange.com/a/1666740/11619) is the argument for a proof by induction. No wonder I had a deja vu -experience :-)
Comment: @TobiasKildetoft  Well, it's a very nice argument indeed!
Comment: The order of an element is preserved by conjugation.
Comment: Worth noting:  the product of two elements of odd order could have even order, so the set of elements of odd order is not necessarily a subgroup.
Comment: I don't think the problem is well posed.  As I say, the set of elements of odd order need not even be a subgroup (though it will always be preserved by conjugation).
Comment: @lulu In this case, the element of odd order really do form a subgroup.
Comment: @lulu that's why the condition that there exists an element of order $2^n$ is crucial; counterexamples if that is removed are easy to come by.
Comment: @TobiasKildetoft  You are correct.  I neglected the condition that there is an element of order $2^n$.
Comment: @TobiasKildetoft I hadn't heard of that theorem before - I'll be sure to look into that!
Comment: @JyrkiLahtonen Always hard to find those answers when they were given in a somewhat different context.
Comment: @JyrkiLahtonen Hmm, somehow I did not notice that it was an answer of mine (rather than your own) you had linked until it gained an upvote just now :)
Comment: @lulu If you mean the one in the linked answer then yes, I quite like it too. I had just apparently completely forgotten that I had given that answer.
Comment: Now that you just edited the question anyway, I should point out that the usual term for numbers that are not even is "odd" rather than "uneven".
Comment: @TobiasKildetoft How silly of me! Thanks!
Answer: Expanding on my comment, let us apply Burnside's transfer theorem to give a nice and conceptual proof of this (and some more general facts).
Theorem (Burnside): Let $G$ be a group with a $p$-Sylow subgroup $P$ satisfying $P\leq Z(N_G(P))$. Then $G$ has a normal subgroup $N$ of index $|P|$ (i.e. a normal $p$-complement).
Theorem (normalizer/centralizer): Let $H$ be a subgroup of a group $G$. Then $C_G(H)$ is a normal subgroup of $N_G(H)$ and $N_G(H)/C_G(H)$ is isomorphic to a subgroup of $\operatorname{Aut}(H)$.
I will lave the proofs as exercises. The second one is a good exercise while the first one is a terrible exercise as it is way too hard (the two proofs I know of either use a lot of stuff about transfer or uses a lot of character theory).
Anyway, using these, we can now show that if $p$ is the smallest prime dividing the order of the group (and in the case at hand, we are considering $p=2$ which will certainly be smallest), and if the $p$-Sylow subgroup is cyclic (which is precisely the assumption), then $G$ has a normal $p$-complement, meaning that the elements of order not divisible by $p$ form a normal subgroup.
To apply Burnside's result here, we need to show that $P\leq Z(N_G(P))$, but this is the same as saying that $N_G(P) = C_G(P)$, and we can show that by showing that $N_G(P)/C_G(P)$ is trivial.
Now, by the normalizer/centralizer theorem, this quotient is isomorphic to a subgroup of $\operatorname{Aut}(P)$, which we know has order $\varphi(|P|)$ since $P$ is cyclic. But this number is coprime to $\frac{|G|}{|P|}$, whereas the order of $N_G(P)/C_G(P)$ must divide $\frac{|G|}{|P|}$ since $C_G(P)$ contains $P$. This precisely implies that $N_G(P) = C_G(P)$ as we wanted, which finishes the proof.


Aplicação com frontend separado pode ser considerada monolítica?

Question: Pesquisei bastante mas não consegui sanar essa dúvida que tive ao estudar sobre aplicações monolíticas, quando backend e front estão isolados.
Tenho uma aplicação X que o frontend e o backend são separados. O backend é um projeto EJB modular (módulo EJB, módulo business, ...) feito em Java, e o frontend é apartado, feito por exemplo com React.
Sabendo que uma aplicação monolítica é quando todas as funcionalidades e códigos estão em um único processo:
1 - Eu posso chamar a aplicação X como um toda de monolítica? Tanto se o back e front estiverem em uma mesma máquina compartilhando os recursos delas, mas em processos separados, ou cada um em um servidor diferente? Acredito que não, mas não obtive a certeza.
2 - Posso chamar o meu backend de monolítico? Ou não, ao se referir a ele devo dizer que é apenas um projeto modular?
Comment: as literaturas (li no wiki, medium, docs.microsoft, etc) diz que uma aplicação monolítica contém "todas as camadas juntas", ou seja, segundo as literaturas **não** pode ser considerada monolítica, uma vez que tem front/back separados. Agora, se olhar para o back todo como uma aplicação, por exemplo ele tem endpoints, api ou outra interface que permita utilizá-lo, poderia ser entendido como uma aplicação, e o front end como outra, dai seria uma mononítico, mas não acho que vai ter uma resposta acertiva pra isso, mas se seguir o conceito, a literatura, não é uma aplicação monolítica
Answer: Depende do contexto que está usando o termo. Ele é usado de maneiras diferentes.
Não vou falar de todos contextos porque alguns não fariam sentido.
Distribuição de executável
Dentro do conceito original, e que parece ser o que a pergunta quer saber, pelo menos no começo, o fato de ter mais de um arquivo executável já não é monolítico. Ou seja, se você tem um monte de script em PHP, JavaScript, Python ou outras linguagens, ou DLLs ou algo semelhante geradas com Java, C#, C++, ou outras linguagens, então você já não tem um monólito. Veja mais em Qual a diferença de DLL e lib?.
Então ter algo rodando em camadas diferentes certamente não tem uma solução monolítica. Mas se considerar só uma parte aí pode ter um monólito só nessa parte, o que pode ocorrer fácil no backend e hoje é possível ter no frontend, ainda que pouco provável, ou perto do impossível, se considerar que você precisa de pelo menos um HTML e mais alguma coisa para ter algo útil.
Mas isso é até complicado classificar porque a ideia original só pensava em executável. Não sei se o conceito se aplica.
De qualquer forma rodar em processos separados ou não, define nada, porque o monólito tem a ver com o arquivo que é distribuído. Se tiver processos iguais mas existem arquivos diferentes não é monólito, e se tiver mais de um processo iniciado com o mesmo arquivo único, então é.
Rodar na mesma máquina não faz algo ser um monólito, mas se algo roda em outra certamente não é, porque já existem partes.
Padrão arquitetural
Se quer falar de monolítico em oposição à arquitetura de microsserviços, então sim, não só pode, como é. Ter uma parte frontend e backend não significa que essas partes são microsserviços.
Quase ninguém entende o que são microsserviços, e menos ainda as pessoas sabem que fazer isso é extremamente difícil e paga-se um preço muito alto, e por isso "ninguém" deve tentar fazer algo assim. O melhor que pode acontecer é a pessoa fazer executáveis separados e dizer que já está na moda, e ter pouco ou nenhum ganho, e a arquitetura continuar sendo monolítica. Mas pode fazer de fato microsserviços e cria um pesadelo para a vida.
Então precisa saber que conceito está falando. Se está falando em ser modular aí o assunto já é arquitetura, e mesmo algo modular ainda é um monólito, a não ser que os serviços separados, e portanto modulares, sejam completamente independentes, o que é muito difícil fazer, e quase ninguém precisa. Modular é algo bom na maioria dos cenários. Quando você tem um frontend e um backend separado alguma modularidade já obteve.
O frontend é completamente independente? Se for então ele é um serviço que não faz parte de um monólito. Provavelmente você tem algo híbrido que em determinada parte tem um serviço separado. E a relação entre as partes é muito simples, o que torna algo viável de ser gerenciado pela maioria dos programadores. Mas é difícil fazer algo ser completamente independente, e o será só em determinado momento e que faça sincronização quando for possível, o que é ainda mais difícil de fazer certo. Fuja dessas coisas. Opte pelo monólito a não ser que você seja um engenheiro muito experiente, tenha uma equipe enorme e uma necessidade extraordinária para adotar algo diferente. A maioria dos engenheiros que optam por microsserviços são só um pouco experientes, se eles fossem mais, não optariam (salvo raríssimas exceções).
Comment: Então, isso eu acho controverso. Porque raramente existem algo tão independentes que não depende de mais nada. A questão talvez passe por ele funcionar ainda que seja com limitações Outra interpretação é ele ter como dependência só o que fornece o que ele precisa sem nada a mais. Híbrido que é uma parte é de um jeito e outra parte é de outro jeito..
Comment: Muito obrigado pela explicação detalhada. Só não entendi essa parte:
"O frontend é completamente independente? Se for então ele é um serviço que não faz parte de um monólito. Provavelmente você tem algo híbrido que em determinada parte tem um serviço separado."

R: Ele necessita dos dados do backend. O frontend chama os serviços REST do backend, recebe o retorno em JSON, renderiza a página e retorna para o usuário. O que você quis dizer com ter algo híbrido nessa aplicação WEB?


Tabelas e Atributos Estrangeiros SQL

Question: Boa tarde, eu fiz um código Sql com as seguintes tabelas:
create table Bairro(
    cdbairro int not null primary key,
    nmbairro varchar(80) not null
)default charset = utf8;

create table Aluno(
    cdaluno int not null primary key,
    nmaluno varchar(80) not null,
    sexo enum('M', 'F'),
    cdcursocur int,
    cdrua int,
    numeroaluno int not null,
    cdbairro int,
    cdcidade int,
    dtnascimentoaluno varchar(15) not null,

    foreign key (cdcursocur) references CursoCur(cdcursocur),
    foreign key (cdrua) references Rua(cdrua),
    foreign key (cdbairro) references Bairro(cdbairro),
    foreign key (cdcidade) references Cidade(cdcidade)
)default charset = utf8;

Em seguida, meu professor requeriu o seguinte item:

Exiba todos os alunos cujo sexo seja M e o bairro centro.

Gostaria de saber como posso resolver esse item, pois já tentei e não consegui.
Comment: Coloque também o código da sua tentativa para que possamos ajudar.
Comment: Vamos lá. Você tem um aluno, e uma aluna. cada um de um sexo, e uma rum bairro você quer o aluno do sexo masculino, e morando no centro. o que você quer desses alunos alem da exigencia ?
Comment: Olá, Lucas. Se a resposta atendeu à sua dúvida, favor aceitá-la.
Answer: select cdaluno, nmaluno
from Aluno inner join Bairro on Aluno.cdbairro = Bairro.cdbairro
where sexo = 'M' and nmbairro = 'CENTRO'

Tabelas e Atributos Estrangeiros SQL