qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
25,733,955
``` valid = {'Temp': [10, 55], 'rain_percent': [49, 100], 'humidity': [30,50]} data = {'Temp': 30.45, 'rain_percent': 80.56 } min_temp , max_temp = valid['Temp'] if not(min_temp <= data['Temp'] <= max_temp): print "Bad Temp" min_rain , max_rain = valid['rain_percent'] if not(min_rain <= data['rain_percent'] <= max_rain): print "It's not going to rain" ``` This is what I'm doing with the 2 dictionarties I'm having. I know that this check can be further modified. Since both the dictionaries i.e `valid` and `data` have the same `keys`, there must be some better way of implementing this check. Can anyone help me in this? Thanks a lot.
2014/09/08
[ "https://Stackoverflow.com/questions/25733955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012241/" ]
This can be achieved by using the multiprocessing module in python, please find the code below ``` #!/usr/bin/python from multiprocessing import Process,Queue import random import time def printrand(): #Checks whether Queue is empty and runs while q.empty(): rand = random.choice(range(1,100)) time.sleep(1) print rand if __name__ == "__main__": #Queue is a data structure used to communicate between process q = Queue() #creating the process p = Process(target=printrand) #starting the process p.start() while True: ip = raw_input("Write something: ") #if user enters stop the while loop breaks if ip=="stop": #Populating the queue so that printramd can read and quit the loop q.put(ip) break #Block the calling thread until the process whose join() #method is called terminates or until the optional timeout occurs. p.join() ```
To wait for input and to display some random output at the same time, you could use a GUI ([something with an event loop](https://stackoverflow.com/a/14040516/4279)): ![screenshot](https://i.stack.imgur.com/1nBkg.png) ``` #!/usr/bin/env python3 import random from tkinter import E, END, N, S, scrolledtext, Tk, ttk, W class App: password = "123456" # the most common password def __init__(self, master): self.master = master self.master.title('To stop, type: ' + self.password) # content frame (padding, etc) frame = ttk.Frame(master, padding="3 3 3 3") frame.grid(column=0, row=0, sticky=(N, W, E, S)) # an area where random messages to appear self.textarea = scrolledtext.ScrolledText(frame) # an area where the password to be typed textfield = ttk.Entry(frame) # put one on top of the other self.textarea.grid(row=0) textfield.grid(row=1, sticky=(E, W)) textfield.bind('<KeyRelease>', self.check_password) textfield.focus() # put cursor into the entry self.update_textarea() def update_textarea(self): # insert random Unicode codepoint in U+0000-U+FFFF range character = chr(random.choice(range(0xffff))) self.textarea.configure(state='normal') # enable insert self.textarea.insert(END, character) self.textarea.configure(state='disabled') # disable editing self.master.after(10, self.update_textarea) # in 10 milliseconds def check_password(self, event): if self.password in event.widget.get(): self.master.destroy() # exit GUI App(Tk()).master.mainloop() ```
25,733,955
``` valid = {'Temp': [10, 55], 'rain_percent': [49, 100], 'humidity': [30,50]} data = {'Temp': 30.45, 'rain_percent': 80.56 } min_temp , max_temp = valid['Temp'] if not(min_temp <= data['Temp'] <= max_temp): print "Bad Temp" min_rain , max_rain = valid['rain_percent'] if not(min_rain <= data['rain_percent'] <= max_rain): print "It's not going to rain" ``` This is what I'm doing with the 2 dictionarties I'm having. I know that this check can be further modified. Since both the dictionaries i.e `valid` and `data` have the same `keys`, there must be some better way of implementing this check. Can anyone help me in this? Thanks a lot.
2014/09/08
[ "https://Stackoverflow.com/questions/25733955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012241/" ]
This can be achieved by using the multiprocessing module in python, please find the code below ``` #!/usr/bin/python from multiprocessing import Process,Queue import random import time def printrand(): #Checks whether Queue is empty and runs while q.empty(): rand = random.choice(range(1,100)) time.sleep(1) print rand if __name__ == "__main__": #Queue is a data structure used to communicate between process q = Queue() #creating the process p = Process(target=printrand) #starting the process p.start() while True: ip = raw_input("Write something: ") #if user enters stop the while loop breaks if ip=="stop": #Populating the queue so that printramd can read and quit the loop q.put(ip) break #Block the calling thread until the process whose join() #method is called terminates or until the optional timeout occurs. p.join() ```
> > I want to be able to input words in the console while, at the same time, have random numbers appear in the console. > > > ``` #!/usr/bin/env python import random def print_random(n=10): print(random.randrange(n)) # print random number in the range(0, n) stop = call_repeatedly(1, print_random) # print random number every second while True: word = raw_input("Write something: ") # ask for input until "quit" if word == "quit": stop() # stop printing random numbers break # quit ``` where [`call_repeatedly()` is define here](https://stackoverflow.com/a/22498708/4279). `call_repeatedly()` uses a separate thread to call `print_random()` function repeatedly.
25,733,955
``` valid = {'Temp': [10, 55], 'rain_percent': [49, 100], 'humidity': [30,50]} data = {'Temp': 30.45, 'rain_percent': 80.56 } min_temp , max_temp = valid['Temp'] if not(min_temp <= data['Temp'] <= max_temp): print "Bad Temp" min_rain , max_rain = valid['rain_percent'] if not(min_rain <= data['rain_percent'] <= max_rain): print "It's not going to rain" ``` This is what I'm doing with the 2 dictionarties I'm having. I know that this check can be further modified. Since both the dictionaries i.e `valid` and `data` have the same `keys`, there must be some better way of implementing this check. Can anyone help me in this? Thanks a lot.
2014/09/08
[ "https://Stackoverflow.com/questions/25733955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012241/" ]
This can be achieved by using the multiprocessing module in python, please find the code below ``` #!/usr/bin/python from multiprocessing import Process,Queue import random import time def printrand(): #Checks whether Queue is empty and runs while q.empty(): rand = random.choice(range(1,100)) time.sleep(1) print rand if __name__ == "__main__": #Queue is a data structure used to communicate between process q = Queue() #creating the process p = Process(target=printrand) #starting the process p.start() while True: ip = raw_input("Write something: ") #if user enters stop the while loop breaks if ip=="stop": #Populating the queue so that printramd can read and quit the loop q.put(ip) break #Block the calling thread until the process whose join() #method is called terminates or until the optional timeout occurs. p.join() ```
you have to run two concurrent threads at the same time in order to get rid of such blocking. looks like there are two interpreters that run your code and each of them executes particular section of your project.
65,248,280
I have a list of strings `(["A", "B", ...])` and a list of sizes `([4,7,...])`. I would like to sample without replacement from the set of strings where initially string in position `i` appears `sizes[i]` times. I have to perform this operation `k` times. Clearly, if I pick string `i`, then `sizes[i]` decreases by 1. The current naive solution that I developed is to generate the entire input set, shuffle it, and iteratively pop the first element of the array. This is clearly inefficient since if a string appears 1 million times I would have to generate 1 million entries. ``` public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Collections.shuffle(bag); for (int i = 0; i < k; i++) { System.out.println(bag.remove(0)); } } ``` Is there a better and more efficient way to perform this operation? Thanks.
2020/12/11
[ "https://Stackoverflow.com/questions/65248280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677697/" ]
Assuming the bag doesn't have to be persistent or be used at all you could create a class that contains input and frequency, e.g. like this (simplified): ``` class SampleElement<T> { private T value; private int frequency; //constructors, getters, setters } ``` Then build a collection of those elements from the input you have, e.g. (again simplified): ``` List<SampleElement<String>> samples = Arrays.asList(new SampleElement<String>("A",10), ...); ``` Finally loop until that collection is empty or you've done it `k` times and pick a random element. Decrease that element's frequency and if it hits 0 you remove it from the collection. Example (off the top of my head so might contain errors): ``` Random rand = new Random(); int runs = k; while(runs > 0 && !samples.isEmpty() ) { runs--; int index = rand.nextInt(samples.size()); SampleElement<String> element = samples.get(index); System.out.println(element.getValue()); element.decrementFrequency(); if( element.getFrequency() <= 0 ) { samples.remove(index); } } ```
You can collect these two arrays into a map: ```java String[] elems = {"A", "B", "C", "D", "E"}; Integer[] sizes = {10, 5, 4, 7, 3}; Map<String, Integer> map = IntStream.range(0, elems.length).boxed() .collect(Collectors.toMap(i -> elems[i], i -> sizes[i])); System.out.println(map); // {A=10, B=5, C=4, D=7, E=3} ```
65,248,280
I have a list of strings `(["A", "B", ...])` and a list of sizes `([4,7,...])`. I would like to sample without replacement from the set of strings where initially string in position `i` appears `sizes[i]` times. I have to perform this operation `k` times. Clearly, if I pick string `i`, then `sizes[i]` decreases by 1. The current naive solution that I developed is to generate the entire input set, shuffle it, and iteratively pop the first element of the array. This is clearly inefficient since if a string appears 1 million times I would have to generate 1 million entries. ``` public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Collections.shuffle(bag); for (int i = 0; i < k; i++) { System.out.println(bag.remove(0)); } } ``` Is there a better and more efficient way to perform this operation? Thanks.
2020/12/11
[ "https://Stackoverflow.com/questions/65248280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677697/" ]
Assuming the bag doesn't have to be persistent or be used at all you could create a class that contains input and frequency, e.g. like this (simplified): ``` class SampleElement<T> { private T value; private int frequency; //constructors, getters, setters } ``` Then build a collection of those elements from the input you have, e.g. (again simplified): ``` List<SampleElement<String>> samples = Arrays.asList(new SampleElement<String>("A",10), ...); ``` Finally loop until that collection is empty or you've done it `k` times and pick a random element. Decrease that element's frequency and if it hits 0 you remove it from the collection. Example (off the top of my head so might contain errors): ``` Random rand = new Random(); int runs = k; while(runs > 0 && !samples.isEmpty() ) { runs--; int index = rand.nextInt(samples.size()); SampleElement<String> element = samples.get(index); System.out.println(element.getValue()); element.decrementFrequency(); if( element.getFrequency() <= 0 ) { samples.remove(index); } } ```
Assuming that the lengths of these two arrays are the same, you can create *a list of map entries* containing pairs of elements from these arrays, and shuffle this list: ```java String[] elems = {"A", "B", "C", "D", "E"}; Integer[] sizes = {10, 5, 4, 7, 3}; List<Map.Entry<String, Integer>> bag = IntStream .range(0, elems.length) .mapToObj(i -> Map.of(elems[i], sizes[i])) .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toList()); System.out.println(bag); // [A=10, B=5, C=4, D=7, E=3] Collections.shuffle(bag); System.out.println(bag); // [D=7, C=4, E=3, A=10, B=5] ``` --- See also: [How to sort an array with respect to another array if there are duplicates?](https://stackoverflow.com/a/65464525/14838237)
65,248,280
I have a list of strings `(["A", "B", ...])` and a list of sizes `([4,7,...])`. I would like to sample without replacement from the set of strings where initially string in position `i` appears `sizes[i]` times. I have to perform this operation `k` times. Clearly, if I pick string `i`, then `sizes[i]` decreases by 1. The current naive solution that I developed is to generate the entire input set, shuffle it, and iteratively pop the first element of the array. This is clearly inefficient since if a string appears 1 million times I would have to generate 1 million entries. ``` public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Collections.shuffle(bag); for (int i = 0; i < k; i++) { System.out.println(bag.remove(0)); } } ``` Is there a better and more efficient way to perform this operation? Thanks.
2020/12/11
[ "https://Stackoverflow.com/questions/65248280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677697/" ]
Assuming the bag doesn't have to be persistent or be used at all you could create a class that contains input and frequency, e.g. like this (simplified): ``` class SampleElement<T> { private T value; private int frequency; //constructors, getters, setters } ``` Then build a collection of those elements from the input you have, e.g. (again simplified): ``` List<SampleElement<String>> samples = Arrays.asList(new SampleElement<String>("A",10), ...); ``` Finally loop until that collection is empty or you've done it `k` times and pick a random element. Decrease that element's frequency and if it hits 0 you remove it from the collection. Example (off the top of my head so might contain errors): ``` Random rand = new Random(); int runs = k; while(runs > 0 && !samples.isEmpty() ) { runs--; int index = rand.nextInt(samples.size()); SampleElement<String> element = samples.get(index); System.out.println(element.getValue()); element.decrementFrequency(); if( element.getFrequency() <= 0 ) { samples.remove(index); } } ```
If all you want is get a random element from `bag`, you do not need to shuffle `bag`. You can use [`Random#nextInt(elems.length * sizes.length)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) to get a random `int` from `0` to `elems.length * sizes.length - 1` and using this `int` as the index, you can get an element from `bag`. **Demo:** ``` import java.util.ArrayList; import java.util.Random; public class Main { public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Random random = new Random(); int count = elems.length * sizes.length; for (int i = 0; i < k; i++) { System.out.println(bag.get(random.nextInt(count))); } } } ```
65,248,280
I have a list of strings `(["A", "B", ...])` and a list of sizes `([4,7,...])`. I would like to sample without replacement from the set of strings where initially string in position `i` appears `sizes[i]` times. I have to perform this operation `k` times. Clearly, if I pick string `i`, then `sizes[i]` decreases by 1. The current naive solution that I developed is to generate the entire input set, shuffle it, and iteratively pop the first element of the array. This is clearly inefficient since if a string appears 1 million times I would have to generate 1 million entries. ``` public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Collections.shuffle(bag); for (int i = 0; i < k; i++) { System.out.println(bag.remove(0)); } } ``` Is there a better and more efficient way to perform this operation? Thanks.
2020/12/11
[ "https://Stackoverflow.com/questions/65248280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677697/" ]
You can collect these two arrays into a map: ```java String[] elems = {"A", "B", "C", "D", "E"}; Integer[] sizes = {10, 5, 4, 7, 3}; Map<String, Integer> map = IntStream.range(0, elems.length).boxed() .collect(Collectors.toMap(i -> elems[i], i -> sizes[i])); System.out.println(map); // {A=10, B=5, C=4, D=7, E=3} ```
Assuming that the lengths of these two arrays are the same, you can create *a list of map entries* containing pairs of elements from these arrays, and shuffle this list: ```java String[] elems = {"A", "B", "C", "D", "E"}; Integer[] sizes = {10, 5, 4, 7, 3}; List<Map.Entry<String, Integer>> bag = IntStream .range(0, elems.length) .mapToObj(i -> Map.of(elems[i], sizes[i])) .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toList()); System.out.println(bag); // [A=10, B=5, C=4, D=7, E=3] Collections.shuffle(bag); System.out.println(bag); // [D=7, C=4, E=3, A=10, B=5] ``` --- See also: [How to sort an array with respect to another array if there are duplicates?](https://stackoverflow.com/a/65464525/14838237)
65,248,280
I have a list of strings `(["A", "B", ...])` and a list of sizes `([4,7,...])`. I would like to sample without replacement from the set of strings where initially string in position `i` appears `sizes[i]` times. I have to perform this operation `k` times. Clearly, if I pick string `i`, then `sizes[i]` decreases by 1. The current naive solution that I developed is to generate the entire input set, shuffle it, and iteratively pop the first element of the array. This is clearly inefficient since if a string appears 1 million times I would have to generate 1 million entries. ``` public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Collections.shuffle(bag); for (int i = 0; i < k; i++) { System.out.println(bag.remove(0)); } } ``` Is there a better and more efficient way to perform this operation? Thanks.
2020/12/11
[ "https://Stackoverflow.com/questions/65248280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677697/" ]
You can collect these two arrays into a map: ```java String[] elems = {"A", "B", "C", "D", "E"}; Integer[] sizes = {10, 5, 4, 7, 3}; Map<String, Integer> map = IntStream.range(0, elems.length).boxed() .collect(Collectors.toMap(i -> elems[i], i -> sizes[i])); System.out.println(map); // {A=10, B=5, C=4, D=7, E=3} ```
If all you want is get a random element from `bag`, you do not need to shuffle `bag`. You can use [`Random#nextInt(elems.length * sizes.length)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) to get a random `int` from `0` to `elems.length * sizes.length - 1` and using this `int` as the index, you can get an element from `bag`. **Demo:** ``` import java.util.ArrayList; import java.util.Random; public class Main { public static void main(String[] args) { String[] elems = { "A", "B", "C", "D", "E" }; Integer[] sizes = { 10, 5, 4, 7, 3 }; int k = 3; ArrayList<String> bag = new ArrayList<>(); for (int i = 0; i < elems.length; i++) { for (int j = 0; j < sizes[i]; j++) { bag.add(elems[i]); } } Random random = new Random(); int count = elems.length * sizes.length; for (int i = 0; i < k; i++) { System.out.println(bag.get(random.nextInt(count))); } } } ```
40,032,387
``` svm_node n=new svm_node(); for (String tk:instance.keySet()){ System.out.println(tk + " "+ instance.get(tk)); if(IndexDic.containsKey(tk)){ n.index=(IndexDic.get(tk)); n.value=instance.get(tk); nodes.add(n); } else{ System.out.println("does not contain"+tk); } } ``` I have the above code. After I output the nodes value on to console or check using debugger all elements have same value. That is, all n in nodes have same values. What can I do to deal with hat?
2016/10/13
[ "https://Stackoverflow.com/questions/40032387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You were adding the same `svm_node` object to the collection over and over again. To fix this, move the instantiation of the `svm_node` to inside the loop: ``` for (String tk:instance.keySet()) { svm_node n=new svm_node(); System.out.println(tk + " "+ instance.get(tk)); if (IndexDic.containsKey(tk)) { n.index = (IndexDic.get(tk)); n.value = instance.get(tk); nodes.add(n); } else { System.out.println("does not contain"+tk); } } ```
You should call `svm_node n = new svm_node()` inside the for-Loop. Otherwise, the same Node will be overwritten!
5,823,141
Can anyone tell me if there's a Rail3 replacement for something like this: ``` <%= unless @page.new_record? || !@page.background_image? %> bla <% end %> ``` I'm trying to display a checkbox on a form only when a user edits. Not when they create.
2011/04/28
[ "https://Stackoverflow.com/questions/5823141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641439/" ]
I think the statement is ok, but should not be included in your view. Instead, create a model method, probably named is\_editable? or something, that includes this statement. Then get an instance variable in your controller and use that instead. Logic in views is a very bad idea :)
You can write it like this: ``` <%= "bla" unless @page.new_record? || !@page.background_image? %> ``` May be you should write separate method with more human-readable name and replace this condition with one method. Try to keep your view as much cleaner as possible
5,823,141
Can anyone tell me if there's a Rail3 replacement for something like this: ``` <%= unless @page.new_record? || !@page.background_image? %> bla <% end %> ``` I'm trying to display a checkbox on a form only when a user edits. Not when they create.
2011/04/28
[ "https://Stackoverflow.com/questions/5823141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641439/" ]
Your mistake is including the = in the ruby code. ``` <% unless @page.new_record? || !@page.background_image? %> bla <% end %> ``` However, as other users have stated, it is probably better to hide this logic in the model rather than in the view. Additionally it considered a best practice to only use unless if there is only one boolean statement. It starts to get harder and harder to read when you have ors and nots included there. ``` <% if @page.is_editable %> blah <% end %> ``` This would be a nicer version, and even better than that (depending on how complicated 'blah' is) would be to hide the whole thing in a helper method. ``` <%= some_special_checkbox(f) %> ``` The parameter f would be the form object so that your helper can render the checkbox for the form.
You can write it like this: ``` <%= "bla" unless @page.new_record? || !@page.background_image? %> ``` May be you should write separate method with more human-readable name and replace this condition with one method. Try to keep your view as much cleaner as possible
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
[Mint](http://haveamint.com/) by Shaun Inman had 'required' labels in the form: ![enter image description here](https://i.stack.imgur.com/dp9Ad.gif) Instead of 'Required' labels you could have 'Wildcard' labels
I often see option symbols in Pizza menus: ![enter image description here](https://i.stack.imgur.com/zKP4X.png) Pepper sign here means "extra spicy" (or even several signs with different number of peppers to visualize different stages), there also may be a "vegetarian" sign, etc. And at the end of the every page of the menu there is a legend describing every sign. So, I think that it's okey to use non-standard symbols which will allow your users to quickly identify different types of inputs and understand how they're working, just don't forget to describe them these signs somehow: ![enter image description here](https://i.stack.imgur.com/kak7T.jpg)
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
[Mint](http://haveamint.com/) by Shaun Inman had 'required' labels in the form: ![enter image description here](https://i.stack.imgur.com/dp9Ad.gif) Instead of 'Required' labels you could have 'Wildcard' labels
1. It looks like *all* your fields allow wildcards. Except Middle Initial, so why not make it support them as well? 2. Also, do your users **really** make use of wildcard capabilities? Have they demonstrated a need for such? In my experience, substring match is usually sufficient, and in fact people expect substring matching. 3. Then, put a banner message above the fields: *"These fields support [[wildcards]]."* (with a hyperlink to usage information) Or quick instructions: *"Fields will also match substrings (e.g., 'Sam\*' will match 'Sam', 'Samantha', and 'Samuel')."*
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
[Mint](http://haveamint.com/) by Shaun Inman had 'required' labels in the form: ![enter image description here](https://i.stack.imgur.com/dp9Ad.gif) Instead of 'Required' labels you could have 'Wildcard' labels
It's a good idea to keep the \* for required fields and if you don't want to clutter the UI you could add an extra label inside the 'wildcard' fields with example of accepted characters.
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
I often see option symbols in Pizza menus: ![enter image description here](https://i.stack.imgur.com/zKP4X.png) Pepper sign here means "extra spicy" (or even several signs with different number of peppers to visualize different stages), there also may be a "vegetarian" sign, etc. And at the end of the every page of the menu there is a legend describing every sign. So, I think that it's okey to use non-standard symbols which will allow your users to quickly identify different types of inputs and understand how they're working, just don't forget to describe them these signs somehow: ![enter image description here](https://i.stack.imgur.com/kak7T.jpg)
1. It looks like *all* your fields allow wildcards. Except Middle Initial, so why not make it support them as well? 2. Also, do your users **really** make use of wildcard capabilities? Have they demonstrated a need for such? In my experience, substring match is usually sufficient, and in fact people expect substring matching. 3. Then, put a banner message above the fields: *"These fields support [[wildcards]]."* (with a hyperlink to usage information) Or quick instructions: *"Fields will also match substrings (e.g., 'Sam\*' will match 'Sam', 'Samantha', and 'Samuel')."*
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
Putting a small label "wildcard" with a mouseover tooltip indicating that "this text box accepts wildcard characters" could be a solution. You can put this label above on the left of the text box or, if your text box title is to large, below.
1. It looks like *all* your fields allow wildcards. Except Middle Initial, so why not make it support them as well? 2. Also, do your users **really** make use of wildcard capabilities? Have they demonstrated a need for such? In my experience, substring match is usually sufficient, and in fact people expect substring matching. 3. Then, put a banner message above the fields: *"These fields support [[wildcards]]."* (with a hyperlink to usage information) Or quick instructions: *"Fields will also match substrings (e.g., 'Sam\*' will match 'Sam', 'Samantha', and 'Samuel')."*
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
icc97 beat me using the image I was going to use :) but considering the use case that some fields can be required and also support wild card charecters, I would recommmend using a combination of both the \* and the required tag as shown in the example used by icc97 ![enter image description here](https://i.stack.imgur.com/x8cS0.gif) So your screen would look like this ![enter image description here](https://i.stack.imgur.com/CBaqH.jpg) The required tag label can be used to denote when a field is required and the asterisk can be used to denote that a wildcard is accepted in the text entry. The asterisk off-course must be denoted in in a legend below. With regards to the positioning of the asterisk I recommend looking at this article [\* Is This A Required Field?](http://www.leemunroe.com/required-fields/) and the article [The UX of Required Fields](http://www.leemunroe.com/required-fields/) I also recommend looking at this excellent question [What's the best way to highlight a Required field on a web form before submission?](https://ux.stackexchange.com/questions/840/whats-the-best-way-to-highlight-a-required-field-on-a-web-form-before-submissio/846#846) to get additional inputs on how to position the asterisk and highlight a legend
1. It looks like *all* your fields allow wildcards. Except Middle Initial, so why not make it support them as well? 2. Also, do your users **really** make use of wildcard capabilities? Have they demonstrated a need for such? In my experience, substring match is usually sufficient, and in fact people expect substring matching. 3. Then, put a banner message above the fields: *"These fields support [[wildcards]]."* (with a hyperlink to usage information) Or quick instructions: *"Fields will also match substrings (e.g., 'Sam\*' will match 'Sam', 'Samantha', and 'Samuel')."*
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
[Mint](http://haveamint.com/) by Shaun Inman had 'required' labels in the form: ![enter image description here](https://i.stack.imgur.com/dp9Ad.gif) Instead of 'Required' labels you could have 'Wildcard' labels
icc97 beat me using the image I was going to use :) but considering the use case that some fields can be required and also support wild card charecters, I would recommmend using a combination of both the \* and the required tag as shown in the example used by icc97 ![enter image description here](https://i.stack.imgur.com/x8cS0.gif) So your screen would look like this ![enter image description here](https://i.stack.imgur.com/CBaqH.jpg) The required tag label can be used to denote when a field is required and the asterisk can be used to denote that a wildcard is accepted in the text entry. The asterisk off-course must be denoted in in a legend below. With regards to the positioning of the asterisk I recommend looking at this article [\* Is This A Required Field?](http://www.leemunroe.com/required-fields/) and the article [The UX of Required Fields](http://www.leemunroe.com/required-fields/) I also recommend looking at this excellent question [What's the best way to highlight a Required field on a web form before submission?](https://ux.stackexchange.com/questions/840/whats-the-best-way-to-highlight-a-required-field-on-a-web-form-before-submissio/846#846) to get additional inputs on how to position the asterisk and highlight a legend
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
I often see option symbols in Pizza menus: ![enter image description here](https://i.stack.imgur.com/zKP4X.png) Pepper sign here means "extra spicy" (or even several signs with different number of peppers to visualize different stages), there also may be a "vegetarian" sign, etc. And at the end of the every page of the menu there is a legend describing every sign. So, I think that it's okey to use non-standard symbols which will allow your users to quickly identify different types of inputs and understand how they're working, just don't forget to describe them these signs somehow: ![enter image description here](https://i.stack.imgur.com/kak7T.jpg)
It's a good idea to keep the \* for required fields and if you don't want to clutter the UI you could add an extra label inside the 'wildcard' fields with example of accepted characters.
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
Putting a small label "wildcard" with a mouseover tooltip indicating that "this text box accepts wildcard characters" could be a solution. You can put this label above on the left of the text box or, if your text box title is to large, below.
It's a good idea to keep the \* for required fields and if you don't want to clutter the UI you could add an extra label inside the 'wildcard' fields with example of accepted characters.
31,541
Everyone most web users understand that the asterisk (\*) indicates that the fields on a form are required. But what about non-standard symbols? Our UX team is currently working with an application dev group where there is a need to flag special functionality related to specific text boxes. In this particular case, this new flag would indicate that the related text box accepts wild card characters. Mockup Example: ![mockup](https://i.stack.imgur.com/eVTM9.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2feVTM9.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) What would be the best way to indicate special functionality that is related to a particular set field(s)?
2013/01/08
[ "https://ux.stackexchange.com/questions/31541", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/7450/" ]
Why flag for where something is allowed, instead of flagging when something erroneous is entered: ![mockup](https://i.stack.imgur.com/mll0z.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fmll0z.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) As @mervin points out below, different functionalities of the different types of fields should be visualized. "Special functionality" though, as the OP describes it, is hard to visualize. The problem needs to be either written out in text, or resolved, for example by finding a way to let all the input fields have the same functionality.
1. It looks like *all* your fields allow wildcards. Except Middle Initial, so why not make it support them as well? 2. Also, do your users **really** make use of wildcard capabilities? Have they demonstrated a need for such? In my experience, substring match is usually sufficient, and in fact people expect substring matching. 3. Then, put a banner message above the fields: *"These fields support [[wildcards]]."* (with a hyperlink to usage information) Or quick instructions: *"Fields will also match substrings (e.g., 'Sam\*' will match 'Sam', 'Samantha', and 'Samuel')."*
433,844
How can I save values (states) to be used on a second pass compilation? For example, look at this simple example: ``` \definecounter[foox] \setcounter[foox][1] \definestartstop [foo] [before={\textrule[top]{Foo: \rawcountervalue[foox]}}, after={\incrementcounter[foox]}] \starttext Total of Foos: \rawcountervalue[foox] \startfoo \stopfoo \startfoo \stopfoo \startfoo \stopfoo \stoptext ``` How can I make `Total of Foos:` print 3? Of course I don't want to be counting the amount of `startfoo ... stopfoo` manually In latex, `\immediate\write` seems to do the trick **EDITED** As a bonus, is there any way to save marks on text to be used later? For example (using an hypothetical command `\setmark`): ``` \startfoo \setmark{x} \stopfoo ... ``` where the values in `\setmark{...}` could be used early? ``` \definecounter[foox] \setcounter[foox][1] \definestartstop [foo] [before={\textrule[top]{Foo: \rawcountervalue[foox]}}, after={\incrementcounter[foox]}] \starttext Total of Foos: % those marks where retrieved from the text Foo 1 -> mark1 Foo 2 -> mark2 Foo 3 -> mark3 \startfoo \setmark{mark1} \stopfoo \startfoo \setmark{mark2} \stopfoo \startfoo \setmark{mark3} \stopfoo \stoptext ``` I hope I make this clear enough.
2018/05/28
[ "https://tex.stackexchange.com/questions/433844", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/163632/" ]
All counters which are created with `\definecounter` are stored in the auxiliary file and ConTeXt already provides commands to access the last value it. If you just want to print the last value in your document you can use `type=last` in the second argument of `\convertedcounter`. ``` \definecounter [amadeus] \startbuffer [amadeus] \starttabulate[|l|l|][before=,after=] \NC First value \EQ \convertedcounter [amadeus] [type=first] \NC\NR \NC Previous value \EQ \convertedcounter [amadeus] [type=previous] \NC\NR \NC Current value \EQ \convertedcounter [amadeus] \NC\NR % \convertedcounter [amadeus] [type=number] \NC Next value \EQ \convertedcounter [amadeus] [type=next] \NC\NR \NC Last value \EQ \convertedcounter [amadeus] [type=last] \NC\NR \stoptabulate \stopbuffer \define\ShowAmadeus {\incrementcounter[amadeus] \starttextrule{Amadeus \convertedcounter [amadeus]} \getbuffer[amadeus] \stoptextrule} \starttext \dorecurse{5}{\ShowAmadeus} \stoptext ``` [![Printing the first and last values of a counter](https://i.stack.imgur.com/e3adr.png)](https://i.stack.imgur.com/e3adr.png) If you want to use these values to with calculations (e.g. with `\numexpr`) you have to use the following commands with give you the raw values of the counter which means no formatting or conversion is applied to them. ``` \definecounter [amadeus] \startbuffer [amadeus] \starttabulate[|l|l|][before=,after=] \NC First value \EQ \firstcountervalue [amadeus] \NC\NR \NC Previous value \EQ \prevcountervalue [amadeus] \NC\NR \NC Current value \EQ \rawcountervalue [amadeus] \NC\NR \NC Next value \EQ \nextcountervalue [amadeus] \NC\NR \NC Last value \EQ \lastcountervalue [amadeus] \NC\NR \stoptabulate \stopbuffer \define\ShowAmadeus {\incrementcounter[amadeus] \starttextrule{Amadeus \convertedcounter [amadeus]} \getbuffer[amadeus] \stoptextrule} \starttext \dorecurse{5}{\ShowAmadeus} \stoptext ```
After the comment of @Metafox, and after I found these links: [Storing and retrieving data in tuc file](https://tex.stackexchange.com/questions/52067/storing-and-retrieving-data-in-tuc-file) and [System Macros/Key Value Assignments](http://wiki.contextgarden.net/System_Macros/Key_Value_Assignments#Multi-pass_data) I derived a solution from the problem, which stores the states in the .tuc file: ``` \definecounter[foox] \setcounter[foox][1] \definedataset[foo] \setdataset[foo][total={\lastcountervalue[foox]}] \define[1]\SetMark{ \setdataset[foo][pos={\rawcountervalue[foox]}, mark={#1}] } \definestartstop [foo] [before={\textrule[top]{Foo: \rawcountervalue[foox]}}, after={\incrementcounter[foox]}] \starttext Total of Foos: \dostepwiserecurse{2}{\datasetvariable{foo}{1}{total}}{1} {Foo \datasetvariable{foo}{\recurselevel}{pos} -> \datasetvariable{foo}{\recurselevel}{mark}\blank} \startfoo \SetMark{mark1} \stopfoo \startfoo \SetMark{mark2} \stopfoo \startfoo \SetMark{mark3} \stopfoo \stoptext ``` Snapshot: [![Results](https://i.stack.imgur.com/PuBh2.png)](https://i.stack.imgur.com/PuBh2.png)
30,438
I have a view that utilizes a node-reference field. I want users to be able to filter by this field using a search-box (or an autocomplete field), but when I set the exposed filter to the node-reference field, all I get is a drop-down. How can I force this to be either a text field or autocomplete? Thanks! views 3 drupal 7
2012/05/08
[ "https://drupal.stackexchange.com/questions/30438", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/7242/" ]
This might help you, <http://drupal.org/node/506654#comment-6412784> [Views autocomplete filters](http://drupal.org/project/views_autocomplete_filters)
You can also use entity reference instead of node reference. That module offers an autocomplete filter.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
I do not know how to do what your are trying but I can suggest you "legal" solution. Implement convertor that has both old and new packages in classpath and does the following: reads data from DB, de-serializes it using the old package, converts old instances to new in java and then stores new data in DB again. This solution requires performing some dirty job but it is safe. Moreover the results may be reused in future. But I wish you good luck to find solution that just replaces class name in serialized data.
If the data-to-be-refactored is being stored - in string form - in a database, one option is to use SQL to simply update that data, e.g., (in pseudo MySQL) ``` update mydata set serialized_data = replace(serialized_data, "com.oldpackage", "com.newpackage") ``` you would, of course, refactor your Java code before attempting to re-read this data from the DB.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
I do not know how to do what your are trying but I can suggest you "legal" solution. Implement convertor that has both old and new packages in classpath and does the following: reads data from DB, de-serializes it using the old package, converts old instances to new in java and then stores new data in DB again. This solution requires performing some dirty job but it is safe. Moreover the results may be reused in future. But I wish you good luck to find solution that just replaces class name in serialized data.
IIRC you can (with sufficient permissions) override `ObjectInputStream.resolveClass` (and `resolveProxyClass`) to return a `Class` with a different package names. Although, IIRC, you cannot change the simple class name.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
I do not know how to do what your are trying but I can suggest you "legal" solution. Implement convertor that has both old and new packages in classpath and does the following: reads data from DB, de-serializes it using the old package, converts old instances to new in java and then stores new data in DB again. This solution requires performing some dirty job but it is safe. Moreover the results may be reused in future. But I wish you good luck to find solution that just replaces class name in serialized data.
Can i suguest an alternative tack. The java serialisation format has some significant issues when being used for long term storage. Since you are refactoring and are most likely going to have to deserialise all the stored data one way or another, you may want to look at [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/) as an alternative serialisation format. It might take a bit more work but it is designed specifically for long term storage and versioning. Good luck
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
IIRC you can (with sufficient permissions) override `ObjectInputStream.resolveClass` (and `resolveProxyClass`) to return a `Class` with a different package names. Although, IIRC, you cannot change the simple class name.
If the data-to-be-refactored is being stored - in string form - in a database, one option is to use SQL to simply update that data, e.g., (in pseudo MySQL) ``` update mydata set serialized_data = replace(serialized_data, "com.oldpackage", "com.newpackage") ``` you would, of course, refactor your Java code before attempting to re-read this data from the DB.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
Can i suguest an alternative tack. The java serialisation format has some significant issues when being used for long term storage. Since you are refactoring and are most likely going to have to deserialise all the stored data one way or another, you may want to look at [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/) as an alternative serialisation format. It might take a bit more work but it is designed specifically for long term storage and versioning. Good luck
If the data-to-be-refactored is being stored - in string form - in a database, one option is to use SQL to simply update that data, e.g., (in pseudo MySQL) ``` update mydata set serialized_data = replace(serialized_data, "com.oldpackage", "com.newpackage") ``` you would, of course, refactor your Java code before attempting to re-read this data from the DB.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
To precise Tom Hawtin's reply, I have managed to implement it using the following code: ``` public static ObjectInputStream getSwapOIS( InputStream in ,String fromClass,String toClass) throws IOException ,ClassNotFoundException { final String from="^"+fromClass,fromArray="^\\[L"+fromClass,toArray="[L"+toClass; return new ObjectInputStream(in) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); return Class.forName(name); } protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass cd = super.readClassDescriptor(); String name = cd.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); if(!name.equals(cd.getName())) { cd = ObjectStreamClass.lookup(Class.forName(name)); } return cd; } }; } ``` Note that you also need to override readClassDescriptor(). It works for both standard types and arrays and you can even change the class name not just the package name. Just do: ``` InputStream in = new ByteArrayInputStream(classBytes); ObjectInputStream ois = getSwapOIS( in, "com.oldpackage.className", "com.newpackage.newClassName"); Object myObject= ois.readObject(); ```
If the data-to-be-refactored is being stored - in string form - in a database, one option is to use SQL to simply update that data, e.g., (in pseudo MySQL) ``` update mydata set serialized_data = replace(serialized_data, "com.oldpackage", "com.newpackage") ``` you would, of course, refactor your Java code before attempting to re-read this data from the DB.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
To precise Tom Hawtin's reply, I have managed to implement it using the following code: ``` public static ObjectInputStream getSwapOIS( InputStream in ,String fromClass,String toClass) throws IOException ,ClassNotFoundException { final String from="^"+fromClass,fromArray="^\\[L"+fromClass,toArray="[L"+toClass; return new ObjectInputStream(in) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); return Class.forName(name); } protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass cd = super.readClassDescriptor(); String name = cd.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); if(!name.equals(cd.getName())) { cd = ObjectStreamClass.lookup(Class.forName(name)); } return cd; } }; } ``` Note that you also need to override readClassDescriptor(). It works for both standard types and arrays and you can even change the class name not just the package name. Just do: ``` InputStream in = new ByteArrayInputStream(classBytes); ObjectInputStream ois = getSwapOIS( in, "com.oldpackage.className", "com.newpackage.newClassName"); Object myObject= ois.readObject(); ```
IIRC you can (with sufficient permissions) override `ObjectInputStream.resolveClass` (and `resolveProxyClass`) to return a `Class` with a different package names. Although, IIRC, you cannot change the simple class name.
4,668,675
I want to replace the String "com.oldpackage.className" with "com.newPackage.className" in a stream of serialized data. This serialized data is read from the DB and updated after replacing the string. I am facing some problems while doing the same. If you already guessed it, this is part of a refactoring exercise. Are there any libraries that would help me in manipulating the serialized data? If you can also please comment on any precautions or caveats, it would be of great help. Thanks a lot, Chris. P.S: Both the old class and the new class do not declare a serialversion ID as part of its fields.
2011/01/12
[ "https://Stackoverflow.com/questions/4668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567328/" ]
To precise Tom Hawtin's reply, I have managed to implement it using the following code: ``` public static ObjectInputStream getSwapOIS( InputStream in ,String fromClass,String toClass) throws IOException ,ClassNotFoundException { final String from="^"+fromClass,fromArray="^\\[L"+fromClass,toArray="[L"+toClass; return new ObjectInputStream(in) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String name = desc.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); return Class.forName(name); } protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass cd = super.readClassDescriptor(); String name = cd.getName().replaceFirst(from, toClass); name = name.replaceFirst(fromArray, toArray); if(!name.equals(cd.getName())) { cd = ObjectStreamClass.lookup(Class.forName(name)); } return cd; } }; } ``` Note that you also need to override readClassDescriptor(). It works for both standard types and arrays and you can even change the class name not just the package name. Just do: ``` InputStream in = new ByteArrayInputStream(classBytes); ObjectInputStream ois = getSwapOIS( in, "com.oldpackage.className", "com.newpackage.newClassName"); Object myObject= ois.readObject(); ```
Can i suguest an alternative tack. The java serialisation format has some significant issues when being used for long term storage. Since you are refactoring and are most likely going to have to deserialise all the stored data one way or another, you may want to look at [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/) as an alternative serialisation format. It might take a bit more work but it is designed specifically for long term storage and versioning. Good luck
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
You can use custom validation messages per field, either on validation language file or in your code itself: <https://laravel.com/docs/5.2/validation#custom-error-messages> Let's simulate a controller validation to see how it works: ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; class YourController extends Controller { public function store(Request $request) { $rules = [ 'birth_date' => 'required|date|before:today|after:01-jan-1920', ]; $messages = [ 'birth_date.before' => 'A data de nascimento deve ser uma data antes de hoje.', // "The birth date must be a date before today" in portuguese ]; $this->validate($request, $rules, $messages); /* your stuff */ } } ``` You can also do that with [form requests](https://laravel.com/docs/5.2/validation#form-request-validation) (which are even nicer), all you need to do is return your custom translated messages inside `messages()` method. :)
It probably makes more sense to make some custom validations but I think you should be able to do this simply with Carbon: ``` $dt = new Carbon\Carbon(); $today = $dt->today(); $tomorrow = $dt->tomorrow(); $rules = [ ... 'birth_date' => 'required|date|before:'.$today.'|after:01-jan-1920', 'another_date' => 'required|date|before:'.$tomorrow.'|after:01-jan-1990' ]; ```
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
Use custom error messages. ``` $this->validate( $request, [ 'phone' => 'required|regex:/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i' ], [ 'regex' => 'You must enter a valid phone number.', 'required' => 'You must enter a valid phone number.' ] ); ``` Replace 'regex' and 'required' with 'before:today' and 'before:tomorrow' and replace with custom error messages.
It probably makes more sense to make some custom validations but I think you should be able to do this simply with Carbon: ``` $dt = new Carbon\Carbon(); $today = $dt->today(); $tomorrow = $dt->tomorrow(); $rules = [ ... 'birth_date' => 'required|date|before:'.$today.'|after:01-jan-1920', 'another_date' => 'required|date|before:'.$tomorrow.'|after:01-jan-1990' ]; ```
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
In short, add following code into `resources/lang/whichever/validation.php` ```php 'values' => [ // or whatever fields you wanna translate 'birth_date' => [ // or tomorrow 'today' => '今天' ] ] ``` Explained: <https://github.com/laravel/framework/blob/7.x/src/Illuminate/Validation/Concerns/FormatsMessages.php#L319> ```php /** * Get the displayable name of the value. * * @param string $attribute * @param mixed $value * @return string */ public function getDisplayableValue($attribute, $value) { if (isset($this->customValues[$attribute][$value])) { return $this->customValues[$attribute][$value]; } // the key we want $key = "validation.values.{$attribute}.{$value}"; // if the translate found, then use it if (($line = $this->translator->get($key)) !== $key) { return $line; } if (is_bool($value)) { return $value ? 'true' : 'false'; } return $value; } ```
It probably makes more sense to make some custom validations but I think you should be able to do this simply with Carbon: ``` $dt = new Carbon\Carbon(); $today = $dt->today(); $tomorrow = $dt->tomorrow(); $rules = [ ... 'birth_date' => 'required|date|before:'.$today.'|after:01-jan-1920', 'another_date' => 'required|date|before:'.$tomorrow.'|after:01-jan-1990' ]; ```
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
You can use custom validation messages per field, either on validation language file or in your code itself: <https://laravel.com/docs/5.2/validation#custom-error-messages> Let's simulate a controller validation to see how it works: ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; class YourController extends Controller { public function store(Request $request) { $rules = [ 'birth_date' => 'required|date|before:today|after:01-jan-1920', ]; $messages = [ 'birth_date.before' => 'A data de nascimento deve ser uma data antes de hoje.', // "The birth date must be a date before today" in portuguese ]; $this->validate($request, $rules, $messages); /* your stuff */ } } ``` You can also do that with [form requests](https://laravel.com/docs/5.2/validation#form-request-validation) (which are even nicer), all you need to do is return your custom translated messages inside `messages()` method. :)
Use custom error messages. ``` $this->validate( $request, [ 'phone' => 'required|regex:/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i' ], [ 'regex' => 'You must enter a valid phone number.', 'required' => 'You must enter a valid phone number.' ] ); ``` Replace 'regex' and 'required' with 'before:today' and 'before:tomorrow' and replace with custom error messages.
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
In short, add following code into `resources/lang/whichever/validation.php` ```php 'values' => [ // or whatever fields you wanna translate 'birth_date' => [ // or tomorrow 'today' => '今天' ] ] ``` Explained: <https://github.com/laravel/framework/blob/7.x/src/Illuminate/Validation/Concerns/FormatsMessages.php#L319> ```php /** * Get the displayable name of the value. * * @param string $attribute * @param mixed $value * @return string */ public function getDisplayableValue($attribute, $value) { if (isset($this->customValues[$attribute][$value])) { return $this->customValues[$attribute][$value]; } // the key we want $key = "validation.values.{$attribute}.{$value}"; // if the translate found, then use it if (($line = $this->translator->get($key)) !== $key) { return $line; } if (is_bool($value)) { return $value ? 'true' : 'false'; } return $value; } ```
You can use custom validation messages per field, either on validation language file or in your code itself: <https://laravel.com/docs/5.2/validation#custom-error-messages> Let's simulate a controller validation to see how it works: ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; class YourController extends Controller { public function store(Request $request) { $rules = [ 'birth_date' => 'required|date|before:today|after:01-jan-1920', ]; $messages = [ 'birth_date.before' => 'A data de nascimento deve ser uma data antes de hoje.', // "The birth date must be a date before today" in portuguese ]; $this->validate($request, $rules, $messages); /* your stuff */ } } ``` You can also do that with [form requests](https://laravel.com/docs/5.2/validation#form-request-validation) (which are even nicer), all you need to do is return your custom translated messages inside `messages()` method. :)
36,546,161
In my model I defined a few validation rules for date fields using `before` and `after`: ``` 'birth_date' => 'required|date|before:today|after:01-jan-1920', 'another_date' => 'required|date|before:tomorrow|after:01-jan-1990', ``` The validation works fine, however I can't figure out how to translate the strings `today` and `tomorrow` on the validation message. In the `validation.php` language file the `after` and `before` messages are localizable, however the `:date` part of the message is still displaying the English version for `today` and `tomorrow`. ``` "after" => "The :attribute must be a date after :date.", "before" => "The :attribute must be a date before :date.", ``` How could I localize those two words - `today` and `tomorrow` - in the validation message?
2016/04/11
[ "https://Stackoverflow.com/questions/36546161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1369191/" ]
In short, add following code into `resources/lang/whichever/validation.php` ```php 'values' => [ // or whatever fields you wanna translate 'birth_date' => [ // or tomorrow 'today' => '今天' ] ] ``` Explained: <https://github.com/laravel/framework/blob/7.x/src/Illuminate/Validation/Concerns/FormatsMessages.php#L319> ```php /** * Get the displayable name of the value. * * @param string $attribute * @param mixed $value * @return string */ public function getDisplayableValue($attribute, $value) { if (isset($this->customValues[$attribute][$value])) { return $this->customValues[$attribute][$value]; } // the key we want $key = "validation.values.{$attribute}.{$value}"; // if the translate found, then use it if (($line = $this->translator->get($key)) !== $key) { return $line; } if (is_bool($value)) { return $value ? 'true' : 'false'; } return $value; } ```
Use custom error messages. ``` $this->validate( $request, [ 'phone' => 'required|regex:/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i' ], [ 'regex' => 'You must enter a valid phone number.', 'required' => 'You must enter a valid phone number.' ] ); ``` Replace 'regex' and 'required' with 'before:today' and 'before:tomorrow' and replace with custom error messages.
29,544,441
I am very new to MatLab. I got a task for modelling non-linear regression using neural network in MatLab. I need to create a two-layer neural network where: 1. The first layer is N neurons with sigmoid activation function. 2. The second layer is layer with one neuron and a linear activation function. Here is how I implemented the network: ``` net = network(N, 2); net.layers{1}.transferFcn = 'logsig'; net.layers{1}.size = N net.layers{2}.size = 1; ``` Is this implementation correct? How should I assign the linear activation function to the second layer?
2015/04/09
[ "https://Stackoverflow.com/questions/29544441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882829/" ]
This problem looks similar to this question. [Submit WatchKit Provisioning Error](https://stackoverflow.com/questions/29479139/submit-watchkit-provisioning-error) I had the same problem. Here is the solution that worked for me. Technical Q&A QA1830 The beta-reports-active Entitlement Q: How do I resolve the "beta-reports-active" code signing error? <https://developer.apple.com/library/ios/qa/qa1830/_index.html> I had to regenerate the "Distribution" Provisioning Profile that I was using to submit my entire app, before I included the WatchKit extension. Specifically, these steps fixed my problem: I logged onto developer.apple.com, selected "Certificates, Identifiers & Profiles". 1. On the Certs IDs & Profiles website > Provisioning Profiles page, click the App Store profile. 2. Click 'Edit' 3. Click 'Generate'
I needed to revoke my certificates (preferences -> accounts). After that XCode offered to recreate them. All fine now. Not sure whether this has unwanted side effects as previous certificates are now invalid.
29,544,441
I am very new to MatLab. I got a task for modelling non-linear regression using neural network in MatLab. I need to create a two-layer neural network where: 1. The first layer is N neurons with sigmoid activation function. 2. The second layer is layer with one neuron and a linear activation function. Here is how I implemented the network: ``` net = network(N, 2); net.layers{1}.transferFcn = 'logsig'; net.layers{1}.size = N net.layers{2}.size = 1; ``` Is this implementation correct? How should I assign the linear activation function to the second layer?
2015/04/09
[ "https://Stackoverflow.com/questions/29544441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882829/" ]
This problem looks similar to this question. [Submit WatchKit Provisioning Error](https://stackoverflow.com/questions/29479139/submit-watchkit-provisioning-error) I had the same problem. Here is the solution that worked for me. Technical Q&A QA1830 The beta-reports-active Entitlement Q: How do I resolve the "beta-reports-active" code signing error? <https://developer.apple.com/library/ios/qa/qa1830/_index.html> I had to regenerate the "Distribution" Provisioning Profile that I was using to submit my entire app, before I included the WatchKit extension. Specifically, these steps fixed my problem: I logged onto developer.apple.com, selected "Certificates, Identifiers & Profiles". 1. On the Certs IDs & Profiles website > Provisioning Profiles page, click the App Store profile. 2. Click 'Edit' 3. Click 'Generate'
I had the same error message trying to submit an update to a Watch App that was previously rejected. Since i had previously uploaded, I did not see this error. I used a support incident to get help after exhausting all paths. I got a response in just 1 or 2 business days -- which at first annoyed me. They said i needed to reset everything to use "team provisioning profiles" and all would be fine. I am an individual developer, so my "team profile" is just mine... but I did walk through all the steps and ta-da, much to my surprise, everything worked and the errors went away. Nothing really to do with any of the application specific or other provisioning profiles i had -- i must have changed a "signing identity" somewhere so Xcode's automatic resolution / fix up did not work. Apple's message was: CONVERTING TO TEAM BASED CODE SIGNING Team-based signing should be used in Xcode 5 and later: it’s the recommended workflow and is what’s covered in App Distribution Guide. Team based code signing requires resetting of all code signing settings in each targets build settings to their defaults. Xcode will no longer use the Code Signing Identity and Provisioning Profile build settings, but instead choose the best combination of signing identities and provisioning profile for the scheme being built. [Technical Q&A QA1814 - Setting up Xcode to automatically manage your provisioning profiles](https://developer.apple.com/library/ios/qa/qa1814/_index.html/Title) Which is quite clear and solved all my problems.
29,544,441
I am very new to MatLab. I got a task for modelling non-linear regression using neural network in MatLab. I need to create a two-layer neural network where: 1. The first layer is N neurons with sigmoid activation function. 2. The second layer is layer with one neuron and a linear activation function. Here is how I implemented the network: ``` net = network(N, 2); net.layers{1}.transferFcn = 'logsig'; net.layers{1}.size = N net.layers{2}.size = 1; ``` Is this implementation correct? How should I assign the linear activation function to the second layer?
2015/04/09
[ "https://Stackoverflow.com/questions/29544441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882829/" ]
This problem looks similar to this question. [Submit WatchKit Provisioning Error](https://stackoverflow.com/questions/29479139/submit-watchkit-provisioning-error) I had the same problem. Here is the solution that worked for me. Technical Q&A QA1830 The beta-reports-active Entitlement Q: How do I resolve the "beta-reports-active" code signing error? <https://developer.apple.com/library/ios/qa/qa1830/_index.html> I had to regenerate the "Distribution" Provisioning Profile that I was using to submit my entire app, before I included the WatchKit extension. Specifically, these steps fixed my problem: I logged onto developer.apple.com, selected "Certificates, Identifiers & Profiles". 1. On the Certs IDs & Profiles website > Provisioning Profiles page, click the App Store profile. 2. Click 'Edit' 3. Click 'Generate'
Following steps help me out: 1.Make sure "App Groups" in Capabilities page in Container target and Extension target. 2.Goto Xcode > Preferences > Accounts > YOUR\_ACCOUNT > View Details ..., CTRL+Click one of the Profiles and open in Finder. Move all Profiles to Trash. 3.Open "App Groups" in Container target and Extension target. Xcode will generate two profiles for you, just like iOSTeam Provisioning Profile: YOURAPPID and iOSTeam Provisioning Profile: YOURAPPID.watchkitextension. (Make sure your container target and WatchKit App target choose the first one as PP,and your extension target choose the second one). 4.If everything goes well, you can do whatever build, run and submit.
29,544,441
I am very new to MatLab. I got a task for modelling non-linear regression using neural network in MatLab. I need to create a two-layer neural network where: 1. The first layer is N neurons with sigmoid activation function. 2. The second layer is layer with one neuron and a linear activation function. Here is how I implemented the network: ``` net = network(N, 2); net.layers{1}.transferFcn = 'logsig'; net.layers{1}.size = N net.layers{2}.size = 1; ``` Is this implementation correct? How should I assign the linear activation function to the second layer?
2015/04/09
[ "https://Stackoverflow.com/questions/29544441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882829/" ]
Following steps help me out: 1.Make sure "App Groups" in Capabilities page in Container target and Extension target. 2.Goto Xcode > Preferences > Accounts > YOUR\_ACCOUNT > View Details ..., CTRL+Click one of the Profiles and open in Finder. Move all Profiles to Trash. 3.Open "App Groups" in Container target and Extension target. Xcode will generate two profiles for you, just like iOSTeam Provisioning Profile: YOURAPPID and iOSTeam Provisioning Profile: YOURAPPID.watchkitextension. (Make sure your container target and WatchKit App target choose the first one as PP,and your extension target choose the second one). 4.If everything goes well, you can do whatever build, run and submit.
I needed to revoke my certificates (preferences -> accounts). After that XCode offered to recreate them. All fine now. Not sure whether this has unwanted side effects as previous certificates are now invalid.
29,544,441
I am very new to MatLab. I got a task for modelling non-linear regression using neural network in MatLab. I need to create a two-layer neural network where: 1. The first layer is N neurons with sigmoid activation function. 2. The second layer is layer with one neuron and a linear activation function. Here is how I implemented the network: ``` net = network(N, 2); net.layers{1}.transferFcn = 'logsig'; net.layers{1}.size = N net.layers{2}.size = 1; ``` Is this implementation correct? How should I assign the linear activation function to the second layer?
2015/04/09
[ "https://Stackoverflow.com/questions/29544441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882829/" ]
Following steps help me out: 1.Make sure "App Groups" in Capabilities page in Container target and Extension target. 2.Goto Xcode > Preferences > Accounts > YOUR\_ACCOUNT > View Details ..., CTRL+Click one of the Profiles and open in Finder. Move all Profiles to Trash. 3.Open "App Groups" in Container target and Extension target. Xcode will generate two profiles for you, just like iOSTeam Provisioning Profile: YOURAPPID and iOSTeam Provisioning Profile: YOURAPPID.watchkitextension. (Make sure your container target and WatchKit App target choose the first one as PP,and your extension target choose the second one). 4.If everything goes well, you can do whatever build, run and submit.
I had the same error message trying to submit an update to a Watch App that was previously rejected. Since i had previously uploaded, I did not see this error. I used a support incident to get help after exhausting all paths. I got a response in just 1 or 2 business days -- which at first annoyed me. They said i needed to reset everything to use "team provisioning profiles" and all would be fine. I am an individual developer, so my "team profile" is just mine... but I did walk through all the steps and ta-da, much to my surprise, everything worked and the errors went away. Nothing really to do with any of the application specific or other provisioning profiles i had -- i must have changed a "signing identity" somewhere so Xcode's automatic resolution / fix up did not work. Apple's message was: CONVERTING TO TEAM BASED CODE SIGNING Team-based signing should be used in Xcode 5 and later: it’s the recommended workflow and is what’s covered in App Distribution Guide. Team based code signing requires resetting of all code signing settings in each targets build settings to their defaults. Xcode will no longer use the Code Signing Identity and Provisioning Profile build settings, but instead choose the best combination of signing identities and provisioning profile for the scheme being built. [Technical Q&A QA1814 - Setting up Xcode to automatically manage your provisioning profiles](https://developer.apple.com/library/ios/qa/qa1814/_index.html/Title) Which is quite clear and solved all my problems.
68,937
We installed a wiring kit to the rear lights so we could plug in lights for towing a trailer. After testing the lights with a trailer, the brake lights stopped working and then the car wouldn't shift out of park. We removed the kit and put all the wires back where they were originally, and still, the car won't shift out of park.
2019/07/15
[ "https://mechanics.stackexchange.com/questions/68937", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/35573/" ]
The issue was the brake light fuse burned out. This was frustrating us because there is a separate fuse labeled `TAIL` for the tail lights and a different fuse labeled `STOP` for the brake lights. Without Google, we wouldn't have thought about looking for the `STOP` fuse. Once the fuse was replaced, the car would shift out of park. I guess we need to look into getting a different wiring kit brand or checking the trailer connection for any issues that caused the fuse to burn out. > > NOTE: The fuses in the RAV4 are below the steering wheel. The size for the `STOP` fuse is 10A and was in slot number 9. > > >
I see 3 possibilities: 1. you made an error when connecting the "stop" wire. 2. the trailer kit (socket) has a fault on the stop pin. 3. The trailer you used for testing has a fault on the stop circuit (shorted wire or shorted bulb). You may not need a new trailer connection kit, just need to find what was wrong.
46,743,625
I have a column having over 800 rows shown below: ``` 0 ['Overgrow', 'Chlorophyll'] 1 ['Overgrow', 'Chlorophyll'] 2 ['Overgrow', 'Chlorophyll'] 3 ['Blaze', 'Solar Power'] 4 ['Blaze', 'Solar Power'] 5 ['Blaze', 'Solar Power'] 6 ['Torrent', 'Rain Dish'] 7 ['Torrent', 'Rain Dish'] 8 ['Torrent', 'Rain Dish'] 9 ['Shield Dust', 'Run Away'] 10 ['Shed Skin'] 11 ['Compoundeyes', 'Tinted Lens'] 12 ['Shield Dust', 'Run Away'] 13 ['Shed Skin'] 14 ['Swarm', 'Sniper'] 15 ['Keen Eye', 'Tangled Feet', 'Big Pecks'] 16 ['Keen Eye', 'Tangled Feet', 'Big Pecks'] 17 ['Keen Eye', 'Tangled Feet', 'Big Pecks'] ``` ### What do I want? 1. I would like to count the number of times each string value has occurred. 2. I also would like to arrange the unique string values into a list. Here is what I have done to obtain the second part: ``` list_ability = df_pokemon['abilities'].tolist() new_list = [] for i in range(0, len(list_ability)): m = re.findall(r"'(.*?)'", list_ability[i], re.DOTALL) for j in range(0, len(m)): new_list.append(m[j]) list1 = set(new_list) ``` I am able to get the unique string values into a list, but is there a better way? ### Example: 'Overgrow' - 3 'Chlorophyll' - 3 'Blaze' - 3 'Sheild Dust' - 2 .... and so on (By the way, the name of the column is `'abilities'` from the dataframe `df_pokemon`.)
2017/10/14
[ "https://Stackoverflow.com/questions/46743625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6885902/" ]
Since the values are strings you can use regex and split to convert them to list then use itertools just the way @JonClements mentioned in comment to count i.e ``` from collections import Counter count = pd.Series(df['abilities'].str.replace('[\[\]\']','').str.split(',').map(Counter).sum()) ``` Output: ``` Big Pecks 3 Chlorophyll 3 Rain Dish 3 Run Away 2 Sniper 1 Solar Power 3 Tangled Feet 3 Tinted Lens 1 Blaze 3 Compoundeyes 1 Keen Eye 3 Overgrow 3 Shed Skin 2 Shield Dust 2 Swarm 1 Torrent 3 dtype: int64 dtype: int64 ``` For making list of only unique values then `count[count==1].index.tolist()` ``` ['Sniper', 'Tinted Lens', 'Compoundeyes', 'Swarm'] ``` For making list of the index then ``` count.index.tolist() ```
Use `value_counts` ``` In [1845]: counts = pd.Series(np.concatenate(df_pokemon.abilities)).value_counts() In [1846]: counts Out[1846]: Rain Dish 3 Keen Eye 3 Chlorophyll 3 Blaze 3 Solar Power 3 Overgrow 3 Big Pecks 3 Tangled Feet 3 Torrent 3 Shield Dust 2 Shed Skin 2 Run Away 2 Compoundeyes 1 Swarm 1 Tinted Lens 1 Sniper 1 dtype: int64 ``` For unique values you could ``` In [1850]: counts.index.tolist() Out[1850]: ['Rain Dish','Keen Eye', 'Chlorophyll', 'Blaze', 'Solar Power', 'Overgrow', 'Big Pecks', 'Tangled Feet', 'Torrent', 'Shield Dust', 'Shed Skin', 'Run Away', 'Compoundeyes', 'Swarm', 'Tinted Lens', 'Sniper'] ``` Or, ``` In [1849]: np.unique(np.concatenate(df_pokemon.abilities)) Out[1849]: array(['Big Pecks', 'Blaze', 'Chlorophyll', 'Compoundeyes', 'Keen Eye', 'Overgrow', 'Rain Dish', 'Run Away', 'Shed Skin', 'Shield Dust', 'Sniper', 'Solar Power', 'Swarm', 'Tangled Feet', 'Tinted Lens', 'Torrent'], dtype='|S12') ``` --- **Note** - As pointed in [Jon's comments](https://stackoverflow.com/questions/46743625/pandas-count-and-get-unique-occurrences-of-string-values-from-a-column/46743771#comment80433595_46743771) if `type(df_pokemon.abilities[0])` is not `list` then, convert to list first ``` import ast df_pokemon.abilities = df_pokemon.abilities.map(ast.literal_eval) ``` --- Details ``` In [1842]: df_pokemon Out[1842]: abilities 0 [Overgrow, Chlorophyll] 1 [Overgrow, Chlorophyll] 2 [Overgrow, Chlorophyll] 3 [Blaze, Solar Power] 4 [Blaze, Solar Power] 5 [Blaze, Solar Power] 6 [Torrent, Rain Dish] 7 [Torrent, Rain Dish] 8 [Torrent, Rain Dish] 9 [Shield Dust, Run Away] 10 [Shed Skin] 11 [Compoundeyes, Tinted Lens] 12 [Shield Dust, Run Away] 13 [Shed Skin] 14 [Swarm, Sniper] 15 [Keen Eye, Tangled Feet, Big Pecks] 16 [Keen Eye, Tangled Feet, Big Pecks] 17 [Keen Eye, Tangled Feet, Big Pecks] In [1843]: df_pokemon.dtypes Out[1843]: abilities object dtype: object In [1844]: type(df_pokemon.abilities[0]) Out[1844]: list ```
54,861,462
I have started learning cloud architecture and found out that they all are using columnar databases which claims to be more efficient as they are storing column rather than a row to reduce duplicate. From a data mart perspective (lets say for an organization a department only want to monitor internet sales growth and some other department want to focus on outlet performances), **how can I design an architecture which can handle data load and provide easy data access.** I know how data mart can be easily designed on top of it and end user doesn't have to bother about calculation at all. I had have experience in SSAS (OLAP) in which all calculation on a large data warehouse is already computed and a normal business user can directly connect to the cube and analyze the data with self service BI tool (as simple as drag and drop) on the other hand columnar databases seems to follow ELT approach and leaves all computation on either queries(views) or on reporting tool. As I have experience in SQL Server, I presume that my query (for example below) ``` SELECT region, state, City, Country, SUM(Sales_Amount), AVG(Discount_Sale), SUM(xyz) .... FROM Columnar_DataTable ``` is going to scan complete table which can increase cost. Imagine if above query is executed more than 1000 times in a day for a large enterprise. **So, is it appropriate to create a OLAP on top of columnar databases with dimensional modeling or it is better to load the data first then filter/transform it on reporting tool?** Considering that most Self service BI tool already have this in mind and limit the usage of data consumption (ex: Power BI desktop community edition allows 10 GB per data set) and forces user to do his/her own calculation. * If we segregate the data into multiple tables then all reporting tools, anyways, needs relation between tables for filtering. * If we keep single table format then reporting tool has to read all data before making any calculation.
2019/02/25
[ "https://Stackoverflow.com/questions/54861462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298336/" ]
Business analysis queries do often involve computing aggregations for metrics, like the total sales amounts and the average discount that you exemplified. OLAP data structures are useful for these use cases because the aggregations can be precomputed and stored, thereby requiring less computation and I/O at query time and speeding up the query patterns used in these use cases. The OLAP approach gained momentum (also) because a typical relational database was less performant in these scenarios and OLAP turned out to be an effective optimization. The columnar database approach (in analytics-oriented databases) is also meant to optimize these use cases, mostly by structuring and storing data in a way that only selected columns, like labels and measures for aggregations, have to be read from storage. This requires less I/O and is one of the main reasons why columnar formats offer great performance for these use cases (the others being sophisticated partitioning, parallel processing, compression and metadata, like in [Apache Parquet](https://parquet.apache.org/)). So, regarding your question, I'd say that you should only worry about precomputing aggregations in a columnar database if you experience low performance in ad hoc query scenarios, and cannot solve it in more immediate ways (like caching, proper partitioning and compression). But this also depends on what database/saas/file format you use. As to dimensional modelling, that's a different issue. If you use a columnar file format like Parquet it could actually be desirable (depending on the user and use case) to use something like [Hive](https://hive.apache.org/) to create a (meta) dimensional model over the files, so that e.g. you can expose database tables and a SQL interface to your users instead of a bunch of files. Regarding PowerBI, like with most reporting tools you can use it in Direct Query mode if users will indeed be working with datasets over 10GB. PS: in a columnar database that specific piece of SQL will not "scan the complete table", it will only scan the columns you select; that's part of the optimization of a columnar design.
Your sales growth SQL does not make sense. Sales growth is monitored over time but you did not define the time part in your SQL. For example If business wants to monitor weekly or monthly sales, then you create either a weekly Fact table or a monthly Fact table and you calculate weekly or monthly sales and save into that Fact table. In this way you append weekly or monthly data into the Fact table so the report just read it from the Fact table. Do have a dates which represents start of the week/month and end of week/month in the fact table so report can use it. Report Performance would be fast with this design approach because it does not do any calculation but shows summarized data.
55,286,086
I understand *canonicalization* and *normalization* to mean removing any non-meaningful or ambiguous parts of of a data's presentation, turning *effectively* identical data into *actually* identical data. For example, if you want to get the hash of some input data and it's important that anyone else hashing the canonically same data gets the same hash, you don't want one file indenting with tabs and the other using spaces (and no other difference) to cause two very different hashes. In the case of JSON: * object properties would be placed in a standard order (perhaps alphabetically) * unnecessary white spaces would be stripped * indenting either standardized or stripped * the data may even be re-modeled in an entirely new syntax, to enforce the above Is my definition correct, and the terms are interchangeable? Or is there a well-defined and specific difference between **canonicalization** and **normalization** of input data?
2019/03/21
[ "https://Stackoverflow.com/questions/55286086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1489243/" ]
"Canonicalize" & "normalize" (from "canonical (form)" & "normal form") are two related general mathematical terms that also have particular uses in particular contexts per some exact meaning given there. It is reasonable to label a particular process by one of those terms when the general meaning applies. Your characterizations of those specific uses are fuzzy. The formal meanings for general & particular cases are more useful. Sometimes given a bunch of things we partition them (all) into (disjoint) groups, aka equivalence classes, of ones that we consider to be in some particular sense similar or the same, aka equivalent. The members of a group/class are the same/equivalent according to some particular [equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation). We pick a particular member as the representative thing from each group/class & call it the canonical form for that group & its members. Two things are equivalent exactly when they are in the same equivalence class. Two things are equivalent exactly when their canonical forms are equal. A normal form might be a canonical form or just one of several distinguished members. To canonicalize/normalize is to find or use a canonical/normal form of a thing. [Canonical form](https://en.wikipedia.org/wiki/Canonical_form). > > The distinction between "canonical" and "normal" forms varies by subfield. In most fields, a canonical form specifies a unique representation for every object, while a normal form simply specifies its form, without the requirement of uniqueness. > > > Applying the definition to your example: Have you a bunch of values that you are partitioning & are you picking some member(s) per each class instead of the other members of that class? Well you have JSON values and short of re-modeling them you are partitioning them per what same-class member they map to under a function. So you can reasonably call the result JSON values canonical forms of the inputs. If you characterize re-modeling as applicable to all inputs then you can also reasonably call the post-re-modeling form of those canonical values canonical forms of re-modeled input values. But if not then people probably won't complain that you call the re-modeled values canonical forms of the input values even though technically they wouldn't be.
Consider a set of objects, each of which can have multiple representations. From your example, that would be the set of JSON objects and the fact that each object has multiple valid representations, e.g., each with different permutations of its members, less white spaces, etc. *Canonicalization* is the process of converting any representation of a given object to **one and only one**, unique per object, representation (a.k.a, *canonical form*). To test whether two representations are of the same object, it suffices to test equality on their *canonical forms*, see also wikipedia's [definition](https://en.wikipedia.org/wiki/Canonical_form#Definition). *Normalization* is the process of converting any representation of a given object to a **set** of representations (a.k.a., "normal forms") that is unique per object. In such case, equality between two representations is achieved by "subtracting" their *normal forms* and comparing the result with a *normal form* of "zero" (typically a trivial comparison). *Normalization* may be a better option when *canonical forms* are difficult to implement consistently, e.g., because they depend on arbitrary choices (like ordering of variables). *Section 1.2* from the ["A=B"](https://www2.math.upenn.edu/%7Ewilf/AeqB.html) book, has some really good examples for both concepts.
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
I can access ARP table without root. Here is my code: ``` string GetMACAddressviaIP(string ipAddr) { string result = ""; ostringstream ss; ss << "/proc/net/arp"; string loc = ss.str(); ifstream in(loc); if(!in) { printf("open %s failed\n",loc.c_str()); return result; } string line; while(getline(in, line)){ if(strstr(line.c_str(), ipAddr.c_str())) { const char *buf = strstr(line.c_str(), ":") - 2; int counter = 0; stringstream ss; while(counter < 17) { ss << buf[counter]; counter++; } result = ss.str(); } } return result; } ```
I recommend something like the following for Java. This combines the answers for the other two. It's not tested, so it might need some tweaks, but you get the idea. ``` public String getMacAddressForIp(final String ipAddress) { try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) { String line; while ((line = br.readLine()) != null) { if (line.contains(ipAddress)) { final int macStartIndex = line.indexOf(":") - 2; final int macEndPos = macStartIndex + 17; if (macStartIndex >= 0 && macEndPos < line.length()) { return line.substring(macStartIndex, macEndPos); } else { Log.w("MyClass", "Found ip address line, but mac address was invalid."); } } } } catch(Exception e){ Log.e("MyClass", "Exception reading the arp table.", e); } return null; } ```
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
I can access ARP table without root. Here is my code: ``` string GetMACAddressviaIP(string ipAddr) { string result = ""; ostringstream ss; ss << "/proc/net/arp"; string loc = ss.str(); ifstream in(loc); if(!in) { printf("open %s failed\n",loc.c_str()); return result; } string line; while(getline(in, line)){ if(strstr(line.c_str(), ipAddr.c_str())) { const char *buf = strstr(line.c_str(), ":") - 2; int counter = 0; stringstream ss; while(counter < 17) { ss << buf[counter]; counter++; } result = ss.str(); } } return result; } ```
As an alternative to previous answers a "no coding" solution is to install a linux terminal emulator on your device and use the arp -a command to view the arp table.
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
I can access ARP table without root. Here is my code: ``` string GetMACAddressviaIP(string ipAddr) { string result = ""; ostringstream ss; ss << "/proc/net/arp"; string loc = ss.str(); ifstream in(loc); if(!in) { printf("open %s failed\n",loc.c_str()); return result; } string line; while(getline(in, line)){ if(strstr(line.c_str(), ipAddr.c_str())) { const char *buf = strstr(line.c_str(), ":") - 2; int counter = 0; stringstream ss; while(counter < 17) { ss << buf[counter]; counter++; } result = ss.str(); } } return result; } ```
It seems that an application has not been able to access the arp file since Android 10. [link](https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem)
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
For better understanding, using Java language, you can retrieve the ARP table in android as: ``` BufferedReader br = null; ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>(); try { br = new BufferedReader(new FileReader("/proc/net/arp")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }Catch(Exception e){ }finally { try { br.close(); } catch (IOException e) { } } ```
I recommend something like the following for Java. This combines the answers for the other two. It's not tested, so it might need some tweaks, but you get the idea. ``` public String getMacAddressForIp(final String ipAddress) { try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) { String line; while ((line = br.readLine()) != null) { if (line.contains(ipAddress)) { final int macStartIndex = line.indexOf(":") - 2; final int macEndPos = macStartIndex + 17; if (macStartIndex >= 0 && macEndPos < line.length()) { return line.substring(macStartIndex, macEndPos); } else { Log.w("MyClass", "Found ip address line, but mac address was invalid."); } } } } catch(Exception e){ Log.e("MyClass", "Exception reading the arp table.", e); } return null; } ```
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
For better understanding, using Java language, you can retrieve the ARP table in android as: ``` BufferedReader br = null; ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>(); try { br = new BufferedReader(new FileReader("/proc/net/arp")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }Catch(Exception e){ }finally { try { br.close(); } catch (IOException e) { } } ```
As an alternative to previous answers a "no coding" solution is to install a linux terminal emulator on your device and use the arp -a command to view the arp table.
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
For better understanding, using Java language, you can retrieve the ARP table in android as: ``` BufferedReader br = null; ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>(); try { br = new BufferedReader(new FileReader("/proc/net/arp")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }Catch(Exception e){ }finally { try { br.close(); } catch (IOException e) { } } ```
It seems that an application has not been able to access the arp file since Android 10. [link](https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem)
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
I recommend something like the following for Java. This combines the answers for the other two. It's not tested, so it might need some tweaks, but you get the idea. ``` public String getMacAddressForIp(final String ipAddress) { try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) { String line; while ((line = br.readLine()) != null) { if (line.contains(ipAddress)) { final int macStartIndex = line.indexOf(":") - 2; final int macEndPos = macStartIndex + 17; if (macStartIndex >= 0 && macEndPos < line.length()) { return line.substring(macStartIndex, macEndPos); } else { Log.w("MyClass", "Found ip address line, but mac address was invalid."); } } } } catch(Exception e){ Log.e("MyClass", "Exception reading the arp table.", e); } return null; } ```
It seems that an application has not been able to access the arp file since Android 10. [link](https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem)
42,660,034
I am recently working on a Android project that requires to access the ARP table. One of the requirement is to avoid any methods that need a rooted device. So, my question is: is there any way to access the ARP table in android without rooting the device? Currently I have found that most of the approaches use the /proc/net/arp for the ARP table access which requires root permission, and I am not sure if this is the only way.
2017/03/07
[ "https://Stackoverflow.com/questions/42660034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4032889/" ]
As an alternative to previous answers a "no coding" solution is to install a linux terminal emulator on your device and use the arp -a command to view the arp table.
It seems that an application has not been able to access the arp file since Android 10. [link](https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem)
34,235,068
[![enter image description here](https://i.stack.imgur.com/OOS4w.jpg)](https://i.stack.imgur.com/OOS4w.jpg) Is there a wat to make a indicator like this? it has some pointed arrow down like in the selected item?
2015/12/12
[ "https://Stackoverflow.com/questions/34235068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104871/" ]
The only solution I could find is to grab the source code of the original `TabLayout` and customize it, according your needs. In fact, all you need to do to get this custom pointing arrow is to override `SlidingTabStrip`'s `void draw(Canvas canvas)` method. Unfortunately, `SlidingTabStrip` is `private` inner class inside `TabLayout`. [![enter image description here](https://i.stack.imgur.com/dZwhz.gif)](https://i.stack.imgur.com/dZwhz.gif) Luckily, all support library code is open, so we can create our own `TabLayoutWithArrow` class. I replaced the standard `void draw(Canvas canvas)` by this one to draw the arrow: ``` @Override public void draw(Canvas canvas) { super.draw(canvas); // i used <dimen name="pointing_arrow_size">3dp</dimen> int arrowSize = getResources().getDimensionPixelSize(R.dimen.pointing_arrow_size); if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) { canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight - arrowSize, mIndicatorRight, getHeight() - arrowSize, mSelectedIndicatorPaint); canvas.drawPath(getTrianglePath(arrowSize), mSelectedIndicatorPaint); } } private Path getTrianglePath(int arrowSize) { mSelectedIndicatorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mSelectedIndicatorPaint.setAntiAlias(true); int leftPointX = mIndicatorLeft + (mIndicatorRight - mIndicatorLeft) / 2 - arrowSize*2; int rightPointX = leftPointX + arrowSize*2; int bottomPointX = leftPointX + arrowSize; int leftPointY = getHeight() - arrowSize; int bottomPointY = getHeight(); Point left = new Point(leftPointX, leftPointY); Point right = new Point(rightPointX, leftPointY); Point bottom = new Point(bottomPointX, bottomPointY); Path path = new Path(); path.setFillType(Path.FillType.EVEN_ODD); path.setLastPoint(left.x, left.y); path.lineTo(right.x, right.y); path.lineTo(bottom.x, bottom.y); path.lineTo(left.x, left.y); path.close(); return path; } ``` Of course, the background, the particular design of the indicator can be improved/adjust according your needs. To make my custom `TabLayoutWithArrow`, I had to copy these files into my project: * AnimationUtils * TabLayout * ThemeUtils * ValueAnimatorCompat * ValueAnimatorCompatImplEclairMr1 * ValueAnimatorCompatImplHoneycombMr1 * ViewUtils * ViewUtilsLollipop To have transparency behind the arrow, you just need to set this `Shape`-`drawable`, as a `background` for the `TabLayoutWithArrow` : ``` <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:bottom="@dimen/pointing_arrow_size"> <shape android:shape="rectangle" > <solid android:color="#FFFF00" /> </shape> </item> <item android:height="@dimen/pointing_arrow_size" android:gravity="bottom"> <shape android:shape="rectangle" > <solid android:color="#00000000" /> </shape> </item> </layer-list> ``` And the actual usage is: ``` <klogi.com.viewpagerwithdifferentmenu.CustomTabLayout.TabLayoutWithArrow android:id="@+id/tabLayout" android:background="@drawable/tab_layout_background" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` I've uploaded the whole project (the TabLayoutWithArrow + one-page app which is using it) to my dropbox - [feel free to check it out](https://www.dropbox.com/s/bid2s0k9r3daigv/CustomTabLayoutApp.zip?dl=0). I hope, it helps
now it doesn't work, tintmanager class is removed from support library 23.2.0 , I managed same functionality by changing background drawable at runtime inside for loop detecting clicked position , PS : check this question and answer I am using same library : <https://github.com/astuetz/PagerSlidingTabStrip/issues/141>
34,235,068
[![enter image description here](https://i.stack.imgur.com/OOS4w.jpg)](https://i.stack.imgur.com/OOS4w.jpg) Is there a wat to make a indicator like this? it has some pointed arrow down like in the selected item?
2015/12/12
[ "https://Stackoverflow.com/questions/34235068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104871/" ]
The only solution I could find is to grab the source code of the original `TabLayout` and customize it, according your needs. In fact, all you need to do to get this custom pointing arrow is to override `SlidingTabStrip`'s `void draw(Canvas canvas)` method. Unfortunately, `SlidingTabStrip` is `private` inner class inside `TabLayout`. [![enter image description here](https://i.stack.imgur.com/dZwhz.gif)](https://i.stack.imgur.com/dZwhz.gif) Luckily, all support library code is open, so we can create our own `TabLayoutWithArrow` class. I replaced the standard `void draw(Canvas canvas)` by this one to draw the arrow: ``` @Override public void draw(Canvas canvas) { super.draw(canvas); // i used <dimen name="pointing_arrow_size">3dp</dimen> int arrowSize = getResources().getDimensionPixelSize(R.dimen.pointing_arrow_size); if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) { canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight - arrowSize, mIndicatorRight, getHeight() - arrowSize, mSelectedIndicatorPaint); canvas.drawPath(getTrianglePath(arrowSize), mSelectedIndicatorPaint); } } private Path getTrianglePath(int arrowSize) { mSelectedIndicatorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mSelectedIndicatorPaint.setAntiAlias(true); int leftPointX = mIndicatorLeft + (mIndicatorRight - mIndicatorLeft) / 2 - arrowSize*2; int rightPointX = leftPointX + arrowSize*2; int bottomPointX = leftPointX + arrowSize; int leftPointY = getHeight() - arrowSize; int bottomPointY = getHeight(); Point left = new Point(leftPointX, leftPointY); Point right = new Point(rightPointX, leftPointY); Point bottom = new Point(bottomPointX, bottomPointY); Path path = new Path(); path.setFillType(Path.FillType.EVEN_ODD); path.setLastPoint(left.x, left.y); path.lineTo(right.x, right.y); path.lineTo(bottom.x, bottom.y); path.lineTo(left.x, left.y); path.close(); return path; } ``` Of course, the background, the particular design of the indicator can be improved/adjust according your needs. To make my custom `TabLayoutWithArrow`, I had to copy these files into my project: * AnimationUtils * TabLayout * ThemeUtils * ValueAnimatorCompat * ValueAnimatorCompatImplEclairMr1 * ValueAnimatorCompatImplHoneycombMr1 * ViewUtils * ViewUtilsLollipop To have transparency behind the arrow, you just need to set this `Shape`-`drawable`, as a `background` for the `TabLayoutWithArrow` : ``` <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:bottom="@dimen/pointing_arrow_size"> <shape android:shape="rectangle" > <solid android:color="#FFFF00" /> </shape> </item> <item android:height="@dimen/pointing_arrow_size" android:gravity="bottom"> <shape android:shape="rectangle" > <solid android:color="#00000000" /> </shape> </item> </layer-list> ``` And the actual usage is: ``` <klogi.com.viewpagerwithdifferentmenu.CustomTabLayout.TabLayoutWithArrow android:id="@+id/tabLayout" android:background="@drawable/tab_layout_background" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` I've uploaded the whole project (the TabLayoutWithArrow + one-page app which is using it) to my dropbox - [feel free to check it out](https://www.dropbox.com/s/bid2s0k9r3daigv/CustomTabLayoutApp.zip?dl=0). I hope, it helps
Here is the code for anyone requiring an upward triangle using @Konstantin Loginov code ``` private Path getTrianglePath(int arrowSize) { mSelectedIndicatorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mSelectedIndicatorPaint.setAntiAlias(true); mSelectedIndicatorPaint.setColor(Color.WHITE); int leftPointX = mIndicatorLeft + (mIndicatorRight - mIndicatorLeft) / 2 - arrowSize * 1 / 2; int mTopX = leftPointX + arrowSize; int mTopY = getHeight() - arrowSize; int rightPointX = leftPointX + arrowSize * 2; int leftPointY = getHeight(); Point left = new Point(leftPointX, leftPointY); Point right = new Point(rightPointX, leftPointY); Point bottom = new Point(mTopX, mTopY); Path path = new Path(); path.setFillType(Path.FillType.EVEN_ODD); path.setLastPoint(left.x, left.y); path.lineTo(right.x, right.y); path.lineTo(bottom.x, bottom.y); path.lineTo(left.x, left.y); path.close(); return path; } ```
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try to add ``` window.open(url,'_blank'); ``` ### Edit Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async). You could try something like this though, it should look like a user action to a popup-blocker: ``` var $a = $('<a>', { href: url, target: '_blank' }); $(document.body).append($a); $a.click(); ``` ### Edit 2 Looks like you're better of keeping things sync. As long as the new window is "same origin" you have some power to manipulate it with JS. ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ```
Try adding async: false. It should be working ``` $('#myButton').click(function() { $.ajax({ type: 'POST', async: false, url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ```
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try to add ``` window.open(url,'_blank'); ``` ### Edit Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async). You could try something like this though, it should look like a user action to a popup-blocker: ``` var $a = $('<a>', { href: url, target: '_blank' }); $(document.body).append($a); $a.click(); ``` ### Edit 2 Looks like you're better of keeping things sync. As long as the new window is "same origin" you have some power to manipulate it with JS. ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ```
What worked for me was: ``` var win = window.open('about:blank', '_blank'); myrepository.postmethod('myserviceurl', myArgs) .then(function(result) { win.location.href = 'http://yourtargetlocation.com/dir/page'; }); ``` You open the new window tab before the sync call while you're still in scope, grab the window handle, and then re-navigate once you receive the ajax results in the promise.
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try to add ``` window.open(url,'_blank'); ``` ### Edit Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async). You could try something like this though, it should look like a user action to a popup-blocker: ``` var $a = $('<a>', { href: url, target: '_blank' }); $(document.body).append($a); $a.click(); ``` ### Edit 2 Looks like you're better of keeping things sync. As long as the new window is "same origin" you have some power to manipulate it with JS. ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ```
The answer posted by @pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created. e.g: ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); $(wi.document.body).html("<p>Please wait while you are being redirected...</p>"); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ``` This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try to add ``` window.open(url,'_blank'); ``` ### Edit Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async). You could try something like this though, it should look like a user action to a popup-blocker: ``` var $a = $('<a>', { href: url, target: '_blank' }); $(document.body).append($a); $a.click(); ``` ### Edit 2 Looks like you're better of keeping things sync. As long as the new window is "same origin" you have some power to manipulate it with JS. ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ```
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null. <https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ> > > How can I tell when my window was blocked by a popup blocker? With the > built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 > SP2, you have to check the return value of window.open(): it will be > null if the window wasn't allowed to open. However, for most other > popup blockers, there is no reliable way. > > >
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try adding async: false. It should be working ``` $('#myButton').click(function() { $.ajax({ type: 'POST', async: false, url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ```
The answer posted by @pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created. e.g: ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); $(wi.document.body).html("<p>Please wait while you are being redirected...</p>"); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ``` This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
Try adding async: false. It should be working ``` $('#myButton').click(function() { $.ajax({ type: 'POST', async: false, url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ```
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null. <https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ> > > How can I tell when my window was blocked by a popup blocker? With the > built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 > SP2, you have to check the return value of window.open(): it will be > null if the window wasn't allowed to open. However, for most other > popup blockers, there is no reliable way. > > >
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
What worked for me was: ``` var win = window.open('about:blank', '_blank'); myrepository.postmethod('myserviceurl', myArgs) .then(function(result) { win.location.href = 'http://yourtargetlocation.com/dir/page'; }); ``` You open the new window tab before the sync call while you're still in scope, grab the window handle, and then re-navigate once you receive the ajax results in the promise.
The answer posted by @pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created. e.g: ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); $(wi.document.body).html("<p>Please wait while you are being redirected...</p>"); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ``` This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
What worked for me was: ``` var win = window.open('about:blank', '_blank'); myrepository.postmethod('myserviceurl', myArgs) .then(function(result) { win.location.href = 'http://yourtargetlocation.com/dir/page'; }); ``` You open the new window tab before the sync call while you're still in scope, grab the window handle, and then re-navigate once you receive the ajax results in the promise.
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null. <https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ> > > How can I tell when my window was blocked by a popup blocker? With the > built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 > SP2, you have to check the return value of window.open(): it will be > null if the window wasn't allowed to open. However, for most other > popup blockers, there is no reliable way. > > >
22,007,592
I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous? **EDIT** Here is some minimal code that demonstrates this behaviour: ``` $('#myButton').click(function() { $.ajax({ type: 'POST', url: '/echo/json/', data: {'json': JSON.stringify({ url:'http://google.com'})}, success: function(data) { window.open(data.url,'_blank'); } }); }); ``` <http://jsfiddle.net/ESMUA/2/> One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
2014/02/25
[ "https://Stackoverflow.com/questions/22007592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543666/" ]
The answer posted by @pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created. e.g: ``` $('#a').on('click', function(e){ e.preventDefault(); var wi = window.open('about:blank', '_blank'); $(wi.document.body).html("<p>Please wait while you are being redirected...</p>"); setTimeout(function(){ // async wi.location.href = 'http://google.com'; }, 500); }); ``` This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null. <https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ> > > How can I tell when my window was blocked by a popup blocker? With the > built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 > SP2, you have to check the return value of window.open(): it will be > null if the window wasn't allowed to open. However, for most other > popup blockers, there is no reliable way. > > >
318,777
I am using the unix `pr` command to combine multiple text files into one text file: ``` pr -F *files > newfile ``` Each file is a different length, a different number of lines. I am mostly happy with the result, I like that it includes the name of the original text file followed by the contents of that file. However, I would like to eliminate the blank lines in between the name of the original text file and it's contents. I only want blank lines between the different text files to separate each. Also, it prints the character `^L` after the contents of each text file, and I would like to eliminate that character. Each file read in is also given a 'page' number. Only one file is longer than the 66 line default. that file ends up being spit into 2 'pages', and is split into 2 sections divided by blank lines. Is it possible to write that text in continuously without it being split? Thank you for any help!
2013/07/11
[ "https://askubuntu.com/questions/318777", "https://askubuntu.com", "https://askubuntu.com/users/148317/" ]
You can use the AWK utility: ``` awk 'FNR==1{print ""}{print}' *files > newfile ``` Source: <https://stackoverflow.com/questions/1653063/how-do-i-include-a-blank-line-between-files-im-concatenating-with-cat>
You can use `cat` to dump the text of files into one file with: ``` cat file1 file2 file3 > newfile ```
318,777
I am using the unix `pr` command to combine multiple text files into one text file: ``` pr -F *files > newfile ``` Each file is a different length, a different number of lines. I am mostly happy with the result, I like that it includes the name of the original text file followed by the contents of that file. However, I would like to eliminate the blank lines in between the name of the original text file and it's contents. I only want blank lines between the different text files to separate each. Also, it prints the character `^L` after the contents of each text file, and I would like to eliminate that character. Each file read in is also given a 'page' number. Only one file is longer than the 66 line default. that file ends up being spit into 2 'pages', and is split into 2 sections divided by blank lines. Is it possible to write that text in continuously without it being split? Thank you for any help!
2013/07/11
[ "https://askubuntu.com/questions/318777", "https://askubuntu.com", "https://askubuntu.com/users/148317/" ]
To have empty lines betwen files: ``` cat file1 newline file2 newline file3 > newfile ``` Where 'newline' is file with empty line.
You can use `cat` to dump the text of files into one file with: ``` cat file1 file2 file3 > newfile ```
318,777
I am using the unix `pr` command to combine multiple text files into one text file: ``` pr -F *files > newfile ``` Each file is a different length, a different number of lines. I am mostly happy with the result, I like that it includes the name of the original text file followed by the contents of that file. However, I would like to eliminate the blank lines in between the name of the original text file and it's contents. I only want blank lines between the different text files to separate each. Also, it prints the character `^L` after the contents of each text file, and I would like to eliminate that character. Each file read in is also given a 'page' number. Only one file is longer than the 66 line default. that file ends up being spit into 2 'pages', and is split into 2 sections divided by blank lines. Is it possible to write that text in continuously without it being split? Thank you for any help!
2013/07/11
[ "https://askubuntu.com/questions/318777", "https://askubuntu.com", "https://askubuntu.com/users/148317/" ]
``` for file in *.txt; do (cat "${file}"; echo) >> concatenated.txt; done ``` The above will append the contents of eacb txt file into concatenated.txt adding a new line between them.
You can use `cat` to dump the text of files into one file with: ``` cat file1 file2 file3 > newfile ```
318,777
I am using the unix `pr` command to combine multiple text files into one text file: ``` pr -F *files > newfile ``` Each file is a different length, a different number of lines. I am mostly happy with the result, I like that it includes the name of the original text file followed by the contents of that file. However, I would like to eliminate the blank lines in between the name of the original text file and it's contents. I only want blank lines between the different text files to separate each. Also, it prints the character `^L` after the contents of each text file, and I would like to eliminate that character. Each file read in is also given a 'page' number. Only one file is longer than the 66 line default. that file ends up being spit into 2 'pages', and is split into 2 sections divided by blank lines. Is it possible to write that text in continuously without it being split? Thank you for any help!
2013/07/11
[ "https://askubuntu.com/questions/318777", "https://askubuntu.com", "https://askubuntu.com/users/148317/" ]
You can use the AWK utility: ``` awk 'FNR==1{print ""}{print}' *files > newfile ``` Source: <https://stackoverflow.com/questions/1653063/how-do-i-include-a-blank-line-between-files-im-concatenating-with-cat>
``` for file in *.txt; do (cat "${file}"; echo) >> concatenated.txt; done ``` The above will append the contents of eacb txt file into concatenated.txt adding a new line between them.
318,777
I am using the unix `pr` command to combine multiple text files into one text file: ``` pr -F *files > newfile ``` Each file is a different length, a different number of lines. I am mostly happy with the result, I like that it includes the name of the original text file followed by the contents of that file. However, I would like to eliminate the blank lines in between the name of the original text file and it's contents. I only want blank lines between the different text files to separate each. Also, it prints the character `^L` after the contents of each text file, and I would like to eliminate that character. Each file read in is also given a 'page' number. Only one file is longer than the 66 line default. that file ends up being spit into 2 'pages', and is split into 2 sections divided by blank lines. Is it possible to write that text in continuously without it being split? Thank you for any help!
2013/07/11
[ "https://askubuntu.com/questions/318777", "https://askubuntu.com", "https://askubuntu.com/users/148317/" ]
To have empty lines betwen files: ``` cat file1 newline file2 newline file3 > newfile ``` Where 'newline' is file with empty line.
``` for file in *.txt; do (cat "${file}"; echo) >> concatenated.txt; done ``` The above will append the contents of eacb txt file into concatenated.txt adding a new line between them.
2,176,180
I want to get the dynamic contents from a particular url: I have used the code ``` echo $content=file_get_contents('http://www.punoftheday.com/cgi-bin/arandompun.pl'); ``` I am getting following results: ``` document.write('"Bakers have a great knead to make bread." ') document.write('© 1996-2007 Pun of the Day.com ') ``` How can i get the string **Bakers have a great knead to make bread.** Only string inside first document.write will change, other code will remain constant Regards, Pankaj
2010/02/01
[ "https://Stackoverflow.com/questions/2176180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146192/" ]
You are fetching a JavaScript snippet that is supposed to be built in directly into the document, not queried by a script. The code inside is JavaScript. You could pull out the code using a regular expression, but I would advise against it. First, it's probably not legal to do. Second, the format of the data they serve can change any time, breaking your script. I think you should take at [**their RSS feed**](http://feeds.feedburner.com/PunOfTheDay). You can parse that programmatically way easier than the JavaScript. Check out this question on how to do that: [**Best way to parse RSS/Atom feeds with PHP**](https://stackoverflow.com/questions/250679/best-way-to-parse-rss-atom-feeds-with-php)
Pekka's answer is probably the best way of doing this. But anyway here's the regex you might want to use in case you find yourself doing something like this, and can't rely on RSS feeds etc. ``` document\.write\(' // start tag ([^)]*) // the data to match '\) // end tag ``` **EDIT** for example: ``` <?php $subject = "document.write('&quot;Paying for college is often a matter of in-tuition.&quot;<br />')\ndocument.write('<i>&copy; 1996-2007 <a target=\"_blank\" href=\"http://www.punoftheday.com\">Pun of the Day.com</a></i><br />')"; $pattern = "/document\.write\('([^)]*)'\)/"; preg_match($pattern, $subject, $matches); print_r($matches); ?> ```
2,176,180
I want to get the dynamic contents from a particular url: I have used the code ``` echo $content=file_get_contents('http://www.punoftheday.com/cgi-bin/arandompun.pl'); ``` I am getting following results: ``` document.write('"Bakers have a great knead to make bread." ') document.write('© 1996-2007 Pun of the Day.com ') ``` How can i get the string **Bakers have a great knead to make bread.** Only string inside first document.write will change, other code will remain constant Regards, Pankaj
2010/02/01
[ "https://Stackoverflow.com/questions/2176180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146192/" ]
You are fetching a JavaScript snippet that is supposed to be built in directly into the document, not queried by a script. The code inside is JavaScript. You could pull out the code using a regular expression, but I would advise against it. First, it's probably not legal to do. Second, the format of the data they serve can change any time, breaking your script. I think you should take at [**their RSS feed**](http://feeds.feedburner.com/PunOfTheDay). You can parse that programmatically way easier than the JavaScript. Check out this question on how to do that: [**Best way to parse RSS/Atom feeds with PHP**](https://stackoverflow.com/questions/250679/best-way-to-parse-rss-atom-feeds-with-php)
1) **several local methods** ``` <?php echo readfile("http://example.com/"); //needs "Allow_url_include" enabled echo include("http://example.com/"); //needs "Allow_url_include" enabled echo file_get_contents("http://example.com/"); echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled ?> ``` 2) **Better Way is CURL**: ``` echo get_remote_data('http://example.com'); // GET request echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request //============= https://github.com/tazotodua/useful-php-scripts/ =========== function get_remote_data($url, $post_paramtrs=false) { $c = curl_init();curl_setopt($c, CURLOPT_URL, $url);curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); if($post_paramtrs){curl_setopt($c, CURLOPT_POST,TRUE); curl_setopt($c, CURLOPT_POSTFIELDS, "var1=bla&".$post_paramtrs );} curl_setopt($c, CURLOPT_SSL_VERIFYHOST,false);curl_setopt($c, CURLOPT_SSL_VERIFYPEER,false);curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:33.0) Gecko/20100101 Firefox/33.0"); curl_setopt($c, CURLOPT_COOKIE, 'CookieName1=Value;'); curl_setopt($c, CURLOPT_MAXREDIRS, 10); $follow_allowed= ( ini_get('open_basedir') || ini_get('safe_mode')) ? false:true; if ($follow_allowed){curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);}curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 9);curl_setopt($c, CURLOPT_REFERER, $url);curl_setopt($c, CURLOPT_TIMEOUT, 60);curl_setopt($c, CURLOPT_AUTOREFERER, true); curl_setopt($c, CURLOPT_ENCODING, 'gzip,deflate');$data=curl_exec($c);$status=curl_getinfo($c);curl_close($c);preg_match('/(http(|s)):\/\/(.*?)\/(.*\/|)/si', $status['url'],$link);$data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/|\/)).*?)(\'|\")/si','$1=$2'.$link[0].'$3$4$5', $data);$data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/)).*?)(\'|\")/si','$1=$2'.$link[1].'://'.$link[3].'$3$4$5', $data);if($status['http_code']==200) {return $data;} elseif($status['http_code']==301 || $status['http_code']==302) { if (!$follow_allowed){if(empty($redirURL)){if(!empty($status['redirect_url'])){$redirURL=$status['redirect_url'];}} if(empty($redirURL)){preg_match('/(Location:|URI:)(.*?)(\r|\n)/si', $data, $m);if (!empty($m[2])){ $redirURL=$m[2]; } } if(empty($redirURL)){preg_match('/href\=\"(.*?)\"(.*?)here\<\/a\>/si',$data,$m); if (!empty($m[1])){ $redirURL=$m[1]; } } if(!empty($redirURL)){$t=debug_backtrace(); return call_user_func( $t[0]["function"], trim($redirURL), $post_paramtrs);}}} return "ERRORCODE22 with $url!!<br/>Last status codes<b/>:".json_encode($status)."<br/><br/>Last data got<br/>:$data";} ``` **NOTICE:** It automatically handles FOLLOWLOCATION problem + Remote urls are automatically re-corrected! ( src="./imageblabla.png" --------> src="http://example.com/path/imageblabla.png" ) p.s.on GNU/Linux distro servers, you might need to install the `php5-curl` package to use it.
13,894,589
When I started `JUnit Plug-in Test`, I always have eclipse GUI launched. Can I change the setup to prevent this? I'm testing eclipse plugin - [Difference between `JUnit Plug-in Test` and `JUnit Test` in eclipse](https://stackoverflow.com/questions/13894287/difference-between-junit-plug-in-test-and-junit-test-in-eclipse) ![enter image description here](https://i.stack.imgur.com/MK3GX.png) ![enter image description here](https://i.stack.imgur.com/zP9MN.png)
2012/12/15
[ "https://Stackoverflow.com/questions/13894589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
Are you developing Eclipse plugins (or an RCP application)? **No**: You don't want to run a "JUnit Plugin test". Always run your tests as "Junit test". **Yes**: On the "Main" tab of your Junit Plugin test launch configuration, select the radio button "Run an application" and choose the application "No application - Headless Mode".
In my opinion this is a problem of the Plug-in Development Environment (PDE) tooling of the Eclipse IDE. When you select “Run as > JUnit Plug-in Test”, Eclipse is starting all plug-ins in your workspace to run the tests. ![Run as > JUnit Plug-in Test](https://i.stack.imgur.com/BUbCE.png) You can check this by opening the corresponding “Run Configuration” ![Run Configurations](https://i.stack.imgur.com/u87lP.png) I do not know your exact set-up, but I guess that you do not need all the plugins when you run a unit test. Here is how I do it: 1. Switch to “plug-ins selected bellow only” 2. Click on “Delesect All” 3. Select the Bundle where your test are located (`org.eclipsescout.demo.minifigcreator.client.test` in my case) 4. Click on “Add required Plug-ins” 5. [optional] click on “Validate Plug-ins” (expected message: “No problems were detected”) 6. Click on “Run” ![Run Configurations - correct set of plug-ins](https://i.stack.imgur.com/LBmJA.png) Your test should now run, and no second eclipse workbench (Eclipse GUI) should be opened (unless you have a direct dependency to it). Depending on your setup (workspace, team, source control...), it might be usefull to save this as launcher file and to share it with your team (see the options in the “Commons” tab).
86,074
I want to be able to reference a table value in my text (this is because I often update my tables, and then list the specific values in the text). Here is an example table I would use: ``` % Example Table \documentclass{minimal} \begin{filecontents*}{scientists.csv} name,surname,age Albert,Einstein,133 Marie,Curie,145 Thomas,Edison,165 \end{filecontents*} % Read in Table \documentclass{article} \usepackage{pgfplotstable} \begin{document} \pgfplotstabletypeset[ col sep=comma, string type, columns/name/.style={column name=Name, column type={|l}}, columns/surname/.style={column name=Surname, column type={|l}}, columns/age/.style={column name=Age, column type={|c|}}, every head row/.style={before row=\hline,after row=\hline}, every last row/.style={after row=\hline}, ]{scientists.csv} \end{document} ``` I may want to be able to reference a given scientists age in the text by a reference of his/her name (ie,:) ``` Albert Einstein is \ref{albert} years old. ``` Ideally, this would still be using pgfplotstable because it is how I currently read in many tables. Thanks,
2012/12/08
[ "https://tex.stackexchange.com/questions/86074", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/21998/" ]
Another alternative without modifying the data is via `\pgfplotstablegetelem`...`\pgfplotsretval` pair. Note that the row index starts from 0 instead of 1. ``` \documentclass{article} \usepackage{pgfplotstable} \begin{filecontents*}{scientists.csv} name,surname,age Albert,Einstein,133 Marie,Curie,145 Thomas,Edison,165 \end{filecontents*} \pgfplotstableread[col sep=comma]{scientists.csv}\mytable \def\getcell#1#2#3{ \pgfplotstablegetelem{#1}{#2}\of{#3}\pgfplotsretval% } \begin{document} \pgfplotstabletypeset[ string type, columns/name/.style={column name=Name, column type={|l}}, columns/surname/.style={column name=Surname, column type={|l}}, columns/age/.style={column name=Age, column type={|c|}}, every head row/.style={before row=\hline,after row=\hline}, every last row/.style={after row=\hline}, ]\mytable \bigskip \getcell{0}{name}{\mytable} \getcell{0}{surname}{\mytable} is \getcell{0}{age}{\mytable} years old. \getcell{1}{name}{\mytable} \getcell{1}{surname}{\mytable} is \getcell{1}{age}{\mytable} years old. But \getcell{2}{name}{\mytable} \getcell{2}{surname}{\mytable} is still older, he is \getcell{2}{age}{\mytable} years old. \end{document} ``` ![enter image description here](https://i.stack.imgur.com/DDnL8.png)
If it is an option to have your csv files suitably prepared, try this (here I bundled the filecontents thing and the table in one latex source) ``` \documentclass{article} \makeatletter \def\printandsetlabel#1#2#3{#2\setcounter{#1}{#2}% \protected@edef\@currentlabel {\csname p@#1\endcsname\csname the#1\endcsname}% \label{#3}} \makeatother \newcounter{age} \newcommand*{\age}[2]{\printandsetlabel{age}{#1}{#2}} \begin{filecontents*}{scientists.csv} name,surname,age Albert,Einstein,\age{133}{albert} Marie,Curie,\age{145}{marie} Thomas,Edison,\age{165}{thomas} \end{filecontents*} % Read in Table \usepackage{pgfplotstable} \pgfplotsset{compat=1.7} \begin{document}\thispagestyle{empty}\hsize8cm \pgfplotstabletypeset[ col sep=comma, string type, columns/name/.style={column name=Name, column type={|l}}, columns/surname/.style={column name=Surname, column type={|l}}, columns/age/.style={column name=Age, column type={|c|}}, every head row/.style={before row=\hline,after row=\hline}, every last row/.style={after row=\hline}, ]{scientists.csv} \bigskip Albert Einstein is \ref{albert} years old and Marie Curie is \ref{marie} years old. But Thomas Edison is still older, he is \ref{thomas} years old. \end{document} ``` ![outcome of the code](https://i.stack.imgur.com/6Wm7E.png)
12,637,946
I have this common statement in my code ``` <body link="#FFFF00" vlink="#FFFF00" alink="#FFFF00"> ``` Web Expression 4 highlight the code with a message 'The World Wide Web Consortium now regards the attributes as outdated. Newer constructs are recommended.' Unfortunately it doesn't give me any more information. What code do I need to make it up to date?
2012/09/28
[ "https://Stackoverflow.com/questions/12637946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/595577/" ]
You shouldn't embed styling within the structure of HTML - that's why you are getting the message. It's been quite a while that a separation between the document structure and how it looks has been accepted as a good thing - style goes into CSS. To resolve the issue, use CSS. For links you should style the `a` element with the pseudo classes for `link`, `visited` and `active`: ``` a:link, a:visited, a:active { color: #FFFF00; } ```
The attributes still work the same way they used to. Replacing them with CSS would be trivial, but would not change anything (except in the relatively rare cases where CSS is disabled – then default link colors would be used). Using CSS would be useful if you wanted to use different colors for different links on a page, for example. The main problem with the code is not the way you set link colors but setting them to the same color and to a color that is not commonly recognized as indicating a link.
59,388,941
I want to achieve this requirement if vertical stack has two label than Text should be centre aligned to image [![enter image description here](https://i.stack.imgur.com/78wvS.png)](https://i.stack.imgur.com/78wvS.png) and if not than top aligned to Image [![enter image description here](https://i.stack.imgur.com/D2ZDp.png)](https://i.stack.imgur.com/D2ZDp.png) How can I achieve this without writing any code
2019/12/18
[ "https://Stackoverflow.com/questions/59388941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2442383/" ]
One other solution besides dask is to use `chunksize` parameter in `pd.read_csv`, then `pd.concat` your chunks. A quick example: ```py chunksize = 1000 l = pd.read_csv('doc.csv', chunksize=chunksize, iterator=True) df = pd.concat(l, ignore_index=True) ``` Addition: To do something with the chunks one by one you can use: ```py chunksize = 1000 for chunk in pd.read_csv('doc.csv', chunksize=chunksize, iterator=True): # do something with individual chucks there ``` To see the progress you can consider using tqdm. ```py from tqdm import tqdm chunksize = 1000 for chunk in tqdm(pd.read_csv('doc.csv', chunksize=chunksize, iterator=True)): # do something with individual chucks there ```
You could use [`dask`](https://dask.org/), which is specially built for this. ``` import dask.dataframe as dd dd.read_csv("doc.csv", sep = "\t").sum().compute() ```
59,388,941
I want to achieve this requirement if vertical stack has two label than Text should be centre aligned to image [![enter image description here](https://i.stack.imgur.com/78wvS.png)](https://i.stack.imgur.com/78wvS.png) and if not than top aligned to Image [![enter image description here](https://i.stack.imgur.com/D2ZDp.png)](https://i.stack.imgur.com/D2ZDp.png) How can I achieve this without writing any code
2019/12/18
[ "https://Stackoverflow.com/questions/59388941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2442383/" ]
You could use [`dask`](https://dask.org/), which is specially built for this. ``` import dask.dataframe as dd dd.read_csv("doc.csv", sep = "\t").sum().compute() ```
u can use `pandas.Series.append` and `pandas.DataFrame.sum` along with `pandas.DataFrame.iloc`, while reading the data in chunks, ``` row_sum = pd.Series([]) for chunk in pd.read_csv('doc.csv',sep = "\t" ,chunksize=50000): row_sum = row_sum.append(chunk.iloc[:,3:].sum(axis = 1, skipna = True)) ```
59,388,941
I want to achieve this requirement if vertical stack has two label than Text should be centre aligned to image [![enter image description here](https://i.stack.imgur.com/78wvS.png)](https://i.stack.imgur.com/78wvS.png) and if not than top aligned to Image [![enter image description here](https://i.stack.imgur.com/D2ZDp.png)](https://i.stack.imgur.com/D2ZDp.png) How can I achieve this without writing any code
2019/12/18
[ "https://Stackoverflow.com/questions/59388941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2442383/" ]
One other solution besides dask is to use `chunksize` parameter in `pd.read_csv`, then `pd.concat` your chunks. A quick example: ```py chunksize = 1000 l = pd.read_csv('doc.csv', chunksize=chunksize, iterator=True) df = pd.concat(l, ignore_index=True) ``` Addition: To do something with the chunks one by one you can use: ```py chunksize = 1000 for chunk in pd.read_csv('doc.csv', chunksize=chunksize, iterator=True): # do something with individual chucks there ``` To see the progress you can consider using tqdm. ```py from tqdm import tqdm chunksize = 1000 for chunk in tqdm(pd.read_csv('doc.csv', chunksize=chunksize, iterator=True)): # do something with individual chucks there ```
u can use `pandas.Series.append` and `pandas.DataFrame.sum` along with `pandas.DataFrame.iloc`, while reading the data in chunks, ``` row_sum = pd.Series([]) for chunk in pd.read_csv('doc.csv',sep = "\t" ,chunksize=50000): row_sum = row_sum.append(chunk.iloc[:,3:].sum(axis = 1, skipna = True)) ```
16,454,252
I have a Maven project. I have converted it to eclipse project using the command. ``` mvn eclipse:eclipse ``` **I imported this project to eclipse. I am getting missing library error.** I have updated the maven repository details in Maven setting of eclipse. My current maven repository is `E:\myfolder\repository` I have edited this my **settings.xml** too. ``` <localRepository>E:\myfolder\repository</localRepository> ``` I have added a class-path variable MAVEN\_REPO. ``` MAVEN_REPO = E:\myfolder\repository ``` **The actual address of the jar in repository is M2\_REPO/javax/ccpp/ccpp/1.0/ccpp-1.0.jar.** But the eclipse is not able to locate the jar in the repository. ``` It is taking default repository address. ``` Still I am getting missing library error and it is pointing to default maven repository address rather than my new repository address. ``` Project 'Testproj' is missing required library: '\\user dir\.m2\repository\antlr\antlr\2.7.6\antlr-2.7.6.jar' ``` Can some one tell how to overcome this error. Thanks in Advance.
2013/05/09
[ "https://Stackoverflow.com/questions/16454252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262477/" ]
In eclipse, go to `Preferences` > `Maven` > `Installations` Make sure that the **Global Settings** file is pointing to the right config and it is pointing to the right local repository.
Are you sure you did all the configurations and only then executed mvn eclipse:eclipse? Also is this mvn pointing to the same maven installation which you have configured? Before open the project in eclipse just check the generated .classpath file and see if it points to wrong location repo. Although I would suggest this - Eclipse has excellent maven plugin. You do not need to do mvn eclipse:eclipse. Simply import project in eclipse as maven project. Before import ensure the maven plugin is configured to use the same settings.xml which you have configured for command line maven.
16,454,252
I have a Maven project. I have converted it to eclipse project using the command. ``` mvn eclipse:eclipse ``` **I imported this project to eclipse. I am getting missing library error.** I have updated the maven repository details in Maven setting of eclipse. My current maven repository is `E:\myfolder\repository` I have edited this my **settings.xml** too. ``` <localRepository>E:\myfolder\repository</localRepository> ``` I have added a class-path variable MAVEN\_REPO. ``` MAVEN_REPO = E:\myfolder\repository ``` **The actual address of the jar in repository is M2\_REPO/javax/ccpp/ccpp/1.0/ccpp-1.0.jar.** But the eclipse is not able to locate the jar in the repository. ``` It is taking default repository address. ``` Still I am getting missing library error and it is pointing to default maven repository address rather than my new repository address. ``` Project 'Testproj' is missing required library: '\\user dir\.m2\repository\antlr\antlr\2.7.6\antlr-2.7.6.jar' ``` Can some one tell how to overcome this error. Thanks in Advance.
2013/05/09
[ "https://Stackoverflow.com/questions/16454252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262477/" ]
This is what worked for me: In Eclipse, Windows->Preferences->Maven->User Settings Even if the settings.xml was updated as expected it was still pointing to default directory. So i did 'Restore Defaults' then 'Apply' And then i again changed the Global Settings and User Settings to point to correct settings.xml. Do Reindex for local repository. Click OK and bang! Projects compiled perfectly!
Are you sure you did all the configurations and only then executed mvn eclipse:eclipse? Also is this mvn pointing to the same maven installation which you have configured? Before open the project in eclipse just check the generated .classpath file and see if it points to wrong location repo. Although I would suggest this - Eclipse has excellent maven plugin. You do not need to do mvn eclipse:eclipse. Simply import project in eclipse as maven project. Before import ensure the maven plugin is configured to use the same settings.xml which you have configured for command line maven.
16,454,252
I have a Maven project. I have converted it to eclipse project using the command. ``` mvn eclipse:eclipse ``` **I imported this project to eclipse. I am getting missing library error.** I have updated the maven repository details in Maven setting of eclipse. My current maven repository is `E:\myfolder\repository` I have edited this my **settings.xml** too. ``` <localRepository>E:\myfolder\repository</localRepository> ``` I have added a class-path variable MAVEN\_REPO. ``` MAVEN_REPO = E:\myfolder\repository ``` **The actual address of the jar in repository is M2\_REPO/javax/ccpp/ccpp/1.0/ccpp-1.0.jar.** But the eclipse is not able to locate the jar in the repository. ``` It is taking default repository address. ``` Still I am getting missing library error and it is pointing to default maven repository address rather than my new repository address. ``` Project 'Testproj' is missing required library: '\\user dir\.m2\repository\antlr\antlr\2.7.6\antlr-2.7.6.jar' ``` Can some one tell how to overcome this error. Thanks in Advance.
2013/05/09
[ "https://Stackoverflow.com/questions/16454252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262477/" ]
In eclipse, go to `Preferences` > `Maven` > `Installations` Make sure that the **Global Settings** file is pointing to the right config and it is pointing to the right local repository.
This is what worked for me: In Eclipse, Windows->Preferences->Maven->User Settings Even if the settings.xml was updated as expected it was still pointing to default directory. So i did 'Restore Defaults' then 'Apply' And then i again changed the Global Settings and User Settings to point to correct settings.xml. Do Reindex for local repository. Click OK and bang! Projects compiled perfectly!
8,487,843
My Java program that opens up a webcam stream and streams the captured video to a Swing component works, but when I launch it, it causes Windows to switch to the Basic theme. This is an excerpt from my code: ``` String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; captureDeviceInfo = CaptureDeviceManager.getDevice(str2); Format[] formats = captureDeviceInfo.getFormats(); for (Format format : formats) { System.out.println(format); } mediaLocator = captureDeviceInfo.getLocator(); try { player = Manager.createRealizedPlayer(mediaLocator); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { playerPanel.add(comp); add(playerPanel, BorderLayout.NORTH); } ``` If I comment out the line where the I add comp to playerPanel, it doesn't switch to the basic theme, so I assume that's where it goes wrong. From what I understand JMF is not maintained anymore and probably isn't fully compatible with Windows 7 Aero Theme. But still, is there a way to fix this? Why does it switch?
2011/12/13
[ "https://Stackoverflow.com/questions/8487843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230654/" ]
> > What is the technical name for them (ATL? ActiveX? ActiveX control? Automation? or...?) > > > Internet Explorer refers to both as *ActiveX controls* (see the *Type* column in the image below) ![](https://kb2.adobe.com/cps/194/tn_19482/images/manage_add.gif) * **ATL (Active Template Library)** refers to a library that simplifies the creation of COM objects, including ActiveX controls. * **Automation** refers to the technology for inter-process communication on which ActiveX controls are built. ActiveX controls may be referred to as *Automation objects*. > > And how are they different from objects that can be used in IE this way > > > ActiveX controls instantiated through JavaScript are referred to by **Programmatic Identifier (ProgID)** and have no user interface. Controls placed in the document as `<object>` tags, commonly referred to as *user controls*, are specified by **Class Identifier (ClassID)** and *may have* a user interface. `<object>` tags also inherit various traits of HTML elements.
This family of late-bound objects are most often referred to as COM (Common Object Model) Objects. The loosely applied term "COM" typically encompasses any OLE, OLE Automation, ActiveX, COM+, or DCOM object. Essentially, this is any object that provides a scriptable (IUnknown) interface through any number of technologies.
8,487,843
My Java program that opens up a webcam stream and streams the captured video to a Swing component works, but when I launch it, it causes Windows to switch to the Basic theme. This is an excerpt from my code: ``` String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; captureDeviceInfo = CaptureDeviceManager.getDevice(str2); Format[] formats = captureDeviceInfo.getFormats(); for (Format format : formats) { System.out.println(format); } mediaLocator = captureDeviceInfo.getLocator(); try { player = Manager.createRealizedPlayer(mediaLocator); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { playerPanel.add(comp); add(playerPanel, BorderLayout.NORTH); } ``` If I comment out the line where the I add comp to playerPanel, it doesn't switch to the basic theme, so I assume that's where it goes wrong. From what I understand JMF is not maintained anymore and probably isn't fully compatible with Windows 7 Aero Theme. But still, is there a way to fix this? Why does it switch?
2011/12/13
[ "https://Stackoverflow.com/questions/8487843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230654/" ]
From the documentation of ActiveXObject function in MSDN: An object that provides an interface to an **Automation object**. An automation object is a COM object whose class exposes IDispatch. ActiveX control, strictly speaking, is designed for a container. The OLE interfaces like IOleObject and IOleControl define the contract between the control and its host. An ActiveX may or may not provide automation interface via IDispatch. If an ActiveX does provide automation interface, we call it a dual Interface ActiveX or scriptable ActiveX, which means the ActiveX can be used in late-binding languages like Jscript. ATL is a class library in Visual C++. It is designed to writing ActiveX , yes, but it can also be used to write windows services and other libraries (e.g. MFC) and apps. Of course it is not necessary in writing ActiveX, there were many ActiveX controls written before it was invented. There are many other components that are also associated with ActiveX. ActiveX documents (e.g. Adobe Reader, Microsoft Word) is a type of documents that can be hosted in ActiveX documents servers, such as an Internet Explorer frame. An ActiveX-enabled application (e.g. Microsoft Word, Windows Media Player) runs in its own process but can be automated via automation interface.
This family of late-bound objects are most often referred to as COM (Common Object Model) Objects. The loosely applied term "COM" typically encompasses any OLE, OLE Automation, ActiveX, COM+, or DCOM object. Essentially, this is any object that provides a scriptable (IUnknown) interface through any number of technologies.
8,487,843
My Java program that opens up a webcam stream and streams the captured video to a Swing component works, but when I launch it, it causes Windows to switch to the Basic theme. This is an excerpt from my code: ``` String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; captureDeviceInfo = CaptureDeviceManager.getDevice(str2); Format[] formats = captureDeviceInfo.getFormats(); for (Format format : formats) { System.out.println(format); } mediaLocator = captureDeviceInfo.getLocator(); try { player = Manager.createRealizedPlayer(mediaLocator); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { playerPanel.add(comp); add(playerPanel, BorderLayout.NORTH); } ``` If I comment out the line where the I add comp to playerPanel, it doesn't switch to the basic theme, so I assume that's where it goes wrong. From what I understand JMF is not maintained anymore and probably isn't fully compatible with Windows 7 Aero Theme. But still, is there a way to fix this? Why does it switch?
2011/12/13
[ "https://Stackoverflow.com/questions/8487843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230654/" ]
> > What is the technical name for them (ATL? ActiveX? ActiveX control? Automation? or...?) > > > Internet Explorer refers to both as *ActiveX controls* (see the *Type* column in the image below) ![](https://kb2.adobe.com/cps/194/tn_19482/images/manage_add.gif) * **ATL (Active Template Library)** refers to a library that simplifies the creation of COM objects, including ActiveX controls. * **Automation** refers to the technology for inter-process communication on which ActiveX controls are built. ActiveX controls may be referred to as *Automation objects*. > > And how are they different from objects that can be used in IE this way > > > ActiveX controls instantiated through JavaScript are referred to by **Programmatic Identifier (ProgID)** and have no user interface. Controls placed in the document as `<object>` tags, commonly referred to as *user controls*, are specified by **Class Identifier (ClassID)** and *may have* a user interface. `<object>` tags also inherit various traits of HTML elements.
From the documentation of ActiveXObject function in MSDN: An object that provides an interface to an **Automation object**. An automation object is a COM object whose class exposes IDispatch. ActiveX control, strictly speaking, is designed for a container. The OLE interfaces like IOleObject and IOleControl define the contract between the control and its host. An ActiveX may or may not provide automation interface via IDispatch. If an ActiveX does provide automation interface, we call it a dual Interface ActiveX or scriptable ActiveX, which means the ActiveX can be used in late-binding languages like Jscript. ATL is a class library in Visual C++. It is designed to writing ActiveX , yes, but it can also be used to write windows services and other libraries (e.g. MFC) and apps. Of course it is not necessary in writing ActiveX, there were many ActiveX controls written before it was invented. There are many other components that are also associated with ActiveX. ActiveX documents (e.g. Adobe Reader, Microsoft Word) is a type of documents that can be hosted in ActiveX documents servers, such as an Internet Explorer frame. An ActiveX-enabled application (e.g. Microsoft Word, Windows Media Player) runs in its own process but can be automated via automation interface.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
There are three things which effect compatibility and performance when connecting external storage: 1. The physical connector and cable. The 2020 iMac has four USB Type A (USB-A) and two USB Type C (USB-C) connectors. 2. The data transfer protocol - USB 1, USB 2, USB 3 (and later variants 3.1 and 3.2) and Thunderbolt. There is also USB 4, but this is not relevant to 2020 iMac. The 202O iMac supports: * USB-A ports: USB 3.0 (maximum speed 5 Gbits/s) and slower USB 2 and USB 1. * USB-C ports: Thunderbolt 3 (maximum speed 40 Gbits/s), USB 3.1 gen2 (10 Gbits/s), and slower USB 3.1 speeds. 3. The drive inside the external device/enclosure. Common types are are SATA (maximum speed 6 Gbits/s) or NVMe (faster). HDD are usually SATA, whilst SSDs might be SATA or NVMe. The 5 Gbit/s USB 3.1 gen1 and 3.2 gen1x1 standards are similar to USB 3.0 and storage devices specifying these are generally compatible with USB 3.0 via the USB-A ports. Further, the 10 Gbit/s USB 3.2 gen2x1 is very close to USB 3.1 gen2. So storage devices specifying USB 3.2 gen2x1 should be compatible with the 10 Gbit/s USB 3.1 gen2 protocol delivered by the USB-C ports. As well as the the iMac ports supporting or being compatible with multiple data protocols, most USB storage devices support multiple data protocols and (in many cases) both USB-A and USB-C cables and computer ports. For an overview of USB standards read [Wikipedia](https://en.wikipedia.org/wiki/USB). Thunderbolt is a different connection standard developed by Intel (in collaboration with Apple) when Apple saw a need for a faster connection than that provided by USB 3. The first two iterations of the standard used the Mini DisplayPort physical connector on iMacs, whereas Thunderbolt 3 uses USB-C. Thunderbolt and USB standards have now converged with Thunderbolt 4 and USB 4 being very similar. For more detail, read [Wikipedia](https://en.wikipedia.org/wiki/Thunderbolt_(interface)). The current 2021 iMacs support Thunderbolt 3 and USB 4 (using USB-C physical ports). For the 2020 iMac, Thunderbolt 3 storage devices can only be connected to the USB-C ports and must use Thunderbolt 3 cables. Older Thunderbolt 1 and 2 devices can only be connected using cables which convert to Thunderbolt 3 - the iMac does not directly support Thunderbolt 1 and 2. Note that physical USB-C ports which support Thunderbolt 3 have a thunderbolt like symbol next to them. To further confuse matters (but out of scope for this question) USB-C ports also support connecting monitors using, for examples, Display Port and HDMI standards. **What should you be looking for:** For maximum speed (and cost) you should be looking for a Thunderbolt 3 SSD storage device. These can have performance similar to the internal SSD (~2000 MByte/s). Example: Samsung X5. For a more modest cost, there are SSDs which use USB 3.1 Gen 2 (or 3.2 Gen 2x1) and via the USB-C ports on the iMac will deliver ~1000 Mbyte/s. Example: Sumsung T7. And for a slightly more modest cost there are SSDs which use USB 3.1 Gen 2, but internally use SATA SSDs and deliver only ~500 Mbyte/s. Example: Samsung T5. These devices can connect to either USB-C or USB-A ports using USB 3.0, 3.1 Gen1/2 or 3.2 Gen1/2 - the differences in speed are minor as the SATA SSD becomes the bottleneck. Unless you have a professional need for highest speed, devices like the Samsung T7 (or T5) provide fast secondary storage. I have just used Samsung as examples. There are other equally good (and some not quite so good) brands.
I have a 2018 Mac mini which has the same USB and Thunderbolt 3 capabilities as your Mac. I also have a Thunderbolt 3 [Samsung X5](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) SSD and a 10 Gb/s USB [Samsung T7](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) SSD. I will base my answers on what I know about this hardware. --- When the Thunderbolt 3 Samsung X5 is connected to the Mac through a USB Type-C receptacle (jack), System Information displays the following under NVMExpress. [![NVMExpress](https://i.stack.imgur.com/5RrB5.png)](https://i.stack.imgur.com/5RrB5.png) Like the internal drive, the Thunderbolt 3 Samsung X5 appears as a NVMExpress drive, except the drive is external. Note that [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) is supported. System Information also displays the following under Thunderbolt. [![Thunderbolt 3](https://i.stack.imgur.com/dKaXY.png)](https://i.stack.imgur.com/dKaXY.png) The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s. In terms of bits per second, this would be 22.4 Gb/s, since 8 bits = 8 byte. Since the speed shown in the image above is up to 40 Gb/s, one can conclude the read speed of 22.4 Gb/s is not limited by Thunderbolt 3, but rather by the NVMe drive inside the Samsung X5. --- When the USB Samsung T7 is connected to the Mac through a USB Type-C receptacle, System Information displays the following under USB. [![Type-C](https://i.stack.imgur.com/evL4n.png)](https://i.stack.imgur.com/evL4n.png) The data transfer speed is unto 10 Gb/s. This is the maximum speed for USB devices connected a USB Type-C receptacle on both of our Macs. There is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support, which may not be necessary if the embedded PCIe NVMe technology is sufficiently fast. --- When the USB Samsung T7 is plugged in a USB Type-A receptacle on the Mac, System Information displays the following under USB. > > Note: The USB Samsung T7 comes a cable for plugging into a USB Type-C receptacle and a different cable for plugging into a USB Type-A receptacle. > > > [![Type-A](https://i.stack.imgur.com/RtXe3.png)](https://i.stack.imgur.com/RtXe3.png) The data transfer speed is unto 5 Gb/s. This is the maximum speed for USB devices connected a USB Type-A receptacle on both of our Macs. Again, there is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support. --- Conclusions ----------- You post contains the following four questions. * What is the fastest external storage supported on Intel 2020 27" iMac? The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s, which is 22.4 Gb/s. This means the data rate between the external drive and the Mac must exceed 22.4 Gb/s, which is faster than the maximum USB data rate of 10 Gb/s offered my your Mac. From this, the following conclusion can be made. **>Nothing that USB offers will be faster than what Thunderbolt 3 offers and also be compatible with your Mac.** * What does the 2020 Intel iMac 27" support? The The USB Type-C receptacles support at least the following devices. Self powered Thunderbolt 1 Self powered Thunderbolt 2 Thunderbolt 3 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) USB 3.1 Gen 2 (same as USB 3.2 Gen 2×1) > > Note: Apple's [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter) does not provide power from the Mac to the device. > > > The The USB Type-A receptacles support at least the following devices. USB 1.1 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) * What does that mean for data transfer speeds? The USB Type-C receptacles offer Thunderbolt 3 speeds up 40 Gb/s and USB speeds up to 10 Gb/s. The USB Type-A receptacles offer USB speeds up to 5 Gb/s. * When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option? Look for a Thunderbolt 3 SSD with high with read/write speeds (in the GB/s range). The SSD should also support [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)). You can also look for a Thunderbolt 1 and 2 SSD, but these drives would need to be self powered and would require a [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter). However, finding a self power Thunderbolt 1 or Thunderbolt 2 SDD at a price lower than Thunderbolt 3 SSD is unlikely. --- Speed Comparisons ----------------- | | T5External SSD | T7External SSD | X5External SSD | 27" 2020 iMacInternal SSD | 27" 2020 iMacInternal SSD | | --- | --- | --- | --- | --- | --- | | Source | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [StorageReview](https://www.storagereview.com/review/samsung-ssd-t7-review) | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [Tom's Guide](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | [PC Magazine](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | | Capacity | 1 TB | 2 TB | 1 TB | 1 TB | 1 TB | | BenchmarkApplications | NovabenchandBlackmagic | Blackmagic | NovabenchandBlackmagic | Blackmagic | Blackmagic | | AverageRead | 518 MBps | 894 MBps | 2410 MBps | 2467 MBps | 2427 MBps | | AverageWrite | 475 MBps | 840 MBps | 1708 MBps | 2757 MBps | 2735 MBps | Advertised Specifications ------------------------- | | T5 External SSD | T7 External SSD | X5 External SSD | | --- | --- | --- | --- | | Source | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t5/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) | | Interface | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 40 Gbps(Thunderbolt 3) | | Read | Up to540 MBps | Up to1050 MBps | Up to2800 MBps | | Write | Up to540 MBps | Up to1000 MBps | Up to2300 MBps |
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
The fastest port on your iMac is the Thunderbolt port. It can support data rates as high as 40Gbit/s, which is 5GB/s. Now most consumer SSDs are pretty fast but won't exceed that theoretical limit of 5GB/s. The fastet you can usually get is about 3GB/s, which you could do with [this enclosure](https://www.amazon.de/Nvme-Geh%C3%A4use-Kompatibel-Thunderbolt-3-Schnittstelle-Solid-State-NVME-SSD-Universal-Tools/dp/B08X9YTWJC/ref=sr_1_4?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=Thunderbolt%20SSD&qid=1627032726&sr=8-4) and basically any NVME SSD that fits that criteria mentioned in the product page. --- About the confusion of Thunderbolt: Thunderbolt and Thunderbolt 2 was primarily used on Macs and most Windows Computers "only" had USB. Thunderbolt is more versatile than the older USB 2 and USB 1 standard. It is able to support e.g. display connections through the DisplayPort standard which was integrated in the Thunderbolt specs, which normal USB 1 and 2 did not include. Older USB and Thunderbolt ports did not share the same connector so distinction was easy. Nowadays the USB-C connector is the same as Thunderbolt 3, even USB 4 and Thunderbolt 4 use this connector. However USB-C is not generally as powerful as Thunderbolt 3. The supported protocols however, may differ. I.e. you could have a USB-C connector which only supports the USB 3.1 protocol while an other one looking identical would support USB 3.2.
Im keeping this fairly non-technical, so I'm sure someone will be along to quibble with the details. ;-) Thunderbolt is "lots of different things". It includes PCIe, which is the standard for connecting devices to computers' motherboards. So instead of having a slot on the board, you now have a cable. It also includes DisplayPort video signals, and power. This is why you can use Thunderbolt to connect to a 'hub' that provides more USB ports, video ports, SD card readers, and Ethernet. It's a motorway for different vehicles. Thunderbolt 1, 2, 3 (and 4!) are just newer, faster iterations of the technology. (As with USB.) USB was devised as a general means of connecting devices: mice, keyboards, drives, etc. Thunderbolt devices will generally be slightly faster than USB ones. And by faster, I mean expensive. NVMe is a property of the device itself, rather than a 'transport'.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
There are three things which effect compatibility and performance when connecting external storage: 1. The physical connector and cable. The 2020 iMac has four USB Type A (USB-A) and two USB Type C (USB-C) connectors. 2. The data transfer protocol - USB 1, USB 2, USB 3 (and later variants 3.1 and 3.2) and Thunderbolt. There is also USB 4, but this is not relevant to 2020 iMac. The 202O iMac supports: * USB-A ports: USB 3.0 (maximum speed 5 Gbits/s) and slower USB 2 and USB 1. * USB-C ports: Thunderbolt 3 (maximum speed 40 Gbits/s), USB 3.1 gen2 (10 Gbits/s), and slower USB 3.1 speeds. 3. The drive inside the external device/enclosure. Common types are are SATA (maximum speed 6 Gbits/s) or NVMe (faster). HDD are usually SATA, whilst SSDs might be SATA or NVMe. The 5 Gbit/s USB 3.1 gen1 and 3.2 gen1x1 standards are similar to USB 3.0 and storage devices specifying these are generally compatible with USB 3.0 via the USB-A ports. Further, the 10 Gbit/s USB 3.2 gen2x1 is very close to USB 3.1 gen2. So storage devices specifying USB 3.2 gen2x1 should be compatible with the 10 Gbit/s USB 3.1 gen2 protocol delivered by the USB-C ports. As well as the the iMac ports supporting or being compatible with multiple data protocols, most USB storage devices support multiple data protocols and (in many cases) both USB-A and USB-C cables and computer ports. For an overview of USB standards read [Wikipedia](https://en.wikipedia.org/wiki/USB). Thunderbolt is a different connection standard developed by Intel (in collaboration with Apple) when Apple saw a need for a faster connection than that provided by USB 3. The first two iterations of the standard used the Mini DisplayPort physical connector on iMacs, whereas Thunderbolt 3 uses USB-C. Thunderbolt and USB standards have now converged with Thunderbolt 4 and USB 4 being very similar. For more detail, read [Wikipedia](https://en.wikipedia.org/wiki/Thunderbolt_(interface)). The current 2021 iMacs support Thunderbolt 3 and USB 4 (using USB-C physical ports). For the 2020 iMac, Thunderbolt 3 storage devices can only be connected to the USB-C ports and must use Thunderbolt 3 cables. Older Thunderbolt 1 and 2 devices can only be connected using cables which convert to Thunderbolt 3 - the iMac does not directly support Thunderbolt 1 and 2. Note that physical USB-C ports which support Thunderbolt 3 have a thunderbolt like symbol next to them. To further confuse matters (but out of scope for this question) USB-C ports also support connecting monitors using, for examples, Display Port and HDMI standards. **What should you be looking for:** For maximum speed (and cost) you should be looking for a Thunderbolt 3 SSD storage device. These can have performance similar to the internal SSD (~2000 MByte/s). Example: Samsung X5. For a more modest cost, there are SSDs which use USB 3.1 Gen 2 (or 3.2 Gen 2x1) and via the USB-C ports on the iMac will deliver ~1000 Mbyte/s. Example: Sumsung T7. And for a slightly more modest cost there are SSDs which use USB 3.1 Gen 2, but internally use SATA SSDs and deliver only ~500 Mbyte/s. Example: Samsung T5. These devices can connect to either USB-C or USB-A ports using USB 3.0, 3.1 Gen1/2 or 3.2 Gen1/2 - the differences in speed are minor as the SATA SSD becomes the bottleneck. Unless you have a professional need for highest speed, devices like the Samsung T7 (or T5) provide fast secondary storage. I have just used Samsung as examples. There are other equally good (and some not quite so good) brands.
Im keeping this fairly non-technical, so I'm sure someone will be along to quibble with the details. ;-) Thunderbolt is "lots of different things". It includes PCIe, which is the standard for connecting devices to computers' motherboards. So instead of having a slot on the board, you now have a cable. It also includes DisplayPort video signals, and power. This is why you can use Thunderbolt to connect to a 'hub' that provides more USB ports, video ports, SD card readers, and Ethernet. It's a motorway for different vehicles. Thunderbolt 1, 2, 3 (and 4!) are just newer, faster iterations of the technology. (As with USB.) USB was devised as a general means of connecting devices: mice, keyboards, drives, etc. Thunderbolt devices will generally be slightly faster than USB ones. And by faster, I mean expensive. NVMe is a property of the device itself, rather than a 'transport'.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
I have a 2018 Mac mini which has the same USB and Thunderbolt 3 capabilities as your Mac. I also have a Thunderbolt 3 [Samsung X5](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) SSD and a 10 Gb/s USB [Samsung T7](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) SSD. I will base my answers on what I know about this hardware. --- When the Thunderbolt 3 Samsung X5 is connected to the Mac through a USB Type-C receptacle (jack), System Information displays the following under NVMExpress. [![NVMExpress](https://i.stack.imgur.com/5RrB5.png)](https://i.stack.imgur.com/5RrB5.png) Like the internal drive, the Thunderbolt 3 Samsung X5 appears as a NVMExpress drive, except the drive is external. Note that [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) is supported. System Information also displays the following under Thunderbolt. [![Thunderbolt 3](https://i.stack.imgur.com/dKaXY.png)](https://i.stack.imgur.com/dKaXY.png) The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s. In terms of bits per second, this would be 22.4 Gb/s, since 8 bits = 8 byte. Since the speed shown in the image above is up to 40 Gb/s, one can conclude the read speed of 22.4 Gb/s is not limited by Thunderbolt 3, but rather by the NVMe drive inside the Samsung X5. --- When the USB Samsung T7 is connected to the Mac through a USB Type-C receptacle, System Information displays the following under USB. [![Type-C](https://i.stack.imgur.com/evL4n.png)](https://i.stack.imgur.com/evL4n.png) The data transfer speed is unto 10 Gb/s. This is the maximum speed for USB devices connected a USB Type-C receptacle on both of our Macs. There is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support, which may not be necessary if the embedded PCIe NVMe technology is sufficiently fast. --- When the USB Samsung T7 is plugged in a USB Type-A receptacle on the Mac, System Information displays the following under USB. > > Note: The USB Samsung T7 comes a cable for plugging into a USB Type-C receptacle and a different cable for plugging into a USB Type-A receptacle. > > > [![Type-A](https://i.stack.imgur.com/RtXe3.png)](https://i.stack.imgur.com/RtXe3.png) The data transfer speed is unto 5 Gb/s. This is the maximum speed for USB devices connected a USB Type-A receptacle on both of our Macs. Again, there is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support. --- Conclusions ----------- You post contains the following four questions. * What is the fastest external storage supported on Intel 2020 27" iMac? The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s, which is 22.4 Gb/s. This means the data rate between the external drive and the Mac must exceed 22.4 Gb/s, which is faster than the maximum USB data rate of 10 Gb/s offered my your Mac. From this, the following conclusion can be made. **>Nothing that USB offers will be faster than what Thunderbolt 3 offers and also be compatible with your Mac.** * What does the 2020 Intel iMac 27" support? The The USB Type-C receptacles support at least the following devices. Self powered Thunderbolt 1 Self powered Thunderbolt 2 Thunderbolt 3 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) USB 3.1 Gen 2 (same as USB 3.2 Gen 2×1) > > Note: Apple's [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter) does not provide power from the Mac to the device. > > > The The USB Type-A receptacles support at least the following devices. USB 1.1 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) * What does that mean for data transfer speeds? The USB Type-C receptacles offer Thunderbolt 3 speeds up 40 Gb/s and USB speeds up to 10 Gb/s. The USB Type-A receptacles offer USB speeds up to 5 Gb/s. * When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option? Look for a Thunderbolt 3 SSD with high with read/write speeds (in the GB/s range). The SSD should also support [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)). You can also look for a Thunderbolt 1 and 2 SSD, but these drives would need to be self powered and would require a [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter). However, finding a self power Thunderbolt 1 or Thunderbolt 2 SDD at a price lower than Thunderbolt 3 SSD is unlikely. --- Speed Comparisons ----------------- | | T5External SSD | T7External SSD | X5External SSD | 27" 2020 iMacInternal SSD | 27" 2020 iMacInternal SSD | | --- | --- | --- | --- | --- | --- | | Source | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [StorageReview](https://www.storagereview.com/review/samsung-ssd-t7-review) | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [Tom's Guide](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | [PC Magazine](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | | Capacity | 1 TB | 2 TB | 1 TB | 1 TB | 1 TB | | BenchmarkApplications | NovabenchandBlackmagic | Blackmagic | NovabenchandBlackmagic | Blackmagic | Blackmagic | | AverageRead | 518 MBps | 894 MBps | 2410 MBps | 2467 MBps | 2427 MBps | | AverageWrite | 475 MBps | 840 MBps | 1708 MBps | 2757 MBps | 2735 MBps | Advertised Specifications ------------------------- | | T5 External SSD | T7 External SSD | X5 External SSD | | --- | --- | --- | --- | | Source | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t5/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) | | Interface | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 40 Gbps(Thunderbolt 3) | | Read | Up to540 MBps | Up to1050 MBps | Up to2800 MBps | | Write | Up to540 MBps | Up to1000 MBps | Up to2300 MBps |
If you see Mactracker : <https://apps.apple.com/us/app/mactracker/id430255202?mt=12> your Mac have 2 Thunderbolt 3 port : ``` Thunderbolt 2 - Thunderbolt 3 (up to 40 Gbps) ``` So it's the fastest on your Mac. The externals enclosures SSD Thunderbolt 3 have inside a NVME SSD. For exemple you have the Samsung X5.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
If you see Mactracker : <https://apps.apple.com/us/app/mactracker/id430255202?mt=12> your Mac have 2 Thunderbolt 3 port : ``` Thunderbolt 2 - Thunderbolt 3 (up to 40 Gbps) ``` So it's the fastest on your Mac. The externals enclosures SSD Thunderbolt 3 have inside a NVME SSD. For exemple you have the Samsung X5.
Im keeping this fairly non-technical, so I'm sure someone will be along to quibble with the details. ;-) Thunderbolt is "lots of different things". It includes PCIe, which is the standard for connecting devices to computers' motherboards. So instead of having a slot on the board, you now have a cable. It also includes DisplayPort video signals, and power. This is why you can use Thunderbolt to connect to a 'hub' that provides more USB ports, video ports, SD card readers, and Ethernet. It's a motorway for different vehicles. Thunderbolt 1, 2, 3 (and 4!) are just newer, faster iterations of the technology. (As with USB.) USB was devised as a general means of connecting devices: mice, keyboards, drives, etc. Thunderbolt devices will generally be slightly faster than USB ones. And by faster, I mean expensive. NVMe is a property of the device itself, rather than a 'transport'.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
There are three things which effect compatibility and performance when connecting external storage: 1. The physical connector and cable. The 2020 iMac has four USB Type A (USB-A) and two USB Type C (USB-C) connectors. 2. The data transfer protocol - USB 1, USB 2, USB 3 (and later variants 3.1 and 3.2) and Thunderbolt. There is also USB 4, but this is not relevant to 2020 iMac. The 202O iMac supports: * USB-A ports: USB 3.0 (maximum speed 5 Gbits/s) and slower USB 2 and USB 1. * USB-C ports: Thunderbolt 3 (maximum speed 40 Gbits/s), USB 3.1 gen2 (10 Gbits/s), and slower USB 3.1 speeds. 3. The drive inside the external device/enclosure. Common types are are SATA (maximum speed 6 Gbits/s) or NVMe (faster). HDD are usually SATA, whilst SSDs might be SATA or NVMe. The 5 Gbit/s USB 3.1 gen1 and 3.2 gen1x1 standards are similar to USB 3.0 and storage devices specifying these are generally compatible with USB 3.0 via the USB-A ports. Further, the 10 Gbit/s USB 3.2 gen2x1 is very close to USB 3.1 gen2. So storage devices specifying USB 3.2 gen2x1 should be compatible with the 10 Gbit/s USB 3.1 gen2 protocol delivered by the USB-C ports. As well as the the iMac ports supporting or being compatible with multiple data protocols, most USB storage devices support multiple data protocols and (in many cases) both USB-A and USB-C cables and computer ports. For an overview of USB standards read [Wikipedia](https://en.wikipedia.org/wiki/USB). Thunderbolt is a different connection standard developed by Intel (in collaboration with Apple) when Apple saw a need for a faster connection than that provided by USB 3. The first two iterations of the standard used the Mini DisplayPort physical connector on iMacs, whereas Thunderbolt 3 uses USB-C. Thunderbolt and USB standards have now converged with Thunderbolt 4 and USB 4 being very similar. For more detail, read [Wikipedia](https://en.wikipedia.org/wiki/Thunderbolt_(interface)). The current 2021 iMacs support Thunderbolt 3 and USB 4 (using USB-C physical ports). For the 2020 iMac, Thunderbolt 3 storage devices can only be connected to the USB-C ports and must use Thunderbolt 3 cables. Older Thunderbolt 1 and 2 devices can only be connected using cables which convert to Thunderbolt 3 - the iMac does not directly support Thunderbolt 1 and 2. Note that physical USB-C ports which support Thunderbolt 3 have a thunderbolt like symbol next to them. To further confuse matters (but out of scope for this question) USB-C ports also support connecting monitors using, for examples, Display Port and HDMI standards. **What should you be looking for:** For maximum speed (and cost) you should be looking for a Thunderbolt 3 SSD storage device. These can have performance similar to the internal SSD (~2000 MByte/s). Example: Samsung X5. For a more modest cost, there are SSDs which use USB 3.1 Gen 2 (or 3.2 Gen 2x1) and via the USB-C ports on the iMac will deliver ~1000 Mbyte/s. Example: Sumsung T7. And for a slightly more modest cost there are SSDs which use USB 3.1 Gen 2, but internally use SATA SSDs and deliver only ~500 Mbyte/s. Example: Samsung T5. These devices can connect to either USB-C or USB-A ports using USB 3.0, 3.1 Gen1/2 or 3.2 Gen1/2 - the differences in speed are minor as the SATA SSD becomes the bottleneck. Unless you have a professional need for highest speed, devices like the Samsung T7 (or T5) provide fast secondary storage. I have just used Samsung as examples. There are other equally good (and some not quite so good) brands.
If you see Mactracker : <https://apps.apple.com/us/app/mactracker/id430255202?mt=12> your Mac have 2 Thunderbolt 3 port : ``` Thunderbolt 2 - Thunderbolt 3 (up to 40 Gbps) ``` So it's the fastest on your Mac. The externals enclosures SSD Thunderbolt 3 have inside a NVME SSD. For exemple you have the Samsung X5.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
There are three things which effect compatibility and performance when connecting external storage: 1. The physical connector and cable. The 2020 iMac has four USB Type A (USB-A) and two USB Type C (USB-C) connectors. 2. The data transfer protocol - USB 1, USB 2, USB 3 (and later variants 3.1 and 3.2) and Thunderbolt. There is also USB 4, but this is not relevant to 2020 iMac. The 202O iMac supports: * USB-A ports: USB 3.0 (maximum speed 5 Gbits/s) and slower USB 2 and USB 1. * USB-C ports: Thunderbolt 3 (maximum speed 40 Gbits/s), USB 3.1 gen2 (10 Gbits/s), and slower USB 3.1 speeds. 3. The drive inside the external device/enclosure. Common types are are SATA (maximum speed 6 Gbits/s) or NVMe (faster). HDD are usually SATA, whilst SSDs might be SATA or NVMe. The 5 Gbit/s USB 3.1 gen1 and 3.2 gen1x1 standards are similar to USB 3.0 and storage devices specifying these are generally compatible with USB 3.0 via the USB-A ports. Further, the 10 Gbit/s USB 3.2 gen2x1 is very close to USB 3.1 gen2. So storage devices specifying USB 3.2 gen2x1 should be compatible with the 10 Gbit/s USB 3.1 gen2 protocol delivered by the USB-C ports. As well as the the iMac ports supporting or being compatible with multiple data protocols, most USB storage devices support multiple data protocols and (in many cases) both USB-A and USB-C cables and computer ports. For an overview of USB standards read [Wikipedia](https://en.wikipedia.org/wiki/USB). Thunderbolt is a different connection standard developed by Intel (in collaboration with Apple) when Apple saw a need for a faster connection than that provided by USB 3. The first two iterations of the standard used the Mini DisplayPort physical connector on iMacs, whereas Thunderbolt 3 uses USB-C. Thunderbolt and USB standards have now converged with Thunderbolt 4 and USB 4 being very similar. For more detail, read [Wikipedia](https://en.wikipedia.org/wiki/Thunderbolt_(interface)). The current 2021 iMacs support Thunderbolt 3 and USB 4 (using USB-C physical ports). For the 2020 iMac, Thunderbolt 3 storage devices can only be connected to the USB-C ports and must use Thunderbolt 3 cables. Older Thunderbolt 1 and 2 devices can only be connected using cables which convert to Thunderbolt 3 - the iMac does not directly support Thunderbolt 1 and 2. Note that physical USB-C ports which support Thunderbolt 3 have a thunderbolt like symbol next to them. To further confuse matters (but out of scope for this question) USB-C ports also support connecting monitors using, for examples, Display Port and HDMI standards. **What should you be looking for:** For maximum speed (and cost) you should be looking for a Thunderbolt 3 SSD storage device. These can have performance similar to the internal SSD (~2000 MByte/s). Example: Samsung X5. For a more modest cost, there are SSDs which use USB 3.1 Gen 2 (or 3.2 Gen 2x1) and via the USB-C ports on the iMac will deliver ~1000 Mbyte/s. Example: Sumsung T7. And for a slightly more modest cost there are SSDs which use USB 3.1 Gen 2, but internally use SATA SSDs and deliver only ~500 Mbyte/s. Example: Samsung T5. These devices can connect to either USB-C or USB-A ports using USB 3.0, 3.1 Gen1/2 or 3.2 Gen1/2 - the differences in speed are minor as the SATA SSD becomes the bottleneck. Unless you have a professional need for highest speed, devices like the Samsung T7 (or T5) provide fast secondary storage. I have just used Samsung as examples. There are other equally good (and some not quite so good) brands.
### If money is no object, an enterprise-grade PCIe SSD via Thunderbolt for >3.5GB/s sequential read or write, and over 1 million IOPS\* (IO ops / sec). Most likely a recent Intel Optane SSD using 3D XPoint memory, not flash, although there are fast enterprise SSDs from other vendors. Numbers in the title are a rough guesstimate of what you might get from an Optane SSD DC P5800X PCIe4.0 drive bottlenecked by PCIe3.0. Or some flash SSD from another vendor that can push up to the limits of PCIe3.0 x4. Or even a bunch of DRAM in a PCIe card, if they still make those. **You said "fastest", not "fastest that might be worth buying for consumer/personal use",** so that's the point of this answer: ways in which SSDs can be fast, and how to spend thousands of dollars on a terabyte or more of SSD space that could keep up with many cores on a big Xeon for many workloads. That machine has a Thunderbolt 3 port, so that gives you a PCIe3.0 x4 connection to work with, much more bandwidth and lower latency / less overhead than USB3.1 or even 3.2, even with UASP (USB-attached-SCSI that bypasses some of the USB protocol overhead and limitations). With the right adapter, that should let you connect an M.2 SSD (like modern laptops and desktops use for high-performance SSDs). Or with something designed as an external GPU enclosure, should give you a PCIe x16 card slot (electrically only x4 from Thunderbolt) with cooling fan, letting you use enterprise SSDs with serious heat-sinks designed to go in motherboard PCIe slots. e.g. like [this one](https://www.startech.com/en-ca/cards-adapters/tb31pciex16) that came up in a search result. (*Sustained* SSD performance typically involves some serious heat in the controller, e.g. 21W for a high-end Intel Optane DC like [P5800X](https://www.intel.ca/content/www/ca/en/products/sku/201859/intel-optane-ssd-dc-p5800x-series-1-6tb-2-5in-pcie-x4-3d-xpoint/specifications.html), so a heat sink is required to allow continuous operation without having to throttle to avoid overheating. M.2 consumer drives often will need to throttle if you run them hard, but usually that only happens during artificial benchmarks; real use is typically bursty like copying a few tens of GB for a few seconds and then going back to idle.) The NVMe driver interface standard for computers to talk to SSDs means that you wouldn't (AFAIK) need a special driver to use enterprise-grade SSDs with a Mac. (The very fastest non-volatile storage memory is probably Optane DC PM that comes in DIMMs that you plug into memory slots ([like this](https://www.storagereview.com/review/intel-optane-persistent-memory-200-series-review-memverge)), for use with Cascade Lake and later server CPU, letting user-space processes truly map the storage into their own address space, bypassing the kernel and letting drivers control access via virtual memory page permissions. [It's pretty neat](https://superuser.com/questions/1389552/can-intel-optane-memory-compensate-for-less-ram/1391391#1391391), but you couldn't use it with an iMac). SSDs that use [3D XPoint](https://en.wikipedia.org/wiki/3D_XPoint) instead of Flash can be *very* fast, especially for small writes and for mixed read+write workloads, so that's what you'd want to go for in this hypothetical scenario. SSDs built around 3D XPoint instead of flash are definitely optimized for speed over capacity and price. PCIe is backwards compatible: a drive capable of PCIe4.0 plugged into a slot / cable / adapter only capable of PCIe3.0 will negotiate the fastest speed both sides are capable of, so a super high-end drive like an **Intel Optane SSD [P5800X](https://www.intel.ca/content/www/ca/en/products/sku/201859/intel-optane-ssd-dc-p5800x-series-1-6tb-2-5in-pcie-x4-3d-xpoint/specifications.html)** (2.5" NVMe PCIE4.0 x4) ([review](https://www.storagereview.com/review/intel-optane-ssd-p5800x-review)) can still run at PCIe3.0 speed. Thunderbolt 3's PCIe3.0 x4 interface ([32.4Gbit/s i.e. ~4GByte/s raw interface bandwidth](https://en.wikipedia.org/wiki/Thunderbolt_(interface)#Thunderbolt_3)) will be a bottleneck for sequential transfers, instead of the drive's native capability of up to 7.4GB/s read or write. You might still be able to get close to the 2 million IOPS mixed read+write operations this drive claims to be capable of, for small mixed read+write, though. (up to 1.55 million random 4k read IOPS, up to 1.6 million random 4k write IOPS). Also, the low latency guarantees should fully apply, like <6 us for 99% of small requests, and <66 us for 99.999% of small requests. (I'm not sure if Thunderbolt adds any meaningful amount of extra latency to PCIe transactions beyond the few nanoseconds of light-speed delay from cable length and a few gate delays from muxing. [wikichip shows some details of Thunderbolt 3 in Ice Lake](https://en.wikichip.org/wiki/intel/microarchitectures/ice_lake_(client)#Thunderbolt_IO_subsystem), but doesn't go into detail about if/how Thunderbolt encapsulates PCIe packets.) That drive comes in U.2 and E1.S form factors. U.2 is like a 2.5" laptop / server drive, but with PCIe connectors instead of SATA, intended to slide into a bay in a storage server. Lets just say that in theory you could connect it to Thunderbolt. See also <https://nvmexpress.org/new-pcie-form-factor-enables-greater-pcie-ssd-adoption/> re: form factors. Something you definitely could use with a Thunderbolt -> PCIe slot enclosure is a DapuStor H3100 which comes in HHHL card slot form factor (Half Height Half Length), PCIe3.0 x4. So the numbers you see on [this review](https://www.storagereview.com/review/dapustor-h3100-ssd-review) are using the same interface speed you could get via Thunderbolt. 3528 MB/s read, 2603 MB/s write, 803 kIOPS random read, 250 kIOPS random write. This is an eTLC NAND flash device, so obviously it's much slower at random write than the Optane using 3D XPoint. And the latency is worse. MacOS isn't on the supported OS list, but it is an NVMe SSD. --- Note that sequential bandwidth isn't the only criterion for storage speed. NVMe has some inherent protocol / driver advantages for low latency and high number of small IO operations per second (IOPS), important if you want to use this storage for a database server for example. Some storage hardware-review sites do benchmarks that test drives in both low and high "queue depth" situations, i.e. number of outstanding requests in parallel. In a single-user desktop situation, it's common that a program won't do other reads until after the data comes back from the current read. (e.g. loading an executable, it can't run and make `open` system calls until it itself is loaded). So desktop responsiveness is often more correlated with low queue depth IOPS and latency, like QD 1 to 4.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
There are three things which effect compatibility and performance when connecting external storage: 1. The physical connector and cable. The 2020 iMac has four USB Type A (USB-A) and two USB Type C (USB-C) connectors. 2. The data transfer protocol - USB 1, USB 2, USB 3 (and later variants 3.1 and 3.2) and Thunderbolt. There is also USB 4, but this is not relevant to 2020 iMac. The 202O iMac supports: * USB-A ports: USB 3.0 (maximum speed 5 Gbits/s) and slower USB 2 and USB 1. * USB-C ports: Thunderbolt 3 (maximum speed 40 Gbits/s), USB 3.1 gen2 (10 Gbits/s), and slower USB 3.1 speeds. 3. The drive inside the external device/enclosure. Common types are are SATA (maximum speed 6 Gbits/s) or NVMe (faster). HDD are usually SATA, whilst SSDs might be SATA or NVMe. The 5 Gbit/s USB 3.1 gen1 and 3.2 gen1x1 standards are similar to USB 3.0 and storage devices specifying these are generally compatible with USB 3.0 via the USB-A ports. Further, the 10 Gbit/s USB 3.2 gen2x1 is very close to USB 3.1 gen2. So storage devices specifying USB 3.2 gen2x1 should be compatible with the 10 Gbit/s USB 3.1 gen2 protocol delivered by the USB-C ports. As well as the the iMac ports supporting or being compatible with multiple data protocols, most USB storage devices support multiple data protocols and (in many cases) both USB-A and USB-C cables and computer ports. For an overview of USB standards read [Wikipedia](https://en.wikipedia.org/wiki/USB). Thunderbolt is a different connection standard developed by Intel (in collaboration with Apple) when Apple saw a need for a faster connection than that provided by USB 3. The first two iterations of the standard used the Mini DisplayPort physical connector on iMacs, whereas Thunderbolt 3 uses USB-C. Thunderbolt and USB standards have now converged with Thunderbolt 4 and USB 4 being very similar. For more detail, read [Wikipedia](https://en.wikipedia.org/wiki/Thunderbolt_(interface)). The current 2021 iMacs support Thunderbolt 3 and USB 4 (using USB-C physical ports). For the 2020 iMac, Thunderbolt 3 storage devices can only be connected to the USB-C ports and must use Thunderbolt 3 cables. Older Thunderbolt 1 and 2 devices can only be connected using cables which convert to Thunderbolt 3 - the iMac does not directly support Thunderbolt 1 and 2. Note that physical USB-C ports which support Thunderbolt 3 have a thunderbolt like symbol next to them. To further confuse matters (but out of scope for this question) USB-C ports also support connecting monitors using, for examples, Display Port and HDMI standards. **What should you be looking for:** For maximum speed (and cost) you should be looking for a Thunderbolt 3 SSD storage device. These can have performance similar to the internal SSD (~2000 MByte/s). Example: Samsung X5. For a more modest cost, there are SSDs which use USB 3.1 Gen 2 (or 3.2 Gen 2x1) and via the USB-C ports on the iMac will deliver ~1000 Mbyte/s. Example: Sumsung T7. And for a slightly more modest cost there are SSDs which use USB 3.1 Gen 2, but internally use SATA SSDs and deliver only ~500 Mbyte/s. Example: Samsung T5. These devices can connect to either USB-C or USB-A ports using USB 3.0, 3.1 Gen1/2 or 3.2 Gen1/2 - the differences in speed are minor as the SATA SSD becomes the bottleneck. Unless you have a professional need for highest speed, devices like the Samsung T7 (or T5) provide fast secondary storage. I have just used Samsung as examples. There are other equally good (and some not quite so good) brands.
The fastest port on your iMac is the Thunderbolt port. It can support data rates as high as 40Gbit/s, which is 5GB/s. Now most consumer SSDs are pretty fast but won't exceed that theoretical limit of 5GB/s. The fastet you can usually get is about 3GB/s, which you could do with [this enclosure](https://www.amazon.de/Nvme-Geh%C3%A4use-Kompatibel-Thunderbolt-3-Schnittstelle-Solid-State-NVME-SSD-Universal-Tools/dp/B08X9YTWJC/ref=sr_1_4?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=Thunderbolt%20SSD&qid=1627032726&sr=8-4) and basically any NVME SSD that fits that criteria mentioned in the product page. --- About the confusion of Thunderbolt: Thunderbolt and Thunderbolt 2 was primarily used on Macs and most Windows Computers "only" had USB. Thunderbolt is more versatile than the older USB 2 and USB 1 standard. It is able to support e.g. display connections through the DisplayPort standard which was integrated in the Thunderbolt specs, which normal USB 1 and 2 did not include. Older USB and Thunderbolt ports did not share the same connector so distinction was easy. Nowadays the USB-C connector is the same as Thunderbolt 3, even USB 4 and Thunderbolt 4 use this connector. However USB-C is not generally as powerful as Thunderbolt 3. The supported protocols however, may differ. I.e. you could have a USB-C connector which only supports the USB 3.1 protocol while an other one looking identical would support USB 3.2.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
I have a 2018 Mac mini which has the same USB and Thunderbolt 3 capabilities as your Mac. I also have a Thunderbolt 3 [Samsung X5](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) SSD and a 10 Gb/s USB [Samsung T7](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) SSD. I will base my answers on what I know about this hardware. --- When the Thunderbolt 3 Samsung X5 is connected to the Mac through a USB Type-C receptacle (jack), System Information displays the following under NVMExpress. [![NVMExpress](https://i.stack.imgur.com/5RrB5.png)](https://i.stack.imgur.com/5RrB5.png) Like the internal drive, the Thunderbolt 3 Samsung X5 appears as a NVMExpress drive, except the drive is external. Note that [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) is supported. System Information also displays the following under Thunderbolt. [![Thunderbolt 3](https://i.stack.imgur.com/dKaXY.png)](https://i.stack.imgur.com/dKaXY.png) The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s. In terms of bits per second, this would be 22.4 Gb/s, since 8 bits = 8 byte. Since the speed shown in the image above is up to 40 Gb/s, one can conclude the read speed of 22.4 Gb/s is not limited by Thunderbolt 3, but rather by the NVMe drive inside the Samsung X5. --- When the USB Samsung T7 is connected to the Mac through a USB Type-C receptacle, System Information displays the following under USB. [![Type-C](https://i.stack.imgur.com/evL4n.png)](https://i.stack.imgur.com/evL4n.png) The data transfer speed is unto 10 Gb/s. This is the maximum speed for USB devices connected a USB Type-C receptacle on both of our Macs. There is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support, which may not be necessary if the embedded PCIe NVMe technology is sufficiently fast. --- When the USB Samsung T7 is plugged in a USB Type-A receptacle on the Mac, System Information displays the following under USB. > > Note: The USB Samsung T7 comes a cable for plugging into a USB Type-C receptacle and a different cable for plugging into a USB Type-A receptacle. > > > [![Type-A](https://i.stack.imgur.com/RtXe3.png)](https://i.stack.imgur.com/RtXe3.png) The data transfer speed is unto 5 Gb/s. This is the maximum speed for USB devices connected a USB Type-A receptacle on both of our Macs. Again, there is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support. --- Conclusions ----------- You post contains the following four questions. * What is the fastest external storage supported on Intel 2020 27" iMac? The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s, which is 22.4 Gb/s. This means the data rate between the external drive and the Mac must exceed 22.4 Gb/s, which is faster than the maximum USB data rate of 10 Gb/s offered my your Mac. From this, the following conclusion can be made. **>Nothing that USB offers will be faster than what Thunderbolt 3 offers and also be compatible with your Mac.** * What does the 2020 Intel iMac 27" support? The The USB Type-C receptacles support at least the following devices. Self powered Thunderbolt 1 Self powered Thunderbolt 2 Thunderbolt 3 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) USB 3.1 Gen 2 (same as USB 3.2 Gen 2×1) > > Note: Apple's [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter) does not provide power from the Mac to the device. > > > The The USB Type-A receptacles support at least the following devices. USB 1.1 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) * What does that mean for data transfer speeds? The USB Type-C receptacles offer Thunderbolt 3 speeds up 40 Gb/s and USB speeds up to 10 Gb/s. The USB Type-A receptacles offer USB speeds up to 5 Gb/s. * When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option? Look for a Thunderbolt 3 SSD with high with read/write speeds (in the GB/s range). The SSD should also support [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)). You can also look for a Thunderbolt 1 and 2 SSD, but these drives would need to be self powered and would require a [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter). However, finding a self power Thunderbolt 1 or Thunderbolt 2 SDD at a price lower than Thunderbolt 3 SSD is unlikely. --- Speed Comparisons ----------------- | | T5External SSD | T7External SSD | X5External SSD | 27" 2020 iMacInternal SSD | 27" 2020 iMacInternal SSD | | --- | --- | --- | --- | --- | --- | | Source | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [StorageReview](https://www.storagereview.com/review/samsung-ssd-t7-review) | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [Tom's Guide](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | [PC Magazine](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | | Capacity | 1 TB | 2 TB | 1 TB | 1 TB | 1 TB | | BenchmarkApplications | NovabenchandBlackmagic | Blackmagic | NovabenchandBlackmagic | Blackmagic | Blackmagic | | AverageRead | 518 MBps | 894 MBps | 2410 MBps | 2467 MBps | 2427 MBps | | AverageWrite | 475 MBps | 840 MBps | 1708 MBps | 2757 MBps | 2735 MBps | Advertised Specifications ------------------------- | | T5 External SSD | T7 External SSD | X5 External SSD | | --- | --- | --- | --- | | Source | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t5/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) | | Interface | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 40 Gbps(Thunderbolt 3) | | Read | Up to540 MBps | Up to1050 MBps | Up to2800 MBps | | Write | Up to540 MBps | Up to1000 MBps | Up to2300 MBps |
### If money is no object, an enterprise-grade PCIe SSD via Thunderbolt for >3.5GB/s sequential read or write, and over 1 million IOPS\* (IO ops / sec). Most likely a recent Intel Optane SSD using 3D XPoint memory, not flash, although there are fast enterprise SSDs from other vendors. Numbers in the title are a rough guesstimate of what you might get from an Optane SSD DC P5800X PCIe4.0 drive bottlenecked by PCIe3.0. Or some flash SSD from another vendor that can push up to the limits of PCIe3.0 x4. Or even a bunch of DRAM in a PCIe card, if they still make those. **You said "fastest", not "fastest that might be worth buying for consumer/personal use",** so that's the point of this answer: ways in which SSDs can be fast, and how to spend thousands of dollars on a terabyte or more of SSD space that could keep up with many cores on a big Xeon for many workloads. That machine has a Thunderbolt 3 port, so that gives you a PCIe3.0 x4 connection to work with, much more bandwidth and lower latency / less overhead than USB3.1 or even 3.2, even with UASP (USB-attached-SCSI that bypasses some of the USB protocol overhead and limitations). With the right adapter, that should let you connect an M.2 SSD (like modern laptops and desktops use for high-performance SSDs). Or with something designed as an external GPU enclosure, should give you a PCIe x16 card slot (electrically only x4 from Thunderbolt) with cooling fan, letting you use enterprise SSDs with serious heat-sinks designed to go in motherboard PCIe slots. e.g. like [this one](https://www.startech.com/en-ca/cards-adapters/tb31pciex16) that came up in a search result. (*Sustained* SSD performance typically involves some serious heat in the controller, e.g. 21W for a high-end Intel Optane DC like [P5800X](https://www.intel.ca/content/www/ca/en/products/sku/201859/intel-optane-ssd-dc-p5800x-series-1-6tb-2-5in-pcie-x4-3d-xpoint/specifications.html), so a heat sink is required to allow continuous operation without having to throttle to avoid overheating. M.2 consumer drives often will need to throttle if you run them hard, but usually that only happens during artificial benchmarks; real use is typically bursty like copying a few tens of GB for a few seconds and then going back to idle.) The NVMe driver interface standard for computers to talk to SSDs means that you wouldn't (AFAIK) need a special driver to use enterprise-grade SSDs with a Mac. (The very fastest non-volatile storage memory is probably Optane DC PM that comes in DIMMs that you plug into memory slots ([like this](https://www.storagereview.com/review/intel-optane-persistent-memory-200-series-review-memverge)), for use with Cascade Lake and later server CPU, letting user-space processes truly map the storage into their own address space, bypassing the kernel and letting drivers control access via virtual memory page permissions. [It's pretty neat](https://superuser.com/questions/1389552/can-intel-optane-memory-compensate-for-less-ram/1391391#1391391), but you couldn't use it with an iMac). SSDs that use [3D XPoint](https://en.wikipedia.org/wiki/3D_XPoint) instead of Flash can be *very* fast, especially for small writes and for mixed read+write workloads, so that's what you'd want to go for in this hypothetical scenario. SSDs built around 3D XPoint instead of flash are definitely optimized for speed over capacity and price. PCIe is backwards compatible: a drive capable of PCIe4.0 plugged into a slot / cable / adapter only capable of PCIe3.0 will negotiate the fastest speed both sides are capable of, so a super high-end drive like an **Intel Optane SSD [P5800X](https://www.intel.ca/content/www/ca/en/products/sku/201859/intel-optane-ssd-dc-p5800x-series-1-6tb-2-5in-pcie-x4-3d-xpoint/specifications.html)** (2.5" NVMe PCIE4.0 x4) ([review](https://www.storagereview.com/review/intel-optane-ssd-p5800x-review)) can still run at PCIe3.0 speed. Thunderbolt 3's PCIe3.0 x4 interface ([32.4Gbit/s i.e. ~4GByte/s raw interface bandwidth](https://en.wikipedia.org/wiki/Thunderbolt_(interface)#Thunderbolt_3)) will be a bottleneck for sequential transfers, instead of the drive's native capability of up to 7.4GB/s read or write. You might still be able to get close to the 2 million IOPS mixed read+write operations this drive claims to be capable of, for small mixed read+write, though. (up to 1.55 million random 4k read IOPS, up to 1.6 million random 4k write IOPS). Also, the low latency guarantees should fully apply, like <6 us for 99% of small requests, and <66 us for 99.999% of small requests. (I'm not sure if Thunderbolt adds any meaningful amount of extra latency to PCIe transactions beyond the few nanoseconds of light-speed delay from cable length and a few gate delays from muxing. [wikichip shows some details of Thunderbolt 3 in Ice Lake](https://en.wikichip.org/wiki/intel/microarchitectures/ice_lake_(client)#Thunderbolt_IO_subsystem), but doesn't go into detail about if/how Thunderbolt encapsulates PCIe packets.) That drive comes in U.2 and E1.S form factors. U.2 is like a 2.5" laptop / server drive, but with PCIe connectors instead of SATA, intended to slide into a bay in a storage server. Lets just say that in theory you could connect it to Thunderbolt. See also <https://nvmexpress.org/new-pcie-form-factor-enables-greater-pcie-ssd-adoption/> re: form factors. Something you definitely could use with a Thunderbolt -> PCIe slot enclosure is a DapuStor H3100 which comes in HHHL card slot form factor (Half Height Half Length), PCIe3.0 x4. So the numbers you see on [this review](https://www.storagereview.com/review/dapustor-h3100-ssd-review) are using the same interface speed you could get via Thunderbolt. 3528 MB/s read, 2603 MB/s write, 803 kIOPS random read, 250 kIOPS random write. This is an eTLC NAND flash device, so obviously it's much slower at random write than the Optane using 3D XPoint. And the latency is worse. MacOS isn't on the supported OS list, but it is an NVMe SSD. --- Note that sequential bandwidth isn't the only criterion for storage speed. NVMe has some inherent protocol / driver advantages for low latency and high number of small IO operations per second (IOPS), important if you want to use this storage for a database server for example. Some storage hardware-review sites do benchmarks that test drives in both low and high "queue depth" situations, i.e. number of outstanding requests in parallel. In a single-user desktop situation, it's common that a program won't do other reads until after the data comes back from the current read. (e.g. loading an executable, it can't run and make `open` system calls until it itself is loaded). So desktop responsiveness is often more correlated with low queue depth IOPS and latency, like QD 1 to 4.
424,473
I know modern Macs all have USB3 support, but now there's USB 3.1, USB 3.2, NVMe and of course thunderbolt (presumably multiple versions) and I am lost. What does the 2020 Intel iMac 27" support? What does that mean for data transfer speeds? When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option?
2021/07/23
[ "https://apple.stackexchange.com/questions/424473", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/38485/" ]
I have a 2018 Mac mini which has the same USB and Thunderbolt 3 capabilities as your Mac. I also have a Thunderbolt 3 [Samsung X5](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) SSD and a 10 Gb/s USB [Samsung T7](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) SSD. I will base my answers on what I know about this hardware. --- When the Thunderbolt 3 Samsung X5 is connected to the Mac through a USB Type-C receptacle (jack), System Information displays the following under NVMExpress. [![NVMExpress](https://i.stack.imgur.com/5RrB5.png)](https://i.stack.imgur.com/5RrB5.png) Like the internal drive, the Thunderbolt 3 Samsung X5 appears as a NVMExpress drive, except the drive is external. Note that [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) is supported. System Information also displays the following under Thunderbolt. [![Thunderbolt 3](https://i.stack.imgur.com/dKaXY.png)](https://i.stack.imgur.com/dKaXY.png) The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s. In terms of bits per second, this would be 22.4 Gb/s, since 8 bits = 8 byte. Since the speed shown in the image above is up to 40 Gb/s, one can conclude the read speed of 22.4 Gb/s is not limited by Thunderbolt 3, but rather by the NVMe drive inside the Samsung X5. --- When the USB Samsung T7 is connected to the Mac through a USB Type-C receptacle, System Information displays the following under USB. [![Type-C](https://i.stack.imgur.com/evL4n.png)](https://i.stack.imgur.com/evL4n.png) The data transfer speed is unto 10 Gb/s. This is the maximum speed for USB devices connected a USB Type-C receptacle on both of our Macs. There is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support, which may not be necessary if the embedded PCIe NVMe technology is sufficiently fast. --- When the USB Samsung T7 is plugged in a USB Type-A receptacle on the Mac, System Information displays the following under USB. > > Note: The USB Samsung T7 comes a cable for plugging into a USB Type-C receptacle and a different cable for plugging into a USB Type-A receptacle. > > > [![Type-A](https://i.stack.imgur.com/RtXe3.png)](https://i.stack.imgur.com/RtXe3.png) The data transfer speed is unto 5 Gb/s. This is the maximum speed for USB devices connected a USB Type-A receptacle on both of our Macs. Again, there is no indication of [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) support. --- Conclusions ----------- You post contains the following four questions. * What is the fastest external storage supported on Intel 2020 27" iMac? The Thunderbolt 3 Samsung X5 has a read speed of 2800 MB/s, which is 22.4 Gb/s. This means the data rate between the external drive and the Mac must exceed 22.4 Gb/s, which is faster than the maximum USB data rate of 10 Gb/s offered my your Mac. From this, the following conclusion can be made. **>Nothing that USB offers will be faster than what Thunderbolt 3 offers and also be compatible with your Mac.** * What does the 2020 Intel iMac 27" support? The The USB Type-C receptacles support at least the following devices. Self powered Thunderbolt 1 Self powered Thunderbolt 2 Thunderbolt 3 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) USB 3.1 Gen 2 (same as USB 3.2 Gen 2×1) > > Note: Apple's [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter) does not provide power from the Mac to the device. > > > The The USB Type-A receptacles support at least the following devices. USB 1.1 USB 2.0 USB 3.0 (same as USB 3.1 Gen 1 and USB 3.2 Gen 1×1) * What does that mean for data transfer speeds? The USB Type-C receptacles offer Thunderbolt 3 speeds up 40 Gb/s and USB speeds up to 10 Gb/s. The USB Type-A receptacles offer USB speeds up to 5 Gb/s. * When buying an external drive what do I need to look out for to make sure it will be compatible with the fastest option? Look for a Thunderbolt 3 SSD with high with read/write speeds (in the GB/s range). The SSD should also support [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)). You can also look for a Thunderbolt 1 and 2 SSD, but these drives would need to be self powered and would require a [Thunderbolt 3 (USB-C) to Thunderbolt 2 Adapter](https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter). However, finding a self power Thunderbolt 1 or Thunderbolt 2 SDD at a price lower than Thunderbolt 3 SSD is unlikely. --- Speed Comparisons ----------------- | | T5External SSD | T7External SSD | X5External SSD | 27" 2020 iMacInternal SSD | 27" 2020 iMacInternal SSD | | --- | --- | --- | --- | --- | --- | | Source | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [StorageReview](https://www.storagereview.com/review/samsung-ssd-t7-review) | [The Verge](https://www.theverge.com/2019/5/13/18518127/portable-ssd-external-thunderbolt-3-usb-c-samsung-x5-t5-specs-test-how-to) | [Tom's Guide](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | [PC Magazine](https://www.tomsguide.com/reviews/apple-imac-27-inch-2020) | | Capacity | 1 TB | 2 TB | 1 TB | 1 TB | 1 TB | | BenchmarkApplications | NovabenchandBlackmagic | Blackmagic | NovabenchandBlackmagic | Blackmagic | Blackmagic | | AverageRead | 518 MBps | 894 MBps | 2410 MBps | 2467 MBps | 2427 MBps | | AverageWrite | 475 MBps | 840 MBps | 1708 MBps | 2757 MBps | 2735 MBps | Advertised Specifications ------------------------- | | T5 External SSD | T7 External SSD | X5 External SSD | | --- | --- | --- | --- | | Source | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t5/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/t7/) | [Samsung](https://www.samsung.com/semiconductor/minisite/ssd/product/portable/x5/) | | Interface | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 10 Gbps(USB 3.2 Gen 2x1)(USB 3.1 Gen 2) | Up to 40 Gbps(Thunderbolt 3) | | Read | Up to540 MBps | Up to1050 MBps | Up to2800 MBps | | Write | Up to540 MBps | Up to1000 MBps | Up to2300 MBps |
The fastest port on your iMac is the Thunderbolt port. It can support data rates as high as 40Gbit/s, which is 5GB/s. Now most consumer SSDs are pretty fast but won't exceed that theoretical limit of 5GB/s. The fastet you can usually get is about 3GB/s, which you could do with [this enclosure](https://www.amazon.de/Nvme-Geh%C3%A4use-Kompatibel-Thunderbolt-3-Schnittstelle-Solid-State-NVME-SSD-Universal-Tools/dp/B08X9YTWJC/ref=sr_1_4?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=Thunderbolt%20SSD&qid=1627032726&sr=8-4) and basically any NVME SSD that fits that criteria mentioned in the product page. --- About the confusion of Thunderbolt: Thunderbolt and Thunderbolt 2 was primarily used on Macs and most Windows Computers "only" had USB. Thunderbolt is more versatile than the older USB 2 and USB 1 standard. It is able to support e.g. display connections through the DisplayPort standard which was integrated in the Thunderbolt specs, which normal USB 1 and 2 did not include. Older USB and Thunderbolt ports did not share the same connector so distinction was easy. Nowadays the USB-C connector is the same as Thunderbolt 3, even USB 4 and Thunderbolt 4 use this connector. However USB-C is not generally as powerful as Thunderbolt 3. The supported protocols however, may differ. I.e. you could have a USB-C connector which only supports the USB 3.1 protocol while an other one looking identical would support USB 3.2.
572,564
I am in the middle of writing a paper, and I want to highlight the importance of "learning" in the following sentence. > > Nowadays, we use our mobile phones for different purposes: > communicating with friends and relatives, transportation, shopping, and > **learning**. > > > Is there any way to attract readers' attention to learning in this list of examples? To be honest, I was thinking about saying "and more prominently learning", or something like that but then I think that the most prominent application of mobile phones is for communication. Any suggestions for me? Thank you
2021/08/10
[ "https://english.stackexchange.com/questions/572564", "https://english.stackexchange.com", "https://english.stackexchange.com/users/420010/" ]
The expression "*not least*" is useful to single out the term that follow it as special, important, noteworthy. * Nowadays, we use our mobile phones for different purposes: communicating with friends and relatives, transportation, shopping, and *not least*, learning. > > ([FreeDictionary](https://idioms.thefreedictionary.com/not+least)) **not least** notably; in particular. > > >
You could set traditional use(s) apart from newer ones, and emphasize the last with an adverb, something like: > > Nowadays, we use our mobile phones **not only** for communicating with > friends and relatives, **but also** for transportation, shopping, and > **especially/particularly** learning. > > > (or *.... and learning in particular.*) **particularly** > > 3 : in particular : SPECIFICALLY > > *The tools were useful, particularly the knife.* [m-w](https://www.merriam-webster.com/dictionary/particularly) > > >
572,564
I am in the middle of writing a paper, and I want to highlight the importance of "learning" in the following sentence. > > Nowadays, we use our mobile phones for different purposes: > communicating with friends and relatives, transportation, shopping, and > **learning**. > > > Is there any way to attract readers' attention to learning in this list of examples? To be honest, I was thinking about saying "and more prominently learning", or something like that but then I think that the most prominent application of mobile phones is for communication. Any suggestions for me? Thank you
2021/08/10
[ "https://english.stackexchange.com/questions/572564", "https://english.stackexchange.com", "https://english.stackexchange.com/users/420010/" ]
The expression "*not least*" is useful to single out the term that follow it as special, important, noteworthy. * Nowadays, we use our mobile phones for different purposes: communicating with friends and relatives, transportation, shopping, and *not least*, learning. > > ([FreeDictionary](https://idioms.thefreedictionary.com/not+least)) **not least** notably; in particular. > > >
In your particular case, since the element you wish to emphasise is the last on your list, it is common to use the expression ***last but not least***, which means: > > importantly, despite being mentioned after everyone else; despite being mentioned at the end: > > > * I would like to thank my publisher, my editor, and ***, last but not least,*** my husband.([Cambridge](https://dictionary.cambridge.org/dictionary/english/last-but-not-least)) > > > You can use it as an aside, between commas (before *last* and after *least*), or only with one comma after *least*: > > The television is big, has an excellent picture, ***and last but not least,*** it's cheap.([M-W](https://www.merriam-webster.com/dictionary/last%20but%20not%20least)) > > >
70,675,709
I would like to create a separation between the groups (D, E, F, G, H, I e J) of slashes inside ggplot. Using the diamonds database. ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = "dodge")+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() ``` I've: [![enter image description here](https://i.stack.imgur.com/XQqdD.png)](https://i.stack.imgur.com/XQqdD.png) but I would like to create some visual separation between the groups in a simple way, similar to this` [![enter image description here](https://i.stack.imgur.com/sC1SX.png)](https://i.stack.imgur.com/sC1SX.png) OBS1: `facet_grid` won't work because I'm going to use two other variables to add to `facet_grid`. OBS2: For clarification: I'd like to add something visual that helps visually separate the groups, to make it easier to understand where each group starts and ends. OB3:I edited the second image (Expectative) with rectangles separating each group. The idea would be more or less this.
2022/01/12
[ "https://Stackoverflow.com/questions/70675709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14212922/" ]
using `geom_vline` ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = "dodge")+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() + geom_vline(xintercept = (0:7)+0.5) ``` [![enter image description here](https://i.stack.imgur.com/dj5TD.png)](https://i.stack.imgur.com/dj5TD.png)
**EDIT: new answer - use `geom_rect`.** ``` ggplot(diamonds, aes(x = color, y = depth, fill = factor(clarity ))) + geom_col(position = "dodge") + geom_rect(aes(xmin = as.numeric(color) - 0.5, xmax = as.numeric(color) + 0.5), ymin = -0.5, ymax = Inf, color = "red", fill = NA, size = 2) + scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name = "clarity") + theme_light() ``` Result: [![enter image description here](https://i.stack.imgur.com/KkFNs.png)](https://i.stack.imgur.com/KkFNs.png) **OLD ANSWER - before you modified your question.** I think the easiest way is to use `facet_grid`. It's not really designed for that purpose, but will result in the required visual effect. ``` ggplot(diamonds, aes(x = color, y = depth, fill = factor(clarity ))) + geom_col(position = "dodge") + scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name = "clarity") + facet_grid(. ~ color, scales = "free_x", switch = "x") + theme_light() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) ``` Result: [![enter image description here](https://i.stack.imgur.com/aSSKk.png)](https://i.stack.imgur.com/aSSKk.png)
70,675,709
I would like to create a separation between the groups (D, E, F, G, H, I e J) of slashes inside ggplot. Using the diamonds database. ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = "dodge")+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() ``` I've: [![enter image description here](https://i.stack.imgur.com/XQqdD.png)](https://i.stack.imgur.com/XQqdD.png) but I would like to create some visual separation between the groups in a simple way, similar to this` [![enter image description here](https://i.stack.imgur.com/sC1SX.png)](https://i.stack.imgur.com/sC1SX.png) OBS1: `facet_grid` won't work because I'm going to use two other variables to add to `facet_grid`. OBS2: For clarification: I'd like to add something visual that helps visually separate the groups, to make it easier to understand where each group starts and ends. OB3:I edited the second image (Expectative) with rectangles separating each group. The idea would be more or less this.
2022/01/12
[ "https://Stackoverflow.com/questions/70675709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14212922/" ]
using `geom_vline` ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = "dodge")+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() + geom_vline(xintercept = (0:7)+0.5) ``` [![enter image description here](https://i.stack.imgur.com/dj5TD.png)](https://i.stack.imgur.com/dj5TD.png)
The `geom_vline()` method already posted in [this answer](https://stackoverflow.com/a/70675991/9664796) will answer your specific request quite well; however, it's probably not the best solution to your problem *graphically*. Even with lines drawn between the bars... it's super difficult to separate visually the sets of bars from one another. The bars are already thin, so drawing a thin vertical line is going to make it very difficult for the viewer to separate the line from the bar. If you plan to facet your data in addition to this, the issue will get even worse. The alternative I would propose is to use whitespace to separate your groups of bars by utilizing `position=position_dodge(width=...)` and the `width=...` argument inside of `geom_col()` itself. Here's examples of what this does from your posted example. ### Using width inside of geom\_col() ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = "dodge", width=0.5)+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() ``` [![enter image description here](https://i.stack.imgur.com/zHRXe.png)](https://i.stack.imgur.com/zHRXe.png) You can see that the argument for `width=` in `geom_col()` has the effect to change the width of the overall geom in each x position. Thus this value controls the width of the *entire group* of bars. This small change is enough to clearly show the separation without adding lines (and maintaining a bit of whitespace to make things easier to compare). *(For comparison, the default `width=` is something like 0.7 or 0.8).* ### Using position\_dodge(width=...) to control group spacing You may want to adjust just a bit further the graph above to provide a tiny bit of separation between the bars. This one is a bit more on visual preference, but is useful to know as a tool to control the position of groups of bars. `position="dodge"` is a shorthand way of saying `position=position_dodge()`. The default width puts the bars right next to each other, wherein the `width=` argument inside `position_dodge()` is equal to the `width=` of the overall geom. If you make this number larger in `position_dodge()`, you'll add spacing between the bars. If you make it smaller, you will get overlapping bars. Here's what happens when you add just a bit of spacing between the bars: ``` ggplot(diamonds, aes(x = color, y=depth, fill=factor(clarity ))) + geom_col(position = position_dodge(width=0.6), width=0.5)+ scale_fill_manual(values = c("red4", "seagreen3", "grey", "yellow", "black", "blue", "green", "sienna","tomato1", "tan2"), name="clarity") + theme_light() ``` [![enter image description here](https://i.stack.imgur.com/w4WDo.png)](https://i.stack.imgur.com/w4WDo.png) I think it looks a bit better than having the bars next to each other, but it will depend on your own specific chart and how many facets, x position values, and bars in each group you have.
58,395,576
Given an application converting csv to parquet (from and to S3) with little transformation: ``` for table in tables: df_table = spark.read.format('csv') \ .option("header", "true") \ .option("escape", "\"") \ .load(path) df_one_seven_thirty_days = df_table \ .filter( (df_table['date'] == fn.to_date(fn.lit(one_day))) \ | (df_table['date'] == fn.to_date(fn.lit(seven_days))) \ | (df_table['date'] == fn.to_date(fn.lit(thirty_days))) ) for i in df_one_seven_thirty_days.schema.names: df_one_seven_thirty_days = df_one_seven_thirty_days.withColumnRenamed(i, colrename(i).lower()) df_one_seven_thirty_days.createOrReplaceTempView(table) df_sql = spark.sql("SELECT * FROM "+table) df_sql.write \ .mode("overwrite").format('parquet') \ .partitionBy("customer_id", "date") \ .option("path", path) \ .saveAsTable(adwords_table) ``` I'm facing a difficulty with spark EMR. On local with spark submit, this has no difficulties running (140MB of data) and quite fast. But on EMR, it's another story. the first "adwords\_table" will be converted without problems but the second one stays idle. I've gone through the spark jobs UI provided by EMR and I noticed that once this task is done: > > Listing leaf files and directories for 187 paths: > > > Spark kills all executors: [![enter image description here](https://i.stack.imgur.com/FAL2c.png)](https://i.stack.imgur.com/FAL2c.png) and 20min later nothing more happens. All the tasks are on "Completed" and no new ones are starting. I'm waiting for the saveAsTable to start. My local machine is 8 cores 15GB and the cluster is made of 10 nodes r3.4xlarge: 32 vCore, 122 GiB memory, 320 SSD GB storage EBS Storage:200 GiB The configuration is using `maximizeResourceAllocation` true and I've only change the --num-executors / --executor-cores to 5 Does any know why the cluster goes into "idle" and don't finishes the task? (it'll eventually crashes without errors 3 hours later) **EDIT:** I made few progress by removing all glue catalogue connections + downgrading hadoop to use: hadoop-aws:2.7.3 Now the saveAsTable is working just fine, but once it finishes, I see the executors being removed and the cluster is idle, the step doesn't finish. Thus my problem is still the same.
2019/10/15
[ "https://Stackoverflow.com/questions/58395576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599698/" ]
I would recommend: ``` select r1.* from R1 where exists (select 1 from r2 where r1.a = r2.val) or exists (select 1 from r2 where r1.b = r2.val); ``` Then, you want an index on `r2(val)`. If `r2` is *really* small and `r1` is *really* big and there are separate indexes on `r1(a)` and `r1(b)`, then this might be faster: ``` select r1.* from r1 join r2 on r1.a = r2.val union select r1.* from r1 join r2 on r1.b = r2.val; ```
And how about ``` select * from r1 join r2 on r1.a=r2.val union select * from r1 join r2 on r1.b=r2.val ``` ?
58,395,576
Given an application converting csv to parquet (from and to S3) with little transformation: ``` for table in tables: df_table = spark.read.format('csv') \ .option("header", "true") \ .option("escape", "\"") \ .load(path) df_one_seven_thirty_days = df_table \ .filter( (df_table['date'] == fn.to_date(fn.lit(one_day))) \ | (df_table['date'] == fn.to_date(fn.lit(seven_days))) \ | (df_table['date'] == fn.to_date(fn.lit(thirty_days))) ) for i in df_one_seven_thirty_days.schema.names: df_one_seven_thirty_days = df_one_seven_thirty_days.withColumnRenamed(i, colrename(i).lower()) df_one_seven_thirty_days.createOrReplaceTempView(table) df_sql = spark.sql("SELECT * FROM "+table) df_sql.write \ .mode("overwrite").format('parquet') \ .partitionBy("customer_id", "date") \ .option("path", path) \ .saveAsTable(adwords_table) ``` I'm facing a difficulty with spark EMR. On local with spark submit, this has no difficulties running (140MB of data) and quite fast. But on EMR, it's another story. the first "adwords\_table" will be converted without problems but the second one stays idle. I've gone through the spark jobs UI provided by EMR and I noticed that once this task is done: > > Listing leaf files and directories for 187 paths: > > > Spark kills all executors: [![enter image description here](https://i.stack.imgur.com/FAL2c.png)](https://i.stack.imgur.com/FAL2c.png) and 20min later nothing more happens. All the tasks are on "Completed" and no new ones are starting. I'm waiting for the saveAsTable to start. My local machine is 8 cores 15GB and the cluster is made of 10 nodes r3.4xlarge: 32 vCore, 122 GiB memory, 320 SSD GB storage EBS Storage:200 GiB The configuration is using `maximizeResourceAllocation` true and I've only change the --num-executors / --executor-cores to 5 Does any know why the cluster goes into "idle" and don't finishes the task? (it'll eventually crashes without errors 3 hours later) **EDIT:** I made few progress by removing all glue catalogue connections + downgrading hadoop to use: hadoop-aws:2.7.3 Now the saveAsTable is working just fine, but once it finishes, I see the executors being removed and the cluster is idle, the step doesn't finish. Thus my problem is still the same.
2019/10/15
[ "https://Stackoverflow.com/questions/58395576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599698/" ]
It seems like in this specific case the first query I suggested in my main comment provides the best performance : ``` select * from R1 where R1.a in (select VAL from R2) or R1.b in (select VAL from R2); ``` @klin prepared a dbfiddle with all the execution plans if someone want to have a look : <https://dbfiddle.uk/?rdbms=postgres_9.5&fiddle=5b50f605262e406c0bab13710ec121d5>
And how about ``` select * from r1 join r2 on r1.a=r2.val union select * from r1 join r2 on r1.b=r2.val ``` ?