text:
Q: arraylist to array unique order So I'm trying to go through an arraylist of objects that all have a certain strength value and depending on their strength value, they go into the bigger 2d array based on that. So if their strength value is 0 then they go in the 0th array of the bigger one and this is what my code looks like so far
private ArrayList<Battleable> arr;

public BattleDeck() {
    arr = new ArrayList<Battleable>();
    for (Battleable creature: arr){
        arr.add(creature);
    }

}

public Battleable[][] export2Darray() {
    //returns a two-dimensional ragged array where each row
    //  contains a deep copy of all of the Battleable objects
    //  in the BattleStack with the corresponding Level value
    Battleable[][] retVal = new Battleable[10][];

    int k = 0;

    for (int i = 0; i<arr.size(); i++){
        int levelOfObj = arr.get(i).getLevel();
        if(levelOfObj == k) {
            //insert it into retVal[0][0]

        }

        }
    }

    return retVal;
}

and I was wondering how I would do that? How do i syntax-tically say "get the obj that has strength 0 and put it in position 0 0 of my 2d array

A: A solution using Java 8 streams:
// group Battleables ArrayList by strength
Map<Integer, List<Battleable>> map =
    arr.stream().collect(Collectors.groupingBy(Battleable::getStrength));

The result is a Map containing the Battleables as Lists with their strength as their key.
If you need the result as a jagged 2D array, sort the entries like this:
final Battleable[][] arrays = new Battleable[10][];
map.entrySet().forEach(entry -> {
    arrays[entry.getKey()] = entry.getValue().toArray(new Battleable[entry.getValue().size()]);
});

A: Since arrays are of fixed size in Java, there is no clean way to add items to an array. You can resize the array each time by creating a new array each time, one larger than the last, and copying the data from the old array to the new array, but that would be messy and you would be reinventing a wheel called ArrayList. Modus Tollens has a good answer, but it uses some slightly advanced Java 8 concepts. Here's one way to write it without them:
public Battleable[][] export2Darray() {
    Battleable[][] retVal = new Battleable[10][];

    // create a map that will hold the items, arranged by level
    Map<Integer, List<Battleable>> byLevel = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        // initialize all levels with empty lists
        byLevel.put(i, new ArrayList<>());
    }

    for (Battleable battleable : arr) {
        int level = battleable.getLevel();
        // get the list for this level and add to it
        byLevel.get(level).add(battleable);
    }

    // Now we have a map from levels to lists of battleables;
    // we need to turn each list into an array in our retVal

    for (int level = 0; level < 10; level++) {
        // get each list, convert it toArray and assign to slot in retVal
        retVal[level] = byLevel.get(level).toArray(new Battleable[0]);
    }

    return retVal;
}

A: Here's a solution using ArrayLists, I am creating an ArrayList which will be referenced by strength, then inside of this I have another ArrayListwhich will have all of the Battleable objects of that strength level.
public ArrayList<ArrayList<Battleable>> exportBattleable() {
    ArrayList<ArrayList<Battleable>> retVal = new ArrayList<ArrayList<Battleable>>();

    for (int i = 0; i < arr.size(); i++){
        retVal.get(arr.getLevel()).add(arr.get(i));
    }
    return retVal;
}

Now if you want to print all Battleable objects of strength = 3, you would do:
ArrayList<Battleable> strength3 = retVal.get(3);
for(Battleable battleable : strength3) {
    System.out.println(battleable.toString());
}

This way you don't have to worry about re-sizing your arrays depending on how many Battleable objects you are adding in, same with strength levels, if you decide that instead of using strength levels from 0-9 that you wanted to use 0-20 you already have the ability to scale up or down.


text:
Q: Office Outlook 2007 C# add-in built with Visual Studio 2010: InvalidManifestException I can't figure out how to get a C# add-in built with VS 2010 working on Outlook 2007.
Outlook doesn't load it, i get this error:

Microsoft.VisualStudio.Tools.Applications.Runtime.InvalidManifestException
  An unexpected element "description" was found in the XML.

The plugin "per se" it's ok, since someone before me got it working here at work, even if there were problems with it (sometimes this plugin's button disappeared).
I tried even to overwrite the manifest of my build with the manifest of the working version, but i get another InvalidManifestException.
I installed vsto30, vsto40 and primary interop assembly (PIA) for office 2007.
I tried both using a visual studio setup project and the setup.exe generated by the Publish wizard.
I even tried to create a new "Office 2007" project in VS2010, and i still get the same InvalidManifestException.
Update:
Following more carefulyl the steps, i get this Exception:
InvalidDeploymentException: Exception reading manifest from file:///C:/Provaaddin/SmartOutlookAddIn/SmartOutlookAddIn.dll.manifest: the manifest may not be valid or the file could not be opened. ---> System.Deployment.Application.InvalidDeploymentException: Deployment manifest is not semantically valid. ---> System.Deployment.Application.InvalidDeploymentException: Deployment manifest requires < deployment > section.

A: Ok, solved.
Thank you to SliverNinja for the link.
There were another couple of my errors:
1-it seems it didn't like to be placed in program files folder
2-i have had to re-include dlls that the msdn guide suggested me to exclude in the setup project
3-i had added the |vstolocal string in the registry key, but i hadn't redirected the manifest to .vsto file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create kibana watcher to trigger email with containg kibana json attribute value We have multiple applications which pushing log into Kibana.
In JSON, below parameter will be there :

*

*srcSystem.componentName: "DATA-LAMBDA-FUNCTION"

*srcSystem.data.auditJson.job_status: "FAILURE"

*srcSystem.data.auditJson.errorMessage: "Bad SQL Grammer.."

*srcSystem.data.auditJson.entityName: "Test_Entity1234"

There will be chances available multiple job_status: FAILURE within 5 mins.
I want to create Kibana Watcher to trigger email if there are at least single failure every 5 mins. Email should contain like below:
srcSystem.data.auditJson.entityName          srcSystem.data.auditJson.errorMessage
Test_Entity1234                               Authentication Failure
Test_4312                                     Server Down
Address_Entity                                Bad SQL
Can you please help me to create JSON Payload to create Watcher through Kibana Watcher API?

A: Got the solution by providing the exact JSON.


text:
Q: Is int π; is valid syntax in java? I have some doubt ,i want to know that is int π; is a valid syntax in Java Or Not because Java support UNICODE so according to me it can be valid but I want to make sure

A: int π; is perfectly valid - as you say Java supports unicode so anything not reserved is fair game for identifiers.


text:
Q: Does cluster reject queries when rolling restart? Here is the post of rolling restarts:
https://www.elastic.co/guide/en/elasticsearch/guide/master/_rolling_restarts.html
Does it affect any queries running during this process? The process does not explicitly let clusters know a node will be killed, but only stop sync and rebalancing. Are existing queries rejected or retried?
There is another option
"transient": {
"cluster.routing.allocation.exclude._ip":
}
which can 'disable' a node to restart and rebalance data. Is this one better than the approach the link says?

A: It depends on your cluster configuration. You can avoid it.
If you have replicas and not querying restarting node directly you should be fine.
First of all, take a look at coordinating node note

Requests like search requests or bulk-indexing
  requests may involve data held on different data nodes. A search
  request, for example, is executed in two phases which are coordinated
  by the node which receives the client request — the coordinating node.
In the scatter phase, the coordinating node forwards the request to
  the data nodes which hold the data. Each data node executes the
  request locally and returns its results to the coordinating node. In
  the gather phase, the coordinating node reduces each data node's
  results into a single global resultset.
Every node is implicitly a coordinating node. This means that a node
  that has all three node.master, node.data and node.ingest set to false
  will only act as a coordinating node, which cannot be disabled. As a
  result, such a node needs to have enough memory and CPU in order to
  deal with the gather phase.

There could be different edge cases:

*

*you have only one node in cluster: requests will fail -- add more nodes

*you have several nodes in cluster and 0 replicas for your shards: if you need data from restarting node in your query, request will partially fail -- have replicas

*you have several nodes with replicas and you querying restarting node directly: request will fail -- exclude restarting nodes from your application or always query dedicated coordinating node, it will take care about nodes leaving the cluster.


text:
Q: virtualenv: how to switching global site packages inheritance on and off? In virtualenv, the option to inherit site packages from parent seems to be determined when it was created, and cannot be modified later.
This has created great inconvenience for dependency management, e.g. when the venv is referenced and dereferenced in Pycharm:
https://youtrack.jetbrains.com/issue/PY-38221?project=PY&clearDraft=true&description=PC-192.6817.19,%20JRE%2011.0.4%2010-b304.69x64%20JetBrains%20s.r.o,%20OS%20Linux(amd64)%20v5.0.0-29-generic,%20screens%201920x1080
The inheritance will be permanently disabled and never found again.
Is my impression correct? If not, what is the easiest way to achieve this feature?

A: If I remember just recreate the virtualenv with the same target directory and with or without the --system-site-packages and it should toggle.
It least with older versions of virtualenv this worked if I recall correctly

A: virtualenvwrapper has a command toggleglobalsitepackages.


text:
Q: Get X/Y position of substring in multi-line + scrollable TextView in SwiftUI and macOS 11 Plan
I have implemented a TextView into my Swift-app (macOS 11) using the following implementation, which makes the TextView scrollable by placing it into a ScrollViewer:
https://gist.github.com/unnamedd/6e8c3fbc806b8deb60fa65d6b9affab0
Now, I'm trying to display annotations on the side of the text, which should eventually look something like this:

I planned to achieve this by

*

*Setting a custom AttributedString-key to the NSAttributedString of the TextView

*Add a second ScrollView on the left side, which contains the annotations, and synchronise the scroll position of both ScrollViews (i.e., the left one and the one in the TextView.)

