Comparing an Arraylist to a String

Question: I am trying to compare a string which the user enters in case 3 in the ProcessRecords class. I am then trying to compare that string to each last name in the Arraylist and if a record matches the user's input then i want to print it. I am not sure how to accomplish this but I would appreciate any guidance.
import java.util.*;
import java.io.*;

public class ProcessRecords {

public static void AskUser()
throws Exception {
    Scanner preference = new Scanner(System.in);
    //Creating a new scanner will allow us to gather user input

    boolean flag=true;
    //I will use this for my while loop
    while (flag) {
        System.out.println("What type of Search would you like to run?\n 1)Search for all students\n 2) Search for students graduating in a specific year\n 3)Search for students whose last name begins with a certain string\n(4) Exit\n");
        int searchType=preference.nextInt();

        //This variable will store what type of query the user would like to run

        switch(searchType) {
            case 1:
            System.out.println("Gathering Records for all students\n");
            //Query.getAll();
            break;
            //Call Query Method in the Query Class to return all students in the colletion
            case 2: System.out.println("What graduation year would you like to search for? \n");
            int yearsearch=preference.nextInt();

            Query.getYears(yearsearch);
            break;
            //Call Query Method to return students who are graduating in the specified year
            //Pass the "yearsearch" variable to the Query class
            case 3:
            System.out.println("What string would you like to search for? \n");
            String lstsearch=preference.next();
            Query.getLast(lstsearch);
            break;

            case 4:
            System.out.println("You have chosen to exit the program. Thank you!");
            flag=false;
            break;

            default:
            System.out.println("Please pick a number between 1 and 4") ;
            break;
            //Call Query Method in the Query Class to return students who have the string in their last name
            //Also I need to pass the "lstsearch" variable to the Query class to search through last names

        }
    }
  }
public List<StudentRecord> studentRecords;
public static void main(String[] args)
throws Exception
{
    Scanner input = new Scanner(new File("students.txt"));
    //This will import the file
    input.nextLine();
    //This will skip the headers in the file
    System.out.println("Processing file now...");
    //Let the user know that the file is being processed

    int id;
    String last;
    String first;
    int year;
    int i=1;
    // Declare variables that we will extract from the file

    //Now we will being processing the file with a while loop

    List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
    while(input.hasNext())
    {
        id=input.nextInt();
        last=input.next();
        first=input.next();
        year=input.nextInt();
        StudentRecord record = new StudentRecord(id, last, first, year);
        studentRecords.add(record);
        System.out.println(id + "  " + last + "  " + first + "  " + year + "\n");

    }
    System.out.println(" You have successfully read and printed from the file!");
    for (StudentRecord s : studentRecords)
        System.out.println(s.toString());

    Query query = new Query(studentRecords);
 }
}

+++++++++++++++++++++++++++++++++++
Next Class
 import java.util.*;
 public class StudentRecord
 {
private int id;
private String last;
private String first;
private int year;

public StudentRecord(int id, String last, String first, int year)
{
    this.id=id;
    this.last=last;
    this.first=first;
    this.year=year;
}

public String toString()
{
    return id + "  " + last + "  " + first + "  " + year;
}

public int getYear()
{

    return year;
}

public String getLast()
{
    return last;
  }

   }

+++++++++++++++++++++++++++++++++++
Next Class
import java.util.*;
import java.io.*;

public class Query
{
static List<StudentRecord> records;
public List<StudentRecord> studentRecords;

public Query(List<StudentRecord> records) {
    this.records = records;
}

public static void getYears(int yearSearch) {
    //I am trying to create a method to get students who are graduating in a specific year.
    // I want to call this method in the ProcessRecord SwitchCase Case #2
    int count = 0;

    System.out.println("ID" +"  " +"Last" + "  " + "First" + "  " + "Year \n");
    for(StudentRecord record : records) {
        if(record.getYear() == yearSearch) {
            System.out.println((record.toString()));
            count++;
        }
        System.out.printf("\n");
    }

}

public static void getLast(String lstsearch){

    int count =0;
    System.out.println("ID" +"    " +"Last" + "    " + "First" + "    " + "Year \n");
    int sizes= lstsearch.length();
    System.out.println(lstsearch);

    for(StudentRecord record : records) {
        System.out.println(count);
        if(record.getLast() == lstsearch) {
            System.out.println((record.toString()));
            count++;
        }
    }
}
public void getAll(){
 for (StudentRecord s : studentRecords)
        System.out.println(s.toString());
 }

}

Once again, I am looking for help searching through the arraylist and if the last name in the array list starts with the string,i.e."g", then I want to print it. Thank you for all of your help!
Comment: Please simplify the code to the specific problem you need to solve. It is pretty easy to loop over an ArrayList but I am not sure if that is what you are looking for.
Answer: public static StudentRecord searchRecords(Collection<StudentRecord> records, String lastName)
{
    for (StudentRecord record : records)
    {
        if (lastName.equalsIgnoreCase(record.getLast()))
            return record;
    }
    return null;
}

This will search through your array for the appropriate record. If it exists it returns that record -- otherwise it returns null. If you have such questions in the future you can always consult the appropriate javadoc for some methods you can use to compare objects.

Comparing an Arraylist to a String


Remove commas within numbers only

Question: I have a list of product sales (and their cost) which have frustratingly been concatenated into a single string, separated by commas. I ultimately need to separate out each product into unique rows which is easy enough with stringr::str_split.
However, the cost associated with each product has comma to show thousands e.g. 1,000.00 or 38,647.89. Therefore str_split is splitting products incorrectly as it hits commas within a product's cost.
I was wondering what the best tidyverse solution would be to remove all commas which are surrounded by numbers so that 1,000.00 becomes 1000.00 and 38,647.89 becomes 38647.89. Once these commas are removed I can str_split on the commas which delimit the products and thus split each unique product into its own row.
Here is a dummy dataset:
df<-data.frame(id = c(1, 2), product = c("1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78", "1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78"))

df

  id                                                              product
1 1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78
2 1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78

Expected outcome:
  id                                                              product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78

Comment: Good point and I should imagine this would work most of the time, to be honest with you. However, I cannot guarantee that a space will *always* follow a comma so I'm thinking that the safest bet would be to remove all commas within numbers first.
Answer: df %>%
  mutate(product = product %>% str_replace_all("([0-9]),([0-9])", "\\1\\2"))

Result
  id                                                           product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78

Comment: Accepting this answer as it's within  `tidyverse`.
Comment: Looks looks ideal, thank you. One question: what does `"\\1\\2"` do in your code?
Comment: They are references to the matched numbers within the parentheses, which are returned again as the replacement (without the comma between them).
Answer: > apply(df,1,function(x){gsub(",([0-9])","\\1",x[2])})

[1] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"
[2] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"

Answer: A way via base R can be,
sapply(strsplit(as.character(df$product), ' '), function(i)paste(sub(',', '', i), collapse = ' '))
#[1] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78" "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"

Comment: Sorry. Minor typo. I meant to use `sub` not the global one.Check it now
Comment: Thanks for the response but your code removes all commas, not just those within numbers. My downstream code using `stringr::str_split` will therefore not work as I can't split on the commas between products.
Answer: library(tidyverse)
df$product <- str_replace_all(df$product, "(?<=\\d),(?=\\d)", "")
df
  id                                                           product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78

Remove commas within numbers only


How do I convert ASCII code to ASCII glyph in python 3

Question: I'm trying to convert a list of strings like u0032 u0033 to their glyph equivalent in python. I know there has to be a built in function for this but I can't find it.
input = 0032 or u0032 or \u0032
print(function(input))
output: 2
Comment: In the title you should replace ASCII with Unicode. What you are asking is not limited to ASCII
Comment: Note: "Glyph" is a strange word for this case. Glyph imply an image, so it is something that font do (and you can extract an image of every glyphs [but some, e.g. control codes in ASCII]). Technically you are still sending 0x32. Just hidden on video card chip (or in graphical terminal program) there is the translation of code to glyph. And if you connect to a Braille console, you still do not have the normal glyph of two (but still a two).
Answer: There are a few ways to achieve this. This is the simplest:
def u_chr(s):
    if s[:2] == '\\u':
        s = s[2:]
    elif s[0] == 'u':
        s = s[1:]
    return chr(int(s, 16))

print(u_chr("u0032"))  # 2
print(u_chr("u00C4"))  # Ä
print(u_chr("u5678"))  # 噸

This uses the ast library:
import ast

def u_chr(s):
    if s[:2] == '\\u':
        t = f'"{s}"'
    elif s[0] == 'u':
        t = f'"\\{s}"'
    else:
        t = f'"\\u{s}"'
    return ast.literal_eval(t)

This uses codecs:
def u_chr(s):
    if s[0] == 'u':
        s = '\\' + s
    elif s[:2] != '\\u':
        s = '\\u' + s
    return s.encode('latin_1').decode('unicode_escape')

In these examples I have left out parameter checking and error handling. If, e.g., you want None to be returned when an exception would be raised, just replace
    return ...

with
    try:
        return ...
    except ValueError:
        return None


Create MS COCO style dataset

Question: How to create a MS COCO style dataset to use with TensorFlow? Does anyone have an experience with this? I have images, and annotations, as well as ground truth masks. I need to convert them to be compatible with MS COCO and any help is appreciated. I can't find any open source tool to create COCO style JSON annotations.
TensorFlow MS COCO reads JSON files which I'm not very experienced with.
Comment: did you find any answer for this ?
Comment: and i wanted to ask you that how did you annnotated images and prepared ground truth mask ?
Answer: I'm working on a python library which has many useful classes and functions for doing this. It's called Image Semantics.
Here is an example of adding masks and exporting them in COCO format:
from imantics import Mask, Image, Category

image = Image.from_path('path/to/image.png')
mask = Mask(mask_array)
image.add(mask, category=Category("Category Name"))

# dict of coco
coco_json = image.export(style='coco')
# Saves to file
image.save('coco/annotation.json', style='coco')

Answer: You can try to use pycococreator, which includes a set of tools to convert binary masks to the polygon and RLE formats that COCO uses.
https://github.com/waspinator/pycococreator/
Here is an example of how you could use it to create annotation information from a binary mask:
annotation_info = pycococreatortools.create_annotation_info(
                    segmentation_id, image_id, category_info, binary_mask,
                    image.size, tolerance=2)

You can read more details about how to use pycococreator here:
https://patrickwasp.com/create-your-own-coco-style-dataset/
Answer: In order to convert a mask array of 0's and 1's into a polygon similar to the COCO-style dataset, use skimage.measure.find_contours, thanks to code by waleedka.
import numpy
from skimage.measure import find_contours

