Opencart 3.x generating SEO-Friendly links for 'Search on homepage' and 'admin page'

Question: Working with opencart 3.x. I was thinking of changing .htaccess, seo_url, I wouldn't want to mess with the tables in mysql if it's possible. Three questions I can't find a solution to. I'm stuck on these two, trying to make them SEO friendly & having a block html on the php page. Any help would be nice, thanks.
current link:
https://www.-----.com/index.php?route=product/search&search=...

Q: 1) How to get SEO link to be just
https://www.-----.com/search

admin current link
https://www.-----.com/admin/index.php?route=common/dashboard&user_token=...
Q: 2) How to get SEO link to be just
https://www.-----.com/admin/dashboard

Q: 3) How can I create a block html on opencart manually in FZilla? I like write them in the actually files instead of modifying it and screw up the store.
Comment: Please ask 1 question at a time.

1. Look for an extension.
2. Why do you want this? I don't think there's any point.
3. You mean modify the twig files? They are in the template folder.
Answer: FRONTEND
For frontend (catalog) I have 2 solutions: long and short.

Long.

first, add support for custom urls in catalog/controller/statup/seo_url.php on line 103 after the closing }

else {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($data['route']) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

    if ($query->num_rows && $query->row['keyword']) {
        $url .= '/' . $query->row['keyword'];
    } else {
        $url = '';
    }
}

Then run the following MySQL code in your phpMyAdmin. It will populate the custom urls.
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'product/search', 'search');

You can also add all the other custom urls as well.
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'common/home', '');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/wishlist', 'wishlist');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/account', 'my-account');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'checkout/cart', 'shopping-cart');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'checkout/checkout', 'checkout');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/login', 'login');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/logout', 'logout');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/order', 'order-history');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/newsletter', 'newsletter');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'product/special', 'specials');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/account', 'affiliates');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/voucher', 'voucher');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'product/manufacturer', 'brands');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'information/contact', 'contact-us');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/return/add', 'request-return');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'information/sitemap', 'sitemap');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/forgotten', 'forgot-password');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/download', 'downloads');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/return', 'returns');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/transaction', 'transactions');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/register', 'create-account');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'product/compare', 'compare-products');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/edit', 'edit-account');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/password', 'change-password');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/address', 'address-book');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'account/reward', 'reward-points');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/edit', 'edit-affiliate-account');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/password', 'change-affiliate-password');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/payment', 'affiliate-payment-options');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/tracking', 'affiliate-tracking-code');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/transaction', 'affiliate-transactions');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/logout', 'affiliate-logout');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/forgotten', 'affiliate-forgot-password');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/register', 'create-affiliate-account');
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'affiliate/login', 'affiliate-login');

Short.

Just install SEO Module URL and set it up. You will have all custom URLs edited automatically for you and you can then customize them as you wish via the admin panel.