*Calculate the Y-position of each annotation using the relevant substring and place/draw the annotation/connecting line
Problem
I tried to evaluate the Y-Position of a substring using the textView.firstRect function (which I found in all the other, old SO-questions), however, it does not seem to return the correct values unless the position of a substring within the first line of the TextView is used.
    class TextViewExtended: NSTextView {

func getAllRectangles() {
    for CurRange in self.selectedRanges {
        self.layoutManager!.ensureLayout(for: self.textContainer!) // S. https://stackoverflow.com/a/30752520/2624880
        let CurRangeAsNSRange:NSRange = CurRange as! NSRange
        var actualRange = NSRange(location: 0, length: self.attributedString().length)
        let rect = self.firstRect(forCharacterRange: CurRangeAsNSRange, actualRange: &actualRange)
    }}}

Question
What would be to correct way to determine the coordinates of a substring of a TextView in SwiftUI & macOS 11? Or does anybody have an even simpler idea how I could achieve this?
Thanks a lot in advance for any advise!
Ps. I have omitted the full code of the TextView implementation since it follows the above tutorial closely; please let me know if I should add additional code.

A: Try updating the rect using the actualRange. some thing like this:
rect = textView.firstRect(forCharacterRange: range, actualRange: &actualRange)
while actualRange.upperBound < rangeToCheck.upperBound {
    rangeToCheck.length = (rangeToCheck.upperBound - actualRange.upperBound)
    rangeToCheck.location = actualRange.upperBound
    rect = textView.firstRect(forCharacterRange: rangeToCheck, actualRange: &actualRange)
}


text:
Q: Writing secure transport level using security framework I have developed security sensitive App. I had to use TEA based algorithm to encrypt/decrypt data to communicate with server and follow Server protocols. I have used AsyncSocket for trasport level communication which uses CFNetwork APIs. I have noticed that TEA algorithm is not very secure and can be hacked easily. Moreover, AsyncSocket library isn't using Apple's Security Framework anywhere. I am planning to rewrite transport layer and redefining client-server security protocols. I have been researching on what kind of security algorithm should I use for data protection which has no or minimum performance impact and difficult to break. Moreover, I am going through Security frameworks but couldn't find any example that uses this framework to implement transport layer. Could someone please assist me on this? What are the things I should follow to code secure transport layer? what are the security measures that I could check against my App?

A: As @CodesInChaos notes, you should use TLS for this. You absolutely should not design or implement a new transport protocol.
The fact that CFNetwork supports TLS does not mean that you are using it. You need to actively use it. Your server needs a certificate that your client trusts, and it needs to negotiate a TLS session. In general, if you just use HTTPS and the standard NSURLConnection routines , then you're going to get most of what you need for free. But if you start building it by hand in CFNetwork, you need to make sure that you're configuring it correctly. My recommendation is to use HTTPS whenever possible. It's simple and makes a wide variety of problems go away.
That said, just because the transport is secured does not mean that your app is "secured enough." In particular, your server still needs to be able to deal with malicious clients talking over a secured transport. You need to properly authenticate the user and you need to handle malicious data gracefully. When the data reaches your server, you need to store is securely. You may need to encrypt data on the client. There are many aspects to securing a system beyond the transport.


text:
Q: Загрузка содержимого Excel-вложения Gmail в Таблицу Google Мне на почту Gmail приходит отчет в формате xlsx. Хочу, что-бы он автоматически переносился в Гугл Таблицу в один лист.
Пробую использовать скрипт на Google Apps, yо он не работает.
Может кто подскажет, где там ошибки, при запуске ругается на 9 строчку с ошибкой

ReferenceError: fileInfo is not defined

function importProduct() {
  var requete = "1pdbQ_AoXIVcPtN8CIoVVu84kiX-wp5KA";
  var threads = GmailApp.search(requete);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages);
  }

  const file = Drive.Files.insert(fileInfo, excelFile, { convert: true });
}
function getExcelFile(thread) {
  var messages = thread.getMessages();
  var len = messages.length;
  var message = messages[len - 1];
  var attachments = message.getAttachments();

  var xlsxBlob = attachments[0];
  Logger.log(xlsxBlob.getContentType());
  var convertedSpreadsheetId = Drive.Files.insert(
    { mimeType: MimeType.GOOGLE_SHEETS },
    xlsxBlob
  ).id;
  var filename = xlsxBlob.getName();
  var tabName = filename.substring(13).slice(0, filename.length - 18);

  var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0];
  var destination = SpreadsheetApp.openById(
    "1lfDEEn1PpTh5dja6VOPvKvMVPPCBA5xgV6uVRemKmcc"
  );
  var sss = destination.getSheetByName("Общий");

  Drive.Files.remove(convertedSpreadsheetId);
  labelName = "1pdbQ_AoXIVcPtN8CIoVVu84kiX-wp5KA";
  deleteForever(labelName);
}

A: Вероятно, что-то такое должно подойти
function saveExcelGmailAttachmentToExistingSheet() {
  const query = "subject:file with excel"; // Поисковый запрос, чтобы найти нужное сообщение с вложением
  const targetBookId = "abcd1234"; // Идентификатор Таблицы, в которую нужно загрузить данные

  const mediaData = GmailApp.search(query)[0]
    .getMessages()[0]
    .getAttachments()[0];

  const resource = {
    title: mediaData.getName(),
    mimetype: mediaData.getContentType(),
    description: "",
  };

  const file = Drive.Files.insert(resource, mediaData, { convert: true });

  const data = SpreadsheetApp.openById(file.id)
    .getSheets()[0]
    .getDataRange()
    .getValues();

  const targetBook = SpreadsheetApp.openById(targetBookId);
  const targetSheet = targetBook.getSheets()[0];
  targetSheet.appendRow([""]);
  targetSheet
    .getRange(targetSheet.getLastRow() + 1, 1, data.length, data[0].length)
    .setValues(data);

  DriveApp.getFileById(file.id).setTrashed(true);
}

Простого метода нет, поэтому приходится загружать Blob и конвертировать его в Таблицу, читать эту Таблицу и записывать результат в требуемую.


text:
Q: Quick.db unwarn command unwarns all the warns in a member I am coding my own discord bot, and making warn system with quick.db package, and having a problem. If I warn a person 2 times, and unwarn him, It removes all the warns of the user. The code is:
//I have imported discord.js and others. This is only the part of warn and unwarn command.
if(command === "warn" ) {
   const db = require('quick.db')
   const Wuser = message.mentions.users.first();
   const member = message.guild.member(Wuser)
   if(!message.member.hasPermission("MANAGE_MESSAGES"))
   return message.channel.send("You dont have the permission to warn anyone").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
          if (!Wuser) return;
          if(Wuser.id === message.author.id) return message.channel.send("You cant warn yourself").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
          if(Wuser.id === client.user.id) return message.channel.send("You cant warn me").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
          db.add(`warn.${Wuser.id}`, 1);
          const data = db.get(`warn.${Wuser.id}`);
      if(data === undefined ) {
        let data = 0
      }
      message.channel.send(`${Wuser} you are warned. Additional infractions may result in a mute. You have ${data} warns.`)
      logchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)
   blogchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)

   }

if(command === "unwarn" ) {
   if(!message.member.hasPermission("MANAGE_MESSAGES"))
   return message.channel.send("You dont have the permission to unwarn anyone").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
           const db = require('quick.db')
           let Wuser = message.mentions.users.first();
           let member = message.guild.member(Wuser)
          if (!Wuser) return;
          if(Wuser.id === message.author.id) return message.channel.send("You cant unwarn yourself").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
          if(Wuser.id === client.user.id) return message.channel.send("You cant unwarn me").then(msg => {
                                                     msg.delete({ timeout: 10000 })
                                                             })
          db.delete(`warn.${Wuser.id}`)
          const data = db.get(`warn.${Wuser.id}`)
          message.channel.send(`${Wuser} is unwarned. `)
          logchannel.send(`${Wuser} is unwarned by ${message.author}.`)
          blogchannel.send(`${Wuser} is unwarned by ${message.author}.`)
     }

if(command === "userlog") {
    if(!message.member.hasPermission("MANAGE_MESSAGES"))
    return message.channel.send("Why are you looking other's user log?").then(msg => {
        msg.delete({ timeout: 10000 })
    })
  let Wuser = message.mentions.users.first()
  let member = message.guild.member(Wuser)
  if (!Wuser) return message.channel.send("User not specified").then(msg => {
      msg.delete({ timeout: 10000 })
  })
   const db = require('quick.db')
   const data = db.get(`warn.${Wuser.id}`)
   let logEmbed = new MessageEmbed()
   .setTitle(`Log of ${Wuser.tag}`)
   .setDescription(`${Wuser} currently have ${data} warns.`)
   .setThumbnail(member.user.displayAvatarURL)
   message.channel.send(logEmbed)
   logchannel.send(`${message.author.tag} used **.userlog** command.`)
   }

What I have to edit the code? Thanks in advance.

A: In the unwarn command
db.delete(`warn.${Wuser.id}`)

Instead of this add to the db
          db.add(`warn.${Wuser.id}`, -1);

or subtract from the value
          db.subtract(`warn.${Wuser.id}`, 1);


text:
Q: Can you assign values to all elements in struct for a 2D array in C? I want to make a grayscale filter so I have to assign the average of all 3 RGB values to each. I use a 2D array because this is a bitmap image and I'm filtering it by changing each pixel.
This is how the struct is defined (where BYTE is uint8_t):
typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

Do I need to assign the value to each element of struct separately, like I did below, or is there a way to assign that value to all elements of the struct (since they are the same type) in that specific location in the array at once?
This is the code for the filtering function.
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0 ; j < width; j++)
        {
            image[i][j].rgbtBlue = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
            image[i][j].rgbtGreen = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
            image[i][j].rgbtRed = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
        }
    }
    return;
}