mask = numpy.zeros(width, height) # Mask
mask_polygons = [] # Mask Polygons

# Pad to ensure proper polygons for masks that touch image edges.
padded_mask = np.zeros(
(mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = mask
contours = find_contours(padded_mask, 0.5)
for verts in contours:
    # Subtract the padding and flip (y, x) to (x, y)
    verts = np.fliplr(verts) - 1
    pat = PatchCollection([Polygon(verts, closed=True)], facecolor='green', linewidths=0, alpha=0.6)
    mask_polygons.append(pat)

To generate the JSON file for a COCO-style dataset, you should look into the Python's JSON API. Beyond that, it's just simply about matching the format used by the COCO dataset's JSON file.
You should take a look at my COCO style dataset generator GUI repo. I built a very simple tool to create COCO-style datasets.
The specific file you're interested in is create_json_file.py, which takes matplotlib polygon coordinates in the form (x1, y1, x2, y2 ...) for every polygon annotation and converts it into the JSON annotation file quite similar to the default format of COCO.
Comment: do you have any suggestions on how to generate uncompressed RLE encoded masks for `iscrowd: 1` annotations?
Comment: As far as I understood, `iscrowd=1` annotations are just collections of polygons representing a cluster of similar objects. I haven't looked into it myself but if they are just collections of polygons, extending to multiple polygons would be to add multiple polygon support for a single object cluster.
Answer: CREATING COCO STYLE DATASETS AND USING ITS API TO EVALUATE METRICS
Let's assume that we want to create annotations and results files for an object detection task (So, we are interested in just bounding boxes). Here is a simple and light-weight example which shows how one can create annoatation and result files appropriately formatted for using COCO API metrics.
Annotation file: ann.json
{"images":[{"id": 73}],"annotations":[{"image_id":73,"category_id":1,"bbox":[10,10,50,100],"id":1,"iscrowd": 0,"area": 10}],"categories": [{"id": 1, "name": "person"}, {"id": 2, "name": "bicycle"}, {"id": 3, "name": "car"}]}

Result file: res.json
[{"image_id":73,"category_id":1,"bbox":[10,10,50,100],"score":0.9}]

Now, you can simply use the following script to evaluate the COCO metrics:
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

annFile = './ann.json'
resFile='./res.json'

cocoGt=COCO(annFile)

cocoDt=cocoGt.loadRes(resFile)

annType = 'bbox'
cocoEval = COCOeval(cocoGt,cocoDt,annType)
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()

Create MS COCO style dataset


How to concatenate React objects without JSX

Question: How can I concatenate two React objects(React.createElement()) without JSX ?
Goal
My goal is to render message, the message should contain the user full name in bold.
Problem
The problem is that when I concatenate the react objects I am getting the message content and instead of the full name there is [object Object] in the string.
Code
var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = "Hello " + firstName + " " +  lastName
message += " You can edit your profile in the Users Table"
return React.createElement("p", {}, message)

Comment: have u tried to access the text by using props? I guess it's the only way
Comment: Does this answer your question? [how to render multiple children without JSX](https://stackoverflow.com/questions/27290013/how-to-render-multiple-children-without-jsx)
Comment: How can I do this with props ?
Answer: You should concatenate them using array as follows:
var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = ["Hello ", firstName, " ", lastName]
message.push(" You can edit your profile in the Users Table")
return React.createElement("p", {}, message)

Answer: React.createElement returns you an Object of the component instance, you cannot directly concat it with a string. you instead can pass them to createElement as an array of children elements
 var firstName = React.createElement("b", {},  this.state.User["FirstName"])
 var lastName = React.createElement("b", {}, this.state.User["LastName"])
 const message = ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]
 return React.createElement("p", {}, message);

Working demo

class App extends React.Component {
   render() {
      var firstName = React.createElement("b", {},  "Stack")
      var lastName = React.createElement("b", {}, "Overflow")
      return React.createElement("p", {}, ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]);
   }
}

ReactDOM.render(<App/>, document.getElementById('app'));


Installing Ubuntu on RAID 1, but not using all disks capacity? And what is HotSpare?

Question: I'm totally new to all this hard disks matter and even newer to topic with RAID.
I hope somebody can help me!
I have installed Ubuntu 14.04 LTS (BioLinux) on Dell Precision T7500, with Dell PERC 6/i Adapter RAID controller, but only 1.8TB usable.
I have 8 disks, totaling up to 12TB, how do I activate and use them all?
I created new Virtual disk and followed through the short guide from the below 2 links to install my BioLinux with USB stick.
http://www.orangecomputers.com/node/?command=kb&docid=25
https://www.youtube.com/watch?v=llvGKVYSQ4A
After successfully booting, gparted only showing 1.8TB size available and there is only 1MB of unallocated space.
How do I activate back the other disks and get the Ubuntu (BioLinux) run on total 12TB space (or at least 6TB)? Is it possible?
Something to tweak in the Configuration Utility? Use other levels of RAID?
And what is "HotSpare"??
Greatly appreciate any help from anyone :)
Answer: When you use RAID 1, the disks are all duplicates of each other.  If you have the 12 disks, the data will be duplicated 12 times up to the capacity of the smallest disk.
What you want is either RAID 0, 5, 6, or 10.
In RAID 0, all the disks are used to store data with no redundancy.  The total space would be the smallest disk size * 8.
In RAID 5, data is stored with parity bits.  This allows a single disk to fail and data still be readable.  The size of the virtual disk would be the size of the smallest disk * 7.
In RAID 6, it is basicly the same as RAID 5 except data is stored with 2 differenty parity bits.  This means that 2 disks can fail and data is still recoverable.  The size of the virtual disk would be the size of the smallest disk * 6.
In RAID 10, is groups of disks in RAID 1 combined in RAID 0.  This allows for the possibility of multiple disks to fail as long as they are not in the same RAID 1 group.  The size of your RAID 1 groups will determine the final size of the array.
Note not all RAID Controllers support RAID 5 & 10, but according to dell  your controller does support RAID (0,1,5,6,10)
(http://www.dell.com/learn/us/en/04/campaigns/dell-raid-controllers)
Hot Spares are used as spare disks in the RAID Array.  When a disk fails, (assuming it is a recoverable error) the array will recreate the data that was on the failed disk on the hot spare.
Overall I would recommend NOT using RAID 0 unless the information you are storing in VERY UNIMPORTANT.  If ANY of the 8 disks would fail, it would mean the loss of all of your data.
RAID 1 as you have found out crates many duplicates increasing read speed, but there is really no reason to put 8 disks in RAID 1.
I would recommend either doing RAID 5, 6, or 10 depending on the disk space your require and the data integrity needed.
Comment: Thank you so much Eric for the elaboration and check up on RAID compatibility!

We would like to have as much space as possible, moderated with the best data integrity we can get.
We are dealing with Biological data thus data loss is totally unfavorable although we do backups once in a while.

To confirm, "The size of the virtual disk would be the size of the smallest disk",
do u mean if I have 1TB disk, the space i have in the end is only 1TB?

Sorry I don't understand the "* 8/7/6"

In RAID10,how many RAID1 group can be created? E.g. 4TB in 1 group, 8TB in another, array will have 4 or 8TB?
Comment: When saying the size of the disk is the size of the smallest disk, if you were to put 2 disks in raid, the larger disk is only used to the capacity of the smaller disk. Example: RAID 0 with a 1TB and a 2TB: size is 2TB as the 1TB is the smaller disk so it would cap the 2TB at its capacity.  Example: RAID 1 with a 1TB and a 2TB: total space is 1TB which is the size of the smallest disk.
Comment: With the total capacity, (assuming all disks are the same size) if you have 8 disks in raid 0, you will have all 8 disks storage for your use, but with no redundancy.  If you use raid 5, you will be using 7 disks for storage and 1 disk for parity.  This way if a single disk fails, the storage array can be rebuilt when you insert a new disk.  In raid 6, you will be using 6 disks for storage and 2 disks for parity.  This way if 2 disks fail, the array can still be rebuilt.
Comment: With raid 10, you would create raid 1 partitions.  These would then be used to create a raid 0 partition of the raid 1 partitions.  You can have as many disks in the raid 1 partitions as you would like (even 0!) and you can put as many of these raid 1 partitions together as you want to make your virtual disk.


Reducing Bit Order Logic

Question: I have the following code, and I'm wondering if there's a more succinct, reduced way to write this code:
(FontStyle is a .NET Enum with the Flags attribute)
lblPrompt.Font.Style = FontStyle.Regular;

if (chkBold.Checked)
    lblPrompt.Font.Style |= FontStyle.Bold;
if (chkItalics.Checked)
    lblPrompt.Font.Style |= FontStyle.Italic;
if (chkUnderline.Checked)
    lblPrompt.Font.Style |= FontStyle.Underline;

I have a feeling the answer lies in correctly applying the and & operator between CheckBox.Checked and the desired flag, similar to the following:
lblPrompt.Font.Style =
    (chkBold.Checked & FontStyle.Bold)
    | (chkItalics.Checked & FontStyle.Italic)
    | (chkUnderline.Checked & FontStyle.Underline);

This does not work however because the compiler apparently does not like my direct application of the ampersand with a bool and a Flag/Enum type.
Comment: The first snippet is clear and easy to reason about. I wouldn't change it.
Answer: How about something along these lines:
lblPrompt.Font.Style |=
    (chkBold.Checked ? FontStyle.Bold : 0)
    | (chkItalics.Checked ? FontStyle.Italic : 0)
    | (chkUnderline.Checked ?  FontStyle.Underline : 0);

Comment: The assignment (`=`) should be an OR (`|=`) to match the original behavior.
Comment: Is that any more efficient than the previous attempt?  It is more succinct, which is what the OP was after, I think, but I'm wondering if it is faster.  I only ask because we're dealing with bitwise manipulation.
Comment: @BlackVegetable I think the OP only cared about brevity. Though, I personally don't think it's more readable than the original code.
Comment: This solution works, although you must precede it with the following: ( lblPrompt.Font.Style = FontStyle.Regular ) otherwise it will simply add new flags, not "reset" them to the state of the UI controls. I was really hoping for a solution that allows me to "set" the flags without having to preset the variable to zero, for brevity sake.
Comment: @MartinBliss well, you can assign `FontStyle.Regular = 0` in your enum. Then it is the default value when doing bit logic.
Comment: @Shedal I don't understand what you mean. It sounds like you're saying the same thing I just said: That you have to set the enum to 0 BEFORE the code in your original answer, because the code given only "adds" flags, and doesn't "set" them.
Comment: @Martin I was referring to the possibility of manually assigning numerical values for the flags while defining the enum. Like, Regular=0, Bold=1, and so on. In that case, "no flags" already means "Regular". But maybe I misunderstood what you're missing in the solution.
Comment: @Shedal What I mean is that, given an enum I can't modify (it's not my enum), I have to set the value of an enum variable to 0 before executing your line of code, otherwise I will simply get the previous value AND any new flags set. For example: If the initial value of lblprompt.Font.Style is FontStyle.Italic, and I have Bold and Underline checked, the result (with your code) is all three. If I set to zero prior to your code, I will get Bold and Underline, NOT Italic... the expected behavior. I was hoping to avoid having to set the initial flag as a matter of code style.
Comment: @MartinBliss just use `lblPrompt.Font.Style =` instead of `lblPrompt.Font.Style |=`.
Comment: @Shedal I don't know why I didn't think of that! I'm pretty sure I tried it once and it didn't work, but it works now so I guess I made a mistake before. Thanks!
Answer: Only way I can think of would be to use the ternary operator, like the following:
lblPrompt.Font.Style = FontStyle.Regular
             | (chkBold.Checked      ? FontStyle.Bold      : FontStyle.Regular)
             | (chkItalics.Checked   ? FontStyle.Italic    : FontStyle.Regular)
             | (chkUnderline.Checked ? FontStyle.Underline : FontStyle.Regular);

