Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
10,170,964
I wonder if there is any posibility to sort a text file by columns. For example I have `aux1.txt` with rows like this ``` Name SecondName Grade ``` In shell i can do this ``` sort -r -k 3 aux1 ``` It sorts the file by the 3rd column(grade). In batch ``` sort /+3 < aux1.txt ``` sorts the file after the 3rd letter. I read the sort manual for batch but no results.
2012/04/16
[ "https://Stackoverflow.com/questions/10170964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331244/" ]
You could write your own *sort-wrapper* with a batch file. You only need to reorder the columns into a temporary file, sort it and order it back. (nearly obvious) ``` REM *** Get the desired colum and place it as first column in the temporary file setlocal DisableDelayedExpansion ( for /F "tokens=1-3 delims= " %%A in (aux1.txt) DO ( set "par1=%%A" set "par2=%%B" set "par3=%%C" setlocal EnableDelayedExpansion echo(!par2! !par1! !par2! !par3! endlocal ) ) > aux1.txt.tmp REM ** Now sort the first colum, but echo only the rest of the line for /F "usebackq tokens=1,* delims= " %%A in (`sort /r aux1.txt.tmp`) DO ( echo(%%B ) ```
May be too late for you but as a general advice you can do it much simpler than creating a temporary file. Just pipe it all through sort: ``` for /f "tokens=1-3" %%a in ('(for /f "tokens=1-3" %%x in (aux1.txt^) do @echo %%z %%x %%y^)^|sort') do echo %%b %%c %%a ``` Note, that it's a single command and can be used just by typing at command prompt without any batch file at all (have to reduce %%'s for that, of course).
10,170,964
I wonder if there is any posibility to sort a text file by columns. For example I have `aux1.txt` with rows like this ``` Name SecondName Grade ``` In shell i can do this ``` sort -r -k 3 aux1 ``` It sorts the file by the 3rd column(grade). In batch ``` sort /+3 < aux1.txt ``` sorts the file after the 3rd letter. I read the sort manual for batch but no results.
2012/04/16
[ "https://Stackoverflow.com/questions/10170964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331244/" ]
You could write your own *sort-wrapper* with a batch file. You only need to reorder the columns into a temporary file, sort it and order it back. (nearly obvious) ``` REM *** Get the desired colum and place it as first column in the temporary file setlocal DisableDelayedExpansion ( for /F "tokens=1-3 delims= " %%A in (aux1.txt) DO ( set "par1=%%A" set "par2=%%B" set "par3=%%C" setlocal EnableDelayedExpansion echo(!par2! !par1! !par2! !par3! endlocal ) ) > aux1.txt.tmp REM ** Now sort the first colum, but echo only the rest of the line for /F "usebackq tokens=1,* delims= " %%A in (`sort /r aux1.txt.tmp`) DO ( echo(%%B ) ```
`SortFileBySecondColumn.bat` ``` @echo off if "%1"=="" ( echo Syntax: %0 FileToSort.txt [/R] echo /R means Sort in Reverse Order goto Ende ) set InputFile=%1 for /f "tokens=1-2* delims= " %%a in ('(for /f "tokens=1-2* delims= " %%n in (%InputFile%^) do @echo %%o %%n %%p^)^|sort %2') do echo %%b %%a %%c :Ende ``` Usage: `SortFileBySecondColumn UnsortedFile.txt > SortedFile.txt` If you exchange `delims=` by `delims=;` then you can use it for CSV files. Example Input file: ``` 172.20.17.59 PC00000781 # 14.01.2022 12:35:55 172.20.17.22 NB00001021 # 31.01.2022 14:40:38 172.20.16.114 TRANSFER14 # 11.02.2022 11:22:07 10.59.80.27 PC00001034 # 14.02.2022 15:39:23 10.59.80.140 XXBNB00173 # 16.02.2022 10:13:31 172.20.17.23 PC00000XXX # 18.02.2022 12:40:58 10.59.232.25 NB00000178 # 18.02.2022 14:38:53 ``` Resulting Output file: ``` 10.59.232.25 NB00000178 # 18.02.2022 14:38:53 172.20.17.22 NB00001021 # 31.01.2022 14:40:38 172.20.17.59 PC00000781 # 14.01.2022 12:35:55 172.20.17.23 PC00000XXX # 18.02.2022 12:40:58 10.59.80.27 PC00001034 # 14.02.2022 15:39:23 172.20.16.114 TRANSFER14 # 11.02.2022 11:22:07 10.59.80.140 XXBNB00173 # 16.02.2022 10:13:31 ```
10,170,964
I wonder if there is any posibility to sort a text file by columns. For example I have `aux1.txt` with rows like this ``` Name SecondName Grade ``` In shell i can do this ``` sort -r -k 3 aux1 ``` It sorts the file by the 3rd column(grade). In batch ``` sort /+3 < aux1.txt ``` sorts the file after the 3rd letter. I read the sort manual for batch but no results.
2012/04/16
[ "https://Stackoverflow.com/questions/10170964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331244/" ]
May be too late for you but as a general advice you can do it much simpler than creating a temporary file. Just pipe it all through sort: ``` for /f "tokens=1-3" %%a in ('(for /f "tokens=1-3" %%x in (aux1.txt^) do @echo %%z %%x %%y^)^|sort') do echo %%b %%c %%a ``` Note, that it's a single command and can be used just by typing at command prompt without any batch file at all (have to reduce %%'s for that, of course).
While I really like Jeb's answer, Ive been using Chris LaRosa's [TextDB tools](https://web.archive.org/web/20220316171736/https://geocities.restorativland.org/SiliconValley/Monitor/5986/TDBUTILS.ZIP) for years. You can sort multiple columns, pipe through another of his tools (or any other CL tool). Kind of old...
10,170,964
I wonder if there is any posibility to sort a text file by columns. For example I have `aux1.txt` with rows like this ``` Name SecondName Grade ``` In shell i can do this ``` sort -r -k 3 aux1 ``` It sorts the file by the 3rd column(grade). In batch ``` sort /+3 < aux1.txt ``` sorts the file after the 3rd letter. I read the sort manual for batch but no results.
2012/04/16
[ "https://Stackoverflow.com/questions/10170964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331244/" ]
May be too late for you but as a general advice you can do it much simpler than creating a temporary file. Just pipe it all through sort: ``` for /f "tokens=1-3" %%a in ('(for /f "tokens=1-3" %%x in (aux1.txt^) do @echo %%z %%x %%y^)^|sort') do echo %%b %%c %%a ``` Note, that it's a single command and can be used just by typing at command prompt without any batch file at all (have to reduce %%'s for that, of course).
`SortFileBySecondColumn.bat` ``` @echo off if "%1"=="" ( echo Syntax: %0 FileToSort.txt [/R] echo /R means Sort in Reverse Order goto Ende ) set InputFile=%1 for /f "tokens=1-2* delims= " %%a in ('(for /f "tokens=1-2* delims= " %%n in (%InputFile%^) do @echo %%o %%n %%p^)^|sort %2') do echo %%b %%a %%c :Ende ``` Usage: `SortFileBySecondColumn UnsortedFile.txt > SortedFile.txt` If you exchange `delims=` by `delims=;` then you can use it for CSV files. Example Input file: ``` 172.20.17.59 PC00000781 # 14.01.2022 12:35:55 172.20.17.22 NB00001021 # 31.01.2022 14:40:38 172.20.16.114 TRANSFER14 # 11.02.2022 11:22:07 10.59.80.27 PC00001034 # 14.02.2022 15:39:23 10.59.80.140 XXBNB00173 # 16.02.2022 10:13:31 172.20.17.23 PC00000XXX # 18.02.2022 12:40:58 10.59.232.25 NB00000178 # 18.02.2022 14:38:53 ``` Resulting Output file: ``` 10.59.232.25 NB00000178 # 18.02.2022 14:38:53 172.20.17.22 NB00001021 # 31.01.2022 14:40:38 172.20.17.59 PC00000781 # 14.01.2022 12:35:55 172.20.17.23 PC00000XXX # 18.02.2022 12:40:58 10.59.80.27 PC00001034 # 14.02.2022 15:39:23 172.20.16.114 TRANSFER14 # 11.02.2022 11:22:07 10.59.80.140 XXBNB00173 # 16.02.2022 10:13:31 ```
1,086,956
I was working through my Precalculus 12 book, when I came across these questions: *Is each point on the unit circle? Give evidence to support your answer* a) $(0.65, -0.76)$ b) $\left(-\frac{\sqrt{2}}{2}, -\frac{\sqrt{2}}{2}\right)$ My book says that both of these points lie on the unit circle, but I can't understand how.
2014/12/31
[ "https://math.stackexchange.com/questions/1086956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/204152/" ]
**Hint:** A point with coordinates $(a,b)$ is in the unit circle if and only if $$ a^2+b^2=1. $$ Explanation: The unit circle is by definition a circle with radius equal to $1$ and center $(0,0)$, so the distance of the points $(x,y)$ in that circle to the center is equal to $1$, hence by the distance formula : $$ \sqrt{a^2+b^2}=1\iff a^2+b^2=1. $$
we have $x^2+y^2=1$ then we plug the coordinates in this equation $$0.65^2+0.76^2=1.0001$$ and further $$\left(\frac{\sqrt{2}}{2}\right)^2+\left(\frac{\sqrt{2}}{2}\right)^2=1/2+1/2=1$$ the second point is on the unit circle
1,086,956
I was working through my Precalculus 12 book, when I came across these questions: *Is each point on the unit circle? Give evidence to support your answer* a) $(0.65, -0.76)$ b) $\left(-\frac{\sqrt{2}}{2}, -\frac{\sqrt{2}}{2}\right)$ My book says that both of these points lie on the unit circle, but I can't understand how.
2014/12/31
[ "https://math.stackexchange.com/questions/1086956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/204152/" ]
**Hint:** A point with coordinates $(a,b)$ is in the unit circle if and only if $$ a^2+b^2=1. $$ Explanation: The unit circle is by definition a circle with radius equal to $1$ and center $(0,0)$, so the distance of the points $(x,y)$ in that circle to the center is equal to $1$, hence by the distance formula : $$ \sqrt{a^2+b^2}=1\iff a^2+b^2=1. $$
If you are studying the unit circle, then b) should be a familiar cartesian coordinate, as it equivalent to the polar coordinate $\left(1,\frac{5\pi}{4}\right)$. To determine if a) is on the unit circle, you can do as others have suggested, and check the value of $$0.65^2+(-0.76)^2$$ If it equals $1$, it is on the unit circle. It does not equal $1$, which is easy to see by using a calculator. So *technically* that point is not on the unit circle, although the value is so close to $1$ that it is reasonable to assume the book rounded the decimals. I would make a note of that if I were turning this in for homework.
58,613,108
I'm trying to learn how to implement MICE in imputing missing values for my datasets. I've heard about fancyimpute's MICE, but I also read that sklearn's IterativeImputer class can accomplish similar results. From sklearn's docs: > > Our implementation of IterativeImputer was inspired by the R MICE > package (Multivariate Imputation by Chained Equations) [1], but > differs from it by returning a single imputation instead of multiple > imputations. However, IterativeImputer can also be used for multiple > imputations by applying it repeatedly to the same dataset with > different random seeds when sample\_posterior=True > > > I've seen "seeds" being used in different pipelines, but I never understood them well enough to implement them in my own code. **I was wondering if anyone could explain and provide an example on how to implement seeds for a MICE imputation using sklearn's IterativeImputer?** Thanks!
2019/10/29
[ "https://Stackoverflow.com/questions/58613108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7488114/" ]
`IterativeImputer` behavior can change depending on a random state. The random state which can be set is also called a "seed". As stated by the documentation, we can get multiple imputations when setting `sample_posterior` to `True` and changing the random seeds, i.e. the parameter `random_state`. Here is an example of how to use it: ``` import numpy as np from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer X_train = [[1, 2], [3, 6], [4, 8], [np.nan, 3], [7, np.nan]] X_test = [[np.nan, 2], [np.nan, np.nan], [np.nan, 6]] for i in range(3): imp = IterativeImputer(max_iter=10, random_state=i, sample_posterior=True) imp.fit(X_train) print(f"imputation {i}:") print(np.round(imp.transform(X_test))) ``` It outputs: ``` imputation 0: [[ 1. 2.] [ 5. 10.] [ 3. 6.]] imputation 1: [[1. 2.] [0. 1.] [3. 6.]] imputation 2: [[1. 2.] [1. 2.] [3. 6.]] ``` We can observe the three different imputations.
A way to go about stacking the data might be to change @Stanislas' code around a bit like so: ``` mvi = {} # just my preference for dict, you can use a list too # mvi collects each dataframe into a dict of dataframes using index: 0 thru 2 for i in range(3): imp = IterativeImputer(max_iter=10, random_state=i, sample_posterior=True) mvi[i] = np.round(imp.fit_transform(X_train)) ``` **combine the imputations into a single dataset using** ``` # a. pandas concat, or pd.concat(list(dfImp.values()), axis=0) #b. np stack dfs = np.stack(list(dfImp.values()), axis=0) ``` `pd.concat` creates a 2D data, on the other hand,`np.stack` creates a 3D array that you can reshape into 2D. The breakdown of the numpy 3D is as follows: * axis 0: num of iterated dataframes * axis 1: len of original df (num of rows) * axis 2: num of columns in original dataframe **create a 2D from 3D** You can use numpy reshape like so: ``` np.reshape(dfs, newshape=(dfs.shape[0]*dfs.shape[1], -1)) ``` which means you essentially multiply `axis 0` by `axis 1` to stack the dataframes into one big dataframe. The `-1` at the end just means that whatever axes is left off, use that, in this case it is the columns.
42,711,574
I try to save and read multiple objects in one XML-File. The function Serialize is not working with my existing List, but i dont know why. I already tried to compile it but i get an error wich says, that the methode needs an object refference. Program.cs: ``` class Program { static void Main(string[] args) { List<Cocktail> lstCocktails = new List<Cocktail>(); listCocktails.AddRange(new Cocktail[] { new Cocktail(1,"Test",true,true, new Cocktail(1, "Test4", true, true, 0) }); Serialize(lstCocktails); } public void Serialize(List<Cocktail> list) { XmlSerializer serializer = new XmlSerializer(typeof(List<Cocktail>)); using (TextWriter writer = new StreamWriter(@"C:\Users\user\Desktop\MapSample\bin\Debug\ListCocktail.xml")) { serializer.Serialize(writer, list); } } private void DiserializeFunc() { var myDeserializer = new XmlSerializer(typeof(List<Cocktail>)); using (var myFileStream = new FileStream(@"C:\Users\user\Desktop\MapSample\bin\Debug\ListCocktail.xml", FileMode.Open)) { ListCocktails = (List<Cocktail>)myDeserializer.Deserialize(myFileStream); } } ``` Cocktail.cs: ``` [Serializable()] [XmlRoot("locations")] public class Cocktail { [XmlElement("id")] public int CocktailID { get; set; } [XmlElement("name")] public string CocktailName { get; set; } [XmlElement("alc")] public bool alcohol { get; set; } [XmlElement("visible")] public bool is_visible { get; set; } [XmlElement("counter")] public int counter { get; set; } private XmlSerializer ser; public Cocktail() { ser = new XmlSerializer(this.GetType()); } public Cocktail(int id, string name, bool alc,bool vis,int count) { this.CocktailID = id; this.CocktailName = name; this.alcohol = alc; this.is_visible = vis; this.counter = count; } } } ``` Ii also think I messed something up with the DiserializeFunc().
2017/03/10
[ "https://Stackoverflow.com/questions/42711574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7685488/" ]
``` passenger = Passenger.where("DATE(created_at) = ?", Date.yesterday) ```
The proper solution will be is: ``` passengers = Passenger.where("DATE(created_at) = DATE(?)", Date.yesterday) ``` But if you need take only one, you can use ``` passenger = Passenger.find_by(created_at: Date.yesterday) ``` I wrote it because name of variable was not plural
55,435
I'm trying to plot a violin plot with a split based on Sex ( like in the fourth example in the [doccumentation](https://seaborn.pydata.org/generated/seaborn.violinplot.html) but with Sex) [![Example plot from the doccumentation](https://i.stack.imgur.com/46Jgl.png)](https://i.stack.imgur.com/46Jgl.png) I can produce a categorical scatter plot and split it by Sex. However, when i attempt the same but as a violin plot; it throws an error. ``` Traceback (most recent call last): File "<ipython-input-868-0599b976fd6c>", line 1, in <module> sns.catplot(x="Batch", y="Age", hue = 'Sex', data = ages, kind='violin') File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 3755, in catplot g.map_dataframe(plot_func, x, y, hue, **plot_kws) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py", line 820, in map_dataframe self._facet_plot(func, ax, args, kwargs) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py", line 838, in _facet_plot func(*plot_args, **plot_kwargs) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 2387, in violinplot color, palette, saturation) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 564, in __init__ self.estimate_densities(bw, cut, scale, scale_hue, gridsize) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 679, in estimate_densities kde, bw_used = self.fit_kde(kde_data, bw) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 719, in fit_kde kde = stats.gaussian_kde(x) File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 208, in __init__ self.set_bandwidth(bw_method=bw_method) File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 540, in set_bandwidth self._compute_covariance() File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 551, in _compute_covariance aweights=self.weights)) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/lib/function_base.py", line 2427, in cov avg, w_sum = average(X, axis=1, weights=w, returned=True) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/lib/function_base.py", line 419, in average scl = wgt.sum(axis=axis, dtype=result_dtype) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/core/_methods.py", line 36, in _sum return umr_sum(a, axis, dtype, out, keepdims, initial) TypeError: No loop matching the specified signature and casting was found for ufunc add ``` My code is: ``` >>> print(ages.head()) Age Sex Batch PassengerId 852 74 male Train 86 33 female Train 161 44 male Train 812 39 male Train 837 21 male Train >>> sns.catplot(x="Batch", y="Age", hue = 'Sex', data = ages, kind='violin') ``` Removing the kind argument produces the following scatterplot: [![Scatter plot that i can correctly produce](https://i.stack.imgur.com/F1z17.png)](https://i.stack.imgur.com/F1z17.png) How do I get rid of the error to display the data as a violin plot? Thanks in advance edit: Seaborn version: 0.9.0 Numpy version: 1.16.2 Python version: 3.7.3
2019/07/10
[ "https://datascience.stackexchange.com/questions/55435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/77162/" ]
I had tried the suggestion from @foxthatruns's answer to no avail. I found that changing my numeric column to `float64` solved the problem ([reference](https://www.reddit.com/r/learnpython/comments/7ivopz/numpy_getting_error_on_matrix_inverse/dr1w9pm/)). `df['my_column']=df['my_column'].astype('float64')` This was done with Python 3.7, seaborn 0.9.0, numpy 1.16.4.
I ran into the same error in a different context. Maybe this will help debugging? I was trying to show a vertical violin plot with a continuous vs categorical comparison. I produced the same error when I put the categorical variable in the `y` argument and also set `orient='v'`. Obviously this doesn't make sense. I fixed it by swapping the arguments. Maybe there's a hidden orientation issue? Try forcing the orientation? `seaborn.violinplot(x='Batch', y='Age', hue='Sex', data=ages, orient='v')`
67,678,503
I am using jinja template to print the key of a dictionary. here is the code: ``` from jinja2 import Template import json data = ''' hello {{Names}} Heading is {{ Names.keys() }} ''' schema = ''' { "Names" : [ "Name1", "Name2", "Name3" ] } ''' k = json.loads(schema) tm = Template(data) jdata = tm.render(Names=k) print(jdata) ``` with this it is printing template as `dict_keys`, see output below: ``` hello {'Names': ['Name1', 'Name2', 'Name3']} Heading is dict_keys(['Names']) ``` so, I think `dict_keys` is of type `set` which doesn't support indexing and also i am not able to use `list` method (as normally used in python) to convert it to list and then use indexing. I want to print it as a string, expected output: ``` hello {'Names': ['Name1', 'Name2', 'Name3']} Heading is Names # see the Names, it is string ```
2021/05/24
[ "https://Stackoverflow.com/questions/67678503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7400128/" ]
how about : ``` select * from ( select * , row_number() over (partition by month_id order by rand()) rn from my_table ) t where rn <= 1000000 order by month_id ```
According to the [Databricks TABLESAMPLE docs](https://docs.databricks.com/sql/language-manual/sql-ref-syntax-qry-select-sampling.htm): > > Always use TABLESAMPLE (percent PERCENT) if randomness is important. >TABLESAMPLE (num\_rows ROWS) is not a simple random sample but instead is >implemented using LIMIT. > > > I don't know why TABLESAMPLE and LIMIT together in your lower example caused a different result but I would use PERCENT instead of ROWS: ``` %sql with c1 as( select * from my_table TABLESAMPLE(0.2 PERCENT) ) select month_id, count(*) cnt from c1 group by month_id order by month_id ```
61,638,447
I have got a situation where the `$user_id` parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel's eloquent and query builder as well. Any help is much appreciated. ``` function get_user($user_id) { $this->db->select('u.id as user_id, u.name, u.email, u.mobile'); if($user_id != '') { $this->db->where('user_id', $user_id); } return $this->db->get('users as u')->result(); } ``` Thanks
2020/05/06
[ "https://Stackoverflow.com/questions/61638447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551438/" ]
This is because `points.append(point)` is a method and doesn't return a value, hence when you do `points = points.append(point)`, `points` takes the (lack of a) return value and becomes `None` (you overwrote the `list` type with `None` type). However, when you do `point.append(point)`, you are correctly adding elements to the list by calling its built-in method, and not overwriting anything, which is why the second code works but not the first.
With `points=points.append(point)`, you actually assign a `NoneType Object` instead of list since `points.append(point)` return `None`. So, assigning `points=points.append(point)` destroys your list.
61,638,447
I have got a situation where the `$user_id` parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel's eloquent and query builder as well. Any help is much appreciated. ``` function get_user($user_id) { $this->db->select('u.id as user_id, u.name, u.email, u.mobile'); if($user_id != '') { $this->db->where('user_id', $user_id); } return $this->db->get('users as u')->result(); } ``` Thanks
2020/05/06
[ "https://Stackoverflow.com/questions/61638447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551438/" ]
This is because `points.append(point)` is a method and doesn't return a value, hence when you do `points = points.append(point)`, `points` takes the (lack of a) return value and becomes `None` (you overwrote the `list` type with `None` type). However, when you do `point.append(point)`, you are correctly adding elements to the list by calling its built-in method, and not overwriting anything, which is why the second code works but not the first.
In your first code, after the first iteration of the loop, `points` gets assigned the return value or `.append()`, which does not return anything. If you wanted to use the assignment statement to add to a list you could do `points[len(points):len(points)] = [point]`.
61,638,447
I have got a situation where the `$user_id` parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel's eloquent and query builder as well. Any help is much appreciated. ``` function get_user($user_id) { $this->db->select('u.id as user_id, u.name, u.email, u.mobile'); if($user_id != '') { $this->db->where('user_id', $user_id); } return $this->db->get('users as u')->result(); } ``` Thanks
2020/05/06
[ "https://Stackoverflow.com/questions/61638447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551438/" ]
`append` is a method on list and doesn't return anything (so returns `None` object). Thus `points` is set to `None` after the first iteration. By the way, there's no need to iterate: ```py points = list(zip(labels, x_coord,y_coord, z_coord)) ```
With `points=points.append(point)`, you actually assign a `NoneType Object` instead of list since `points.append(point)` return `None`. So, assigning `points=points.append(point)` destroys your list.
61,638,447
I have got a situation where the `$user_id` parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel's eloquent and query builder as well. Any help is much appreciated. ``` function get_user($user_id) { $this->db->select('u.id as user_id, u.name, u.email, u.mobile'); if($user_id != '') { $this->db->where('user_id', $user_id); } return $this->db->get('users as u')->result(); } ``` Thanks
2020/05/06
[ "https://Stackoverflow.com/questions/61638447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551438/" ]
`append` is a method on list and doesn't return anything (so returns `None` object). Thus `points` is set to `None` after the first iteration. By the way, there's no need to iterate: ```py points = list(zip(labels, x_coord,y_coord, z_coord)) ```
In your first code, after the first iteration of the loop, `points` gets assigned the return value or `.append()`, which does not return anything. If you wanted to use the assignment statement to add to a list you could do `points[len(points):len(points)] = [point]`.
284,680
The following sum $$\sqrt{8+\frac2n}\cdot\left(\frac2n\right) + \sqrt{8+\frac4n}\cdot\left(\frac2n\right) + \ldots+ \sqrt{8+\frac{2n}n}\cdot\left(\frac2n\right)$$ is a right Riemann sum for the definite integral. (1) $\displaystyle\int\_6^b f(x)dx$; $f(x)=~$? It is also a Riemann sum for the definite integral. (2) $\displaystyle\int\_8^b g(x)dx$; $g(x)=~$?
2013/01/23
[ "https://math.stackexchange.com/questions/284680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/59255/" ]
Instead of just giving you the answer, for the second one, you are wanting to compare $$ \sum\_{i=1}^{n} f(8 + i\Delta x)\Delta x $$ with $$ \sum\_{i=1}^{n} \sqrt{8 + i\frac{2}{n}}\frac{2}{n}. $$ (Noting that this sum is the sum that you have in your question). * First: Can you see what $\Delta x$ should be? * Second: Can you then guess what $f$ could be? * Third: If $\Delta x = \frac{b - a}{2}$ where here $a=8$, what would $b$ be? Now try to do similarly for the first one. Hint: Here you might note that $8 = 2 + 6$.
(2) $g(x) = \sqrt{x}$, $b=10$. (1) $f(x) = \sqrt{2+x}$, $b=8$.
47,492,685
I have a dataframe with two columns as below: ``` Var1Var2 a 28 b 28 d 28 f 29 f 29 e 30 b 30 m 30 l 30 u 31 t 31 t 31 ``` I'd like to create a third column with values which increases by one for every change in value of another column. ``` Var1Var2Var3 a 28 1 b 28 1 d 28 1 f 29 2 f 29 2 e 30 3 b 30 3 m 30 3 l 30 3 u 31 4 t 31 4 t 31 4 ``` How would I go about doing this?
2017/11/26
[ "https://Stackoverflow.com/questions/47492685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389921/" ]
You can compare `Var2` with its shifted-by-1 version: ``` v Var1 Var2 a 0 28 b 1 28 d 2 28 f 3 30 f 4 30 e 5 2 b 6 2 m 7 2 l 8 2 u 9 5 t 10 5 t 11 5 i = v.Var2 v['Var3'] = i.ne(i.shift()).cumsum() v Var1 Var2 Var3 a 0 28 1 b 1 28 1 d 2 28 1 f 3 30 2 f 4 30 2 e 5 2 3 b 6 2 3 m 7 2 3 l 8 2 3 u 9 5 4 t 10 5 4 t 11 5 4 ```
Something like this: ``` (df.Var2.diff() != 0).cumsum() ```
47,492,685
I have a dataframe with two columns as below: ``` Var1Var2 a 28 b 28 d 28 f 29 f 29 e 30 b 30 m 30 l 30 u 31 t 31 t 31 ``` I'd like to create a third column with values which increases by one for every change in value of another column. ``` Var1Var2Var3 a 28 1 b 28 1 d 28 1 f 29 2 f 29 2 e 30 3 b 30 3 m 30 3 l 30 3 u 31 4 t 31 4 t 31 4 ``` How would I go about doing this?
2017/11/26
[ "https://Stackoverflow.com/questions/47492685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389921/" ]
Using `category` ``` df.Var2.astype('category').cat.codes.add(1) Out[525]: 0 1 1 1 2 1 3 2 4 2 5 3 6 3 7 3 8 3 9 4 10 4 11 4 dtype: int8 ``` Updated ``` from itertools import groupby grouped = [list(g) for k, g in groupby(df.Var2.tolist())] np.repeat(range(len(grouped)),[len(x) for x in grouped])+1 ```
Something like this: ``` (df.Var2.diff() != 0).cumsum() ```
47,492,685
I have a dataframe with two columns as below: ``` Var1Var2 a 28 b 28 d 28 f 29 f 29 e 30 b 30 m 30 l 30 u 31 t 31 t 31 ``` I'd like to create a third column with values which increases by one for every change in value of another column. ``` Var1Var2Var3 a 28 1 b 28 1 d 28 1 f 29 2 f 29 2 e 30 3 b 30 3 m 30 3 l 30 3 u 31 4 t 31 4 t 31 4 ``` How would I go about doing this?
2017/11/26
[ "https://Stackoverflow.com/questions/47492685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389921/" ]
Using `category` ``` df.Var2.astype('category').cat.codes.add(1) Out[525]: 0 1 1 1 2 1 3 2 4 2 5 3 6 3 7 3 8 3 9 4 10 4 11 4 dtype: int8 ``` Updated ``` from itertools import groupby grouped = [list(g) for k, g in groupby(df.Var2.tolist())] np.repeat(range(len(grouped)),[len(x) for x in grouped])+1 ```
You can compare `Var2` with its shifted-by-1 version: ``` v Var1 Var2 a 0 28 b 1 28 d 2 28 f 3 30 f 4 30 e 5 2 b 6 2 m 7 2 l 8 2 u 9 5 t 10 5 t 11 5 i = v.Var2 v['Var3'] = i.ne(i.shift()).cumsum() v Var1 Var2 Var3 a 0 28 1 b 1 28 1 d 2 28 1 f 3 30 2 f 4 30 2 e 5 2 3 b 6 2 3 m 7 2 3 l 8 2 3 u 9 5 4 t 10 5 4 t 11 5 4 ```
45,931,335
I'm getting an error while pushing one object into another object. But the 2nd object is an array and inside an array there is an object. How can I fix this cause I want to add that into my object My object just like this I want to add the the **Object2** into **Object1** **Objet1** ``` stdClass Object ( [id_laporan_pemeriksa] => 5 [no_pkpt] => SNE [tgl_pkpt] => 2010 [no_penugasan] => ST-4000/PW25/2/2017 [tgl_penugasan] => 2017-08-09 [judul_laporan] => Masukkan Kode disini [no_laporan] => LBINA-9000/PW25/2/2017 [tgl_laporan] => 2017-08-01 [tahun_anggaran_penugasan] => 2009 [nilai_anggaran_penugasan] => 10000000 [realisasi_anggaran_penugasan] => 100000000 [jenis_anggaran_penugasan] => Utang [sumber_laporan] => Inspektorat Maluku [nama_sumber_penugasan] => PKPT [nama_ketua_tim] => Abdul Rofiek, Ak. [nama_pengendali_teknis] => Alfian Massagony, S.E. [nama_unit_penugasan] => Irban Wil. I [nama_penugasan] => Penjaminan [nama_sub_penugasan] => Audit [id_s_sub_penugasan] => 010105 [nama_s_sub_penugasan] => Audit atas hal-hal lain di bidang kepegawaian. ) ``` **Object2** ``` stdClass Object ( [id] => 3 [data_sebab] => Array ( [0] => stdClass Object ( [id] => 4 [data_rekomendasi] => Array ( [0] => stdClass Object ( [id] => 4 [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 9 [tgl_tindak_lanjut] => 0000-00-00 ) ) ) [1] => stdClass Object ( [id] => 5 [id_rekomendasi] => [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 10 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) [1] => stdClass Object ( [id] => 11 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) ) ) ) ) ) ) ``` I have tried ``` $Object1['data']->$Object2; ``` But i got an error > > **Cannot use object of type stdClass as array** > > >
2017/08/29
[ "https://Stackoverflow.com/questions/45931335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7840345/" ]
The syntax of adding `$Object2` as a property of `$Object1` is: ``` $Object1->Object2 = $Object2; ``` Or: ``` $Object1->{'Object2'} = $Object2; ```
It should be: ``` $Object1->data = $Object2; // it will create data element with obj2 as value ```
45,931,335
I'm getting an error while pushing one object into another object. But the 2nd object is an array and inside an array there is an object. How can I fix this cause I want to add that into my object My object just like this I want to add the the **Object2** into **Object1** **Objet1** ``` stdClass Object ( [id_laporan_pemeriksa] => 5 [no_pkpt] => SNE [tgl_pkpt] => 2010 [no_penugasan] => ST-4000/PW25/2/2017 [tgl_penugasan] => 2017-08-09 [judul_laporan] => Masukkan Kode disini [no_laporan] => LBINA-9000/PW25/2/2017 [tgl_laporan] => 2017-08-01 [tahun_anggaran_penugasan] => 2009 [nilai_anggaran_penugasan] => 10000000 [realisasi_anggaran_penugasan] => 100000000 [jenis_anggaran_penugasan] => Utang [sumber_laporan] => Inspektorat Maluku [nama_sumber_penugasan] => PKPT [nama_ketua_tim] => Abdul Rofiek, Ak. [nama_pengendali_teknis] => Alfian Massagony, S.E. [nama_unit_penugasan] => Irban Wil. I [nama_penugasan] => Penjaminan [nama_sub_penugasan] => Audit [id_s_sub_penugasan] => 010105 [nama_s_sub_penugasan] => Audit atas hal-hal lain di bidang kepegawaian. ) ``` **Object2** ``` stdClass Object ( [id] => 3 [data_sebab] => Array ( [0] => stdClass Object ( [id] => 4 [data_rekomendasi] => Array ( [0] => stdClass Object ( [id] => 4 [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 9 [tgl_tindak_lanjut] => 0000-00-00 ) ) ) [1] => stdClass Object ( [id] => 5 [id_rekomendasi] => [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 10 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) [1] => stdClass Object ( [id] => 11 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) ) ) ) ) ) ) ``` I have tried ``` $Object1['data']->$Object2; ``` But i got an error > > **Cannot use object of type stdClass as array** > > >
2017/08/29
[ "https://Stackoverflow.com/questions/45931335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7840345/" ]
The syntax of adding `$Object2` as a property of `$Object1` is: ``` $Object1->Object2 = $Object2; ``` Or: ``` $Object1->{'Object2'} = $Object2; ```
As the objects are objects and not arrays, using: ``` $Object1['data']->$Object2; ``` wont work. However doing the following will work: ``` $Object1->data = $Object2; ```
45,931,335
I'm getting an error while pushing one object into another object. But the 2nd object is an array and inside an array there is an object. How can I fix this cause I want to add that into my object My object just like this I want to add the the **Object2** into **Object1** **Objet1** ``` stdClass Object ( [id_laporan_pemeriksa] => 5 [no_pkpt] => SNE [tgl_pkpt] => 2010 [no_penugasan] => ST-4000/PW25/2/2017 [tgl_penugasan] => 2017-08-09 [judul_laporan] => Masukkan Kode disini [no_laporan] => LBINA-9000/PW25/2/2017 [tgl_laporan] => 2017-08-01 [tahun_anggaran_penugasan] => 2009 [nilai_anggaran_penugasan] => 10000000 [realisasi_anggaran_penugasan] => 100000000 [jenis_anggaran_penugasan] => Utang [sumber_laporan] => Inspektorat Maluku [nama_sumber_penugasan] => PKPT [nama_ketua_tim] => Abdul Rofiek, Ak. [nama_pengendali_teknis] => Alfian Massagony, S.E. [nama_unit_penugasan] => Irban Wil. I [nama_penugasan] => Penjaminan [nama_sub_penugasan] => Audit [id_s_sub_penugasan] => 010105 [nama_s_sub_penugasan] => Audit atas hal-hal lain di bidang kepegawaian. ) ``` **Object2** ``` stdClass Object ( [id] => 3 [data_sebab] => Array ( [0] => stdClass Object ( [id] => 4 [data_rekomendasi] => Array ( [0] => stdClass Object ( [id] => 4 [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 9 [tgl_tindak_lanjut] => 0000-00-00 ) ) ) [1] => stdClass Object ( [id] => 5 [id_rekomendasi] => [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 10 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) [1] => stdClass Object ( [id] => 11 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) ) ) ) ) ) ) ``` I have tried ``` $Object1['data']->$Object2; ``` But i got an error > > **Cannot use object of type stdClass as array** > > >
2017/08/29
[ "https://Stackoverflow.com/questions/45931335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7840345/" ]
It should be: ``` $Object1->data = $Object2; // it will create data element with obj2 as value ```
As the objects are objects and not arrays, using: ``` $Object1['data']->$Object2; ``` wont work. However doing the following will work: ``` $Object1->data = $Object2; ```
28,612,173
I have a text file that was created when someone pasted from Excel into a text-only email message. There were originally five columns. ``` Column header 1 Column header 2 ... Column header 5 Row 1, column 1 Row 1, column 2 etc ``` Some of the data is single-word, some has spaces. What's the best way to get this data into column-formatted text with unix utils? Edit: I'm looking for the following output: ``` Column header 1 Column header 2 ... Column header 5 Row 1 column 1 Row 1 column 2 ... ... ``` I was able to achieve this output by manually converting the data to CSV in vim by adding a comma to the end of each line, then manually joining each set of 5 lines with J. Then I ran the csv through `column -ts,` to get the desired output. But there's got to be a better way next time this comes up.
2015/02/19
[ "https://Stackoverflow.com/questions/28612173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440257/" ]
Perhaps a perl-one-liner ain't "the best" way, but it should work: ``` perl -ne 'BEGIN{$fields_per_line=5; $field_seperator="\t"; \ $line_break="\n"} \ chomp; \ print $_, \ $. % $fields_per_row ? $field_seperator : $line_break; \ END{print $line_break}' INFILE > OUTFILE.CSV ``` Just substitute the "5", "\t" (tabspace), "\n" (newline) as needed.
You would have to use a script that uses readline and counter. When the program reaches that line you want, use cut command and space as a dilimeter to get the word you want ``` counter=0 lineNumber=3 while read line do counter += 1 if lineNumber==counter do echo $line | cut -d" " -f 4 done fi ```
238,192
Someone asked about this question on the main StackOverflow. The full question is: > > Given a value N, find `p` such that all of `[p, p + 4, p + 6, p + 10, p + 12, p + 16]` are prime. > > > * The sum of `[p, p + 4, p + 6, p + 10, p + 12, p + 16]` should be at least N. > > > My thinking is: * Sieve all primes under N * Ignore primes below `(N-48)/6` * Create consecutive slices of length 6 for the remaining primes. * Check if the slice matches the pattern. Here's my solution. I'd appreciate some feedback. ``` from itertools import dropwhile, islice def get_solutions(n): grid = [None for _ in range(n+1)] i = 2 while i < n+1: if grid[i] is None: grid[i] = True for p in range(2*i, n+1, i): grid[p] = False else: i += 1 sieve = (index for index, b in enumerate(grid) if b) min_value = (n - 48) / 6 reduced_sieve = dropwhile(lambda v: v < min_value, sieve) reference_slice = list(islice(reduced_sieve, 6)) while True: try: ref = reference_slice[0] differences = [v - ref for v in reference_slice[1:]] if differences == [4, 6, 10, 12, 16]: yield reference_slice reference_slice = reference_slice[1:] + [next(reduced_sieve)] except StopIteration: break n = 2000000 print(next(get_solutions(n))) # or for all solutions for solution in get_solutions(n): print(solution) ```
2020/03/01
[ "https://codereview.stackexchange.com/questions/238192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/217493/" ]
Overall, good first question! The first obvious improvement is to factor out the code that generates the primes ``` def prime_sieve(n): grid = [None for _ in range(n+1)] i = 2 while i < n+1: if grid[i] is None: grid[i] = True for p in range(i*i, n+1, i): grid[p] = False else: i += 1 return (index for index, b in enumerate(grid) if b) ``` Note that `for p in range(i*i, n+1, i):` starts later than the `for p in range(2*i, n+1, i):` which you used. This is safe because anything less than the current prime squared will have already been crossed out. This difference alone makes the code about 2x faster for `n = 4000000`. By separating the sieve, it makes things like profiling much easier, and you can see that most of the time this method takes is still in the sieve. Using some tricks from [Find primes using Sieve of Eratosthenes with Python](https://codereview.stackexchange.com/questions/194756/find-primes-using-sieve-of-eratosthenes-with-python), we can focus our efforts on speeding this part up. ``` def prime_sieve(n): is_prime = [False] * 2 + [True] * (n - 1) for i in range(int(n**0.5 + 1.5)): # stop at ``sqrt(limit)`` if is_prime[i]: is_prime[i*i::i] = [False] * ((n - i*i)//i + 1) return (i for i, prime in enumerate(is_prime) if prime) ``` This prime sieve works pretty similarly, but is shorter, and about 4x faster. If that isn't enough, numpy and <https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188> can come to the rescue with this beauty which is another 12x faster. ``` import numpy def prime_sieve(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool) for i in range(1,int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k//3 ::2*k] = False sieve[k*(k-2*(i&1)+4)//3::2*k] = False return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)] ``` At this point, further speedup would need to come from fancy number theory, but I'll leave that for someone else.
I agree with the tips given in the [answer](https://codereview.stackexchange.com/a/238211/98493) by [@OscarSmith](https://codereview.stackexchange.com/users/100359/oscar-smith) regarding the prime sieve. In addition, here are a few more comments on how to make the rest of your code slightly better. * You can go one step further and create a `primes_in_range` function that does the dropping for you. This might actually become a bottleneck at some point, (if a is large and a >> b - a), but at that point you only need to change the implementation of one function. * Your `reference_slice` is always the same length, but if you want to add the next element you need to resort to list slicing and list addition, both of which might create a copy. Instead, you can use [`collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque) with the optional argument `maxlen`. If you append another element, the first one will be automatically pushed out. * Similarly, you can avoid the slice in the calculation of the differences by just including the first element. You just have to add a `0` as first element in the correct differences list. Alternatively you could just define a `diff` function and adjust the correct differences to be relative to the previous elements instead of the first. * You should limit your `try` block as much as possible. This increases readability on one hand, and reduces unwanted exceptions being caught on the other (not such a big risk here, but true in general). * But even better is to not need it at all. A `for` loop consumes all elements of an iterable, which is exactly what we need here. This way we don't even need to special case the first five elements, because if the list is too short, the pattern cannot match. Alternatively, you could implement a `windowed(it, n)` function, which is what I have done below. * You should try to avoid magical values. In your code there are two. The first is the length of the pattern and the second is the pattern itself. Fortunately, the former is already given by the latter. I would make the pattern an argument of the function, which makes it also more general. At this point a less generic name might also be needed (although the name I propose below is maybe not ideal either). * You should protect the code executing your functions with a [`if __name__ == "__main__";` guard](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) to allow importing from this script without it being run. All of these changes make your function doing the actual work a lot shorter and IMO more readable. The functions I defined below are also nice things to have in you toolkit, since they are generally applicable and not only for this specific usecase. ``` from collections import deque from itertools import dropwhile, islice def prime_sieve(n): ... def primes_in_range(a, b): yield from dropwhile(lambda x: x < a, prime_sieve(b)) def diff(it): it = iter(it) previous = next(it) for x in it: yield x - previous previous = x def windowed(it, n): d = deque(islice(it, n), maxlen=n) assert len(d) == n for x in it: yield tuple(d) d.append(x) def find_primes_matching_pattern_below(diff_pattern, n): min_value = (n - 48) / 6 # A comment explaining this bound primes = primes_in_range(min_value, n) for candidate in windowed(primes, len(diff_pattern) + 1): if tuple(diff(candidate)) == diff_pattern: yield candidate if __name__ == "__main__": n = 2000000 # from (4, 6, 10, 12, 16) relative to the first element diff_pattern = (4, 2, 4, 2, 4) print(next(find_primes_matching_pattern_below(diff_pattern, n))) ``` For the given testcase, your code takes 741 ms ± 34.3 ms, while this code takes 146 ms ± 3.77 ms (using the `numpy` prime sieve from the [answer](https://codereview.stackexchange.com/a/238211/98493) by [@OscarSmith](https://codereview.stackexchange.com/users/100359/oscar-smith)) on my machine.
48,547
I've been told that there's a design rule of thumb that whenever you have a "bus" providing power and ground (for example, in an array of PWM outputs) that the ground connection is placed nearest the edge. What is the reasoning behind this? ![enter image description here](https://i.stack.imgur.com/FkxpF.png)
2012/11/09
[ "https://electronics.stackexchange.com/questions/48547", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17697/" ]
Ground ring around the periphery as a sort of EMI shield is what I was taught, but I understand that in a quarter century, the validity of that purpose may have worn off. Pure speculation alert: One possible benefit of keeping the neutral rail consistently at the outer periphery of a board is that accidental contact between two boards near the edges would not cause catastrophic short circuits. There is no reference I can quote to validate this speculation, though.
I was always taught that it is because the ground rail of a circuit normally runs around the outskirts of a board to help preventing any external noise. This is especially important in amplification circuits for obvious reasons but I suspect nowdays with surface mount and multi layer boards its probably just an old habit/rule of thumb with no real benefit.
48,547
I've been told that there's a design rule of thumb that whenever you have a "bus" providing power and ground (for example, in an array of PWM outputs) that the ground connection is placed nearest the edge. What is the reasoning behind this? ![enter image description here](https://i.stack.imgur.com/FkxpF.png)
2012/11/09
[ "https://electronics.stackexchange.com/questions/48547", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17697/" ]
Ground ring around the periphery as a sort of EMI shield is what I was taught, but I understand that in a quarter century, the validity of that purpose may have worn off. Pure speculation alert: One possible benefit of keeping the neutral rail consistently at the outer periphery of a board is that accidental contact between two boards near the edges would not cause catastrophic short circuits. There is no reference I can quote to validate this speculation, though.
A practical reason: If you had the signals *bus* at the outer edge, they can be more difficult to route. In addition, it does become a little bit of a ground *wall* at the outer edge, which is usually a good thing.
48,547
I've been told that there's a design rule of thumb that whenever you have a "bus" providing power and ground (for example, in an array of PWM outputs) that the ground connection is placed nearest the edge. What is the reasoning behind this? ![enter image description here](https://i.stack.imgur.com/FkxpF.png)
2012/11/09
[ "https://electronics.stackexchange.com/questions/48547", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17697/" ]
Ground ring around the periphery as a sort of EMI shield is what I was taught, but I understand that in a quarter century, the validity of that purpose may have worn off. Pure speculation alert: One possible benefit of keeping the neutral rail consistently at the outer periphery of a board is that accidental contact between two boards near the edges would not cause catastrophic short circuits. There is no reference I can quote to validate this speculation, though.
Lots of interesting reasons from everyone! I worked on a robotics team for a number of years and we always followed that rule largely so that a stray wire that was touching the grounded frame was slightly less likely to hit a positive lead. Essentially it was a small protection against having grounded things short out because the high-current positive rails were shielded by the ground pins. With our team it was never a hard and fast rule though. We did it when possible and convenient. The extra benefit of that "rule" is that in a three-pin system, putting the positive rail in the middle and having a current-limiting resistor on the signal line makes it more difficult to damage the system by plugging it it backwards. We actually set up one system so that it was ground-positive-ground to introduce the "can't plug it in backwards" property because it was a $400 part we were plugging in! With PWM lines it's also just a matter of practicality. That will match how commercial servos are wired hence why you normally just make it match so that you don't rewire all the servos yourself. Anyway, no idea if this also is passed down due to EMI reasons, but that was why we did it.
54,015,119
I’m writing a cache handler that needs a unique ID number for every instance of the application, so that when someone has two projects open in two instances, the caches don’t get confused. According to [this thread](http://forums.codeguru.com/showthread.php?452992-What-exactly-is-hInstance), it appears the `HINSTANCE` passed to `WinMain` is a handle to the module, which could simply be the exe, not necessarily a unique process ID. The thread seems to say that information about the module/process to be run is brought into memory only once, and the `HINSTANCE` is a handle to that. Does that mean the `HINSTANCE` can’t be used as a unique identifier for the process because they all point to the same module? Or am I mistaken?
2019/01/03
[ "https://Stackoverflow.com/questions/54015119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5456130/" ]
`HINSTANCE` is mostly obsolete, a holdover from 16-bit days. It'll have the same value for all instances of your application. For a unique process ID, use [`GetCurrentProcessId`](https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessid)
On Win32 the `HINSTANCE` corresponds to the `HMODULE` of the executable, which in turn boils down to its base address. It isn't unique to the process in any way - AFAIK a given executable will always be loaded at its requested base address. You can either use the process ID for your task, or, if the fact that process IDs are recycled is a problem, or if you prefer an unique ID across machines, just generate a new GUID at startup and use *that* as the ID.
73,275,340
I'm trying to install NET. 6.3 on my chromebook with Linux but when I try to execute ```bash ./dotnet-install.sh -c Current ``` in the Linux Terminal it always gives me this error: ```bash -bash: ./dotnet-install.sh: No such file or directory ``` Any way around it/any fix for it? I have done sudo -i so I got full permission and I have put the file I'm trying to execute in a lot of folders including my Linux folder. Any help is appreciated!
2022/08/08
[ "https://Stackoverflow.com/questions/73275340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19716022/" ]
I suppose you should: ```bash chmod +x ./dotnet-install.sh ./dotnet-install.sh -c Current ``` or ```bash /bin/bash dotnet-install.sh -c Current ```
There are two ways to execute a script on a UNIX/Linux platform: * Either you make the script executable, as explained in the other answer. * Either you use the `sh` or other relevant command for launching it, I prefer this way of working. So, I would propose you to launch the following command: ``` sh ./dotnet-install.sh -c Current ```
73,275,340
I'm trying to install NET. 6.3 on my chromebook with Linux but when I try to execute ```bash ./dotnet-install.sh -c Current ``` in the Linux Terminal it always gives me this error: ```bash -bash: ./dotnet-install.sh: No such file or directory ``` Any way around it/any fix for it? I have done sudo -i so I got full permission and I have put the file I'm trying to execute in a lot of folders including my Linux folder. Any help is appreciated!
2022/08/08
[ "https://Stackoverflow.com/questions/73275340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19716022/" ]
I suppose you should: ```bash chmod +x ./dotnet-install.sh ./dotnet-install.sh -c Current ``` or ```bash /bin/bash dotnet-install.sh -c Current ```
Have you tried the **pwd** command to see on which path are you working on? Then try to **ls | grep dotnet-install** in the current directory, if there isn't output you have to change directory. Probably you are trying to execute the **dotnet-install.sh** in a wrong directory, i suppose. Another way is to get file trough **wget** command on terminal to be sure you download the file in the correct directory. Regards
63,135,921
Working on a project, new to c# here, and I'm trying to take care of unhanded exceptions. What I'm trying to do is give the user a helpful error message whenever they type something that isn't one of the choices and keep prompting them until they enter a valid response. ``` string input = Console.ReadLine(); // bool userBool = false; // while( userBool){ // } switch (Int32.Parse(input)) { case 1: farm.AddGrazingField(new GrazingField()); Console.WriteLine("Your Facility has been added"); break; case 2: farm.AddPlowedField(new PlowedField()); Console.WriteLine("Your Facility has been added"); break; case 3: farm.AddNaturalField(new NaturalField()); Console.WriteLine("Your Facility has been added"); break; case 4: farm.AddChickenHouse(new ChickenHouse()); Console.WriteLine("Your Facility has been added"); break; case 5: farm.AddDuckHouse(new DuckHouse()); Console.WriteLine("Your Facility has been added"); break; default: break; } ``` I know I could do this with a while loop and conditionals but havent been successful doing that with switch case.
2020/07/28
[ "https://Stackoverflow.com/questions/63135921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14009868/" ]
You can use function to both read and also validate the input of the user: ``` int GetUserInput() { while (true) { Console.Write("Please enter a number: "); var input = Console.ReadLine(); if (int.TryParse(input, out var value)) return value; } } ``` This function will not throw an exception if the user enters an invalid value. Instead it will prompt the user again. You can expand this to limit the range of the input that you allow and write descriptive error messages.
Please observe the below updates in your code. ``` try { Console.WriteLine("Please enter your input in number form"); string input = Console.ReadLine(); switch (Int32.Parse(input)) { case 1: farm.AddGrazingField(new GrazingField()); Console.WriteLine("Your Facility has been added"); break; case 2: farm.AddPlowedField(new PlowedField()); Console.WriteLine("Your Facility has been added"); break; case 3: farm.AddNaturalField(new NaturalField()); Console.WriteLine("Your Facility has been added"); break; case 4: farm.AddChickenHouse(new ChickenHouse()); Console.WriteLine("Your Facility has been added"); break; case 5: farm.AddDuckHouse(new DuckHouse()); Console.WriteLine("Your Facility has been added"); break; default: throw new Exception(); } } catch (Exception ex) { //Can proovide more info to user to make sure he knows the input to be entered or options available to him Console.WriteLine("Please verify the input"); } finally { //As it will get executed in case of exception also you can log some message or perform something here } ``` This is just the beginning. You can have your custom exceptions and use them for logging messages.
3,179,439
Is it possible to detect a programming language source code (primarily Java and C# ) in a text? For example I want to know whether there is any source code part in this text. ``` .. text text text text text text text text text text text text text text text text text text text text text text text text text text text public static Person createInstance() { return new Person();} text text text text text text text text text text text text text text text text text text text text text text text text text text text .. ``` I have been searching this for a while and I couldn't find anything. A solution with Python would be wonderful. Regards.
2010/07/05
[ "https://Stackoverflow.com/questions/3179439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336583/" ]
There are some syntax highlighters around ([pygments](http://pygments.org), [google-code-prettify](http://code.google.com/p/google-code-prettify/)) and they've solved code detection and classification. Studying their sources could give an impression how it is done. (now that I looked at pygments again - I don't know if they can autodetect the programming language. But google-code-prettify definitly can do it)
You would need a database of keywords with characteristics of those keywords (definition, control structures, etc.), as well as a list of operators, special characters that would be used throughout the languages structure (eg (`}`,`*`,`||`), and a list of regex patterns. The best bet, to reduce iterations, would be to search on the keywords/operators/characters. Using a spacial/frequency formula, only start at text that *may* be a language, based on the value of the returned formula. Then it's off to identifying what language it is and where it ends. Because many languages have similar code, this might be hard. Which language is the following? ``` for(i=0;i<10;i++){ // for loop } ``` Without the comment it could be many different types of languages. With the comment, you could at least throw out Perl, since it uses `#` as the comment character, but it could still be JavaScript, C/C++, etc. Basically, you will need to do a lot of recursive lookups to identify proper code, which means that if you want something quick, you'll need a beast of a computer, or cluster of computers. Additionally, the search formula and identification formula will need to be well refined, for each language. Code identification without proper library calls or includes may be impossible, unless listing that it could belong to many languages, which you'll need a syntax library for.
103,998
The Torah says if a man seduces a woman he must pay her 50 silver shekel and should marry her ([Shemot 22,16](https://www.sefaria.org.il/Exodus.22.15?lang=bi&aliyot=0)): > > וְכִי־יְפַתֶּה אִישׁ בְּתוּלָה אֲשֶׁר לֹא־אֹרָשָׂה וְשָׁכַב עִמָּהּ מָהֹר יִמְהָרֶנָּה לּוֹ לְאִשָּׁה׃ > > > If a man seduces a virgin for whom the bride-price has not been paid, and lies with her, he must make her his wife by payment of a bride-price. > > > What if the woman seduces the man, must he pay the penalty?
2019/05/24
[ "https://judaism.stackexchange.com/questions/103998", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/17060/" ]
If the *Naara* seduces the man and her father is not alive he does not pay the penalty as she wanted it and she has forgiven the money (but if she was raped he would have to pay her) Mishne Lemelech Naaro Besula 2,14: > > ואם אין לה אב הרי הן של עצמה. פי' דוקא באונס אבל מפותה אין לה כלום שכבר מחלה > > > However when the father is alive she is in his jurisdiction so the man should have realised when she was trying to seduce him that the rights for consummation belong to her father. So regardless whether she seduced him or not, she is not in charge of her body and he has to pay for "seducing" her away from her father and **he is benefiting from the cohabitation at the expense of her father's monetary loss** as she is no longer virgin. However it is the father's right be *Mochel* forgive the monetary damages (just like all monetary obligations) as he has the potential to make her get married against her will to a person who is repulsive or with leprosy so Kesubos 40b: > > **ונתן האיש השוכב עמה לאבי הנערה חמשים כסף הנאת שכיבה חמשים** מכלל דאיכא בושת ופגם ואימא לדידה ...מסתברא דאביה הוי דאי בעי מסר לה למנוול ומוכה שחין: > > >
The Gemara in Yevamos (53b) and Sanhedrin (74b) tells us the nature of a Man when it comes to sexual relations: > > אין קישוי אלא לדעת > > > That a man cannot develop or maintain an erection without his knowledge or intent to do so. The Gemara also tells us in contrast with man, that a woman is קרקע עולם. Meaning that she is always considered as a passive actor. A man is always considered to be in the proverbial "drivers seat" when it comes to the act of Relations. Technically, a woman is always the receiver and a man the giver. This is why a man cannot be raped. For to maintain his erection implies he also intends on doing the act. Now while פיתוי - seduction - is not rape, As it is consensual in nature. Still as The Meforshim explain (Rashi, Ramban etc. מדבר על ליבה) it implies that one was needed to be convinced and pushed into the consensual act. If a man is subject to פיתוי it would would contradict the statement above of אין קישוי אלא לדעת which means that a Man is 100% fully intentional in his act without need for convincing. Furthermore, as previously mentioned, a woman is a passive player, thus by definition, she cannot be a seducer in the act, which implies an active role.
103,998
The Torah says if a man seduces a woman he must pay her 50 silver shekel and should marry her ([Shemot 22,16](https://www.sefaria.org.il/Exodus.22.15?lang=bi&aliyot=0)): > > וְכִי־יְפַתֶּה אִישׁ בְּתוּלָה אֲשֶׁר לֹא־אֹרָשָׂה וְשָׁכַב עִמָּהּ מָהֹר יִמְהָרֶנָּה לּוֹ לְאִשָּׁה׃ > > > If a man seduces a virgin for whom the bride-price has not been paid, and lies with her, he must make her his wife by payment of a bride-price. > > > What if the woman seduces the man, must he pay the penalty?
2019/05/24
[ "https://judaism.stackexchange.com/questions/103998", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/17060/" ]
The Gemara in Yevamos (53b) and Sanhedrin (74b) tells us the nature of a Man when it comes to sexual relations: > > אין קישוי אלא לדעת > > > That a man cannot develop or maintain an erection without his knowledge or intent to do so. The Gemara also tells us in contrast with man, that a woman is קרקע עולם. Meaning that she is always considered as a passive actor. A man is always considered to be in the proverbial "drivers seat" when it comes to the act of Relations. Technically, a woman is always the receiver and a man the giver. This is why a man cannot be raped. For to maintain his erection implies he also intends on doing the act. Now while פיתוי - seduction - is not rape, As it is consensual in nature. Still as The Meforshim explain (Rashi, Ramban etc. מדבר על ליבה) it implies that one was needed to be convinced and pushed into the consensual act. If a man is subject to פיתוי it would would contradict the statement above of אין קישוי אלא לדעת which means that a Man is 100% fully intentional in his act without need for convincing. Furthermore, as previously mentioned, a woman is a passive player, thus by definition, she cannot be a seducer in the act, which implies an active role.
According to Rambam's [Halachot Naarah Betulah](https://www.sefaria.org.il/Mishneh_Torah%2C_Virgin_Maiden.1.1?lang=he&with=all&lang2=he), **seduction plays no role in the case of a Mefateh**, see my long answer [here](https://judaism.stackexchange.com/a/104099/15579). A man that had sexual relations with an underage girl (given the conditions I listed) is automatically considered Mefateh (in a city or a Rapist if in rural), no matter who started, how it started. This is only when the girl wasn't a prostitute in the first place, of course (thanks @tcdw).
103,998
The Torah says if a man seduces a woman he must pay her 50 silver shekel and should marry her ([Shemot 22,16](https://www.sefaria.org.il/Exodus.22.15?lang=bi&aliyot=0)): > > וְכִי־יְפַתֶּה אִישׁ בְּתוּלָה אֲשֶׁר לֹא־אֹרָשָׂה וְשָׁכַב עִמָּהּ מָהֹר יִמְהָרֶנָּה לּוֹ לְאִשָּׁה׃ > > > If a man seduces a virgin for whom the bride-price has not been paid, and lies with her, he must make her his wife by payment of a bride-price. > > > What if the woman seduces the man, must he pay the penalty?
2019/05/24
[ "https://judaism.stackexchange.com/questions/103998", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/17060/" ]
If the *Naara* seduces the man and her father is not alive he does not pay the penalty as she wanted it and she has forgiven the money (but if she was raped he would have to pay her) Mishne Lemelech Naaro Besula 2,14: > > ואם אין לה אב הרי הן של עצמה. פי' דוקא באונס אבל מפותה אין לה כלום שכבר מחלה > > > However when the father is alive she is in his jurisdiction so the man should have realised when she was trying to seduce him that the rights for consummation belong to her father. So regardless whether she seduced him or not, she is not in charge of her body and he has to pay for "seducing" her away from her father and **he is benefiting from the cohabitation at the expense of her father's monetary loss** as she is no longer virgin. However it is the father's right be *Mochel* forgive the monetary damages (just like all monetary obligations) as he has the potential to make her get married against her will to a person who is repulsive or with leprosy so Kesubos 40b: > > **ונתן האיש השוכב עמה לאבי הנערה חמשים כסף הנאת שכיבה חמשים** מכלל דאיכא בושת ופגם ואימא לדידה ...מסתברא דאביה הוי דאי בעי מסר לה למנוול ומוכה שחין: > > >
According to Rambam's [Halachot Naarah Betulah](https://www.sefaria.org.il/Mishneh_Torah%2C_Virgin_Maiden.1.1?lang=he&with=all&lang2=he), **seduction plays no role in the case of a Mefateh**, see my long answer [here](https://judaism.stackexchange.com/a/104099/15579). A man that had sexual relations with an underage girl (given the conditions I listed) is automatically considered Mefateh (in a city or a Rapist if in rural), no matter who started, how it started. This is only when the girl wasn't a prostitute in the first place, of course (thanks @tcdw).
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I think it depends what you are doing with the string once it leaves the method. If you are going to continue appending to it then you might want to consider returning a stringbuilder for greater efficiency. If you are always going to call .ToString() on it then you should do that inside the method for better encapsulation.
If you need to append more stuff to the string and use other stringbuilder related functionality, return the stringbuilder. Otherwise if you're just using the string itself, return the string. There are other more technical considerations, but thats the highest level concerns.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I would say the method should return sb.ToString(). If the logic surrounding the creation of the StringBuilder() object should change in the future it makes sense to me that it be changed in the method not in each scenario which calls the method and then goes on to do something else
I would return a `string` in almost all situations, especially if the method is part of a public API. An exception would be if your method is just one part of a larger, private "builder" process and the calling code will be doing further manipulations. In that case then I'd maybe consider returning a `StringBuilder`.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I don't think performance should be a factor in this question. Either way someone is going to call sb.ToString() so your going to take the hit someplace. The more important question is what is the intention of the method and the purpose. If this method is part of a builder you might return the string builder. Otherwise I would return a string. If this is part of a public API I would lean towards returning a string instead of the builder.
I would return a `string` in almost all situations, especially if the method is part of a public API. An exception would be if your method is just one part of a larger, private "builder" process and the calling code will be doing further manipulations. In that case then I'd maybe consider returning a `StringBuilder`.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I would say the method should return sb.ToString(). If the logic surrounding the creation of the StringBuilder() object should change in the future it makes sense to me that it be changed in the method not in each scenario which calls the method and then goes on to do something else
The method was given a concrete task and it should be expected to complete it and return the finished result that does not require further processing. Only return StringBuilder when you really need it. In that case also add something to the method name to indicate that you are returning something special.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
`StringBuilder` is an implementation detail of your method. You should return string until it becomes a performance problem, at which point you should explore another pattern (like [visitor Pattern](http://en.wikipedia.org/wiki/Visitor_pattern)) that can help you introduce indirection and protect you from the internal implementation decisions. Strings are always stored in the heap, so you will have a reference returned if the return type is string. You can't count, however, on two identical strings to have identical references. In general, it's safe to think of a string as if it were a value type even though it is actually a reference type.
I think it depends what you are doing with the string once it leaves the method. If you are going to continue appending to it then you might want to consider returning a stringbuilder for greater efficiency. If you are always going to call .ToString() on it then you should do that inside the method for better encapsulation.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I would say the method should return sb.ToString(). If the logic surrounding the creation of the StringBuilder() object should change in the future it makes sense to me that it be changed in the method not in each scenario which calls the method and then goes on to do something else
If you need to append more stuff to the string and use other stringbuilder related functionality, return the stringbuilder. Otherwise if you're just using the string itself, return the string. There are other more technical considerations, but thats the highest level concerns.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
Return the StringBuilder if you're going to further modify the string, otherwise return the string. This is an API question. Regarding efficiency. Since this is a vague/general question without any specifics then I think mutable vs. immutable is more important than performance. Mutability is an API issue of letting your API return modifiable objects. String length is irrelevant to this. That said. If you look at StringBuilder.ToString with Reflector: ``` public override string ToString() { string stringValue = this.m_StringValue; if (this.m_currentThread != Thread.InternalGetCurrentThread()) { return string.InternalCopy(stringValue); } if ((2 * stringValue.Length) < stringValue.ArrayLength) { return string.InternalCopy(stringValue); } stringValue.ClearPostNullChar(); this.m_currentThread = IntPtr.Zero; return stringValue; } ``` You can see it may make a copy but if you modify it with the StringBuilder then it will make a copy then (this is what I can tell the point of m\_currentThread is because Append checks this and will copy it if it mismatches the current thread). I guess the end of this is that if you do not modify the StringBuilder then you do not copy the string and length is irrelevant to efficiency (unless you hit that 2nd if). **UPDATE** System.String is a class which means it is a reference type (as opposed to value type) so "string foo;" is essentially a pointer. (When you pass a string into a method it passes the pointer, not a copy.) System.String is mutable inside mscorlib but immutable outside of it which is how StringBuilder can manipulate a string. So when ToString() is called it returns its internal string object by reference. At this point you cannot modify it because your code is not in mscorlib. By setting the m\_currentThread field to zero then any further operations on the StringBuilder will cause it to copy the string object so it can be modified **and** not modify the string object it returned in ToString(). Consider this: ``` StringBuilder sb = new StringBuilder(); sb.Append("Hello "); string foo = sb.ToString(); sb.Append("World"); string bar = sb.ToString(); ``` If StringBuilder did not make a copy then at the end foo would be "Hello World" because the StringBuilder modified it. But since it did make a copy then foo is still just "Hello " and bar is "Hello World". Does that clarify the whole return/reference thing?
Since your not going to modify it anymore ``` return sb.ToString(); ``` should be most efficient
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
It depends on what you are planning on doing with the output. I would return a string personally. That way if you need to change the method down the road to not use a stringbuilder, you can as you won't be stuck with that as a return value. Upon thinking about it for the moment, the answer is much clearer. The question of asking which should be returned really answers the question. The return object should be a string. The reason is that if you are asking the question, "Is there a reason to return the StringBuilder object when a string will do?" then the answer is no. If there was a reason, then returning string would be out of the question, because the methods and properties of the stringbuilder are needed.
If you need to append more stuff to the string and use other stringbuilder related functionality, return the stringbuilder. Otherwise if you're just using the string itself, return the string. There are other more technical considerations, but thats the highest level concerns.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
It depends on what you are planning on doing with the output. I would return a string personally. That way if you need to change the method down the road to not use a stringbuilder, you can as you won't be stuck with that as a return value. Upon thinking about it for the moment, the answer is much clearer. The question of asking which should be returned really answers the question. The return object should be a string. The reason is that if you are asking the question, "Is there a reason to return the StringBuilder object when a string will do?" then the answer is no. If there was a reason, then returning string would be out of the question, because the methods and properties of the stringbuilder are needed.
The method was given a concrete task and it should be expected to complete it and return the finished result that does not require further processing. Only return StringBuilder when you really need it. In that case also add something to the method name to indicate that you are returning something special.
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
I would return a `string` in almost all situations, especially if the method is part of a public API. An exception would be if your method is just one part of a larger, private "builder" process and the calling code will be doing further manipulations. In that case then I'd maybe consider returning a `StringBuilder`.
The method was given a concrete task and it should be expected to complete it and return the finished result that does not require further processing. Only return StringBuilder when you really need it. In that case also add something to the method name to indicate that you are returning something special.
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
You can form a group for each `owner_id` and check, if all rows within group match required condition *or at least one row doesn't match it*, you can achieve it with `group by` and `having` clauses: ``` scope :heavy, -> { group("owner_id").having(["count(case when weight <= ? then weight end) = 0", 30]) } ``` There is also another option, more of a Rails-ActiverRecord approach: ``` scope :heavy, -> { where.not(owner_id: Pet.where(["weight <= ?", 30]).distinct.pluck(:owner_id)).distinct } ``` Here you get all `owner_id`s that don't fit condition (*searching by contradiction*) and exclude them from the result of original query.
You can just add a the `uniq` to your scope: ``` scope :heavy_pets, -> { uniq.joins(:pets).merge(Pet.heavy) } ``` It works on a database level, using the `distinct` query.
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
What if you do it in two steps, first you get all `owner_ids` that have at least 1 heavy pet, then get all `owner_ids` that have at least 1 not-heavy pet and then grab the owners where id exists in the first array but not in the second? Something like: ``` scope :not_heavy, -> { where('weight <= ?', 30) } ``` ... ``` owner_ids = Pet.heavy.pluck(:owner_id) - Pet.not_heavy.pluck(:owner_id) owners_with_all_pets_heavy = Owner.where(id: owner_ids) ```
You can just add a the `uniq` to your scope: ``` scope :heavy_pets, -> { uniq.joins(:pets).merge(Pet.heavy) } ``` It works on a database level, using the `distinct` query.
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
Isn't this simply a matter of finding the owners for whom the minimum pet weight is greater than some value: ``` scope :heavy, -> { group("owner_id").joins(:pets).having("min(pets.weight) >= ?", 30)} ``` Or conversely, ``` scope :light, -> { group("owner_id").joins(:pets).having("max(pets.weight) < ?", 30)} ``` These are scopes on the Owner, by the way, not the Pet Another approach is to turn this into a scope on Owner: ``` Owner.where(Pet.where.not("pets.owner_id = owners.id and pets.weight < ?", 30).exists) ``` Subtly different, as it is checking for the non-existence of a per with a weight less than 30, so if an owner has no pets then this condition will match for that owner. In database terms, this is going to be the most efficient query for large data sets. Indexing of pets(owner\_id, weight) is recommended for both these approaches.
You can just add a the `uniq` to your scope: ``` scope :heavy_pets, -> { uniq.joins(:pets).merge(Pet.heavy) } ``` It works on a database level, using the `distinct` query.
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
What if you do it in two steps, first you get all `owner_ids` that have at least 1 heavy pet, then get all `owner_ids` that have at least 1 not-heavy pet and then grab the owners where id exists in the first array but not in the second? Something like: ``` scope :not_heavy, -> { where('weight <= ?', 30) } ``` ... ``` owner_ids = Pet.heavy.pluck(:owner_id) - Pet.not_heavy.pluck(:owner_id) owners_with_all_pets_heavy = Owner.where(id: owner_ids) ```
You can form a group for each `owner_id` and check, if all rows within group match required condition *or at least one row doesn't match it*, you can achieve it with `group by` and `having` clauses: ``` scope :heavy, -> { group("owner_id").having(["count(case when weight <= ? then weight end) = 0", 30]) } ``` There is also another option, more of a Rails-ActiverRecord approach: ``` scope :heavy, -> { where.not(owner_id: Pet.where(["weight <= ?", 30]).distinct.pluck(:owner_id)).distinct } ``` Here you get all `owner_id`s that don't fit condition (*searching by contradiction*) and exclude them from the result of original query.
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
What if you do it in two steps, first you get all `owner_ids` that have at least 1 heavy pet, then get all `owner_ids` that have at least 1 not-heavy pet and then grab the owners where id exists in the first array but not in the second? Something like: ``` scope :not_heavy, -> { where('weight <= ?', 30) } ``` ... ``` owner_ids = Pet.heavy.pluck(:owner_id) - Pet.not_heavy.pluck(:owner_id) owners_with_all_pets_heavy = Owner.where(id: owner_ids) ```
Isn't this simply a matter of finding the owners for whom the minimum pet weight is greater than some value: ``` scope :heavy, -> { group("owner_id").joins(:pets).having("min(pets.weight) >= ?", 30)} ``` Or conversely, ``` scope :light, -> { group("owner_id").joins(:pets).having("max(pets.weight) < ?", 30)} ``` These are scopes on the Owner, by the way, not the Pet Another approach is to turn this into a scope on Owner: ``` Owner.where(Pet.where.not("pets.owner_id = owners.id and pets.weight < ?", 30).exists) ``` Subtly different, as it is checking for the non-existence of a per with a weight less than 30, so if an owner has no pets then this condition will match for that owner. In database terms, this is going to be the most efficient query for large data sets. Indexing of pets(owner\_id, weight) is recommended for both these approaches.
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
Instinctual familiarity ----------------------- The hemomancers have instinctual familiarity with their own blood. They know the properties of it so well that they can easily control it. Other blood can *also* be manipulated but there are so many small things that are *different* that it is difficult to generalise the experience with your own blood to others. On purely biochemical level, the blood of others could have different viscosity, different percentage of different types of cells, different amounts of other trace materials, etc. On metaphysical level, the blood is going to have intrinsically different links. Learning the more general way of manipulating any blood is very hard. Harder still when trying to apply it for other *vampires*. Knowing how to manipulate the blood of the mortal needs you to *understand* the blood and apply the correct magic force to correctly affect it. However, a *vampire* has stolen the blood of many mortals. It is a big mix. That changes after every feeding. It is much harder to properly understand that blood enough to manipulate it with magic. Vampires know how to manipulate their own blood but not in a way that they can express to others. The same way you can know how to juggle. Sure, you can do it. You can also *show* somebody how to juggle. However, but you cannot explain to them how to do it. They need to learn themselves. Only with blood manipulation, there is no easy visual shortcut that they can mimic until they actually get the tiny but important details of.
Necromancy is a [fundamental interaction](https://en.wikipedia.org/wiki/Fundamental_interaction) ================================================================================================ Therefore the farther apart two necromantic particles are from each other, the weaker the interaction between them will be. When people talk about a "life force" they are not joking. There is a fundamental particle, called animon (or pranion or whatever) that makes stuff live. The necron is its antiparticle, and carries death. The actual formula for the necromantic force is this: $$ F = N\frac{Dd}{r^2} $$ Where $F$ is the total force, $D$ and $d$ are the amount of death/decay in both interacting objects, $r$ is the distance between them, and $N$ is the emo necromantic constant, which is 1.764 × 10−11 m3dt−1s−2 (1dt = 1 death unit, about what you get from killing a muskrat). As you can see, you need an absurd amount of death to get any relevant amount of force over even a few centimeters. Skilled vampires and necromancers can exert much more death with their death muscle, which is why their necromancy can reach further than their own skin. This is also why vampires can exert influence over their ghouls and familiars over longer distances than they can influence regular people. Those ghouls and familiars have more death into them than a regular person.
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
Necromancy is a [fundamental interaction](https://en.wikipedia.org/wiki/Fundamental_interaction) ================================================================================================ Therefore the farther apart two necromantic particles are from each other, the weaker the interaction between them will be. When people talk about a "life force" they are not joking. There is a fundamental particle, called animon (or pranion or whatever) that makes stuff live. The necron is its antiparticle, and carries death. The actual formula for the necromantic force is this: $$ F = N\frac{Dd}{r^2} $$ Where $F$ is the total force, $D$ and $d$ are the amount of death/decay in both interacting objects, $r$ is the distance between them, and $N$ is the emo necromantic constant, which is 1.764 × 10−11 m3dt−1s−2 (1dt = 1 death unit, about what you get from killing a muskrat). As you can see, you need an absurd amount of death to get any relevant amount of force over even a few centimeters. Skilled vampires and necromancers can exert much more death with their death muscle, which is why their necromancy can reach further than their own skin. This is also why vampires can exert influence over their ghouls and familiars over longer distances than they can influence regular people. Those ghouls and familiars have more death into them than a regular person.
**The limitation is entirely mental** As not-living not-dead things part of a vampire's affliction affects their minds. They can't accept that they should be dead, they're addicted to the idea of life. Their blood is as disillusioned as they are. When they manipulate their own blood they *think* they're manipulating living blood. A human's living blood is also living, like theirs (so they think), so obviously they should have no issue and they don't have much. But another vampire's blood, well they become confronted with the truth of the matter. Their own undeath. Such a cognitive dissonance is terribly difficult to deal with. As they magically reach out to the other vampire's blood the idea creeps in, "you died, you're not mortal any more, your soul is forfeit, your skin is pale but you feel fine. people didn't just start liking you because you bought a new coat, it's the vampiric charm..." Some humans can fool themselves into believing impossibilities their whole life, but if you want to manipulate another vampire's blood you're going to have to face the most difficult-to-accept concept. Their own vampirism. Experienced vampires have already come to grips with this. The more experiences they get the harder the cognitive dissonance is to ignore, and every mind has its breaking point. Maybe this point of acceptance could be given its own name, like a rite of passage or a sort of transition from vampiric adolescence into adulthood.
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
Instinctual familiarity ----------------------- The hemomancers have instinctual familiarity with their own blood. They know the properties of it so well that they can easily control it. Other blood can *also* be manipulated but there are so many small things that are *different* that it is difficult to generalise the experience with your own blood to others. On purely biochemical level, the blood of others could have different viscosity, different percentage of different types of cells, different amounts of other trace materials, etc. On metaphysical level, the blood is going to have intrinsically different links. Learning the more general way of manipulating any blood is very hard. Harder still when trying to apply it for other *vampires*. Knowing how to manipulate the blood of the mortal needs you to *understand* the blood and apply the correct magic force to correctly affect it. However, a *vampire* has stolen the blood of many mortals. It is a big mix. That changes after every feeding. It is much harder to properly understand that blood enough to manipulate it with magic. Vampires know how to manipulate their own blood but not in a way that they can express to others. The same way you can know how to juggle. Sure, you can do it. You can also *show* somebody how to juggle. However, but you cannot explain to them how to do it. They need to learn themselves. Only with blood manipulation, there is no easy visual shortcut that they can mimic until they actually get the tiny but important details of.
**Vampire blood is a separate entity to the vampire itself** Call it a kind of magical slime mould or whatever, but the fact could be that the vampire's blood itself is a symbiotic creature that uses the vampire's body to survive and reproduce in exchange for allowing the vampire to be ageless or whatever other benefits your vampires might have. Controlling blood could be the creature's natural albeit magical ability, and it may even be able to control other vampire blood as well but the reason why it is so darn difficult is because the vampire's blood must overcome the agency of the other vampire's blood's will, essentially enslaving it to its will for a while. Becoming a vampire would then involve some of this 'blood' introduced to the potential vampire, leading to a relatively painful process where the blood eats the potential vampire's blood to make space for itself in the potential vampire's veins and then eats the vampire's bone marrow to allow it a space to replicate its cells(the bone marrow being where blood cells are normally made anyway for those who don't know). The blood itself eating other blood could also explain why vampires can only survive on blood. The reason why vampires burn in the sun could also be because of the 'blood', it being photo-volatile enough to even burn up under relatively dim light(moon, fires, stars) outside a body but inside a body it is fine. Lord help the 'blood' if it's ever exposed to sunlight though, it being reactive enough to burn even within the confines of a vampire's veins.
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
**Vampire blood is a separate entity to the vampire itself** Call it a kind of magical slime mould or whatever, but the fact could be that the vampire's blood itself is a symbiotic creature that uses the vampire's body to survive and reproduce in exchange for allowing the vampire to be ageless or whatever other benefits your vampires might have. Controlling blood could be the creature's natural albeit magical ability, and it may even be able to control other vampire blood as well but the reason why it is so darn difficult is because the vampire's blood must overcome the agency of the other vampire's blood's will, essentially enslaving it to its will for a while. Becoming a vampire would then involve some of this 'blood' introduced to the potential vampire, leading to a relatively painful process where the blood eats the potential vampire's blood to make space for itself in the potential vampire's veins and then eats the vampire's bone marrow to allow it a space to replicate its cells(the bone marrow being where blood cells are normally made anyway for those who don't know). The blood itself eating other blood could also explain why vampires can only survive on blood. The reason why vampires burn in the sun could also be because of the 'blood', it being photo-volatile enough to even burn up under relatively dim light(moon, fires, stars) outside a body but inside a body it is fine. Lord help the 'blood' if it's ever exposed to sunlight though, it being reactive enough to burn even within the confines of a vampire's veins.
**The limitation is entirely mental** As not-living not-dead things part of a vampire's affliction affects their minds. They can't accept that they should be dead, they're addicted to the idea of life. Their blood is as disillusioned as they are. When they manipulate their own blood they *think* they're manipulating living blood. A human's living blood is also living, like theirs (so they think), so obviously they should have no issue and they don't have much. But another vampire's blood, well they become confronted with the truth of the matter. Their own undeath. Such a cognitive dissonance is terribly difficult to deal with. As they magically reach out to the other vampire's blood the idea creeps in, "you died, you're not mortal any more, your soul is forfeit, your skin is pale but you feel fine. people didn't just start liking you because you bought a new coat, it's the vampiric charm..." Some humans can fool themselves into believing impossibilities their whole life, but if you want to manipulate another vampire's blood you're going to have to face the most difficult-to-accept concept. Their own vampirism. Experienced vampires have already come to grips with this. The more experiences they get the harder the cognitive dissonance is to ignore, and every mind has its breaking point. Maybe this point of acceptance could be given its own name, like a rite of passage or a sort of transition from vampiric adolescence into adulthood.
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
Instinctual familiarity ----------------------- The hemomancers have instinctual familiarity with their own blood. They know the properties of it so well that they can easily control it. Other blood can *also* be manipulated but there are so many small things that are *different* that it is difficult to generalise the experience with your own blood to others. On purely biochemical level, the blood of others could have different viscosity, different percentage of different types of cells, different amounts of other trace materials, etc. On metaphysical level, the blood is going to have intrinsically different links. Learning the more general way of manipulating any blood is very hard. Harder still when trying to apply it for other *vampires*. Knowing how to manipulate the blood of the mortal needs you to *understand* the blood and apply the correct magic force to correctly affect it. However, a *vampire* has stolen the blood of many mortals. It is a big mix. That changes after every feeding. It is much harder to properly understand that blood enough to manipulate it with magic. Vampires know how to manipulate their own blood but not in a way that they can express to others. The same way you can know how to juggle. Sure, you can do it. You can also *show* somebody how to juggle. However, but you cannot explain to them how to do it. They need to learn themselves. Only with blood manipulation, there is no easy visual shortcut that they can mimic until they actually get the tiny but important details of.
**The limitation is entirely mental** As not-living not-dead things part of a vampire's affliction affects their minds. They can't accept that they should be dead, they're addicted to the idea of life. Their blood is as disillusioned as they are. When they manipulate their own blood they *think* they're manipulating living blood. A human's living blood is also living, like theirs (so they think), so obviously they should have no issue and they don't have much. But another vampire's blood, well they become confronted with the truth of the matter. Their own undeath. Such a cognitive dissonance is terribly difficult to deal with. As they magically reach out to the other vampire's blood the idea creeps in, "you died, you're not mortal any more, your soul is forfeit, your skin is pale but you feel fine. people didn't just start liking you because you bought a new coat, it's the vampiric charm..." Some humans can fool themselves into believing impossibilities their whole life, but if you want to manipulate another vampire's blood you're going to have to face the most difficult-to-accept concept. Their own vampirism. Experienced vampires have already come to grips with this. The more experiences they get the harder the cognitive dissonance is to ignore, and every mind has its breaking point. Maybe this point of acceptance could be given its own name, like a rite of passage or a sort of transition from vampiric adolescence into adulthood.
2,898,059
There are 10 points in a plane and 4 of them are collinear. Find the number of triangles formed by producing the lines resulting from joining the points infinitely in both directions (assuming no two lines are parallel). I can see that there are 10C2-4C2=40 straight lines. If no two pairs of lines were concurrent we would have 40C3=9880 triangles. However, I do not know how to adjust for the concurrent lines. Any help/suggestions much appreciated.
2018/08/29
[ "https://math.stackexchange.com/questions/2898059", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49971/" ]
In the statement, "assuming no two lines are parallel" probably means that the $$\binom{10}{2}-\binom{4}{2}+1=40$$ lines are distinct and pairwise concurrent. Then the number of triangles is $\binom{40}{3}=9880$.
Actually, I think I was on the right track. The number of triangles eliminated for each of the 4 collinear points is 7C3=35 and the number of triangles eliminated from the 6 non-collinear points is 9C3=84. Hence we eliminate 4\*35+6\*84=644 triangles, resulting in 9880-644=9236 triangles formed.
69,625,065
I have found this code online but not sure what does "any" do there!? ``` def fibonacci(count): fib_list = [0, 1] any(map(lambda _: fib_list.append(sum(fib_list[-2:])), range(2, count))) return fib_list[:count] print(fibonacci(20)) ```
2021/10/19
[ "https://Stackoverflow.com/questions/69625065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188165/" ]
`Element '<shortcut>' is missing a required attribute, 'android:shortcutId'.` is showing because the minSdkVersion must be 25. That being said, if you still want your app to support OS below SDK 25, you can create a xml folder for SDK 25: `xml-v25` put your shortcuts file in it. `xml-v25/shortcuts.xml` Edit the `xml/shortcuts.xml` and remove any `<shortcut>` tag. Shortcuts will be available for SDK 25 and above, and your app can be installed for anything that match your minSDKVersion
Add a reference to shortcuts.xml in your app manifest by following these steps: 1. In your app's manifest file (AndroidManifest.xml), find an activity whose intent filters are set to the android.intent.action.MAIN action and the android.intent.category.LAUNCHER category. 2. Add a reference to shortcuts.xml in AndroidManifest.xml using a tag in the Activity that has intent filters for both MAIN and LAUNCHER, as follows: ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <application ... > <activity android:name="Main"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" /> </activity> </application> </manifest> ```
69,625,065
I have found this code online but not sure what does "any" do there!? ``` def fibonacci(count): fib_list = [0, 1] any(map(lambda _: fib_list.append(sum(fib_list[-2:])), range(2, count))) return fib_list[:count] print(fibonacci(20)) ```
2021/10/19
[ "https://Stackoverflow.com/questions/69625065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188165/" ]
`Element '<shortcut>' is missing a required attribute, 'android:shortcutId'.` is showing because the minSdkVersion must be 25. That being said, if you still want your app to support OS below SDK 25, you can create a xml folder for SDK 25: `xml-v25` put your shortcuts file in it. `xml-v25/shortcuts.xml` Edit the `xml/shortcuts.xml` and remove any `<shortcut>` tag. Shortcuts will be available for SDK 25 and above, and your app can be installed for anything that match your minSDKVersion
I solved it by doing change in android/build.gradle. 1. minsdkVersion = 30 2. taargetsdkVersion = 30
72,416,734
I want to increase the value of i every time the button is clicked I've tried this code but it's not working. ``` val textview = findViewById<TextView>(R.id.texttest) var i = 10 bookbutton.setOnClickListener { i++ } textview.text = "$i" ```
2022/05/28
[ "https://Stackoverflow.com/questions/72416734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17438980/" ]
You have to set the text inside the listener: ``` bookbutton.setOnClickListener { i++ textview.text = "$i" } ```
Your listener *is* updating the value of `i` — but that's not having any visible effect because by then it's too late: the text shown in your textview has already been set. Let's review the order of events: * Your code runs. That creates a text view and a variable, sets a listener on the button, and sets the text in the text view. * At some later point(s), the user might click on the button. That calls the listener, which updates the variable. So while your code *sets* the listener, **the listener does not run until later**. It might not run at all, or it might run many times, depending on what the user does, but it won't run before you set the text in the text view. So you need some way to update the text when you update the variable. The simplest way is to do explicitly it in the listener, e.g.: ``` bookbutton.setOnClickListener { textview.text = "${++i}" } ``` (There are other ways — for example, some UI frameworks provide ways to ‘bind’ variables to screen fields so that this sort of update happens automatically. But they tend to be a lot more complex; there's nothing wrong with the simple solution.)
57,147,178
It's easy to produces multi-level groupby result like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 Parrot Captive 30.0 Wild 20.0 ``` The code would look like `df.groupby(['animal', 'type'])['speed'].max()` However, if I want to add a total row to each subgroup, to produce something like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ``` How can I do it? The reason for adding the sub-level-row, is that it enables choosing category when I put it into BI tools for other colleagues. UPDATE: in the example above I show using `max()`, I also want to know how to do it with `user_id.nunique()`. --- Right now I produce the result by 2 groupby and then concat them. something like ``` df1 = df.groupby(['animal', 'type'])['speed'].max() df2 = df.groupby(['animal'])['speed'].max() ##### ... manually add `overall` index to df_2 df_total = pd.concat([df1, df2]).sort_index() ``` but it seems bit too manual, is there better approach?
2019/07/22
[ "https://Stackoverflow.com/questions/57147178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794744/" ]
You can do this with 2 `concat`'s, starting from your `groupby` result. --- ``` g = df.groupby(level=0).max() m = pd.concat([g], keys=['overall'], names=['Type']).swaplevel(0, 1) pd.concat([df, m], axis=0).sort_index(level=0) ``` ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ```
Adapting from [this answer](https://stackoverflow.com/a/41384950/4895877): ```py # Create data np.random.seed(2019) df = pd.DataFrame({ 'animal' : np.repeat(['Falcon', 'Parrot'], 10), 'type' : np.tile(['Captive','Wild'], 10), 'speed' : np.random.uniform(10,20,20)}) df.loc[df['animal'] == 'Falcon', 'speed'] = df['speed'] * 3 df.loc[df['type'] == 'Captive', 'speed'] = df['speed'] * .7 # Summary table table = df.pivot_table(index=['animal','type'], values='speed', aggfunc=max) # or... table = df.groupby(['animal','type'])['speed'].max().to_frame() pd.concat([d.append(d.max().rename((k, 'Total'))) for k, d in table.groupby(level=0) ]).append(table.max().rename(('Grand','Total'))) ``` gives ``` speed animal type Falcon Captive 39.973127 Wild 57.096185 Total 57.096185 Parrot Captive 10.167126 Wild 19.847235 Total 19.847235 Grand Total 57.096185 ``` If you don't want the grand total, you can remove `.append(table.max().rename(('Grand','Total')))`
57,147,178
It's easy to produces multi-level groupby result like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 Parrot Captive 30.0 Wild 20.0 ``` The code would look like `df.groupby(['animal', 'type'])['speed'].max()` However, if I want to add a total row to each subgroup, to produce something like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ``` How can I do it? The reason for adding the sub-level-row, is that it enables choosing category when I put it into BI tools for other colleagues. UPDATE: in the example above I show using `max()`, I also want to know how to do it with `user_id.nunique()`. --- Right now I produce the result by 2 groupby and then concat them. something like ``` df1 = df.groupby(['animal', 'type'])['speed'].max() df2 = df.groupby(['animal'])['speed'].max() ##### ... manually add `overall` index to df_2 df_total = pd.concat([df1, df2]).sort_index() ``` but it seems bit too manual, is there better approach?
2019/07/22
[ "https://Stackoverflow.com/questions/57147178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794744/" ]
You can do this with 2 `concat`'s, starting from your `groupby` result. --- ``` g = df.groupby(level=0).max() m = pd.concat([g], keys=['overall'], names=['Type']).swaplevel(0, 1) pd.concat([df, m], axis=0).sort_index(level=0) ``` ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ```
An efficient way is : ``` df1 = df.groupby(['animal', 'type'])['speed'].max() pd.concat([df1.reset_index(level='type'), pd.DataFrame(df1.max(level=0)).assign( type='overall')]).set_index('type',append=True).sort_index(level=0) ``` Out: ``` speed animal type Falcon Captive 19.238636 Wild 19.607617 overall 19.607617 Parrot Captive 18.386352 Wild 17.735187 overall 18.386352 ```
23,855,399
do you know how can I add a Respring button in Setting>My tweak? I know the code must added in the PreferenceBundle folder, but I don't know the code :D Example: <http://i.imgur.com/aAOiAiyl.png> Thanks in advance! P.S: I know how to use Theos (if this can be useful)
2014/05/25
[ "https://Stackoverflow.com/questions/23855399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515609/" ]
For theos just do this: 1. In the settings bundle open "resources" and then the .plist file of your tweak (maybe it will be "my tweak settings.plist" and add a button with this value: `cell: PSButtonCell label: Respring action: respring` 2. Now go back in your settings bundle and open the file called "my tweak settings.mm" and, in the @implementation part, add the method for the respiring action: ```cpp -(void)respring { [(SpringBoard *)[UIApplication sharedApplication] _relaunchSpringBoardNow]; } ``` Non you will have a PSButtonCell that will respiring your device.
I know Codyd51 has some good examples of tweaks. Look at his Github to get read up on PreferenceBundles. <https://github.com/codyd51/Theos-Examples> I know, they can be confusing! :D
23,855,399
do you know how can I add a Respring button in Setting>My tweak? I know the code must added in the PreferenceBundle folder, but I don't know the code :D Example: <http://i.imgur.com/aAOiAiyl.png> Thanks in advance! P.S: I know how to use Theos (if this can be useful)
2014/05/25
[ "https://Stackoverflow.com/questions/23855399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515609/" ]
For theos just do this: 1. In the settings bundle open "resources" and then the .plist file of your tweak (maybe it will be "my tweak settings.plist" and add a button with this value: `cell: PSButtonCell label: Respring action: respring` 2. Now go back in your settings bundle and open the file called "my tweak settings.mm" and, in the @implementation part, add the method for the respiring action: ```cpp -(void)respring { [(SpringBoard *)[UIApplication sharedApplication] _relaunchSpringBoardNow]; } ``` Non you will have a PSButtonCell that will respiring your device.
Add this in your .mm file in you preference bundle folder: ``` -(void)respring { system("killall -9 Springboard"); } ``` In your .plist (preference\_folder/resources/)add above the : ``` <dict> <key>action</key> <string>respring</string> <key>cell</key> <string>PSButtonCell</string> <key>label</key> <string>Respring your device</string> </dict> ```
16,724,395
I created a `UIView` which I want to display over my `UITableView`. I add it by adding to the current view: `[self.view addSubview:self.adBanner];` When I `scroll` the `section headers` will hover over top of this `view`. Am I adding the `view` over table correctly or should I be adding it to a different `view`?
2013/05/23
[ "https://Stackoverflow.com/questions/16724395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362413/" ]
Have you trie the following? ``` [self.view insertSubview:self.adBanner aboveSubview:yourTableview]; ```
Import quartzCore and set z-index of table view to -100 as given code below:- ``` #import <QuartzCore/QuartzCore.h> [tableView.layer setZPosition:-100]; ```
41,221,474
Hi I'm trying to play a sound on tapping of an image but it is not playing. Actually here i'm also using one media element to play a sound on this page continuously. It is playing but other which should be played on tapping of image is not playing.Any idea would be appreciated. Xaml code ``` <MediaElement x:Name="mycontrol" Source="/Audio/bg_sound.mp3" AutoPlay="True"/> <MediaElement x:Name="mediaElement1" /> ``` C# Code ``` public sealed partial class Home : Page { public Home() { this.InitializeComponent(); } private void L_color_tap(object sender, TappedRoutedEventArgs e) { mediaElement1.Source = new Uri("ms-appx:///Assets/LearnColor/Objectnamesmp3/colors.mp3"); mediaElement1.AutoPlay = true; this.Frame.Navigate(typeof(L_Col_Act)); } } ```
2016/12/19
[ "https://Stackoverflow.com/questions/41221474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7268189/" ]
First of all as you are using color list for radio buttons , its the way for Checkbox list . But if you wanna use it like this only , you can do it by adding a `ng-change` in it like - View Code- ``` <div class="form-group" > <label class="control-label">Select Colors : </label> <div ng-repeat = "color in colorlist"> <input type="radio" name="color" ng-change="changed(color)" ng- value="true" ng-model="color.idDefault"/> {{color.colorName}} </div> Colors : {{colorlist}} ``` and in controller add a method - ``` $scope.changed=function(color){ for(var i=0;i<$scope.colorlist.length;i++) if($scope.colorlist[i].colorName!==color.colorName){ $scope.colorlist[i].idDefault=false; } } ``` Check the [fiddle](https://jsfiddle.net/z7k9okvw/) hope it will work for you.
The method that you are trying to use above is used for checkboxes where you can select multiple value but here you want only one color to be selected at time. You can this as, ``` <div class="form-group" > <label class="control-label">Select Colors : </label> <div ng-repeat = "color in colorlist"> <input type="radio" name="color" ng-value="color" ng-model="selectedColor"> {{color.colorName}} </input> </div> ``` This way you can get the selected color in your contoller in `$scope.selectedColor` variable.
51,613,428
I have file with following lines: **lines.txt** ``` 1. robert smith 2. harry 3. john ``` I want to get array as follows: ``` ["robert\nsmith","harry","john"] ``` I tried something like this: ``` with open('lines.txt') as fh: m = [re.match(r"^\d+\.(.*)",line) for line in fh.readlines()] print(m) for i in m: print(i.groups()) ``` It outputs following: ``` [<_sre.SRE_Match object; span=(0, 9), match='1. robert'>, None, <_sre.SRE_Match object; span=(0, 8), match='2. harry'>, <_sre.SRE_Match object; span=(0, 7), match='3. john'>] (' robert',) Traceback (most recent call last): File "D:\workspaces\workspace6\PdfGenerator\PdfGenerator.py", line 5, in <module> print(i.groups()) AttributeError: 'NoneType' object has no attribute 'groups' ``` It seems that I am approaching this problem in very wrong way. How you will solve this?
2018/07/31
[ "https://Stackoverflow.com/questions/51613428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6357916/" ]
You may read in the file into memory and use ``` r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)' ``` See the [regex demo](https://regex101.com/r/humIzT/1) **Details** * `(?ms)` - enable `re.MULTILINE` and `re.DOTALL` modes * `^` - start of a line * `\d+` - 1+ digits * `\.` - a dot * `\s*` - 0+ whitespaces * `(.*?)` - Group 1 (this is what `re.findall` returns here): any 0+ chars, as few as possible * `(?=^\d+\.|\Z)` - up to (but not inlcuding) the first occurrence of + `^\d+\.` - start of a line, 1+ digits and `.` + `|` - or + `\Z` - end of string. Python: ``` with open('lines.txt') as fh: print(re.findall(r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)', fh.read())) ```
I propose a solution, which gathers **only** names, without unnecessary spaces in the middle of names, contrary to some other solutions. The idea is: * Save a list of tuples *(number, name\_segment)*, "copying" the group number from previous line if absent in the current line. The pair to be saved is prepared by *getPair* function. * Group these tuples on the number (first element). * Join name segments from each group, using *\n* as separator. * Save these joined names in a result list. Using list comprehensions allows to write the program in a quite concise way. See below: ``` import re, itertools def getPair(line): global grp nr, nameSegm = re.match(r'^(\d+\.)?\s+(\w+)$', line).groups() if nr: # Number present grp = nr return grp, nameSegm grp = '' # Group label (number) with open('lines.txt') as fh: lst = [getPair(line) for line in fh.readlines()] res = ['\n'.join([t[1] for t in g]) for _, g in itertools.groupby(lst, lambda x: x[0])] print(f"Result: {res}") ``` To sum up, the program is a bit longer than other, but is gives **only** names, without additional spaces.
51,613,428
I have file with following lines: **lines.txt** ``` 1. robert smith 2. harry 3. john ``` I want to get array as follows: ``` ["robert\nsmith","harry","john"] ``` I tried something like this: ``` with open('lines.txt') as fh: m = [re.match(r"^\d+\.(.*)",line) for line in fh.readlines()] print(m) for i in m: print(i.groups()) ``` It outputs following: ``` [<_sre.SRE_Match object; span=(0, 9), match='1. robert'>, None, <_sre.SRE_Match object; span=(0, 8), match='2. harry'>, <_sre.SRE_Match object; span=(0, 7), match='3. john'>] (' robert',) Traceback (most recent call last): File "D:\workspaces\workspace6\PdfGenerator\PdfGenerator.py", line 5, in <module> print(i.groups()) AttributeError: 'NoneType' object has no attribute 'groups' ``` It seems that I am approaching this problem in very wrong way. How you will solve this?
2018/07/31
[ "https://Stackoverflow.com/questions/51613428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6357916/" ]
Use `re.findall` to find all from `\d\.\s+` pattern to next '\n\d' pattern or upto end ``` >>> import re >>> re.findall(r'\d+\.\s+(.*?(?=\n\d|$))', text, flags=re.DOTALL) ['robert\n smith', 'harry', 'john'] ```
I propose a solution, which gathers **only** names, without unnecessary spaces in the middle of names, contrary to some other solutions. The idea is: * Save a list of tuples *(number, name\_segment)*, "copying" the group number from previous line if absent in the current line. The pair to be saved is prepared by *getPair* function. * Group these tuples on the number (first element). * Join name segments from each group, using *\n* as separator. * Save these joined names in a result list. Using list comprehensions allows to write the program in a quite concise way. See below: ``` import re, itertools def getPair(line): global grp nr, nameSegm = re.match(r'^(\d+\.)?\s+(\w+)$', line).groups() if nr: # Number present grp = nr return grp, nameSegm grp = '' # Group label (number) with open('lines.txt') as fh: lst = [getPair(line) for line in fh.readlines()] res = ['\n'.join([t[1] for t in g]) for _, g in itertools.groupby(lst, lambda x: x[0])] print(f"Result: {res}") ``` To sum up, the program is a bit longer than other, but is gives **only** names, without additional spaces.
51,613,428
I have file with following lines: **lines.txt** ``` 1. robert smith 2. harry 3. john ``` I want to get array as follows: ``` ["robert\nsmith","harry","john"] ``` I tried something like this: ``` with open('lines.txt') as fh: m = [re.match(r"^\d+\.(.*)",line) for line in fh.readlines()] print(m) for i in m: print(i.groups()) ``` It outputs following: ``` [<_sre.SRE_Match object; span=(0, 9), match='1. robert'>, None, <_sre.SRE_Match object; span=(0, 8), match='2. harry'>, <_sre.SRE_Match object; span=(0, 7), match='3. john'>] (' robert',) Traceback (most recent call last): File "D:\workspaces\workspace6\PdfGenerator\PdfGenerator.py", line 5, in <module> print(i.groups()) AttributeError: 'NoneType' object has no attribute 'groups' ``` It seems that I am approaching this problem in very wrong way. How you will solve this?
2018/07/31
[ "https://Stackoverflow.com/questions/51613428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6357916/" ]
You can use `re.split`. **Regex**: [`\n?\d+\.\s*`](https://regex101.com/r/ZZeVWH/2) Details: * `\n` - Newline * `?` - Matches between zero and one times, match if 'new line' exists * `\d+` - Matches a digit (+) between one and unlimited times * `\.` - Dot * `\s*` - Matches any whitespace character (equal to `[\r\n\t\f\v ]`) (\*) between zero and unlimited times **Python code**: ``` re.split(r'\n?\d+\.\s*', lines)[1:] ``` `[1:]` removes the first item because its empty string Output: ``` ['robert\n smith', 'harry', 'john'] ```
I propose a solution, which gathers **only** names, without unnecessary spaces in the middle of names, contrary to some other solutions. The idea is: * Save a list of tuples *(number, name\_segment)*, "copying" the group number from previous line if absent in the current line. The pair to be saved is prepared by *getPair* function. * Group these tuples on the number (first element). * Join name segments from each group, using *\n* as separator. * Save these joined names in a result list. Using list comprehensions allows to write the program in a quite concise way. See below: ``` import re, itertools def getPair(line): global grp nr, nameSegm = re.match(r'^(\d+\.)?\s+(\w+)$', line).groups() if nr: # Number present grp = nr return grp, nameSegm grp = '' # Group label (number) with open('lines.txt') as fh: lst = [getPair(line) for line in fh.readlines()] res = ['\n'.join([t[1] for t in g]) for _, g in itertools.groupby(lst, lambda x: x[0])] print(f"Result: {res}") ``` To sum up, the program is a bit longer than other, but is gives **only** names, without additional spaces.
47,031,464
I'm using Firebase for iOS on my app the user has to associate a photo with his profile on MySQL there is BLOB type to save images inside the database but on Firebase I don't find such a thing
2017/10/31
[ "https://Stackoverflow.com/questions/47031464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1763004/" ]
You have to use `Firebase Storage` to upload the image, and then get the URL and save the URL somewhere in your database. Here's the documentation on how to upload files: <https://firebase.google.com/docs/storage/ios/upload-files> Here's an example from one of my projects ``` FIRStorageReference *ref = [[[FIRStorage storage] reference] child:[NSString stringWithFormat:@"images/users/profilesPictures/pp%@.jpg", [UsersDatabase currentUserID]]]; [ref putData:imageData metadata:nil completion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) { if (error) { [[self viewController] hideFullscreenLoading]; [[self viewController] showError:error]; } else { [ref downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) { if (error) { [[self viewController] hideFullscreenLoading]; [[self viewController] showError:error]; } else { [[self viewController] hideFullscreenLoading]; [self.profilePictureButton setImage:nil forState:UIControlStateNormal]; [[UsersDatabase sharedInstance].currentUser setProfilePictureURL:[URL absoluteString]]; [UsersDatabase saveCurrentUser]; // This also updates the user's data in the realtime database. } }]; } }]; ```
Fortunately, this is super simple task. A Firebase user object has a photoUrl property which can be read like this ``` let user = Auth.auth().currentUser if let user = user { let uid = user.uid let email = user.email let photoURL = user.photoURL // ... } ``` The URL can be one that's external to Firebase or kept in [Firebase storage](https://firebase.google.com/docs/storage/ios/upload-files) To change the photoUrl: ``` let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() changeRequest?.displayName = //if you want to change the displayName changeRequest?.photoURL = //some Url changeRequest?.commitChanges { (error) in // ... } ```
47,031,464
I'm using Firebase for iOS on my app the user has to associate a photo with his profile on MySQL there is BLOB type to save images inside the database but on Firebase I don't find such a thing
2017/10/31
[ "https://Stackoverflow.com/questions/47031464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1763004/" ]
``` guard let uid = Auth.auth().currentUser?.uid else {return} guard let imageData = UIImageJPEGRepresentation(profilePic, 0.5) else {return} let profileImgReference = Storage.storage().reference().child("profile_image_urls").child("\(uid).png") let uploadTask = profileImgReference.putData(imageData, metadata: nil) { (metadata, error) in if let error = error { print(error.localizedDescription) } else { let downloadURL = metadata?.downloadURL()?.absoluteString ?? "" // Here you get the download url of the profile picture. } } uploadTask.observe(.progress, handler: { (snapshot) in print(snapshot.progress?.fractionCompleted ?? "") // Here you can get the progress of the upload process. }) ``` Step 1: convert your UIImage to Jpeg Data or PNG Data by using `UIImageJPEGRepresentation(UIImage, compressionQuality)` or `UIImagePNGRepresentation(UIImage)` Step 2: Create a storage reference. In the above example I have used `Storage.storage().reference()` to get the storage reference of the current Firebase app and then I am creating a folder by using `.child("FolderName")` Step 3: Use Firebase Storage's `.putData` function for upload the image data to firebase storage. You can capture the task reference (ie. uploadTask) for observing the progress of the upload. // Note: I am using the Firebase user ID as the image name because every user id is unique for firebase Auth and there is no mismatch in profile picture replacing or getting deleted accidently.
Fortunately, this is super simple task. A Firebase user object has a photoUrl property which can be read like this ``` let user = Auth.auth().currentUser if let user = user { let uid = user.uid let email = user.email let photoURL = user.photoURL // ... } ``` The URL can be one that's external to Firebase or kept in [Firebase storage](https://firebase.google.com/docs/storage/ios/upload-files) To change the photoUrl: ``` let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() changeRequest?.displayName = //if you want to change the displayName changeRequest?.photoURL = //some Url changeRequest?.commitChanges { (error) in // ... } ```
14,078,677
here is my code ``` $id = $this->user->id; $data['last_cust_code'] = $a_Search['custcode']; $data['last_paid_filter'] = $a_Search['paid']; $data['last_unpd_filter'] = $a_Search['unpaid']; $data['last_group_field'] = $a_Search['grouping']; $data['last_session_code'] = $a_Search['session']; $out = $objDb->update('tblusrusers', $data,array("id = ?"=>$id)); ``` profiler output ``` UPDATE `tblusrusers` SET `last_cust_code` = ?, `last_paid_filter` = ?, `last_unpd_filter` = ?, `last_group_field` = ?, `last_session_code` = ? WHERE (id = '70') Array ( [1] => TESTAAA [2] => N [3] => N [4] => 1 [5] => 19993E ) ``` when i update directly through mysql client its updating properly. IMPORTANT:When i select the output through a query i am able to see the update ,but not in through phpmyadmin.does it has something to do with commit statements ,i mean is my autocommit is false?for some other queries am using transactions will it effect my above update query?please help
2012/12/29
[ "https://Stackoverflow.com/questions/14078677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1300034/" ]
Actually the problem is someone in my production team just put an `$objDb->beginTransaction()` but did not commit using `$objDb->commit()` which resulted in mysql database auto commit to false(bcoz the began transaction statement set autocommit to false) therefore all the other queries where not working since commit was not happening .
I never used Zend but I think your data array should be as ``` $data = array('last_cust_code' => $a_Search['custcode'], 'last_paid_filter' => $a_Search['paid'], 'last_unpd_filter' => $a_Search['unpaid'], 'last_group_field' => $a_Search['grouping'], 'last_session_code' => $a_Search['session'] ); ```
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
The way I've solved this historically is by using precompiled headers, and doing something like this (StdAfx.h, Pch.h, PreCompiled.h or whatever): ``` //First include all headers using placement new #include <boost/tuple/tuple.hpp> #include <vector> #define new MY_NEW #define MY_NEW new(__FILE__, __LINE__) ``` And then make sure no files include the boost headers directly but only the precompiled header.
`define new DEBUG_NEW` line should be placed in a source files, after all #include lines. By this way it is applied only to your own code, and not applied to any other h-files like Boost. Global new to DEBUG\_NEW redifinition may cause compilation to fail and should be avoided.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
``` #pragma push_macro("new") #undef new new(pointer) my_class_t(arg1, arg2); #pragma pop_macro("new") ``` or ``` #pragma push_macro("new") #undef new #include <...> #include <...> #include <...> #pragma pop_macro("new") ```
The way I've solved this historically is by using precompiled headers, and doing something like this (StdAfx.h, Pch.h, PreCompiled.h or whatever): ``` //First include all headers using placement new #include <boost/tuple/tuple.hpp> #include <vector> #define new MY_NEW #define MY_NEW new(__FILE__, __LINE__) ``` And then make sure no files include the boost headers directly but only the precompiled header.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
The way I've solved this historically is by using precompiled headers, and doing something like this (StdAfx.h, Pch.h, PreCompiled.h or whatever): ``` //First include all headers using placement new #include <boost/tuple/tuple.hpp> #include <vector> #define new MY_NEW #define MY_NEW new(__FILE__, __LINE__) ``` And then make sure no files include the boost headers directly but only the precompiled header.
I know this is kind of late, but that problem can be solved by using template magic. I've been lately coding a debug\_new debugger, that adds a new keyword "placement", that gets writen infront of all placement new calls. You can check out my debugger here: <https://sourceforge.net/projects/debugnew/> Or the debug\_new debugger from nvwa here: <https://sourceforge.net/projects/nvwa/>
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
The way I've solved this historically is by using precompiled headers, and doing something like this (StdAfx.h, Pch.h, PreCompiled.h or whatever): ``` //First include all headers using placement new #include <boost/tuple/tuple.hpp> #include <vector> #define new MY_NEW #define MY_NEW new(__FILE__, __LINE__) ``` And then make sure no files include the boost headers directly but only the precompiled header.
This whole DEBUG\_NEW thing should die in fire! It was only ever barely useful and it is not useful in modern C++ at all, because you no longer see `new` in sane C++. There were better options like DUMA and now that there is [Dr. Memory](http://www.drmemory.org/) (which works similarly to [Valgrind](http://valgrind.org/), but on Windows), there is absolutely no point in using the DEBUG\_NEW abomination.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
``` #pragma push_macro("new") #undef new new(pointer) my_class_t(arg1, arg2); #pragma pop_macro("new") ``` or ``` #pragma push_macro("new") #undef new #include <...> #include <...> #include <...> #pragma pop_macro("new") ```
`define new DEBUG_NEW` line should be placed in a source files, after all #include lines. By this way it is applied only to your own code, and not applied to any other h-files like Boost. Global new to DEBUG\_NEW redifinition may cause compilation to fail and should be avoided.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
I know this is kind of late, but that problem can be solved by using template magic. I've been lately coding a debug\_new debugger, that adds a new keyword "placement", that gets writen infront of all placement new calls. You can check out my debugger here: <https://sourceforge.net/projects/debugnew/> Or the debug\_new debugger from nvwa here: <https://sourceforge.net/projects/nvwa/>
`define new DEBUG_NEW` line should be placed in a source files, after all #include lines. By this way it is applied only to your own code, and not applied to any other h-files like Boost. Global new to DEBUG\_NEW redifinition may cause compilation to fail and should be avoided.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
This whole DEBUG\_NEW thing should die in fire! It was only ever barely useful and it is not useful in modern C++ at all, because you no longer see `new` in sane C++. There were better options like DUMA and now that there is [Dr. Memory](http://www.drmemory.org/) (which works similarly to [Valgrind](http://valgrind.org/), but on Windows), there is absolutely no point in using the DEBUG\_NEW abomination.
`define new DEBUG_NEW` line should be placed in a source files, after all #include lines. By this way it is applied only to your own code, and not applied to any other h-files like Boost. Global new to DEBUG\_NEW redifinition may cause compilation to fail and should be avoided.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
``` #pragma push_macro("new") #undef new new(pointer) my_class_t(arg1, arg2); #pragma pop_macro("new") ``` or ``` #pragma push_macro("new") #undef new #include <...> #include <...> #include <...> #pragma pop_macro("new") ```
I know this is kind of late, but that problem can be solved by using template magic. I've been lately coding a debug\_new debugger, that adds a new keyword "placement", that gets writen infront of all placement new calls. You can check out my debugger here: <https://sourceforge.net/projects/debugnew/> Or the debug\_new debugger from nvwa here: <https://sourceforge.net/projects/nvwa/>
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
``` #pragma push_macro("new") #undef new new(pointer) my_class_t(arg1, arg2); #pragma pop_macro("new") ``` or ``` #pragma push_macro("new") #undef new #include <...> #include <...> #include <...> #pragma pop_macro("new") ```
This whole DEBUG\_NEW thing should die in fire! It was only ever barely useful and it is not useful in modern C++ at all, because you no longer see `new` in sane C++. There were better options like DUMA and now that there is [Dr. Memory](http://www.drmemory.org/) (which works similarly to [Valgrind](http://valgrind.org/), but on Windows), there is absolutely no point in using the DEBUG\_NEW abomination.
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
This whole DEBUG\_NEW thing should die in fire! It was only ever barely useful and it is not useful in modern C++ at all, because you no longer see `new` in sane C++. There were better options like DUMA and now that there is [Dr. Memory](http://www.drmemory.org/) (which works similarly to [Valgrind](http://valgrind.org/), but on Windows), there is absolutely no point in using the DEBUG\_NEW abomination.
I know this is kind of late, but that problem can be solved by using template magic. I've been lately coding a debug\_new debugger, that adds a new keyword "placement", that gets writen infront of all placement new calls. You can check out my debugger here: <https://sourceforge.net/projects/debugnew/> Or the debug\_new debugger from nvwa here: <https://sourceforge.net/projects/nvwa/>
61,241
There is a rule that if you are eating multiple items that are in the same blessing category (e.g. shehakol) then you only say one blessing and have in mind the other items. Does this inclusion have an expiration? For example you are having ice cream and have in mind to have tea right after when you recite the shehakol blessing how much time after the ice cream can you have the tea without an additional blessing? On a relates note, does the tea need to be already prepared (i.e. not in front of you) at the time of the blessing or can you make it after finishing the ice cream?
2015/07/15
[ "https://judaism.stackexchange.com/questions/61241", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/3006/" ]
This is one of the many self-flagellative practices of the [Hassidei Ashkenaz](https://en.wikipedia.org/wiki/Ashkenazi_Hasidim). The [Rokeah](https://en.wikipedia.org/wiki/Eleazar_of_Worms), for example, writes (Hilkhot Teshuva: 11) that sitting in ice or snow is an appropriate form of penance for sexual relations with a married woman: > > הבא על אשת איש שהוא במיתה יסבול צער קשה כמיתה ישב בקרח או בשלג בכל יום שעה אחת בכל יום פעם אחת או פעמיים > > > It doesnt seem that one needs to do that act of self-affliction in particular; it is just a way of causing great suffering to oneself, "similar to death". Accordingly, in the summer, he suggests (there) other forms of self-flagellation, such as sitting among bees or other insects. He further generally recommends all types of self-flagellation and suffering. This is similar to the writings of his mentor [R. Yehuda HaHassid](https://en.wikipedia.org/wiki/Judah_ben_Samuel_of_Regensburg) who in Sefer Hassidim (ed. Margolis: 176) suggests torturing oneself by sitting in ice. (Although perhaps this refers to sitting in a frozen river (cf. 177) in which the pain comes from the cold water, rather than the ice.) He similarly approvingly cites a story (528) about a pious person sitting with his feet in freezing water until his feet became frozen together. Here too it doesn't sound like there is significance to torturing yourself with ice in particular; winter just affords someone with great snow and ice torture opportunities. During the summer other forms of self-affliction are possible (cf. 167). Importantly, however, the Sefer Hassidim adds (there; in parenthesis in ed. Margolis) that water is particularly appropriate for use in afflicting oneself, as there is a Midrash that Adam afflicted himself for 130 years with water as a form of penance for eating from the *ets hadaat*. (Perhaps this would apply to snow or ice as well): > > ולמה במים אמרו במדרש ק"ל שנים היה אדם הראשון יושב במים עד חוטמו להתכפר על שחטא בעץ הדעת שנגזר גזירה על כל הדורות > > >
A partial answer re. the second half of the question\*: The purpose of this form of bodily mortification is to sustain commensurate repentance (a concept developed by the early pietists known as "teshuvat ha-mishkal", wherein the offender inflicts pain commensurate to the punishment biblically prescribed for a given sin). In a responsum re. a person who committed homosexual activity, [R. Yosef Hayyim](https://en.wikipedia.org/wiki/Yosef_Hayyim) of Baghdad ([Rav Pe'alim 2:44](http://www.hebrewbooks.org/pdfpager.aspx?req=1401&st=&pgnum=143), s.v. 'ועל שאלה הג) prescribes, according to Lurianic tradition, rolling in snow. He adds that if snow cannot be obtained, immersion in freezing waters is sufficient. Again, because the original aim is accomplished. \*Re. the first half; @mevaqesh's source is indeed, AFAIK, either the earliest or of the earliest discussing the practice. My only reservation is based on recollection of J. Elbaum in his book 'תשובת הלב וקבלת יסורים' where IIRC he published a manuscript of Rokeach's predecessor, [R. Judah Ha-Hassid](https://en.wikipedia.org/wiki/Judah_ben_Samuel_of_Regensburg) who likewise made mention of rolling in snow (including smearing one's self with honey and sitting among bees, even to the extent of suicide in atonement for personal sins).
189,153
I have a program which generates some html documentation. At the end of the script, I use the `open` command to automatically view the page in the browser. ``` generate-document > index.html open index.html ``` However, after iterating on the code, I end up with numerous obsolete copies of `index.html` open in my browser. Is there a way (either from the command line, or within the browser) to say something like "if index.html is already being viewed refresh it, otherwise load it."? ``` generate-document > index.html open-or-reload index.html ``` Safari or Chrome specific methods are fine.
2015/05/28
[ "https://apple.stackexchange.com/questions/189153", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/25478/" ]
The following command line can be added to your script and it will refresh the Tab that has focus in the frontmost Safari window, (even if the frontmost window only has a single page loaded): ``` osascript -e \ 'tell application "Safari" to set URL of current tab of front window to "file:///foo.html"' ```
Check out [LiveReload](http://livereload.com). It is an app that watches your HTML files and can automatically for reload the pages in your browser. LiveReload can also do other things like automatically recompile SASS files to CSS and then reload the browser. In addition to the app at the link above, LiveReload is available on GitHub under a "Open Community Indie Software License" which is not quite open source, but does include a dead man clause to convert to MIT if no new binary updates come out for two years. <https://github.com/livereload/LiveReload>
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
You can try this! ``` getResources().getStringArray(R.id.dog_breeds)[selectedIndex]; ``` -and you can get your desired solution -Please let me know if it was helpful or not or you can also correct me if i am wrong.!
I suggest you to change your xml file a bit like : use seperate `array` for different breed info : ``` <array name="Type_of_dog"> <item>black_russian_terrier</item> <item>boxer</item> <item>3rd type</item> <item>4th type</item> </array> <array name="characteristic_1"> <item>Working Dogs</item> <item>Working Dogs</item> <item>...</item> <item>...</item> </array> <array name="characteristic_2"> <item>2\'2" - 2\'6"</item> <item>1\'9" - 2\'1"</item> <item>...</item> <item>...</item> </array> <array name="characteristic_3"> <item>80 - 140 lbs</item> <item>60 - 70 lbs</item> <item>...</item> <item>...</item> </array> <array name="characteristic_4"> <item>10 - 11 years</item> <item>10 - 12 years</item> <item>...</item> <item>...</item> </array> ``` From Java file, access them : ``` public void getBreedInfo(int index){ Resources resources = getResources(); TypedArray type = resources.obtainTypedArray(R.array.Type_of_dog); TypedArray char1 = resources.obtainTypedArray(R.array.characteristic_1); TypedArray char2 = resources.obtainTypedArray(R.array.characteristic_2); TypedArray char3 = resources.obtainTypedArray(R.array.characteristic_3); TypedArray char4 = resources.obtainTypedArray(R.array.characteristic_4); if(type.equals("black_russian_terrier")) { // do it something for type 1 } else if(type.equals("boxer") { // do it something for type 2 } type.recycle(); char1.recycle(); char2.recycle(); char3.recycle(); char4.recycle(); } ``` Reference answer : [this](https://stackoverflow.com/a/6774856/1994950) Hope you will get your code working
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
You can try this! ``` getResources().getStringArray(R.id.dog_breeds)[selectedIndex]; ``` -and you can get your desired solution -Please let me know if it was helpful or not or you can also correct me if i am wrong.!
**You can extract your needs from my detailed answer..** ``` CharSequence[] infos; TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs, R.styleable.PostableEditText, 0, 0); try { infos = a.getTextArray(R.styleable.PostableEditText_infos); } finally { a.recycle(); } ``` **attrs.xml** ``` <declare-styleable name="PostableEditText"> <attr name="infos" format="reference" /> </declare-styleable> ``` **your custom\_layout.xml** ``` <com.my.app.views.custom.edittext.PostableEditText android:id="@+id/orderProduct" android:layout_width="match_parent" android:layout_height="55dp" app:infos="@array/orderProductInfos" /> ``` **ids.xml** ``` <array name="orderProductInfos"> <item>@string/Price</item> <item>@string/Name</item> <item>@string/Id</item> </array> ``` **strings.xml** ``` <!-- Order Product Infos --> <string name="Price">Price</string> <string name="Name">Name</string> <string name="Id">Id</string> ```
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
You can try this! ``` getResources().getStringArray(R.id.dog_breeds)[selectedIndex]; ``` -and you can get your desired solution -Please let me know if it was helpful or not or you can also correct me if i am wrong.!
try this for getting string array from string.xml ``` String[] hList = getResources().getStringArray(R.array.price_array); ```
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
I suggest you to change your xml file a bit like : use seperate `array` for different breed info : ``` <array name="Type_of_dog"> <item>black_russian_terrier</item> <item>boxer</item> <item>3rd type</item> <item>4th type</item> </array> <array name="characteristic_1"> <item>Working Dogs</item> <item>Working Dogs</item> <item>...</item> <item>...</item> </array> <array name="characteristic_2"> <item>2\'2" - 2\'6"</item> <item>1\'9" - 2\'1"</item> <item>...</item> <item>...</item> </array> <array name="characteristic_3"> <item>80 - 140 lbs</item> <item>60 - 70 lbs</item> <item>...</item> <item>...</item> </array> <array name="characteristic_4"> <item>10 - 11 years</item> <item>10 - 12 years</item> <item>...</item> <item>...</item> </array> ``` From Java file, access them : ``` public void getBreedInfo(int index){ Resources resources = getResources(); TypedArray type = resources.obtainTypedArray(R.array.Type_of_dog); TypedArray char1 = resources.obtainTypedArray(R.array.characteristic_1); TypedArray char2 = resources.obtainTypedArray(R.array.characteristic_2); TypedArray char3 = resources.obtainTypedArray(R.array.characteristic_3); TypedArray char4 = resources.obtainTypedArray(R.array.characteristic_4); if(type.equals("black_russian_terrier")) { // do it something for type 1 } else if(type.equals("boxer") { // do it something for type 2 } type.recycle(); char1.recycle(); char2.recycle(); char3.recycle(); char4.recycle(); } ``` Reference answer : [this](https://stackoverflow.com/a/6774856/1994950) Hope you will get your code working
**You can extract your needs from my detailed answer..** ``` CharSequence[] infos; TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs, R.styleable.PostableEditText, 0, 0); try { infos = a.getTextArray(R.styleable.PostableEditText_infos); } finally { a.recycle(); } ``` **attrs.xml** ``` <declare-styleable name="PostableEditText"> <attr name="infos" format="reference" /> </declare-styleable> ``` **your custom\_layout.xml** ``` <com.my.app.views.custom.edittext.PostableEditText android:id="@+id/orderProduct" android:layout_width="match_parent" android:layout_height="55dp" app:infos="@array/orderProductInfos" /> ``` **ids.xml** ``` <array name="orderProductInfos"> <item>@string/Price</item> <item>@string/Name</item> <item>@string/Id</item> </array> ``` **strings.xml** ``` <!-- Order Product Infos --> <string name="Price">Price</string> <string name="Name">Name</string> <string name="Id">Id</string> ```
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
try this for getting string array from string.xml ``` String[] hList = getResources().getStringArray(R.array.price_array); ```
**You can extract your needs from my detailed answer..** ``` CharSequence[] infos; TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs, R.styleable.PostableEditText, 0, 0); try { infos = a.getTextArray(R.styleable.PostableEditText_infos); } finally { a.recycle(); } ``` **attrs.xml** ``` <declare-styleable name="PostableEditText"> <attr name="infos" format="reference" /> </declare-styleable> ``` **your custom\_layout.xml** ``` <com.my.app.views.custom.edittext.PostableEditText android:id="@+id/orderProduct" android:layout_width="match_parent" android:layout_height="55dp" app:infos="@array/orderProductInfos" /> ``` **ids.xml** ``` <array name="orderProductInfos"> <item>@string/Price</item> <item>@string/Name</item> <item>@string/Id</item> </array> ``` **strings.xml** ``` <!-- Order Product Infos --> <string name="Price">Price</string> <string name="Name">Name</string> <string name="Id">Id</string> ```
18,848,090
I have a text file from where i read values ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); String var_1 = tokens[0]; System.out.println(var_1); getstaffinfo(var_1,connection); } ``` The values read from text file is passed to getstaffinfo method to query the db ``` public static String getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid = '"+var_1+"'"); rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } return record; } ``` I get almost 14000 values read from text file which is passed to getstaffinfo method, all database activities such has loading driver, establishing connectivity all works fine. But while printing it throws error ``` java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01000: maximum open cursors exceeded ORA-01000: maximum open cursors exceeded ``` Although i understand that this error is to do with database configuration, Is there an efficent way of making one db call and exceute the query for multiple values read from text file. Any inputs would be of great use. Many Thanks in advance!!
2013/09/17
[ "https://Stackoverflow.com/questions/18848090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744539/" ]
Close ResultSet `rs.close();` and Statement `stmt.close();` after your while loop in `getstaffinfo()`, preferably inside a `finally{}`
You need to close resultSet via `rs.close();` and Statement via `stmt.close();` ``` while(rs.next()){ record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } rs.close(); stmt.close(); ```
18,848,090
I have a text file from where i read values ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); String var_1 = tokens[0]; System.out.println(var_1); getstaffinfo(var_1,connection); } ``` The values read from text file is passed to getstaffinfo method to query the db ``` public static String getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid = '"+var_1+"'"); rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } return record; } ``` I get almost 14000 values read from text file which is passed to getstaffinfo method, all database activities such has loading driver, establishing connectivity all works fine. But while printing it throws error ``` java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01000: maximum open cursors exceeded ORA-01000: maximum open cursors exceeded ``` Although i understand that this error is to do with database configuration, Is there an efficent way of making one db call and exceute the query for multiple values read from text file. Any inputs would be of great use. Many Thanks in advance!!
2013/09/17
[ "https://Stackoverflow.com/questions/18848090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744539/" ]
Close ResultSet `rs.close();` and Statement `stmt.close();` after your while loop in `getstaffinfo()`, preferably inside a `finally{}`
The issue is you are not `close`ing `ResultSet` and `Statement` (though it is good that your are working on one `Connection`), try closing resources, the error should not happen. Bigger issue is that if you do close, you are hitting DB `n` number of times where `n` is number of filtering criteria. One solution to this could be make `in` clause instead of `=` selection. e.g: Say total lines = N, divide into x chunks hence make N/x `select` statements For example is N=20000, x=1000; you need to fire 20 `selects` instead of 20000.
18,848,090
I have a text file from where i read values ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); String var_1 = tokens[0]; System.out.println(var_1); getstaffinfo(var_1,connection); } ``` The values read from text file is passed to getstaffinfo method to query the db ``` public static String getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid = '"+var_1+"'"); rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } return record; } ``` I get almost 14000 values read from text file which is passed to getstaffinfo method, all database activities such has loading driver, establishing connectivity all works fine. But while printing it throws error ``` java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01000: maximum open cursors exceeded ORA-01000: maximum open cursors exceeded ``` Although i understand that this error is to do with database configuration, Is there an efficent way of making one db call and exceute the query for multiple values read from text file. Any inputs would be of great use. Many Thanks in advance!!
2013/09/17
[ "https://Stackoverflow.com/questions/18848090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744539/" ]
Close ResultSet `rs.close();` and Statement `stmt.close();` after your while loop in `getstaffinfo()`, preferably inside a `finally{}`
close resultset and statement like this way ``` rs.close(); stmt.close(); ```
18,848,090
I have a text file from where i read values ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); String var_1 = tokens[0]; System.out.println(var_1); getstaffinfo(var_1,connection); } ``` The values read from text file is passed to getstaffinfo method to query the db ``` public static String getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid = '"+var_1+"'"); rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } return record; } ``` I get almost 14000 values read from text file which is passed to getstaffinfo method, all database activities such has loading driver, establishing connectivity all works fine. But while printing it throws error ``` java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01000: maximum open cursors exceeded ORA-01000: maximum open cursors exceeded ``` Although i understand that this error is to do with database configuration, Is there an efficent way of making one db call and exceute the query for multiple values read from text file. Any inputs would be of great use. Many Thanks in advance!!
2013/09/17
[ "https://Stackoverflow.com/questions/18848090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744539/" ]
Close ResultSet `rs.close();` and Statement `stmt.close();` after your while loop in `getstaffinfo()`, preferably inside a `finally{}`
Best way is to use `IN` clause in the query and call the method only once. ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; String var_1 = ""; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); var_1 = var_1+tokens[0]+","; System.out.println(var_1); } var_1 = var_1.subString(0,var_1.lastIndexOf(",")); getstaffinfo(var_1,connection); ``` change `getstaffinfo()` like this ``` public static List<String> getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; List<String> list = new ArrayList<String>(); Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid IN ("+var_1+")"); try{ rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " +rs.getString(2) + " " +rs.getString(3); System.out.println(record); list.add(record); } }finally{ stmt.close(); rs.close(); } return list; } ``` Note : Cant we put more than 1000 values in 'in clause'. Related links. 1.<https://forums.oracle.com/thread/235143?start=0&tstart=0> 2.[java.sql.SQLException: - ORA-01000: maximum open cursors exceeded](https://stackoverflow.com/questions/12192592/java-sql-sqlexception-ora-01000-maximum-open-cursors-exceeded)
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
If you have a multilib GCC installed, it's as simple as adding `-m64` to the commandline. The compiler should complain if it is not built with multilib support. In order to link, you'll need all the 64-bit counterparts of the standard libraries. If your distro has a multilib GCC, these should also be in the repositories.
You will need a gcc that will compile on 64 bits machines, eg `x86_64-linux-gcc`. Check your distribution package manager.
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
Go into Synaptic and search for gcc-multilib or g++-multilib and install the package, if the `-m64` option does not work. Then, compile with the `-m64` option.
You will need a gcc that will compile on 64 bits machines, eg `x86_64-linux-gcc`. Check your distribution package manager.
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
If you have a multilib GCC installed, it's as simple as adding `-m64` to the commandline. The compiler should complain if it is not built with multilib support. In order to link, you'll need all the 64-bit counterparts of the standard libraries. If your distro has a multilib GCC, these should also be in the repositories.
Go into Synaptic and search for gcc-multilib or g++-multilib and install the package, if the `-m64` option does not work. Then, compile with the `-m64` option.
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
If you have a multilib GCC installed, it's as simple as adding `-m64` to the commandline. The compiler should complain if it is not built with multilib support. In order to link, you'll need all the 64-bit counterparts of the standard libraries. If your distro has a multilib GCC, these should also be in the repositories.
I think you could install `gcc-multilib` pachage first. And then compile your code using `gcc -m64 yourcode`, you cound check the ELF file using `file yourprogram`, the output should be like this `yourprogram: ELF 64-bit LSB executable,.......`
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
Go into Synaptic and search for gcc-multilib or g++-multilib and install the package, if the `-m64` option does not work. Then, compile with the `-m64` option.
I think you could install `gcc-multilib` pachage first. And then compile your code using `gcc -m64 yourcode`, you cound check the ELF file using `file yourprogram`, the output should be like this `yourprogram: ELF 64-bit LSB executable,.......`
22,204
I've had these pepper plants for a year and a half now. They weren't 100% healthy when I bought them. The actual plan was to pick the fruits and then bin the plants, but I felt bad doing that! They had gotten lots of bugs on my balcony, so I applied soapy water and alcohol and rinsed and replanted them. They have been doing great, giving me good fruits, but I could never get rid of the curly leaves. (Here is my [previous question](https://gardening.stackexchange.com/questions/14623/home-made-solution-for-white-spotted-curley-leaves-on-pepper-leaves) regarding this.) A while back I went away for a month, (I attempted to give them a self-watering system), and came back to see lots of leaves that looked burnt/dried. I trimmed them, and they had started doing okay again, but now there are loads and loads of annoying brown bugs. I've applied an alcohol/soapy water spray over and over, but it hasn't helped. The last time was around 10 days ago when I was going to leave for a week, and I decided that I'd bin them forever if the bugs weren't gone when I got back. Not only are they still there, but there are many more of them, and they're killing all the blooms and baby fruits. Is it worth attempting to fix them or should I just bin the whole thing? [![enter image description here](https://i.stack.imgur.com/eqrGJ.jpg)](https://i.stack.imgur.com/eqrGJ.jpg) [![enter image description here](https://i.stack.imgur.com/a5UKa.jpg)](https://i.stack.imgur.com/a5UKa.jpg) [![enter image description here](https://i.stack.imgur.com/IcYMI.jpg)](https://i.stack.imgur.com/IcYMI.jpg) P.S. They're next to my tomato boxes, all sitting inside a south-facing window shelf. I confess that some of the tomatoes are also mildly infected, but since the tomatoes won't last long, I'm not too worried. I have a bonsai ficus, and some African violets, on the other end of the house, at the north-facing windows, and I'm paranoid that they've got the curly leaves from these peppers as well. (It's not just paranoia, as I think I can see that the leaves are curled!) I've also gotten a cactus recently, and I hope that one survives!
2015/10/23
[ "https://gardening.stackexchange.com/questions/22204", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/6990/" ]
To be frank, I'd bin them without a second's hesitation, and would have done so a while back, and that's what I recommend to you. They're serving no useful purpose other than as a source of infection to your other plants, but it may be too late, the aphid infestation may already have spread to those too - use neem spray to treat them with. Curled leaves on African violets often indicates cyclamen mite, but I'm not at all sure that's a problem where you live. Inspect the backs of the leaves and every part of the plant to see what you can find.
Bamboo is probably right, by the look of it. However, if you really want to *try* to save the plants, and don't care about the risk of infection to other plants, I have some thoughts for you. 1. Manually remove all the visible pests (every day). You don't need pesticides for those. 2. Give your peppers a *lot* of light. The more sunlight your peppers have, the less pests should be interested in them. In my experience, shaded plants attract pests really, really easily compared to plants in full sun. The opposite seems to be true for pollinators. The sunlight will encourage growth, too, and strengthen/feed the plant. Just make sure the change isn't too sudden. 3. Give it potassium, calcium and silica. Those help provide insect resistance. 4. Apply neem oil. 5. Make sure there aren't other plants harboring the pests to reinfect your peppers. 6. Close the windows. Pests may come in through the windows. 7. Give it some [sea minerals](http://store.rockdustlocal.com/Sea-Minerals-20-lbs_p_25.html). See my comment. They seemed to strengthen my indoor pepper plant against spider mites, anyway, so far. Peppers seem to like sea minerals. I think [the world's heaviest pepper](http://www.worldrecordacademy.com/nature/largest_green_pepper_Gigantic_Israeli_Pepper_breaks_Guinness_world_record_213234.html) actually had some seawater. Of course, I'm thinking you don't want to overdo it. See the comments. That being said, aphids can seem pretty magical at times. I had some on mint from an outdoor cutting that just wouldn't go away no matter what I tried (though I didn't try neem oil). If I ever grow indoor mint again, I plan to grow it from seed, or from a trusted plant (not an outdoor one). I think that's a different species of aphid than is on your peppers, though. Hopefully those aren't as bad.
27,968,162
I'm trying to add all the elements of an array in which are embedded 3 other arrays of differing lengths. At the third level are two 1-element arrays whose values I cannot figure out how to access. What am I doing wrong? Please advise (no lamp-throwing, please). ``` function addArrayElems(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) { if (typeof arr[i] === "number") sum += arr[i]; for (var j = 0; j < arr.length; j++) { if (typeof arr[i][j] === "number") sum += arr[i][j]; } //arr[i][j][k] doesn't work for (var k = 0; k < arr.length; k++) { if (typeof arr[i][j][k] === "number") sum += arr[i][j][k]; } for (var l = 0; l < arr.length; l++) { if (typeof arr[i][j] === "number") sum += arr[i][j]; } } return sum; } var arr = [1, 2, 3, 4, 5, [6, 7, 8, [9], [10]]]; console.log(addArrayElems(arr)); ```
2015/01/15
[ "https://Stackoverflow.com/questions/27968162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3743226/" ]
You get `null` because your `Test` calls `DbConnection.connectDB();` before making a call to `loadProp()`. You can fix this problem if you copy the first two lines from the `main` into your code. However, this would not be a good fix, because you have a non-static method `loadProp()` that modifies `static String properties[]` array. You would be better off making `loadProp()` static. In order to do that you would have to replace `this.getClass()` with a static way of obtaining the class - for example, by using `DbConnection.class`. Moreover, you could convert the method to a static initializer, and avoid calling it explicitly altogether: ``` static { Properties prop = new Properties(); InputStream input = DbConnection.class.getResourceAsStream("connection.properties"); try { prop.load(input); } catch (IOException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); System.out.println("exception " + ex); } String username = prop.getProperty("username"); String password = prop.getProperty("password"); properties[0] = username; properties[1] = password; System.out.println(properties[0]); System.out.println(properties[1]); } ``` Now your new `main` would work properly.
Possibly make your **loadProp()** static. Then do this: ``` DbConnection.loadProp(); Connection c = DbConnection.connectDB(); System.out.println("connected " + c); ``` The problem is your **loadProp** is an instance method. You will need to call it after constructing DbConnection to set the values. You could make it easier simply by making your **loadProp** static and call this before trying to get connection object. The bonus is that you don't need to make a constructor call. Once you call the DbConnection.loadProp(), your static values are set and will be available for as long as the class is loaded. Therefore you can call it once in your application and get connection as many times as needed through connectDB. Calling loadProp once is sufficient and desirable (given your settings are not changing often) because reading through Stream is considered expensive and should be done only when needed.
33,870,029
I am storing `TIMESTAMP` in database and when i fetch it back from database i want to convert it into AM and PM date format. ``` var dbDate = moment(milliseconds); // **i am getting an error over here** var data = dbDate.format("hh:mm:A").split(":"); ``` but i am getting following error `moment(milliseconds);` > > "Deprecation warning: moment construction falls back to js Date. This > is discouraged and will be removed in upcoming major release. Please > refer to <https://github.com/moment/moment/issues/1407> for more info. > > >
2015/11/23
[ "https://Stackoverflow.com/questions/33870029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/405383/" ]
The moment library, by default, only supports a limited number of formats within the constructor. If you don't use one of those formats, it defaults back to using `new Date`, where [browsers are free to interpret the given date how they choose](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2) unless it fits certain criteria. The deprecation warning is there to warn you of this behaviour - it's not necessarily an error. In your case, you have milliseconds, so you can use the [moment constructor that has a format parameter](http://momentjs.com/docs/#/parsing/string-format/), telling it you're specifically passing in milliseconds: ``` var dbDate = moment(milliseconds, 'x'); ``` All this assumes that you currently have `milliseconds` being returned to your JavaScript layer as a String. If you return it and treat it as a Number, you shouldn't be seeing that warning, as moment also has a [specific constructor that takes a single Number](http://momentjs.com/docs/#/parsing/unix-offset/), which if your `milliseconds` parameter is a Number should be being used already.
I'm not all that familiar with moment.js but from a quick look in the docs I don't think the constructor supports a milliseconds argument. Try this: ``` var dbDate = moment({milliseconds: milliseconds}); ``` edit ---- The above code might just treat that as the value after the decimal point in the seconds - if so try this: ``` var dbDate = moment(new Date(milliseconds)); ```
69,612,135
The code below is part of my repository. The static function cannot be used as follows, but I want to receive a different query depending on the parameter value taken over by the service. Can you give me a hand? Thank you in advance. ``` @Query(value = " select * " + "from t_user usr " + "left outer join t_sale_order ord on usr.id = ord.user_idx " + "LEFT OUTER JOIN ( " + "SELECT " + "sale_order_idx, sum(taxable_amount) + sum(non_taxable_amount) as amount " + "FROM t_sale_receipt " + "GROUP BY sale_order_idx " + ") receipt " + "ON receipt.sale_order_idx = ord.id " + "where NOT exists ( " + "select 1 from t_encourage_sent_list sl " + "where sl.user_idx = usr.id and sl.push_idx = ?1 " + ") " + "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) " + // readBookCondition(readBook) + "AND usr.active = 1", nativeQuery = true) List<User> findEncouragePushMsgTarget(Integer pushIdx, Integer readBook); static String readBookCondition(Integer readBook) { String readBookCondition = "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) "; if ( readBook != null ) return ""; if ( readBook != 0 ) readBookCondition.replace("NOT", ""); return readBookCondition; } ```
2021/10/18
[ "https://Stackoverflow.com/questions/69612135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12192313/" ]
At the moment, this cannot be done. AFAIU, Google needs to update its tools to use the customer's domain in the return path of emails to solve this issue.
Currently there is still no way to change the *Envelope From* for Google apps. And it is unlikely that this will change, because Google uses the return path for bounce handling, and using your Google Workspace domain could be tricky. Without such option, SPF may pass but it won't match the "From" domain, which is needed for DMARC to pass. However you can make DMARC pass by setting up and enabling DKIM. SPF still won't be in alignment, but DKIM will, which is enough for DMARC to pass. Just make sure that you set up DKIM **and** enable signing (aka. "start authentication"). It seems that this second step is often missed, which [makes Google Calendar invitation replies to fail DMARC](https://dmarcpal.com/learn/google-calendar-emails-fail-dmarc). This often pass unnoticed because Gmail works fine without it (the article explains why).