A: You can do it with a compound literal:
RGBTRIPLE x = image[i][j];  // Use temporary to reduce repetition.
BYTE t = (x.rgbtBlue + x.rgbtRed + x.rgbtGreen)/3;
image[i][j] = (RGBTRIPLE) { t, t, t };

A: You can certainly avoid making the calculation three times on each loop. Two obvious ways to do this are:
(1) Chain the assignments (note that expressions like a = b = 3; are valid C and the = operator associates right-to-left);
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j].rgbtBlue = image[i][j].rgbtGreen = image[i][j].rgbtRed =
                (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen) / 3;
        }
    }
    return;
}

(2) Calculate that 'gray' value and assign that to the array element (in one go) using a compound literal constructed from that calculated value:
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            BYTE gray = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen) / 3;
            image[i][j] = (RGBTRIPLE){ gray, gray, gray };
        }
    }
    return;
}

Whether or not either of the above actually constitutes an improvement is subjective (and a good compiler will likely generate the same code in both cases). However, for more complex situations, these techniques can make your code clearer and its purpose easier for a reader to understand.

Note also that, as pointed out in the comments, the above two examples will assign the same value to each of the three components of the image[i][j] element. In your posted code, the second and third recalculations use one or two values that will have been modified by the previous line(s).


text:
Q: How to assing values to a dictionary I am creating a function which is supposed to return a dictionary with keys and values from different lists. But I amhavin problems in getting the mean of a list o numbers as values of the dictionary. However, I think I am getting the keys properly.
This is what I get so far:
 def exp (magnitudes,measures):
   """return for each magnitude the associated mean of numbers from a list"""
dict_expe = {}
for mag in magnitudes:
    dict_expe[mag] = 0
    for mea in measures:
        summ = 0
    for n in mea:
        summ += n
        dict_expe[mag] = summ/len(mea)

        return dict_expe

print(exp(['mag1', 'mag2', 'mag3'], [[1,2,3],[3,4],[5]]))

The output should be:
{mag1 : 2, mag2: 3.5, mag3: 5}

But what I am getting is always 5 as values of all keys. I thought about the zip() method but im trying to avoid it as because the it requieres the same length in both lists.

A: An average of a sequence is sum(sequence) / len(sequence), so you need to iterate through both magnitudes and measures, calculate these means (arithmetical averages) and store it in a dictionary.
There are much more pythonic ways you can achieve this. All of these examples produce {'mag1': 2.0, 'mag2': 3.5, 'mag3': 5.0} as result.
Using for i in range() loop:
def exp(magnitudes, measures):
    means = {}
    for i in range(len(magnitudes)):
        means[magnitudes[i]] = sum(measures[i]) / len(measures[i])
    return means

print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))

But if you need both indices and values of a list you can use for i, val in enumerate(sequence) approach which is much more suitable in this case:
def exp(magnitudes, measures):
    means = {}
    for i, mag in enumerate(magnitudes):
        means[mag] = sum(measures[i]) / len(measures[i])
    return means

print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))

Another problem hides here: i index belongs to magnitudes but we are also getting values from measures using it, this is not a big deal in your case if you have magnitudes and measures the same length but if magnitudes will be larger you will get an IndexError. So it seems to me like using zip function is what would be the best choice here (actually as of python3.6 it doesn't require two lists to be the same length, it will just use the length of shortest one as the length of result):
def exp(magnitudes, measures):
    means = {}
    for mag, mes in zip(magnitudes, measures):
        means[mag] = sum(mes) / len(mes)
    return means

print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))

So feel free to use the example which suits your requirements of which one you like and don't forget to add docstring.
More likely you don't need such pythonic way but it can be even shorter when dictionary comprehension comes into play:
def exp(magnitudes, measures):
    return {mag: sum(mes) / len(mes) for mag, mes in zip(magnitudes, measures)}

print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))


text:
Q: Which algorithm for triangularization of algebraic surfaces with singularities? I want to code some software in Python that visualizes implicit algebraic surfaces with singularities (say the Barth Sextic e.g.). I am thinking about calculating primitive triangles in Python and then give them to a shader connected via ModernGL for the output graphic.
Since the most literature I found is quite old I am asking here what the state of the art algorithm for triangularization of algebraic surfaces with singularities actually is? I don't know much about the topic but I learned that the standard Cutting Cube and Marching Method probably won't work.


text:
Q: Can't define html content of HTML tag with innerHtml I have this code Html code in my recent project:

    ...
    <input type="radio" name="tabset" id="tab-insert" aria-controls="insert" style="display: none;">
    Insert
    ....

        Novo

    ....

    ....

    ...

when I click on the button above, triggers this javascript function:
function insert_data() {
  if(document.getElementById('tab-insert').style.display === 'none') {
    var url = document.getElementById('insert').dataset.url;

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var myObj = this.responseText;

        parser = new DOMParser();
        var doc = parser.parseFromString(myObj, "text/html");
        var form_html = doc.getElementById('form');

        document.getElementById('tab-insert').removeAttribute('style');
        document.getElementById('label-insert').removeAttribute('style');
        document.getElementById('insert').removeAttribute('style');

        document.getElementById('form-insert').innerHtml = form_html;

        document.getElementById('tab-insert').setAttribute('checked', 'checked');
        document.getElementById('tab-listagem').removeAttribute('checked');
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
  }
}

which is executed by the browser with no error in the console, but no code is added to the

 block.
Cannot figure out what's wrong here. Someone can give a hint of how to make this work?
(I checked, the variable form_html is receiving the right value; all the code seems to work fine, except the line document.getElementById('form-insert').innerHtml = form_html;).


text:
Q: unable to understand these examples from the book javascript, The good parts I am reading javascript: The good parts by Douglas Crockford. I am having difficulty in understanding a particular example and the explanation that author provides.
example 1: (pg 38)
var quo=function (status) {
    return {
        get_status:function() {
           return status;
       }
    };
};

var myQuo=quo("amazed");
document.writeln(myQuo.get_status());

The explanation from book (I do not understand this. please explain this part):

This quo function is designed to be used without the new prefix, so the name is not capitalized.when we call quo, it returns a new object containing a get_status method. A reference to that object is stored in myQuo. The get_status method still has privileged access to quo's status property even though quo has already returned. get_status does not have access to a copy of the parameter. it has access to the paramter itself. This is possible because the function has access to the context in which it was created. This is called closure.

example 2(pg 39):
//make a function that assigns event handler function to array of nodes
//when you click on a node, an alert box will display the ordinal of the node

var add_the_handlers=function (nodes) {
    var helper=function(i) {
        return function(e) {
            alert(i);
        }
    };
    var i;
    for (i=0;i<nodes.length;i++) {
        nodes[i].onclick=helper(i);
    }
};

I am having difficultly to understand how this code works and moreover what function(e) does?
why helper function return function that in turn return nothing. Its very confusing to me. if somebody can explain in simple language, it will be very helpful. Thanks a lot
EDIT:
According to the book is the bad example for the above(example 2):
  var add_the_handlers=function(nodes) {
    var i;
    for (i=0;i<nodes.length;i++) {
     nodes[i].onclick=function(e) {
     alert(i);
     };
   }
};

The author cites this as bad example because it always displays the number of nodes.

A:
What he was implying in the example, I believe, was the fact that you don't have to make a copy of the status parameter and pass it to the get_status function because get_status implicitly gets access to everything enclosed within the context in which it was defined (in this case, quo)
Similarly, in example 2

A:
why helper function return function that in turn return nothing.

In javascript, functions do not have to explicitly return a value. If a return value is ommitted, an implicit return undefined; is.
Furthermore, functions are objects. So, helper() is a javascript function, which returns a function:
function(e) {
   alert(i);
}

Later in the for loop, nodes[i].onclick=helper(i); this line executes the helper() function, which returns a function object, which is then assigned to the onclick handler for the node.
In the Bad Example, the author is illustrating a common problem that trips up novice javascript developers.
//According to the book is the bad example for the above(example 2):
 var add_the_handlers=function(nodes) {
  var i;
  for (i=0;i<nodes.length;i++) {
   nodes[i].onclick=function(e) {
   alert(i);
   };
 }

In this case, the novice programmer expects each node to display its index. However, because the onclick handler created a closure around i, the value of i is set to the value of the outer scope, which ends up being the value of i when the function is executed, instead of when the function is assigned as the novice programmer expects. So for each node that is clicked, it ends up printing the same number, which is nodes.length or the number of nodes in the array.
Per the comment:

further, can you explain what the e in funciton(e) does?

In the DOM Api, event handlers all pass in an event object that contains information about the event. So in this case, e is the click event object. And e is unused by this  function, so it could have been omitted.


text:
Q: android internet connection error fails Hi I try to show the user a costum file if the internet connection fails. In this case it works fine. If the internet connection works and index.php become loaded all works until then.
If I click on a button on index.php and the user become redirected to another page say we login.php the costum error file starts. Thats bad. How can the file myerrorpage.html only become showed when the internet connection fail and not the project file change?
 @Override
public void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.activity_localy);
    mWebView = (WebView) findViewById(R.id.webview);
    // Brower niceties -- pinch / zoom, follow links in place
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    mWebView.setWebViewClient(new GeoWebViewClient());
    // Below required for geolocation
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setGeolocationEnabled(true);
    mWebView.setWebChromeClient(new GeoWebChromeClient());
    // Load google.com
    mWebView.loadUrl("http://192./loc/index.php");

   super.onCreate(savedInstanceState); mWebView.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mWebView.loadUrl("file:///android_asset/myerrorpage.html");

        }
    });
}

A: From,

Report web resource loading error to the host application. These errors usually indicate inability to connect to the server. Note that unlike the deprecated version of the callback, the new version will be called for any resource (iframe, image, etc), not just for the main page. Thus, it is recommended to perform minimum required work in this callback.

This method is not the best place to check for Internet Connectivity Issues. You can manually check for Internet Connectivity and Load the error page.