similarly indenting similar portions of expressions is a stylistic thing that I do and you are by no means obligated to carry it into your own code.
Comment: Similar to Shedal's answer, this doesn't ensure that `FontStyle.Regular` bits, if any, are set when all of the boxes are checked.  It should either use `|=` or toss `FontStyle.Regular | ` in.
Comment: I fixed it to always set FontStyle.Regular.
Answer: If you have significantly more options than just those three, it might be worth doing a table-driven solution:
var table = new [] {
        new { box = chkBold, style = FontStyle.Bold },
        new { box = chkItalics, style = FontStyle.Italic },
        new { box = chkUnderline, style = FontStyle.Underline }
    };

foreach(var combo in table)
{
  if(combo.box.Checked)
        lblPrompt.Font.Style |= combo.style;
}

This is not necessarily more concise, but it keeps you from repeating yourself.
Comment: You can also make it a `Dictionary`.
Comment: Indeed, anything that can hold all the data works. I just like the names of anonymous classes.

Reducing Bit Order Logic


Why can't I play co-op?

Question: When I try to play co-op in Saints Row: The Third, it says I need to enter a code. However, I have already done this and got my unlockable items like the car, gun and clothing. I have been trying to sort it out, but nothing has worked, can you help?
Answer: Sounds you like you got a pre-order bonus, and you've entered the code for that. Did you enter a separate code for an Online Pass? It's possible and pretty likely that they are 2 completely different codes on different pieces of paper in the game box.
I ordered mine after the pre-order bonuses and the game only came with a card with the Online Pass code. The online pass card should look something like this:
Comment: I only got the prof genki code, am I meant to get an online code with the game, because I am not pay 800 Microsoft points to go online, thanks though
Comment: If you bought the game new, yes, it should have the online code with it. If used, then no, it won't come with it.
Comment: Oh, I bought it new and that was the only code I got in it
Comment: @Davidchandler The online pass code is found inside the case of the game, on a paper that looks like the one in Doozer Blake's answer. It might possibly be behind the instruction manual, but it's in the same storage space as the instructions would be.
Comment: Got it, it didnt look like the pics but its all Sorted now, thanks guys :) (The code was on the back of the instructions.)
Comment: Hi David, if Doozer has answered your question, please accept it

Why can't I play co-op?


Looping in SQL Server Management Studio

Question: I am given a list of 717 SKU's that I have to go through and add up the total values of Yearly Sales and Units Sold. I developed a code to search a SKU by year and receive the total amount. I was wondering If there was a way where I could loop to input a greater number of SKU's so that I don't have to go through individually SKU by SKU.
I am familiar with Loop statements but am not the best at executing them. Was wondering if there was a way to do this in the Microsoft SQL Server Management Studio 2017.
I've tried Declaring and repeating the code but it has been inefficient.
DECLARE @SDate date
SET @SDate = '01/01/2018'
DECLARE @EDate date
SET @EDate = '12/31/2018'
DECLARE @Sku varchar(20)
SET @Sku = 'SN1580'

SELECT        SUM(Amount) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN1580')
SELECT        SUM(Quantity) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN1580')

SELECT        SUM(Amount) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN0350')
SELECT        SUM(Quantity) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN0350')

Expect the results to give me something along the lines of
SN1234
Amount 1000
Sum 200

SN3456
Amount 2000
Sum 100

Or if there was a way to get the results in a format that would be easily exportable to excel.
Comment: Which technology is it?  Sql server or mysql it cant be both
Answer: If you need to pass multiple SKUs, you could use a table variable:
DECLARE @SDate date
SET @SDate = '01/01/2018'
DECLARE @EDate date
SET @EDate = '12/31/2018'

DECLARE @Skus table (SKU varchar(20);

INSERT INTO @SKUs
VALUES('SN1580'),
      ('SN0350');

SELECT SIL.[No_] AS SKU,
       SUM(SIL.Amount) AS Amount,
       SUM(SIL.Quanity) AS Quantity
FROM dbo.[Threshold Enterprises$Sales Invoice Line] SIL --I recommeond against special characters (including white space) in object names
     JOIN @SKUs S ON SIL.[No_] = S.SKU
WHERE SIL.[Shipment Date] BETWEEN @SDate AND @EDate
GROUP BY SIL.[No_];

If this is an application using this parametrised query, you may need to create a user defined table type and then use that:
CREATE TYPE dbo.SKUs AS TABLE (SKU varchar(20));

Microsoft's documentation covers how to use these in Table-Valued Parameters.
Edit, side note, if your column [Shipment Date] has both date and time values (and the time could be a value other than 00:00:00) I suggest against BETWEEN. This is becuase any time after midnight on the last day would not be between those 2 dates. For example 2018-04-30 00:00:00.003 is not between 2018-04-01 and 2018-04-30.
If you are do therefore have date and time values I suggest using this clause:
WHERE SIL.[Shipment Date] >= @SDate
  AND SIL.[Shipment Date] < DATEADD(DAY, 1, @EDate)

Comment: I posted a minute after you, Larnu. Not sure why I got the check mark, but you got a +1 from me for a) having nearly identical code to what I came up with and b) giving some really valuable extra pointers along with it.
Comment: OP probably has sort by newest and only tried the first answer, I imagine @EricBrandt.
Comment: I was going to post an almost identical answer. I prefer this approach over using a large IN statement, because the query optimizer tends to have a hard time with those. All of the options in the IN get parsed as separate OR clauses, which means you end up with 700+ different branches the optimizer has to consider.
Comment: Fair observation. After I saw you had beat me, I almost deleted, but really wanted to discourage looping.
Answer: You should be able to do it all in one query using an IN statement where you have comma separated list in your IN statement.  Depending on what SQL technology it is your syntax may be slightly different.
SELECT      No_ AS SKU, SUM(Amount) AS Amount, SUM(Quantity) AS Quantity
FROM        dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE       ([Shipment Date] BETWEEN @SDate AND @EDate)
            AND (No_ IN
                ('SN1580', 'SN0350')
            )
GROUP BY No_;

Or if you have your SKU's in a table you can change the IN to this:
            AND (No_ IN
                (Select SKU from yourTableHere)
            )

Answer: Don't think in terms of loops. Think in terms of sets.
This uses a table variable for the sku list, but you could use a CTE, an actual table, a VALUE list; anything, really, that lets SQL Server handle all of your search terms as a data set rather than as individual inputs.
DECLARE @SDate date = '01/01/2018'
DECLARE @EDate date = '12/31/2018'

DECLARE @Sku TABLE
(
  Sku varchar(20)
);

INSERT @Sku (Sku)
VALUES (N'SN1580'),
       (N'SN0350'); --<--Add your list here. Maybe use Excel to make the wrappers.

SELECT
   l.No_
  ,SUM(l.Amount) AS Amount
  ,SUM(l.Quantity) AS Quantity
FROM
  dbo.[Threshold Enterprises$Sales Invoice Line] AS l
  JOIN
   @Sku AS s
    ON s.Sku = l.No_
WHERE
  l.[Shipment Date] BETWEEN @SDate AND @EDate
GROUP BY
  l.No_

Looping in SQL Server Management Studio


Differences between select() and table.select()

Question: What are the differences between select and tablename.select()? When I pass column name to table.select like:
table.select(table.c.name)

the sql is like
select * from tablename where tablename.name

and when I pass a column to select (instance method):
select([table.c.name])

the sql is like
select name from tablename

I want the same result as select with table.select.
When I read the docs of select it's the same so it's the same method but why they have a different behavior?
Comment: According to the documentation, table.select receives a WhereClause (default = None) and an array of strings. Since you passed only one string, it may have received it as the WhereClause.
Try doing this: table.select([table.c.name])
Answer: Presumably, with select() you mean sqlalchemy.sql.select().
The select() function expressly takes a set of columns as it's argument, and it's result is a stand-alone Select instance. You can also pass in a FromClause object (like a table or an alias) and it'll take the columns from that object. This is described in detail in the Selecting chapter of the core tutorial.
The .select() method on a table on the other hand, takes a whereclause first argument, not a set of columns. In other words, whatever you pass to that method, form the WHERE filter for the select, not the columns you wanted to select. By passing in a column for the where clause, you are selecting all columns, but filtering on WHERE [columnname]. Not much of a filter, since there the expression doesn't really restrict what rows will match.
Proper use of the table.select() function is to pass in a selection filter, and the intention to select all columns:
table.select(table.c.name != None)

which would be compiled to:
SELECT * FROM tablename WHERE tablename.name IS NOT NULL;

(although SQLAlchemy, knowing what columns exist, expands * to an explicit list of all table column names).
You should stick to the select() function to select only specific columns.
Comment: According to the Selecting chapter of core tutorial, `select([table])` will expand to each of its columns and generates `From` clause.
Comment: @dralshehri: I'll try to check this later, but that's probably a new feature introduced since I wrote this answer (which is now over 7 years old). We are now 5 versions along!
Comment: @dralshehri Note that the point of the question was to pick a subset of columns, not all the columns in the table.
Comment: Noted. Thanks for your answer which was helpful even after several years


How would I use NAudio to compress incoming PCM data from the microphone?