SEO Module URL
BACKEND
For backend (admin) OpenCart does not implement SEO Url functionality. You can do it on your own, but it requires a bit more coding to be done.
Basically you need to reproduce the catalog/controller/startup/seo_url.php in admin folder
and register this in system/config/admin.php
$_['action_pre_action'] = array(
...
'startup/seo_url'

You will also need to add the custom urls to the seo_url table in the DB.
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`) VALUES ('0', '1', 'common/dashboard', 'dashboard');

Hope this helps.
Comment: Thank you for an answer, small typo, missed 's' in $query->num_rows


Robust test if an expression can be coerced to character to avoid as.character error

Question: I am looking for a reliable test (= does not throw an error) whether an expression can be converted to character.
How could I do this?
I want to avoid that calling as.character throws an error like eg. in case of as.character(function() 1) which says:
Error in as.character(function() 1) :
  cannot coerce type 'closure' to vector of type 'character'

Example expressions:
# do not throw an error in as.character
1
1:10
"test"
NA
1 + 2
# do throw an error in as.character
function() 1
new.env()

PS: Of course I could use tryCatch but is there an easier way?
Edit 1: I want to test if the result value of an expression can be coerced to a character (not the expression itself)
Comment: `as.character(quote(function() 1)` yields `[1] "function"                      "NULL"
[3] "1"                             "c(1, 20, 1, 31, 20, 31, 1, 1)"` though I'm not sure this qualifies as a reliable test, doesn't throw error.
Comment: Interesting idea! I have just tried it with `as.character(quote(1+2))` and the expression is then not evaluated but kept as-is: `[1] "+" "1" "2"` (instead of `3`). Since I don't know up-front what the user is passing in as argument quoting would be at risk of wrong coercing results (but maybe there is a way to handle this).
Comment: Is the operation synchronous or asynchronous and is it desirable to call/log/identify the cases that will error as noted above?
Comment: @Chris I am not sure what you mean. I simple use cases would be (in pseudo code): `if (can.be.converted.to.character(x)) log.debug(paste("x=", as.character(x)))`
Comment: Not sure this gets any closer `as.character(eval(expression(1+2)) [1] "3"` but fails for new.env(), same with serialize. Would using `promises` pkg to filter good from bad be cheating? Not that I could figure out necessarily the coding or how that would improve over tryCatch. Interesting dilema.
Comment: Currently I'd say if there is no internal function in R that can test for a possible character conversion only a `tryCatch` would work (but I wanted to be sure that I do not oversee another simple solution)
Comment: While this always seemed like it must be at minimum a two step process, perhaps [win-vector article](http://www.win-vector.com/blog/2017/08/neat-new-seplyr-feature-string-interpolation/)
Answer: I'm sure there will be better answers to this question and I look forward to reading them. Wanting evaluated results assumes they are prone to evaluation, but if any unknown input is accepted, one can't be sure.
Depending upon where your pipeline is going next, explore variants of quote or expression.
as.character(quote(function() 1))
[1] "function"                      "NULL"
[3] "1"                             "c(1, 20, 1, 31, 20, 31, 1, 1)"

as.character(expression(1 + 2))
[1] "1 + 2"

as.character(eval(expression(1+2)) # works in this case
[1] "3"

as.character(eval(expression(1+2, 'A') # what would this be?
[1] "A" # so nonsense

Another approach might be to find out what sort of thing in the wild you're being passed and then decide what to do with it:
as.character(typeof(function() 1))
[1] "closure" # not safe or just pass along "closure" and move on

as.character(typeof(new.env())
[1] "environment" # not safe

as.character(typeof(expression(1+2))
[1] "expression" # safe (maybe) for further manipulation, replace typeof with eval

But typeof isn't immune to other user errors on the way to evaluated
results
as.character(typeof(function(x) 1, 'a'))
Error in typeof(function(x) 1, "a") : unused argument ("a")

I find this an interesting question because I've always assumed there was a way to render to string any object in R, though the path may be convoluted.
You'll know best regards your full project and where you are trying to control evaluation.
Comment: Thanks for your answer! I was perhaps somewhat unsharp in my question: I want to test the expression **result** (not the parsed expression) if it can be coerced to character. I have clarified this by editing my question


Multiple column join in linq

Question: I want to convert this sql query to linq
SELECT Students.StdId, Mark.Value
FROM Departments INNER JOIN
Mark ON Departments.DepId = Mark.DepId INNER JOIN
Students ON Departments.DepId = Students.DepId AND Mark.StdId = Students.StdId

I did this, but it's wont working
from s in Students
join d in Departments on s.DepId equals d.DepId
join m in Marks on new {s.StdId, d.DepId} equals new {m.StdId, m.DepId}
select new{
  SId=s.StdId,
  Value=m.Value
}

Answer: Lets try with
from s in Students
join d in Departments on s.DepId equals d.DepId
join m in Marks
on new {StdId = s.StdId, DepId = d.DepId} equals new {StdId = m.StdId, DepId= m.DepId}
select new{
  SId=s.StdId,
  Value=m.Value
}

Answer: How about
from s in Students
join m in Marks on s.StdId equals m.StdId
join d in Departments on m.DepId equals d.DepId
select new { s.StdId, m.Value };

Multiple column join in linq


Backbone.js - Adding keydown events when view is active?

Question: I have a view called gallery that options. I want to listen and act on keydown events when the gallery is rendered (until it's closed).
How do I do this in backbone events? I've tried all variations of 'keydown X':function and none have worked.
Comment: Your gallery is backbone view or standalone html + js?
Comment: show us your selectors for `keydown` events... i think you binding them to wrong elements
Comment: It's just: events: { 'keypress':'doThis' }
Comment: No selectors. Listen to any keypress.
Comment: Try on render bind event to `$(document)` and on `.remove()` make `unbind()`
Comment: What do mean by *"a view called gallery that options"*?
Answer: I just tested the following and it worked flawlessly:
var view = Backbone.View.extend({
  // ... snip ...
  events: {
    'keyup :input': 'logKey'
    ,'keypress :input': 'logKey'
  }
  ,logKey: function(e) {
    console.log(e.type, e.keyCode);
  }
});

I'd go back and check your code. All events in Backbone are defined as delegates attached to the viewInstance.el element. To unbind the events, call viewInstance.remove() which calls $(viewInstance.el).remove() under the covers and cleans up all the delegated events.
Also note that in some browsers (Firefox I believe) there's a known issue that some keys (like arrow keys) don't bubble and will not work properly with delegated keypress events. If you're catching special keys, you're probably better off using keyup and keydown.
Comment: - I can't get these global keypress/keyup/keydown to work. Is there some other minor detail that I must be forgetting? Could you possibly point to a reference or even a fiddle for more information of the document-wide events
Comment: Isn't this making assumptions that the View in question contains inputs? I think the OP was asking about the case where a particular view is simply rendered -- imagine that there is a lightboxed image or something and you wanted to hook up "Escape" to closing the image...
Comment: You are correct. My solution assumes there are input elements. If you wanted to act on key events anywhere in the view, you just exclude the selector (as the Backbone documentation states).

`events: {keyup: 'logKey'}`


Plot rectangle points given height, width, number points

Question: Is it possible to plot the points of a rectangle given the width, height and number of points all within a for-loop using sin/cos or something similar. I'm trying to find an easy way to plot these points in consecutive order.
One thing to mention is that the points would always be a multiple of 4.
Comment: A square has the same width and height. A right-angled quadrilateral whose width and height may not be the same is called a "rectangle".
Comment: But more importantly: what points are you trying to plot? A rectangle has infinitely many points.To plot them, you draw lines, not individual points.
Comment: I want to plot find the points scene in the image above. 1 in each corner and 4 between each corner
Answer: I assume that by "consecutive order", you mean as one travels around the perimeter. Sine and cosine are not well suited for this. The angles between adjacent points change as you go around.
The simplest way is just to use 4 loops: Starting that (x0, y0) as the lowest coordinate corner, with width w and height h, and having n + 1 points per side (counting both corners, so n = 4 in your example), you can do:
dw = w / n
dh = h / n
x1 = x0 + w
y1 = y0 + h
for i = 0 to n - 1
    plot (x0 + i * dw, y0)
next i
for i = 0 to n - 1
    plot (x1, y + i * dh)
next i
for i = 0 to n - 1
    plot (x1 - i * dw, y1)
next i
for i = 0 to n - 1
    plot (x0, y1 - i * dh)
next i


How to install a new PHP extension on IIS 7.5

Question: I have installed PHP 5.2.13 through Web Platform Installer on IIS 7.5/windows 2008 R2
Now I'm trying to install additional PHP extensions, such as mcrypt, so I downloaded the compiled .zip file from the php windows binaries site.
I put the relevant dlls in the extensions folder, and added the lines in the php.ini:
[PHP_MCRYPT]
extension=php_mcrypt.dll

After restarting IIS, no application was working.
This was with VC6 compiled/non thread-safe compiled version of PHP 5.2.13 .zip package.
I also tried with the thread-safe version, which prevented IIS to restart and forced me to reboot the server.
What am I doing wrong here?
Comment: `php_mcrypt.dll` has a dependency on `libmcrypt.dll`. Did you make
`libmcrypt.dll` available to IIS?
Comment: That was exactly the reason why it wasn't working, as I found out later. Please add that as an answer and I'll choose it! :)
Basically, IIS needs that version of PHP as I have written above, and any extension from that compiled package should work just fine (provided the dependencies are in place too).
Answer: Just as bzlm commented:
php_mcrypt.dll has a dependency on libmcrypt.dll. Did you make libmcrypt.dll available to IIS?
That was the reason. Thank you!


How to find trigonometric values using triangles as fractions?

Question: How to find trigonometric values using triangles? I only know how to find values of $30^\circ, 60^\circ, 45^\circ$  using triangle ( in fractional form ). Is there is any way to find values of angle $40^\circ, 90^\circ, 120^\circ, 180^\circ, 360^\circ$ as fractions
My calculator give me answer in decimals but i need answer in fractional form. Is there is any way to find out values using triangle like we find for $30^\circ, 60^\circ, 45^\circ$?
Comment: For 90 and 120 you can use sine rule and cosine rule.
Comment: I guess by $\frac12$ form you mean "in fraction form", rather than its (approximate) decimal representation.
Comment: @ShreevatsaR yes exactly
Comment: Do you know trignometric identities?
Comment: Yes i know, Sin, cos, tan, cosec, sec, cot.
Comment: As an exercise, try to find $\cos 36^\circ$ by analyzing a regular pentagon with similar triangles.
Answer: By far the most interesting of your questions is the one about $40^\circ$, and I'll leave that to the end. The trig functions of the other angles are determined by using the unit circle, as your trigonometry course should have explained to you. Take the circle $x^2+y^2=1$ in the plane, and, starting at the positive $x$-axis, make an angle $\theta$ with vertex at the origin, turning counterclockwise (anticlockwise if you're British). Then the other leg of the angle will intersect the unit circle at a point $(\xi,\eta)$, and you have: $\sin\theta=\eta$, $\cos\theta=\xi$, and $\tan\theta=\eta/\xi$. This will allow you to answer your question for all your angles but $40^\circ$.
Now for the interesting question. For some angles, like $15^\circ$, you can get an expression for the trigonometric functions involving square roots, perhaps repeated. For others, such as $10^\circ$, $20^\circ$, and $40^\circ$, the cosine of the angle satisfies a polynomial with rational coefficients that is irreducible and cubic. The verification of this fact is an essential part of at least one of the proofs that there are angles that can't be trisected with the traditional methods of compass and unmarked straightedge. In particular, you're not going to be able to construct a triangle or describe in any decent geometric way a triangle whose angles include one of $40^\circ$. Even if you used the Cubic Formula, you wouldn't get anywhere in this task. So your hope of finding a triangular description for $\sin40^\circ$ must remain forlorn.


Custom create account form included in a create content form

Question: I am new to Drupal 7 ( 1 month ) and have to do a rather complex task.
I have a content type (lets call it MyContent) for which i tried to create a custom form (I imported the fields from the original add content form in my own custom module generated page) which contains, among other fields, an email field, and i need to add 1 more field called password. With these 2 fields , i want on form submit:
*IF the email & password combination does not already exist
-> first create a user account taking the email as username and password as password ,
-> then create the content(disabled),
-> then make the site visitor confirm his email to enable his account
-> and after validation make the content viewable by all
*IF the email&password combination exists then :
-> create the content viewable
all of this by clicking one button.
The general ideea is that i want visitors, who are not logged, to be able to create content but in the process , get a user account generated as well. Also if the visitor already has an account then the email&password will work as a validator for letting the user create more content.
Is it even posible? I saw that Drupal has a lot of configurable options for users but nothing close to such a crazy ideea.
Answer: All of this is possible, but you will need to write a bit more code for it to work.
First, I suggest you use LoginToboggan.  LT provides a workflow for validating a user's email address which you can hook into either by code or perhaps with the Rules module.  LT already has the framework for tracking if a user is verified or not.  It will be up to you to write the code to create the user (not too hard) and to create the node as published or unpublished depending on the status of the user.
Second, you will have to decide what to do for verification (what if they enter the right email but wrong password?).
Comment: thanks for the answer. My worry is that i can't control the order of the submit ( as in first create user then content) since I imported the form for add new content from the original page. Can i trigger the validation before the submit process using hook_node_submit ?
Comment: Drupal's Form API helps you control this somewhat.  In your form_alter(), you can add something to the `$form['#validate']` function, which will run (and can modify form values) before the submit functions are executed.  Furthermore, you can make sure that your function is run first in the `#submit` group by using the PHP function `array_unshift()` to list your submit function first.  You should definitely read up on the [Form API](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7).


Hamiltonian $C_n$ Proof

Question: Prove that the complement of $C_n$ is Hamiltonian for $n\geq5.$
I know that since $C_5$ is Hamiltonian and $C_5$ is isomorphic to it's complement, then the complement of $C_5$ is Hamiltonian. Since $C_n$ is $2$-regular we know that the complement of $C_n$ is $(n-3)$-regular. So by Dirac's Theorem, $n-3\geq {n\over 2}$ for $n\geq6$. Thus the complement of $C_n$ is Hamiltonian for $n\geq5$.
I feel that this proof is satisfying. However, do I have to actually prove/show that $n-3\geq{n\over 2}$ for $n\geq6$? It seems obvious and that actually showing this is pedantic. What are your thoughts?
Comment: Hint: $n-3=\frac{n}{2}+\frac{n}{2}-3 \geq \frac{n}{2}+\frac{6}{2}-3 $.
Comment: I think the clause "by Dirac's Theorem" should be removed from the statement "So $n-3\ge\frac{n}2$ for $n\ge6$" and inserted in the statement "Thus the complement of $C_n$ is Hamiltonian for $n\ge5$".
Answer: It depends on your audience. If this was a problem in a second or third year course, then you can probably make do without the proof of the claim. At the same time, if this was for a first year course emphasizing proper proof techniques and mathematical rigor, then I would probably include the proof of the claim.
As a rule of thumb, here is my take regarding situations like this: if you have to ask whether a statement needs proof, then the statement needs proof. The proof is only one line in this case anyways, so its probably worth the effort:
$$n - 3 \ge \frac{n}{2} \iff \frac{n}{2} \ge 3 \iff n \ge 6$$
Answer: It's not too difficult to give an explicit construction.
For odd $n$, if the vertices are $\mathbb{Z}_n$, then the vertices of difference $1$ form an $n$-cycle, and the vertices of difference $2$ form a disjoint $n$-cycle.
For even $n$, we take the graph for $n-1$ above, and add in a new vertex $\infty$, replacing the edge between $0$ and $1$ with the path $0$ to $\infty$ to $1$, and replacing the edge between $2$ and $4$ with the the path $2$ to $\infty$ to $4$.
This is depicted below for $n=7$:

Hamiltonian $C_n$ Proof


Why do I get a notice after migrating the site to a new server?

Question: I am getting this error after migrating the site to a new server:

Notice: unserialize() [function.unserialize]: Error at offset 2 of 23 bytes in includes/bootstrap.inc on line 478

I'm sure somewhere a setting has been corrupted; however, the site does appear to be functioning correctly. This error does return inconsistently, for anonymous users, so I do need to take care of it.
The error does not occur on the old server.
I have full control of the server, both the new and the old are Amazon EC2 VMs. The only major difference in the infrastructure is that the old server used a MySQL DB in the same VM, while the new server is using a MySQL Server in RBS.
I've read somewhere that this issue could be caused by the SQL export/import process, and something regarding UTF8. I wasn't able to garner anything I could mold into instructions to follow, but I have a feeling that's a path I need to take; I'm not really sure where to start.
Answer: The problem might be the error handling settings have changed on the new server. You probably have a corrupt variable in the variable table that can't be unsterilized. Try using the variable check module.
Comment: If you just did a `display_errors = Off` then you are just hiding the problem and not solving it.
Comment: That's definitely easier than my approach :)
Comment: Wow good call. PHP Debug was turned on by an administrator for a separate issue. Turning this off solved the problem :) Thanks a lot!
Answer: This is rather difficult to debug, but you might edit includes/bootstrap.inc where the unserialising happens – this is from the variable_init() function, where I assume the error occurs.
The original code looks like this.
while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);
}

Try altering it to something like this:
while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);

  if (!$variables[$variable->name]) {
    drupal_set_message('Possible error while decoding ' . $variable->name);
  }
}