text:
Q: Firebase Authentication updating user profile without permission Users are able to select a photo from their device's gallery when they update the profile photo. The app request permission before the user select photo. But the problem is, when a user uninstalls the app and installs it again they won't see their profile photo anymore because they need to allow the permission once again. I used this code to update the user profile photo:
  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    val userPhoto: CircleImageView = findViewById(R.id.userImage)

    if (requestCode == OPEN_GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        val imageUri = data?.data
        userPhoto.setImageURI(imageUri)

        var user = Utils().getCurrentUser()
        val profileUpdates: UserProfileChangeRequest =
            UserProfileChangeRequest.Builder()
                .setPhotoUri(imageUri)
                .build()
        user?.updateProfile(profileUpdates)?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d("ProfileChange", "User profile updated.")
                Log.d("ProfileChange","${imageUri}")
            }
        }
    }
}

Logcat ouput is :D/ProfileChange: content://media/external/images/media/19344
Is there any solution so users don't have to accept any permission to see their profile photos after they uninstall and reinstall the app?

A:
Is there any solution so users don't have to accept any permission to see their profile photos after they uninstall and reinstall the app.

Unfortunately, there is no way you can preserve permissions on an app uninstall. Once an app is uninstalled, everything that is related to the app goes away, including the local cache and permissions. So you need to accept permissions on every new app install.


text:
Q: 3D mesh representation Currently I'm developing a library to manage some stream of data, but at some point I'd like to represent my findings on 3d. I would like to develop a 3D view of my project:

I have:
- All the 3D vertices of one single block
- All the properties related with the object
The question is: Can I do this on python? Which library should I use? Is there any other solution rather than

A: Depending on what kind of display you are looking for.

*

*if you need to display it as scientific data, there is VTK which propose a great variety of ways to display

*if you want to operate your 3d data, display and inspect it at the same time, you can go for pymadcad  (a lot of other modules are available for mesh manipulation only, but without display)

*if you want a highly flexible rendering pipeline, you can take a look at moderngl, which is very close to the hardware reality by makes everything extremely simple

*if you want a high interaction and flexibility in displaying meshes, maybe a game engine, like Panda3D can be more convenient


text:
Q: Selenium chromedriver opens a blank page instead of url on linux I am trying to open a url in chromedriver(using RemoteWebDriver) on linux.
I took a screenshot after driver.get(url) is called. It displays a blank page.
east-northamptonshire_screenshot.jpg
I tried this(open a url using ChromeDriver) on my local machine(Windows). It is working fine.
This is the url I am trying to open. "https://publicaccess.east-northamptonshire.gov.uk/online-applications/search.do?action=weeklyList"
Main method:
 public static void main(String[] args) throws Exception {

    String OS = System.getProperty("os.name").toLowerCase();

    WebDriver driver = null;
    ChromeDriverService service = null;

    boolean isWindows = OS.indexOf("win") >= 0;
    logger.info("operating System : " + OS);
    if (!isWindows) {
        service = new ServerChromeDriver().loadService();
    }
    driver = new ServerChromeDriver().getPIDriver(service, isWindows);

    String url = "https://publicaccess.east-northamptonshire.gov.uk/online-applications/search.do?action=weeklyList";
    driver.get(url);

    Thread.sleep(3000);
    ScreenShot.takeScreenShot(driver);

    driver.close();
    driver.quit();
    service.stop();
}

ServerChromeDriver Class:
  public ChromeDriverService loadService() throws Exception {

    Configuration configuration = new Configuration();
    configuration.loadProperties();

    Properties props = new Properties();
    try {
        props.load(new FileInputStream("config//log4j.properties"));
    } catch (IOException e) {
        logger.error(e);
    }
    PropertyConfigurator.configure(props);

    service = new ChromeDriverService.Builder().usingDriverExecutable(new File(configuration.getChromeDriverPath()))
            .usingAnyFreePort().withEnvironment(ImmutableMap.of("DISPLAY", configuration.getDisplay())).build();
    service.start();

    return service;
}

  public WebDriver getPIDriver(ChromeDriverService service, boolean isWindows) {

    WebDriver driver;

    if (isWindows) {
        driver = new LocalChromeDriver().getDriver();
    } else {
        driver = new ServerChromeDriver().getDriver(service.getUrl());
    }

    String hostName = new ServerChromeDriver().getHostName(driver);
    logger.info("Running the application on host: " + hostName);

    return driver;
}

public WebDriver getDriver(URL serviceUrl) {

    Configuration configuration = new Configuration();
    configuration.loadProperties();
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    chromeOptions.addArguments("--disable-gpu");
    // chromeOptions.addArguments("--start-maximized");
    chromeOptions.addArguments("--window-size=1800,1800");
    // chromeOptions.addExtensions(new File(configuration.getAdBlockPath()));

    System.setProperty("webdriver.chrome.driver", configuration.getChromeDriverPath());
    System.setProperty("webdriver.chrome.logfile", configuration.getChromeDriverLogFilePath());
    System.setProperty("webdriver.chrome.verboseLogging", configuration.getChromeVerboseLogging());

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    capabilities.setJavascriptEnabled(true);

    try {
        driver = new RemoteWebDriver(serviceUrl, capabilities);
    } catch (Exception e) {
        logger.error("Error creating a new chrome instance");
        throw new RuntimeException(e.getMessage());
    }
    driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);

    return driver;
}

Application is working fone for this url: https://eplanning.birmingham.gov.uk/Northgate/PlanningExplorer/GeneralSearch.aspx
birmingham_screenshot.jpg
I am using
Headless Chrome : 67.0.3396.62
chromedriver    : 2.40.565383

This is what I found from the chromedriver.log file
[0617/144457.403693:ERROR:nss_ocsp.cc(601)] No URLRequestContext for NSS HTTP handler. host: crt.comodoca.com
[0617/144457.403801:ERROR:cert_verify_proc_nss.cc(980)] CERT_PKIXVerifyCert for publicaccess.east-northamptonshire.gov.uk failed err=-8179

A: I think because Chrome version in your Linux machine is not supported.