Question:
I'm working on a VOIP application that will be transmitting audio data across a network using NAudio. I don't want to stream raw PCM because of bandwidth concerns so I'm trying to encode the samples in μ-law. So far, I've been unable to find any explanations on how exactly this is done. I assume that I'm supposed to use NAudio.Codecs.MuLawEncoder.LinearToMuLawSample(short s), but the problem is that I'm given a byte array in the DataAvailable event.
I've tried iterating through the DataAvailable buffer, calling LinearToMuLawSample on every byte. However, the actual size of the array obviously isn't changing and thus I'm not getting any size reduction.
Here's the code responsible for encoding:
byte[] sample = _rawSamples.Take(); //take from sample buffer

for (int i = 0; i < sample.Length; i++) //actual conversion code
    sample[i] = MuLawEncoder.LinearToMuLawSample(sample[i]);

_encodedSamples.Add(sample); //add to network buffer

Here's the contents of my DataAvailable handler:
private void _input_DataAvailable(object sender, WaveInEventArgs e)
{
    byte[] buffer = e.Buffer;
    Array.Resize(ref buffer, e.BytesRecorded);

    _rawSamples.Add(audioData);
}

And finally, here's how I'm declaring my WaveIn:
_input = new WaveIn();
_input.BufferMilliseconds = 100;
_input.DataAvailable += _input_DataAvailable;
_input.RecordingStopped += _input_InputRecordingStopped;

