qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
7,458,209
What would be the best way of sending a signal from an iPad to an Arduino? I am trying to use [XBee](http://en.wikipedia.org/wiki/Digi_International#Wireless), with iPad and Arduino to send a wireless signal. I want to make a big red virtual button on an iPad that, when pressed, turns on an LED on the Arduino. I am a total newbie when it comes to iOS, but OK with Arduino and XBee.
2011/09/17
[ "https://Stackoverflow.com/questions/7458209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950613/" ]
So I'm not sure if I understood correctly, but in my meaning there is only one simple way to solve the problem: Connect an XBee to a Computer and another to the Arduino. On the computer you launch a webserver, which will be accesible from the iPad over Safari. This server handles the clickes and writes to the XBee Com Port, for communication. Here are some examples, people already made: * <http://www.projectallusion.com/1/post/2009/11/iphone-controlled-solar-powered-arduino-tank.html> * <http://www.sparkfun.com/tutorials/152> (not with xbee, but you can implement that by yourself)
Since you need to use a network connection from the iPad, a possibly simpler way to do this would be to use a WiFi module on the Arduino to poll a web script, and have the iPad write a state (button press) to that web script. There's a handy WiFi module called the RN-XV that's designed like an XBee. I wrote up two tutorials on it: * <http://log.liminastudio.com/programming/getting-started-with-the-rn-xv-wifi-module-node-js> * <http://log.liminastudio.com/itp/physical-computing/using-the-rn-xv-wifi-module-as-a-remote-switch>
7,458,209
What would be the best way of sending a signal from an iPad to an Arduino? I am trying to use [XBee](http://en.wikipedia.org/wiki/Digi_International#Wireless), with iPad and Arduino to send a wireless signal. I want to make a big red virtual button on an iPad that, when pressed, turns on an LED on the Arduino. I am a total newbie when it comes to iOS, but OK with Arduino and XBee.
2011/09/17
[ "https://Stackoverflow.com/questions/7458209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950613/" ]
So I'm not sure if I understood correctly, but in my meaning there is only one simple way to solve the problem: Connect an XBee to a Computer and another to the Arduino. On the computer you launch a webserver, which will be accesible from the iPad over Safari. This server handles the clickes and writes to the XBee Com Port, for communication. Here are some examples, people already made: * <http://www.projectallusion.com/1/post/2009/11/iphone-controlled-solar-powered-arduino-tank.html> * <http://www.sparkfun.com/tutorials/152> (not with xbee, but you can implement that by yourself)
I know it's been a while but I just came across to this question and yesterday I was doing the exact same thing so I'll share the method I used and the source of it. In order to set a LED on or off in an Arduino board from the iPad you really don't need anything more than a browser. This is of course if you have a way to connect that Arduino to the local network. Today you have at least two options. The WiFi and the Ethernet shields. Once you have your Arduino board inside the network you can send the instructions (HIGH or LOW) to the board form the browser. These are my two boards connected waiting to be plugged to the local network: ![Arduino Uno + Ethernet Shield](https://i.stack.imgur.com/uqe38.jpg) Of course, you'll have to code the board to process those instructions. There are many examples on how to configure network settings and state instructions: ![Arduino IDE with code for the Web Server](https://i.stack.imgur.com/d0Opx.jpg) If you have a bit of time and want to do something more elaborated you could create a simple app to graphically control the state of those LED(s). ![Simple storyboard of an Arduino Uno board to control LEDs from the App](https://i.stack.imgur.com/aMg7d.jpg) Inside you'll basically do the same thing, create the URL command and send it to the Arduino IP but it'd look much nicer. If you integrate later more controls the sky in the limit. My experiment is a combination of what I learned from this nice [tutorial](http://www.raywenderlich.com/15932/electronics-for-iphone-developers-tutorial-control-a-led-from-your-iphone) and some tips I've read here and there. I hope it becomes also useful to someone else. Cheers,
7,458,209
What would be the best way of sending a signal from an iPad to an Arduino? I am trying to use [XBee](http://en.wikipedia.org/wiki/Digi_International#Wireless), with iPad and Arduino to send a wireless signal. I want to make a big red virtual button on an iPad that, when pressed, turns on an LED on the Arduino. I am a total newbie when it comes to iOS, but OK with Arduino and XBee.
2011/09/17
[ "https://Stackoverflow.com/questions/7458209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950613/" ]
I know it's been a while but I just came across to this question and yesterday I was doing the exact same thing so I'll share the method I used and the source of it. In order to set a LED on or off in an Arduino board from the iPad you really don't need anything more than a browser. This is of course if you have a way to connect that Arduino to the local network. Today you have at least two options. The WiFi and the Ethernet shields. Once you have your Arduino board inside the network you can send the instructions (HIGH or LOW) to the board form the browser. These are my two boards connected waiting to be plugged to the local network: ![Arduino Uno + Ethernet Shield](https://i.stack.imgur.com/uqe38.jpg) Of course, you'll have to code the board to process those instructions. There are many examples on how to configure network settings and state instructions: ![Arduino IDE with code for the Web Server](https://i.stack.imgur.com/d0Opx.jpg) If you have a bit of time and want to do something more elaborated you could create a simple app to graphically control the state of those LED(s). ![Simple storyboard of an Arduino Uno board to control LEDs from the App](https://i.stack.imgur.com/aMg7d.jpg) Inside you'll basically do the same thing, create the URL command and send it to the Arduino IP but it'd look much nicer. If you integrate later more controls the sky in the limit. My experiment is a combination of what I learned from this nice [tutorial](http://www.raywenderlich.com/15932/electronics-for-iphone-developers-tutorial-control-a-led-from-your-iphone) and some tips I've read here and there. I hope it becomes also useful to someone else. Cheers,
Since you need to use a network connection from the iPad, a possibly simpler way to do this would be to use a WiFi module on the Arduino to poll a web script, and have the iPad write a state (button press) to that web script. There's a handy WiFi module called the RN-XV that's designed like an XBee. I wrote up two tutorials on it: * <http://log.liminastudio.com/programming/getting-started-with-the-rn-xv-wifi-module-node-js> * <http://log.liminastudio.com/itp/physical-computing/using-the-rn-xv-wifi-module-as-a-remote-switch>
8,140,346
I don't know if the title is appropriate but this is a design question. I am designing a Java class which has a method which does heavy calculation and I am wondering there is a clean way to avoid this calculation every time the method is called. I know that the calling code can handle this but should it always be the responsibility of the calling code?. To elaborate - I was writing a class for thousand dimensional vectors with a method to calculate the magnitude.So every time this method will be called it will calculate the magnitude over all the dimensions.
2011/11/15
[ "https://Stackoverflow.com/questions/8140346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665720/" ]
The concept you are looking for is called [Memoization](http://en.wikipedia.org/wiki/Memoization)
Just cache the results in some structure internal to your class. Once the method is called, it looks if it has the previously calculated result in cache and returns it. In the other case it does the calculation and stores the result in cache. Be careful with the memory though.
8,140,346
I don't know if the title is appropriate but this is a design question. I am designing a Java class which has a method which does heavy calculation and I am wondering there is a clean way to avoid this calculation every time the method is called. I know that the calling code can handle this but should it always be the responsibility of the calling code?. To elaborate - I was writing a class for thousand dimensional vectors with a method to calculate the magnitude.So every time this method will be called it will calculate the magnitude over all the dimensions.
2011/11/15
[ "https://Stackoverflow.com/questions/8140346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665720/" ]
The concept you are looking for is called [Memoization](http://en.wikipedia.org/wiki/Memoization)
Use flag to indicate whether there is a change to your vectors or not. If there is a change, then the method should do a full calculation or apply the calculation to only the changes but you will need to becareful with all the implementations of the rest of your class and make sure that the flag is properly set every time the value is modified. The second method is to use cache. This is done by storing the previously calculated result and look it up before doing the calculation. However, this method is only work well if you don't have many variety in the key values of your objects oterwise you will end up using a lot of memory. Especially, if your key value has type of double, it is possible that the key value will never be found if they aren't exactly equal.
8,140,346
I don't know if the title is appropriate but this is a design question. I am designing a Java class which has a method which does heavy calculation and I am wondering there is a clean way to avoid this calculation every time the method is called. I know that the calling code can handle this but should it always be the responsibility of the calling code?. To elaborate - I was writing a class for thousand dimensional vectors with a method to calculate the magnitude.So every time this method will be called it will calculate the magnitude over all the dimensions.
2011/11/15
[ "https://Stackoverflow.com/questions/8140346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665720/" ]
The concept you are looking for is called [Memoization](http://en.wikipedia.org/wiki/Memoization)
If the "thousand dimensional vectors" are passed in c'tor you can calculate the magnitude in c'tor and store in some private member variable. Few things to take care of are: * If there are methods to add / delete vectors or contents of vectors then you need to update the magnitude in those methods. * If your class is supposed to be thread-safe then ensure appropriate write functions are atomic.
8,140,346
I don't know if the title is appropriate but this is a design question. I am designing a Java class which has a method which does heavy calculation and I am wondering there is a clean way to avoid this calculation every time the method is called. I know that the calling code can handle this but should it always be the responsibility of the calling code?. To elaborate - I was writing a class for thousand dimensional vectors with a method to calculate the magnitude.So every time this method will be called it will calculate the magnitude over all the dimensions.
2011/11/15
[ "https://Stackoverflow.com/questions/8140346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665720/" ]
The concept you are looking for is called [Memoization](http://en.wikipedia.org/wiki/Memoization)
How often are the magnitudes changed? Is this immutable? How much of the interface for the vector do you control? Specifically, do you have any way to identify rotations or other magnitude-preserving transformations in your 1000 dimensional space? You could just store state for the magnitude, flag when the value changes, and recalculate only when necessary. If your transformations have nice internals, you might be able to skip the calculation based on that knowledge.
19,606,419
i am asked to create a from that will ask for text inputs and a photo to be uploaded. then create an image wherein those are displayed. the generated image must then be saved to the server (not using database). i have a code here that successfully generates the image (i used imagejpeg and imagecreatefromjpeg in this case. but then i still need to save it to the server with the file extension .jpg. i also need to give it a unique name. i tried using **header('Content-Disposition: attachment; filename="image.jpg"');** but what it does is save it to the PC not in the server. below is my code. please feel frre to edit it. also, please leave some comments so that i can understand it and not just do copy paste. thank you so much in advance for you help. i really need to make it working by now. thanks again ``` //for textbox input $title = $_POST['title']; $story = "My super story begins with" . $_POST['story'] . " My task was " . $_POST['task'] ." With the super power of ". $_POST['power'] ." I solved it by ". $_POST['solve'] ." The result was". $_POST['result']; //header('Content-Disposition: attachment; filename="image.jpg"'); //this works for saving img to PC or downloading it force .jpg ext header('Content-Type: image/jpeg'); $upload = $uploadFilename; //this is for getting the uploaded file $im = imagecreatefromjpeg("bg2.jpg"); $img2 = imagecreatefromjpeg($upload); $black = imagecolorallocate($im, 0, 0, 0); $font = 'arialbi.ttf'; $font2 = 'ariali.ttf'; imagettftext($im, 24, 0, $width_sum, 300, $black, $font, $title); $newtext = wordwrap($story, 35, "\n", true); $newertext2 = explode ("\n", $newtext); imagettftext($im, 8, 0, 300, 362, $black, $font, $story); imagettftext($im, 8, 0, 300, 374, $black, $font2,$story); imagettftext($im, 8, 0, 300, 386, $black, $font, $story); imagettftext($im, 8, 0, 300, 398, $black, $font2, $story); imagettftext($im, 8, 0, 300, 410, $black, $font, $story); imagettftext($im, 8, 0, 300, 422, $black, $font2, $story); imagettftext($im, 8, 0, 300, 434, $black, $font,$story); imagettftext($im, 8, 0, 300, 446, $black, $font2, $story); imagettftext($im, 8, 0, 300, 458, $black, $font,$story); imagettftext($im, 8, 0, 300, 570, $black, $font2, $story); imagettftext($im, 8, 0, 300, 582, $black, $font, $story); imagecopymerge($im, $img2, 10, 350, 0, 0, imagesx($img2), imagesy($img2), 100); imagejpeg($im, null, 100); //closing for imagejpeg imagejpeg($im); imagedestroy($im); ```
2013/10/26
[ "https://Stackoverflow.com/questions/19606419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2922814/" ]
Well, as the manual of [imagejpeg](http://php.net/imagejpeg) says: the second argument is the filename where you want to store the image.
Try imagejpeg($im, "/PATH/IMAGE\_NAME.jpeg") This should help.
70,144,307
I am new to `pyparsing`. Although did try to read through the docs, I did not manage to solve the first problem of grouping expressions by "keyword: token(s)". I ended up with this code: ```py import pyparsing from pprint import pprint token = pp.Word(pp.alphas) keyword = pp.Combine(token + pp.Literal(":")) expr = pp.Group(keyword[1] + token[1, ...]) pprint(expr.parse_string("keyA: aaa bb ccc keyB: ddd eee keyC: xxx yyy hhh zzz").as_list()) ``` It stops in the middle and parses the second `keyword` as a regular token. The result is following: the expression: ``` keyA: aaa bb ccc keyB: ddd eee keyC: xxx yyy hhh zzz ``` gets parsed into: ``` [['keyA:', 'aaa', 'bb', 'ccc', 'keyB']] ``` I cannot figure out how to define `keyword` and `token`. --- Edit. In general, I'd like to parse the following expression: ``` keyword1: token11 token12 ... keyword2: token21 & token22 token23 keyword3: (token31 token32) & token33 ``` into the following list: ```py [ ["keyword1:", "token11", "token12", ...], ["keyword2:", ["token21", "&", "token22"], "token23"], ["keyword3:", [["token31", "token32"], "&", "token33"]], ] ```
2021/11/28
[ "https://Stackoverflow.com/questions/70144307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612369/" ]
AFAIK there is no difference here. It's just a coincidence that both constructs are doing the same thing here **in this context**. But, there are differences! The biggest one is that `derivedStateOf` is not composable and it does no caching on it's own (`remember` does). So `derivedStateOf` is meant for long running calculations that have to be run only if key changes. Or it can be used to merge multiple states that are not in composable (in custom class for example). I think the exact explanation is blurred for "outsiders", we need some input from some compose team member here :). My source for the above is [this one thread on slack](https://jetc.dev/slack/2020-12-06-is-it-necessary-to-remember.html) and my own experiments EDIT: Today i learned another `derivedStateOf` usage, very important one. It can be used to limit recomposition count when using some very frequently used value for calculation. Example: ```kotlin // we have a variable scrollState: Int that gets updated every time user scrolls // we want to update our counter for every 100 pixels scrolled. // To avoid recomposition every single pixel change we are using derivedStateOf val counter = remember { derivedStateOf { (scrollState / 100).roundToInt() } } // this will be recomposed only on counter change, so it will "ignore" scrollState in 99% of cases Text(counter.toString()). ``` My source for that is as direct as it can be - from the author of compose runtime and the snapshot system, the Chuck Jazdzewski himself. I highly recommend watching stream with him here: <https://www.youtube.com/watch?v=waJ_dklg6fU> EDIT2: We finally have some official performance documentation with small mention of `derivedStateOf`. So the official purpose of `derivedStateOf` is to limit composition count (like in my example). [sauce](https://developer.android.com/jetpack/compose/performance#use-derivedstateof)
`val result = remember(key1, key2) { computeIt(key1, key2) }` re-calculates when `key1` or `key2` changes but `derivedStateOf` is for tracking a change in one or more State/MutableState as stated in documents as ``` var a by remember { mutableStateOf(0) } var b by remember { mutableStateOf(0) } val sum = remember { derivedStateOf { a + b } } // Changing either a or b will cause CountDisplay to recompose but not trigger Example // to recompose. CountDisplay(sum) ``` It's convenient to use derivedStateOf when you need to track a change in property of a State object. The value you store in State can be an object but when you need to track one or some properties of object you need to use derivedStateOf. And if it's not derived from a `State/MutableState` or object with an interface with `@Stable` annotation Composable won't recompose since recomposition requires a state change. For instance an Input layout or number of items that you need to trigger another recomposition after a certain threshold or state. ``` var numberOfItems by remember { mutableStateOf(0) } // Use derivedStateOf when a certain state is calculated or derived from other state objects. // Using this function guarantees that the calculation will only occur whenever one // of the states used in the calculation changes. val derivedStateMax by remember { derivedStateOf { numberOfItems > 5 } } Column(modifier = Modifier.padding(horizontal = 8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "Amount to buy: $numberOfItems", modifier = Modifier.weight(1f)) IconButton(onClick = { numberOfItems++ }) { Icon(imageVector = Icons.Default.Add, contentDescription = "add") } Spacer(modifier = Modifier.width(4.dp)) IconButton(onClick = { if (derivedStateMin) numberOfItems-- }) { Icon(imageVector = Icons.Default.Remove, contentDescription = "remove") } } if (derivedStateMax) { Text("You cannot buy more than 5 items", color = Color(0xffE53935)) } } ``` This is whatsapp text input that displays icons based on whether text is empty or not by reading from text ``` internal fun ChatInput(modifier: Modifier = Modifier, onMessageChange: (String) -> Unit) { var input by remember { mutableStateOf(TextFieldValue("")) } val textEmpty: Boolean by derivedStateOf { input.text.isEmpty() } Row( modifier = modifier .padding(horizontal = 8.dp, vertical = 6.dp) .fillMaxWidth(), verticalAlignment = Alignment.Bottom ) { ChatTextField( modifier = modifier.weight(1f), input = input, empty = textEmpty, onValueChange = { input = it } ) Spacer(modifier = Modifier.width(6.dp)) FloatingActionButton( modifier = Modifier.size(48.dp), backgroundColor = Color(0xff00897B), onClick = { if (!textEmpty) { onMessageChange(input.text) input = TextFieldValue("") } } ) { Icon( tint = Color.White, imageVector = if (textEmpty) Icons.Filled.Mic else Icons.Filled.Send, contentDescription = null ) } } } ``` [![enter image description here](https://i.stack.imgur.com/hpZzO.gif)](https://i.stack.imgur.com/hpZzO.gif)
70,144,307
I am new to `pyparsing`. Although did try to read through the docs, I did not manage to solve the first problem of grouping expressions by "keyword: token(s)". I ended up with this code: ```py import pyparsing from pprint import pprint token = pp.Word(pp.alphas) keyword = pp.Combine(token + pp.Literal(":")) expr = pp.Group(keyword[1] + token[1, ...]) pprint(expr.parse_string("keyA: aaa bb ccc keyB: ddd eee keyC: xxx yyy hhh zzz").as_list()) ``` It stops in the middle and parses the second `keyword` as a regular token. The result is following: the expression: ``` keyA: aaa bb ccc keyB: ddd eee keyC: xxx yyy hhh zzz ``` gets parsed into: ``` [['keyA:', 'aaa', 'bb', 'ccc', 'keyB']] ``` I cannot figure out how to define `keyword` and `token`. --- Edit. In general, I'd like to parse the following expression: ``` keyword1: token11 token12 ... keyword2: token21 & token22 token23 keyword3: (token31 token32) & token33 ``` into the following list: ```py [ ["keyword1:", "token11", "token12", ...], ["keyword2:", ["token21", "&", "token22"], "token23"], ["keyword3:", [["token31", "token32"], "&", "token33"]], ] ```
2021/11/28
[ "https://Stackoverflow.com/questions/70144307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612369/" ]
`derivedStateOf {}` is used **when your state or key is changing more than you want to update your UI**. It acts as a buffer for you, buffering out the changes you don't need. That is the primary difference between a keyed `remember {}` and `derivedStateOf {}`. With `remember {}`, you will still recompose as much as your key changes, which isn't a bad thing if that's what you need. If you don't need those recompositions though, that is where `derivedStateOf {}` comes in. Take for example showing a button only if the user has scrolled a `LazyColumn`. ``` val isVisible = lazyListState.firstVisibleItemIndex > 0 ``` `firstVisibleItemIndex` will change 0, 1, 2 etc as the user scrolls and cause a recomposition for every time it changes. I only care about if it's 0 or not 0 and only want to recompose when that condition changes. `derivedStateOf` is my buffer, it's buffering out all of those extra state changes I don't need and limiting the recomposition to only when the `derivedStateOf` changes. ``` val isVisible = remember { derivedStateOf { lazyListState.firstVisibleItemIndex > 0 } } ``` For the example given in the question, a `remember(key1, key2) {}` is the correct API to use there, not `derivedStateOf {}` because you want your UI to update any time the key changes, there isn't any change to buffer out. Update: There is a detailed explanation of `derivedStateOf` in this talk <https://www.youtube.com/watch?v=ahXLwg2JYpc&t=412s>
`val result = remember(key1, key2) { computeIt(key1, key2) }` re-calculates when `key1` or `key2` changes but `derivedStateOf` is for tracking a change in one or more State/MutableState as stated in documents as ``` var a by remember { mutableStateOf(0) } var b by remember { mutableStateOf(0) } val sum = remember { derivedStateOf { a + b } } // Changing either a or b will cause CountDisplay to recompose but not trigger Example // to recompose. CountDisplay(sum) ``` It's convenient to use derivedStateOf when you need to track a change in property of a State object. The value you store in State can be an object but when you need to track one or some properties of object you need to use derivedStateOf. And if it's not derived from a `State/MutableState` or object with an interface with `@Stable` annotation Composable won't recompose since recomposition requires a state change. For instance an Input layout or number of items that you need to trigger another recomposition after a certain threshold or state. ``` var numberOfItems by remember { mutableStateOf(0) } // Use derivedStateOf when a certain state is calculated or derived from other state objects. // Using this function guarantees that the calculation will only occur whenever one // of the states used in the calculation changes. val derivedStateMax by remember { derivedStateOf { numberOfItems > 5 } } Column(modifier = Modifier.padding(horizontal = 8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "Amount to buy: $numberOfItems", modifier = Modifier.weight(1f)) IconButton(onClick = { numberOfItems++ }) { Icon(imageVector = Icons.Default.Add, contentDescription = "add") } Spacer(modifier = Modifier.width(4.dp)) IconButton(onClick = { if (derivedStateMin) numberOfItems-- }) { Icon(imageVector = Icons.Default.Remove, contentDescription = "remove") } } if (derivedStateMax) { Text("You cannot buy more than 5 items", color = Color(0xffE53935)) } } ``` This is whatsapp text input that displays icons based on whether text is empty or not by reading from text ``` internal fun ChatInput(modifier: Modifier = Modifier, onMessageChange: (String) -> Unit) { var input by remember { mutableStateOf(TextFieldValue("")) } val textEmpty: Boolean by derivedStateOf { input.text.isEmpty() } Row( modifier = modifier .padding(horizontal = 8.dp, vertical = 6.dp) .fillMaxWidth(), verticalAlignment = Alignment.Bottom ) { ChatTextField( modifier = modifier.weight(1f), input = input, empty = textEmpty, onValueChange = { input = it } ) Spacer(modifier = Modifier.width(6.dp)) FloatingActionButton( modifier = Modifier.size(48.dp), backgroundColor = Color(0xff00897B), onClick = { if (!textEmpty) { onMessageChange(input.text) input = TextFieldValue("") } } ) { Icon( tint = Color.White, imageVector = if (textEmpty) Icons.Filled.Mic else Icons.Filled.Send, contentDescription = null ) } } } ``` [![enter image description here](https://i.stack.imgur.com/hpZzO.gif)](https://i.stack.imgur.com/hpZzO.gif)
73,043,679
This is a really common exception, but obviously none of the solutions I've found have resolved my issue. I have an Encrypt and a Decrypt method; I encrypt a string and write it to a file, then read the string from the file and decrypt it (in theory). In reality, I get a > > **CryptographicException**: Length of the data to decrypt is invalid > > > on the decryption side of the process. Here's the `Main()` method that does all the work: ```cs public static void Main() { var filename = "test.encrypted"; var plainText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; string password = "A better password than this"; string salt = "Sodium Chloride"; var padding = PaddingMode.Zeros; // I have tried every padding mode to no avail var encrypted = Encrypt<AesManaged>(plainText, password, salt, padding); File.WriteAllBytes(filename, encrypted); var fileBytes = File.ReadAllBytes(filename); var decrypted = Decrypt<AesManaged>(fileBytes, password, salt, padding); Console.ReadLine(); } ``` The encrypt side: ```cs static byte[] Encrypt<T>(string plainText, string password, string salt, PaddingMode padding) where T : SymmetricAlgorithm, new() { var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { algorithm.Padding = padding; var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); byte[] iv = new byte[algorithm.BlockSize >> 3]; RNGCryptoServiceProvider.Create().GetNonZeroBytes(iv); var transform = algorithm.CreateEncryptor(key, iv); using (MemoryStream buffer = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) using (StreamWriter writer = new StreamWriter(cryptoStream, Encoding.Unicode)) { writer.Write(plainText); writer.Flush(); // cryptoStream.FlushFinalBlock() is called after writer.Flush() // or as part of the Dispose(). // Calling it here causes a "you can't call that twice" exception. // prepend IV to the data return iv.Concat(buffer.ToArray()).ToArray(); } } } ``` ... and the flip side ```cs static byte[] Decrypt<T>(byte[] encryptedData, string password, string salt, PaddingMode padding) where T : SymmetricAlgorithm, new() { var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { algorithm.Padding = padding; var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); //IV is at the beginning of the data var iv = encryptedData.Take(algorithm.BlockSize >> 3).ToArray(); encryptedData = encryptedData.Skip(iv.Length).ToArray(); var transform = algorithm.CreateDecryptor(key, iv); using (MemoryStream buffer = new MemoryStream()) using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode)) { writer.Write(encryptedData); writer.Flush(); return buffer.ToArray(); } } } ```
2022/07/19
[ "https://Stackoverflow.com/questions/73043679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127888/" ]
Imo the easiest way is to follow the MS pattern, e.g. [here](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=net-6.0): * for encryption: ```cs using (MemoryStream buffer = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(cryptoStream, Encoding.Unicode)) { writer.Write(plainText); } return iv.Concat(buffer.ToArray()).ToArray(); } ``` * and for decryption: ```cs using (MemoryStream buffer = new MemoryStream(encryptedData)) using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(stream, Encoding.Unicode)) { return Encoding.Unicode.GetBytes(reader.ReadToEnd()); } ``` With this construct the call of `Close()`, `FlushFinalBlock()` etc. is triggered via the implicit `Dispose()` calls in the correct order (for details see also [here](https://stackoverflow.com/q/68202243)). This is not the case with the old implementation, which results in incomplete encryption and decryption. In addition, the ciphertext is corrupted by the Unicode (more precisely UTF-16LE) encoding during decryption (which is the cause of the posted exception). --- Keep in mind also the following: * Should you later Unicode-decode the decrypted data (which is likely), it is more efficient to return a string instead of a `byte[]` in `Decrypt()` (i.e. `return reader.ReadToEnd()`). * As for padding, PKCS7 padding should be used instead of zero padding, since PKCS#7 padding is more reliable (with respect to your comment in the code). * Using `StreamReader#.ReadToEnd()` prevents problems related to the [breaking change in .NET 6](https://stackoverflow.com/a/69911546/9014097).
There seems to be an encoding / stream handling mistake. You are writing ciphertext as if it was Unicode. I would recommend wrapping the ciphertext in a `MemoryStream`, then use an **input** `CryptoStream` i.e. one configured for reading, and then a `StreamReader` to read the text back. Now you've fully reversed the streams, which, conceptually speaking, makes most sense. For instance, say you want to directly get the ciphertext from a file. Then you can use a `FileStream` in read mode. You can also decide to do something else with the plaintext. And, of course, if you first have an input stream, you can simply first read the IV, and then continue reading using the `CryptoStream`. Finally, the `CryptoStream` can now clearly find out when the stream ends, and can therefore perform the final operations such as unpadding automatically, fixing your problem.
73,043,679
This is a really common exception, but obviously none of the solutions I've found have resolved my issue. I have an Encrypt and a Decrypt method; I encrypt a string and write it to a file, then read the string from the file and decrypt it (in theory). In reality, I get a > > **CryptographicException**: Length of the data to decrypt is invalid > > > on the decryption side of the process. Here's the `Main()` method that does all the work: ```cs public static void Main() { var filename = "test.encrypted"; var plainText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; string password = "A better password than this"; string salt = "Sodium Chloride"; var padding = PaddingMode.Zeros; // I have tried every padding mode to no avail var encrypted = Encrypt<AesManaged>(plainText, password, salt, padding); File.WriteAllBytes(filename, encrypted); var fileBytes = File.ReadAllBytes(filename); var decrypted = Decrypt<AesManaged>(fileBytes, password, salt, padding); Console.ReadLine(); } ``` The encrypt side: ```cs static byte[] Encrypt<T>(string plainText, string password, string salt, PaddingMode padding) where T : SymmetricAlgorithm, new() { var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { algorithm.Padding = padding; var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); byte[] iv = new byte[algorithm.BlockSize >> 3]; RNGCryptoServiceProvider.Create().GetNonZeroBytes(iv); var transform = algorithm.CreateEncryptor(key, iv); using (MemoryStream buffer = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) using (StreamWriter writer = new StreamWriter(cryptoStream, Encoding.Unicode)) { writer.Write(plainText); writer.Flush(); // cryptoStream.FlushFinalBlock() is called after writer.Flush() // or as part of the Dispose(). // Calling it here causes a "you can't call that twice" exception. // prepend IV to the data return iv.Concat(buffer.ToArray()).ToArray(); } } } ``` ... and the flip side ```cs static byte[] Decrypt<T>(byte[] encryptedData, string password, string salt, PaddingMode padding) where T : SymmetricAlgorithm, new() { var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { algorithm.Padding = padding; var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); //IV is at the beginning of the data var iv = encryptedData.Take(algorithm.BlockSize >> 3).ToArray(); encryptedData = encryptedData.Skip(iv.Length).ToArray(); var transform = algorithm.CreateDecryptor(key, iv); using (MemoryStream buffer = new MemoryStream()) using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode)) { writer.Write(encryptedData); writer.Flush(); return buffer.ToArray(); } } } ```
2022/07/19
[ "https://Stackoverflow.com/questions/73043679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127888/" ]
Imo the easiest way is to follow the MS pattern, e.g. [here](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=net-6.0): * for encryption: ```cs using (MemoryStream buffer = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(cryptoStream, Encoding.Unicode)) { writer.Write(plainText); } return iv.Concat(buffer.ToArray()).ToArray(); } ``` * and for decryption: ```cs using (MemoryStream buffer = new MemoryStream(encryptedData)) using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(stream, Encoding.Unicode)) { return Encoding.Unicode.GetBytes(reader.ReadToEnd()); } ``` With this construct the call of `Close()`, `FlushFinalBlock()` etc. is triggered via the implicit `Dispose()` calls in the correct order (for details see also [here](https://stackoverflow.com/q/68202243)). This is not the case with the old implementation, which results in incomplete encryption and decryption. In addition, the ciphertext is corrupted by the Unicode (more precisely UTF-16LE) encoding during decryption (which is the cause of the posted exception). --- Keep in mind also the following: * Should you later Unicode-decode the decrypted data (which is likely), it is more efficient to return a string instead of a `byte[]` in `Decrypt()` (i.e. `return reader.ReadToEnd()`). * As for padding, PKCS7 padding should be used instead of zero padding, since PKCS#7 padding is more reliable (with respect to your comment in the code). * Using `StreamReader#.ReadToEnd()` prevents problems related to the [breaking change in .NET 6](https://stackoverflow.com/a/69911546/9014097).
You need to encode the plain text in the `Encrypt` method and `.Write` the encoding result rather than the plain text. That is, the input byte array that the [`ICryptoTransform`](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.icryptotransform.transformfinalblock?view=netframework-4.8#system-security-cryptography-icryptotransform-transformfinalblock(system-byte()-system-int32-system-int32)) takes to process and returns the encrypted output byte array. I'd suggest to get rid of the `StreamWriter` and write directly to the `CryptoStream`. Here's a suggested fix. ```cs static byte[] Encrypt<T>(string plainText, string password, string salt) where T : SymmetricAlgorithm, new() { var plainTextBytes = Encoding.Unicode.GetBytes(plainText); var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); byte[] iv = new byte[algorithm.BlockSize >> 3]; RNGCryptoServiceProvider.Create().GetNonZeroBytes(iv); using (var buffer = new MemoryStream()) using (var cryptoStream = new CryptoStream(buffer, algorithm.CreateEncryptor(key, iv), CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); return iv.Concat(buffer.ToArray()).ToArray(); } } } // Return byte array if you need that and let the caller decode it. static string Decrypt<T>(byte[] encryptedData, string password, string salt) where T : SymmetricAlgorithm, new() { var saltBytes = Encoding.Unicode.GetBytes(salt); var derivedBytes = new Rfc2898DeriveBytes(password, saltBytes); using (var algorithm = new T()) { var key = derivedBytes.GetBytes(algorithm.KeySize >> 3); var iv = encryptedData.Take(algorithm.BlockSize >> 3).ToArray(); encryptedData = encryptedData.Skip(iv.Length).ToArray(); using (var buffer = new MemoryStream()) using (var stream = new CryptoStream(buffer, algorithm.CreateDecryptor(key, iv), CryptoStreamMode.Write)) { stream.Write(encryptedData, 0, encryptedData.Length); stream.FlushFinalBlock(); return Encoding.Unicode.GetString(buffer.ToArray()); } } } ``` ... and in some caller: ```cs var filename = "test.encrypted"; var plainText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; var password = "A better password than this"; var salt = "Sodium Chloride"; var encrypted = Encrypt<AesManaged>(plainText, password, salt); File.WriteAllBytes(filename, encrypted); var fileBytes = File.ReadAllBytes(filename); var decrypted = Decrypt<AesManaged>(fileBytes, password, salt); Console.WriteLine(decrypted == plainText); ``` See also the generic `SymmetricCrypto<T>` class [here](https://stackoverflow.com/a/66486747/14171304).
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
``` string ssn = "123456789"; string formattedSSN = string.Join("-", ssn.Substring(0,3), ssn.Substring(3,2), ssn.Substring(5,4)); ``` @George's option is probably cleaner if the SSN is stored as a numeric rather than as a string. start indexes corrected.
Just in case this helps someone, here is a method I created to mask and format a SSN: **USAGE:** ``` string ssn = "123456789"; string masked = MaskSsn(ssn); // returns xxx-xx-6789 ``` **CODE:** ``` public static string MaskSsn(this string ssn, int digitsToShow = 4, char maskCharacter = 'x') { if (String.IsNullOrWhiteSpace(ssn)) return String.Empty; const int ssnLength = 9; const string separator = "-"; int maskLength = ssnLength - digitsToShow; // truncate and convert to number int output = Int32.Parse(ssn.Replace(separator, String.Empty).Substring(maskLength, digitsToShow)); string format = String.Empty; for (int i = 0; i < maskLength; i++) format += maskCharacter; for (int i = 0; i < digitsToShow; i++) format += "0"; format = format.Insert(3, separator).Insert(6, separator); format = "{0:" + format + "}"; return String.Format(format, output); } ```
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
Check out the [String.Insert](http://msdn.microsoft.com/en-us/library/system.string.insert.aspx) method. ``` string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-"); ```
Just in case this helps someone, here is a method I created to mask and format a SSN: **USAGE:** ``` string ssn = "123456789"; string masked = MaskSsn(ssn); // returns xxx-xx-6789 ``` **CODE:** ``` public static string MaskSsn(this string ssn, int digitsToShow = 4, char maskCharacter = 'x') { if (String.IsNullOrWhiteSpace(ssn)) return String.Empty; const int ssnLength = 9; const string separator = "-"; int maskLength = ssnLength - digitsToShow; // truncate and convert to number int output = Int32.Parse(ssn.Replace(separator, String.Empty).Substring(maskLength, digitsToShow)); string format = String.Empty; for (int i = 0; i < maskLength; i++) format += maskCharacter; for (int i = 0; i < digitsToShow; i++) format += "0"; format = format.Insert(3, separator).Insert(6, separator); format = "{0:" + format + "}"; return String.Format(format, output); } ```
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
For a simple, short, and self commenting solution, try: ``` String.Format("{0:000-00-0000}", 123456789) ``` `123456789` representing your SSN variable.
Without data validation and assuming that you only get 9 character string, I would go with something like this - ``` return s.Substring(0, 3) + "-" + s.Substring(3, 2) + "-" + s.Substring(5, 4); ``` But...I am also pretty new...so GendoIkari's answer is soo much better.
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
Check out the [String.Insert](http://msdn.microsoft.com/en-us/library/system.string.insert.aspx) method. ``` string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-"); ```
Without data validation and assuming that you only get 9 character string, I would go with something like this - ``` return s.Substring(0, 3) + "-" + s.Substring(3, 2) + "-" + s.Substring(5, 4); ``` But...I am also pretty new...so GendoIkari's answer is soo much better.
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
Just in case this helps someone, here is a method I created to mask and format a SSN: **USAGE:** ``` string ssn = "123456789"; string masked = MaskSsn(ssn); // returns xxx-xx-6789 ``` **CODE:** ``` public static string MaskSsn(this string ssn, int digitsToShow = 4, char maskCharacter = 'x') { if (String.IsNullOrWhiteSpace(ssn)) return String.Empty; const int ssnLength = 9; const string separator = "-"; int maskLength = ssnLength - digitsToShow; // truncate and convert to number int output = Int32.Parse(ssn.Replace(separator, String.Empty).Substring(maskLength, digitsToShow)); string format = String.Empty; for (int i = 0; i < maskLength; i++) format += maskCharacter; for (int i = 0; i < digitsToShow; i++) format += "0"; format = format.Insert(3, separator).Insert(6, separator); format = "{0:" + format + "}"; return String.Format(format, output); } ```
George Johnston's answer is a great answer and the cleanest. Just needs a bit extra work in case there are one or two leading 0's, and this sample assumes your starting point is an SSN in a String format. Check this out: ``` var socialInString = "003456789"; var formattedSSN = Convert.ToInt32(socialInString).ToString("###-##-####").PadLeft(11, '0'); ```
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
``` string ssn = "123456789"; string formattedSSN = string.Join("-", ssn.Substring(0,3), ssn.Substring(3,2), ssn.Substring(5,4)); ``` @George's option is probably cleaner if the SSN is stored as a numeric rather than as a string. start indexes corrected.
Without data validation and assuming that you only get 9 character string, I would go with something like this - ``` return s.Substring(0, 3) + "-" + s.Substring(3, 2) + "-" + s.Substring(5, 4); ``` But...I am also pretty new...so GendoIkari's answer is soo much better.
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
Check out the [String.Insert](http://msdn.microsoft.com/en-us/library/system.string.insert.aspx) method. ``` string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-"); ```
``` string ssn = "123456789"; string formattedSSN = string.Join("-", ssn.Substring(0,3), ssn.Substring(3,2), ssn.Substring(5,4)); ``` @George's option is probably cleaner if the SSN is stored as a numeric rather than as a string. start indexes corrected.
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
``` string ssn = "123456789"; string formattedSSN = string.Join("-", ssn.Substring(0,3), ssn.Substring(3,2), ssn.Substring(5,4)); ``` @George's option is probably cleaner if the SSN is stored as a numeric rather than as a string. start indexes corrected.
Above answer might be raise exception when string not fixed length. In my case I used following way SSN formating and its working. ``` string SSN = "56245789"; if (SSN.Length > 3 && SSN <= 5) SSN = SSN.Insert(3, "-"); else if (SSN.Length > 5) SSN = SSN.Insert(5, "-").Insert(3, "-"); ``` Hence SSN will get 562-45-789.
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
For a simple, short, and self commenting solution, try: ``` String.Format("{0:000-00-0000}", 123456789) ``` `123456789` representing your SSN variable.
George Johnston's answer is a great answer and the cleanest. Just needs a bit extra work in case there are one or two leading 0's, and this sample assumes your starting point is an SSN in a String format. Check this out: ``` var socialInString = "003456789"; var formattedSSN = Convert.ToInt32(socialInString).ToString("###-##-####").PadLeft(11, '0'); ```
4,128,263
I am getting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like `XXX-XX-XXXX` instead of `XXXXXXXXX`. It's like converting a simple string with dashes at positions `4` and `7`. I am pretty new to C#, so what is the best way to do this?
2010/11/08
[ "https://Stackoverflow.com/questions/4128263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398477/" ]
Just in case this helps someone, here is a method I created to mask and format a SSN: **USAGE:** ``` string ssn = "123456789"; string masked = MaskSsn(ssn); // returns xxx-xx-6789 ``` **CODE:** ``` public static string MaskSsn(this string ssn, int digitsToShow = 4, char maskCharacter = 'x') { if (String.IsNullOrWhiteSpace(ssn)) return String.Empty; const int ssnLength = 9; const string separator = "-"; int maskLength = ssnLength - digitsToShow; // truncate and convert to number int output = Int32.Parse(ssn.Replace(separator, String.Empty).Substring(maskLength, digitsToShow)); string format = String.Empty; for (int i = 0; i < maskLength; i++) format += maskCharacter; for (int i = 0; i < digitsToShow; i++) format += "0"; format = format.Insert(3, separator).Insert(6, separator); format = "{0:" + format + "}"; return String.Format(format, output); } ```
Above answer might be raise exception when string not fixed length. In my case I used following way SSN formating and its working. ``` string SSN = "56245789"; if (SSN.Length > 3 && SSN <= 5) SSN = SSN.Insert(3, "-"); else if (SSN.Length > 5) SSN = SSN.Insert(5, "-").Insert(3, "-"); ``` Hence SSN will get 562-45-789.
20,714,670
Updated version - I have taken the initial advice provided (thanks for that!) but I'm still having the same issue. I have updated everything below. I have two models, products that belong to a store. I'm attempting to display a related object's column (Store.name) in a couple of views for products that belong to a store and can't seem to get the store to save correctly. Please note: Still very new to this and learning. **Model for Product:** ``` class Product < ActiveRecord::Base belongs_to :store validates_presence_of :name, :url, :price end ``` **Model for Store:** ``` class Store < ActiveRecord::Base has_many :products has_many :pins, through: :products accepts_nested_attributes_for :products end ``` **Controller for Product:** class ProductsController < ApplicationController before\_action :set\_product, only: [:show, :edit, :update, :destroy] ``` # GET /products # GET /products.json def index @products = Product.all end # GET /products/1 # GET /products/1.json def show end # GET /products/new def new @product = Product.new @stores = Store.all end # GET /products/1/edit def edit end # POST /products # POST /products.json def create @product = Product.new(product_params) respond_to do |format| if @product.save format.html { redirect_to @product, notice: 'Product was successfully created.' } format.json { render action: 'show', status: :created, location: @product } else format.html { render action: 'new' } format.json { render json: @product.errors, status: :unprocessable_entity } end end end # PATCH/PUT /products/1 # PATCH/PUT /products/1.json def update respond_to do |format| if @product.update(product_params) format.html { redirect_to @product, notice: 'Product was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @product.errors, status: :unprocessable_entity } end end end # DELETE /products/1 # DELETE /products/1.json def destroy @product.destroy respond_to do |format| format.html { redirect_to products_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_product @product = Product.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def product_params params.require(:product).permit(:name, :description, :imageurl, :url, :price, :Store_id) end end ``` **Form for products** ``` <%= form_for(@product) do |f| %> <% if @product.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2> <ul> <% @product.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="form-group"> <%= f.label :name, "Name" %> <%= f.text_field :name, class: "form-control" %> </div> <div class="form-group"> <%= f.label :description, "Description" %> <%= f.text_area :description, class: "form-control" %> </div> <div class="form-group"> <%= f.label :imageurl, "Image" %> <%= f.text_field :imageurl, class: "form-control" %> </div> <div class="form-group"> <%= f.label :url, "Web Address" %> <%= f.text_field :url, class: "form-control" %> </div> <div class="form-group"> <%= f.label :price, "Price" %> $<%= f.text_field :price, class: "form-control" %> </div> <div class="form-group"> <%= collection_select(:product, :Store_id, Store.all, :id, :name, {:prompt=> "Select A Store"}, {:class => "form-control"} ) %> </div> <div class="form-group"> <%= f.submit class: "btn btn-primary" %> </div> <% end %> <%= params.inspect %> ``` **View for products (show.html.erb):** ``` <p id="notice"><%= notice %></p> <p> <strong>Name:</strong> <%= @product.name %> </p> <p> <strong>Description:</strong> <%= @product.description %> </p> <p> <strong>Store Id:</strong> <%= @product.Store_id %> </p> <p> <strong>Store Name:</strong> <%= @product.store.try(:name) %> </p> <p> <strong>Image:</strong> <%= @product.imageurl %> </p> <p> <strong>Url:</strong> <%= @product.url %> </p> <p> <strong>Price:</strong> $<%= @product.price %> </p> <%= params.inspect %> <%= link_to 'Edit', edit_product_path(@product) %> | <%= link_to 'Back', products_path %> ``` You'll notice that I have .try in place where I'm referencing product.store.name from product.store so that I stop getting the error listed in the subject of this post. When I look up the product I'm viewing using the console I see that Store\_id: 2 When I look up the store with id of 2 I see that Store\_id: 1 - so there is a value present there. I printed params on the show view and only get this: {"action"=>"show", "controller"=>"products", "id"=>"2"}. Can anyone find what I'm missing in this whole set up to get product.store.name to display in my product views? Let me know if I can provide more info!
2013/12/21
[ "https://Stackoverflow.com/questions/20714670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864902/" ]
First, you should be using `snake_case` for attributes. `UpperCamelCase` is reserved for constant names in Ruby, that includes things like classes and modules. Update your code to not use UpperCamelCase style naming for attributes (eg. ProdDesc, ProdImageUrl). Also it is unnecessary to use prefixes like `Prod*` for attributes. So instead of ``` class Product < ActiveRecord::Base belongs_to :store validates_presence_of :ProdTitle, :ProdUrl, :ProdPrice end ``` Your class will look like this: ``` class Product < ActiveRecord::Base belongs_to :store validates_presence_of :title, :url, :price end ``` You can read more about Ruby and Rails naming conventions here: * <http://rubylearning.com/satishtalim/ruby_names.html> * <https://github.com/bbatsov/rails-style-guide> I suspect that this causes the problem. You will also need to rename columns in database and change your controller and view code to reflect the change. If you can, please start again with your application.
You have taken name for field In database which are non conventional. By default The active record looks for store\_id field in product table . Field name in a table should be snake case .so now you have to explicitly tell in product model the foreign key for store model
2,481,118
I am trying to install sqlite3 and sqlite-ruby (ruby 1.8.6) on a linux box where I do not have root. I downloaded the sqlite3 source, binaries, and shared library and placed them all in a directory called sqlite3 I then try to install sqlite-ruby using ``` gem install sqlite-ruby --with-sqlite-dir=the_path_sqlite/sqlite3 ``` but I keep getting the error... ``` checking for main() in -lsqlite... no checking for sqlite.h... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/data/scratch/bettbra/common/packages/ruby-1.8.6/bin/ruby --with-sqlite-dir --with-sqlite-include --without-sqlite-include=${sqlite-dir}/include --with-sqlite-lib --without-sqlite-lib=${sqlite-dir}/lib --with-sqlitelib --without-sqlitelib ```
2010/03/19
[ "https://Stackoverflow.com/questions/2481118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/273324/" ]
You specify where the development files (headers & lib) are using the following syntax: ``` gem install sqlite3 -- --with-sqlite3-include=$HOME/include --with-sqlite3-lib=$HOME/lib ``` Notice the -- that mark the end of `gem` options. After them, the options are passed to the extension compiling process. However, I second Reuben's advice; you should really consider using RVM. It is a blessing for this kind of situations AND to smooth your migration to Ruby 1.9.
i'm using ubuntu (debain type linux). i managed to resolve it the following way: sudo apt-get install sqlite3 libsqlite3-dev sudo gem install sqlite3-ruby
2,481,118
I am trying to install sqlite3 and sqlite-ruby (ruby 1.8.6) on a linux box where I do not have root. I downloaded the sqlite3 source, binaries, and shared library and placed them all in a directory called sqlite3 I then try to install sqlite-ruby using ``` gem install sqlite-ruby --with-sqlite-dir=the_path_sqlite/sqlite3 ``` but I keep getting the error... ``` checking for main() in -lsqlite... no checking for sqlite.h... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/data/scratch/bettbra/common/packages/ruby-1.8.6/bin/ruby --with-sqlite-dir --with-sqlite-include --without-sqlite-include=${sqlite-dir}/include --with-sqlite-lib --without-sqlite-lib=${sqlite-dir}/lib --with-sqlitelib --without-sqlitelib ```
2010/03/19
[ "https://Stackoverflow.com/questions/2481118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/273324/" ]
You specify where the development files (headers & lib) are using the following syntax: ``` gem install sqlite3 -- --with-sqlite3-include=$HOME/include --with-sqlite3-lib=$HOME/lib ``` Notice the -- that mark the end of `gem` options. After them, the options are passed to the extension compiling process. However, I second Reuben's advice; you should really consider using RVM. It is a blessing for this kind of situations AND to smooth your migration to Ruby 1.9.
Can you install RVM (Ruby Version Manager) ? <https://rvm.io/rvm/install/> With RVM you install gems etc. as a user *without* sudo/root privileges.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Assume that $P\rightarrow Q\vee R$, we are to show that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q$ holds, in particular, $P$ holds, so by assumption, we have that $Q\vee R$ holds, we get that either $Q$ or $R$ holds. Since we have $\neg Q$ holds, which means that $Q$ does not hold, so from either $Q$ or $R$ holds, we get that $R$ must hold, this justifies that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q\rightarrow R$, we are to show that $P\rightarrow Q\vee R$. So assume that $P$ holds but $Q\vee R$ does not hold, then neither $Q$ nor $R$ holds. In particular, $\neg Q$ holds, so $P\wedge\neg Q$ holds, so we get that $R$ holds, but we have both $R$ and $\neg R$ hold, this is a contradiction. The contradiction comes from that we have assumed that $Q\vee R$ does not hold, so $Q\vee R$ must hold, this justifies that $P\rightarrow Q\vee R$.
You can get this from two simple equivalences: 1. $P \vee Q \Leftrightarrow \neg P \rightarrow Q$ 2. $(P \wedge Q) \rightarrow R \Leftrightarrow P \rightarrow (Q \rightarrow R)$ Here $(P \wedge \neg Q) \rightarrow R$ is equivalent (by 2) to $P \rightarrow (\neg Q \rightarrow R)$ is equivalent (by 1) to $P \rightarrow (Q \vee R)$.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
$$ P\Longrightarrow (Q\cup R) $$ is equivalent to $$ P'\cup (Q\cup R) $$ which is equivalent to $$ (P'\cup Q)\cup R $$ which is equivalent to $$ (P'\cup Q)'\Longrightarrow R $$ which is equivalent to $$ P\cap Q'\Longrightarrow R $$
You can get this from two simple equivalences: 1. $P \vee Q \Leftrightarrow \neg P \rightarrow Q$ 2. $(P \wedge Q) \rightarrow R \Leftrightarrow P \rightarrow (Q \rightarrow R)$ Here $(P \wedge \neg Q) \rightarrow R$ is equivalent (by 2) to $P \rightarrow (\neg Q \rightarrow R)$ is equivalent (by 1) to $P \rightarrow (Q \vee R)$.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Look at these two truth tables: $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q & R & Q \cup R =:I & P\Longrightarrow I\\ \hline 0 & 0 & 1 & 1 & 1 \\ 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 \\ 0 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 1 \\ 1 & 1 & 0 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ \hline \end{array}$$ $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q' & R & P \cap Q' =:J & J\Longrightarrow R\\ \hline 0 & 1 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 & 1 \\ 1 & 1 & 0 & 1 & 0 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 & 1 \\ \hline \end{array}$$
$$ P\Longrightarrow (Q\cup R) $$ is equivalent to $$ P'\cup (Q\cup R) $$ which is equivalent to $$ (P'\cup Q)\cup R $$ which is equivalent to $$ (P'\cup Q)'\Longrightarrow R $$ which is equivalent to $$ P\cap Q'\Longrightarrow R $$
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Look at these two truth tables: $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q & R & Q \cup R =:I & P\Longrightarrow I\\ \hline 0 & 0 & 1 & 1 & 1 \\ 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 \\ 0 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 1 \\ 1 & 1 & 0 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ \hline \end{array}$$ $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q' & R & P \cap Q' =:J & J\Longrightarrow R\\ \hline 0 & 1 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 & 1 \\ 1 & 1 & 0 & 1 & 0 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 & 1 \\ \hline \end{array}$$
> > $P \to (Q \lor R)$ > > > If it is the weekend, then it is Saturday or Sunday. > > $(P \land \lnot Q) \to R$ > > > If it is the weekend, and it is not Saturday, then it is Sunday. Notice how both statements are equivalent to saying "the only possible weekend days are Saturday and Sunday", but neither necessarily implies that Saturday is a weekend or implies that Sunday is a weekend.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Assume that $P\rightarrow Q\vee R$, we are to show that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q$ holds, in particular, $P$ holds, so by assumption, we have that $Q\vee R$ holds, we get that either $Q$ or $R$ holds. Since we have $\neg Q$ holds, which means that $Q$ does not hold, so from either $Q$ or $R$ holds, we get that $R$ must hold, this justifies that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q\rightarrow R$, we are to show that $P\rightarrow Q\vee R$. So assume that $P$ holds but $Q\vee R$ does not hold, then neither $Q$ nor $R$ holds. In particular, $\neg Q$ holds, so $P\wedge\neg Q$ holds, so we get that $R$ holds, but we have both $R$ and $\neg R$ hold, this is a contradiction. The contradiction comes from that we have assumed that $Q\vee R$ does not hold, so $Q\vee R$ must hold, this justifies that $P\rightarrow Q\vee R$.
Look at these two truth tables: $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q & R & Q \cup R =:I & P\Longrightarrow I\\ \hline 0 & 0 & 1 & 1 & 1 \\ 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 \\ 0 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 1 \\ 1 & 1 & 0 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ \hline \end{array}$$ $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q' & R & P \cap Q' =:J & J\Longrightarrow R\\ \hline 0 & 1 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 & 1 \\ 1 & 1 & 0 & 1 & 0 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 & 1 \\ \hline \end{array}$$
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Assume that $P\rightarrow Q\vee R$, we are to show that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q$ holds, in particular, $P$ holds, so by assumption, we have that $Q\vee R$ holds, we get that either $Q$ or $R$ holds. Since we have $\neg Q$ holds, which means that $Q$ does not hold, so from either $Q$ or $R$ holds, we get that $R$ must hold, this justifies that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q\rightarrow R$, we are to show that $P\rightarrow Q\vee R$. So assume that $P$ holds but $Q\vee R$ does not hold, then neither $Q$ nor $R$ holds. In particular, $\neg Q$ holds, so $P\wedge\neg Q$ holds, so we get that $R$ holds, but we have both $R$ and $\neg R$ hold, this is a contradiction. The contradiction comes from that we have assumed that $Q\vee R$ does not hold, so $Q\vee R$ must hold, this justifies that $P\rightarrow Q\vee R$.
$P\to (Q\lor R)$ means that "At least one from $Q$ or $R$ is true, *if* $P$ is true." $(P\land\lnot Q)\to R$ means that "$R$ is true, *if* $P$ is true but $Q$ is false." Assume $P\to (Q\vee R)$ holds; that is at least one from $Q$ or $R$ is true, *if* $P$ is true.   Well, from that we can infer that $R$ will be true is $P$ is true but $Q$ is false.   So $P\to (Q\vee R)$ logically entails $(P\land\neg Q)\to R$. Likewise if $(P\land\neg Q)\to R$ holds we can infer that $P\to(Q\vee R)$ also holds. In summary $(P\land\neg Q)\to R$ is logically equivalent to $P\to (Q\vee R)$
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Assume that $P\rightarrow Q\vee R$, we are to show that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q$ holds, in particular, $P$ holds, so by assumption, we have that $Q\vee R$ holds, we get that either $Q$ or $R$ holds. Since we have $\neg Q$ holds, which means that $Q$ does not hold, so from either $Q$ or $R$ holds, we get that $R$ must hold, this justifies that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q\rightarrow R$, we are to show that $P\rightarrow Q\vee R$. So assume that $P$ holds but $Q\vee R$ does not hold, then neither $Q$ nor $R$ holds. In particular, $\neg Q$ holds, so $P\wedge\neg Q$ holds, so we get that $R$ holds, but we have both $R$ and $\neg R$ hold, this is a contradiction. The contradiction comes from that we have assumed that $Q\vee R$ does not hold, so $Q\vee R$ must hold, this justifies that $P\rightarrow Q\vee R$.
$$ P\Longrightarrow (Q\cup R) $$ is equivalent to $$ P'\cup (Q\cup R) $$ which is equivalent to $$ (P'\cup Q)\cup R $$ which is equivalent to $$ (P'\cup Q)'\Longrightarrow R $$ which is equivalent to $$ P\cap Q'\Longrightarrow R $$
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Assume that $P\rightarrow Q\vee R$, we are to show that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q$ holds, in particular, $P$ holds, so by assumption, we have that $Q\vee R$ holds, we get that either $Q$ or $R$ holds. Since we have $\neg Q$ holds, which means that $Q$ does not hold, so from either $Q$ or $R$ holds, we get that $R$ must hold, this justifies that $P\wedge\neg Q\rightarrow R$. Now assume that $P\wedge\neg Q\rightarrow R$, we are to show that $P\rightarrow Q\vee R$. So assume that $P$ holds but $Q\vee R$ does not hold, then neither $Q$ nor $R$ holds. In particular, $\neg Q$ holds, so $P\wedge\neg Q$ holds, so we get that $R$ holds, but we have both $R$ and $\neg R$ hold, this is a contradiction. The contradiction comes from that we have assumed that $Q\vee R$ does not hold, so $Q\vee R$ must hold, this justifies that $P\rightarrow Q\vee R$.
> > $P \to (Q \lor R)$ > > > If it is the weekend, then it is Saturday or Sunday. > > $(P \land \lnot Q) \to R$ > > > If it is the weekend, and it is not Saturday, then it is Sunday. Notice how both statements are equivalent to saying "the only possible weekend days are Saturday and Sunday", but neither necessarily implies that Saturday is a weekend or implies that Sunday is a weekend.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
$$ P\Longrightarrow (Q\cup R) $$ is equivalent to $$ P'\cup (Q\cup R) $$ which is equivalent to $$ (P'\cup Q)\cup R $$ which is equivalent to $$ (P'\cup Q)'\Longrightarrow R $$ which is equivalent to $$ P\cap Q'\Longrightarrow R $$
> > $P \to (Q \lor R)$ > > > If it is the weekend, then it is Saturday or Sunday. > > $(P \land \lnot Q) \to R$ > > > If it is the weekend, and it is not Saturday, then it is Sunday. Notice how both statements are equivalent to saying "the only possible weekend days are Saturday and Sunday", but neither necessarily implies that Saturday is a weekend or implies that Sunday is a weekend.
2,717,115
Can any body explain the logical statement in common terms: $$P \to (Q \lor R) ~~\iff ~~(P \land\lnot Q) \to R$$ * $\lnot$ negation ("not") * $\land$ conjunction ("and") * $\lor$ disjunction ("or") * $\to$ condition ("implies") * $\iff$ logical equivalence ("if and only if")
2018/04/01
[ "https://math.stackexchange.com/questions/2717115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5049/" ]
Look at these two truth tables: $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q & R & Q \cup R =:I & P\Longrightarrow I\\ \hline 0 & 0 & 1 & 1 & 1 \\ 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 \\ 0 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 1 \\ 1 & 1 & 0 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ \hline \end{array}$$ $$\begin{array}{|c|c|c|c|c|} \hline % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ... P & Q' & R & P \cap Q' =:J & J\Longrightarrow R\\ \hline 0 & 1 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 & 1 \\ 1 & 1 & 0 & 1 & 0 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 & 1 \\ \hline \end{array}$$
$P\to (Q\lor R)$ means that "At least one from $Q$ or $R$ is true, *if* $P$ is true." $(P\land\lnot Q)\to R$ means that "$R$ is true, *if* $P$ is true but $Q$ is false." Assume $P\to (Q\vee R)$ holds; that is at least one from $Q$ or $R$ is true, *if* $P$ is true.   Well, from that we can infer that $R$ will be true is $P$ is true but $Q$ is false.   So $P\to (Q\vee R)$ logically entails $(P\land\neg Q)\to R$. Likewise if $(P\land\neg Q)\to R$ holds we can infer that $P\to(Q\vee R)$ also holds. In summary $(P\land\neg Q)\to R$ is logically equivalent to $P\to (Q\vee R)$
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
In addition to the other answers: You talk about *growth for the people in the company doing AI work under me*: is there anything you can do to use *their* resources? They may not be as experienced as you, but they have their unique thoughts, insights, search techniques, etc. Why not let them do more research to prevent *reinventing the wheel, or doing something that was known to be ineffective*. Use your colleagues as sparring partners in developing the next steps.
The most effective way to do this for huge engineering challenges like learning ML, which is a massive field in mathematical, algorithmic and engineering aspects, is to join a department in an established company. You return to a startup a few years later as a seasoned veteran. Probably you have some of the experience necessary at your startup right now to interview for these roles.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
The majority of the fields I'm competent at are self taught in my own and work time when there was the opportunity. Not having superiors does mean you work from basics upwards, but that is not necessarily a bad thing for you personally. It means your knowledge becomes pretty thorough. Look for courses etc,. that you might be able to convince your employers to pay for. It's important to fill in the gaps between what you can learn on your own and industry best practices. One advantage I found was that you aren't tied down to just what is taught and sometimes solve problems in unique ways because you are too uneducated to know better. In a personal example I combined two fields to solve a problem and didn't think much of it because it was the only way I could work out how to do it. But the solution is now in use in 11 govt departments and most of the schools in two small countries and even got me an audience with a King.
In addition to the other answers: You talk about *growth for the people in the company doing AI work under me*: is there anything you can do to use *their* resources? They may not be as experienced as you, but they have their unique thoughts, insights, search techniques, etc. Why not let them do more research to prevent *reinventing the wheel, or doing something that was known to be ineffective*. Use your colleagues as sparring partners in developing the next steps.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
I am in the same position as you are (although a slightly different field of software engineering), so I can totally relate to your situation. Other people gave good answers about learning through the typical channels (books, etc) which is a good advice. Over the time, you will be better at picking more effective resources. One bit that I would add, for you and others in the same situation, is be honest with your peers and seniors. Don't be afraid to say that you don't know, admit the mistakes that you have made because everyone does. This is very important from the perspective of the people that you are managing because you need their trust. > > And naturally, I'm not going to be providing the best environment of > growth for the people in the company doing AI work under me. > > > You can set a good example of learning on your own, also by sharing resources that you found effective, etc. So it's not as bad as you might think. Good luck!
Podcasts ! I listen to many dev & tech podcasts, almost daily - whenever I commute is an excellant opportunity, and beats the usual radio channels. My knowledge has grown in many areas as a result, and you can get deep insights from experienced industry experts, without giving up any of your valuable spare time. Listen in the car, on the train, on a bus, whilst walking the dog, in the gym, whilst watching TV (just one headphone socket), whilst waiting in a queue, at lunchtimes of your day job, in bed before sleep or upon waking up, whilst sunbathing, etc.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
You're essentially down to the same path that anyone who wants to learn something in their free time. If there are no internal experts look for them elsewhere. The following are the best resources * Seminars, * Conferences, * Courses, * Online articles, * Since it is a pretty new technology, you might consider the scientific publication in that field. You could consider contacting some computer scientist from universities, who might spare a bit of time to give you some direction about where you should look to. The prices and efficiency of various methods may differ, but it depends on where you stand, and what your employer is willing to spend.
The very simple answer is that your job deliverables has to include a new category: "research." If you're doing an agile methodology, then your sprint includes a task for researching the state-of-the-art in the field.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
The majority of the fields I'm competent at are self taught in my own and work time when there was the opportunity. Not having superiors does mean you work from basics upwards, but that is not necessarily a bad thing for you personally. It means your knowledge becomes pretty thorough. Look for courses etc,. that you might be able to convince your employers to pay for. It's important to fill in the gaps between what you can learn on your own and industry best practices. One advantage I found was that you aren't tied down to just what is taught and sometimes solve problems in unique ways because you are too uneducated to know better. In a personal example I combined two fields to solve a problem and didn't think much of it because it was the only way I could work out how to do it. But the solution is now in use in 11 govt departments and most of the schools in two small countries and even got me an audience with a King.
The most effective way to do this for huge engineering challenges like learning ML, which is a massive field in mathematical, algorithmic and engineering aspects, is to join a department in an established company. You return to a startup a few years later as a seasoned veteran. Probably you have some of the experience necessary at your startup right now to interview for these roles.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
In addition to the other answers: You talk about *growth for the people in the company doing AI work under me*: is there anything you can do to use *their* resources? They may not be as experienced as you, but they have their unique thoughts, insights, search techniques, etc. Why not let them do more research to prevent *reinventing the wheel, or doing something that was known to be ineffective*. Use your colleagues as sparring partners in developing the next steps.
The very simple answer is that your job deliverables has to include a new category: "research." If you're doing an agile methodology, then your sprint includes a task for researching the state-of-the-art in the field.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
> > As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. > > > Then why not hire somebody with more experience in the field? > > If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". > > > That saying still holds. You *are* that larger department, but you are lacking the *senior developers with lots of experience in the field*. It looks like hiring such a senior developer would help to have and build the expert knowledge in the field for your company and the team. > > we probably don't have the resources to bring in massive experience > > > It will cost, either by bringing in another experienced employee or by turning you into one. There might be a middle ground in the form of consulting companies, that might be able to reduce the amount of trial and error you are performing.
The very simple answer is that your job deliverables has to include a new category: "research." If you're doing an agile methodology, then your sprint includes a task for researching the state-of-the-art in the field.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
Podcasts ! I listen to many dev & tech podcasts, almost daily - whenever I commute is an excellant opportunity, and beats the usual radio channels. My knowledge has grown in many areas as a result, and you can get deep insights from experienced industry experts, without giving up any of your valuable spare time. Listen in the car, on the train, on a bus, whilst walking the dog, in the gym, whilst watching TV (just one headphone socket), whilst waiting in a queue, at lunchtimes of your day job, in bed before sleep or upon waking up, whilst sunbathing, etc.
The very simple answer is that your job deliverables has to include a new category: "research." If you're doing an agile methodology, then your sprint includes a task for researching the state-of-the-art in the field.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
The majority of the fields I'm competent at are self taught in my own and work time when there was the opportunity. Not having superiors does mean you work from basics upwards, but that is not necessarily a bad thing for you personally. It means your knowledge becomes pretty thorough. Look for courses etc,. that you might be able to convince your employers to pay for. It's important to fill in the gaps between what you can learn on your own and industry best practices. One advantage I found was that you aren't tied down to just what is taught and sometimes solve problems in unique ways because you are too uneducated to know better. In a personal example I combined two fields to solve a problem and didn't think much of it because it was the only way I could work out how to do it. But the solution is now in use in 11 govt departments and most of the schools in two small countries and even got me an audience with a King.
I would suggest collaborating with an AI department/professor of a university. They normally charge much less than professional consultants and have the latest updates in the field. They can also tie you up with their past students who have worked on similar problems. I was in a similar situation few years back where we were doing some advanced developments in telecommunications with a very inexperienced team. We collaborated with a university and had regular weekly meetings with the professor. It was a course correcting mechanism and the professor also updated us on the latest papers in the field. It helped us immensely.
77,951
I'm a member of a small startup. When we decided to look at including a bit of AI in our product, I was asked to investigate, simply because I found it interesting and had taken a few AI/Machine Learning courses at uni (undergrad). Today, I'm now the lead of the central AI component of our product. The only problem, I need (and want) more experience in the area. If this was a usual position, I'd assume I'd join a large department, and spend time learning and growing under senior developers with lots of experience in the field. The old saying "Surround yourself with people better than you". As it stands today, because of lack of experience, most of the decisions I'm making are trial and error, which is slowing us down. Without completely understanding the state of the industry, we'd often spend a fair amount of time implementing a solution, only to discover a month later that we were reinventing the wheel, or doing something that was known to be ineffective. And naturally, I'm not going to be providing the best environment of growth for the people in the company doing AI work under me. Admittedly, I've definitely grown in skill a lot since I'd started in my position, however I would still hesitate to describe myself as anything more that having an "intermediate" skill level in the field. --- To make this a valuable question to anyone: What are practical steps my company or I could take to quickly bring us up to speed in a field where the company's experience is more or less self-taught? In our case, we probably don't have the resources to bring in massive experience, but any advice about that would still be appreciated.
2016/10/18
[ "https://workplace.stackexchange.com/questions/77951", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/32704/" ]
You're essentially down to the same path that anyone who wants to learn something in their free time. If there are no internal experts look for them elsewhere. The following are the best resources * Seminars, * Conferences, * Courses, * Online articles, * Since it is a pretty new technology, you might consider the scientific publication in that field. You could consider contacting some computer scientist from universities, who might spare a bit of time to give you some direction about where you should look to. The prices and efficiency of various methods may differ, but it depends on where you stand, and what your employer is willing to spend.
I am in the same position as you are (although a slightly different field of software engineering), so I can totally relate to your situation. Other people gave good answers about learning through the typical channels (books, etc) which is a good advice. Over the time, you will be better at picking more effective resources. One bit that I would add, for you and others in the same situation, is be honest with your peers and seniors. Don't be afraid to say that you don't know, admit the mistakes that you have made because everyone does. This is very important from the perspective of the people that you are managing because you need their trust. > > And naturally, I'm not going to be providing the best environment of > growth for the people in the company doing AI work under me. > > > You can set a good example of learning on your own, also by sharing resources that you found effective, etc. So it's not as bad as you might think. Good luck!
37,614,566
How can I bundle react-components, defined in jsx-files, in an index.js file? In a way that the components can be accessed by `import module from "/module"; let C = module.Component;`. With: ``` /module index.js Component.jsx ```
2016/06/03
[ "https://Stackoverflow.com/questions/37614566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464562/" ]
To re-export the component as a default export: ``` export { default } from './Component'; ``` To re-export the component as a named export: ``` export { default as NamedComponent } from './Component'; ``` You should prefer exporting as default from `index.js` since it will likely be the only export from the index. Your component import will look like this: ``` import Component from './module'; ``` or this, if you use a named export: ``` import { NamedComponent } from './module'; ``` Assuming you're using webpack to bundle your files, to make sure your imports can use `'./Component'` instead of `'./Component.jsx'`, include `.jsx` as an extension in your `resolve` property in `webpack.config.js`: ``` module.exports = { resolve: { extensions: ['.js', '.jsx'], }, }; ```
``` export Component from "./Component" ``` You should not use export default for your use case. There is only a single default export per module. This value is to be considered as the "main" exported value since it will be the simplest to import. Refer <https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export> for more detail
37,614,566
How can I bundle react-components, defined in jsx-files, in an index.js file? In a way that the components can be accessed by `import module from "/module"; let C = module.Component;`. With: ``` /module index.js Component.jsx ```
2016/06/03
[ "https://Stackoverflow.com/questions/37614566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464562/" ]
``` export Component from "./Component" ``` You should not use export default for your use case. There is only a single default export per module. This value is to be considered as the "main" exported value since it will be the simplest to import. Refer <https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export> for more detail
Inside index.js export { default as ComponentName } from './Component'; Then In App.js [Import it Like this] import {ComponentName} from './module'
37,614,566
How can I bundle react-components, defined in jsx-files, in an index.js file? In a way that the components can be accessed by `import module from "/module"; let C = module.Component;`. With: ``` /module index.js Component.jsx ```
2016/06/03
[ "https://Stackoverflow.com/questions/37614566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4464562/" ]
To re-export the component as a default export: ``` export { default } from './Component'; ``` To re-export the component as a named export: ``` export { default as NamedComponent } from './Component'; ``` You should prefer exporting as default from `index.js` since it will likely be the only export from the index. Your component import will look like this: ``` import Component from './module'; ``` or this, if you use a named export: ``` import { NamedComponent } from './module'; ``` Assuming you're using webpack to bundle your files, to make sure your imports can use `'./Component'` instead of `'./Component.jsx'`, include `.jsx` as an extension in your `resolve` property in `webpack.config.js`: ``` module.exports = { resolve: { extensions: ['.js', '.jsx'], }, }; ```
Inside index.js export { default as ComponentName } from './Component'; Then In App.js [Import it Like this] import {ComponentName} from './module'
60,668,545
I have a problem with SUM function in SQL Server. How to SUM TotalA column but not get duplicate values in Os column? I am using Group by, distinct but inefficient. ![MSSQL Column Images](https://i.stack.imgur.com/02Ifb.png)
2020/03/13
[ "https://Stackoverflow.com/questions/60668545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13056241/" ]
You can do aggregation : ``` select os, sum(distinct totala) from table t group by os; ``` If you want all sum then remove `distinct` : ``` select os, sum(totala) from table t group by os; ``` Both query will produce unique `os`s but, first one will return unique sum & second would return all sum. You can also use sub-query & do aggregation : ``` select os, sum(totala) as totala from (select distinct os, totala from table t ) t group by os; ```
Use two levels of aggregation: ``` select sum(TotalA) from (select os, max(TotalA) as TotalA from t group by os ) o; ``` Do not even consider `sum(distinct TotalA)`. I have never used this in a SQL query, because it does nothing useful. The problem is that two different `os`s could have the same `TotalA` value -- and one of the values would not be included in the `sum()`.
22,899,898
Is there a way to define a geofence (center and radius) around the device's current location, and have the system trigger a callback function in my app when the device exits the geofence? I would like to avoid extensive GPS usage, so I would prefer a system message over periodic GPS polling, even at the price of reduced accuracy.
2014/04/06
[ "https://Stackoverflow.com/questions/22899898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51197/" ]
Use the `Geofence` API in `Google Play Services`. [Here](http://developer.android.com/training/location/geofencing.html) you can find the documentation to use it. You can have up to 100 geofences at a time.
`LocationManager.addProximityAlert`. It uses both GPS and network internally, presumably only turning on GPS when close. Does exactly what you want.
22,899,898
Is there a way to define a geofence (center and radius) around the device's current location, and have the system trigger a callback function in my app when the device exits the geofence? I would like to avoid extensive GPS usage, so I would prefer a system message over periodic GPS polling, even at the price of reduced accuracy.
2014/04/06
[ "https://Stackoverflow.com/questions/22899898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51197/" ]
I've found that the GeoFencing API never intelligently retrieves locations from the GPS hardware. The GeoFence API will observe the most accurate location available from the OS or if no location is currently available, it will cause a location to be calculated from Wifi / Cellular. (which sucks because cellular is wildly inaccurate and wifi is often unavailable) So to get at all responsive or accurate results out of the Geofencing API you have to set up your Geofences and then poll the GPS hardware on an interval, not even doing anything with the result received, so that under the surface you are providing worthwhile data to the OS. I can't speak specifically to the behaviour of LocationManager.addProximityAlert but I doubt it behaves any differently.
`LocationManager.addProximityAlert`. It uses both GPS and network internally, presumably only turning on GPS when close. Does exactly what you want.
22,899,898
Is there a way to define a geofence (center and radius) around the device's current location, and have the system trigger a callback function in my app when the device exits the geofence? I would like to avoid extensive GPS usage, so I would prefer a system message over periodic GPS polling, even at the price of reduced accuracy.
2014/04/06
[ "https://Stackoverflow.com/questions/22899898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51197/" ]
Use the `Geofence` API in `Google Play Services`. [Here](http://developer.android.com/training/location/geofencing.html) you can find the documentation to use it. You can have up to 100 geofences at a time.
I've found that the GeoFencing API never intelligently retrieves locations from the GPS hardware. The GeoFence API will observe the most accurate location available from the OS or if no location is currently available, it will cause a location to be calculated from Wifi / Cellular. (which sucks because cellular is wildly inaccurate and wifi is often unavailable) So to get at all responsive or accurate results out of the Geofencing API you have to set up your Geofences and then poll the GPS hardware on an interval, not even doing anything with the result received, so that under the surface you are providing worthwhile data to the OS. I can't speak specifically to the behaviour of LocationManager.addProximityAlert but I doubt it behaves any differently.
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
You need to use `-P` option of `grep` to enable perl compatible regular expressions, could you please try following. Written and tested with your shown samples. ``` grep -P '("\d+",){4}"[a-zA-Z]+","2020-12-\d{2}"' Input_file ``` ***Explanation:*** Adding explanation for above, following is only for explanation purposes. ``` grep ##Starting grep command from here. -P ##Mentioning -P option for enabling PCRE regex with grep. '("\d+",){4} ##Looking for " digits " comma this combination 4 times here. "[a-zA-Z]+", ##Then looking for " alphabets ", with this one. "2020-12-\d{2}" ##Then looking for " 2020-12-07 date " which OP needs. ' Input_file ##Mentioning Input_file name here. ```
The problem is in: ``` egrep '.*\d{4}-\d{2}-\d{2}.2020-12-.' > output.txt ^ HERE ``` The `.` just matches a single character, but you want to skip `","`, so change to: ``` egrep '.*\d{4}-\d{2}-\d{2}.+2020-12-.' > output.txt ^^ HERE ``` The `.` becomes a `.+`.
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
Use either `grep -P` or `egrep` for short: ``` $ cat test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" $ $ grep -P '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" $ $ egrep '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ``` Explanation: * `^"` - expect a `"` to start * `([^"]*","){6}` - scan over all chars other than `"`, followed by `","`; repeat that 6 times * `2020-12-` - expect `202012-`
The problem is in: ``` egrep '.*\d{4}-\d{2}-\d{2}.2020-12-.' > output.txt ^ HERE ``` The `.` just matches a single character, but you want to skip `","`, so change to: ``` egrep '.*\d{4}-\d{2}-\d{2}.+2020-12-.' > output.txt ^^ HERE ``` The `.` becomes a `.+`.
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
I suggest an alternate solution `awk` due to input data structured in rows and columns using a common delimiter: ```sh awk -F, '$7 ~ /-12-/' file "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ```
The problem is in: ``` egrep '.*\d{4}-\d{2}-\d{2}.2020-12-.' > output.txt ^ HERE ``` The `.` just matches a single character, but you want to skip `","`, so change to: ``` egrep '.*\d{4}-\d{2}-\d{2}.+2020-12-.' > output.txt ^^ HERE ``` The `.` becomes a `.+`.
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
You need to use `-P` option of `grep` to enable perl compatible regular expressions, could you please try following. Written and tested with your shown samples. ``` grep -P '("\d+",){4}"[a-zA-Z]+","2020-12-\d{2}"' Input_file ``` ***Explanation:*** Adding explanation for above, following is only for explanation purposes. ``` grep ##Starting grep command from here. -P ##Mentioning -P option for enabling PCRE regex with grep. '("\d+",){4} ##Looking for " digits " comma this combination 4 times here. "[a-zA-Z]+", ##Then looking for " alphabets ", with this one. "2020-12-\d{2}" ##Then looking for " 2020-12-07 date " which OP needs. ' Input_file ##Mentioning Input_file name here. ```
Use either `grep -P` or `egrep` for short: ``` $ cat test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" $ $ grep -P '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" $ $ egrep '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ``` Explanation: * `^"` - expect a `"` to start * `([^"]*","){6}` - scan over all chars other than `"`, followed by `","`; repeat that 6 times * `2020-12-` - expect `202012-`
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
You need to use `-P` option of `grep` to enable perl compatible regular expressions, could you please try following. Written and tested with your shown samples. ``` grep -P '("\d+",){4}"[a-zA-Z]+","2020-12-\d{2}"' Input_file ``` ***Explanation:*** Adding explanation for above, following is only for explanation purposes. ``` grep ##Starting grep command from here. -P ##Mentioning -P option for enabling PCRE regex with grep. '("\d+",){4} ##Looking for " digits " comma this combination 4 times here. "[a-zA-Z]+", ##Then looking for " alphabets ", with this one. "2020-12-\d{2}" ##Then looking for " 2020-12-07 date " which OP needs. ' Input_file ##Mentioning Input_file name here. ```
I suggest an alternate solution `awk` due to input data structured in rows and columns using a common delimiter: ```sh awk -F, '$7 ~ /-12-/' file "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ```
65,419,561
Ok this is driving me crazy. I have a text file with the following content: ``` "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" ``` etc. I want to filter lines on which the **second date** is in december, I tried things like: ``` grep '.*(\d{4}-\d{2}-\d{2}).*(2020-12-).*' > output.txt grep '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt grep -P '.*\d{4}-\d{2}-\d{2}.*2020-12-.*' > output.txt ``` But nothing seems to work. Is there any way to accomplish this with either grep, egrep, sed or awk?
2020/12/23
[ "https://Stackoverflow.com/questions/65419561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975233/" ]
I suggest an alternate solution `awk` due to input data structured in rows and columns using a common delimiter: ```sh awk -F, '$7 ~ /-12-/' file "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ```
Use either `grep -P` or `egrep` for short: ``` $ cat test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" "1","2","3","4","text","2020-12-12","2020-04-11","21" "1","2","3","4","text","2020-05-21","2020-03-23","453" $ $ grep -P '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" $ $ egrep '^"([^"]*","){6}2020-12-' test.txt "1","2","3","4","text","2020-01-01","2020-12-13","4" "1","2","3","4","text","2020-12-07","2020-12-03","22" ``` Explanation: * `^"` - expect a `"` to start * `([^"]*","){6}` - scan over all chars other than `"`, followed by `","`; repeat that 6 times * `2020-12-` - expect `202012-`
18,412,966
I've got two tables: ``` content: id access 1 3 2 5 3 9 viewlevels: id group 1 [10,12,15] 2 [8,12,11] 3 [9,10,5] ``` The access field in content is related with the id field in viewlevels. I select the rows in viewlevels depending on the current user group. So for example, if group is = 10, my query will select rows 1 and 3. If the group is 12, it will select rows 1 and 2, etc. I'm using the following query: ``` $query="SELECT id FROM #__viewlevels WHERE rules LIKE '%$group%'"; ``` My challenge is to count the number of rows for column id in table content where the access matches with the selected id's from the above query on table viewlevels. I tried the following code but it is returning the error: undefined variable: nartigos ``` $query="SELECT count(id) FROM #__content WHERE access IN (SELECT id FROM #__viewlevels WHERE rules LIKE '%$group%')"; if ($stmt = mysqli_prepare($link, $query)) { /* execute query */ mysqli_stmt_execute($stmt); /* store result */ mysqli_stmt_store_result($stmt); $nartigos=mysqli_stmt_num_rows($stmt); /* close statement */ mysqli_stmt_close($stmt); }; echo "Nº de artigos " .$nartigos; ```
2013/08/23
[ "https://Stackoverflow.com/questions/18412966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
First of all, you really should normalize your data. Consider having a many-to-many join table for viewLevels instead of having all groups in one row. That might look like this: ``` access_id group_id 1 10 1 12 1 15 2 8 2 11 2 12 3 5 3 9 3 10 ``` That would make your query as simple as ``` SELECT c.id AS `content_id`, COUNT(v.access_id) AS `content_count` FROM content AS c INNER JOIN viewLevels AS v ON c.access_id = v.access_id WHERE v.group_id = ? GROUP BY c.id ``` Here `?` is the group id you are querying against. Without normalization (which again I STRONGLY recommend you do), you would still use a join, but it would look like this: ``` SELECT c.id AS `content_id`, COUNT(v.access_id) AS `content_count` FROM content AS c INNER JOIN viewLevels AS v ON c.access_id = v.access_id WHERE v.group LIKE '%?%' GROUP BY c.id ```
you need to "join" your tables. the sql command cant query two tables seperately. when you "join" 2 tables in your sql, think of it as making one virtual/temporary table in the air, of the 2 tables which you can then query. this is quite a good intro <http://www.sitepoint.com/understanding-sql-joins-mysql-database/>
47,799,970
I have created a table with DataTables like this: <https://jsfiddle.net/scaz23z0/2/> **HTML** ``` <table id="example" class="table table-striped table-bordered" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> <tr> <td>Airi Satou</td> <td>Accountant</td> <td>Tokyo</td> <td>33</td> <td>2008/11/28</td> <td>$162,700</td> </tr> </tbody> </table> ``` **Javascript** ``` $(document).ready(function() { $('#example').DataTable(); } ); ``` I'm wondering how I can change the style of the pagination buttons (the ones that say `Previous`,`1` and `Next`) to have another background color for example. I have tried to inspect element to see which CSS class that are affecting them and then trying to edit them, but I haven't gotten it to work.
2017/12/13
[ "https://Stackoverflow.com/questions/47799970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9069393/" ]
<https://jsfiddle.net/cLx7kqgu/1/> The buttons are actually links wrapped inside an `li`named `%table_name%_previous` `%table_name%_next`. You can target them like this. CSS ``` #example_previous a { background-color:black; } #example_next a { background-color:red; } ```
Try this , use important to overwrite bootstrap ``` .pagination>li>a, .pagination>li>span{ border:1px solid red !important; } ```
39,618,411
I need to access to `SelectedIndex` property of a `TabControl` from another thread, I tried with a `Dispatcher` like this: ``` public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } ``` but I get > > System.InvalidOperationException > > > Unable to access the object by the calling thread because that object is owned by another thread properties. > > > I'm trying to return a list through the `SelectedIndex`, what am I doing wrong?
2016/09/21
[ "https://Stackoverflow.com/questions/39618411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6739907/" ]
Here is a way to do it. First we need to get the last week Monday from current date, so we can use the following technique Below will always give the Monday of the current week ``` mysql> select date_sub(curdate(), interval weekday(curdate()) day) as d ; +------------+ | d | +------------+ | 2016-09-19 | +------------+ ``` Now to get the Monday of the last week we can adjust the above as ``` mysql> select date_sub(date_sub(curdate(), interval weekday(curdate()) day), interval 7 day) as d ; +------------+ | d | +------------+ | 2016-09-12 | +------------+ ``` And finally to retrieve the data we can do as ``` select * from your_table where date_column >= date_sub(date_sub(curdate(), interval weekday(curdate()) day), interval 7 day) ``` <http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_weekday> Best is to handle the date calculation i.e. last week Monday on application level and then pass the value to the query.
See [DAYOFWEEK()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek) Not seeing you table structe, start with this and adjust to your needs ``` SELECT * FROM table WHERE date >= curdate() - INTERVAL DAYOFWEEK( curdate() )+ 7 DAY ```
39,618,411
I need to access to `SelectedIndex` property of a `TabControl` from another thread, I tried with a `Dispatcher` like this: ``` public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } ``` but I get > > System.InvalidOperationException > > > Unable to access the object by the calling thread because that object is owned by another thread properties. > > > I'm trying to return a list through the `SelectedIndex`, what am I doing wrong?
2016/09/21
[ "https://Stackoverflow.com/questions/39618411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6739907/" ]
The [YEARWEEK](https://www.w3schools.com/Sql/func_mysql_yearweek.asp) operator takes an mode option that lets you start the week on Monday. Then just query for the YEARWEEK of NOW() minus 1 ``` SELECT * FROM table WHERE YEARWEEK(timestamp,1)=YEARWEEK(NOW(),1)-1 ```
See [DAYOFWEEK()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek) Not seeing you table structe, start with this and adjust to your needs ``` SELECT * FROM table WHERE date >= curdate() - INTERVAL DAYOFWEEK( curdate() )+ 7 DAY ```
39,618,411
I need to access to `SelectedIndex` property of a `TabControl` from another thread, I tried with a `Dispatcher` like this: ``` public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } ``` but I get > > System.InvalidOperationException > > > Unable to access the object by the calling thread because that object is owned by another thread properties. > > > I'm trying to return a list through the `SelectedIndex`, what am I doing wrong?
2016/09/21
[ "https://Stackoverflow.com/questions/39618411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6739907/" ]
See [DAYOFWEEK()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek) Not seeing you table structe, start with this and adjust to your needs ``` SELECT * FROM table WHERE date >= curdate() - INTERVAL DAYOFWEEK( curdate() )+ 7 DAY ```
Try this : date BETWEEN YEARWEEK(CURDATE()) AND CURDATE()-INTERVAL 7 DAY
39,618,411
I need to access to `SelectedIndex` property of a `TabControl` from another thread, I tried with a `Dispatcher` like this: ``` public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } ``` but I get > > System.InvalidOperationException > > > Unable to access the object by the calling thread because that object is owned by another thread properties. > > > I'm trying to return a list through the `SelectedIndex`, what am I doing wrong?
2016/09/21
[ "https://Stackoverflow.com/questions/39618411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6739907/" ]
Here is a way to do it. First we need to get the last week Monday from current date, so we can use the following technique Below will always give the Monday of the current week ``` mysql> select date_sub(curdate(), interval weekday(curdate()) day) as d ; +------------+ | d | +------------+ | 2016-09-19 | +------------+ ``` Now to get the Monday of the last week we can adjust the above as ``` mysql> select date_sub(date_sub(curdate(), interval weekday(curdate()) day), interval 7 day) as d ; +------------+ | d | +------------+ | 2016-09-12 | +------------+ ``` And finally to retrieve the data we can do as ``` select * from your_table where date_column >= date_sub(date_sub(curdate(), interval weekday(curdate()) day), interval 7 day) ``` <http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_weekday> Best is to handle the date calculation i.e. last week Monday on application level and then pass the value to the query.
Try this : date BETWEEN YEARWEEK(CURDATE()) AND CURDATE()-INTERVAL 7 DAY
39,618,411
I need to access to `SelectedIndex` property of a `TabControl` from another thread, I tried with a `Dispatcher` like this: ``` public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } ``` but I get > > System.InvalidOperationException > > > Unable to access the object by the calling thread because that object is owned by another thread properties. > > > I'm trying to return a list through the `SelectedIndex`, what am I doing wrong?
2016/09/21
[ "https://Stackoverflow.com/questions/39618411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6739907/" ]
The [YEARWEEK](https://www.w3schools.com/Sql/func_mysql_yearweek.asp) operator takes an mode option that lets you start the week on Monday. Then just query for the YEARWEEK of NOW() minus 1 ``` SELECT * FROM table WHERE YEARWEEK(timestamp,1)=YEARWEEK(NOW(),1)-1 ```
Try this : date BETWEEN YEARWEEK(CURDATE()) AND CURDATE()-INTERVAL 7 DAY
10,454,568
I'm making an iOS App that need to show some images from a remote site (from an URL), and everytime the users enter to the screen that should show the image, the app get freeze until the download is completed. So I want to store the images already downloaded into a SQLite Table named COVERS. Here is the code that how I'm downloading and Showing the image: Suppose that movieCover is an **UIImageView** and the object movie has a **NSURL** property named cover that contains the URL of the image to be downloaded. ``` NSData *cover = [[NSData alloc] initWithContentsOfURL:movie.cover]; movieCover.image = [[UIImage alloc] initWithData:cover]; ``` But, I want to change it to something like this: ``` NSData *cover = [appDelegate.dataBase getCoverForMovie:movie]; if( !cover ) { cover = [[NSData alloc] initWithContentsOfURL:movie.cover]; [appDelegate.dataBase setCover:cover ToMovie:movie]; } movieCover.image = [[UIImage alloc] initWithData:cover]; ``` Suppose that appDelegate is a property of the current ViewController, and dataBase is a property of the AppDelegate wich uses FMDB to manipulate the data in the DataBase. I need to get the cover previously saved in the database using the method: ``` - (NSData *)getCoverForMovie:(Movie *)movie; ``` But, if there is not a cover saved, then return nil. So I need to save the cover using the method ``` - (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie; ``` But I don't know how to code this method. Need some help with it.
2012/05/04
[ "https://Stackoverflow.com/questions/10454568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468428/" ]
Methods Implementations based on fmdb.m examples ------------------------------------------------ ``` - (NSData *)getCoverForMovie:(Movie *)movie { NSData *cover = nil; FMDatabase *db = [FMDatabase databaseWithPath:databasePath]; [db open]; FMResultSet *results = [db executeQueryWithFormat:@"SELECT * FROM COVERS WHERE movie = %i", movie.movieID]; if([results next]) { cover = [results dataForColumn:@"cover"]; } return cover; } - (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie { BOOL result; FMDatabase *db = [FMDatabase databaseWithPath:databasePath]; [db open]; result = [db executeUpdate:@"INSERT OR REPLACE INTO COVERS (movie, cover) VALUES (?,?)", movie.movieID, cover]; return result; } ``` Thanks to @ccgus for his answer.
Check out main.m in the FMDB distribution- it shows how to save and pull out a binary blob (using the safari icon as an example)".
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $('body').on('click', '.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
Use `$(document).on` ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ``` [**`DEMO`**](http://jsfiddle.net/AHyyq/6/)
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $('body').on('click', '.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
[See here](http://api.jquery.com/on/) ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $('body').on('click', '.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
It is correct behavior. You are adding events to non active elements (all 3 .item's). So it will not unbind events if you add class. I would do something like this: ``` $('input[type=button]').click(function(){ $('.item:nth-child(2)').addClass('active').css('color','#F00'); }); $('.item').on('click', function() { if($(this).is('.active')) return; $('<p>Not active</p>').appendTo('body'); }); ``` <http://jsfiddle.net/AHyyq/9/>
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `$(document).on` ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ``` [**`DEMO`**](http://jsfiddle.net/AHyyq/6/)
[See here](http://api.jquery.com/on/) ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `$(document).on` ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ``` [**`DEMO`**](http://jsfiddle.net/AHyyq/6/)
It is correct behavior. You are adding events to non active elements (all 3 .item's). So it will not unbind events if you add class. I would do something like this: ``` $('input[type=button]').click(function(){ $('.item:nth-child(2)').addClass('active').css('color','#F00'); }); $('.item').on('click', function() { if($(this).is('.active')) return; $('<p>Not active</p>').appendTo('body'); }); ``` <http://jsfiddle.net/AHyyq/9/>
15,564,140
When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live() <http://jsfiddle.net/AHyyq/1/> At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message. ``` $('.item:not(.active)').on('click', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
2013/03/22
[ "https://Stackoverflow.com/questions/15564140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is correct behavior. You are adding events to non active elements (all 3 .item's). So it will not unbind events if you add class. I would do something like this: ``` $('input[type=button]').click(function(){ $('.item:nth-child(2)').addClass('active').css('color','#F00'); }); $('.item').on('click', function() { if($(this).is('.active')) return; $('<p>Not active</p>').appendTo('body'); }); ``` <http://jsfiddle.net/AHyyq/9/>
[See here](http://api.jquery.com/on/) ``` $(document).on('click','.item:not(.active)', function(){ $('<p>Not active</p>').appendTo('body'); }); ```
74,679
Okay, so for the past few weeks, I've had a problem with Minecraft. The problem is that when I play on a new server, I log in and everything is fine, but after about 4 or 5 minutes playing, the game kicks me from the server and I can't reconnect. In the server list, it says "Can't reach server" and when I try connecting to any server, the connection times out. I even asked my friend that has a server to look at the console of his server, and when I got kicked, it says connection lost, generic.reason. And when I try connecting to the server, my connection attempt doesn't even show up. Help!
2012/06/25
[ "https://gaming.stackexchange.com/questions/74679", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/28147/" ]
I believe any power that has a radius when used can penetrate cover. some that come to mind are: * Reave * Incinerate * Biotic Strike * Electric Slash (?)
Here are a couple more I can think of: * Shadow strike * Annihilation Field * Singularity (it does not go through the cover but if you have a good radius on this skill enemies behind cover will get sucked in)
70,634,144
From my local machine I would like to be able to `port forward` to many services in a cluster. For example I have services of name `serviceA-type1`, `serviceA-type2`, `serviceA-type3`... etc. None of these services are accessible externally but can be accessed using the `kubectl port-forward` command. However there are so many services, that port forwarding to each is unfeasible. Is it possible to create some kind of proxy service in kubernetes that would allow me to connect to any of the `serviceA-typeN` services by specifying the them in a URL? I would like to be able to `port-forward` to the proxy service from my local machine and it would then forward the requests to the `serviceA-typeN` services. So for example, if I have set up a port forward on 8080 to this proxy, then the URL to access the `serviceA-type1` service might look like: ``` http://localhost:8080/serviceA-type1/path/to/endpoint?a=1 ``` I could maybe create a small application that would do this but does kubernetes provide this functionality already?
2022/01/08
[ "https://Stackoverflow.com/questions/70634144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240166/" ]
As mentioned in comments you should be using something other than depreciated classes. Below is an example of using runnable, simply add your parser and adapter This should be moved to android view model. ``` public class MainActivity extends AppCompatActivity { private final String LOG_TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.v(LOG_TAG, "on Create"); String apiUrl = "https://lebavui.github.io/jsons/users.json"; getUsers(apiUrl); } //return interface public interface Completion{ void onCompletion(List<String> list); } //calls a function which call Completion.onCompletion interface off of main thread public void getUsers(String apiUrl){ getAsyncData(apiUrl, this::setListDataOnMain); } //bring back to main thread //This should be in Android View model for application context instead of this.getMainLooper private void setListDataOnMain(List<String> list){ Handler mainHandler = new Handler(this.getMainLooper()); Runnable myRunnable = () -> { //Set local object "list" to your global variable //Then notify adapter change //only logging here as example Log.v(LOG_TAG, "List: " + list); }; mainHandler.post(myRunnable); } //make async public void getAsyncData(String apiUrl, Completion completion) { Runnable runnable = () -> { List<String> userList = makeRequest(apiUrl); completion.onCompletion(userList); }; Thread thread = new Thread(runnable); thread.start(); } //This is not async calling this func from main thread will crash public List<String> makeRequest(String apiUrl ) { List<String> userList = new ArrayList<>(); StringBuilder response = new StringBuilder(); URL url; HttpsURLConnection urlConnection = null; try { url = new URL(apiUrl); urlConnection = (HttpsURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int data = isr.read(); while (data != -1) { response.append((char) data); data = isr.read(); } JSONArray jsonArray = new JSONArray(response.toString()); for (int i = 0; i < jsonArray.length(); i++) { //your json parsing here userList.add(String.valueOf(i)); } } catch (Exception e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return userList; } } ```
I think the DataGetter class need to executed first than you can set adapter i test this code and it works ``` @SuppressLint("NotifyDataSetChanged") @Override protected void onPostExecute(Void unused) { super.onPostExecute(unused); progressDialog.dismiss(); userAdapter = new UserAdapter(userList, MainActivity.this); recyclerView.setAdapter(userAdapter); } ```
15,249,577
I would like to measure the traffic rate in Android with `android.net.TrafficStats`. The [documentation](http://developer.android.com/reference/android/net/TrafficStats.html) says, there is a `getUidTcpTxBytes()` and a `getUidUdpTxBytes()` function in this class. These ware added in API level 8. I'm using API level 8, but I can not find these functions, only some of them like `getTotalRxBytes()`. What could be the problem?
2013/03/06
[ "https://Stackoverflow.com/questions/15249577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140232/" ]
[`getUidTcpTxBytes()`](http://developer.android.com/reference/android/net/TrafficStats.html#getUidTcpTxBytes%28int%29) was added in API Level 12, as was [`getUidUdpTxBytes()`](http://developer.android.com/reference/android/net/TrafficStats.html#getUidUdpTxBytes%28int%29). You can tell this by viewing the methods in the JavaDocs and seeing the "Added in API level 12" notation, on the right side of the gray bar that houses the method signature.
Look closer: [getUidTcpTxBytes()](http://developer.android.com/reference/android/net/TrafficStats.html#getUidTcpTxBytes%28int%29) was added in API Level 12, as well as getUidUdpTxBytes(). Actually most of them were added after API Level 12 and 14.
16,831,209
Which is better in terms of performance, 2 medium role instances or 4 small role instances? What are the pro's and cons of each configuration?
2013/05/30
[ "https://Stackoverflow.com/questions/16831209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431681/" ]
The only real way to know if you gain advantage of using larger instances is trying and measuring, not asking here. [This article](http://msdn.microsoft.com/en-us/library/windowsazure/dn197896.aspx) has a table that says that a medium instance has everything twice as large as a small one. However in real life your mileage may vary and how this affects your application only you can measure. Smaller roles have one important advantage - if instances fail separately you get smaller performance degradation. Supposing you know about "guaranteed uptime" requirement of having at least two instances, you have to choose between two medium and four small instances. If one small instance fails you lose 1/4 of your performance, but if one medium instance fails you lose half of performance. Instances will fail if for example you have an unhandled exception inside `Run()` of your role entry point descendant and sometimes something just goes wrong big time and your code can't handle this and it'd better just restart. Not that you should deliberately target for such failures but you should expect them and take measures to minimize impact to your application. So the bottom line is - it's impossible to say which gets better performance, but uptime implications are just as important and they are clearly in favor of smaller instances.
For a start, you won't get the guaranteed uptime of 99% unless you have at least 2 ~~roles~~ role instances, this allows one to die and be restarted while the other one takes the burden. Otherwise, it is a case of how much you want to pay and what specs you get on each. It has not caused me any hassle having more than one ~~role~~ role instance, Azure hides the difficult stuff.
16,831,209
Which is better in terms of performance, 2 medium role instances or 4 small role instances? What are the pro's and cons of each configuration?
2013/05/30
[ "https://Stackoverflow.com/questions/16831209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431681/" ]
Good points by @sharptooth. One more thing to consider: When scaling *in*, the fewest number of instances is *one*, not *zero*. So, say you have a worker role that does some nightly task for an hour, and it requires either 2 Medium or 4 Small instances to get the job done in that timeframe. When the work is done, you may want to save costs by scaling to one instance and let it run as one instance for 23 hours until the next nightly job. With a single Small instance, you'll burn 23 core-hours, and with a single Medium instance, you'll burn 46 core-hours. This thinking also applies to your Web role, but probably more-so since you will probably have minimum two instances to make sure you have uptime SLA (it may not be as important for you to have SLA on your worker if, say, your end user never interacts with it and it's just for utility purposes). My general rule of thumb when sizing: Pick the smallest VM size that can properly do the work, and then scale out/in as needed. Your choice will primarily be driven by CPU, RAM, and network bandwidth needs (and don't forget you need network when moving data between Compute and Storage).
For a start, you won't get the guaranteed uptime of 99% unless you have at least 2 ~~roles~~ role instances, this allows one to die and be restarted while the other one takes the burden. Otherwise, it is a case of how much you want to pay and what specs you get on each. It has not caused me any hassle having more than one ~~role~~ role instance, Azure hides the difficult stuff.
16,831,209
Which is better in terms of performance, 2 medium role instances or 4 small role instances? What are the pro's and cons of each configuration?
2013/05/30
[ "https://Stackoverflow.com/questions/16831209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431681/" ]
For a start, you won't get the guaranteed uptime of 99% unless you have at least 2 ~~roles~~ role instances, this allows one to die and be restarted while the other one takes the burden. Otherwise, it is a case of how much you want to pay and what specs you get on each. It has not caused me any hassle having more than one ~~role~~ role instance, Azure hides the difficult stuff.
One other point maybe worth a mention if you use four small roles you would be able to run two in one datacenter and two in another datacenter and use traffic manager to route people at least which is closer. This might give you some performance gains. Two mediums will give you more options to store stuff in cache at compute level and thus more in cache rather than coming off SQL Azure it is going to be faster. Ideally you have to follow @sharptooth and measure and test. This is all very subjective and I second David also you want to start as small as possible and scale outwards. We run this way, you really want to think about designing your app around a more sharding aspect as this fits azure model better than working in traditional sense of just getting a bigger box to run everything on, at some point you run out into limits thinking in the bigger box process, ie.Like SQL Azure Connection limits. Using technologies like Jmeter is your friend here and should give you some tools to test your app. <http://jmeter.apache.org/>
16,831,209
Which is better in terms of performance, 2 medium role instances or 4 small role instances? What are the pro's and cons of each configuration?
2013/05/30
[ "https://Stackoverflow.com/questions/16831209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431681/" ]
The only real way to know if you gain advantage of using larger instances is trying and measuring, not asking here. [This article](http://msdn.microsoft.com/en-us/library/windowsazure/dn197896.aspx) has a table that says that a medium instance has everything twice as large as a small one. However in real life your mileage may vary and how this affects your application only you can measure. Smaller roles have one important advantage - if instances fail separately you get smaller performance degradation. Supposing you know about "guaranteed uptime" requirement of having at least two instances, you have to choose between two medium and four small instances. If one small instance fails you lose 1/4 of your performance, but if one medium instance fails you lose half of performance. Instances will fail if for example you have an unhandled exception inside `Run()` of your role entry point descendant and sometimes something just goes wrong big time and your code can't handle this and it'd better just restart. Not that you should deliberately target for such failures but you should expect them and take measures to minimize impact to your application. So the bottom line is - it's impossible to say which gets better performance, but uptime implications are just as important and they are clearly in favor of smaller instances.
One other point maybe worth a mention if you use four small roles you would be able to run two in one datacenter and two in another datacenter and use traffic manager to route people at least which is closer. This might give you some performance gains. Two mediums will give you more options to store stuff in cache at compute level and thus more in cache rather than coming off SQL Azure it is going to be faster. Ideally you have to follow @sharptooth and measure and test. This is all very subjective and I second David also you want to start as small as possible and scale outwards. We run this way, you really want to think about designing your app around a more sharding aspect as this fits azure model better than working in traditional sense of just getting a bigger box to run everything on, at some point you run out into limits thinking in the bigger box process, ie.Like SQL Azure Connection limits. Using technologies like Jmeter is your friend here and should give you some tools to test your app. <http://jmeter.apache.org/>
16,831,209
Which is better in terms of performance, 2 medium role instances or 4 small role instances? What are the pro's and cons of each configuration?
2013/05/30
[ "https://Stackoverflow.com/questions/16831209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431681/" ]
Good points by @sharptooth. One more thing to consider: When scaling *in*, the fewest number of instances is *one*, not *zero*. So, say you have a worker role that does some nightly task for an hour, and it requires either 2 Medium or 4 Small instances to get the job done in that timeframe. When the work is done, you may want to save costs by scaling to one instance and let it run as one instance for 23 hours until the next nightly job. With a single Small instance, you'll burn 23 core-hours, and with a single Medium instance, you'll burn 46 core-hours. This thinking also applies to your Web role, but probably more-so since you will probably have minimum two instances to make sure you have uptime SLA (it may not be as important for you to have SLA on your worker if, say, your end user never interacts with it and it's just for utility purposes). My general rule of thumb when sizing: Pick the smallest VM size that can properly do the work, and then scale out/in as needed. Your choice will primarily be driven by CPU, RAM, and network bandwidth needs (and don't forget you need network when moving data between Compute and Storage).
One other point maybe worth a mention if you use four small roles you would be able to run two in one datacenter and two in another datacenter and use traffic manager to route people at least which is closer. This might give you some performance gains. Two mediums will give you more options to store stuff in cache at compute level and thus more in cache rather than coming off SQL Azure it is going to be faster. Ideally you have to follow @sharptooth and measure and test. This is all very subjective and I second David also you want to start as small as possible and scale outwards. We run this way, you really want to think about designing your app around a more sharding aspect as this fits azure model better than working in traditional sense of just getting a bigger box to run everything on, at some point you run out into limits thinking in the bigger box process, ie.Like SQL Azure Connection limits. Using technologies like Jmeter is your friend here and should give you some tools to test your app. <http://jmeter.apache.org/>
41,523,925
Doc says <https://developer.android.com/reference/android/content/Intent.html#ACTION_MAIN> is an entry point. Example code: ``` <activity android:name="org.A.A" android:theme="@style/NoTitle" android:screenOrientation="behind" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> </activity> <activity android:name="org.A.C" android:theme="@style/NoTitle" android:launchMode="singleTop" android:screenOrientation="behind"> <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> </activity> <activity android:name="org.A.B" android:theme="@style/NoTitle" android:launchMode="singleTop" android:screenOrientation="behind"> <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> </activity> ``` 1) So using android.intent.action.ACTION\_MAIN acts as an entry point to the parent component (parent component I mean the activity or receiver or service)? 2) If yes, Entry point from where, as there is no CATEGORY mentioned.
2017/01/07
[ "https://Stackoverflow.com/questions/41523925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705478/" ]
Android apps are composed of different components. e.g. `Activity`, `Service`, `BroadcastReceiver`, and `ContentProvider` and each component can act as an **entry point** of the app. Let's take **activity** as an example, you have defined an activity in your application with following action ``` <intent-filter> <action android:name="com.yourapp.SOME_ACTION" /> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> ``` and I start an activity in **my** app with following intent. ``` Intent intent = new Intent("com.yourapp.SOME_ACTION"); // same action startActivity(intent); ``` Now what will happen? System will search for activities with `com.yourapp.SOME_ACTION` action and if it finds one (in current scenario, it will be activity you have created with `com.yourapp.SOME_ACTION` in your app), it will **start your app** (if it is not already started) and will open the activity in your app. See, now I can **enter** into your app by using `Activity` with `com.yourapp.SOME_ACTION`. Same thing happens in case of other components.
Activity with MAIN action will be entry point of application.If you have one its well and good if more than one then you can have multiple activities through which you can enter into application. ``` <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> ``` But if you have provided CATEGORY for activity it will create launcher for that entry point. ``` <category android:name="android.intent.category.LAUNCHER" /> ``` Suppose two activities is having both MAIN action and CATEGORY as launcher two app icon will be created one will have one activity as entry point second will have another one as entry point. ``` <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> ```
38,566,022
I have just installed a new Ionic project - Ionic v2.0.0-beta.32 Im looking to add a background image to the home page of the fresh install, is there anyone that could show me how i go about this? All i can find is information for Ionic 1 and things seems quite different. From what ive found, the image needs to be the following dimensions ``` 2800px x 2800px ``` But apart from that i cant find any other tutorials. This is my first Ionic project so be gentle Thanks you guys
2016/07/25
[ "https://Stackoverflow.com/questions/38566022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075391/" ]
The image can be any size. go to `app/theme/app.core.scss` and add the following code ``` ion-content{ background-image: url('img/background.jpg'); } ``` This is assuming that the name of your image file is `background.jpg` and is stored in `www/img/` folder. Hope this helps UPDATE Ionic 3.x ---------------- Go to `app/app.scss` and add the following code ``` ion-content { background-image: url('assets/img/background.jpg'); } ``` This is assuming that the name of your image file is `background.jpg` and is stored in `assets/img` folder.
In ionic 2 the background image work only if you put the img folder into the build folder. If you go to inspect on the mage url it will show you that i finding for it in build/img/bg.jpg try to put folder img into build folder. www/build/img
38,566,022
I have just installed a new Ionic project - Ionic v2.0.0-beta.32 Im looking to add a background image to the home page of the fresh install, is there anyone that could show me how i go about this? All i can find is information for Ionic 1 and things seems quite different. From what ive found, the image needs to be the following dimensions ``` 2800px x 2800px ``` But apart from that i cant find any other tutorials. This is my first Ionic project so be gentle Thanks you guys
2016/07/25
[ "https://Stackoverflow.com/questions/38566022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075391/" ]
The image can be any size. go to `app/theme/app.core.scss` and add the following code ``` ion-content{ background-image: url('img/background.jpg'); } ``` This is assuming that the name of your image file is `background.jpg` and is stored in `www/img/` folder. Hope this helps UPDATE Ionic 3.x ---------------- Go to `app/app.scss` and add the following code ``` ion-content { background-image: url('assets/img/background.jpg'); } ``` This is assuming that the name of your image file is `background.jpg` and is stored in `assets/img` folder.
For **Ionic V4** they use some new switch in the scss file. This worked for me: ``` ion-content { --background: url('../../assets/Welcome-screen.png') no-repeat 50% 10%; } ```
38,566,022
I have just installed a new Ionic project - Ionic v2.0.0-beta.32 Im looking to add a background image to the home page of the fresh install, is there anyone that could show me how i go about this? All i can find is information for Ionic 1 and things seems quite different. From what ive found, the image needs to be the following dimensions ``` 2800px x 2800px ``` But apart from that i cant find any other tutorials. This is my first Ionic project so be gentle Thanks you guys
2016/07/25
[ "https://Stackoverflow.com/questions/38566022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075391/" ]
For **Ionic V4** they use some new switch in the scss file. This worked for me: ``` ion-content { --background: url('../../assets/Welcome-screen.png') no-repeat 50% 10%; } ```
In ionic 2 the background image work only if you put the img folder into the build folder. If you go to inspect on the mage url it will show you that i finding for it in build/img/bg.jpg try to put folder img into build folder. www/build/img
41,150
Помогите разрешить спор. Учитель русского языка советской ещё школы утверждает, что слово "оледенение" (проводов, трасс и т. д.) — это единственно верное употребление, а вот "обледенение" — это девчушки вдоль трассы! Словари разнятся в толковании этого слова. Может быть, кто-то знает правило?
2014/10/24
[ "https://rus.stackexchange.com/questions/41150", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/4265/" ]
(1) Оледенеть — превратиться в лёд (сравнить: твёрдый — отвердеть, камень — окаменеть), в том числе в переносном смысле (замерзнуть, очень испугаться). Ледниковый период — это оледенение. Другой пример: "Оледенение, охватившее ее после гибели отца, постепенно прошло". (2) Обледенеть — покрыться льдом. Обычно имеет место обледенение крыльев самолета, проводов, стекол.
Учитель не прав. Возможны оба варианта. ***ОБЛЕДЕНЕТЬ***, - ***Покрываться льдом со всех сторон, по всей поверхности.*** отт. ***Превращаться в лёд; замерзать.*** 2.Становиться холодным как лёд; коченеть (Современный толковый словарь русского языка Ефремовой, 2000г.) ***ОБЛЕДЕНЕТЬ,*** -ею, -еешь; обледенённый; -нён, -нена, -нено; св. 1. ***Покрыться льдом***. Палуба обледенела. ***Мокрая дорога после оттепели обледенела.*** Валенки обледенели, и ноги разъезжались. 2. ***Замёрзнуть, закоченеть***. Руки обледенели. Губы на ветру обледенели. < Обледеневать, -аю, -аешь; нсв. Обледенение, -я; ср. О. крыльев самолёта. Древнее о.( Большой толковый словарь под редакцией Кузнецова). **Обледенение** - ***отложение льда на поверхностях дорог, аэродромов, летательных аппаратов, морских судов и др.***( Энциклопедия техники). ***ОЛЕДЕНЕТЬ, -***нею, -неешь; оледеневший; св. (нсв. также леденеть). 1. ***Превратиться в лёд, покрыться льдом; обледенеть***. Мокрая одежда на морозе оледенела. 2. ***Стать холодным как лёд; замёрзнуть, окоченеть. От холодной воды руки оледенели. < Оледеневать, -аю, -аешь; нсв. Оледенение, -я; ср.*** ( Большой толковый словарь под редакцией Кузнецова). ***ОЛЕДЕНЕНИЕ*** — оболочка льда и снега, включающая все виды О., известные на Земле. Основные типы О.: 1) ***наземное — лед скапливается в виде ледников и ледниковых покровов;*** 2) морское — льды накапливаются на поверхности морей и океанов в виде однолетних и многолетних масс;(Геологическая энциклопедия). 3) подземное (мерзлота). Оледеневать ``` оледенева́ть несов. неперех. 1. ***Покрываться льдом со всех сторон, по всей поверхности; превращаться в лед.*** 2. ***Становиться холодным, как лед; замерзать, коченеть.*** 3. перен. Цепенеть, холодеть от ужаса, страха и т.п. ```
41,150
Помогите разрешить спор. Учитель русского языка советской ещё школы утверждает, что слово "оледенение" (проводов, трасс и т. д.) — это единственно верное употребление, а вот "обледенение" — это девчушки вдоль трассы! Словари разнятся в толковании этого слова. Может быть, кто-то знает правило?
2014/10/24
[ "https://rus.stackexchange.com/questions/41150", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/4265/" ]
Учитель не прав. Возможны оба варианта. ***ОБЛЕДЕНЕТЬ***, - ***Покрываться льдом со всех сторон, по всей поверхности.*** отт. ***Превращаться в лёд; замерзать.*** 2.Становиться холодным как лёд; коченеть (Современный толковый словарь русского языка Ефремовой, 2000г.) ***ОБЛЕДЕНЕТЬ,*** -ею, -еешь; обледенённый; -нён, -нена, -нено; св. 1. ***Покрыться льдом***. Палуба обледенела. ***Мокрая дорога после оттепели обледенела.*** Валенки обледенели, и ноги разъезжались. 2. ***Замёрзнуть, закоченеть***. Руки обледенели. Губы на ветру обледенели. < Обледеневать, -аю, -аешь; нсв. Обледенение, -я; ср. О. крыльев самолёта. Древнее о.( Большой толковый словарь под редакцией Кузнецова). **Обледенение** - ***отложение льда на поверхностях дорог, аэродромов, летательных аппаратов, морских судов и др.***( Энциклопедия техники). ***ОЛЕДЕНЕТЬ, -***нею, -неешь; оледеневший; св. (нсв. также леденеть). 1. ***Превратиться в лёд, покрыться льдом; обледенеть***. Мокрая одежда на морозе оледенела. 2. ***Стать холодным как лёд; замёрзнуть, окоченеть. От холодной воды руки оледенели. < Оледеневать, -аю, -аешь; нсв. Оледенение, -я; ср.*** ( Большой толковый словарь под редакцией Кузнецова). ***ОЛЕДЕНЕНИЕ*** — оболочка льда и снега, включающая все виды О., известные на Земле. Основные типы О.: 1) ***наземное — лед скапливается в виде ледников и ледниковых покровов;*** 2) морское — льды накапливаются на поверхности морей и океанов в виде однолетних и многолетних масс;(Геологическая энциклопедия). 3) подземное (мерзлота). Оледеневать ``` оледенева́ть несов. неперех. 1. ***Покрываться льдом со всех сторон, по всей поверхности; превращаться в лед.*** 2. ***Становиться холодным, как лед; замерзать, коченеть.*** 3. перен. Цепенеть, холодеть от ужаса, страха и т.п. ```
Сказать обводнение можно и звучит нормально. Сказать оводнение нельзя и звучит двусмысленно. Вообще есть другая приставка, если холодно, за-леденеть. Обмерзнуть, замерзнуть, но не омерзнуть, можно сказать омерзительно, обмерзительно нельзя. То есть оледенение-двоякий смысл, возможно, как результат вмешательства составителей словарей, а может и ученых, занимавшихся ВЕЛИКИМ ОЛЕДЕНЕНИЕМ, Оводнением хрусталика,не вполне знакомых с подобной спецификой русского языка.
41,150
Помогите разрешить спор. Учитель русского языка советской ещё школы утверждает, что слово "оледенение" (проводов, трасс и т. д.) — это единственно верное употребление, а вот "обледенение" — это девчушки вдоль трассы! Словари разнятся в толковании этого слова. Может быть, кто-то знает правило?
2014/10/24
[ "https://rus.stackexchange.com/questions/41150", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/4265/" ]
(1) Оледенеть — превратиться в лёд (сравнить: твёрдый — отвердеть, камень — окаменеть), в том числе в переносном смысле (замерзнуть, очень испугаться). Ледниковый период — это оледенение. Другой пример: "Оледенение, охватившее ее после гибели отца, постепенно прошло". (2) Обледенеть — покрыться льдом. Обычно имеет место обледенение крыльев самолета, проводов, стекол.
Сказать обводнение можно и звучит нормально. Сказать оводнение нельзя и звучит двусмысленно. Вообще есть другая приставка, если холодно, за-леденеть. Обмерзнуть, замерзнуть, но не омерзнуть, можно сказать омерзительно, обмерзительно нельзя. То есть оледенение-двоякий смысл, возможно, как результат вмешательства составителей словарей, а может и ученых, занимавшихся ВЕЛИКИМ ОЛЕДЕНЕНИЕМ, Оводнением хрусталика,не вполне знакомых с подобной спецификой русского языка.
58,322,759
NuGet.Core has been deprecated, I am struggling to find out an API to get NuGet package version from remote repository specified by URL. Using IPackageRepository was quite straight forward but I am not getting any way how to do it without using NuGet.Core?
2019/10/10
[ "https://Stackoverflow.com/questions/58322759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142462/" ]
Edit: FactoryExtensionsV3.GetCoreV3 probably refers to "NuGet version 3", not NuGet's v3 HTTP API. So, this code works for local file feeds as well as both V2 and V3 HTTP feeds. Just change the URL passed to PackageSource. ```cs static async Task Main(string[] args) { var packageSource = new PackageSource("https://api.nuget.org/v3/index.json"); var sourceRepository = new SourceRepository(packageSource, FactoryExtensionsV3.GetCoreV3(null)); var metadata = await sourceRepository.GetResourceAsync<MetadataResource>(); var cacheContext = new SourceCacheContext(); var versions = await metadata.GetVersions("newtonsoft.json", cacheContext, NullLogger.Instance, CancellationToken.None); foreach (var version in versions) { Console.WriteLine("Found version " + version.ToNormalizedString()); } } ```
I've made a package to make it easier to interact with NuGet V3 servers: <https://github.com/loic-sharma/BaGet/tree/master/src/BaGet.Protocol#list-package-versions> ```cs NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); IReadOnlyList<NuGetVersion>> versions = await client.ListPackageVersionsAsync("Newtonsoft.Json"); foreach (NuGetVersion version in versions) { Console.WriteLine($"Found version: {version}"); } ``` Please let me know if you have any feedback or suggestions! :)
760,828
I am attempting to install Arch linux and dual boot it with windows. As I am running a modern UEFI system, I have put my SSD (see Specs below) in GPT format (losing my original windows installation in the process) where I plan on installing the UEFI boot loader, Windows, and Arch. At the moment I'm trying to reinstall Windows 7 (Professional x64), so I can do a UEFI boot. When I use Rufus to create a bootable GPT USB drive, I get the boot error 0xc0000225. When I try to do it manually with these (<http://www.eightforums.com/tutorials...e-windows.html>) instructions, my computer does not recognize my flash drive as bootable (it gives the insert proper boot media error). I am using this (<http://msft.digitalrivercontent.net/win/X17-59186.iso>) for the ISO, I also have an old installation disc. Booting the ISO without modification in Legacy BIOS works just fine, but I have no way to install windows to a GPT drive while booting in Legacy BIOS (Windows states it cannot be installed to a GPT drive, probably because it detects the system is running legacy bios instead of UEFI). How can I install Windows 7 onto GPT? Specifications: CPU: i5-4670k Motherboard: Z87x-D3H Gigabyte SSD: OCZ Vertex 3 (Set in GPT mode) HDD: Western Digital Caviar Blue Flash Drive: 8GB JetFlash Transcend USB 3.0
2014/05/30
[ "https://superuser.com/questions/760828", "https://superuser.com", "https://superuser.com/users/328095/" ]
From [Resolving the dreaded Windows 8 0xC0000225 error](http://www.maximumpc.com/forums/viewtopic.php?f=6&t=242035&start=0&sid=40f651e91c64399ffa25322ac03db078) : > > I've had this happen to me twice, all of a sudden Windows 8 refuses to > boot and gives an error code of 0xC0000225 (or something) and anything > you do won't fix it. The problem is that since for whatever reason > Windows thinks there's no bootloader, it refuses to boot. Period. You > can't even go into the recovery environment, which is my biggest > complaint at Microsoft. > > > In any case, there's one way I've found to resolve this. If you have > access to another computer, take out the affected computer's primary > drive and find a way to mount it in the system (internally, > externally, whatever). Then do the following: > > > * Open command prompt as an administrator > * Type in "diskpart" > * Type in "list disk". Find out which disk the affected drive is. > * Type in "select disk #", where # is the affected drive's number > * Type in "list partition", find the partition number of the system partition (it's usually 100MB, 200MB, or 300MB), then type in "select > partition #", where # is the system partition's number. > * Type in "assign letter=z", assuming you don't have a Z: drive. > * Exit out of diskpart by pressing CTRL+C > * Type in BCDBoot `[Drive letter of affected drive's Windows partition]:\Windows /S Z: /F UEFI` So if the affected drive's > Windows partition is say G:\, you would type in BCDBoot G:\Windows /S > Z: /F UEFI > > > It should fix the bootloader. If you can get into a recovery > environment on the affected computer, then this should work as well. > > >
Set Rufus to MBR for UEFI with FAT32 file system to cause it to partition the flash drive as an MBR drive with a single FAT32 partition which contains the Windows UEFI boot files. Additionally you may want to disconnect all other drives. I was having an issue where my HDD which contained a copy of my old SSD installation partition was being recognized as a valid boot drive. This was causing the 0xc0000225 error (in addition to the flash drive being partitioned with the GUID partition table.
12,011,174
I have a client and server setup to run with JBoss AS 7.1.1 and I have a question about my persistence.xml. Currently it looks like this: ``` <persistence> <persistence-unit name="GrahamsProj"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:jboss/datasources/WorkCenterDS</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/> </properties> </persistence-unit> </persistence> ``` I have persistence.xml in the META-INF folder of my server. I must be missing some properties though because I'm getting this error when I try to query the database I'm connected to. ``` 11:35:07,840 ERROR [org.jboss.ejb3.invocation] (EJB default - 1) JBAS014134: EJB Invocation failed on component GrahamsProjBean for method public abstract void grahamsprojserver.session.interfaces.GrahamsProjBeanRemote.test(): javax.ejb.EJB Exception: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Schemas is not mapped [FROM Schemas s] ``` Is there something I'm missing?
2012/08/17
[ "https://Stackoverflow.com/questions/12011174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/515377/" ]
you need to include all your model classes in persistence.xml. example: ``` <persistence> <persistence-unit name="GrahamsProj"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:jboss/datasources/WorkCenterDS</jta-data-source> <class>your.class.model.Example</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/> </properties> </persistence-unit> </persistence> ```
You would probably need to update the hibernate.dialect property too. In your example you are using "org.hibernate.dialect.HSQLDialect" and you use Oracle drivers, e.g. "oracle.jdbc.OracleDriver". If you are using Oracle database, you need to update hibernate dialect, e.g. "org.hibernate.dialect.Oracle10gDialect". Here's your updated code: ``` <persistence> <persistence-unit name="GrahamsProj"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:jboss/datasources/WorkCenterDS</jta-data-source> <class>your.class.model.Example</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/> </properties> </persistence-unit> </persistence> ```
5,343,653
I have a text in MySQL database that is requested in "$description" and I would like to know if `\\\\\\\\r\\\\\\\\n` is present in the description. So i got: ``` if(strpos($description, "\\\\\\\\r\\\\\\\\n") !== FALSE) { echo "String is here."; } else { echo "String not found."; } ``` but this always outputs "String not found." and I believe there is a bad escaping in the searched string (`\\\\\\\\r\\\\\\\\n`). How can I strpos by `\\\\\\\\r\\\\\\\\n` ? Also, I would probably end up str\_replace-ing every `\\\\\\\\r\\\\\\\\n` with `\r\n` as somebody made some bad escaping functions and data arrived as `\\\\\\\\r\\\\\\\\n` instead of `\r\n`, so a str\_replace faces the same problem also. I could use help on any of these tasks (str\_pos,str\_replace). Thank you very much.
2011/03/17
[ "https://Stackoverflow.com/questions/5343653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56409/" ]
``` if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n') !== FALSE) { echo "String is here."; } else { echo "String not found."; } ``` [further reading](http://php.net/types.string)
``` <?php $in = "abc"; if(preg_match('/\n|\r/',$in)){ echo 'found'; }else{ echo 'not found'; } ```
5,343,653
I have a text in MySQL database that is requested in "$description" and I would like to know if `\\\\\\\\r\\\\\\\\n` is present in the description. So i got: ``` if(strpos($description, "\\\\\\\\r\\\\\\\\n") !== FALSE) { echo "String is here."; } else { echo "String not found."; } ``` but this always outputs "String not found." and I believe there is a bad escaping in the searched string (`\\\\\\\\r\\\\\\\\n`). How can I strpos by `\\\\\\\\r\\\\\\\\n` ? Also, I would probably end up str\_replace-ing every `\\\\\\\\r\\\\\\\\n` with `\r\n` as somebody made some bad escaping functions and data arrived as `\\\\\\\\r\\\\\\\\n` instead of `\r\n`, so a str\_replace faces the same problem also. I could use help on any of these tasks (str\_pos,str\_replace). Thank you very much.
2011/03/17
[ "https://Stackoverflow.com/questions/5343653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56409/" ]
The the unfortunate nature of the detecting the backslash character is because it is also the universal escaping character. And to put a literal backslash into a string, you have to escape it - with itself That is to say, if you wanted to detect a *single* backslash, your code might look like this ``` if(strpos($description, '\\' ) !== FALSE) ``` Therefore, if you want to detect eight, consecutive backslashes, your string to match against will need double-that - sixteen. ``` if(strpos($description, '\\\\\\\\\\\\\\\\' ) !== FALSE) ``` Therefore, your final match using `strpos()` would have to look like this ``` if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n' ) !== FALSE) ``` Also noticed that I switched to single-quotes. That's because `\n` and `\r` [are interpreted](http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.double) inside of double-quoted string literals. You can also do this with regular expressions, which is going to be a bit more flexible and powerful ``` if ( preg_match( "/\\x5C{8}[rn]/", $description ) ) ``` EDIT ---- For search-replacing, I suggest something like this. As I mentioned above, the regular expression is going to be more powerful - this one will match `\r` or `\n` (and not just when they're adjacent) with ANY quantity of preceding backslashes, not only 8 of them. ``` $description = preg_replace( "/\\x5C+([rn])/", '\\\${1}', $description ); ```
``` <?php $in = "abc"; if(preg_match('/\n|\r/',$in)){ echo 'found'; }else{ echo 'not found'; } ```
5,343,653
I have a text in MySQL database that is requested in "$description" and I would like to know if `\\\\\\\\r\\\\\\\\n` is present in the description. So i got: ``` if(strpos($description, "\\\\\\\\r\\\\\\\\n") !== FALSE) { echo "String is here."; } else { echo "String not found."; } ``` but this always outputs "String not found." and I believe there is a bad escaping in the searched string (`\\\\\\\\r\\\\\\\\n`). How can I strpos by `\\\\\\\\r\\\\\\\\n` ? Also, I would probably end up str\_replace-ing every `\\\\\\\\r\\\\\\\\n` with `\r\n` as somebody made some bad escaping functions and data arrived as `\\\\\\\\r\\\\\\\\n` instead of `\r\n`, so a str\_replace faces the same problem also. I could use help on any of these tasks (str\_pos,str\_replace). Thank you very much.
2011/03/17
[ "https://Stackoverflow.com/questions/5343653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56409/" ]
The the unfortunate nature of the detecting the backslash character is because it is also the universal escaping character. And to put a literal backslash into a string, you have to escape it - with itself That is to say, if you wanted to detect a *single* backslash, your code might look like this ``` if(strpos($description, '\\' ) !== FALSE) ``` Therefore, if you want to detect eight, consecutive backslashes, your string to match against will need double-that - sixteen. ``` if(strpos($description, '\\\\\\\\\\\\\\\\' ) !== FALSE) ``` Therefore, your final match using `strpos()` would have to look like this ``` if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n' ) !== FALSE) ``` Also noticed that I switched to single-quotes. That's because `\n` and `\r` [are interpreted](http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.double) inside of double-quoted string literals. You can also do this with regular expressions, which is going to be a bit more flexible and powerful ``` if ( preg_match( "/\\x5C{8}[rn]/", $description ) ) ``` EDIT ---- For search-replacing, I suggest something like this. As I mentioned above, the regular expression is going to be more powerful - this one will match `\r` or `\n` (and not just when they're adjacent) with ANY quantity of preceding backslashes, not only 8 of them. ``` $description = preg_replace( "/\\x5C+([rn])/", '\\\${1}', $description ); ```
``` if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n') !== FALSE) { echo "String is here."; } else { echo "String not found."; } ``` [further reading](http://php.net/types.string)
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
1. People with degrees statistically have a [better income](http://study.com/articles/How_Much_More_Do_College_Graduates_Earn_Than_Non-College_Graduates.html) than those without degrees. 2. If assisting your child financially is the difference as to whether they can acquire a degree or not then it seems logical that you should consider helping them in whatever way you can. <http://www.pewsocialtrends.org/2014/02/11/the-rising-cost-of-not-going-to-college/> <https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/229498/bis-13-899-the-impact-of-university-degrees-on-the-lifecycle-of-earnings-further-analysis.pdf> <https://www.abc.net.au/news/2012-10-24/uni-graduates-likely-to-earn-one-million-more-over-lifetime/4330506>
There is no need to pay for their college tuition. I have only my own anecdotal experience. However, by not paying for their college, they will need to ascertain risk/reward themselves. e.g. * Does this private university, which is 300% more, provide additional value to my life? * How could I pay for this without incurring excessive debt? * Should I go part-time to college? * Will I be able to handle this debt with the major I am choosing? Note, please sit with your **child** and *walk them thru* such questions (maybe get reasonable accountant or financial planner to help) This will also help you let the little "chick" leave the nest as these are all their decisions. Now, when they turn 25, if you want to set up a trust or give them a gift, by all means feel free.
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
Split the cost with the child ============================= My parents and I had a deal with regards to college. They would pay for 50% of the costs of college, including tuition/fees/room/board. I had to pay the other 50%, however there was the stipulation that any scholarships I earned went into my 50%. Since I was able to receive a full ride scholarship, my parents even gave me the 50% they had saved for me so I could keep it in savings. If I failed to keep my scholarships, I would have had to take out student loans or started working. This arrangement incentives your children to maintain good grades knowing that they'll have to pay extra if they goof around and start failing classes. It also means that if they're dedicated and get lots of scholarships, they won't have to have a job in college and are able to spend more time on their studies. You also mention the student working part time in college. This is do-able, however the potential gains from scholarships are so much greater than working part time. My parents' philosophy while I was in high school was that my full time job was doing activities/maintaining grades that would get me good scholarships. If you get a full ride, that's essentially saving you anywhere from $100k - $500k. I was able to get a full ride for my first year via ROTC. I decided that I didn't want to join the military, but since I had good grades, I was able to apply for (and get) a bunch of other scholarships that continued to pay for all my tuition and fees. Then my parents payed for housing. I had 1 part time job in college during a lighter semester, but instead of working in college, I was able to graduate with 3 degrees in 4 years, study abroad, and get an honors degree. All of these experiences were way more beneficial to me than working a part time job would have been.
There is no need to pay for their college tuition. I have only my own anecdotal experience. However, by not paying for their college, they will need to ascertain risk/reward themselves. e.g. * Does this private university, which is 300% more, provide additional value to my life? * How could I pay for this without incurring excessive debt? * Should I go part-time to college? * Will I be able to handle this debt with the major I am choosing? Note, please sit with your **child** and *walk them thru* such questions (maybe get reasonable accountant or financial planner to help) This will also help you let the little "chick" leave the nest as these are all their decisions. Now, when they turn 25, if you want to set up a trust or give them a gift, by all means feel free.
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
My husband and I helped our son with undergraduate college so that he wouldn't have so much debt from student loans but only because he was committed to his education. I am all for helping your children with this if you have the resources, but only if they are committed to their education too. I paid for my own college costs with student loans, but I did see some students at that time that were not very committed to their education because their parents were footing the bill. I guess that you have to weigh in all factors.
I think you should, because I wouldn't be able to study aboard for university without my parents' help. But you need to let your children understand you are not giving them free money. I think the key point is to let your children understand the value of their education, and that university degree doesn't just fall from the sky. It comes from your hard work. You can also tell them that this is a loan from you with no interest (or low interest), but you expect them to to pay you back in `x` years. So that they will feel pressure and value their time in university. When we get something for free, we usually take it granted; but when it comes at a price, we usually treat it more carefully. You don't necessarily actually need them to pay you back the loan, but don't let them know that before they graduate. You can actually start teaching them value of money now, by asking them to get some part-time job. --- As others have mentioned, average tuition in US is very expensive. Googling shows that > > published tuition fees for 2014/15 at state colleges are an average of > US$9,139 for state residents, and $22,958 for everyone else. This > compares to an average of $31,231 at private non-profit colleges. > > > (<http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us>) So even if they go to a local one, by working around 1000 hours a week (20 hr/week \* 50 weeks) at $7.25 minimal wage, they can barely cover their tuition, not to mention other expenses (say the university is out of town, then they'll need housing).
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
1. People with degrees statistically have a [better income](http://study.com/articles/How_Much_More_Do_College_Graduates_Earn_Than_Non-College_Graduates.html) than those without degrees. 2. If assisting your child financially is the difference as to whether they can acquire a degree or not then it seems logical that you should consider helping them in whatever way you can. <http://www.pewsocialtrends.org/2014/02/11/the-rising-cost-of-not-going-to-college/> <https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/229498/bis-13-899-the-impact-of-university-degrees-on-the-lifecycle-of-earnings-further-analysis.pdf> <https://www.abc.net.au/news/2012-10-24/uni-graduates-likely-to-earn-one-million-more-over-lifetime/4330506>
I think you should, because I wouldn't be able to study aboard for university without my parents' help. But you need to let your children understand you are not giving them free money. I think the key point is to let your children understand the value of their education, and that university degree doesn't just fall from the sky. It comes from your hard work. You can also tell them that this is a loan from you with no interest (or low interest), but you expect them to to pay you back in `x` years. So that they will feel pressure and value their time in university. When we get something for free, we usually take it granted; but when it comes at a price, we usually treat it more carefully. You don't necessarily actually need them to pay you back the loan, but don't let them know that before they graduate. You can actually start teaching them value of money now, by asking them to get some part-time job. --- As others have mentioned, average tuition in US is very expensive. Googling shows that > > published tuition fees for 2014/15 at state colleges are an average of > US$9,139 for state residents, and $22,958 for everyone else. This > compares to an average of $31,231 at private non-profit colleges. > > > (<http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us>) So even if they go to a local one, by working around 1000 hours a week (20 hr/week \* 50 weeks) at $7.25 minimal wage, they can barely cover their tuition, not to mention other expenses (say the university is out of town, then they'll need housing).
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
Split the cost with the child ============================= My parents and I had a deal with regards to college. They would pay for 50% of the costs of college, including tuition/fees/room/board. I had to pay the other 50%, however there was the stipulation that any scholarships I earned went into my 50%. Since I was able to receive a full ride scholarship, my parents even gave me the 50% they had saved for me so I could keep it in savings. If I failed to keep my scholarships, I would have had to take out student loans or started working. This arrangement incentives your children to maintain good grades knowing that they'll have to pay extra if they goof around and start failing classes. It also means that if they're dedicated and get lots of scholarships, they won't have to have a job in college and are able to spend more time on their studies. You also mention the student working part time in college. This is do-able, however the potential gains from scholarships are so much greater than working part time. My parents' philosophy while I was in high school was that my full time job was doing activities/maintaining grades that would get me good scholarships. If you get a full ride, that's essentially saving you anywhere from $100k - $500k. I was able to get a full ride for my first year via ROTC. I decided that I didn't want to join the military, but since I had good grades, I was able to apply for (and get) a bunch of other scholarships that continued to pay for all my tuition and fees. Then my parents payed for housing. I had 1 part time job in college during a lighter semester, but instead of working in college, I was able to graduate with 3 degrees in 4 years, study abroad, and get an honors degree. All of these experiences were way more beneficial to me than working a part time job would have been.
As you note in your question, college tuition has risen significantly faster than inflation over the past decade or two. This makes it more difficult to cover all one's college costs just from work during college. If you can afford it, you might put enough away to take some of the burden off of them, while still depending on them to do some work to avoid debt. Be aware that many universities take into account how much money a student has available when determining student aid. It pays to be aware of these policies and to put as much of your money as possible into things the universities won't or can't take into account. For example, they are not allowed to take your retirement accounts into account, and most will not take your housing equity into account, though universities differ on the latter.
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
There is no need to pay for their college tuition. I have only my own anecdotal experience. However, by not paying for their college, they will need to ascertain risk/reward themselves. e.g. * Does this private university, which is 300% more, provide additional value to my life? * How could I pay for this without incurring excessive debt? * Should I go part-time to college? * Will I be able to handle this debt with the major I am choosing? Note, please sit with your **child** and *walk them thru* such questions (maybe get reasonable accountant or financial planner to help) This will also help you let the little "chick" leave the nest as these are all their decisions. Now, when they turn 25, if you want to set up a trust or give them a gift, by all means feel free.
I think you should, because I wouldn't be able to study aboard for university without my parents' help. But you need to let your children understand you are not giving them free money. I think the key point is to let your children understand the value of their education, and that university degree doesn't just fall from the sky. It comes from your hard work. You can also tell them that this is a loan from you with no interest (or low interest), but you expect them to to pay you back in `x` years. So that they will feel pressure and value their time in university. When we get something for free, we usually take it granted; but when it comes at a price, we usually treat it more carefully. You don't necessarily actually need them to pay you back the loan, but don't let them know that before they graduate. You can actually start teaching them value of money now, by asking them to get some part-time job. --- As others have mentioned, average tuition in US is very expensive. Googling shows that > > published tuition fees for 2014/15 at state colleges are an average of > US$9,139 for state residents, and $22,958 for everyone else. This > compares to an average of $31,231 at private non-profit colleges. > > > (<http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us>) So even if they go to a local one, by working around 1000 hours a week (20 hr/week \* 50 weeks) at $7.25 minimal wage, they can barely cover their tuition, not to mention other expenses (say the university is out of town, then they'll need housing).
28,167
**In Short** I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better. **Background** I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption. When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself). I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride. I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation. I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement. **Addressing College Cost** I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out. I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult. According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990. We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable. Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents. To be clear on a few points: * Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs. * I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed. * All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to: * The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after.
2016/12/14
[ "https://parenting.stackexchange.com/questions/28167", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/7735/" ]
As you note in your question, college tuition has risen significantly faster than inflation over the past decade or two. This makes it more difficult to cover all one's college costs just from work during college. If you can afford it, you might put enough away to take some of the burden off of them, while still depending on them to do some work to avoid debt. Be aware that many universities take into account how much money a student has available when determining student aid. It pays to be aware of these policies and to put as much of your money as possible into things the universities won't or can't take into account. For example, they are not allowed to take your retirement accounts into account, and most will not take your housing equity into account, though universities differ on the latter.
I think you should, because I wouldn't be able to study aboard for university without my parents' help. But you need to let your children understand you are not giving them free money. I think the key point is to let your children understand the value of their education, and that university degree doesn't just fall from the sky. It comes from your hard work. You can also tell them that this is a loan from you with no interest (or low interest), but you expect them to to pay you back in `x` years. So that they will feel pressure and value their time in university. When we get something for free, we usually take it granted; but when it comes at a price, we usually treat it more carefully. You don't necessarily actually need them to pay you back the loan, but don't let them know that before they graduate. You can actually start teaching them value of money now, by asking them to get some part-time job. --- As others have mentioned, average tuition in US is very expensive. Googling shows that > > published tuition fees for 2014/15 at state colleges are an average of > US$9,139 for state residents, and $22,958 for everyone else. This > compares to an average of $31,231 at private non-profit colleges. > > > (<http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us>) So even if they go to a local one, by working around 1000 hours a week (20 hr/week \* 50 weeks) at $7.25 minimal wage, they can barely cover their tuition, not to mention other expenses (say the university is out of town, then they'll need housing).