A: For people using newer versions of Selenium who are dealing with this issue, I was able to do the following (similar to Abhilash's answer which is using an older version of Selenium) to resolve the blank-page issue for uncertified domains with Chrome:
ChromeOptions options = new ChromeOptions();
...
options.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
...
driver = new ChromeDriver(options);

(In my case, webdriver worked fine on my local machine but not on the Linux box hosting CI tools)

A: After researching about certificate errors, I have added additional capabilities to chrome driver to ignore certificate related errors. Below is my solution.
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();

        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        capabilities.setJavascriptEnabled(true);
        capabilities.setCapability(CapabilityType.PROXY, proxy);
        capabilities.setCapability("acceptSslCerts", true); // Added this additionally
        capabilities.setCapability("acceptInsecureCerts", true); // Added this additionally
        capabilities.setCapability("ignore-certificate-errors", true); // Added this additionally


text:
Q: Is there any particular difference between strval and casting to string like (string) $var It seems to be that there is no difference between the 2 methods since var_dump returns the same result using both methods.
Simple Example:
// integer
$var = 3;

Methods and Outputs:
var_dump($var);         // ouput: int(3)
var_dump((string) $var);  // string(1) "3"
var_dump(strval($var));  // string(1) "3"

As you see case 2 and 3 returns a string as excepted.
What do you think?

A: The largest difference will be the fact that a function (any function) incurs some overhead. It's a negligible amount so, for the most part, this discussion is more academic than anything else. Gerton's link proves it's slower on point but you're unlikely to notice that gap in normal execution because he ran that function 1 million times to get a 0.7s gap (and he was using PHP 5.2, while PHP 7 might make that gap even smaller).  Consider this article on function execution time

The second tip is that PHP is fast, believe me. For what you ask it to do, the way it does the job and the tools it represents to you : it is fast, efficient, reliable. There is not that much room to optimize PHP scripts, at least not as if you were using lower level language like C. The main trick is to optimize what is repeated : loops. If you use a profiler showing you the hot path of you script, you'll happen to find that it is likely to be located into loops. That's the same when we, as contributors, optimize PHP itself : we won't bother optimizing a part of code a few users will trigger, but better optimize the hot path : variable accesses, engine function calls, etc... Because in here, the very little micro-second earned will translate to final milli-seconds or even seconds, as such code is run tons of times (usually involving in loops). Except foreach(), in PHP, loops are the same and lead to the same OPCode. Turning a PHP's while loop into a for loop is both useless and silly. Once more : profiling will tell you that.


text:
Q: Space.Self smooth rotating menu around hand for Oculus Touch. How can I control the speed of the rotation with value for speed? using UnityEngine;

public class Lerp : MonoBehaviour
{
[Range(0, 360)]
public float angle = 120;//Specify Angle For Rotation
float tempAngle;//Temporary Angle Measurement Variable
bool horizontalFlag;//Check For Horizontal Roation
bool isRotating;//Check Whether Currently Object is Rotating Or Not.
int Direction;//Direction Of Rotation

//Called For Initialization
void Start()
{
    horizontalFlag = isRotating = false;
}
//Method For Horizontal Input
void CheckForHorizontalInput()
{
    if (Input.GetAxis("Horizontal") != 0 && !isRotating)
     {
         isRotating = true;
         Direction = (Input.GetAxis("Horizontal") < 0 ? - 1 : 1);
         horizontalFlag = true;
         tempAngle = 0;
     }
 }
 //Method For horizontal Rotation
 void HorizontalRotation()
 {

     transform.Rotate(Vector3.back *  angle * Time.fixedDeltaTime * Direction, Space.Self);
     tempAngle += angle * Time.fixedDeltaTime;
     if (tempAngle >= angle)
     {
         tempAngle = 0;
         isRotating = false;
         horizontalFlag = false;
     }
 }
 void Update()
 {
     CheckForHorizontalInput();
     if (horizontalFlag)
         HorizontalRotation();
 }
 }

I want to be able to control the speed of the rotation of the object in seconds.
now the menu is 3 pages and it is rotating with 120 degrees smoothly and stops on 120 degrees. Also if the button pressed is hold the rotation continues and stops on the same range of 120 degrees that the menu is in. if I move the joystick left the menu rotates left if I move the joystick to the right the menu rotates to the right.
Can you tell me how to do this?


text:
Q: Algolia voice-overlay-ios change titleListening I want to change "listening..." text of inputScreen:
voiceOverlayController.settings.layout.inputScreen.titleListening = "Another text for listening..."
but this doesn't help.

A: Be sure to add your code for changing the UI in the appropriate lifecycle of the ViewController. I have the following appear correctly when the code is under viewDidAppear(:_):
voiceOverlayController.settings.layout.inputScreen.titleListening = "Voice-search is not enabled."


text:
Q: Small Javascript code that will just Read a Cookie (give it's value)? To create a cookie in javascript I use
document.cookie = "cookieName=cookieValue;expires=myDate;path=/"

To read a cookie: I read many articles in the web including w3schools, but they give complicated codes with for(;;){} method and split. I don't need such codes. I just need a small javascript code.
If anyone can, please give me a code that will display an alert with the value of 'cookieName' cookie?

A: This may be the easiest way I can give you.
Call the function it returns cooke value:
      /**
    * Returns cookie.
    * @param {String} sName Main cookie name.
    * @param {String} SubName Sub cookie name.
    * @return {String} Cookie.
    */

GetCookie: function (sName, SubName) {
        var aCookie = document.cookie.split("; "); // cookies are separated by semicolons
        var CookieVal = null;
        var bHasKeys;
        for (var i = 0; i < aCookie.length; i++) {
            var aCrumb = aCookie[i].split("=");
            bHasKeys = aCrumb.length > 2 ? 1 : 0;
            if (sName == aCrumb[0]) {
                var TempVal = aCookie[i];
                TempVal = TempVal.substring(TempVal.indexOf(sName) + sName.length + 1, TempVal.length);
                if (SubName) {
                    TempArr = TempVal.split("&"); // subcookie seperated by &
                    for (var j = 0; j < TempArr.length; j++) {
                        if (TempArr[j].split("=")[0] == SubName) {
                            CookieVal = TempArr[j].split("=")[1];
                            //while loop is added since /+/g syantax does not work here
                            while (CookieVal.indexOf("+") != -1) CookieVal = CookieVal.replace('+', ' ');
                            CookieVal = unescape(CookieVal);
                            break;
                        }
                    }
                }
                else {
                    if (bHasKeys) CookieVal = TempVal;
                    else {
                        CookieVal = aCrumb[1];
                        //while loop is added since /+/g syantax does not work here
                        while (CookieVal.indexOf("+") != -1) CookieVal = CookieVal.replace('+', ' ');
                        CookieVal = unescape(CookieVal);
                    }
                    break;
                }
            }
        }
        return CookieVal == null ? '' : CookieVal;
    }


text:
Q: javascript - set select option value to null I have to disable all the select menus in a div and also set their value to null.
I am using the following code to disable the select menus:
  var div_contents =document.getElementById("div1");
  var elements = div_contents.getElementsByTagName("select");
  for (i=0; i<elements.length; i++) {
      elements[i].disabled = true;
  }

However, I am not able to set the value of the select tag to null.
Also I don't have the null option inside the select tag:
<select id="test1" name="test1">
    <option value="a">aa</option>
    <option value="b">bb</option>
    <option value="c">cc</option>
</select>

How can I set the value of a select list to null, given that I don't have the null option?

A: You could try setting the element's value property:
elements[i].value = '';

A: If you want to show no selection, you should set its selectedIndex to -1.
elements[i].selectedIndex = -1;


text:
Q: Has the A-Wing been retconned? We did not see A-Wings till the Battle of Endor.
When playing the (non-canon) X-Wing games, the A-Wing always seemed to be more advanced than the X-Wing. It was only used for special missions, etc.
So in the 1990s I was under the impression that the A-Wing was the newer fighter.
However we now (in 2015/2016) have Rebels flying A-Wings 5 Years BBY, and X-Wings still in use 35+ years ABY.
Was I mistaken in my 1990s impression of the A-Wing, or has it been changed to be the older craft?

A: In Legends continuity, A-Wing were designed and fielded after the Battle of Yavin, which is why you don't see them before Endor. Disney did a semi-retcon by having them show up in Rebels around 5 years before their former conception.
About them being the "newer" craft, you are comparing oranges to apple, though. What's the better vehicle : a motorcycle, a sedan or a pickup truck? If you want raw speed and maneuverability, the motorcycle is probably your best bet. For a slight drop in maximum speed, though, you could be a lot safer in a sedan, and be able to bring some friends with you. The pickup truck would be slower, but would also allow you to bring a lot more stuff than the other options would. While a motorcycle could be the best option to commute to work on a daily basis, it really wouldn't be my go-to pick if a friend asked me to help him move out of his house.
In Star Wars, it was pretty much the same thing with the A-, X- and Y-Wings. The A-Wings were meant as a counter to the TIE Interceptors, which were a lot faster and better armed than the common TIE Fighters. To achieve similar performances, the A-Wing sacrificed shields and durability, but was also heavily modifiable to suit specific needs. The A-Wing was a huge feat of engineering (at least in the SW Legends), as it managed to be just as fast and well armed as an Interceptor, while still having some shield capacity. The Interceptor had four laser cannons to the A-Wing's two, but the A-Wing had access to concussion missiles, specifically designed to take down enemy starfighters.
X-Wings, on the other hand, were meant to be the "regular" superiority fighters, able to take a heavy beating before going down, usually taking down a few TIEs themselves before doing so. Being much larger, the X-Wing also had access to the very versatile proton torpedo launchers, which could be used for dogfighting, bombing runs or capital ship assaults. The Y-Wings, in the mean time, were intended as slower bombers, with larger payloads but limited dogfight capabilities. Another result of the "Galactic Arms Race", in a fashion similar to the A-Wing, was the creation of the B-Wing, originally intended as a replacement of the Y-Wing. With even heavier shields and targeting capabilities rivaling those of smaller capital ships, they were meant to attack capital ships, using their strong defensive capabilities to live through their bombing runs.
In the end, the A-Wings were not meant to be the "better" or "newer" craft, they were intended as a specific counter measures for TIE Interceptors, which only became apparently superior to X-Wings when their speed and firepower allowed them to make hit-and-run passes at Alliance pilots without them being able to catch up and fight back. The Alliance needed a fighter fast enough to force the Empire into a proper fight, but sturdy enough to live through it, and the A-Wing was born.

A: *

*What's throwing you into confusion is that X-Wings you see in 2015 (I'm assuming you meant 30 years after Endore, in The Force Awakens), are NOT the same X-Wings we see in Original Trilogy.
They are a far more capable and upgraded model, called T-70 (the original was T-65)

*In addition, the main tactical reason for Alliance A-Wings was the fact that they were a TIE/ln-fighter (and TIE-interceptor) equivalent: super fast (Faster than X-wing), no shields and light weapons

A-wings were often modified. The most common variant seen in the Alliance favored raw speed, consisting of a stock model stripped of its shields, armor and heavy weapons. (src)

First Order's new TIE/fo basically became equivalent to X-Wings (shields, better armament) and thus, outclassed the A-Wing in a fight.

A: StarWars.com Databank has an entry for Phoenix Squadron (from Rebels) with a bit of explanation as to why we may not have seen A-Wings at Yavin

Phoenix Squadron was an elite group of A-wings in one of the first
  larger rebel collectives. They served under Commander Jun Sato and
  often assisted the Ghost team on missions -- until one deadly
  encounter with Darth Vader. The Sith Lord, piloting an TIE Advanced
  prototype, wiped out Phoenix Squadron in a vicious attack. Only a few
  ships survived the battle.

http://www.starwars.com/databank/phoenix-squadron
So - to answer your question - probably a bit of both with more emphasis on retconning

A: In Legends, the A-wing was designed after the Battle of Yavin in response to the speed of Imperial TIE fighters. It was observed at that battle that TIEs nearly foiled the Death Star trench run, and that the Rebels needed a faster fighter. In canon, however, A-wings have been seen before the Battle of Yavin in Star Wars Rebels. The backstory for the A-wing has therefore indeed changed.
This arguably not really a retcon, though, since Lucas never considered himself beholden to the EU/Legends; contradictions between canon and Legends don't need to be explained in the same way that contradictions in canon need to.
It is not clear from canon whether the A-wing was developed before or after the T-65B X-wing used by the Rebel Alliance at the Battle of Yavin.


text:
Q: Mitigating touch current in two-pronged AC without dedicated ground I'm trying to work on a simple circuit where (simplified) I plug in a 240V 50Hz AC through a resistive coil to convert to heat. The coil is insulated and placed under a metal plate. I'm noticing that if I touch the plate, I would feel a slight buzzing/tingling sensation, AKA touch current. I have some questions about that:

*

*Is this effect due to induction, or is it a capacitance phenomenon, (or something else??)

*How should I design to ground the plate to eliminate/reduce the touch current? It's easy with 3-pronged plugs with a dedicated earth pin, but old EU plugs are round two-prong and indiscriminately reversible making grounding tricky. The solution would have to work when I plug it in either direction.

A: To be easily perceptible the current has to be fairly large (at least hundreds of uA). To get, say, 500uA by capacitive coupling with a 240VAC difference would require a capacitance of around 7nF, which is pretty huge. If the plate is like 25cm x 25cm and the insulation is rather thin (like 0.25mm) it's possible. UL considers 0.5mA to be the limit of perception and it's also their limit for allowable leakage in many situations.
The other possibility that that you are using an insulation type that leaks at high temperatures and you are allowing the insulation to get very hot. This is not uncommon with sheathed heating elements.
Your best bet might be to make the insulation a bit thicker, and find a dielectric material that transmits heat well enough that provides some separation. Even 1mm would be a big improvement. Lower dielectric constant is also better.
I'm not addressing issues of safety or standards here, that's more-or-less a separate issue. But you definitely do not want to connect the plate to your 2-pin plug.

A: Given the polarityless nature of those reversible EU plugs, what is required here is double insulation.  The various UL documents will talk about this, but the gist is two indepenent ways of assuring current can't get on the metal plate.

A: No matter how it is coupled, the current you feel is a result is a potential voltage difference between you and the plate. You are coupled thru stray e-fields in the room thru the moist air and it goes thru your body's much lower imepdance without any sensation.  But the impedance of the plate close to the coil increases the capacitance and puts a time-varying (high impedance) voltage on the plate.
This difference permits some xx to xxx uA of touch leakage.
Earth-bonding like metal stoves and ovens could be the prudent fix with a 3 wire cordset.
A photo may allow more detailed suggestions how to connect the ground to the plate.
An afterthought approach ... is a thermal BBQ grill , grounded via the cordset to shunt stray E-fields from reaching the plate, yet allow heat to go thru in terrahertz band ;)