Essentially, what I'm looking for is a way to take PCM data in the form of a byte array and convert it to a format suitable for sending over a network. I don't quite understand how the MuLawEncoder class can actually encode/compress audio data in this manner.
Comment: Even though the input is a byte array, what size are the individual samples? In [this example](https://github.com/naudio/NAudio/blob/master/NAudioDemo/NetworkChatDemo/MuLawChatCodec.cs) the samples are 16bit, so they interpret each pair of bytes in the input array as a 16bit integer before passing it to the encoder...
Comment: I'm working with 16 bit audio. So this sample code halves the size of the raw PCM?
Comment: Yes, you got that right.
Comment: A good place to start would be to look at the code for the network chat demo in the NAudioDemo project. It shows basic microphone capturing and Mulaw is one of the available codecs
Answer: Update
I was able to get it working using the examples at https://github.com/naudio/NAudio/blob/master/NAudioDemo/NetworkChatDemo/. Here are the key functions I ended up using:
private byte[] EncodeSamples(byte[] data)
{
    byte[] encoded = new byte[data.Length / 2];
    int outIndex = 0;

    for (int n = 0; n < data.Length; n += 2)
        encoded[outIndex++] = MuLawEncoder.LinearToMuLawSample(BitConverter.ToInt16(data, n));

    return encoded;
}

private byte[] DecodeSamples(byte[] data)
{
    byte[] decoded = new byte[data.Length * 2];
    int outIndex = 0;
    for (int n = 0; n < data.Length; n++)
    {
        short decodedSample = MuLawDecoder.MuLawToLinearSample(data[n]);
        decoded[outIndex++] = (byte)(decodedSample & 0xFF);
        decoded[outIndex++] = (byte)(decodedSample >> 8);
    }
    return decoded;
}

The key was stepping through the data two bytes at a time, converting each pair into an Int16, passing that into LinearToMuLawSample, and packing the return values into a new array of half the size.


Create a cloned div that works separately in the same page

Question: I have a div in my page which contains a table with inputs (with ids), I have some conditions and functions on the inputs written in the Javascript code. What I'm trying to do is to make a button (add new) that clones exactly the same div in the page but with same conditions and functions on the new elements and the submit button to work for each separately.
I tried this :
$('#button-add').bind({
    click: function()
    {
        $("#repeat").clone().appendTo("#add");
    }
});

the problem is that I get the same appearance for the div but the functions are not working (because the inputs have the same id) and i cannot submit only that block (new div).
Is there a simpler way to achieve that?
Comment: use classes instead of id's and then look into `delegated` events http://learn.jquery.com/events/event-delegation/ as you are adding elements dynamically, you will have to listen to events bubbling up from those new elements to an element that has existed from the beginning such as `body`
Answer: Since you're going to duplicate the div, you should not use IDs, because their uniqueness would be compromised. But you can use css class names ($('.className')) or custom data attributes ($('[data-my-id=xxx]')) to address your inputs because they do not need to be unique.
Second, you need to clone your div so that the events attached to your inputs are cloned as well. Check out the jQuery doc for .clone([withDataAndEvents] [,deepWithDataAndEvents]) (http://api.jquery.com/clone/).
Comment: the problem is that i have inputs in my div that depend on each other . if i make a class then when user selects something in the input in the first div it will change the values in the second div two wich i don't want to happen .
i want each new div to work somehow seperately as an individual page.
Comment: You can set a new ID for each main div and then address the input within that div: $('#mainDiv_1 .someInputClassName').
Comment: Or, within the event handlers of your inputs, search only the parent main div for the other inputs: $(this).closest('.mainDivClass').find('.someInputClass')
Answer: Just in case if you ignore making clones.
The way of doing it using a dynamic id.
Say if appending div with different id for every element using random function in javascript.
   $('#add-item').on('click', function (e) {
                        var num = Math.floor(Math.random() * 90000) + 10000;
                        var numtd = Math.floor(Math.random() * 50000) + 10000;

                        $('
' +
                            '' +
                                '
' +
                                '<input type="hidden" id="selected_item_' + numtd + '" name="selected_name" />' +
                                    '<input type="text" name="Inv_Itemsdetail" value="" class="Itemsdetail-typeahead_' + numtd + ' input-search" autocomplete="off" data-provide="typeahead" />' +
                                    '<input type="hidden" id="Inv_Itemsdetail_' + numtd + '" class="auto-complete" name="Itemxx[]" />' +
                                    '' +
                                        '' +

                                    '' +
                                '
' +
                            '	' +'
').appendTo('#yourcontainer_id');
});

Now using jQuery call for same id elements-
Now Note this way I have every element starting with same id name plus a random number.
$('input[id^="selected_item_"]')

Comment: is there a way to select all the ids that begin with an id (indifferent what random number is after the id) because i have javascript functions that should be applied to the new generated elements in the new div . how can i select them if the ids are generated with random number after ?
Comment: @oday, I mentioned the same in last line. Ids are coming randomly
Comment: yes ,Thanks !
i used your solution then i modified the functions to accept parameters with new genereated ids .
Answer: Since the new div is created in new space ie, in #add, select the new div as
#add #repeat
{

}   //  in css

in jquery use next or siblings or children etc to select the new div
For example
see the FIDDLE


How to deploy Er REST Example on cc2650 platform

Question: I am working on cc2650 and cc2531 dongle and I have already installed 6lbr. Now I need to check security for CoAP  and I need to implement a simple example. I want to work on Er-REST example and I have some questions regarding to deployment.
1)Do I have to also use Cooja? I am asking I am using the native-border-router together with the slip-radio. So which settings should I have done to be able to deploy the example?
There are how to's for other platforms but not slip radio cc2650.
Is there anyone who worked on or do you have any suggestions?
Thanks in advance...
Answer: Check the TMOTES HOWTO in https://github.com/contiki-os/contiki/tree/master/examples/er-rest-example
It should be the same concept to what you want.
Be careful with what "native" platform means: check this link https://github.com/contiki-os/contiki/wiki/Native%2C-minimal-net
Comment: I cannot comment except on my own post, so please open another question if you may.


Devise logs users out after hitting certain routes

Question: Here is my routes files:
Tubalr::Application.routes.draw do
  devise_for :users

  root :to => "application#index"

  get "/player/:search_type/:search/:first_video" => "application#player"

  get "/just/:artist_band.json" => "api#just"
  get "/similar/:artist_band.json" => "api#similar"
  get "/:username/favorites.json" => "api#userFavorites"

  get "/just/:artist_band" => "application#index"
  get "/similar/:artist_band" => "application#index"

  get "/history" => "application#history"

  get "/:username/favorites" => "favorites#init"

  post "/check-favorites" => "favorites#check"
  post "/favorites/add" => "favorites#add"
  post "/favorites/remove" => "favorites#remove"

  devise_scope :user do
    get "/users/sign_out" => "devise/sessions#destroy"
  end
end

The routes /history and the default /users/edit route for devise do not log the user out.
I'm not sure what other information to give, if theres something that would help debugging my problem, please let me know and I'll update the question.
The entire projects code can be found here: https://github.com/cjstewart88/Tubalr/tree/user_favorites
Answer: After digging around I finally ran into this:
https://github.com/plataformatec/devise/issues/913
It appears that the csrf token needs to be passed along with AJAX request, which my app is doing a good bit.


Can driveway fabric (petro-mat) be used DIY?

Question: I read that driveway fabric can help prevent new cracking when putting an asphalt overlay on top of an existing asphalt driveway networked with little cracks ("alligator").  Can this be done DIY?  If so, would I fill the depressions with asphalt patch first?
What's the difference between driveway fabric and landscape cloth (if any)?  I have a whole lot of landscape cloth left over from a project and I wonder if I could use that.
Here's a general description of petro-mats:

The greatest source of damaging water in road structural sections is precipitation infiltration through pavements. Most pavements do not have adequate drainage systems to quickly remove infiltrated water. If a pavement base is saturated as little as 10% of the time, the useful life of that pavement will be reduced by 50%. The Petromat fabric, when saturated with the asphalt cement tack coat, becomes a moisture barrier in the pavement, minimizing surface water infiltration. The American Association of Highway and Transportation Officials (AASHTO) 1993 flexible pavement design methodology gives a substantial structural credit to unbound roadbase materials when they are well drained and not allowed to become saturated. By minimizing water infiltration, the Petromat System moisture barrier will keep the road base more well drained and will therefore maximize the structural strength of unbound roadbase materials.

I think geotextiles were initially used in pavement as a weed barrier under the gravel sub-base, but then they evolved from there.
Answer: I talked to one of the petro-mat sellers and found out that the standard petro-mat needs a liquid "tack coat" poured down before the geotextile is put down.  Typically the fabric is put down with a special machine.  To put it down manually would ideally involve four people, one standing at each corner, because if folds or wrinkles form, the piece has to be thrown out and you have to start fresh.  One could do patchwork, with reasonably sized sections, to make it more workable.  But the tack coat is very hot asphalt with no gravel, I think -- which is beyond this DIYer.
Some more googling led me to another type of petro-mat that doesn't required the initial tack coat.  For this one, you just clean the driveway thoroughly, fill any cracks at least half an inch wide, and lay it down.  It sticks to the driveway and stays put nicely while the asphalt is being put down.  Description:

The GlasGrid System capitalizes on the high tensile stiffness of fiberglass. Its grid configuration features fiberglass strands coated with an elastomeric polymer. Each strand has a remarkably high modulus of elasticity that makes GlasGrid stronger than steel by weight.
A pressure-activated adhesive coating on the underside of the grid makes GlasGrid one of the fastest-to-install interlayer systems.

I plan to make an appointment with a residential paving service to have a new layer of asphalt put on my driveway.  The previous weekend I will clean it thoroughly, use a knife to clear out the bigger cracks, fill them with the DIY crack treatment, and then the day of the asphalt appointment, I will lay out the glass grid geotextile and stick it down.  I'll let the asphalt people do their regular thing.
I think that the occasional small depression should get evened out through the normal paving process, so I don't plan to do anything to those spots in advance.
The challenge now is to get a small piece of glass grid.  It comes in very large rolls since this material is not currently marketed to the residential consumer.  However, one of the sales people connected me to a paver three hours away who works with glass grid, and he has agreed to send me a remnant next time he has some leftover from a big parking lot.  (None of the pavers in my area have the slightest idea geotextiles even exist.)
Comment: @isherwood - I haven't been able to try it.  The problem is sourcing a small amount.


Can we use 'self' with 'unsafe-Inline' instead of nonce for content security policy?

Question: We are getting security issue due to unsafe-inline in header and as per security team we should use nonce but that one is difficult to use with inline event handler method so we are looking for the option to use 'self' instead of nonce
Answer: Inline event handlers are not nonceable elements, so you can't allow them with a nonce. Your options are to use 'unsafe-inline' or to rewrite event handling into a file on your server, for which you would need 'self' to load. Adding 'self' will allow files under that directive to load, but will not allow inline event handlers directly.


How to find missing values ( Like a ? ) in large dataframes in R

Question: I have a data set with like 9 different  attributes coloumns, I have to find no of ? in each attribute . How can I find it ? Kindly help
Age
?
45
67
89
?
56
78

Comment: I think it is better to specify `na.strings= "?"` while reading i.e. `read.table` so that it will be NA and the `class` of the column will be `numeric` instead of `"?"`.  For the specific question, use `as.character(df1$Age ) == "?"`.  For finding it in the whole dataset, `lapply(df1, "==", "?")`
Comment: Or ``which(Age=="?")`` afterwards
Answer: Try this :-
#so is the dataframe that has the data
count.q <- function(x) {
      lengths(regmatches(x, gregexpr("\\?", x))) %>% sum
}

apply(so , MARGIN = 2,count.q)

#count.q gets the count of "?" , and I apply it to the columns of the df.

For this data -
Age ID  Siblings
?   we  1
?   ?   ?
11  ?   0
20  ?   0

I got this o/p
 Age        ID      Siblings
       2        3        1


How to fetch records from a Oracle table using SQL based on some condition

Question: Please refer attached ER diagram.
I need to write a SQL query to fetch records from 2 main tables (Table A and Table B) based on a condition.
Condition is for a given Application (APP_ID) :

if the Table A Case_Status is True (if Case_Status = '00') then fetch all the Table A details (like First_name, Last_name) along with details from   Table B (i.e. Person_name, comments from Table B) corresponding to that application
otherwise just fetch application details from Table A only (First_name, Last_name etc)

Table C is just a master table that stores the status code as 'True' or 'False' in its description Column (Status_Id->00, means True and Status_Id->01 means False).
Please suggest me on this. I want to join both columns and bring data but I can't write the condition correctly.
Thank you
Answer: This is a bit of a hack...
select a.app_id
        , a.case_status
        , a.first_name
        , a.last_name
        , b.description
        , b.person_name
        , b.comments
from tableA a
left join tableB b
on a.app_id = b.app_id
and a.case_status = '00'

... but it will return all the values in tableA, plus matching values from tableB when the status is correct.


Why didn't theta change after iterations? I debugged and didn't get any error

Question: import numpy as np

X = np.matrix([[1,6.1101],[1,5.5277]])
y = np.matrix([17.592,9.1302])
theta = np.matrix(np.array([0, 0]))

def gradientDescent(X, y, theta, alpha, iters):
    count = theta.ravel().shape[1]
    for i in range(iters):
        predict = X * theta.T
        for j in range(count):
            theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
    return theta

# def gradientDescent(X, y, theta, alpha, iters):
#     temp_theta = np.matrix(np.zeros(theta.shape))
#     count = theta.ravel().shape[1]
#     for i in range(iters):
#         predict = X * theta.T
#         for j in range(count):
#             temp_theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
#         theta = temp_theta
#     return theta

alpha = 0.01
iters = 1000

g= gradientDescent(X, y, theta, alpha, iters)
print(g)

The right function is annotated. Why do I have to add a temporary variable? The value of theta in my function does not change after any iterations.
Comment: I executed your code on my machine and `theta` is changing: the value returned by `gradientDescent` (which is theta) is `[[0 1]]`
Answer: You need to specify a type for theta.
theta = np.matrix(np.array([0, 0]), dtype=float)

In the end, your script gives you [[0.99642971 2.11975865]]


How to make scoreboard show teams instead of players?

Question: I am trying to make it to where points for teams are shown in the scoreboard but I can only manage to get player names on there, what command do I use? On 1.16
Comment: Interesting, this was not asked before. There are a bunch of related questions, but not really this.
Answer: For this you need a second scoreboard. Let's say that single_scores is the scoreboard that you already have. I'll call the shared one team_scores:
/scoreboard objectives add team_scores dummy "Insert display name here"

Now whenever you want to update the scores, you need to first reset them:
/scoreboard players reset * team_scores

And now add all team scores to the correct dummy players per team:
/scoreboard players operation blue team_scores += @e[team=blue] single_scores
/scoreboard players operation green team_scores += @e[team=green] single_scores
/scoreboard players operation yellow team_scores += @e[team=yellow] single_scores
…

This way the sum of the blue team appears as "blue" in the sidebar, if you set it to display team_scores instead of single_scores. You can even give both the same display name if you want to pretend that they're the same.


Modify SqlDataSource.SelectCommand using Stored Procedure with parameters

Question: I am trying to create a search box in my application, in order to do so i need to modify the SqlDataSource.SelectCommand. I will appreciate any help!
For testing I did it like this, it works but it is vulnerable for sql injection
<code>   SqlDataSource1.SelectCommand = "sp_offer_search '" + txtSearch.Text + "', " +   Session["customerId"] + " , '" + "Pending"+ "'";
   GridView1.DataBind();
</code>
This is What I tried so far but it is not working:
<code> if (txtSearch.Text != "")
        {
         //open connection
          oCn.Open();
          SqlCommand com = new SqlCommand(query, oCn);
          com.CommandType = CommandType.StoredProcedure;

          com.Parameters.AddWithValue("@Variable", txtSearch.Text);
          com.Parameters.AddWithValue("@CustomerId",Session["customerId"]);
          com.Parameters.AddWithValue("@Status", txtStatus.Text);

            DataTable dt = new DataTable();
            dt.Load(com.ExecuteReader());

            SqlDataSource1.SelectCommand = dt.ToString();
            GridView1.DataBind();
       }
</code>
Comment: You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results...
Comment: Exactly how does it now work?  Do you get an error, or incorrect returns, or nothing returned?  Something else?
Comment: it doesn't return anything, it like it doesn't find a match
Comment: Marc_s thank you for the hands up. I did not know that.
Answer: If the GridView datasource is set to the SqlDataSource1 then you don't need the DataTable. And a DataTable.ToString() is not a selectCommand. Try:
<code> if (txtSearch.Text != "")
    {
      SqlCommand com = new SqlCommand(query, oCn);
      com.CommandType = CommandType.StoredProcedure;

      com.Parameters.AddWithValue("@Variable", txtSearch.Text);
      com.Parameters.AddWithValue("@CustomerId",Session["customerId"]);
      com.Parameters.AddWithValue("@Status", txtStatus.Text);

      SqlDataSource1.SelectCommand = com;
      GridView1.DataBind();
   }
</code>
Comment: I've only used EntityFramework against SQL Azure. I found this (https://www.axian.com/2014/12/01/adjustments-for-sql-azure-no-ole-db/) that implies the ADO.Net OleDB provider might work. But if you are going to switch the provider I would suggest EntityFramework.
Comment: Hi Crowcoder, "com" is returning System.Data.SqlClient.SqlCommand and is causing an error:'System.Data.SqlClient.SqlCommand' is not supported in this version of SQL Server any ideas?
Comment: What is your database?
Comment: we are using SQL Azure
Answer: Solved ! Here is what I tried and it works. I hope this can b helpful for someone.
<code>  if (txtSearch.Text != "")
        {
            try
            {
                //  open connection
                oCn.Open();

                SqlDataAdapter da = new SqlDataAdapter("sp_offer_search", oCn);

                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.Add("@Variable", SqlDbType.VarChar).Value = txtSearch.Text;
                da.SelectCommand.Parameters.Add("@CustomerId", SqlDbType.Int).Value = Session["customerId"];
                da.SelectCommand.Parameters.Add("@Status", SqlDbType.VarChar).Value = "Pending";

                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView1.DataSourceID = String.Empty;
                GridView1.DataSource = dt;
                GridView1.DataBind();

            }
            catch(Exception ex)
            {
                Response.Write(ex.ToString());
            }
            finally
            {
                oCn.Close();
            }

        }
        else
        {
            GridView1.DataSourceID = "SqlDataSource1";
            SqlDataSource1.SelectCommand = SqlDataSource1.SelectCommand;
            GridView1.DataBind();
        }
</code>


How to prove that $\sum_{n \, \text{odd}} \frac{n^2}{(4-n^2)^2} = \pi^2/16$?

Question: The series:
$$\sum_{n \, \text{odd}}^{\infty} \frac{n^2}{(4-n^2)^2} = \pi^2/16$$
showed up in my quantum mechanics homework. The problem was solved using a method that avoids evaluating the series and then by equivalence the value of the series was calculated.
How do I prove this directly?
Comment: integrate $\frac{z^2}{(4-z^2)^2}\tan(z)$ over a big circle in the complex plane
Answer: First, the partial fraction of the summand can be written
$$\begin{align}
\frac{n^2}{(4-n^2)^2}&=\frac14\left(\frac{1}{n-2}+\frac{1}{n+2}\right)^2\\\\
&=\frac14 \left(\frac{1}{(n-2)^2}+\frac{1}{(n+2)^2}+\frac{1/2}{n-2}-\frac{1/2}{n+2}\right)
\end{align}$$

Second, we note that
$$\begin{align}
\sum_{n\,\,\text{odd}}\frac{1}{(n\pm 2)^2}&=\sum_{n=-\infty}^\infty \frac{1}{(2n-1)^2}\\\\
&=2\sum_{n=1}^\infty \frac{1}{(2n-1)^2}\\\\
&=2\left(\sum_{n=1}^\infty \frac{1}{n^2}-\sum_{n=1}^\infty \frac{1}{(2n)^2}\right)\\\\
&=\frac32 \sum_{n=1}^\infty \frac{1}{n^2}\\\\
&=\frac{\pi^2}{4}
\end{align}$$

Third, it is easy to show that
$$\sum_{n=-\infty}^\infty \left(\frac{1}{2n-3}-\frac{1}{2n+1}\right)=0$$

Putting it all together we have
$$\sum_{n,\,\,\text{odd}}\frac{n^2}{(4-n^2)^2}=\frac{\pi^2}{8}$$
If we sum over the positive odd only, then the answer is $(1/2)\pi^2/8=\pi^2/16$
Answer: Wolfram Alpha gives me the partial fraction expansion:
$$\frac{n^2}{(4 - n^2)^2} = \frac{1}{8}\left(\frac 1{n-2}-\frac{1}{n + 2}\right) + \frac{1}{4}\left(\frac{1}{(n-2)^2}+\frac{1}{(n+2)^2}\right)$$
So the first part telescopes, and the second part will be some modified version of $\zeta(2)$.
In more detail: $$\begin{align}\sum_{n\text{ odd}} \left(\frac 1{n-2}-\frac{1}{n + 2}\right)&=\frac{1}{-1}-\frac{1}{3}+\frac{1}{1}-\frac{1}{5}+\frac{1}{3}-\frac{1}{7}+\cdots\\
&=-1+1=0\end{align}$$
since all the other terms cancel out.
And $$\begin{align}\sum_{n\text{ odd}}\left(\frac{1}{(n-2)^2}+\frac{1}{(n+2)^2}\right)&=\frac{1}{(-1)^2}+\frac{1}{3^2}+\frac{1}{1^2}+\frac{1}{5^2}+\frac{1}{3^2}+\frac{1}{7^2}+\cdots\\
&=2\left(\frac{1}{1^2}+\frac{1}{3^2}+\frac{1}{5^2}+\cdots\right)
\end{align}$$
It's a famous result that $\frac{1}{1^2}+\frac{1}{3^2}+\frac{1}{5^2}+\cdots=\frac{\pi^2}{8}$. You can can prove it if you know:
$$\frac{\pi^2}{6}=\zeta(2) = \frac{1}{1^2}+\frac{1}{2^2}+\frac{1}{3^2}+\cdots$$
and thus $$\zeta(2)-\frac1{2^2}\zeta(2) = \frac{1}{1^2}+\frac{1}{3^3}+\frac{1}{5^2}+\cdots$$
So $$\sum \frac{n^2}{(4-n^2)^2}=0 + \frac{1}{4}\cdot 2\cdot \frac{\pi^2}{8}=\frac{\pi^2}{16}$$
Comment: Hi Thomas.  I had assumed that the sum over odd integers included the negative ones.  Naturally, the answer in that case is twice the answer if the summation extends to the positive odds only.  Anyway, (+1) for your well-written post.  -Mark
Comment: @Dr.MV Yeah, I wondered about that. I might have read it your way if it had been $\sum_{n\text{ odd}}$ rather than $\sum_{n\text{ odd}}^{\infty}$.
Comment: Ah,  yes.  I see your point.  Well, I did address the issue at the end of the post.  ;-))
Answer: HINT
$$\sum_{n \, \text{odd}}^{\infty} \frac{n^2}{(n^2-4)^2}=\sum_{n=1}^{\infty} \frac{(2n-1)^2}{((2n-1)^2-4)^2}$$
Using partial fraction expansion, note $$\frac{(2n-1)^2}{((2n-1)^2-4)^2}=\left(\frac{1}{4(2n+1)^2}+\frac{1}{4(2n-3)^2}\right)-\left(\frac{1}{8(2n+1)}-\frac{1}{8(2n-3)}\right)$$
Note that the second part has cancelling terms.
Comment: Why the downvote?
Comment: @ThomasAndrews I fixed the signs.


