how can i make all the filenames the same length by adding spaces to it?

Question: i want to make the filename+spaces=211 characters
but the problem is that if the file name characters = 30
i would need  181 spaces
while if file name characters = 80
i would need  131 spaces
i have tried advanced renamer
tags options + spaces .
<Name>

..
and even this script in the scripts section
var maxLength = 25;
var name = item.name;
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");
var numSpaces = maxLength - name.length - date.length;
var spaces = "";
for (i = 0; i < numSpaces; i++) spaces += " ";
return name + spaces + date;

but it give me this error
name is not defined in the line 3
Comment: What is the value of numSpaces in your example above before you use the for loop? Also looks like you have a typo, (var i = 0;) ==> you are missing the var in your forloop.
Comment: If you fix that typo your code will word.
Comment: Possible duplicate of [Is there a JavaScript function that can pad a string to get to a determined length?](https://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng)
Answer: You could use String#padEnd(), to add whitespaces to the end of your filename strings so that the resulting string has a minimum length a specified by you.
Consider the snippet below until where fileNameA.padEnd(211) returns a new string with the same leading characters as fileNameA, but with whitespaces padding the remainder of the string such that the string has length 211:

const fileNameA = 'your file name';
const fileNameB = 'some other big file name';

const paddedFileNameA = fileNameA.padEnd(211);
const paddedFileNameB = fileNameB.padEnd(211);

console.log(`
paddedFileNameA:
"${paddedFileNameA}"
length of paddedFileNameA: ${paddedFileNameA.length}
`)
console.log(`
paddedFileNameB:
"${paddedFileNameB}"
length of paddedFileNameB: ${paddedFileNameB.length}
`)

Update
I'm not familiar with the scripting feature set in Advanced Renamer, however you might find this works for you:
/*
Set length to 211
*/
var maxLength = 211;
var name = item ? item.name : '';
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");

/*
Ensure variables are not undefined or null
*/
if(!name) {
    name = '';
}
if(!date) {
    date = '';
}

/*
Construct result string
*/
var result = name;
for (i = 0; i < (maxLength - (name.length + date.length)); i++) {
    result += ' ';
}
result += date;

return result;

Comment: your script is great but it doesn't work on advanced renamer ....
the reason that i use it that there's item.name and batch rename so i don't have to type the name for every single file ! https://www.advancedrenamer.com/user_guide/method_script
what do you suggest ?
Comment: @minanageh thanks - just updated answer. Does that help you?
Comment: i don't what the is problem !! it keeps saying invalid  script
Comment: what happens if you remove the very last `}` character in the updated code?
Comment: @minanageh sorry, just noticed the `item` and `index` were out of order. I just revised the code in the updated part of the answer.
Comment: thanks ... someone give the script that works in another forms
Comment: "just noticed the item and index were out of order" it works but it doesn't do anything ....
Answer: the script that works using advanced Renamer
var maxLength = 222;
var name = item.name;
var date = app.parseTags("<Year Modified><Month Modified><Day Modified>");
var numSpaces = maxLength - name.length - date.length;
var spaces = "";
for (i = 0; i < numSpaces; i++) spaces += " ";
return name + spaces + date;

credits  David Lee from advanced Renamer forms
Comment: please note that  "if you set the filename +extension to 227 characters then the rest of your file path including volume name must be shorter than 33 characters otherwise Windows will throw an error when you run the batch. "


Resources packs are missing from the DLC page in Dead Space 3. How can I spend my ration seals?

Question: As you know, the game has a mechanism that allows you to earn ration seals. These seals can then be used to buy resources packs from within the game, which give the player with some resources and some "MK-V" parts to upgrade your weapons. The advantage being that the "MK-V" parts, unlike their normal counterparts, have extra stats bonus.

However, many PC players (both on Steam and off Steam) have experienced problems with the ration seals: they can't spend them.
They're supposed to be purchasable with real money or with ration seals. But for some reasons, for many players, the ration seals don't appear among the list of DLCs anymore.
Is there a way to fix this issue and spend ration seals to purchase resources packs as intended?
Comment: For what it's worth, I resorted to cheat engine to "trade" my resources packs into MK-V parts after the proposed solution no longed worked.. But I would discourage you of trying if you don't understand the implications.
Answer: UPDATE 6th September 2022: According to this post, the following solution doesn't work anymore, so ration seals can no longer be spent.

I just now tested this, and it looks like my solution no longer works. Might be that they decided to remove it completely, or their related servers are down/broken.

Old post:

TL;DR: You need a computer with Windows 8.1 or higher in order to perform the solution below. After you're done, you can keep playing on whatever operating system you usually use.

While I was searching up some information, I stumbled on some reasons as to why it might be happening:

The first one some people were bringing up was the fact that the game needs to connect to some remote server for the ration seals purchase to work. However, since the server was shutdown (they believe it was when Visceral Games died, the video game developer studio owned by Electronic Arts that worked on Dead Space).
The second hypothesis is the fact that it might be region locked. Some people who bought the game on Origin (before it was available on Steam) pointed out how they were able to buy resources packs with ration seals after using a VPN to set their location to the United States. Some of them commented how neither living in Europe nor in Canada allowed them to access it until using the VPN.
The third one I noticed is because I bought the game on Steam. Whenever I tried to boot the game, a banner was displaying on Origin, saying: "The Origin store is currently disabled because it was launched from another application". Trying to boot the game on Origin alone would boot it through Steam. Trying to boot the game on Steam alone would boot it through Origin. And trying to shut down both Steam and Origin, then booting the desktop icon, would launch both Origin and Steam. In all scenarios, the message keeps appearing and the resources packs are not available in the DLC page.

Some users suggested some solutions over there on EA forums, one of which worked for me.
Before doing the solution, make sure to:

Have a computer with Windows 8.1 or higher available for the procedure. Mine is running on Windows 7, so I borrowed a computer with Windows 10 just to do it.
Install the game through Steam/Origin on the computer with Windows 8.1 or higher.
Boot the game to have all the latest save files on the computer.

After making sure you have the game installed with all your saves on a computer with Windows 8.1 or higher, do the following:

Within Origin, go to your application settings and uncheck the option to launch on boot.
Exit Origin entirely (closing the window alone won't do; you have to right click on the process in the bottom right and exit).
Go to the install folder of Dead Space 3 then create a shortcut for the game on the desktop. Creating a shortcut through Steam won't work, as it will try to boot the game through Origin.
Download and install the EA Beta App through this link: https://www.ea.com/ea-app-beta. If your computer is running on Windows 7, you won't be able to install it.
Once the installation is done, boot EA Beta App and login using your Origin credentials.
While EA Beta App is running in background, use the shortcut you created on your desktop to launch the game. If you created a Steam shortcut, Origin will tell you that it can't boot while EA Beta App is running. If you created a desktop shortcut through the installation folder of Dead Space 3, it will boot through EA Beta App.
Load your saves. If your saves are missing because you borrowed someone else's computer, you forgot to follow the "Before doing the solution" steps. You need to shut down EA Beta App, boot Origin, launch the game normally. Origin will ask you to choose between the local saves and the cloud saves. Pick the cloud saves to retrieve your remote saves. Then close Origin and repeat from step 5.
Load a game and get to a Bench (in the Weapon Crafting Arena for example).
Open the DLC store. You can now spend 30 ration seals on a resource pack. Make sure you avoid pressing Enter or clicking on Purchase (with real money), or else your game will be stuck trying to load forever.
Once done, you can save your game, close EA Beta App, boot Origin and boot the game to synchronise your saves. Then you came resume playing normally.


TextView vertical center

Question: Andriod text view vertical center problem

My Code
<TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginLeft="10dp"
       android:fontFamily="@font/googlesansbold"
       android:text="Tance"
       android:lineHeight="1dp"
       android:gravity="center_vertical"
       android:textColor="@android:color/white" />

Answer: Instead of
android:gravity="center_vertical"

Try using
android:layout_gravity="center_vertical"

Comment: You need to post your code for xml file. so we can have some idea. Kindly post xml file code.
Comment: here is xml file   https://drive.google.com/open?id=1V2HBf-pz093xQfVu4HKCiqzfbXp971FR
Answer: The problem is that every font has extra padding. You can`t easily remove that padding.
You can to write own textView that extend AppCompatTextView and override onDraw.
The simplest way is to use that textView.
Using:
You need to hard code attribute android:height="dp" on your own preference
<NoPaddingTextView
    android:layout_marginTop="18dp"
    android:background="#c1c1c1"
    android:height="16dp"
    android:includeFontPadding="false"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:lineHeight="1dp"
    android:text="Tance"/>

Answer: Since the parent layout is a LinearLayout with horizontal orientation
and the size of the TextView is wrap_content,
use this attribute for the parent layout and not for the TextView:
android:gravity="center_vertical"

Comment: here is xml file drive.google.com/open?id=1V2HBf-pz093xQfVu4HKCiqzfbXp971FR
Comment: @Thomas I saw the layout and with this attribute the TextView **is** centered
Comment: @Thomas you don't need `android:gravity="center_vertical"` inside the TextView, only in the LinearLayout
Comment: @Thomas not `android:gravity="center|center_vertical"`, only `android:gravity="center_vertical"`

TextView vertical center


How does Close Enough interact with explosive weapons?

Question: I know that Gaige can effectively use elemental weapons with Close Enough - the skill that causes up to 50% of your missed shots to ricochet towards the target for reduced damage. However, I do not know what to think of rounds that explode on impact. I noticed that generally elemental weapons leave a small elemental mark on the point of impact and then deal elemental damage normally. What about rockets from RPGs and Torgue weapons? Their projectiles explode on impact and it's really hard to tell (with my limited playtime) if Close Enough has any influence on them.
Would a Torgue projectile explode on impact and then fly towards the enemy to do regular damage? Or would it explode twice? Or maybe explosions prevents ricocheting?
Answer: It depends on the projectile of the explosive weapon. If the explosive weapon cannot score critical hits (e.g. most rocket launchers, and weapons using folding fin rockets or grenades as ammo), it will not ricochet towards the target
If the explosive weapon can score critical hits (e.g. most explosive weapons using gyrojet projectiles as ammo), it will ricochet (even though they appear to explode on impact). More details regarding which explosive weapons can or cannot score critical hits here: Which explosive guns can cause critical hits?
I tested the ff. explosive weapons at the target practice at Marcus' shop:
Weapon   —   Ammo Type   —  Can ricochet with Close Enough
Unkempt Harold   -   Gyrojet   -   Yes
KerBlaster   -   Folding fin rockets  -  No
Badaboom   -   Rockets  -   No


Node.js Gmail API how can I access the contents of an email?

Question: I'm a noob to Node.js and the Google Gmail API. However, I am familiar with client-side JavaScript. I was able to analyze the code and understand it.
I was able to follow this guide (https://developers.google.com/gmail/api/quickstart/nodejs) to access the labels in my Gmail account (code below):
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Gmail API.
  authorize(JSON.parse(content), listLabels);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels(auth) {
  var gmail = google.gmail('v1');
  gmail.users.labels.list({
    auth: auth,
    userId: 'me',
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var labels = response.labels;
    if (labels.length == 0) {
      console.log('No labels found.');
    } else {
      console.log('Labels:');
      for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        console.log('- %s', label.name);
      }
    }
  });
}

According to (https://developers.google.com/gmail/api/v1/reference/users/messages/delete#javascript), this code will allow me to read emails. However, while the page (linked above) explains the parameters for the functions below, it doesn't explain how to get the message ID. The function asks for an integer (I guess) to determine which message to return. However, there is no information explaining how to get the message ID in the first place. Am I supposed to use a loop and get all the emails and then figure out which I want? What should message ID be? Code below:
/**
 * Delete Message with given ID.
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} messageId ID of Message to delete.
 */
function deleteMessage(userId, messageId) {
  var request = gapi.client.gmail.users.messages.delete({
    'userId': userId,
    'id': messageId
  });
  request.execute(
    function(resp) { });
}

Thank you.
Answer: I was actually wondering this today and I managed to use the listLabels example to figure it out. The first function findMessages will print the response which contains the id's of the last 10 messages. Then it passes the array of messages to the next function which will recursively print the messages.
function findMessages(auth) {
  var gmail = google.gmail('v1');
  gmail.users.messages.list({
  auth: auth,
  userId: 'me',
  maxResults: 10,
  q:""
}, function(err, response) {
    console.log(response);
    console.log("++++++++++++++++++++++++++");
    printMessage(response.data.messages,auth);
  });
}

function printMessage(messageID,auth) {
  var gmail = google.gmail('v1');
  gmail.users.messages.get({
  auth: auth,
  userId: 'me',
  id:messageID[0].id
}, function(err, response) {
    console.log(response);
    messageID.splice(0,1);
    if(messageID.length>0)
     printMessage(messageID,auth);
   else {
     console.log("All Done");
   }
});
}


Determining length of a part of a DNA sequence

Question: I'm being given an DNA sequence, for example:

ATTAGGGCCCATTACGCTGACGAGCACTTG

I need to write a function, given two inputs (the DNA sequence, and A, C, G or T) determine the length of the longest possible part of the sequence containing only that specific letter.
dna = 'ATTAGGGCCCATTACGCTGACGAGCACTTG';
giveLength(dna, 'A')
ans =
       1
giveLength(dna, 'C')
ans =
       3

I had started out like this:
function length = giveLength(sequentce, amino)
[begin, end] = regexp(sequentie, amino , 'start', 'end')
pos = 1;
if isempty(begin)
    error('Doesn't exist!')
else
for i = 1:length(begin)
    if begin(i) ~= end(i)
        if (end(i) - begin(i)) > (end(i) - begin(i)) || (end(i) - begin(i)) > 1
            pos = end(i) - begin(i);
        end
    end
end
length = pos;
end

Obviously this doesn't work, because for each letter the begin and starting position are the same, and I can't write amino+ either to let it select the parts that correspond.
Help would be highly appreciated!
Answer: You can just subtract end from start vectors to get the length of the matching string. Finding the max gives maximum length. This one is also a bit more general, in that you can pass it a sequence such as 'AG' and it will return the number of repetitions of that pattern...
function len = giveLength(sequence, amino)
[begin_i, end_i] = regexp(sequence, sprintf('(%s)+', amino) , 'start', 'end');
if isempty(begin_i)
    error('Doesn''t exist!')
else
len = (max(end_i - begin_i) + 1) / numel(amino);

BTW, try to avoid using variable names such as length, end etc which are either internal functions or keywords.
Comment: Thanks, this works! Yeah, I didn't use those variables in my real script though. I only translated them to english and then forgot to name them otherwise. Thanks for the tip though!
Answer: I would use this answer and adapt it to your needs.
J=find(diff([dna(1)-1, dna]));
repetition=diff([J, numel(numCode)+1]);
symbol=dna(J)

Now having this little preprocessing done, you can query the length for a certain symbol
max(repetition(symbol=='C'))


With peewee how connect to existing SQLite db for reading only

Question: I have a silly question.
This my code:
<code>  from peewee import *

   db = SqliteDatabase(None)

   class Base(Model):
       class Meta:
           database = db

   class Table(Base):
       a_date = DateField()
       url = CharField()

   def __main()__
       parser = argparse.ArgumentParser()
       parser.add_argument('--db-dir', action='store')
       args = parser.parse_args()
       db_path = os.path.join(args.db_dir, 'data.db')
       try:
           db.init(db_path)
           db.connect()
           query = Table.select().order_by(Table.a_date.desc()).get()
       except Exception:
           sys.exit(1)
       else:
           print(query.url)

       sys.exit(0)

   if __name__ == '__main__':
       main()
</code>
This code is working fine, but if the file db not exist db.connect always create it.   How I can prevent this ?
Another question is , How can query table database for this field without declare the peewee Model?
Thanks
Answer: If I understand correctly peewee doc (http://docs.peewee-orm.com/en/latest/peewee/database.html), they use the api provided by python in order to connect to sqlite.
Which means you have to deal with this api (https://docs.python.org/2/library/sqlite3.html#sqlite3.connect), and the connect method always create the database beforehand.
I however believe that you can pass a custom Connection class to this method (parameter factory), you could define your behaviour in this custom class.
<code>import os

from sqlite3 import Connection
from peewee import *

class CustomConnection(Connection):
    def __init__(self, dbname, *args, **kwargs):
        # Check if db already exists or not
        if not os.path.exists(dbname):
            raise ValueError('DB {} does not exist'.format(dbname))
        super(CustomConnection, self).__init__(dbname, *args, **kwargs)

db = SqliteDatabase('mydatabase', factory=CustomConnection)
</code>
Comment: Your answer is good, Thanks. But on this case I can check for file exists before do any db accion.


What would happen to my inactive Clash of Clans account?

Question: Most of the villages we see during attack research seem to be active. Sometimes you find an opponent that has been inactive for a couple of days and bingo, his extractors are full. but I still consider this as an active player.
Let's assume I delete the app or I do not connect to the app for several months. What would happen then ? Would I still visible when opponents go for matchmaking ? Would I earn an infinite shield because of inactivity ?
Comment: Possible duplicate of [What happens if you leave your Clash of Clans game for a week?](http://gaming.stackexchange.com/questions/184174/what-happens-if-you-leave-your-clash-of-clans-game-for-a-week)
Comment: @aytimothy not really ; the point of my question is to know what happens after several months of inactivity, and not a couple of days
Answer: I took a break for about a year and just reinstalled it for this question.  Below are screenshots of my base immediately after opening the app.
All of my collectors were almost full, I was kicked out of my Clan, I am not placed in any league, and my land has a lot of trees/rubbish on it (usually I had it clean).
Their EULA must have changed, as I had to accept this again:

Collectors almost full and rubbish everywhere:

Top of defense log:

Bottom of defense log (30 days max I guess?), was still visible to attackers, no infinite shield.

Proof, nothing in my attack log:

I also had a lot of notes about the updates and changes they made to read through but my base was not deleted.
Comment: To add to this, from what I have been reading longer periods of inactivity seems to put you lower down onto the matchmaking list. So you will have a gradual decrease in raids the longer you are inactive.
Answer: If you are inactive, or delete the app, it will be just like if you are away for a couple of days, except longer. Your collectors and mines will be full, and you will have been raided. A Lot.


Ubuntu Server MOTD

Question: I have a Ubuntu server 16.04 installation and I'm trying to get rid of the message of the day.
I've already disabled all the files in /etc/update-motd.d/ and
run-parts /etc/update-motd.d/
Doesnt't output anything.
In addition to that I've commented out the motd lines in those 2 files:
/etc/pam.d/login
/etc/pam.d/sshd

The problem is that I'm still getting system information printed whenever I login over ssh.
Does anyone know where this could be coming from?
Answer: After some poking around in the sshd_config file, I found the Banner option and that referenced the file /etc/issue. Said file contained exactly the message I was seeing on each ssh login. I've commented out the Banner option and that fixed the issue. Hope that helps someone in the future.

Ubuntu Server MOTD


Equipment Grounding Bar for a Data Closet?

Question: I'm building out a data closet for my home office using a Leviton structured media cabinet (plastic). Some of my equipment (routers, switches) have lugs for external grounds and use 'brick' power supplies without ground plugs.
I found a nice 6" grounding bar pre-drilled with tapped holes from an industrial supplier, and I'm planning to mount it in the cabinet. My question concerns connecting it to the home's grounding system. As part of the upgrades I have an accessible metal junction box with EMT running all the way back to the service entrance within about 8 feet of the data cabinet. Would it be acceptable practice to take a green #12 stranded wire, crimp ring terminals onto each end, and connect one end to the ground screw in the junction box and the other end with a screw to one of the tapped holes in my new grounding bar?
Comment: Not an expert, so just a comment. But I *think* that the proper way to do this is to connect it only on the *outside* - e.g., put a metal cover on the box and connect the screw/wire to the front.
Comment: Does someone make a grounding clamp that I could attach to the outside of the EMT?
Comment: I don't believe there's actually a problem with going into the box to the box grounding screw. A pipe grounding clamp could be used on the outside of the EMT, though I don't know if that would be *listed* for that application as opposed to grounding a water pipe as commonly intended. A 3/4" ground rod clamp might also work for 1/2" EMT (OD of 0.707") or you could just use a **metal box grounding clip** or a thread-forming grounding screw from outside the box (if you think you have to be outside) on the "waste less money on this" side of things.
Answer: First to bond the common bonding bus in the media cabinet to the Grounding Electrode System of your homes electrical Service. To do that run a large conductor or bond strap with the same cross sectional area as the conductor from the media cabinet single point bonding busbar to the service equipment. The National Electrical Code only requires #10 American Wire Gauge (AWG) but I would suggest a bare number 4 AWG copper wire or strap of equivalent cross sectional area if you are able to pay the higher cost for the strap. The reason for using strap instead of a round conductor of the same cross sectional area as the strap is that the physical shape of a strap causes it to have a lower impedance to the passage of current during and electric anomaly such as a lightning discharge, contact between the secondary distribution conductors which supply your home with power and higher voltage wires, and current surges or voltage spikes on the utility system's distribution conductors.
At the Service Equipment enclosure connect the bonding conductor to one of the Grounding Electrode Conductors from your Service Equipment. That is often the main panel that contains the first point at which you can disconnect all power from the houses electrical system. That very first Breaker, fused pull out, or Fused Switch is the Service Disconnecting Means. That will bond the common point bonding busbar to the Grounding Electrode System of your homes electrical system.That is done to do the all important job of keeping the conductive pathways, such as Ethernet cables, as near as possible to the same voltage during a voltage spike event. If a large voltage difference develops in between the communications equipment and the Service Equipment Grounding Electrode Conductors it may equalize through your communications equipment by forcing more current through their circuits and components than they can carry without being destroyed.
[All electrical and electronic systems function because they contain magic smoke! If you let the magic smoke escape you will have to buy replacement equipment that still has it's magic smoke or install new components in your damaged equipment to replace the components from which the magic smoke has escaped. No Magic Smoke No function.]
The bonding conductor provides a much lower impedance pathway between the Grounded/(Neutral) Conductor of the Electrical utility's supply. With all of the Grounded Conductors of every circuit powering things in your home connected to that grounded conductor you want to keep the voltage as nearly the same on the grounded Conductors everywhere in your home's wiring system.
That is were this next question comes in. What do you have for electrical power receptacles in your structured media cabinet? Whatever form the mounting of those receptacles takes you want them to be protected from high  voltages in the conductors supplying that circuit. That is done by installing high quality surge protection devices at the media cabinet and bonding the Equipment Grounding Conductor (EGC) of the electrical circuit to the single point bonding busbar. That is done by drilling a hole through which you can install a 10/32 bronze or copper bolt from the inside of the receptacles enclosure to the portion of your media cabinet were your single point bonding busbar is mounted. On the inside of the receptacle enclosure the EGC of the branch circuit supplying the receptacles gets bonded to this machine screw. On the outside of the receptacle enclosure you connect a bonding conductor or strap to the single point bonding busbar. This bonding connection keeps the EGC of the branch circuit as close as possible in voltage to the bonding terminals of the communications equipment. Keeping the voltage difference as low as practicable prevents the flow of destructive amounts of current through the communications equipment.
Install a high quality surge protector on every cable which enters the cabinet. That includes twisted pair cable like the ones used for wired Ethernet and coaxial cable if that is used for cable television. With Coaxial cable it is important to use Surge protectors and not just cable shield bonding blocks.

You must use a coaxial cable protector instead!

The protector provides voltage difference limiting while the shield bond connection only keeps the exterior protective braid near ground potential.
Installing surge protection for every conductive pathway into or out of your media cabinet gives you the highest likelihood of avoiding equipment damage.
Consider installing point of use protection at every device served by the communications wiring and power wiring. You do that by using plug strip protectors that also have protection for the communications media that connects to the same device. If 2 types of communications media connect to one device use a protector which protects both communications paths and the power.
I worked as  a communications wireman for several years doing construction and installation coordination of remote communications equipment shelters. I also was part of 2 different crews who installed communications systems in large building such as the AOL server farm in Dulles, Virginia. My answers are based on my understanding of Soares book on Grounding, Motorola Standard R56 Standards and Guidelines for Communication Sites and National Fire Protection Association Standard 70: 2020 National Electric Code.
Tom Horne
Comment: To answer your question about power supply: I'm actually using four Leviton cabinets...one 42", one 28", and two 14". One of the 14" cabinets holds a UPS which will be fed by a surge-protected receptacle. There are bottom-mounted 15A receptacles in the other three cabinets which are wired to 14-gauge extension cord plugs which connect to the UPS. The 42" cabinet will be for Ethernet and telephone, the other 14" cabinet is where I will put my Internet gateway, and the 28" cabinet will be for audio/video and possibly security once the system is built out.
Answer: The proper way is to run another single green or uninsulated wire back to your entrance panel disconnects ground. This will be where the building ground, ground rods, and electrical grounds are all connected. Condulet grounds do not work well with electronics. Over time the joints will increase in resistance causing a grounding failure. I have been down this path several times in office and factories, the direct wire always works. I also over size it and use copper.
Comment: I'll see about picking up a roll of #10 green wire, then, and run it parallel to the EMT back to the service entrance. I can zip-tie it to the conduit to keep it neat.
Answer: Let me suggest that you run the # 10 green inside the Electrical Metallic Tubing back to the panel and bond it to the EMT at both ends.
That will minimize the impedance of the EMT while providing a redundant Equipment Grounding Conductor for the branch circuit. It needn't be larger than the #14 EGC required for a 15 ampere circuit or the 12 AWG for a 20 ampere branch circuit. Notice the Lay In Lug. Turn that straight out from the inside wall of the enclosure. Let the locknut that is on the EMT connector do it's job of holding the connector in place and bonding the connector to the wall of the enclosure by making it up wrench tight. screw the bonding bushing down as far as it will go and then turn it so that you can use both the lug terminating screw and the bonding screw of the bushing easily. The tighten the bonding screw which will make a good electrical connection. Lay the EGC in the lug and tighten the lug terminal screw.
What I was suggesting as a bonding conductor for the common bonding busbar in the media center is #4 bare or black insulated stranded wire. A bonding conductor can be terminated to a Grounding Electrode Conductor or to the Grounded/Neutral Conductor busbar inside the service equipment enclosure. The bonding conductor may not be green in color because green is reserved for Equipment Grounding Conductors (EGC)s run with individual circuits or added to existing circuits under 250.130(C). Because of the particular job you would be installing the bonding conductor to do it should leave the media cabinets and enter the Service Equipment Enclosure through a Kenny Clamp.

That bonds the Bonding conductor to the enclosure at each end so that the enclosure will not behave as a choke and add reactance to the bonding circuit thus raising the impedance of the Bonding Conductor equalization pathway needlessly. The reason for the suggested size of the intersystem bonding conductor is to keep the grounded conductors of the electrical service and the communications circuits and equipment as close to each other in voltage as possible. It takes a difference of potential, measured in volts, to cause destructive current flow. I used to express it to new people thus. "We don't care if they get up to thousands of volts as long as they're dancing to the same music and holding each other really tightly. NO SUBSTANTIAL DIFFERENCE = NO DESTRUCTIVE CURRENT FLOW.
Tom Horne


Bounded Trace Sobolev Embedding

Question: Just a sanity check here: all the references I've seen concerning Sobolev spaces discuss Sobolev trace embeddings of the form
$$\|u\|_{L^q(\partial\Omega)}\le C\|u\|_{W^{1,p}(\Omega)}$$
where $\Omega$ is bounded and sufficiently smooth, and $q$ is given in term of $p$ and the dimension $n$, with finite $q<\infty$. Is the reason for only considering finite $q$ simply because the Sobolev spaces that are embedded in $L^\infty(\partial\Omega)$ coincide with the Sobolev spaces that are embedded in $L^\infty(\Omega)$?
Answer: If $p\le n$ then we have these trace theorem for some $q<\infty$. If $p>n$ then $W^{1,p}$ is embedded in spaces of (Hoelder) continuous functions, for which traces exist as restrictions to the boundary. Hence these cases are not discussed.

Bounded Trace Sobolev Embedding


Displaying how many times a button has been clicked

Question: I have created a button in HTML and I want to know how I can use Vue.js to  display in the console how many times it has been pressed at.
This is what I have done so far:

  <button id = "Abutton" @click="abutton()">

  </button>

And in Vue.js:
abutton: function (e) {
  const ButtonVal = e.target.value;
  console.log("Number of likes:" + ButtonVal)
},

Comment: You have nothing here holding the value of the button clicks.  If you are using the options API, you need to add a`data` property (call it `clickCount`) and increment that in your function `abutton` and then print `clickCount`.
Answer: A button has no value... But you could use a data attribute like this:

  <button id = "Abutton" @click="abutton()" data-clickcount="0">

  </button>

And in Vue.js:
abutton: function (e) {
  // Get the count
  const ButtonVal = +(e.target.dataset.clickcount);
  // Increment and store it
  e.target.dataset.clickcount = ButtonVal++;
  // log it
  console.log("Number of likes:" + ButtonVal)
},


Prove that polynomial $1+x+x^2$ of $\mathbb{R}[x]$ is irreducible over $\mathbb{R}$. Do not use the Eisenstein criterion.

Question: Prove that $1+x+x^2$ is irreducible over $\mathbb{R}[x]$. Do not use the Eisenstein criterion.
I don't know where to start. Could someone help me?
Comment: If it is reducible, it separates into linear factors. In other words, it has a root in $\mathbb R$. But, the discriminant $1-4=-3<0$, so there are no roots in $\mathbb R$. This is a contradiction.
Comment: Also note that the Eisenstein criterion can never be applied on polynomials over a field.
Comment: You probably know how to factor it in $\mathbb C[x]$ (use quadratic formula).  But irreducible factors there are unique, and neither factor belongs to subring $\mathbb R[x]$, so the polynomial is irreducible in the subring.  Your remark not to "use the Eisenstein criterion" suggest the context for this problem is beyond early undergraduate studies, but you've omitted such context.  Please edit to include such.
Answer: For all $x\in\mathbb R$, $x^2+x+1=\left(x+\frac12\right)^2+\frac34>0$, so $x^2+x+1$ has no roots in $\mathbb R$.
A quadratic polynomial with no roots is irreducible.
Comment: So when a polynomial has no roots, it is considered unreducible?
Comment: When a *quadratic* (or cubic) polynomial has no roots, it is irreducible, [but not generally](https://math.stackexchange.com/questions/222237/irreducible-polynomial-means-no-roots)
Comment: How could I give a counterexample in this case?
Comment: A counterexample to what?
Comment: Not to be irreducible in $\mathbb{R}$?
Comment: $(x-1)(x-2)=x^2-3x+2\;$ is reducible over $\Bbb R$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117859/discussion-between-fernando-sousa-and-j-w-tanner).


How is a Phillips screwdriver size determined?

Question: I have two different sized Phillips screwdrivers that both say they are 00 sized (click here for full-sized image):

The green screwdriver came from an iPhone 3/4 disassembly kit, and on the package it says "Phillips#00".  The tip is about 1.5mm wide.
The screwdriver on the bottom is a Craftsman and it says "P-00" on it.  The tip is about 2mm wide.
One of these screwdrivers cannot be 00 sized.  Which one is 00, and what size is the other one?
Comment: I found this handy set of charts most helpful in determining bit sizes.
https://www.garagetooladvisor.com/hand-tools/screwdriver-sizes/
Comment: What is the home improvement issue here?
Comment: I'll take Craftsman at their word for keeping the proper dimensions, they've been making quality tools too long. The other's run-of-the-mill cheap. There's considerably less metal in the shank and that tiny tip usually isn't properly hardened for durability.
Comment: @FiascoLabs Although that may be true, I can pretty much guarantee you the Craftsman is too big to fit into the iPhone screw hole
Answer: The Phillips screwdriver size is based on the size at the very tip.  Based on diagrams of the tip from the original Phillips patent (shown in one of the links to sizes.com), I'm guessing that the relevant physical size is the cross you see when you point the screwdriver at your nose (as though it were a screw) and look at it end-on, or something directly related to that.  How much the tip widens to become part of the shaft is irrelevant.  You could make one that widens to a meter in diameter, making it nearly impossible for humans to use.
I tried this experiment:  using some digital calipers, insert just the tip between the calipers, and measure the distance from one point on the cross to the opposite point.  This is difficult to do accurately since if you insert a little more than the tip, you get a result that is too large.  I tried several different sets of screwdrivers and bits for them from different manufacturers.
The results:  PH3: 0.141 inches, PH2: 0.086 inches, PH1: 0.071 inches, PH0: 0.055 inches, PH00: 0.048 inches, PH000: 0.039 inches, and PH0000 is so tiny I really couldn't get a consistent reading.  I don't have a PH4 and I'm not sure I've seen one.  As I said, it's difficult to get an accurate reading.  I can quite consistently eyeball the difference between a PH3 and a PH2 or a PH2 and a PH1.  It's difficult to consistently see that a PH00 is larger than a PH000.  I can see that like sizes give similar results, and measuring the same bit over and over also gives similar results, however, the ranges for adjacent sizes overlap a bit for PH000, PH00, and PH0.
A serious attempt to make these measurements would probably require several vices, a powerful magnifying glass or a microscope, and digital calipers with a thinner edge than the set I have.  Either that or I'd need about 6 hands.
I presume a PH0000 screwdriver is intended to drive #0000 screws, a PH000 screwdriver is intended to drive #000 screws, and a PH00 screwdriver is intended to drive #00 screws, as these seem to be the only screws smaller than #0 in the inch-based "numbered screw" system.  There could be a #00000 screw, but it's less than one-hundredth of an inch wide and probably can't take much torque, and a #000000 screw would have a negative diameter, which is obviously impossible.
Somewhere buried in an ANSI standard is the physical dimension that determines the driver size.  I may have found one of them, but it costs $65.
Comment: [Reply Gordon Burditt with gratitude!](https://i.stack.imgur.com/YfvlQ.png)
Comment: In other words PH000 = .039 inches = 1mm
Answer: 00 refers to the size and angle of the tip. It doesn't say how thick the tip becomes before merging into the shaft. So, yes, these could both be 00 sized, if they fit the same screws; the thicker one just (a) will fit larger 00 screws better than the small one would and (b) won't fit into as small an opening.
Comment: A non-precision comparison on my computer screen of the enlarged image does appear to show both tips as the same size. And then watch out for the JIS, PoZiDrive, and other "cross-shaped but not Phillips" screws, which NO Phillips screwdriver will fit correctly. They, do however, do a dandy job of mangling the screw heads.
Comment: Something they have in common with Philips, @Ecnerwal.  All those screws exist to cam out.
Answer: Phillips screwdrivers are not sized based on the physical dimensions of the tool itself. Instead, they are sized based on the screws with which they fit. Each size will work best with a range of screw sizes, which means the actual size of the tip can vary slightly.
<code>Tip Size    Screw Sizes
 0           0  - 1
 1           2  - 4
 2           5  - 9
 3           10 - 16
 4           18 - 29
</code>
This chart can vary slightly, depending on the type of screw being driven
Comment: What screw sizes would Phillips 00, 000, and 0000 tips work on?
Answer: The screwdriver point size will fit different size screws, depending on the type of screw (wood, machine, sheet metal). The point size of the bit is determined by the diameter of the tip. You can measure the tip easily using a vernier caliper. Specifications for the bit size can be found here: http://www.leisto.com/screwdrivrer-bits/phillips-screwdriver-bits/
As a quick reference:
PH00 = 0.8mm - 0.9mm
PH0 = 0.9mm - 1.0mm
PH1 = 1.3mm - 1.4mm
PH2 = 2.2mm - 2.3mm
PH3 = 3.8mm - 4.0mm


Unity: Is it possible to use 2 passes consecutively?

Question: I have a shader with multiple passes inside it, 2 of which are an outline pass and a blur pass. I am trying to create an outline and then blur it. How do I make the blur pass take in the output of the outline pass to blur?
Outline pass:
Pass{
        Name "OUTLINE"
        Cull Off
        ZWrite Off
        ZTest Always
        Blend SrcAlpha OneMinusSrcAlpha
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile_fog

    fixed4 frag(v2f IN) : SV_Target
    {
        fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;

        if (c.a > _Cutoff) {
            float totalAlpha = 1.0;

            [unroll(16)]
            for (int i = 1; i < _OutlineSize + 1; i++) {
                fixed4 pixelUp = tex2D(_MainTex, IN.texcoord + fixed2(0, i * _MainTex_TexelSize.y));
                fixed4 pixelDown = tex2D(_MainTex, IN.texcoord - fixed2(0, i *  _MainTex_TexelSize.y));
                fixed4 pixelRight = tex2D(_MainTex, IN.texcoord + fixed2(i * _MainTex_TexelSize.x, 0));
                fixed4 pixelLeft = tex2D(_MainTex, IN.texcoord - fixed2(i * _MainTex_TexelSize.x, 0));

                totalAlpha = totalAlpha * pixelUp.a * pixelDown.a * pixelRight.a * pixelLeft.a;
            }

            if (totalAlpha == 0) {
                c.rgba = fixed4(0.4, 1, 1, 1);
            }
            else
                c.rgba = fixed4(0.5, 0.5, 0.5, .5);
        }

        c.rgb *= c.a;
        return c;
    }

    ENDCG
    }

Blur pass:
Pass{
        Name "BLUR"
        Cull Off
        ZWrite Off
        ZTest Always
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile_fog

        fixed4 frag(v2f IN) : SV_Target
    {
        fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;

        if (c.a > _Cutoff) {
            fixed4 pixelUp = tex2D(_MainTex, IN.texcoord + fixed2(0, _MainTex_TexelSize.y));
            fixed4 pixelDown = tex2D(_MainTex, IN.texcoord - fixed2(0,  _MainTex_TexelSize.y));
            fixed4 pixelRight = tex2D(_MainTex, IN.texcoord + fixed2(_MainTex_TexelSize.x, 0));
            fixed4 pixelLeft = tex2D(_MainTex, IN.texcoord - fixed2(_MainTex_TexelSize.x, 0));
            fixed4 pixelUp2 = tex2D(_MainTex, IN.texcoord + fixed2(0, 2 * _MainTex_TexelSize.y));
            fixed4 pixelDown2 = tex2D(_MainTex, IN.texcoord - fixed2(0, 2 * _MainTex_TexelSize.y));
            fixed4 pixelRight2 = tex2D(_MainTex, IN.texcoord + fixed2(2 * _MainTex_TexelSize.x, 0));
            fixed4 pixelLeft2 = tex2D(_MainTex, IN.texcoord - fixed2(2 * _MainTex_TexelSize.x, 0));
            fixed4 pixelUp3 = tex2D(_MainTex, IN.texcoord + fixed2(0, 3 * _MainTex_TexelSize.y));
            fixed4 pixelDown3 = tex2D(_MainTex, IN.texcoord - fixed2(0, 3 * _MainTex_TexelSize.y));
            fixed4 pixelRight3 = tex2D(_MainTex, IN.texcoord + fixed2(3 * _MainTex_TexelSize.x, 0));
            fixed4 pixelLeft3 = tex2D(_MainTex, IN.texcoord - fixed2(3 * _MainTex_TexelSize.x, 0));

            c = c * 0.18
                + 0.15 * (pixelUp + pixelDown + pixelRight + pixelLeft)
                + 0.12 * (pixelUp2 + pixelDown2 + pixelRight2 + pixelLeft2);
                + 0.09 * (pixelUp3 + pixelDown3 + pixelRight3 + pixelLeft3);
        }

        c.rgb *= c.a;
        return c;
    }

        ENDCG
    }

I am new to shaders so if there is any advice would be appreciated.
Answer: Using a Grab pass, you can take the screen generated so far and sample from it in another pass.
In your case, put it after the outline pass, and sample from the resulting texture in the blur pass instead of the raw texture.
Pass{
    // ...
    // no change
    // ...
}

GrabPass { "_GrabTexture" }

Pass{
    // Note the changes from calling tex2D with _MainTex to _GrabTexture,
    // matching the string in the GrabPass directive above

    // ...
    // use a vertex shader to get the uvs of the screen grab

    struct v2f {
        float4 grabPos : TEXCOORD0;
        float4 pos : SV_POSITION;
    };

    v2f vert(appdata_base v) {
        v2f o;
        // use UnityObjectToClipPos from UnityCG.cginc to calculate
        // the clip-space of the vertex
        o.pos = UnityObjectToClipPos(v.vertex);
        // use ComputeGrabScreenPos function from UnityCG.cginc
        // to get the correct texture coordinate
        o.grabPos = ComputeGrabScreenPos(o.pos);
        return o;
    }

    // Note the changes from calling tex2D with _MainTex to _GrabTexture,
    // matching the string in the GrabPass directive above
    // as well as IN.grabPos instead of IN.texcoord
    // and tex2Dproj instead of tex2D

    fixed4 frag(v2f IN) : SV_Target {
        fixed4 c = tex2Dproj(_GrabTexture, IN.grabPos) * IN.color;

        if (c.a > _Cutoff) {
            fixed4 pixelUp = tex2Dproj(_GrabTexture, IN.grabPos+ fixed2(0, _MainTex_TexelSize.y));
            fixed4 pixelDown = tex2Dproj(_GrabTexture, IN.grabPos - fixed2(0,  _MainTex_TexelSize.y));
            fixed4 pixelRight = tex2Dproj(_GrabTexture, IN.texcoord + fixed2(_MainTex_TexelSize.x, 0));
            fixed4 pixelLeft = tex2Dproj(_GrabTexture, IN.texcoord - fixed2(_MainTex_TexelSize.x, 0));
            fixed4 pixelUp2 = tex2Dproj(_GrabTexture, IN.texcoord + fixed2(0, 2 * _MainTex_TexelSize.y));
            fixed4 pixelDown2 = tex2Dproj(_GrabTexture, IN.texcoord - fixed2(0, 2 * _MainTex_TexelSize.y));
            fixed4 pixelRight2 = tex2Dproj(_GrabTexture, IN.texcoord + fixed2(2 * _MainTex_TexelSize.x, 0));
            fixed4 pixelLeft2 = tex2Dproj(_GrabTexture, IN.texcoord - fixed2(2 * _MainTex_TexelSize.x, 0));
            fixed4 pixelUp3 = tex2Dproj(_GrabTexture, IN.texcoord + fixed2(0, 3 * _MainTex_TexelSize.y));
            fixed4 pixelDown3 = tex2Dproj(_GrabTexture, IN.texcoord - fixed2(0, 3 * _MainTex_TexelSize.y));
            fixed4 pixelRight3 = tex2Dproj(_GrabTexture, IN.texcoord + fixed2(3 * _MainTex_TexelSize.x, 0));
            fixed4 pixelLeft3 = tex2Dproj(_GrabTexture, IN.texcoord - fixed2(3 * _MainTex_TexelSize.x, 0));

            c = c * 0.18
                + 0.15 * (pixelUp + pixelDown + pixelRight + pixelLeft)
                + 0.12 * (pixelUp2 + pixelDown2 + pixelRight2 + pixelLeft2);
                + 0.09 * (pixelUp3 + pixelDown3 + pixelRight3 + pixelLeft3);
        }

        c.rgb *= c.a;
        return c;
    }

        ENDCG
    }


How to build mainline kernel and make it show up on GRUB?

Question: After successfully compiling and building my mainline Kernel (220.127.116.11) under my Ubuntu 10.04 with these headers I was wondering: how to make this kernel on startup, so I can choose which one to boot?
I have GRUB2 (grup-install -v says: 'GNU GRUB 0.97') installed.
I tried this:
sudo make install

And got:
luky@ubuntu1004:/usr/src/linux-18.104.22.168$ sudo make install
sh /usr/src/linux-220.127.116.11/arch/x86/boot/install.sh 188.8.131.52 arch/x86/boot/bzImage \
  System.map "/boot"

Here's my /boot folder:
luky@ubuntu1004:/boot$ ls
abi-2.6.32-24-generic         System.map-2.6.32-24-generic
config-2.6.32-24-generic      System.map-184.108.40.206
config-184.108.40.206              vmcoreinfo-2.6.32-24-generic
grub                          vmlinuz-2.6.32-24-generic
initrd.img-2.6.32-24-generic  vmlinuz-220.127.116.11
memtest86+.bin

I would NOT like to have to manually change GRUB's config files.
Comment: Upstream kernels do not have a "-" in their version number, that is for package versions. It would be more clear if you said "126.96.36.199".
Answer: Well, after all what solved my problem was: install the grub-pc package. This will replace the default one shipped with Ubuntu 10.04.
I'm on a PC, so I guess that's fine.
Comment: Maybe grub-pc ?
Answer: I am assuming that you have grub2 installed because you are running 10.04, rather than grub legacy. You will need to update grub following the instructions here: https://help.ubuntu.com/community/Grub2
It should be a simple: sudo update-grub
This should check for new kernels and make grub entries from which you should be able to boot.
Comment: Yeah, I don't know if that was the solution, since I also edited my /etc/default/grub file... but now it's showing up.

Next problem: Kernel panic: unable to mount root fs

LOL!
Comment: Thats because of your /dev/sda4 (or something) is missing in initramfs /dev folder. Try sudo update-initramfs -u -k all
Answer: The kernels from that location are meant to be installed, not built yourself. They already have everything needed in their packaging to appear in grub, etc.
To build a mainline kernel and still get a proper .deb package, see the instructions here: https://wiki.ubuntu.com/KernelTeam/GitKernelBuild
That will guide you through the build prerequisites, how to transfer the build-time configs, and generate the package. If you don't need to change configurations, see http://kernel.ubuntu.com/~kernel-ppa/mainline/daily/ for pre-built mainline kernels.
Comment: I forgot to mention that I downloaded the sources from kernel.org: http://www.kernel.org/pub/linux/kernel/v2.6/linux-126.96.36.199.tar.bz2
Comment: Can you edit your question to reflect that? It changes the answer significantly. :)
Comment: yeah, done. sorry for the confusion! =)
Answer: To build and install kernel in ubuntu or any debian based system for that matter its best to use makepkg istead of the usual make, make modules_install ....
makepkg --initrd linux-image linux-headers warning: this might throw a permission error some times
This creates a couple of .deb files in the parent directory which can be installed like any other .deb file.Do not worry about grub,it will configure itself;if using burg you must run "sudo update-burg".This will also ensure that the initrd file is properly generated
Comment: this command doesnt work.


Why did they hammer nails in half way and bent them over to secure supports?

Question: In my 1950s house they hammered nails in half way and bent them over to secure the supports to the beam.  Why was this technique used?
Comment: Simple answer: Nails were too long and they didn't have any smaller ones available. Bend the long ones over. Apparently it has held all these years.
Answer: The nail heads aren't big enough for the holes. At that time carpenters didn't enjoy the vast array of fasteners and installation tools that we do today, so they may have used what was available at the moment. It did the job, right?
~ or ~
The carpenter had intended to replace them with lag screws and forgot.
~ or ~
There's something sensitive to puncture behind the surface of that lumber. It looks like a standard beam, but it's hard to say from my house.
Comment: Came to say the holes were too big for the nail holes.  Seems like the best provable reason.
Comment: Agree that the holes are intended for coach bolts or lag bolts of some kind, certainly too big for any nail. If they bother you, remove them (one at a time), drill a suitably sized pilot hole and use a lag bolt (and washer) of a suitable length for the beam depth.
Answer: Because it is easy to remove the nails if required to move the post.
The nails mostly hold the post in position until the overall weight of the building bears down a lot of pressure on the post. At that point it is mostly friction between the upper post plate and the beam that holds the post in position.
Comment: Banging the nails all the way in will simply put splits in the beam without adding to the holding power.
Comment: I'm not convinced that anyone would intentionally remove fasteners in a case like this and not replace them with something better. Without them it's certainly possible that a light load (which can happen for various reasons) coupled with an accidental collision could shift the post.
Answer: in my judgement, bending the nails halfway secures better the support then hammering the nails entirely. why is this? because the surface of half of the nail's length is larger than the surface of the nail's head.  it's all about the contact surface between the nail and the supports. suppose someone tries to pull the pipe. what would keep the bean in place? the nails; the larger the contact surface of the nails , the better the pipe is kept in place
for the same pulling Force being distributed over a larger nail Surface, this results in a smaller Pressure, thus reducing the chances that the nails break; in fact, there is no need for someone to pull the pipe; its the pipe's own weight that acts as a force towards the nails.
there is also a second factor that keeps the pipe fixed, apart from the nail's contact surface with the supports: how deep the nails went into the wood. Perhaps the ratio 1:1 (half of the nail into the wood, half outside) seemed to be a reasonable compromise. ideally, a large part of the nail should go into the wood, and a large part should remain outside as well. so a compromise has to be made. what would be the perfect ratio is a complicated question, the answer depending on the friction between wood and nail, and the pulling forces that are expected to act on the pipe, and ,further, on the nails.


How to detect that an add-on has been disabled by the user in IE9?

Question: IE9 users can disable an add-on, such as a browser helper object, by clicking on the cog button and selecting "Manage Add-Ons". I need to detect if a given add-on has been disabled in such way, using JavaScript.
I can't seem to find a way for my error handler (<object ... onerror="myhandler(event)") to detect that the BHO has been disabled. errorEvent.type is simply "error". Is there any way?
I need to detect this scenario because just having the webpage try to install the BHO again yields no result. IE9 simply ignores the request. The user isn't shown any warnings either, so neither him nor the webpage know what's going on.

Some background:
Internet Explorer 9 identifies browser helper objects that took a long time to start and reports those to the user, with a big button to disable them. This means that a lot of users will be disabling BHOs they actually need, if only by the sheer impulse to click on big buttons.
This also means my company is in some trouble, as we make a BHO which is used by a significant amount of clients and is sometimes (but not always) identified as being too slow. We are working hard on making it start up faster. But in the meantime we need some way to detect that a user has disabled our BHO and ask them to enable it again.
Answer: There is no script-accessible mechanism that would allow you to reliably distinguish between an add-on not being installed vs. being installed and disabled.
There's also, generally, no way for a page to know whether a BHO is installed even if it's enabled unless the BHO explicitly exposes a DOM-accessible property.
You can detect whether ActiveX add-ons are disabled by ActiveX Filtering using the window.external.msActiveXFilteringEnabled() API.
Comment: I'm not sure what you mean when you say "requests a BHO." Generally speaking, pages cannot "request" a BHO-- they can request an ActiveX control (e.g. using the OBJECT tag above), but BHOs aren't *typically* accessible to pages. Pages can detect when an ActiveX control is missing/disabled by putting fallback content into the OBJECT tag.
Comment: Thanks Eric. If I may suggest a feature, I think users should be shown a warning when a page requests a BHO that was disabled for performance reasons. Otherwise they're left in the dark as to why the webpage isn't working properly.
Answer: Eric,
What do you think of this sort of trick?

The add-on injects a script into every page the user visits.
Once a second or so, the script sends a "heartbeat request" message to the add-on. The add-on should send "acknowledged" response.
If the add-on doesn't respond, the script assumes that the add-on has been disabled or uninstalled, and it notifies the server.

(The idea is borrowed from http://keep12on.com/2011/05/26/detecting-extension-uninstallations-on-chrome/)
Thanks
Comment: From a reliability and performance point-of-view, doing something like this would be pretty horrible.
Comment: I beg to differ. Injecting a few hundred bytes of script into every page, then doing the heartbeat request/response every second should hardly be noticeable.


Repository Methods vs. Extending IQueryable

Question: I have repositories (e.g. ContactRepository, UserRepository and so forth) which encapsulate data access to the domain model.
When I was looking at searching for data, e.g.

finding a contact whose first name
starts with XYZ
a contact whose birthday is after
1960
(etc),

I started implementing repository methods such as FirstNameStartsWith(string prefix) and YoungerThanBirthYear(int year), basically following the many examples out there.
Then I hit a problem - what if I have to combine multiple searches? Each of my repository search methods, such as above, only return a finite set of actual domain objects. In search for a better way, I started writing extension methods on IQueryable<T>, e.g. this:
public static IQueryable<Contact> FirstNameStartsWith(
               this IQueryable<Contact> contacts, String prefix)
{
    return contacts.Where(
        contact => contact.FirstName.StartsWith(prefix));
}

Now I can do things such as
ContactRepository.GetAll().FirstNameStartsWith("tex").YoungerThanBirthYear(1960);

However, I found myself writing extension methods (and inventing crazy classes such as ContactsQueryableExtensions all over, and I lose the "nice grouping" by having everything in the appropriate repository.
Is this really the way to do it, or is there a better way to achieve the same goal?
Answer: I have been thinking about this a lot lately, after starting at my current job. I am used to Repositories, they go the full IQueryable path using just bare bones repositories as you suggest.
I feel the repo pattern is sound and does a semi-effective job at describing how you want to work with the data in the application domain. However the issue you are describing definitely occurs. It gets messy, fast, beyond a simple application.
Are there, perhaps, ways to rethink why you are asking for the data in so many ways? If not, I really feel that a hybrid approach is the best way to go. Create repo methods for the stuff you reuse. Stuff that actually it makes sense for. DRY and all that. But those one-offs? Why not take advantage of IQueryable and the sexy things you can do with it?  It is silly, as you said, to create a method for that, but it doesn't mean you don't need the data. DRY doesn't really apply there does it?
It would take discipline to do this well, but I really think it's an appropriate path.
Answer: @Alex - i know this is an old question, but what I would be doing would be letting the Repository do really simple stuff only. This means, get all records for a table or view.
Then, in the SERVICES layer (you are using an n-tiered solution, right? :) ) i would be handling all the 'special' query stuff there.
Ok, example time.
Repository Layer
ContactRepository.cs

public IQueryable<Contact> GetContacts()
{
    return (from q in SqlContext.Contacts
            select q).AsQueryable();
}

Nice and simple. SqlContext is the instance of your EF Context .. which has an Entity on it called Contacts .. which is basically your sql Contacts class.
This means, that method basically is doing: SELECT * FROM CONTACTS ... but it's not hitting the database with that query .. it's only a query right now.
Ok .. next layer.. KICK ... up we go (Inception anyone?)
Services Layer
ContactService.cs

public  ICollection<Contact> FindContacts(string name)
{
    return FindContacts(name, null)
}

public ICollection<Contact> FindContacts(string name, int? year)
{
   IQueryable<Contact> query = _contactRepository.GetContacts();

   if (!string.IsNullOrEmpty(name))
   {
       query = from q in query
               where q.FirstName.StartsWith(name)
               select q;
   }

   if (int.HasValue)
   {
       query = from q in query
               where q.Birthday.Year <= year.Value
               select q);
    }

    return (from q in query
            select q).ToList();
}

Done.
So lets recap. First, we start our with a simple 'Get everything from contacts' query. Now, if we have a name provided, lets add a filter to filter all contacts by name. Next, if we have a year provided, then we filter the birthday by Year. Etc. Finally, we then hit the DB (with this modified query) and see what results we get back.
NOTES:-

I've omitted any Dependency Injection for simplicity. It's more than highly recommended.
This is all pseduo-code. Untested (against a compiler) but you get the idea ....

Takeaway points

The Services layer handles all the smarts. That is where you decide what data you require.
The Repository is a simple SELECT * FROM TABLE or a simple INSERT/UPDATE into TABLE.

Good luck :)
Comment: I think it is worth mentioning that this really only works efficiently, and please correct me if I am wrong, if you are using a DAL that supports deferred execution such as Linq To Sql as per your example. Otherwise you will retrieve a lot of data from your data store that may not get used.  Now if you know the user is going to be using the same data set in multiple different ways this ultimately may be ok, but if they are just running this query once then retrieving entirely unrelated data this design would lead to mentionable overhead.
Comment: We've all done this hack. For each additional filter we add an 'optional' parameter. I think the authors original example is far cleaner and easier to use (and reuse).
Comment: @joshlrogers : dude - waaaay incorrect! DO you know what an IQueryable is/does? it doesn't hit the DB. It's a _query_. So i'm not really doing a SELECT * FROM XXX. I *extend* that query by adding extra where clauses .. when required. So the final sql is actually a SELECT * FROM XXX WHERE blah (if the user has provided the *optional* name and/or *optional* year arguments*. So unless I misunderstood you .. careful what you say :(
Comment: @Jerod Houghtelling : hack? How is this a hack? With the author's original example, they will have a very complex repository (as he/she suggested).. and then this is sorta-replicated in the services layer. Not very DRY if you ask me. Want a more indepth example of my answer? Check this good blog post out: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/
Comment: Gotcha now :) and yep - agreed. But i didn't worry about that 'cause this was an EF question :)
Comment: @Pure.Krome That is exactly what I am saying.  Your code example used execution deferred code.  Linq isn't executed until it is actually called so at that point everything creates one coherent query.  I was only bringing this up because if they try to home brew something they should know that it isn't good practice to get an entire table of data then perform all filtering, sorting, etc, afterwards except in rare circumstances.  I was just trying to make sure people understood what was happening.
Comment: @Joshlrogers : i'm so confused :( Are you saying that my code is (1) using deferred execution and (2) returns all rows to code (massive overhead) then client code does filtering/sorting or (3) returns only the exact rows required because filtering/sorting is part of the sql code executed?  (My answers are (1) and (3) ... definately not (2).
Comment: @Pure.Krome : Sorry I didn't mean to be confusing.  Your code is deferred execution because you are utilizing linq. No you aren't experiencing 2 due to the nature of deferred execution the sql isn't generated until the linq query is actually executed with a ToList().  I wasn't trying to say your code was wrong at all, quite the contrary.  What I was trying to say to anyone reading your post that doesn't happen to be using an ORM or DAL that supports deferred execution that they would be doing # 2 if they followed your instructions.
Answer: I realize this is old, but I've been dealing with this same issue lately, and I came to the same conclusion as Chad: with a little discipline, a hybrid of extension methods and repository methods seems to work best.
Some general rules I've been following in my (Entity Framework) application:
Ordering queries
If the method is used only for ordering, I prefer to write extension methods that operate on IQueryable<T> or IOrderedQueryable<T> (to leverage the underlying provider.) e.g.
public static IOrderedQueryable<TermRegistration> ThenByStudentName(
    this IOrderedQueryable<TermRegistration> query)
{
    return query
        .ThenBy(reg => reg.Student.FamilyName)
        .ThenBy(reg => reg.Student.GivenName);
}

Now I can use ThenByStudentName() as needed within my repository class.
Queries returning single instances
If the method involves querying by primitive parameters, it usually requires an ObjectContext and can't be easily made static. These methods I leave on my repository, e.g.
public Student GetById(int id)
{
    // Calls context.ObjectSet<T>().SingleOrDefault(predicate)
    // on my generic EntityRepository<T> class
    return SingleOrDefault(student => student.Active && student.Id == id);
}

However, if the method instead involves querying an EntityObject using its navigation properties, it can usually be made static quite easily, and implemented as an extension method. e.g.
public static TermRegistration GetLatestRegistration(this Student student)
{
    return student.TermRegistrations.AsQueryable()
        .OrderByTerm()
        .FirstOrDefault();
}

Now I can conveniently write someStudent.GetLatestRegistration() without needing a repository instance in the current scope.
Queries returning collections
If the method returns some IEnumerable, ICollection or IList, then I like to make it static if possible, and leave it on the repository even if it uses navigation properties. e.g.
public static IList<TermRegistration> GetByTerm(Term term, bool ordered)
{
    var termReg = term.TermRegistrations;
    return (ordered)
        ? termReg.AsQueryable().OrderByStudentName().ToList()
        : termReg.ToList();
}

This is because my GetAll() methods already live on the repository, and it helps to avoid a cluttered mess of extension methods.
Another reason for not implementing these "collection getters" as extension methods is that they would require more verbose naming to be meaningful, since the return type isn't implied. For example, the last example would become GetTermRegistrationsByTerm(this Term term).
I hope this helps!
Comment: Meaningful naming, aka *Ubiquitous Language* is a key goal and benefit for a services layer. **GetRegistrationsByTerm()** is a good example.
Answer: Six years later, I am certain @Alex has solved his problem, but after reading the accepted answer I wanted to add my two cents.
The general purpose of extending IQueryable collections in a repository to provide flexibility and empower its consumers to customize data retrieval. What Alex has already done is good work.
The primary role of a service layer is to adhere to the separation of concerns principle and address command logic associated with business function.
In real world applications, query logic often needs no extension beyond the retrieval mechanics provided by the repository itself (ex. value alterations, type conversions).
Consider the two following scenarios:
IQueryable<Vehicle> Vehicles { get; }

// raw data
public static IQueryable<Vehicle> OwnedBy(this IQueryable<Vehicle> query, int ownerId)
{
    return query.Where(v => v.OwnerId == ownerId);
}

// business purpose
public static IQueryable<Vehicle> UsedThisYear(this IQueryable<Vehicle> query)
{
    return query.Where(v => v.LastUsed.Year == DateTime.Now.Year);
}

Both methods are simple query extensions, but however subtle they have different roles. The first is a simple filter, while the second implies business need (ex. maintenance or billing). In a simple application one might implement them both in a repository. In a more idealistic system UsedThisYear is best suited for the service layer (and may even be implemented as a normal instance method) where it may also better facilitate CQRS strategy of separating commands and queries.
Key considerations are (a) the primary purpose of your repository and (b) how much do you like to adhere to CQRS and DDD philosophies.


Can we use the Yammer search API v2? Is it official?

Question: When searching in Yammer it uses an <code>/api/v2/search</code> endpoint like this:
https://www.yammer.com/api/v2/search/models?search=test&start=0&size=20&model_types=threads&_network=xxxxxxx&relevance=DEFAULT
Compared to the v1 search endpoint this returns more data. We need this data. And we successfully tested using this v2 endpoint.
Now the question: Is this v2 search endpoint safe to use? Is it "official"? Maybe somebody from Yammer reads along - on their Help page it says:

We encourage you to post all programming questions to StackOverflow
  with a #yammer hashtag

So here we are. Any help is appreciated.
Comment: Just found another question about the API v2 release date - from 2016. https://stackoverflow.com/questions/35459558/possible-yammer-rest-api-v2-release-date This and a possible future of the API in the Microsoft Graph could point to the v2 API being pretty stable now....
Answer: The Yammer v2 search API endpoint is not yet officially supported for third-party use. This is because we anticipate the need to make changes to it as we build it out. There are no plans to lock developers out of experimenting with the v2 search API. However, when developing any important functionality against this API, automated testing should be used to detect any unannounced breaking changes that we make while we continue to build it out.
Comment: Thank you so much for the feedback. Who must I bribe to get any documentation about the different v2 search properties and sub-endpoints?


I have set content security policy inside the meta tag in html but still the policy is not followed

Question: I have set up the Content Security Policy inside the meta tag in html
<code>    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="Content-Security-Policy"  content="frame-src http://localhost:35637/" /> >
        <title>User Input</title>

</code>
Still when I run the code and see the developers tool I am getting

Refused to frame 'http://localhost:35637/' because it violates the
following Content Security Policy directive: "frame-src 'self'".

Why is it not able to detect the "frame-src http://localhost:35637/" and showing "frame-src 'self' "
Comment: You will need to define CSP as part of the HTTP headers, not HTML header...
Comment: @f_puras
I have my html code which contains a form and the action method of form has post method which calls 'http://localhost:35637/'. How to set up http headers in front end
Comment: It is not part of the front-end, but usually belongs to the webserver configuration, i.e. Apache, IIS or nginx, depending on what you use. There is no point in placing the directives in the HTML itself, because in case of an XSS attack, they could be manipulated as well.
Answer: The most likely explanation is that the there is a Content-Security-Policy set with the directive "frame-src 'self'" on your page. This is most likely set as a response header. You are adding another policy, and that can only make the total enforced policy stricter. You will need to identify how the existing policy is set and modify or remove it.


Set radius for each corner with rounded rect?

Question: Here's the source code which makes form corner rounded,
but how could I set own radius with each corner?
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
        (
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
         );

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, 405, 546, 20, 20));

I want only top-left corner rounded.
Answer: You can create it yourself.
Use a GraphicsPath, and then convert it to a Region using the constructor overload which takes a GraphicsPath
using (GraphicsPath gfxPath = new GraphicsPath())
{
    int d = CornerRadius * 2;
    gfxPath.AddArc(Bounds.Left, Bounds.Top, d, d, 180, 90);
    gfxPath.AddLine(Bounds.Right, Bounds.Top, Bounds.Right, Bounds.Bottom);
    gfxPath.AddLine(Bounds.Right, Bounds.Bottom, Bounds.Left, Bounds.Bottom);
    gfxPath.CloseAllFigures();
    region = new Region(gfxPath);
}


Matplotlib center plot_surface on axis area

Question: I am trying to create a 3d surface plot but the result is not aligned to the origin:

You can easily see on the Z-projection that it's a little off on the X and Y axes. My data is a matrix where the first two columns are my X's and Y's and the 3rd column is my Z. This is how I compute the values:
bins = np.linspace(0, 1, 1000)
indices = np.digitize(data[:, :2], bins, right=True)
X, Y = np.meshgrid(bins, bins, indexing='ij')
Q = np.zeros_like(X)
C = np.zeros_like(X)
d = data[:, 2]
for idx in range(0, len(indices)):
    (i,j) = indices[idx]
    Q[i, j] += d[idx]
    C[i, j] += 1
C[C == 0] = 1 # avoid division by zero errors
Q /= C
return (X, Y, Q, C)

Plotting code:
fig = plt.figure(figsize=(30, 15))
ax = fig.add_subplot(121, projection='3d')
ax.set_xlim3d(-0.5, 1)
ax.set_ylim3d(0, 1.5)
ax.set_zlim3d(-1.5, 1)
Q = ndi.gaussian_filter(Q, sigma=10)
ax.plot_surface(X, Y, Q, cmap=cm.coolwarm, lw=lw, rstride=rs, cstride=cs, alpha=a, antialiased=True)
ax.contourf(X, Y, Q, zdir='z', offset=-1.5, cmap=cm.coolwarm)
ax.contourf(X, Y, Q, zdir='x', offset=-0.5, cmap=cm.coolwarm)
ax.contourf(X, Y, Q, zdir='y', offset=+1.5, cmap=cm.coolwarm)

My question is, am I missing any calculation to ensure the surface is aligned to the origin? thanks.
Answer: The surface is aligned to the origin. But the origin is "hanging in the air". Or in other words, the bottom pane is slightly (~0.05 units) below the contourf plot, which makes it appear as if the plot was misaligned.
You may want to look at this question: Removing axes margins in 3D plot use one of the two answers to have the panes aligned properly.


Updating/Zooming Into Current Location on iPhone

Question: Ok so I am trying to get the same zoom in/location update feature that the iPhone Maps application has when you tap on the current location button. I am using code I found from here and here(code from the post by Brad Smith) to do most of the work. So all I really need to do is center the map around the updated current location and zoom in a little further every time there is an update.
Right now I am having some difficulty testing for whether centerCoord is null or not. As you can see from the results(listed below) it crashes for some reason which I can't figure out. Here is the relevant code:
- (void) showCurrentLocationButtonTapped {
    NSLog(@"Showing current location.");

    locController = [[LocationController alloc] init];

    [mapView setShowsUserLocation:YES];

    zoomTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(zoomToCurrentLocation) userInfo:nil repeats:YES];

}

- (void) zoomToCurrentLocation {
    CLLocationCoordinate2D centerCoord = self.locController.currentLocation.coordinate;
    NSLog(@"Checking if loc controller is null");
    if (!self.locController) {
        NSLog(@"centerCoord is null!");
    }
    NSLog(@"centerCoord: %@",centerCoord);
    [mapView setCenterCoordinate:centerCoord zoomLevel:7 animated:YES];
}

Here is the console output:
2010-11-10 14:56:11.002 App Name[5278:207] Showing current location.
2010-11-10 14:56:11.504 App Name[5278:207] Checking if loc controller is null
2010-11-10 14:56:11.505 App Name[5278:207] centerCoord: (null)
2010-11-10 14:56:12.004 App Name[5278:207] Checking if loc controller is null
2010-11-10 14:56:12.004 App Name[5278:207] centerCoord: (null)
2010-11-10 14:56:12.504 App Name[5278:207] Checking if loc controller is null

I am aware I am not testing for the null-ness of centerCoord, but if I do this:
if (!centerCoord) {

I get an error on that line saying:
MapViewController.m:55: error: wrong type argument to unary exclamation mark

Answer: Here's what you need to do:
First, check if location services is enabled:
if ([CLLocationManager locationServicesEnabled])
    [self findUserLocation];

Then in your findUserLocation method, instantiate your CLLocationManager and start receiving updates:
- (void)findUserLocation
{
    CLLocationManager *locationManager_ = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracy{ChooseYourOptionHere};
    [locationManager startUpdatingLocation];
}

And finally, implement this delegate method, which will get called every time an update is received. Check the current location's accuracy against your desired accuracy (set above), center the map if you are happy with it AND don't forget to stop the location manager from receiving updates:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if ([newLocation horizontalAccuracy] < [manager desiredAccuracy])
    {
        // Accuracy is good enough, zoom to current location
        [manager stopUpdatingLocation];
    }
// else keep trying...
}

Comment: And I just realised this is like 6 months old, not sure why it was bumped to the top again?
Comment: I have no idea, heh. Thanks for the answer though, I will go back to that portion of my project and do what you suggested and if it helps me do what I am looking for I'll be sure to accept your answer. :) You got +1 from me for answering this in anycase.
Answer: Maybe the Location Controller is taking time to update your location.
Try to set your timer to 30 seconds and see what happens.
Comment: I did 5 seconds instead of 30, as 30 is too long. The little blue dot shows up on a zoomed-out map. And after 5 seconds, it crashes. Here is the console output: 2010-11-10 17:24:09.507 App Name[5731:207] Showing current location.
Wed Nov 10 17:24:10 ...: CGImageCreateWithImageProvider: invalid image size: 0 x 0.
2010-11-10 17:24:14.509 App Name[5731:207] Checking if loc controller is null
Comment: MapViewController.m:55: error: wrong type argument to unary exclamation mark means that you can't use the exclamation mark for this. Try CLLocationCoordinate2DIsValid(centerCoord).


Difficulty with a meromorphic extension.

Question: I'm trying to understand the prime number theorem, but never having followed a course in complex analysis, I have some difficulties. (the article is this: http://www.maths.dur.ac.uk/~dma0hg/prime_number_theorem_zagier.pdf)
I understand intuitively what an holomorphic extension is, but some implications are obscures for me.
In particular when it's proved that $-\frac{\zeta'(s)}{\zeta(s)} = \sum_{p} \frac{log(p)}{(p^s-1)} =\phi(s) + \sum_p \frac{log(p)}{p^s(p^s-1)} $
it's directly stated that the final sum converges for $\Re(s)>1/2$ (Why?)
moreover this, and the fact that $\zeta(s) - \frac{1}{s-1}$ is holomorpic for $\Re(s)>0$ implies that $\phi(s)$ extends meromorphically to $\Re(s)>1/2$.
Why this implication?
Thank you for the help!
Answer: The quantity $\log n/n^s(n^s - 1)$ is comparable to $\log n/n^{2s}.$
Now the series $\zeta(s) = \sum_n 1/n^s$ converges (absolutely, and uniformly on compact subsets) when $\Re s > 1$, so the same is true of its derivative,
which is $-\sum_n \log n/n^s$.  Thus $\sum_n \log n /n^{2 s}$ converges if $\Re s > 1/2,$ and so the same is true for $\sum_{n = 2}^{\infty} \log n/ n^s (n^s -1)$,
and hence the corresponding some over primes also converges (since it is bounded above by the sum over all $n \geq 2$).  In fact, the convergence is absolute (again, by comparison with the $\zeta$ function), and uniform on compact subsets, and hence the limit is a holomorphic function of $s$ (provided $\Re s > 1/2$).
Since $\zeta(s) - 1/(s-1)$ is holomorphic when $\Re s > 0$, we see
that $\zeta(s)$ is meromorphic in this region (being the sum of a holomorphic function and the meromorphic function $1/(s-1)$).  Thus $\zeta'(s)$ is also
meromorphic in this region, and hence so is the ratio $\zeta'(s)/\zeta(s)$.
Finally, $\phi(s)$ is the difference of a meromorphic function and a holomorphic function on the region $\Re s > 1/2$, and so is meromorphic in this region.
Comment: Thank you very much! You have been very clear :-)
Comment: @Benzio: Dear Benzio, You're welcome.  Regards,


Which usb driver is called in order to transfer data?

Question: I would like to change the behaviour of one of my USB flash drive by editing its driver, but i can't find which driver is called.
I searched and i found that the drivers/usb/storage/transport.c is responsible for some exchanges beetween the host and the device (configuration), but i want to find the driver that sends URB whith data.
Is there any way to find that?
Thank you
Luis
Comment: What is a USB key? Try using `ftrace` to see what gets called.
Comment: Sorry, it's the litteral translation from my language.I meant USB flash drive
Answer: I searched and i found that it's the function usb_stor_bulk_transfer_sglist in transport.c that perform a data transfer for a USB flash drive
In fact, it uses URB with sglist of address


Ruby Global Interpreter Lock (GIL) - rb_thread_call_without_gvl

Question: I am struggling to pass arguments to rb_thread_call_without_gvl. This is the simple code I am using.
#include <stdio.h>
#include <ruby.h>
#include <ruby/thread.h>

VALUE summa(VALUE self, VALUE x)
{
    double result;
    result = NUM2DBL(x) + NUM2DBL(x);

    printf("The sum in C is %f\n", result);
    return DBL2NUM(result);
}

VALUE no_gvl(VALUE self)
{
    double arg = 3.0;
    double *ptr = &arg;
    rb_thread_call_without_gvl(summa, ptr, NULL, NULL);
    return Qnil;
}

void Init_csum()
{
    VALUE myModule = rb_define_module("MyModule");
    VALUE myClass = rb_define_class_under(myModule, "MyClass", rb_cObject);
    rb_define_method(myClass, "summa", summa, 1);
    rb_define_method(myClass, "no_gvl", no_gvl, 0);
}

I then try to call the extension from Ruby with the script client.rb:
require './csum'
obj = MyModule::MyClass.new # MyClass is defined in C
puts "The sum in R is " + obj.summa(7.0).to_s
puts obj.no_gvl

And finally my extconf.rb:
require 'mkmf'
extension_name = 'csum'
create_makefile(extension_name)

I am a beginner in C, but I need to create an extension that can use a library without the limitation of one single thread. See my other question.
When I make the extension I receive a warning saying
warning: incompatible pointer types passing 'VALUE (VALUE, VALUE)' to parameter of type 'void *(*)(void *)'

Although I understand what it says, I cannot see how to fix it. Should I just ignore it?
Also when I run client.rb I have a segmentation fault when it calls obj.no_gvl.
I am on Mac OSX 10.10.5 and I am using Ruby 2.0.0-p247 through rbenv.
Answer: If you haven't seen it already, the source for rb_thread_call_without_gvl includes some documentation. (I've linked to the version that you're using, but that's a pretty old Ruby, you should look at updating if possible. This API is the same in current versions at least up to 2.3.1.)
The function prototype looks like:
void *rb_thread_call_without_gvl(void *(*func)(void *), void *data1,
             rb_unblock_function_t *ubf, void *data2);

The function that is being called should accept a single void * argument and return void *, i.e. it is a plain C function, not a C function implementing a Ruby method as you have in your example. In fact it can't implement a Ruby method as doing so would mean accessing structures protected by the GVL.
To use it you need to move the code you want to execute without the lock into a function with the correct interface, and that doesn't use any of the Ruby API. Here is an example (based on your own) that creates a Ruby method that doubles the argument passed to it, and does the work without the GVL:
#include <stdio.h>
#include <ruby.h>
#include <ruby/thread.h>

// The function that does the work, accepts void* and returns void*
void* doubleArg(void* x) {
    // Unpack the arg and cast back to double.
    double val = *(double*)x;
    double result = val + val;
    printf("The sum in C is %f\n", result);

    // If you wanted you could wrap up some data here to return to
    // Ruby land.
    return NULL;
}

// The function implementing the Ruby method
VALUE double_no_gvl(VALUE self, VALUE arg) {
    // First wrap up the input as a pointer.
    // You'll probably want to do some checking on the type of the
    // argument here too.
    double argAsDouble = NUM2DBL(arg);
    double *ptr = &argAsDouble;

    // Now call the function without the GVL.
    // It might be worth looking into providing
    // an ubf function here too.
    rb_thread_call_without_gvl(doubleArg, ptr, NULL, NULL);
    return Qnil;
}

void Init_csum() {
    VALUE myModule = rb_define_module("MyModule");
    VALUE myClass = rb_define_class_under(myModule, "MyClass", rb_cObject);
    rb_define_method(myClass, "double_no_gvl", double_no_gvl, 1);
}

You can call it with a script like:
require './csum'
obj = MyModule::MyClass.new
obj.double_no_gvl(3.9)

Comment: @Rojj yes, but be careful about allocation. You shouldn't return a pointer to a local variable to a calling function, as in the calling function the pointer will point to somewhere off the stack (and will likely be overwritten the next time you call a function). It _might_ work if you unpack it immediatley, but would be risky. Instead you'll need to `malloc` some storage (and `free` it in the calling function), or possibly pass a pointer to a struct that contains the arguments you need and allows you to set the result in it (rather than returning the result).
Comment: Very clear thanks. Re: Ruby version. I need to use this version because it is embedded in the software (SketchUp) for which I am writing a plugin. Also, I think I better understand the issue in [this](http://stackoverflow.com/questions/36245878/releasing-the-global-vm-lock-in-a-c-extension-without-using-another-function) question. I am now trying to return the result to Ruby. If my understanding is correct I need to return a `void *` and then cast it back to `double` in `double_no_gvl`.


My shower doesn't turn on when I turn the diverter

Question: I have a problem with my shower.  When I turn the diverter knob no water comes out of the shower head.  I have the type of knobs that are three one for hot one for cold and the middle to turn on the shower.  What is going on and can I easily fix it?  It isn't brand new but not very old the handles about 7 years old.  It worked until recently.  Any help? please!
Answer: It sounds like there is a problem with the diverter valve. When you turn on the hot and/or cold water valves they flow through the diverter valve on the way to the tub spout. When you turn the diverter valve, it redirects the flow up the pipe to the shower head.
When a diverter valve malfunctions, initial symptoms usually include partial diversion, where some water comes out of the tub spout and some comes out of the shower head, it is unusual for there to suddenly be "no water out of the shower head" like you describe.
Special tools are usually required, like a shower valve socket tool which reaches deep into the wall to facilitate removal. If you want to DIY you need to give more info and post pics. If you are not ambitious, call a plumber.
Comment: I agree Jimmy they don't usually totally fail. Could the knob that connects to the valve stem be stripped?
Comment: @ed beal, good thought, that would create zero diversion. Hope OP figures it out or comes back with some info.


What is Mann-Up Mode?

Question: The Mann vs. Machine update for Team Fortress 2 has revealed something called "Mann-Up" mode, which plays the new maps on official Valve servers, and requires a "Tour of Duty" ticket.
However, the only references I can find to that item are in the Mann. Co store, on sale for .99 cents each.
Do I have to fork over 1$ every time I want to play this mode? What gives? How does Mann-Up mode work? If I can play the update without playing in Mann-Up mode (and without paying), what's the benefit to paying Valve each time?
Can I perhaps pay a lump sum, like when I originally purchased TF2?
Answer: Found out some information here.

Do I have to fork over 1$ every time I want to play this mode?

It seems that you do need to buy a ticket each time you want to play in Mann Up Mode, however you do not need to pay to play Mann vs. Machine.

What gives? How does Mann-Up mode work?

Playing on the Valve servers in Mann Up mode is the same as playing on regular Mann vs Machine servers, with the addition of item drops and service record information tracking, in the form of a Tour of Duty Badge.
Each successful win in Mann Up Mode gives you a exclusive Mann vs Machine item drop.
Mann Up mode keeps track of the games you have played, and you can earn progress to a 'rare item'. Then upon receiving that rare item, your card gets leveled up and you can repeat the process as a higher rank and continue to get more and more rare items.

If I can play the update without playing in Mann-Up mode (and without paying), what's the benefit to paying Valve each time?

The $0.99 you spend gets you an item each time. I'm going to say it gives you a hat or misc each time since the FAQ linked above states:

All items unique to Mann Up Mode are cosmetic

So the $0.99 you spend each time gives you a hat/misc each time, as well as adding up to a 'rare-item' though the progress of your Tour of Duty Badge.

However, you do not need to pay the $0.99 each time you play Mann Up Mode,

Tour of Duty Tickets and Squad Surplus Vouchers are ONLY consumed upon successful completion of a Mission. If you do not beat the Mission for any reason, then your Tickets and Vouchers will not be consumed and can be used again later.

So a disconnect or a loss does not consume the $0.99. Therefore you really do get a hat/misc for each ticket you buy.

Personal Experience:
I have played Mann vs. Machine on a regular, non-Mann Up mode, server.  I did not receive any item drops upon successful completion of the game.
 (Aside, this game mode is very fun and I highly recommend it. Although it can be glitchy, it seems as though Valve hasn't fully tested it when they released it.)
It seems as though STAR has beaten me to sum up what Mann Up Mode is.
Watch his vid at 2:35 to 3:15 and 4:24 to 5:28 for some first hand experience as to what Mann-Up mode is.
Comment: So the $1 for Mann Up is essentially like buying a random item from the store, except you get items exclusive to Mann Up mode? And also you have to play a round of Hat Simulator or something weird like that in the middle.
Comment: @Tacroy as far I have figured out, yes it is like buying a random, Mann Up exclusive, item from the store.  I've never heard of any Hat Simulator round or anything, but I'll try and get on sometime this weekend to try it out and post my findings here.
Comment: Oh sorry the "Hat Simulator" thing was just a joke about TF2's fondness for hats :)
Comment: @Tacroy oh haha xD I thought it was a legit mini-game to determine what hat you got or something

What is Mann-Up Mode?