text:
Q: How to capture clicked button in js functions? I have to buttons like this:
<input type='submit' id='submit' class='processAnimation'>
<input type='reset' id='reset' class='processAnimation'>

Now I have two js function. First function is called when ajax request is started and seconf function is called when ajax request is completed.
this.showLoading = function () {
     backupsource = $('.processAnimation').attr('class');
     $('.processAnimation').removeAttr('class').addClass('disabled-btn processAnimation');
     $('.processAnimation').attr( 'backupsource', backupsource );
}

this.hideLoading = function () {
    backupsource = $('.processAnimation').attr('backupsource');
    if( backupsource != undefined ) {
       $('.processAnimation').removeAttr('class').addClass( backupsource );
       $('.processAnimation').removeAttr('backupsource');
    }
}

EDIT: Above two functions are working and moving flower replaced clicked button. When request is complete then button is back. Problem is that when I click one button it replace all buttons(class=procesAnimation) with moving flower.
Thanks

A: Since you haven't posted your click event binding I am going to take a quick guess and say that your selector is not set right or conflicts with another element.  try something like this:
$('input').click(function(){
     switch( $(this).attr('id') ){
        case 'submit' :
            ShowLoading();
            break;
        case 'reset' :
            HideLoading();
            break;
      }
 });

and change the syntax of how you initialize the two functions to the following:
function ShowLoading(){
     //do your show loading procedure here
};

function HideLoading(){
    //do your hide loading procedure here
};

A: This is using the code u have currently
$('.processAnimation').click(function (){
   if($(this).attr('type')=='submit'){
      //submit has been clicked
   }else{
      //reset has been clicked
   }
});

but it looks like you should really be using ID's rather than class's

A: if you have jQuery it is simple
$('#submit').click(showLoading)
$('#reset').click(hideLoading)

Just two different binding of events.
or did I miss something? :)


text:
Q: Updating a model using Entity Framework Core is updating another values When I try to update a model using Entity Framework Core, it is deleting existing values of different columns in a same row. Please help.
I was trying to update a few columns but it's deleting existing columns info also.


text:
Q: How do you fill a List() for a BatchUpdateSpreadsheetRequest to update multiple rows/columns/cells in a google spreadsheet in C# BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
            requestBody.Requests = new List<Request>();
            Request r = new Request();
            requestBody.Requests.Add(r);
            r.UpdateCells = new UpdateCellsRequest();

            var gc = new GridCoordinate();
            gc.ColumnIndex = 0;
            gc.RowIndex = 0;
            gc.SheetId = 0;

            r.UpdateCells.Start = gc;
            r.UpdateCells.Fields = "*";
            r.UpdateCells.Rows = new List<RowData>();

            //TODO:: loop through record set to update cell data (cd) with values to insert
            SqlDataReader reader = default(SqlDataReader);
            reader = o_cSQL.RunSPReturnDataReader("Shippments", 40997, sNow, sNow);
            while (reader.Read())
            {

                var rd = new RowData();
                r.UpdateCells.Rows.Add(rd);
                rd.Values = new List<CellData>();
                var cd = new CellData();
                cd.UserEnteredValue = new ExtendedValue();
                // the next line is only updating the first cell (first row/first column)
                //how to you get multiple CellData created for a single row ?
                cd.UserEnteredValue.StringValue = reader["new_attn"].ToString();
                rd.Values.Add(cd);
            }
            SpreadsheetsResource.BatchUpdateRequest batchRequest = service.Spreadsheets.BatchUpdate(requestBody, spreadsheetId);
            batchRequest.Execute();

Can someone please help with how you get multiple cells updated per row ?
I know I'm only showing one value from my 'reader' from the database, that's where I got stuck in that I don't know how to specifically pinpoint each cell of my spreadsheet. I'm pulling an unknown recordset size from a database and need to enter it on a google spreadsheet.  I know how many columns.

A: Since I know my columns, I just kept making new CellData(); items for each RowData item in my reader.Read() while looping. Worked first time!


text:
Q: ASP.NET Show/Hide Sections in a Datagrid row I have a datagrid where each row has information on Employees in a company.
I would like to allow each row the ability to show/hide extra information. My first idea was use the CollapsiblePanelExtender from the AJAX toolkit and have each row like this:
<ajaxtoolkit:collapsiblepanelextender
     TargetControlID="panel2">
     ExpandControlID="LinkButton1"
     CollapseControlID="LinkButton1">
</ajaxtoolkit:collapsiblepanelextender>

<asp:panel>
    FirstName | LastName | Phone | Email
    <LinkButton1>  <- this hides/show extra info in panel2
</asp:panel>

<asp:panel2>
     <textbox ="FirstName">
     <textbox ="LastName">
     <textbox ="EmailName">
     ...
     ...lots of textboxes where information is assigned from the database.
</asp:panel2>

This works very well but it can be computationally expensive. The extra information panel has a lot of textboxes/labels, all of which gets its values from the database.
Everytime the page loads all the data is got from the database at the start, some of it is hidden.
Is there a better way to achieve my goal? Or is there a way to only load an employees extra details when the Show/Hide button is click?
Thanks in advance!

A: I´ve done something like this but with a ModalPopupExtender.
I had a panel with textboxes and labels, that retrieve information only when the user pushes over an imagebutton.
In this example, the imagebutton was in a GridViewRow, and the key for retrieving data was in the DataKeys properties of the Row.
GridViewRow row = ((GridViewRow)((ImageButton)sender).NamingContainer);
//NamingContainer return the container that the control sits in
DataKey key = ((GridView)row.NamingContainer).DataKeys[row.RowIndex];

//Retrieve data with a server method. It can be with wathever you want, I use an ArrayList
ArrayList AL=Domain.GetCustomerData(key[0].ToString());

//Fill controls with data,
LblDate.Text = AL[0].ToString();
dLectHidro.Value = AL[1].ToString();
idLectHL.Value = AL[2].ToString();
LblEstacion.Text = HttpUtility.HtmlDecode(AL[3].ToString());
TxtLluvia.Text = HttpUtility.HtmlDecode(AL[4].ToString());
TxtLluvia1.Text = HttpUtility.HtmlDecode(AL[5].ToString());

//Show the popup
this.ModalPopupModif.Show();

Hope this helps.
Claudia


text:
Q: Clmtrackr cannot work with, responsive html5 camera video I use clmtrackr to track my face, but when I set the width of video tag equal to 100%, it cannot track the face. And I try to set the width of canvas tag as same as the width of video tag, but it still cannot work.

        <video id="inputVideo" width="100%" height="auto" autoplay></video>
        <canvas id="canvas" width="100%" height="auto" style="position:absolute; top:0; left:0;"></canvas>

Why it cannot work track the face unless set the video's width equal to 640, and video's  height equal to 480?
How to fix it with responsive width='100%' and height='auto'?

A: Your webcam resolution should be 640x480 and you're trying to take a frame with higher resolution (width='100%'). I had the same problem and fixed it by reducing the width-height attributes of the video element.


text:
Q: Error Of JQuery in Internet explorer 8 I am running on of my project on Internet Explorer 8 i.e. IE8 and i am getting the following errors. this project is successfully run on the Chrome and Mozilla as well as IE11 also but i want to use IE8. is there any way to solve the Errors..

A: What is used JQuery Version?
jQuery 2.x does not support Internet Explorer 6, 7, or 8.
Check the version of JQuery please.

Version Checking!
Check your html(index.html) file
<script type="text/javascript" charset="utf-8"
        src="/lib/jquery/js/jquery-1.11.1.min.js"></script>

File name have version name like "jquery-1.11.1.min.js"
In this case, version is 1.X, then this version support IE 8.
If your script link(src) don't have version like "jqeury.js",
Open the file.
You can find the comment of version like below code.
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */

A: jQuery 2.0 dropped support for some browsers. See the post at
http://blog.jquery.com/2013/04/18/jquery-2-0-released/
No more support for IE 6/7/8: Remember that this can also affect IE9 and even IE10 if they are used in their "Compatibility View" modes that emulate older versions. To prevent these newer IE versions from slipping back into prehistoric modes, we suggest you always use an X-UA-Compatible tag or HTTP header. If you can use the HTTP header it is slightly better for performance because it avoids a potential browser parser restart.
Keep jQuery 1.9 if IE 6/7/8 are a concern.


text:
Q: How to make a textfield for searching data from Database? I am trying to develop a Java application that runs on Windows.  For part of the application, I want to allow the user to enter a date into a text field in a form.  My application will use that date to query a MSAccess database to retrieve information which will be placed in other elements of the form.
How should I retrieve the information from the database using a document listener?
[I have tried searching for advice, but have not found what I need.]