Why setState with callback function giving error : "TypeError: Cannot read property 'files' of null" while normal setState methods works just fine?

Question: I have a use case, can you help me understand at what point the callback setState method and normal setState method is getting executed, how does these two differs from execution point ?
handleselectedFile = event => {
  this.setState((prevState, props) => {
    return {

      selectedFile: event.target.files[0],
      loaded: 0,
      fileName: event.target.files[0].name
      };
    }
  })
};

When the event is triggered and method is called by child class and passes the event to parent class where above method is getting executed.
Above methods throws this error :

" TypeError: Cannot read property 'files' of null"

If I replace the above setState callback method with normal setState method, everything works just fine.
handleselectedFile = event => {
  this.setState({
    selectedFile: event.target.files[0],
    loaded: 0,
    fileName: event.target.files[0].name
  })
};

Any help would be greatly appreciated, what's causing this. I have searched a lot but couldn't find anything relevant or maybe didn't understood the solution.
Read this post, but unable to understand the problem with my situation : When to use React setState callback
Comment: @ShubhamKhatri Yes it was indeed very helpful, since I am new to react, I was not knowing that the synthetic object properties are getting nullified in seState callback function to increase performance. Thanks again.
Comment: Remove 'return' after the arrow on the first method. To understand why the error occurs, you need to understand how arrow functions work.
Comment: An arrow function usually looks like this: `params => returnValue` or this: `params => { /* function body */ }` You have `params => return { ... }` edit: ....aand you just inserted the missing braces
Comment: @ChrisG Sorry I have missed those braces during some console code deletion.
Comment: Glad it helped you
Answer: Could be missing function square brackets
 handleselectedFile = event => {
      this.setState((prevState, props) => { <-- here
        return {

          selectedFile: event.target.files[0],
          loaded: 0,
          fileName: event.target.files[0].name
        };
      })
    };

Comment: Either this or removing `return` and adding parentheses around the object that is being returned from the arrow function should do the trick. So `(prevState, props) => ({ selectedFile... })`
Comment: Thanks, must have missed these during deleting some lines.
Answer:   try this way
  handleselectedFile = event => {
     this.setState({

      selectedFile: event.target.files[0],
      loaded: 0,
      fileName: event.target.files[0].name
    },(prevState, props) =>(console.log(prevState,props)))
  };

Why setState with callback function giving error : "TypeError: Cannot read property ‘files’ of null" while normal setState methods works just fine?


Can an electrical subpanel go underneath plumbing?

Question: I was about to wire up my new basement subpanel when I realized I had put it directly under a toilet.

I don't think this is a code violation. I can relocate it with some difficulty. I'm also considering a hack like cutting a slightly larger piece of PVC in half and putting it under the plumbing pipe to carry any water to the other side of the joist.
Is the present installation unsafe? If so, what should I do?
Answer: The National Electric Code strictly prohibits the installation of water piping above the service equipment you described.
Art. 110.26(F)(1)(a) states:

National Electrical Code 2008
Article 110 Requirements for Electrical Installations
II. 600 Volts, Nominal, or Less
110.26 Spaces About Electrical Equipment.
(F) Dedicated Equipment Space.
(1) Indoor.
(a) Dedicated Electrical Space. The space equal to the width and depth of the equipment and extending from the floor to a height of 1.8 m (6 ft) above the equipment or to the structural ceiling, whichever is lower, shall be dedicated to the electrical installation. No piping, ducts, leak protection apparatus, or other equipment foreign to the electrical installation shall be located in this zone.
(b) Foreign Systems. The area above the dedicated space required by 110.26(F)(1)(a) shall be permitted to contain foreign systems, provided protection is installed to avoid damage to the electrical equipment from condensation, leaks, or breaks in such foreign systems.

You can place the piping from the toilet above the electrical panel provided it's located above the 6 foot high dedicated space, and provided it "is installed to avoid damage to the electrical equipment from condensation, leaks, or breaks in such foreign systems."
Comment: The last 2 sentences of your answer seem contradictory... My reading of that code section is that your last sentence is the correct one.
Comment: _Suspended ceilings, etc do not count as a structural ceiling._ Cellotex drop ceilings stop water as effectively as used toilet paper, and there's nothing as useless as used toilet paper. Structural floor also needs to not have anything piercing the flooring membrane (sheeting). I can tell you that from experience. Our hyper-intelligent building contractor put the heating closet above the telecom closet and then installed the water heater there. Drip trays mostly work unless the water is spraying out of the casing seam. Nearly KO'd our $30k PBX and routers.
Comment: Is the first floor sub-floor the "structural ceiling" for the basement?
Comment: Paragraph (c) says that structural ceilings must strengthen the structure. Suspended ceilings, etc do not count as a structural ceiling. It means to me that if he puts the protections in place he mentioned to redirect leaks, AND put a structural ceiling on the bottom of those joists (drywall), then he could keep everything where it is. I'm not familiar with what would constitute sufficient protection as mentioned in paragraph (b). The plans he submitted to the permit office should show both the plumbing and the electrical panel. If they approved it, then it should be good to go.
Comment: After flooding the heating closet, the water down through the plumbing and wiring routing holes bored through the 1 1/8" plywood floor. Some of the holes led down into the main circuit breaker panels. The rest rained on the drop ceiling, saturated it, we saw the water coming out under the telecom closet door, opened it to find the drop ceiling thankfully lying on the floor which kept the water from going that addtional 6 inches that would have been disaster. Nobody could go near the breaker panels till it had dried up a bit.
Comment: At least I noticed before I wired it up. I'll move it. Thank you.
Comment: But what about paragraph (b) "provided protection is installed to avoid damage".
So if I find a panel with this issue, can I install a mini-roof over it and be good?
Answer: Putting the panel under a toilet is a disaster waiting to happen. I have replaced a hundred wax rings and closet flanges over the years. From looking at your pic, it looks like you could move the panel to the right one or two bays and avoid the potential problem. As seen right now, it does not meet code and poses a serious safety hazard or shock or fire. DSlake gave you the right answer. Just move it and sleep soundly at night.
Answer: My answer is this: Code is clear - nothing above the service panel except a structural ceiling. In viewing this install I see the panel set INTO the stud space with a 2x4 plate (header like) above it. Therefore that should represent a structural ceiling as far as the panel is concerned. Code does not specify any area in front of the panel - only the width and depth (which are inside the stud-space). The closet drain enters the overhead in front of the panel - not direcly above it. In the strict interpretation the panel appears to be legal (though a a hard-ass inspector might disagree). There is no plumbing directly over the panel as would be if the panel was surface mounted. If it can moved that would be best if only to appease a particular inspector. This appears easy at this point with only 1 non-connected cable hanging in it in the photo. Can't see the wall on either side?
Comment: Hello, and welcome to Home Improvement. Good answer; keep 'em coming!