There will be some false positives here, given that some values are actually FALSE or 0, but it should narrow the field, helping you to identify the broken variable. Then you can inspect the variables table in the database to find and fix it :)
Comment: Ah, the http://drupal.org/project/variablecheck module suggested by Adam S would be a much easier way to accomplish this :)
Answer: I have had this happen when I migrate a database from staging to live and have to hand edit the database for paths, domain name, etc.
What is happens in the case is that the search-replace matches a string in the variables table, and alters the row.  The problem is that length (the number after the s: doesn't get changes, so the unserialize fails.
If you go into the variable editor via the admin menu, you will likely see a blank entry where there was a real variable.  Either update it here and save, or use a MySQL tool and fix the length in that row.


JavaScript: detect the moment when window is starting to change location

Question: I'm trying to detect the exact moment when the page leaves its current location and begins loading of a new one: immediately after clicking on a link or pressing "submit" or any other way.
I'm aware of "onload" event and several ways to make use of it, but that's not what I'm looking for: plenty of time can pass between 1) clicking on link and 2) firing "onload" event and I need to detect the moment after 1).
Answer: I think what you're looking for is:  onbeforeunload or onunload
Answer: I like using the onhashchange event:
window.onhashchange = function() {
    console.log("Hash changed");
}

Demo: http://jsfiddle.net/v8j9F/
Reference: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange
Answer: onbeforeunload is probably the earliest, it's described briefly here


How do I use non-admin theme for page containing node form?

Question: I've created a custom route where I return node add form with a controller. It works fine, but for the administrator user it is using the administrator theme.
I tried using the following, but it doesn't help.
  options:
    _admin_route: FALSE

Is there a good approach to achieve this? As I remember, in Drupal 7, it worked fine with hook_admin_paths().
Comment: I'm voting to close this question as off-topic because bugs are of topic
Comment: You've done it correctly - did you clear your cache after doing this?
Comment: @Jaypan yes, sure
Answer: Well, the issue was related to the bug in metatag module, it was in version 8.x-1.0-beta11.
It caused break of my routes when they ended with /add. It was trying to handle prefix of path as entity type, so my routes worked fine only if I had _node_operation_route: TRUE in route options. But if this option is set _admin_route: TRUE is added by core.
I updated metatag module to the latest version (8.x-1.0 currently) and found they've added check for existing entity type, so I'm not forced to use _node_operation_route: TRUE anymore and I'm able to output custom routes in a default site theme.


"compiler is unable to type-check this expression" — how to rewrite this basic expression?

Question: Before someone flags this as "SO is not a code writing service"... please read my post fully and see all the possible solutions I have tried to fix my problem:
I am trying to use a ForEach loop to create cutout circle masks, to look like a perforated edge. I get this error:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

I have encountered this error before, and it's usually straightforward to do as it says and break the expression up. This time, I can't figure out a way to solve it.
I believe the issue is caused by the padding on the Circle with the holePunchSize (and various alternatives). It works fine if I use a fixed value. Originally I had the multiplier expression right in the .padding — ((geo.size.width - 40) / 17) * 2.3. Then I thought to calculate the value once in an .onAppear and use that (holePunchSize). Then I thought, maybe I have to split the expression further, the result you can see in the .onAppear below.
Still, I get the error. I have no idea how I can possibly break this down any more.
Also, I have tried to simplify this further just for testing, by using fixed values in the .frame(width.., and all but one of the .padding, it still complains.
Code:
.reverseMaskBottomLeading {
    ForEach(0..<17) { i in
        Circle()
            .frame(width: (geo.size.width - 40) / 17, alignment: .bottomLeading)
            .padding([.bottom], -14)
            .padding([.leading], i * (geo.size.width - 40) )
            .padding([.leading], CGFloat((i * (holePunchSize))))
            .padding([.leading], -12)
    }
    .padding([.leading, .trailing])
}
.onAppear {
    holePunchSize = geo.size.width - 40
    holePunchSize = holePunchSize / 17
    holePunchSize = holePunchSize * 2.3
}

...

@inlinable
public func reverseMaskBottomLeading<Mask: View>(
    alignment: Alignment = .bottomLeading,
    @ViewBuilder _ mask: () -> Mask
) -> some View {
    self.mask {
        Rectangle()
            .overlay(alignment: alignment) {
                mask()
                    .blendMode(.destinationOut)
            }
    }
}

Comment: Show a minimal reproducible code that produces your error, see: https://stackoverflow.com/help/minimal-reproducible-example
Answer: Swift doesn't support binary arithmetic operators like + and * with operands of different types. The only exception is that Swift will convert between CGFloat and Double automatically.
For example, in the code you posted, i * (geo.size.width - 40) is not legal, because i is Int while geo.size.width - 40 is CGFloat.
Note that integer literals like 40 can be treated as a variety of types depending on context; here, if the errors are corrected, it will be treated as CGFloat to make the - operator work. However, when there are errors around, Swift can end up trying lots of different types for each integer literal, which means lots of different combinations, and so it can time out. Your Circle expression has five integer literals, so if Swift can treat each as any of, let's say, 12 different types, then there are 12⁵ = 248,832 type combinations it could try. Swift has optimizations to reduce this number, but it's still exponential.
Anyway, I see at least two cases where you are trying to multiply Int by CGFloat:
            .padding([.leading], i * (geo.size.width - 40) )
                                   ↑
                                   here

and
            .padding([.leading], CGFloat((i * (holePunchSize))))
                                            ↑
                                            here

You need to convert i to CGFloat in both places:
            .padding([.leading], CGFloat(i) * (geo.size.width - 40))
            .padding([.leading], CGFloat(i) * holePunchSize)

Also, you might want to consider using a Canvas to draw your reverseMaskBottomLeading instead of that modifier-heavy ForEach/Circle combination.


Returning pseudo random number- C programming language

Question: I don't know what the heck all this is about. All I know about is that it's a function that produces random number.
So can you explain this whole entire piece of code to me.
This is page 46 in K&R C programming language 2nd edition book.
<code>unsigned long int next = 1;

/* rand: return pseudo-random integer on 0..32767 */
int rand(void)
{
    next = next * 1103515245 + 12345;   /*What the heck is this line doing?????? */
    return (unsigned int) (next/65536) % 32768; /*This line, too, I have no idea.. */
}

/* srand: set seed for rand() */
void srand(unsigned int seed)
{
     next = seed;
}
</code>
Comment: possible duplicate of [Why 1103515245 is used in rand?](http://stackoverflow.com/questions/8569113/why-1103515245-is-used-in-rand)
Answer: This random number generator consists an LCG, which are algorithms of the form Xn+1 (the next element) = aXn+c mod m (Xn is the current element). It then takes the 15 bits starting from the second bit of the seed as output. In an LCG, each number is produced by multiplying  the state number by a constant, adding it to a constant and moduloing it a constant, which will determine the size of the output.


Why is the derivative of the binormal vector parallel to the normal vector?

Question: In my notes, it says to consider an arc length parameterization r(s). Then we can show that B' points in the direction of N such that we can write B'=-N. I understand why ||B'||= but am unsure how to show why B' is parallel to N? Also, is the minus sign just for convention or is there a reason it is there?
Any help would be greatly appreciated!
Comment: What can you use to measure angle between vectors ?
Answer: $\def\vt{\mathbf{T}}
\def\vn{\mathbf{N}}
\def\vb{\mathbf{B}}
\def\vr{\mathbf{r}}$In what follows differentiation with respect to arc length is indicated with a prime.
We have
\begin{align*}
\vt &= \vr' \\
\vn &= \vt'/\|\vt'\| \\
\vb &= \vt\times\vn.
\end{align*}
Then
\begin{align*}
\vb' &= \vt'\times\vn+\vt\times\vn' \\
&= \|\vt'\|\underbrace{\vn\times\vn}_{\mathbf{0}} + \vt\times\vn' \\
&= \vt\times\vn'.
\end{align*}
Note that $\vb$ is orthogonal to $\vt$ by definition of the cross product.
Since $\|\vb\|=1$, $\vb'$ is also orthogonal to $\vb$.
(Proof: $(\vb\cdot\vb)' = 2\vb\cdot\vb' = 0$.)
Since $\vt,\vn,\vb$ form an orthogonal basis, it must be the case that $\vb'$ is proportional to $\vn$.
We take
$\vb' = -\tau\vn$.
The minus sign is a convention.
It is a version of the right-hand rule.
Note that $\tau>0$ indicates a twisting of the coordinate frame about the $\vt$ axis in a right-handed manner.
(Take your right hand and point your thumb in the $\vt$ direction.
Twist your hand about this axis in the direction in which your fingers are pointing.
This twist corresponds to $\tau>0$.)
Comment: Ah thank you this makes a lot of sense now!
Comment: I am glad to help!


Accessing devops interface outside Cassandra EC2 cluster

Question: I have just setup a four nodes Cassandra 3.4 cluster running centOS 7 on AWS. I was able to configure it and get all the nodes together. Now I would like to perform some tests, monitoring the cluster behavior using the devops center which I installed on one machine.
I thought using ssh-tunneling to access it from my computer:
ssh -i Amazon-EC2-Ami.pem -L 9999:localhost:8888 centos@public_address

Using my browser, localhost:9999 gets correctly tunneled to the devops login page: http://localhost:8888/opscenter/login.html, but I got a ERR_CONNECTION_REFUSED
I tried accessing devops on that machine using a command line browser and it displays the login page. I really do not know what the issue could be. Any information is truly appreciated. This is the cassandra-yaml configuration file, in case it helps:
cluster_name: 'Cloak'
listen_address:
endpoint_snitch: GossipingPropertyFileSnitch
rpc_address:
seed_provider:
- class_name: org.apache.cassandra.locator.SimpleSeedProvider
  parameters:
  - seeds: "172.31.55.186,172.31.55.187"

EDIT
Using the -v option launching the ssh tunneling I can confirm that the requests are correctly tunneled:
[centos@ip-172-31-55-186 ~]$ debug1: Connection to port 9999
forwarding to localhost port 8888 requested.
debug1: channel 3: new [direct-tcpip]
debug1: Connection to port 9999 forwarding to localhost port 8888
requested.
debug1: channel 4: new [direct-tcpip]
debug1: channel 3: free: direct-tcpip: listening port 9999 for
localhost port 8888, connect from 127.0.0.1 port 43846 to 127.0.0.1
port 9999, nchannels 5

Answer: Finally I managed to access it from my computer. I had to modify the configuration file for the operation center, located in /etc/opscenter/opscenterd.conf (only for package installation):
[webserver]
port = 8888
interface = 127.0.0.1

By default the webserver accepts requests only from the localhost. Probably it won't be the best option, but since the operation center allows to configure users, I set interface = 0.0.0.0, allowing any host to contact it.


How many rolls until probability of a 5 is at least 1/2?

Question: Problem: Jak rolls two die and wants the probability of rolling at least a 5 to be $\frac{1}{2}$. How many should Jak roll?
basically, I got two answers (same), but different approaches. Can someone tell me why one of them could be wrong?
Solution 1
The chance of getting a 5 is $\frac{1}{6}$ and rolling n dies or n times (same meaning in this situation) is $\frac{n}{6}$. Now I want the probability to be at least $\frac{1}{2}$
So I have $\frac{n}{6} > \frac{1}{2} \implies n > 3 \implies n = 4$
That is I want to roll four dices.
Solution 2
This one is a bit more formal.
It basically thinks about the probability of NOT getting that 5. So I have $\frac{5}{6}$. Now rolling n times, I get $(\frac{5}{6})^n$
Thus, the event of getting at least one five would be $1 - (\frac{5}{6})^n$ and we want this to be greater than 1/2.
$$1 - (\frac{5}{6})^n > \frac{1}{2} \implies n > 3.80 \implies n = 4 $$
Both gives me n = 4, but clearly the first one is informal. Could someone tell me why the first one could be wrong?
Comment: can "a chance" be $n/6$?
Comment: Oh I see. I made a mistake, it should've been $\frac{1}{6^n}$ and I wouldn't get n = 4 at all.
Answer: Unfortunately, the first one is in fact wrong because you can't add probabilities in this way. If you could, we could set up a ridiculous situation.
Say that, instead of a die, you are using a fair coin and you want to guarantee getting heads. If probabilities simply added, that means that the probability of getting heads after two trials would be $2\cdot\frac{1}{2}=1$. This is clearly not true. Your first method would be correct, however, if there was something to prevent the same event from happening twice, but this isn't the case in the problem.
Your second method is correct. You are finding the probability $P$ that the opposite of the event happens every time. $P$ is the complement of the event happening at least once, and therefore $1-P$ is the probability you are looking for.
Edit: I should have been clearer about this. $n=4$ is the right answer, and you justified it perfectly the second time. The first time just happens to be right; it's not a valid method of finding the answer to this problem.
Comment: Oh I see. I made a mistake, it should've been $\frac{1}{6^n}$ and I wouldn't get n = 4 at all.
Comment: That would be the probability of rolling a $5$ every time. An event of probability $P$ occurring $n$ times in a row has probability $P^n$, and the probability of the complement (opposite) of $P$ occurring during $n$ trials is $1-P^n$.


Apple obrigando desenvolver app para iPhone e obrigatoriamente para iPad, é isso mesmo?

Question: Ontem submeti um App que é feito somente para iPhone, e não para iPad, conforme solicitação do cliente, porém o meu app foi rejeitado por que ele não roda corretamente em um iPad.
Motivo da Rejeição:

Reasons
2.10: iPhone Apps must also run on iPad without modification, at iPhone resolution, and at 2X iPhone 3GS resolution
  ----- 2.10 -----
We found that your app did not meet the requirements for running on
  iPad, as required by the App Store Review Guidelines.
Your app did not run at iPhone resolution when reviewed on iPad. While
  your app may be built for iPhone or iPod, it must still run on iPad,
  at iPhone resolution and at 2x iPhone 3GS resolution.
For information on iOS device screen sizes and resolutions, see Points
  versus Pixels, in the View Programming Guide for iOS. For discrete
  code-level questions, you may wish to consult with Apple Developer
  Technical Support. When the DTS engineer follows up with you, please
  be ready to provide:

complete details of your rejection issue(s)
screenshots
steps to reproduce the issue(s)
symbolicated crash logs - if your issue results in a crash log

If you have difficulty reproducing a reported issue, please try
  testing the workflow as described in
  https://developer.apple.com/library/ios/qa/qa1764/Technical Q&A
  QA1764: How to reproduce a crash or bug that only App Review or users
  are seeing.

Eu entendi bem ou a Apple quer nos forçar a desenvolver apps para os dois modelos (iPad e iPhone)???
Comment: É pq o Wpp exige um numero telefônico como forma de registro, e como um ID único. :D Tanto que para trocar de telefone e se manter com o backup de conversa tem q passar por outro processo de cadastro e confirmação de emaik
Comment: Ele precisa rodar no iPad naquela "janelinha", como se tivesse uma tela de iPhone dentro da tela do iPad.
Comment: Estranho, o Whatsapp por exemplo não roda em iPad.
Comment: Serio? mesmo sendo iPad com 3G (possuindo chip)??? @bfavaretto
Comment: Hm, nunca testei num 3G, só no Wi-Fi. E aí faz sentido mesmo não ter rodado (== nem me deixa baixar da app store)
Comment: Bom, o que eu entendi da mensagem (posso estar enganado de novo, rs) é que mesmo uma app para iPhone precisa rodar no iPad sem alteração, nas resoluções especificadas. Isso não significa que você seja obrigado a a publicar a app como iPhone/iPad. Pelo que entendi, você tem algum problema de resolução.
Comment: kkkk pow, se eu faço um app para iPhone, que pode ser rodado em um iPad, e DEVO fazer a interface dele ser executada em um iPad, vai me dizer que não estou sendo obrigado a fazer para o app para iPhone E para iPad?
Answer: O problema ai é de interpretação de texto.
Ênfase nos seguintes pontos:

2.10: iPhone Apps must also run on iPad without modification, at iPhone resolution (...)

E

Your app did not run at iPhone resolution when reviewed on iPad.

Traduzindo:

2.10: aplicativos pro iPhone devem rodar também no fondle-slab iPad, sem modificações, na mesma resolução que no telefone (...)

E

Seu aplicativo não rodou na resolução de um iPhone quando revisado num iPad.

Em suma... Alguém lá na Apple pegou teu build, colocou num iPad, e a tela ficou do tamanho errado. Faça com que tenha a mesma resolução nos dois aparelhos (ou o dobro no iPad, se o seu iPhone de testes for o 3GS) que o pessoal lá deixa passar.
Comment: EU fiz com que a tela aumentasse os elementos, ou realocasse proporcionalmente, e submeti novamente o app. Espero que resolva... vou informar aqui se deu certo.
Answer: Segundo a Apple embora alguns App's não sejam feitos para iPad, eles devem manter o mínimo de compatibilidade, e oferecer um auto ajuste da tela, para que o usuário possa usá-lo problemas.
Embora seja contra esta atitude da Apple, infelizmente tive que ceder para que meu app fosse aprovado.
Porém questionei sobre app's que não possuem versão para iPad, e nem mesmo aparecem na iTunes Store dos iPads, e não me responderam nada.
Conclusão: Faça auto resize de layout em seus apps para que possam ser rodados em telas de tamanhos diferentes, incluindo a tela do iPad.


Why won't a Dell PowerEdge R310 support 16GB RAM in a 4x 4GB RDIMM configuration?

Question: I am trying to upgrade a Dell R310 from the 1GB RAM that it came with (1 stick - 1GB UDIMM - Hynix part number HMT112U7BFR8C) to 16GB using 4 x 4GB Dual Rank RDIMM 1333MHz memory modules purchased directly from Dell. However, I cannot get these new chips to work.
Dell don't seem to have any idea why they don't work, and they have already replaced them twice with no luck. The motherboard has also been replaced by Dell in case that was fault but it still doesn't work.
I have also tried the sticks in lower capacity configurations:

1x 4GB stick in slot 1 for total 4GB
1x 4GB stick in slot 1, 1x 4GB stick in slot 2 for total 8GB

None of these combinations work. As soon as the original unbuffered DIMM is put back in by itself, it works fine.
I have checked that the combinations and slot choices are in accordance with the Hardware Owners Manual and it all checks out.
Has anyone seen this problem before? Any idea what we need to do to get this working?
Comment: Are they properly inserted in their slots ? by order ? I upgraded from 1RAM to 4RAM in a 2*2GB cards it worked well.
Answer: Just ran into the same problem with an R310.  Took quite a bit of digging but the link to the R310 Tech Guide helped.  The 1GB UDIMM uses 128Mb x8 chips which is why it works.  The Samsung sticks they keep sending you use 256Mb x8 chips and as you found in the Tech Guide the R310 won't work with 256Mb chips.  I ran into the same problem using some memory we pulled out of an R710 server but they were 256Mb x4 chips so it was a double no-no.
Here is what I've found regarding memory.  The actual DRAM chips on the memory module have differing numbers of lines.  This is also referred to as the rank width, e.g., x4, x8, x16.  The DRAM chips are also different sizes, e.g., 128Mb, 256Mb, 512Mb.  The easiest way to explain ranks is to think of each rank as a virtual DIMM.  So a single rank module is just that; a single memory module on a single physical DIMM.  Dual rank memory actually has 2 memory modules on a single physical DIMM (it's deeper than that but this is the easiest way to visualize it).
So the bottom line is that the R310 will only accept DIMMs that are made out of 128Mbit or 1Gb/2Gb chips that are x8 devices.  Or at least that's my story and I'm sticking with it until Dell tells me otherwise; e-mail to them is out and I'll let you know if they say something different.
Link to Hynix part: http://www.hynix.co.kr/datasheet/eng/module/details/module_20_HMT112U7BFR8C.jsp?searchType=2&menuNo=1&m=1&s=1&RK=20&RAM_NAME=
A link to an excellent briefing from Intel:
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CDsQFjAB&url=http%3A%2F%2Fdownload.intel.com%2Feducation%2Fhighered%2Fsignal%2FELCT865%2FClass2_21_lab_and_project_assignment3.ppt&ei=VKOiT-yKDoau9AS86730CA&usg=AFQjCNHOMlxRyI0C8F7GIdwMkU8h1ZOmyQ&sig2=nLNmplaHcJjbv7rktoqb2Q
Slide 13 is the key, but the entire package is very good depending on your level of geekdom :)
Update: Confirmed with Dell except that I was wrong about requiring 128Mb and smaller chips.  The Foxhollow platform does support 1Gb and 2Gb chips.  See here: http://cache-www.intel.com/cd/00/00/43/26/432686_432686.pdf
Answer: Dell's documentation isn't all that great. But I would start by making sure the BIOS is up to date. Then look inside the BIOS to see if there are some settings related to memory.
This is the tech guide
Look at page 35+ for memory related stuff. Slot configuration is important per the documentation.
But really Dell should be able to fix this for you. Try to get your service call escalated.
Comment: I agree, this should be put back on Dell.
Comment: Dell have been involved several times already. They are coming out *again* this afternoon, but we are now at the point where we just need this working, regardless of how!
Comment: The manual link that you sent is different from the links I had seen previously. I note that there are various restrictions such as "No support for 256Mb/512Mb technology or x4 and x16 DRAMs on RDIMM". The chips that they keep sending us are Samsung model M393B5273cho-ch9. However, my knowledge of RAM is not good enough to know if this is compatible or not! Their product spec sheet is here: http://www.samsung.com/global/system/business/semiconductor/family/2010/1/1/ddr3_product_guide_oct_09.pdf (page 7, about halfway down). Anyone got any clue if it's compatible?
Comment: More "manual" goodness @ ftp://ftp.dell.com/manuals/all-products/esuprt_ser_stor_net/esuprt_poweredge/poweredge-r310_owner's%20manual_en-us.pdf#page=106
Answer: had the same problem with a T110 and RDIMM. RDIMM is only supported with XEON CPU´s on the R310
RDIMM can´t be used with Desktop CPU and Xeon L3206!
Chec
Answer: To use 16GB of memory you will need XEON processor and a quantity of (4) 4GB sticks that are dual ranked and use a x8 data width (2Rx8).
Answer: I experienced the same issue with our PowerEdge R310 where the only support for RDIMM is with a Xeon processor (ours had a Core i3).  There was a single ambiguous reference in the Technical Manual that confirmed this.
To use all six slots requires RDIMM, so the bottom line is that the UDIMM maximum is 4 x 4GB Dual Ranked DIMMs leading to the 16GB maximum.
Answer: The Dell Tech Guide provides detailed information that should help.
https://i.dell.com/sites/csdocuments/Shared-Content_data-Sheets_Documents/en/PowerEdge-R310-Tech-Guide-rev1.pdf
Look in section 8.1 (pages 36-37) for information on which RDIMMs or UDIMMs to use to obtain different memory configurations. The speed and rank are also important.
Comment: How is this different from cwheeler33's answer of more than five years' previous?


Continuity of $\delta_E : (X, \tau_d) \rightarrow (R, \varepsilon_1): \delta_E(p) = d(p, E)$

Question: Let $(X,d) $be a metric space and $E \subseteq X$.
We define $d(p,E) = inf \{ d(p, q)| q \in E \}$ the distance from $ p \in X$ to $E$
I have the following example in my lecture notes:
Problem:
Let $(X, d)$be a metric space and $E \subseteq X$.Now, the function
$\delta_E : (X, \tau_d) \rightarrow (R, \varepsilon_1)$ defined by  $\delta_E(p) = d(p, E)$ is continuous
Proof
Let $p_0 \in X$ and let $d_0 = \delta_E(p_0) \in \mathbb{R}$. For each $p \in X$ and $q \in E $ we have
$d(p, q)  \leq  d(p, p_0) + d(p_0,q)$ ........(1)
and $d(p_0, q) ≤ d(p_0, p) + d(p, q)$
from which
$\delta_E(p) = inf_{q \in E}d(p, q) ≤ d(p, p_0) + \delta_E(p_0)$ and $\delta_E(p_0) ≤ d(p_0, p) + \delta_E(p)$:
Therefore,  $|\delta_E(p) − \delta_E(p_0)| = |\delta_E(p) − d_0| ≤ d(p, p_0)$.
Now, given $\epsilon > 0, V_{\epsilon} = (d_0 −
\epsilon, d_0 +\epsilon) $ is the ball of center $d_0 $ and radious $\epsilon > 0 $ in $(\mathbb{R}, d_{\varepsilon})$ and $\delta_E(B(p_0, \epsilon)) \subseteq V_{\varepsilon}$, ........(2)
from which we get the continuity of $ \delta_E$.
I am having trouble understanding (1) and (2) :
(1)$\delta_E(p) = inf_{q \in E}d(p, q) ≤ d(p, p_0) + \delta_E(p_0)$
How did the last term $\delta_E(p_0)$ get here?
(2) how do they get this expresion: $\delta_E(B(p_0, \epsilon)) \subseteq V_{\varepsilon}$ ? I tried to take an element in the left set and prove it is the right one , but I am not getting anywhere. I know that to prove continuity I must show the first ball is contained in the second one
Can someone please detail what is going on?
Comment: \inf looks better than inf.  And we should assume E is not empty.
Answer: Hint for (1) Take infimum over $q$ on both sides
of the given inequality
$$d(p, q)  \leq  d(p, p_0) + d(p_0,q)$$
Use the general statement: If for every $y$ in set of real numbers $B$ there is an $x$ in set of real numbers $A$ such that $x\leq y$, then
$$ \inf A \leq \inf B.$$
Edit:  Take:
$$A = \{ d(p, q) \mid q \in E \}$$
$$B = \{ d(p, p_0) + d(p_0,q) \mid q \in E \} $$
and then note that:
$$ \inf B = d(p, p_0) + \inf \; \{  d(p_0,q) \mid q \in E \} $$
Hint for (2) From
$$|\delta_E(p) − \delta_E(p_0)|≤ d(p, p_0),$$
if $p \in B(p_0,\epsilon)$, then
$$ |\delta_E(p) -\delta_E(p_0)| ≤ d(p, p_0) < \epsilon. $$
That is
$$ \delta_E(p) \in B(\delta_E(p_0), \epsilon)=V_\epsilon $$
for all $p \in B(p_0,\epsilon)$.
Comment: I was thinking that, but I was not sure if it could be done, I am trying to find a theorem to justify it. All I can find are properties for sets and inclusion, but here we have an inequality
Comment: Note that $d(p,p_0)$ is independent of $q$ and remember the definitions of $\delta_E(p)$ and $\delta_E(p_0)$  .
Comment: Yeah taking the inf will yield the result directly, it's clear, but can I really take the inf of numbers in an inequality an distribute it over a sum? I know I can take the inf for sets like in $A \subseteq B$
Comment: @J.C.VegaO I added the general $\inf$ statement that should help.
Answer: A more clear proof:
Proof. In order to show that $\delta_E : X \to \mathbb R$ is continuous, we show that $\delta_E$ is continuous at every $p_0 \in X$, that is, we show that for all $\varepsilon>0$ there exists $\delta>0$ such that $$\delta_E(B(p_0,\delta)) \subseteq (\delta_E(p_0)-\varepsilon,\delta_E(p_0)+\varepsilon),$$ in other words, for all $\varepsilon>0$ there exists $\delta>0$ with the following property:
$$\textrm{for all $p \in X$ such that $d(p,p_0)<\delta$ we have $|\delta_E(p)-\delta_E(p_0)|<\varepsilon.$}$$
So, let $p_0 \in X$ be arbitrary, and $\varepsilon>0$ also arbitrary. We claim that $\delta := \varepsilon/2$ works. To see this, let $p \in X$ such that $d(p,p_0) < \delta$ and now note that:

For any $q \in E$ we have $\delta_E(p) \leq d(p,q) \leq d(p,p_0)+d(p_0,q) < \delta +d(p_0,q)$, or,
$$\delta_E(p) - \delta < d(p_0,q)$$
meaning that the set $\{d(p_0,q) : q \in E\}$ is bounded below by $\delta_E(p) - \delta$. Now, since $\delta_E(p_0)$ is the greatest lower bound for $\{d(p_0,q) : q \in E\}$ we have $\delta_E(p) - \delta \leq \delta_E(p_0)$, i.e.
$$\delta_E(p) - \delta_E(p_0) \leq \delta < \varepsilon.$$

Similarly we can obtain the other inequality: $-\varepsilon < \delta_E(p) - \delta_E(p_0)$.


Git pull and merge and push specific changes without bringing in unrelated commits?

Question: I have 1 develop branch and 1 project branch, the project branch has changes I want in develop but it also has changes I am not quite ready to put into develop. The project branch acts as the "develop" branch for myself while the develop branch is shared.
So my steps are:

Create a feature off the develop branch
git pull origin project.branch.name --no-commit (this will give me the diff and I can pick out the changes I want to add to develop before committing)
git push

This works fine except that it brings in commits that are not related to the changes I am pushing. The issue with bringing these commits in is that next time I want to do a pull request from the project to develop, it won't recognize the changes because develop will have the commits but not the code changes.
I looked into cherry picking but that's very tedious for changes that contain a lot of commits. Does anyone have an alternative solution?
Much appreciated!
Update
After extensive research, this is apparently not very common outside of working with monoliths. I have resolved the issue by gritting my teeth and cherry picking.
Comment: Could you illustrate your situation with a schema or a log and how you tried to cherry-pick? With ranges it's not that hard in many situations.
Comment: I agree, with ranges cherry picking isn't too bad but I'm assuming there is an alternative way because I feel that this is a common case that teams face.
Answer: Step 2 gave me a headache. You are working by hand on changes that are coming from a branch? This is a problem for 2 main reasons:

you are prone to (unwillingly, of course) add mistakes by editing files on the fly.
even if you are flawless on the edition process before finishing the pull/merge operation, if you choose to get rid of changes related to a thing you don't want to have in your branch, those revisions are part of the history of the branch when you finish pulling/merging.

There are probably other problems with your approach but those are the biggest two I can think of.... and they are big.
Comment: It's only by hand in determining what files to commit but not hand on editing the code. I do agree there has to be a better approach. Is there an alternative approach you could recommend?


statsmodels.api error while importing pandas Int64Index

Question: When I try to import the following library:

import statsmodels.api as sm
I recibe the following error: "cannot import name 'Int64Index' from 'pandas'"

I guess Pandas should have upgraded to a new version where they deleted this 'Int64Index', but I'm not sure, can anyone help?
Thanks for the support
Answer: Same error message for me, manually installing the latest statsmodels library fixed it for me:
<code>pip uninstall statsmodels
pip install statsmodels==0.14.0
</code>


Synchronize two ListView positions when you scroll from both list views Android

Question: I have two ListViews. Is there any way to synchronize the position of ListViews when I scroll both the Lists
Comment: I have a working sollution please check this post

http://stackoverflow.com/questions/11906263/how-to-syncronisize-two-listview-positions/16168749#16168749
Answer: Use the following method to get the scroll position of your first listView-
<code>    private void saveListScrollPosition()
    {
    // save index and top position
    index = _listview1.getFirstVisiblePosition();
    View view = _listview1.getChildAt(0);
    top = (view == null) ? 0 : view.getTop();
    }
</code>
And scroll the second listView to that position with-
<code>// restore
    _listview2.setSelectionFromTop(index, top);
</code>
Answer: You could use this in your second list view: smoothScrollToPosition(position)
And in your first ListView you could use a OnScrollListener and check the first visible item with getFirstVisiblePosition.
Best wishes,
Tim
Comment: have you tried with the above solution .since i didnt get scrolling with the same idea


Android App Development - Firebase Database

Question: I'm building an activity in an app where users can upload a post, and other users in the app can view the post.
I built a function called loadPost()
This function will take what's there in the database and load it in my View.
Unfortunately, I'm facing an error with the
 .addValueEventListener(ValueEventListener{

It's telling me that the interface needs a constructor.
here's the function:
//*******************************************************
//Load posts to the screen from the database
//****************************************************
fun loadPost(){

  myRef.child("posts")
    .addValueEventListener(ValueEventListener{
        override fun onDataChange(@NonNull dataSnapshot: DataSnapshot?) {

            try {
                postElements.clear()
                postElements.add(Post("0","him","url","add"))
                postElements.add(Post("0","him","url","ads"))

                //Hashmap : Key and value (represents the post and node)
                var td= dataSnapshot!!.value as HashMap<String,Any>

                for(key in td.keys){
                    var post= td[key] as HashMap<String,Any>

                    postElements.add(Post(key,
                            post["text"] as String,
                            post["postImage"] as String
                            ,post["userUID"] as String))
                }

                adpater!!.notifyDataSetChanged() //notify when there's an update in the adapter
            }catch (ex:Exception){}
        }

        override fun onCancelled(p0: DatabaseError?) {

        }
    })

}

Comment: what do you mean by "It's telling me that the interface needs a constructor", nice try, but could you be a little more specific about the problem? because I would rather say, that **an interface cannot have constructors**, by design.
Comment: Yes, an interface can't have a constructor. However, that's what the compiler shows.
Comment: Any idea how to implement the  .addValueEventListener?
Comment: Sorry. This is the message:
Comment: Interface ValueEventListener does not have constructors
Comment: @RasheedAlRasheed Please paste here the entire error that you get and the specific line at which it occurs. Please responde with @.
Answer: this is how the constructor of a ValueEventListener should look alike:
object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {

    }
}

which means, that you have to replace this one line
.addValueEventListener(ValueEventListener {

with:
.addValueEventListener(object : ValueEventListener {

see https://youtrack.jetbrains.com/issue/KT-7770 (concerning the code-converter)


Why is the deviance defined with a factor 2 (or likelihood ratio squared)?

Question: The deviance statistic is defined as
$$D(\mathbf{y}, \hat{\mu}) = 2 \Big( \log p(\mathbf{y} | \hat{\theta}_s) - \log p(\mathbf{y} | \hat{\theta}_0) \Big),$$
where $\hat{\mu} = \mathbb{E}(Y|\hat{\theta}_0)$.  I see the motivation in why we would define the deviance as a difference of log-likelihoods or just the logarithm of the likelihood-ratio, but why the factor 2? Why square the ratio? Does this introduce new information that we otherwise would not have insight to?

Edit: I have yet to find a satisfying answer, but could it be to do with having an approximate chi-squared distribution?
Comment: Hello, I figured this isn't worth a full response, but your edit is still up about not having a satisfying answer. I found this [Likelihood-ratio test](https://en.wikipedia.org/wiki/Likelihood-ratio_test) page from your Wilks' theorem page, which says that multiplying by −2 ensures that, in Wilks' theorem, the likelihood ratio converges to being chi-squared distributed if the null hypothesis is true. It gives the reference Silvey, S.D. (1970). Statistical Inference. London: Chapman & Hall. pp. 112–114. So that's a direct answer. Hope that helps, I enjoyed your post.
Answer: I'm not certain that this is the intended reason from the progenitor of the deviance measure, but it seems likely that the reason for the factor of two is to ensure that the deviance corresponds to an appropriate scaled version of the sum-of-squares in the normal case.  That is, in the case where you have a GLM using a normal distribution with variance $\sigma^2$ (i.e., standard regression) you get deviance values:
$$\begin{equation} \begin{aligned}
D_{TOT} = 2(\hat{\ell}_{s} - \hat{\ell}_0) &= \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{TOT}, \\[6pt]
D_{REG} = 2(\hat{\ell}_{p} - \hat{\ell}_0) &= \frac{1}{\sigma^2} \sum_{i=1}^n (\hat{y}_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{REG}, \\[6pt]
D_{RES} = 2(\hat{\ell}_{s} - \hat{\ell}_{p}) &= \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \hat{y}_i)^2 = \frac{1}{\sigma^2} \cdot SS_{RES}, \\[6pt]
\end{aligned} \end{equation}$$
where the log-likelihoods under the null model, actual model, and saturated model, are given respectively by:
$$\begin{equation} \begin{aligned}
\hat{\ell}_0 = \ln p(y|\hat{\theta}_0) \quad \quad \quad
\hat{\ell}_p = \ln p(y|\hat{\theta}_p) \quad \quad \quad
\hat{\ell}_s = \ln p(y|\hat{\theta}_s).
\end{aligned} \end{equation}$$
If you go through the algebraic derivation of these results you will see that the factor of two in the deviance cancels out with the $\frac{1}{2}$ in the exponential for the normal density.  Presumably the reason to have this factor is to define the deviance measures in a way that naturally extends the sums-of-squares in standard Gaussian regression.
Comment: @Kevin C: Yes.  Without the factor of two it would have a scaled cih-squared distribution (multiplied by $\tfrac{1}{2}$).
Comment: Hi @Ben , thanks, I think I can accept that! Does the 2 contribute to the statistic following a ChiSquared distribution at all? [Wilks' Theorem](https://en.wikipedia.org/wiki/Wilks%27_theorem#Use)


What is your recommended Banner/Slider module for D7?

Question: I am searching for module that create banner/slider effect for D7.
Have a check on this page:
http://drupal.org/node/418616
Mostly not yet port to D7.
What are your recommend modules?
Answer: I have used Views Slideshow a couple of times and it was quite easy to use. It's based on the jQuery Cycle Plugin. The port to D7 is in alpha, so you might want to give it a go and contribute back to help the module reach a stable state.
That said, a module is not strictly necessary to do things like this. It's surprisingly easy to implement the (well documented) jQuery Cycle Plugin yourself, directly from your theme. Just add the plugin and write about 10 lines of jQuery in a custom .js file.
Answer: @marcavangend is mostly right.
There is one other to consider which is Drupal 7 only: Rotating Banner.
It may not match your exact needs, but it is quite nice.

### Features

Various transition effects (fade, wipe, etc)
Rich Editor where you can pick a background image and add headlines and text areas
Supports inline editing and drag and drop
Creates blocks, you can make a bunch of them
Can be a static size, or will grow to the size of your largest / smallest image or the size of the region you put it in automatically
Comment: It looks like it's not maintained anymore. I am choosing between Views Slideshow and Nivo Slider. Views Slideshow looks like it's more robust. Will post here after I've compared them.
Answer: Check the Nivo Slider module.

Nivo Slider provides an easy and eye-catching way to showcase featured content. Nivo Slider gives administrators three important tools:

A simple method of adding slides to the slideshow.
An administration interface to configure slideshow settings.
Simple slider positioning using the Drupal block system.


Confidence interval for correlation

Question: I know the confidence interval of an estimated correlation can be calculated after performing Fisher transformation.
But I never figured out why. I also couldn't find the explanation online. Can someone point me to the right direction?
Comment: Sorry, but I find your question not very clearly expressed. What exactly do you want explained?
Answer: Nick Cox has a really good explanation in a 2008 Speaking Stata column from SJ that I will excerpt here:

pwcorr [DVM: Stata's pairwise correlation command] offers only a $p$-value from the
  standard $t$ test of whether the population correlation $\rho$ is really
  zero. .... The latter $t$ test cannot be converted into useful
  confidence intervals, because once the population correlation is
  really not zero, the sampling distribution of estimates $r$ is
  substantially skewed, even for large sample sizes. That should not
  seem surprising, given that correlations are constrained to fall
  within $[−1, 1]$. Getting at the form of the distribution is a messy
  problem with, for the most part, only complicated exact solutions, but
  for practical data analysts an attractive way forward is offered by a
  suggestion of Ronald Aylmer Fisher (1890–1962): even though $r$ usually
  has an awkward skewed distribution, the inverse hyperbolic tangent, or
  atanh, of $r$ is much better behaved. This transform, within statistics
  often labeled Fisher's $z$, is said to be normally distributed to a good
  approximation. The basic tactic is now evident: apply standard
  normal-based technique on the $z$ scale, and then back-transform using
  its inverse transform, the hyperbolic tangent, or tanh.

Bootstrapping is a more modern alternative to the classical transformation approach.

Confidence interval for correlation


I am unsure how to record how many times a mouse was clicked in a certain area

Question: I'm fluent in java, and have messed with vb.net, but I prefer java. I wish to make a program that ++'s a variable everytime I click my mouse in a certain coordinate on my screen. Not sure how to record when a mouse click has happened outside of the program's forms.
Comment: This might help you [Java Robot](http://stackoverflow.com/questions/19185162/how-to-simulate-a-real-mouse-click-using-java)
Answer: This can't be done in pure Java but people have written JNI libraries that can capture global mouse and keyboard events. Take a look at
https://github.com/kwhat/jnativehook


How will the limit $\lim \sin(A^{n})$ behave for $|A| > 1$?

Question: While answering to the following question

Problem. Find the range of $x$ for which $\displaystyle \sum_{n=0}^{\infty} (-1)^{n} \sin(x^{-n})$ converges.

Unlike some careless answerers who merely claimed that this converges only for $|x| > 1$, I faced a hard question:
Question. Is there any $|A| > 1$ such that $\sin (A^{n})$ converges? (Of course, I put $A = x^{-1}$ here.)
I literally have no idea on it since the behavior of the sequence depends on $n \mapsto A^{n} \text{ mod } 2\pi$ and I have no idea how it behaves for values of $A$.
Actually I suspect that there is a number $A > 1$ for which $\sin (A^{n})$ converges. But this is just a groundless guess, anyway.
Do you have any idea regarding this one?
Comment: Do you have to answer your question to solve the problem? or you already have solution to the problem, but just curious about the question?
Comment: @i707107 As you see, my question is logically just a necessary condition for the problem. I failed to manage both of them.

In fact, this is a problem I saw in some QnA site, and none gave a satisfactory answer. I'm sure that even the one who made this question was *not* aware of this delicacy.
Answer: It can be shown that
$$
\mathcal{D}=\{|A|>1 : \sin(A^n) \textrm{ diverges.}\}
$$
is dense. (I conjecture that $\mathcal{C}=\{|A|>1: \sin(A^n) \textrm{ converges.}\} $ has measure zero, do not know how to deal with complex exponentials ---> now I do know.)
This follows from a result on equidistribution:

For real numbers $\theta>1$, is is shown in  Koksma's
  paper that
  $\theta^n$ is equidistributed modulo $1$ for almost all $\theta>1$.
  Equidistribution modulo $2\pi$ is just a minor modification of Satz 2
  in the paper.

Then the density of $\mathcal{D}$ follows from considering $A=re^{i\pi\frac{k}{m}}$ for $k,m$ fixed integers. In fact
$A^{2mn}=(r^{2m})^n$, and for almost all $r^{2m}>1$, $(r^{2m})^n$ is equidistributed modulo $2\pi$.
A stronger result of the above(in terms of error term) is shown in
Leveque's paper.
Edit: Proof of my conjecture
Let $A=re^{i \theta}$, so $A^n=r^ne^{in\theta}$. Suppose that $\theta\neq  k\pi$ for any integer $k$. Then there is a subsequence $n_j$ for $j=1,2,\cdots$ such that
$$\sin n_j\theta >\frac 12 \ \ \textrm{ for all }j. $$
Now, $$\sin A^n = \frac{e^{-r^n\sin n\theta}e^{i r^n\cos n\theta}-e^{r^n\sin n\theta}e^{-i r^n\cos n\theta}}{2i}$$
Since $|v-w|\geq ||v|-|w||$ for any complex $v, w$,
$$|\sin A^{n_j}|\geq \frac{1}{2} \left|e^{r^{n_j}\sin n_j\theta}-e^{-r^{n_j}\sin n_j\theta}\right| $$
Since $r>1$, the above $\rightarrow\infty$ as $j\rightarrow\infty$.
Hence, if $A=re^{i\theta}$, with $\theta \neq\pi \textrm{ mod }2\pi$, then the sequence $\sin A^n$ diverges. This proves my conjecture.
$$\mathcal{C}\textrm{ has measure zero.}$$
Further, we see that $\mathcal{C}\subset \mathbb{R}$, and has measure zero for the Lebesgue measure on $\mathbb{R}$.
Edit2
I finally found references that partially settles your problem.
Pisot and
Kawapisz
We have (1) from Pisot, (2) from Kawapisz.

(1) If a real number $\lambda$ is transcendental, then the series $$
  \sum_{n=0}^{\infty} \sin^2 (\pi\lambda x^n)$$ is divergent for all
  $x\geq 1$.
(2) If $x$ is algebraic, and there exists $\lambda\neq 0$ such that $$\sin (\pi\lambda x^n)$$ converges to $0$, then $\lambda \in \mathbb{Q}(x)$.

With $\lambda=1/\pi$, there does not exist any real number $x\geq 1$ such that
$$
\sum_{n=0}^{\infty} \sin^2 x^n$$
converges.
Therefore, the a partial conclusion to your problem is:

The series $$ \sum_{n=0}^{\infty} (-1)^{n} \sin(x^{-n})$$ absolutely converges if and only
  if $|x|>1$. If $|x|<1$ and $x$ is algebraic, then the series does not converge.

Still, whether or not there exists a real number $x>1$ such that $\sin x^n$ converges, is open.  What we know so far is: if $x>1$ algebraic then $\sin x^n$ does not converge to $0$.
Answer: One observation.
Let, w.l.o.g. $1<A<2\pi$. Then, let, $n=\min_{k}\{k\in \mathbb{N}:A^{k}<2\pi,\ A^{k+1}\ge2\pi\}$. So the $n+1$ st term of the sequence $A^n\mod{2\pi}$ is $A^{n+1}-2\pi m$ for some $m\ge 1$. Let, $A_1:=A^{n+1}-2\pi m$. Now, $A_1\le 2\pi A-2\pi$. So, if $2\pi A-2\pi \le A\Rightarrow A\le \frac{2\pi}{2\pi -1}$, then, $A_1\le A$. now, again define $n_1:=\min_{k}\{k\in \mathbb{N},k\ge n+1: A_1^{k}<2\pi, A_1^{k+1}\ge 2\pi\}$ and again set $A_2:=A_1^{n_1+1}-2\pi m_1$ and now, we can see that $A_2\le A_1$. In this way one can find a decreasing sub-sequence ${A_n}$ in the orbit of $A^n \mod{2\pi} $.
Comment: $\sin((A+2\pi)^2) \ne \sin(A^2)$.
Comment: I am not using this anywhere, all I'm saying is that once you have a term $A^n$ which is the first term to cross $2\pi$, then call it $A_1$ and similarly if you define $A_2,A_3,\cdots $ etc. then they should form a non-increasing sequence.


Paginando um Datagridview

Question: Boa tarde...
Tenho uma datagridview que carrega varias linhas, andei pesquisando na net como posso paginar este datagridview, mas não consegui realizar tal procedimento, por não ter tanta experiencia em c#, então via aqui pedir mais uma vez a ajuda do forum para conseguir paginar o datagridview, ou seja cirar paginas no datagridview.
Segue minha tela

segue o código que carrega o datagrid
private void ListaGrid()
        {
            try
            {
                SqlCommand tabnet = new SqlCommand("usp_TabelaPrecosNet", conexaoDADOADV(true));
                tabnet.Parameters.AddWithValue("@CODTABELA", this.cb_tabela.Text);
                tabnet.CommandType = CommandType.StoredProcedure;
                tabnet.ExecuteNonQuery();

                SqlDataAdapter dados = new SqlDataAdapter(tabnet);
                DataTable dtLista = new DataTable();
                dados.Fill(dtLista);

                dgw_listanet.DataSource = dtLista;

                dgw_listanet.Columns["CODPRODUTO"].HeaderText = "COD.PRODUTO";
                dgw_listanet.Columns["DESCRICAO"].HeaderText = "PROD. DESCRIÇÃO";
                dgw_listanet.Columns["IPI"].HeaderText = "% IPI";
                dgw_listanet.Columns["PRECO"].HeaderText = "PREÇO NET";
                dgw_listanet.Columns["MOEDA"].HeaderText = "TIPO MOEDA";

            }
            catch
            {
                MessageBox.Show("Não exstem dados digitados para a consulta, por favor verificar!!!");
                return;
            }
        }

Answer: Primeiramente você devera alterar sua procedure para que retornem os valores paginados passando 2 paramentos a mais.
-Index da pagina;
-Quantidade de registros requisitados.
CREATE PROCEDURE dbo.proc_PaginadaExemplo
(
@IndexPagina int,
@QuantidadeRegistros int
)
AS

SET NOCOUNT ON

DECLARE @PrimeiroRegistro int, @UltimoRegistro int

SELECT @PrimeiroRegistro = (@IndexPagina - 1) * @UltimoRegistro
SELECT @UltimoRegistro = (@IndexPagina * @QuantidadeRegistros + 1);

WITH ResultadoTemp as
(
SELECT ROW_NUMBER() OVER(ORDER BY <CampoOrdenacao> DESC) as NumeroLinha,
s.<campo1>, m.<campo2>, s.<campo3>, l.<campo4>
FROM dbo.<tabela> m
INNER JOIN dbo.<tabela2> s
ON s.<campo1> = m.<campo2>
)
SELECT top (@UltimoRegistro-1) *
FROM ResultadoTemp
WHERE NumeroLinha > @PrimeiroRegistro
AND NumeroLinha < @UltimoRegistro

SET NOCOUNT OFF
GO

E na sua tela devera conter campos e botões para controle de paginação e quantidade de registros.
Comment: Leandro boa tarde e obrigado pela atenção, agora deixa me ver se entendi, preciso colocar todo esta query dentro da minha porcedure e isso ou tenho que criar uma nova procedure.
Comment: Voce deve implementar esses parâmetros na sua query. Em suma alterar o select do exemplo para a sua query na procedure.

Paginando um Datagridview


XML issue with array indexing

Question: <?xml version="1.0" encoding="ISO-8859-1"?>
<servers>
  <server serverid="server1" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port>
    <port portid ="port2" asset="Sample"  ></port>
  </server>

  <server serverid="server2" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port>
    <port portid ="port2" asset="Sample"  ></port>
    <port portid ="port3" asset="Sample"  ></port>
    <port portid ="port4" asset="Sample"  ></port>
  </server>
<server serverid="server1" asset="Sample" >
    <port portid ="port1" asset="Sample"  ></port>
    <port portid ="port2" asset="Sample"  ></port>
    <port portid ="port3" asset="Sample"  ></port>
  </server>

</servers>

I am trying to add Server XElements and port XElements to the existing XML DOC.I tried the following code,
int[] test = new int[3];
string[] PortName1 = new string[3];
string[] PortId1 = new string[3];
PortName1[0]="portname1";
PortName1[1] = "portname2";
PortName1[2] = "portname3";

PortId1[0] = "port1";
PortId1[1] = "port2";
PortId1[2] = "port3";
var fileName = @"C:\sample.xml";
var xdoc = XDocument.Load(fileName);

var server =
    new XElement("server",
        new XAttribute("serverid", ServerId),
        new XAttribute("name", ServerName),
            test.Select(sample =>
                new XElement("port",
                    new XAttribute("asset", PortName),
                    new XAttribute("portid", PortId)
                ))
        );

Everything is working fine,but the problem is PortName & PortId are string array variables.Dont know how to get indexed dynamic values for each iterate of "test".For me everytime it is getting the zero index values only.
Answer: Why do you need test array? You should use PortName1 array or PortId1, like this:
var portIdIndex = 0; // declare variable somewhere before

PortName1.Select(port =>
             new XElement("port",
                 new XAttribute("asset", port),
                 new XAttribute("portid", PortId1[portIdIndex++])
             ))

Or like this:
PortName1.Select(port =>
             new XElement("port",
                 new XAttribute("asset", port),
                 new XAttribute("portid", PortId1[PortName1.IndexOf(port)])
             ))

Or you can combine PortId and PortName using anonymous types:
var portData = new [] {
    new { PortName="Port 1", PortId = 1},
    new { PortName="Port 2", PortId = 2}
};

portData.Select(port =>
     new XElement("port",
         new XAttribute("asset", port.PortName),
         new XAttribute("portid", port.PortId)
     ))

Get data from user input:
var portData = new List<string[]>();
// here we need to get data like this:
var portName = Console.ReadLine();
var portId = Console.ReadLine();
portData.Add(new string[]{portName, portId});

portData.Select(port =>
     new XElement("port",
         new XAttribute("asset", port[0]),
         new XAttribute("portid", port[1])
     ))

A little demo.
Comment: :PortName & PortId's are dynamic,sometimes 2(size) & sometimes 3,it depends on userinput.so can u suggest,under portdata how to generate dynamic portname's & portId's
Comment: am getting error @Tuple (i guess tuple is a class that needs to define)
Comment: It is well known type of .Net http://msdn.microsoft.com/en-US/library/dd268536(v=vs.110).aspx, which version of .net do you use?
Comment: It should be available. Hm, ok, let's use array, see my updated answer.
Comment: @user1676709: The version of Visual Studio you're using isn't actually relevant - which version of .NET are you targeting in your project? That will determine which types are available.
Comment: actually am getting error @ portName, portId (Cannot implicitly convert type 'string[]' to string).@ Console.ReadLine(); passing an array.
Comment: @user1676709 Really? That's odd, please see my demo how it should work: http://dotnetfiddle.net/xdQITq
Comment: @Tony really your demo helped me a lot.And thanks a lot for your help & patience till the issue get resolved.Thanks a lot again.
Answer: If you're using .NET 4, you can just use Zip:
var server =
    new XElement("server",
        new XAttribute("serverid", ServerId),
        new XAttribute("name", ServerName),
            PortName1.Zip(PortId1, (name, id) =>
                new XElement("port",
                    new XAttribute("asset", name),
                    new XAttribute("portid", id)
                ))
        );

If you're not using .NET 4 or later, you can implement Zip very easily in your own code - Eric Lippert has sample code in a blog post.
(As a side note, I'd encourage you to follow .NET naming conventions - I'd change the names of PortId1 and PortName1 to portIds and portNames for example.)

XML issue with array indexing


How to split some elements from array by semicolon and add them as new elements to original array

Question: I have for example this array
String[] mailToCc = {"firstname.lastname@example.com; email@example.com;", "firstname.lastname@example.com"};

1st element are 2 mails with a semicolon at the end. What I want is to separate those 2(they can be found on any element of the array, not always the first) and add them to the originl array like new elements.
This is how it should look
["firstname.lastname@example.com", "firstname.lastname@example.com", "firstname.lastname@example.com"];

This is my attempt
import java.util.ArrayList;

import java.util.Arrays;
public class Main
{
    public static void main(String[] args) {
        ArrayList<String> updatedMailToCc = new ArrayList<>();
        String[] mailToCc = {"firstname.lastname@example.com; email@example.com;", "email@example.com"};

        for (String element : mailToCc) {
            String[] splitElements = element.split(";");

            // Add the original element itself
            updatedMailToCc.add(element);

            // If it could be split, add each part as a new element
            if (splitElements.length > 1) {
                 updatedMailToCc.addAll(Arrays.asList(splitElements));
            }
       }

       // Convert the ArrayList back to an array if needed
       mailToCc = updatedMailToCc.toArray(new String[0]);

       // Print the updated array
       System.out.println("resultado =" + Arrays.toString(mailToCc));
    }
}

But instead of getting what I need I get this result
["firstname.lastname@example.com; firstname.lastname@example.com;", "email@example.com",  "firstname.lastname@example.com", "email@example.com"]

Comment: Even though you have two answers, it will be a good lesson to run this code in a debugger. Set a breakpoint early. Then, run the code one-step-at-a-time, observing the values of variables at each step. Debugging is a good skill to have. If you want to become a software developer, or otherwise regularly create software, it will be a necessary skill.
Comment: thanx, I was doing that but I guess I was not doing it the right way.
Answer: Issue is that you are adding the original element to the updatedMailToCc list regardless of whether it contains a semicolon or not thats why you are seeing the original string with the semicolons in the result.
To fix this, you should only add the split elements to the updatedMailToCc list and skip adding the original element.
import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> updatedMailToCc = new ArrayList<>();
        String[] mailToCc = {"firstname.lastname@example.com; firstname.lastname@example.com;", "email@example.com"};

        for (String element : mailToCc) {
            String[] splitElements = element.split(";");

            // If it could be split, add each part as a new element
            for (String splitElement : splitElements) {
                if (!splitElement.trim().isEmpty()) { // Avoid adding empty strings
                    updatedMailToCc.add(splitElement.trim());
                }
            }
        }

        // Convert the ArrayList back to an array if needed
        mailToCc = updatedMailToCc.toArray(new String[0]);

        // Print the updated array
        System.out.println("resultado = " + Arrays.toString(mailToCc));
    }
}

Answer: The problem is that you both add the base element and its decomposition, so you duplicate things that have semicolon

Don't bother to check the amount of parts you have, add them all everytime, but not the base element. Also change a bit the regex to avoid keeping space around your emails
for (String element : mailToCc) {
    String[] splitElements = element.split("\\s*;\\s*");
    updatedMailToCc.addAll(Arrays.asList(splitElements));
}

Another way would be to  add the base element conditionaly
for (String element : mailToCc) {
    String[] splitElements = element.split("\\s*;\\s*");

    if (splitElements.length > 1) {
         updatedMailToCc.addAll(Arrays.asList(splitElements));
    } else {
         updatedMailToCc.add(element);
    }
}


Creating config schema file for mutable data

Question: I have a custom module where I need to have a couple different types of configuration, both immutable and mutable. The immutable portion contains a feed URL for a couple different sites, so I have /my_module/config/install/my_module.settings.yml set up like this:
sites:
  site1:
    channel_url: 'http://www.site1.org/feed/channels'
  site2:
    channel_url: 'http://www.site2.com/feed/channels'
list_time: 24

That works fine, and I can read from it via $config-get();.
The second part of my settings involves mapping of tids between the two sites (used for importing video nodes from one site to another. My initial thought was to modify the settings like so:
sites:
  site1:
    channel_url: 'http://www.site1.org/feed/channels'
    mappings:
      1: 1
      2: 2
      3: 3
  site2:
    channel_url: 'http://www.site2.com/feed/channels'
    mappings:
      7: 7
      8: 8
      9: 9
list_time: 24

However, since this is mutable, it appears that this isn't allowed (based on the error messages I get when I try to run $config->set().
From what I'm finding, it looks like I need to have a separate schema config file for my mapping data. I'm still wading through docs, but if someone could verify if I'm correct in my thinking and maybe provide a sample of what my schema should look like, I'd appreciate it.
UPDATE: Reading through this change record, it appears that I can write to my settings file if I declare it in my form class in getEditableConfigNames(), which I've done:
protected function getEditableConfigNames() {
  return ['my_module.settings'];
}

It also appears that, according to the error message I get, I need to retrieve it with \Drupal\Core\Config\ConfigFactoryInterface::getEditable()
Drupal\Core\Config\ImmutableConfigException: Can not set values on immutable configuration my_module.settings:sites. Use \Drupal\Core\Config\ConfigFactoryInterface::getEditable() to retrieve a mutable configuration object in Drupal\Core\Config\ImmutableConfig->set() (line 27 of core/lib/Drupal/Core/Config/ImmutableConfig.php).

Just keep swimming....
UPDATE2: Base on @berdir's comment below, I'm showing what I have, since in my original question, I didn't state that I am already using the ConfigFormBase class:
class MyModuleAdminForm extends ConfigFormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'my_module_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildform(array $form, FormStateInterface $form_state) {
    $form = array();
    $channels = array();

    // build form here

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  protected function getEditableConfigNames() {
    return ['my_module.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->config('my_module:settings');

    foreach($values as $site => $mappings) {
      if (is_array($mappings)) {
        foreach ($mappings as $source_channel => $target_channel) {
          $config->set('sites',[$site => ['mappings' => [$source_channel => $target_channel]]]);
        }
      }
    }
     $config->save();

    parent::submitForm($form, $form_state);
  }
}

However, this still gives me the same error. Am I using $this->config() incorrectly? Or do I still need to use getEditable() somewhere?
Answer: Mutable or Immutable has nothing to do with config schema, that's something else.
getEditableConfigNames() only works if you actually implement \Drupal\Core\Form\ConfigFormBase and $this->config().
Otherwise you need to explicitly get the config.factory service or \Drupal::configFactory() and then call getEditable() on that, instead of get().
Comment: I updated my original question with more details.
Answer: I got past this error with the code I had above after figuring out one tiny issue.  The code in ConfigFormBaseTrait::config() (called with $this->config() in a form that uses ConfigFormBase) has the following code:
if (in_array($name, $this->getEditableConfigNames())) {
  // Get a mutable object from the factory.
  $config = $config_factory->getEditable($name);
}
else {
  $config = $config_factory->get($name);
}

For some reason in_array() was returning FALSE, even though I had my_module.settings returned from getEditableConfigNames(). The eagle eyed will note that in my last update in the original question I had
$this->config('my_module:settings');

but in getEditableConfigNames() I had
return ['my_module.settings'];

The difference was the period vs the colon in the config value. Sigh.
With that change, config() loads getEditable() instead of get(), and I'm off and running.
Answer: when it's immunable you should use configFactory.
for example:
$alertConfig = \Drupal::configFactory()
  ->getEditable('sitewide_alert.settings');

$alertConfig->set('alert_styles', "test|TestValue")->save();