A: I wrote a decorator for a text field that display matching results as the user types. I think that is what you want if I am not mistaken. Here is the link https://github.com/Skylion007/java-manga-reader/blob/master/src/org/skylion/mangareader/util/AutoSuggestor.java


text:
Q: Getting Top N items per group in pySpark I am using Spark 1.6.2, I have the following data structure:
sample = sqlContext.createDataFrame([
                    (1,['potato','orange','orange']),
                    (1,['potato','orange','yogurt']),
                    (2,['vodka','beer','vodka']),
                    (2,['vodka','beer','juice', 'vinegar'])

    ],['cat','terms'])

I would like to extract top N most frequent terms per cat. I have developed the following solution which seems to work, however I wanted to see if there is a better way to do this.
from collections import Counter
def get_top(it, terms=200):
    c = Counter(it.__iter__())
    return [x[0][1] for x in c.most_common(terms)]

( sample.select('cat',sf.explode('terms')).rdd.map(lambda x: (x.cat, x.col))
 .groupBy(lambda x: x[0])
 .map(lambda x: (x[0], get_top(x[1], 2)))
 .collect()
)

It provides the following output:
[(1, ['orange', 'potato']), (2, ['vodka', 'beer'])]

Which is in line with what I am looking for, but I really don't like the fact that I am resorting to using Counter. How can I do it with spark alone?
Thanks

A: If this is working it is probably better to post this to Code Review.
Just as an exercise I did this without the Counter but largely you are just replicating the same functionality.

*

*Count each occurrence of (cat, term)

*Group by cat

*Sort the values based on Count and slice to number of terms (2)

Code:
from operator import add

(sample.select('cat', sf.explode('terms'))
 .rdd
 .map(lambda x: (x, 1))
 .reduceByKey(add)
 .groupBy(lambda x: x[0][0])
 .mapValues(lambda x: [r[1] for r, _ in sorted(x, key=lambda a: -a[1])[:2]])
 .collect())

Output:
[(1, ['orange', 'potato']), (2, ['vodka', 'beer'])]


text:
Q: Error in importing data from salesforce in exacttarget In my exacttarget when I'm importing data from salesforce report I'm getting "Casesensitive Salesforce Id" error.
I'm importing data from salesforce Campaign reports which contains Lead/Contact Id column.
Thanks

A: I faced the same issue recently where I got the error CaseSensitiveSalesforceID when I tried to import into Exacttarget a Salesforce report built on a custom report type that included the contact id field from a lookup.
The issue was that Exacttarget/Marketing Cloud doesn't just expect a contact id or lead id as the key it also expects the column name to be exactly Contact ID or Lead ID.
The default value in my custom report type was Primary Contact : Contact ID. I changed this to Contact ID and it worked fine.

A: I recently came across an article I think relates to your error for the case sensitive salesforce ID.
Do you have ContactID or LeadID set as primarykey on the import? Then I think this article will give you some tips:
http://help.salesforce.com/HTViewSolution?id=000213103&language=en_US

A: Use 18 characters Salesforce Id (eg. leadId or contactId) to update in Marketing Cloud


text:
Q: In jqgrid, Is it possible to use select formatter without setting editoptions? Since one of my jqgrid column is not editable,so I do not set required value info i.e.{value:"1:John;2:Smith"} to editoptions, instead, I set formatter:select and value info to formatoptions. When I look at the js sourcecode of select formatter it tightly coupled with editoptions especially for getting "multiple" property of it. Is it possible to achieve this without writing custom formatter?
formatter:select
formatoptions:{value:"1:John;2:Smith"}

data being sent to this column is "1" or "2", and I expect from jqGrid to display John or Smith.
thanks,
Alper.

A: You are right, that the code of the select formatter could be improved to use opts.colModel.formatoptions.multiple in the line in the same way as it will be used opts.colModel.editoptions.multiple in the line of code.
Nevertheless I don't think that it's a real problem. If you has no editable property in the column or if you has editable: false the column stay non-editable even if you use editoptions.
So I agree you that the usage of formatoptions.multiple would be better, but I think that it's "nice to have" problem only.


text:
Q: MVC Interceptor get content type of Exception handler method If I have a method such as the following in a Controller:
@RequestMapping(value = "/mymapping",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public final JsonResponse<?> myMethod() {

When the method throws an exception, I want a MVC interceptor to catch it and return a JSON error.  I only want this to work for produces = MediaType.APPLICATION_JSON_VALUE methods in the controller.
How can I do this in my afterCompletion of HandlerInterceptor.  If I inspect the contentType of the response it is null when an exception occurs.
@Override
public void afterCompletion(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
    //TODO
}


text:
Q: Sinatra, sending an empty page This is the tail end of my code within a route block. What's happening is that the success_loader never renders and instead Sinatra sends a null response (page is blank)
if v.test
  mydata = v.sheetData
end
if v.errors.size == 0
  #success
  haml :success_loader, :layout => :base,
       :locals => {:pub_path => settings.root, :app_ver => settings.version }
else
  #fail
  haml :failure_loader, :layout => :base,
       :locals => {:pub_path => settings.root, :app_ver => settings.version,
       :app_error => v.errors }
end
File.delete(target) if File.exists?(target)

Using debugger I show each line starting at the point where the call to haml begins
haml :success_loader, :layout => :base,
     :locals => {:pub_path => settings.root, :app_ver => settings.version }
getter = proc { value }

value = :pub_path

getter = proc { value }

value = :apper_ver

File.delete(target) if File.exists?(target)
@params = @original_params
filter! :after unless env['sinatra.static_file']
res = [res] if Fixnum === res or String === res
if Array === res and Fixnum === res.first
status(res.shift)
body(res.pop)
headers(*res)
invoke { error_block!(response.status) }
unless @response['Content-Type'

bunch more similar lines. Then several lines from Thin beginning with this:
log "!! Rack application returned nil body. Probably you wanted it to be an empty string?" if @response.body.nil?

I tested the code outside the route so it's not throwing any exception. The haml templates work fine when used in other routes. Any ideas what's going on?

A: The body will be the last thing evaluated in the route block. The last thing is:
File.delete(target) if File.exists?(target)

The docs for File.delete tell us:

Deletes the named files, returning the number of names passed as arguments.

So I'm guessing that target didn't exist or was nil, something that would make that statement evaluate to nil.
If you want to set the body earlier than the end, use the body helper:
body = if v.errors.size == 0
  #success
  haml :success_loader, :layout => :base,
       :locals => {:pub_path => settings.root, :app_ver => settings.version }
else
  #fail
  haml :failure_loader, :layout => :base,
       :locals => {:pub_path => settings.root, :app_ver => settings.version,
       :app_error => v.errors }
end
File.delete(target) if File.exists?(target)

but this can be refactored a bit to:
template = v.errors.size == 0 ? :success_loader : :failure_loader
File.delete(target) if File.exists?(target)
haml template, :layout => :base,
               :locals => {
                 :pub_path => settings.root,
                 :app_ver => settings.version,
                 :app_error => v.errors
               }.delete_if{|k,v| v.nil?}


text:
Q: External Storage for 2TB of backups and 4TB of data RAID level? HW vs Software? I have a Mac Mini set up as a media center/file server. Currently I just have a hodgepodge mess of external drives for storage. I'm maxed out, and I have some new laptops on the way with much larger drives and I need to work out a good storage solution for backing them up, as well as storing media on the server. I need around 2 TB of storage for the time machine backups from my various systems and around 2 TB more for media. I would like to build this to handle around 6 TB total so I have some growing room. Since I'm using a Mac Mini as the server I need to use external enclosure(s) that support USB 2 or Firewire 800 (preferred) or gigabit Ethernet. Performance of the system isn't a huge concern since the majority of the access from other computers is done over 802.11N. I plan on using 2TB drives, for the final version, but initially I'll try and use my existing 2 (1TB) drives + some new 2TB drives, and swap the 1TB ones out as I fill up.
As to the actual questions:

*

*Should I use hardware RAID in some enclosure? Because if the enclosure dies I have to find an identical one to get to my data right? Wouldn't a software RAID be better as I can use any method of connecting the drives to the system? Remember OS X server is my OS. What if I had to reinstall OS X, can I restore the software RAID easily?

*What RAID version should I use? For the 2TB used for the time machine disk I don't see why I need RAID here, just a single 2TB drive since its already the backup, but for the remaining 4TB it would be the only copy of the data so I should build some redundancy.

*I had a RAID 5 setup using a cheep RAID PCI card years ago running RAID 5 in a 2 TB array and when a drive died it wanted 48 hours to rebuild. Is this crazy slow for a setup of this size or is this to be expected?

*Any suggestions as to drive enclosures?

A: Not exacly cheap, but does exactly what you want:
USB2 & Firewire Device: The Drobo
Network Attached (SMB): The Drobo FS
They hold 5 drives, if you put 5 1TB drives in there, RAID5, that about 4TB of storage. Rebuilds take a long time, but are faster than 48+ hours (faster drives = faster rebuilds too). Data Robotics has been around for a few years, so I wouldn't be too concerned with hardware support disappearing.


text:
Q: JQuery animation is working differently in IE/Opera, Chrome, Firefox i have animation of image which is not working correctly in latest chrome and firefox and it's working fine in IE8 and latest Opera
http://jsfiddle.net/wzHx3/7/ and the full screen example http://dev.fama.net.pl/tides/ - click on the right triangle to trigger animation and than click on the left one to trigger second animation
UPDATE - second animation in Chrome is now fixed thx to afshin
UPDATE 2 - all Chrom issues are fixed thx to afshin
ISSUE - Firefox: first animation is shorter than animation in other browsers and second one is preceded by big jump to the right
Chrome, IE8 and Opera works perfect
JQUERY
$(window).load(function(){

    var speed = 500;
    var times = 2;
    var loop = setInterval(anim, 500);
    function anim(){
        times--;
        if(times === 0){clearInterval(loop);}
        $('#arrow-right').animate({right:-1,opacity:.2},speed).animate({right:-15, opacity:.5},speed);
    }
    anim();

    $('#bg img.pic').css('opacity','0');
});
$(document).ready(function(){

    var easing = 'easeInOutCubic';

$('#arrow-right').click(function(){
    $('#bg img.pic').animate({left:'0%', opacity: 1}, 2500, function() {
        $('#arrow-left').animate({left:0}, 800, easing);
    });
    $(this).animate({right:-125}, 800, easing);

});

$('#arrow-left').click(function(){
    $('#bg img.pic').animate({left: '20%', opacity: 0}, 2500, easing, function() {
        $('#arrow-right').animate({right:-15}, 800, easing);
        //$(this).css('left','75%');
    });
    $(this).animate({left:-125}, 800, easing);
});
});

CSS
* { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }

body,html {
    overflow: hidden
}
#bg {
    position:fixed;
    top:-50%;
    left:-50%;
    width:200%;
    height:200%;
}
#bg img {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    min-width:50%;
    min-height:50%;
}
#bg img.blank {
    z-index: 0;
}
#bg img.pic {
    z-index: 1;
    left: 20%;
    opacity: 0;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
}
.arrow {
    position: absolute;
    top: 50%;
    margin-top: -120px;
    width: 0;
    height: 0;
    opacity:.5;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    cursor: pointer;
    border-top: 120px solid transparent;
    border-bottom: 120px solid transparent;
}
.arrow:hover {
    opacity:.2 !important;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)" !important;
}
#arrow-left {
    border-left: 120px solid #83bedd;
    left: -125px;
    z-index: 2;
}
#arrow-right {
    border-right: 120px solid #83bedd;
    right: -15px;
    z-index: 2;
}