Cant boot from USB

Question:
I tried to install ubuntu alongside with Windows 8, but for some reason, it just deleted the W8 installation. But now, i want windows back, because Wine cant emulate all programs, which is, of course, to be expected. BUT: Even though i created the USB key with WinUSB (http://www.addictivetips.com/ubuntu-linux-tips/winusb-create-bootable-windows-installer-usb-in-ubuntu-linux/) my computer won't boot from it! I have changed the boot order, tried to use boot menu, but i am all out of ideas :(
The USB key is a Kingston DataTraveller 32GB USB3, formatted as NTFS and all the windows files on it (Note, i am trying to install Windows 7), so i don't understand where it went wrong.
I hope you guys/girls have some ideas :)
Jonas Strand
Answer: Are you sure the Ubuntu install deleted Win8? When installing alongside an existing Windows, it should not touch Windows at all. It might just be a grub issue. In a terminal, type sudo update-grub then reboot. You should see an entry for your Win8.
If, in fact, the Ubuntu installer DID remove your Win8, and you have to reinstall Windows via USB, your USB stick has to be formatted as Fat32, not NTFS.
Comment: Are you sure it has to be FAT32? The way i remember it is, that Windows 7 needs NTFS USB key to boot, but i can be mistaken, heh ^
Comment: You may be correct about NTFS. But I would try with a Fat32 stick and test it too.
Comment: This is what comes when i try to start Win8 from grub: http://www.the-strand.dk/pic.jpg
Comment: UEFI. Worst "improvement" ever. I am not sure I can help with this, but I bet Win8 is still on your hard drive. Are there any mountable folders/drives in Nautilus? If so, these are likely the Win8 install. If not, then something happened during the Ubuntu installation that really did remove Win8.
Comment: Alrigt, its not because am killing myself because i lost the win8 install (its win8 after all), but do you have any idea why i can't boot from USB? I am using the program WinUSB, link above, which formats it automatically as NTFS. But, if i were to format as FAT32, how to? I am complete Ubuntu/Linux noob ^ EDIT: Sorry for not answering your question, no, there is only "Reserved for system" :(
Comment: I agree about Win8...but that's another story...

As for booting, in UEFI there should be an option to boot first from device of your choice. Plug in the USB stick, then reboot, and it should show up in the UEFI. See if that works.
Comment: That is what i mean with "Boot menu", i see the USB drive, all right, i select it and clicks enter, so far so good, but when it tries to boot, nothing happens, it just loads GRUB :/
Comment: Weird. You have gone into the BIOS/UEFI, yes? It is either 'Delete' or 'F1' (usually Delete) to get into it. Then choose your first boot device.
Comment: Yep, indeed the case. I dont understand it either, as i used the exact same USB key to install Ubuntu from :S
Comment: Can you choose to change between UEFI and good old BIOS? I wonder if that would get things moving.
Comment: Well, i have to option to disable UEFI, if that is what you mean? And i have just fetched another USB key, so ill try to copy Win7 to it and check if it is the key's fault :)
Comment: Yes. And good idea getting another USB stick. Something might have written wrong on the first one, causing all the complications.
Comment: Alright, so far so good, now I can skip grub, but I get stuck on, what appears to be equal to BSoD on earlier windows versions. I get this error: 0xc000000e. But I can't boot from the new USB either :(
Comment: I am now out of suggestions.
Comment: I am sorry to hear that :(

Cant boot from USB


Angularjs ng-repeat how do I get the object key name?

Question: I am using Angularjs to search and display data stored in a documentDB. I have a Web Api 2 (.net) serving the data using IHttpActionResult.
When I look at the data returned from a $http,get I can see the structure is as expected, one of the properties of the document returned is called identifiers and is a collection of different identifers in a key value pair type scenario... see below..
 "identifiers": {
  "sourceid": null,
  "secondaryid": null,
  "name": null,
  "anotherid1": null,
  "anotherid2": "412417118",
  "etc": null
},

Obviously my actual data has different names for the sub identifiers replaced with generic names above...
in my Html I am using ng-repeat to display the list of identifiers for each record like so:

                        Identifiers:

 {{ident}}

                        Start Date:

                        {{ vessel.startdate | date : 'dd/MM/yyyy'}}

                        End Date:

                        {{ vessel.enddate | date : 'dd/MM/yyyy'}}

.........

However What I get written out is simply the value of each identifier but without the key or anything ... I have tried passing that to a function on the controller but when I do that and console.log the input it is literally just the string value, no longer a key/value pair.....
How to I get it to write the key and the value??
Interestingly if I get rid of the ng-repeat and just but {{identifiers}} in that
 tag, I get the following written out...

{"sourceid":null,"secondaryid":null,"name":null,"anotherid1":null,"anotherid2":"BJ5077","anotherid3":null,"etc":null,"etc2":""}
Answer: After coming at it a different way and taking inspiration from the stackoverflow post (linked here to help others) it was the syntax of my ng-repeat which was incorrect, it should have looked like this... obvious when you think about it!!!

 {{key}} : {{value}}


Find MINIMUM in multiple-column range, return value from Column A

Question: I am working on a spreadsheet for my fantasy football draft. Screenshot below.
I'm looking to put a formula into AA25 that finds the MINIMUM VALUE of W1:AH17 and then returns the corresponding value in Column A in the same row.
For example, in the screenshot, the minimum value in W1:AH17 would '12' (cell AH1), which would then return the value '1' (cell A1).
I currently have a successful formula in AA25...
=ArrayFormula(TEXTJOIN(", ",TRUE,IF((MIN(W22:AH22))=(W1:AH17),(A1:A17),"")))

...that returns the value I'm looking for, except it's using TEXTJOIN to do so. So when I pull that number into another sheet, it isn't being recognized as a numeric value, but instead text.
Answer: Try this
=ArrayFormula(TEXTJOIN(", ",TRUE,IF((MIN(W22:AH22))=(W1:AH17),(A1:A17),""))*1)

By using *1 or +0 we turn the text value of the number to a real number.
Comment: Perfect! Amazing how simple that solution is, thank you! (Making me wait a few minutes before accepting this answer as correct, but will do)
Comment: @sebo620 I would also suggest if I may (since this is not tight to MINIMUM) to maybe changing the title to something more general like *"turning a number value to a number"*


Trying to connect to wwwroot and get a image

Question: I work in aspnet core mvc technology,
I manage to add an image, it does go to wwwroot, but the image does not display well in the browser
Example: enter image description here
enter image description here
My Controller:
 [HttpPost,ActionName("CreateAnimal")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateAnimal([FromForm] CreateAnimalViewModel model)
    {
        string wwwPath = _Environment.WebRootPath;
        string contentPath = _Environment.ContentRootPath;
        ModelState.Clear();
        model.Animal!.Category = _context.Categories.Where(c => c.CategoryId == model.Animal.CategoryId).FirstOrDefault()!;
        var path = Path.Combine(wwwPath, "Images", model.Photo!.FileName);
        if (model.Photo.Length > 0)
        {
            using var stream = new FileStream(path, FileMode.Create);
            await model.Photo.CopyToAsync(stream);
        }

        model.Animal.PhotoUrl = path;
        _context.Add(model.Animal);

        if (TryValidateModel(model))
        {

            _context.Add(model.Animal!);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Manager));
        }

        ViewBag.CategoryId = new SelectList(_context.Categories, "CategoryId", "Name");
        return View();
    }

My View:
@model IEnumerable<PetShop.Data.Models.Animal>

        @Html.DisplayNameFor(model => model.PhotoUrl)
        @Html.DisplayNameFor(model => model.Name)
        @Html.DisplayNameFor(model => model.BirthDate)
        @Html.DisplayNameFor(model => model.Description)
        @Html.DisplayNameFor(model => model.Category.Name)
        @Html.DisplayNameFor(model => model.Category)
        Edit Animel
        Delete Animel

@foreach (var item in Model!) {
            item.PhotoUrl)">

       @Html.DisplayFor(modelItem => item.Name)
       @Html.DisplayFor(modelItem => item.BirthDate)
       @Html.DisplayFor(modelItem => item.Description)
       @Html.DisplayFor(modelItem => item.Category.Name)
       @Html.DisplayFor(modelItem => item.CategoryId)

           <input type="submit" value="Edit">

           <input type="submit" value="Delete">

}
Comment: path issue... you've got a local file path in there... should be something like "localhost/images/your_file.png"?  (I use: AppContext.BaseDirectory... which is the directory where core runs, then add from there... then I use another controller to serve up files for download. ex: dl_file?id=file_id )
Answer: Below is a work demo, you can refer to it.
ProductController.cs:
   [Route("product")]
    public class ProductController : Controller
    {
        private IWebHostEnvironment webHostEnvironment;

        public ProductController(IWebHostEnvironment _webHostEnvironment)
        {
            webHostEnvironment = _webHostEnvironment;
        }

        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
                return View("Index", new Product());
        }
        [Route("save")]
        [HttpPost]
        public IActionResult Save(Product product, IFormFile photo)
        {
            if (photo == null || photo.Length == 0)
            {
                return Content("File not selected");
            }
            else
            {
                var path = Path.Combine(this.webHostEnvironment.WebRootPath, "images", photo.FileName);
                var stream = new FileStream(path, FileMode.Create);
                photo.CopyToAsync(stream);
                product.Photo = photo.FileName;
            }
            ViewBag.product = product;

                return View("Success");
        }

    }

Index.cshtml:
@model SingleFile.Models.Product

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <form asp-controller="product" asp-action="save" method="post" enctype="multipart/form-data">

                Id

                    <input type="text" asp-for="Id" />

                Name

                    <input type="text" asp-for="Name" />

                Price

                    <input type="text" asp-for="Price" />

                Photo

                    <input type="file" name="photo" />

                <input type="submit" value="Save" />

    </form>

Success.cshtml:

    <meta name="viewport" content="width=device-width" />
    <title>Success</title>

Product Info

            Id
            @ViewBag.product.Id

            Name
            @ViewBag.product.Name

            Price
            @ViewBag.product.Price

            Photo

Product
 public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Photo { get; set; }

    }