HTML

A: check this out maybe help
$('#arrow-right').click(function(){
    $('#bg img.pic').animate({left:'0%', opacity: 1}, 2500, function() {
        $('#arrow-left').animate({left:0}, 800, easing);
    });
    $(this).animate({right:-125}, 800, easing);

});

$('#arrow-left').click(function(){
    $('#bg img.pic').animate({left: 20+'%', opacity: 0}, 2500, easing, function() {
        $('#arrow-right').animate({right:-15}, 800, easing);
        //$(this).css('left','75%');
    });
    $(this).animate({left:-125}, 800, easing);
});

jsFiddle


text:
Q: Observe reference removal I have a very simple question.
I have a reference like this : /myref for which I set a value for example : "Hello"
And I want to listen when the myref reference is removed.
I tried observeSingleEvent Child Removed but it is not triggered as there is no child.
And I don't want to listen the parent reference until the child removed is myref.
Do you have any solution ?
Thanking you in advance.

A: You don't want to observe child events, just watch the path itself and look for NSNull (which means the path no longer exists):
Firebase *postsRef = [[Firebase alloc] initWithUrl: @"https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts"];

FEventTypeChildAdded event
// triggered before this point.
[postsRef observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
  if (snapshot.value == [NSNull null])
     NSLog(@"value was removed");
}];


text:
Q: Mapping one value to another in a list In a Python list, how can I map all instances of one value to another value?
For example, suppose I have this list:
x = [1, 3, 3, 2, 3, 1, 2]

Now, perhaps I want to change all 1's to 'a', all 2's to 'b', and all 3's to 'c', to create another list:
y = ['a', 'c', 'c', 'b', 'c', 'a', 'b']

How can I do this mapping elegantly?

A: You should use a dictionary and a list comprehension:
>>> x = [1, 3, 3, 2, 3, 1, 2]
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> [d[i] for i in x]
['a', 'c', 'c', 'b', 'c', 'a', 'b']
>>>
>>> x = [True, False, True, True, False]
>>> d = {True: 'a', False: 'b'}
>>> [d[i] for i in x]
['a', 'b', 'a', 'a', 'b']
>>>

The dictionary serves as a translation table of what gets converted into what.

A: An alternative solution is to use the built-in function map which applies a function to a list:
>>> x = [1, 3, 3, 2, 3, 1, 2]
>>> subs = {1: 'a', 2: 'b', 3: 'c'}
>>> list(map(subs.get, x)) # list() not needed in Python 2
['a', 'c', 'c', 'b', 'c', 'a', 'b']

Here the dict.get method was applied to the list x and each number was exchanged for its corresponding letter in subs.

A: In [255]: x = [1, 3, 3, 2, 3, 1, 2]

In [256]: y = ['a', 'c', 'c', 'b', 'c', 'a', 'b']

In [257]: [dict(zip(x,y))[i] for i in x]
Out[257]: ['a', 'c', 'c', 'b', 'c', 'a', 'b']


text:
Q: Force caching data on Client Side I am writing a script that will load custom javascript and images based on details entered by user (using php on server). Is there a way to force these JS and images to be cached on browser on client side to reduce load on server when similar data is requested next time?

A: yes there is a way you can set expire headers to a longer period. i.e. if you are using .htaccess write this in your .htaccess file
<IfModule mod_expires.c>
AddType image/x-icon .ico

ExpiresActive On

ExpiresByType image/* A86400
ExpiresByType image/x-icon A2592000

ExpiresByType application/javascript A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType text/javascript A2592000
ExpiresByType text/css A2592000

SetEnvIfNoCase Request_URI ".*/(uploads|weather)/.*\.(jpeg|jpg|png|gif)$" is_monthly=true
Header set cache-control: max-age=604800 env=is_monthly

A: You'll need to look at your servers caching defaults, and see how they can be controlled, if its apache there is mod_cache and mod_expire which you can use via .htaccess:
http://httpd.apache.org/docs/2.2/mod/mod_cache.html
http://httpd.apache.org/docs/2.0/mod/mod_expires.html
Or.. you could serve the files up as PHP and use headers for cache-control.  But that would be crazy...


text:
Q: Whitespace through empty figure environment I am trying to alter my documents bottom margin for a single page. I have looked at all sorts of posts concerned with the geometry package and so on and have not found a solution for my needs. (See Raise page number on first page of chapter with fancyhdr)
If I simply add a
\documentclass{report}

\begin{document}

\chapter{first}
\begin{figure}[b!]
\end{figure}

\end{document}

at the beginning of that page (right after \chapter{}), if manage to achieve what I want.
Is there a way to control the height of that figure without using \includegraphics[]{}? Or another environment that lets me place whitespace at the bottom of a page with controllable height? Specifically, make it smaller than with the above code?

A: Use \vspace within the figure.
% marginprob.tex  SE 569697
\documentclass{book}
\usepackage{lipsum}
\begin{document}
\chapter{First}
\begin{figure}[b!]
\vspace{1in} % adjust this to suit, negative to reduce the whitespace
\end{figure}

\lipsum[1-5]

\lipsum[1-5]

\end{document}


text:
Q: Entity Framework Fluent migration default value I'm trying to generate automatically a default value for metadata columns
in my code first database. It seems like code first migration fluent api does not handle
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)
Every table in my DB has a "CREATION_DATE" column using default value "getdate()". In my EntityTypeConfiguration i try to use:
Property(p => p.CREATION_DATE).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

This is generated for the migration:
CREATION_DATE = c.DateTime(nullable: false)

I can manually add defaultValueSql: "getdate()", but I don't want to do this every migration. I did write a SqlServerMigrationSqlGenerator for this, but it just does not seem to generate the default value.
    internal sealed class Configuration : DbMigrationsConfiguration<TheModel>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        SetSqlGenerator(SqlProviderServices.ProviderInvariantName, new CustomMigrationSqlGenerator());
    }

and in the CustomMigrationSqlGenerator class
        protected override void Generate(CreateTableOperation createTableOperation)
    {
        SetDefaultDate(createTableOperation.Columns);
        base.Generate(createTableOperation);
    }

The default value is not generated with or without the CustomMigrationSqlGenerator.
Am I missing something? I read on forums that it was an issue at some point, but the posts date back from 2010-2012.
*Edit
Content of SetDefaultDate
    private static void SetDefaultDate(IEnumerable<ColumnModel> columns)
    {
        foreach (var item in columns)
        {
            SetDefaultDate(item);
        }
    }
    private static void SetDefaultDate(ColumnModel column)
    {
        if (column.Type.Equals(System.Data.Entity.Core.Metadata.Edm.PrimitiveTypeKind.DateTime))
        {
            column.DefaultValueSql = "getdate()";
        }
    }


text:
Q: HTML письма Каким образом можно с gmail оправлять письма написанные на html. Пробовал просто вставлять в письмо html и пересылать, приход голый html код.
A: С самого сайта gmail никак. Используй почтовый клиент (The Bat, mozilla thunderbird, или на крайний случай microsoft outlook)


text:
Q: Why does Java exit with success after an uncaught exception? Any time a Perl, Python, C++ or Tcl program halts with an unhandled exception, those language runtimes take care to register a non-zero exit code for the process. Even Eclipse-based programs return 1 if they fail during startup. Programs run by the standard java.exe, however, happily return zero no matter how abruptly they end, unless the program calls System.exit() with an exit value. Even AssertionFailedError or UnsatisfiedLinkError are reported back to the calling program as successful exits.
Of course not all systems have program return codes, but Unix and Windows were important enough to warrant java.lang.Process.exitValue() for child processes; don't they also warrant honouring conventions for parent processes?
Is this a flaw in the language design or just in the implementation? Is there an argument that it's a good idea?

A: If the Java Language Specification does not explicitly define what exit value to expect, then it is undefined and you should not rely on it.
You need to catch Throwable in your main method, and call System.exit(1) yourself.