Comment: It does not work for me
I think this line in view is my problem
src = "~/firstname.lastname@example.com (modelItem => item.PhotoUrl)"
Comment: Try to use
Comment: I tried what you said it also does not work it is worse because even pictures that already exist it also does not show.
Comment: It gives me the full path and not what wwwroot @Qing Guo

C: \ Users \ danie \ OneDrive \ Desktop \ Projectss \ PetShop \ PetShop.Client \ wwwroot \ Images \ 6.png
Comment: Do you mean you can show the picture?
Comment: I can not see the image because I get the full path
Comment: For example: an image I already have in wwwroot so I get it like this:
HumiRabbit.jpg
But that I add it gives me a full path
Comment: Because you code' model.Animal.PhotoUrl = path; 'So you get full path. If you want the photo name , you should use 'model.Animal.PhotoUrl = PhotoUrl.FileName;'  .  Just like the code in my demo, I use ' product.Photo = photo.FileName;'  .
Comment: You are welcom! Glad it can help. If my answer help you resolve your issue, could you please accept as answer? If not, could you please follow up to let me know? Refer to:[How to access an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) Thanks.


ActionbarCompat not showing Action-Icons

Question: When using ActionbarCompat as Actionbar BackPort I am having the problem that action-icons do not show up - same code/res works with actionbarsherlock.
Am I doing something wrong or is this not yet supported? I am also missing the whole Menu/MenuItem getSupportMenuInflater() part that ABS has in ActionBar compat - can anyone shed some light on this?
Answer: This question was already answered in Actionbar not shown with AppCompat.
Add the following namespace to the "menu" item in your xml file
xmlns:compat="http://schemas.android.com/apk/res-auto"

Then change the "showAsAction" attribute to use the new namespace
compat:showAsAction="ifRoom"

Here's a full example with one item in the menu, with the changes on lines 2 and 6 (from Actionbar not shown with AppCompat)
<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:compat="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/action_whatever"
      android:icon="@drawable/ic_action_whatever"
      android:title="@string/whatever"
      compat:showAsAction="ifRoom"  />
</menu>

Comment: Please add the essential parts of the links as part of your answer.
Comment: Updated to include full answer and the example, as suggested by CSchulz.
Answer: When using the new ActionBarActivity, you no longer need getSupportMenuInflator. Your code should look like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

When calling invalidateOptionsMenu with ActionBarActivity you do need to use the new support version:
supportInvalidateOptionsMenu();

Those are the only two main differences between ActionBarSherlock and the new ActionBarActivity that I have found.
Comment: hm my code was looking that way, but the actions-icons did not show up
Comment: Can you post your menu xml and onCreate method? Are you extending ActionBarActivity?
Comment: really hard to extract and I am basically back to ABS where this just worked out of the box and wait for the AppCompat to mature I think before giving it another try ;-)


What is the most efficent use of karma?

Question: Simply put, what is the most efficient use of karma at level 80?
I've reached 80k karma or so, and I've been looking to turn this karma into gold profits. Most armor and weapons take far too much karma to be useful, so I've started to look into using karma for cooking. As more players raise cooking, however, I find cooking to be fairly unprofitable.
Are there are any armors or weapons that efficiently use karma?
Assuming that I have only 100k karma, how can I efficiently use this karma to benefit a level 80 character?
Comment: @DavidYell They got banned because they used a bug repeatedly that allowed them to convert karma into much more gold (like a thousandfold or something) than it was intended to.
Comment: Is your primary goal to convert karma into gold as efficiently as possible? Or are you trying to advance some character attribute?
Comment: I have no goals in mind, as I've seen very few uses for karma, so I'd swing towards gold, so that I can advance in ways I know of.
Comment: 100k Karma!?! I haven't spent any of mine and I only have 25k.
Comment: Do bear in mind that accounts got banned for converting Karma into Gold using an exploit. Karma is specifically designed to be separate from the gold economy.
Answer: There is no direct way to convert the karma into coins as all the items you trade with karma are immediately soulbound on acquire. However there are some important uses for karma.
If you ever want to level your cooking you will need to save some to buy recipe items. Although the cooking items aren't worth much on the trading post, the magic find bonus will give you better drops and the stat bonuses could effectively keep you alive when otherwise you wouldn't have. In this way you indirectly make money by not having to fix your armor. A copper saved is a copper earned.
Another important use for karma is to obtain recipes for crafting. With the exception of cooking, you need to buy recipes from all the master crafters in order to reach level 400 crafting. The crafting only reveal insignia/inscriptions up to level 350. Once you reach about level 380, all the recipes are grayed out and you can't earn any experience unless you use the recipes from the master crafter that you need karma to buy.
You can use it to buy armor and weapons and accessories from karma traders around the world to supplement your gear if any of them fall behind.
Please note that you should not use your karma to buy cultural weapons. The cultural weapons do not go towards any title and is only rare not exotic so it is not max stat. Since they cost 63k each, it is not an effective way to spend karma.
However outside the Gate of Arah, you are able to buy maxed Exotic Armor pieces for 42k karma a piece. I find this the most effective way to spend your karma. As of now, a piece of Exotic armor is equivalent to about 2.5g gold coins. If you save up the karma you can buy a complete exotic armor set and save about 15g you would otherwise have to directly spend.
Comment: I've attempted making a profit of the first two points, with mixed success. Is the Gate of Arah armor part of a set (with a rune attached)? I'm already able to buy a maxed set with gold, since I doubt I'll earn that amount of karma before farming CoF enough times.
Comment: While cultural weapons are "only" rares, they are bought for the skins. For example, i love the skins of the sereph longbow and greatsword, so that is where i spend my karma.
Comment: @TerryChia while I agree with that, the OP is asking the most cost effective way to use karma. And gold weapons are worth much less in coins for more of a karma cost.
Comment: Upvote for buying Temple Karma Vendor armour items.
Answer: It depends on your current equip. If you got already an full exotic armor,  you can spend the karma for obsidian shards. You can use these obsidian shards to create rare crafting materials at the mystic forge.
If you still need an exotic armor, you should spend your karma for the orr armor pieces.
Answer: You need somewhere between 500k and 1mil karma per legendary weapon creation.  That's what you should be saving every single penny for.  For the armor, you should just buy a traveler's... lvl 79 set for the magic find and forget getting a lvl 80 exotic set all together until you have that legendary unless you plan on WvWing.  Of course my advice is from someone who cares much more about how his weapon looks than his armor.  You might be different.
Comment: Considering that I play Ranger, with a sweet looking short bow, I'd prefer not to go for a legendary that shoots flowers. Also, the stats on the legendary are the same as an exotic, which makes it completely useless.
Answer: There are ways to convert karma into gold.
You can buy Masterwork items from karma vendors such as Cachistic Gloves from Scholar Merla, forge them in the Mystic Forge and then receive Rare Items (so you can sell them on the Trading Post or salvage them), as you can check in this Karma to gold Experiment. The rate would be something like 1k karma = 3.4silver.
But, as in 28 January patch, players are able to buy Lost Orrian Jewelry Boxes for 4.5k karma each from Orr karma vendors, opening it may gives you karma liquids, lodestones and unidentifiable object.
According to this post, buying Lost Orrian Jewerly boxes is way more profitable (Like 80% more).

What is the most efficent use of karma?


How can I minimise damage to a moldy patch of plywood?

Question: I removed a waterproof camping bag in my student appartment today that's been filled with stuff to find that it has left a moldy spot on the untreated plywood it stood on. It's been parked up right next the door/window.
I guess the damage has already been done since I think the white stuff may be mold, but is there anything I can do to minimise any further harm?
(It's darker than it looks in the picture)
Answer: A dilute solution of bleach sprayed on it will kill and neutralize the mold. Then wire brush the damaged spot. If you want to prevent this later, seal the plywood with something, primer or polyurethane.
(While bleach contains chlorine which is not good for you, the chlorine is volatile and quickly evaporates. It is typically used by brewers to sterilize equipment for this reason.)
Answer: Put hydrogen peroxide on it, let it sit for a bit and scrub it. Repeat if needed.
Bleach works well on solid surfaces like cinder block, but not porous like wood.
Or, could you replace the piece of wood?
Comment: Bleach is actually more harmful than most of the molds. You can also just use soapy hot water. Damp the mold / area to keep the dust down. Then scrape it and get rid of the mold. Then for the leftover use hydrogen peroxide. A small amount should be good. Make sure the area is well ventilated to the outside. You should also seal off the room so the mold does not go to other areas.
Comment: Cinder block is porous.


I can not control Banshee from the sound menu in Gnome 3 Shell

Question: I am running Gnome 3.2 on Ubuntu 11.10.
In Banshee, I have 'Show Banshee in Sound menu' enabled in Edit-Preferences.
MPRIS D-Bus Integration and Sound Menu Integration extensions are also enabled.
Still, there is no Banshee on the sound menu.
What is missing?
Thanks in advance.
Answer: Banshee's Sound Menu extension is specifically for Ubuntu's sound menu.
Banshee doesn't currently make use of the playback controls in Gnome Shell's message tray and notifications.  That feature is Bug 645628 if you're interested in following the progress.
However, as Gamx points out below, even if this isn't possible out-of-the-box with Banshee, there are third-party solutions.
Webupd8's PPA provides a gnome-shell-extensions-mediaplayer extension that allows you to control various media players -- including Banshee -- using the controls in Gnome Shell.  To learn more about Personal Package Archives, see this question on Ask Ubuntu.  To install the Gnome-shell extension, in terminal type:
sudo add-apt-repository ppa:webupd8team/gnome3
sudo apt-get update
sudo apt-get install gnome-shell-extensions-mediaplayer

Comment: Does not work in 17.10: "E: The repository 'http://ppa.launchpad.net/webupd8team/gnome3/ubuntu artful Release' does not have a Release file."
Comment: @GlenPeterson this is a very old question/answer. You shouldn't need a special plugin or PPA anymore. I'm pretty sure Gnome tray integration was added to Banshee several years ago.
Comment: It's in the Notification Area in Ubuntu 17.10.  I just didn't know to click on the time/date to see it.  Thanks!
Comment: Ah, I see. I haven't updated to 17.10 (and actually, it's been a few years since I've used Banshee). Good luck.
Comment: What are you using instead of Banshee?
Comment: I ended up moving my collection to Google Music, but sometimes I miss having a local app.
Answer: I may have misunderstood your question, but in gnome-shell you can have something very similar to the Sound Menu in Unity. Simply install gnome-shell-extensions-mediaplayer. You can find instructions here
http://www.webupd8.org/2011/10/gnome-shell-mediaplayer-extension.html