qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
15,363,595
I'm practicing ACM problems to become a better programmer, but I'm still fairly new to c++ and I'm having trouble interpreting some of the judges code I'm reading. The beginning of a class starts with ``` public: State(int n) : _n(n), _p(2*n+1) { ``` and then later it's initialized with ``` State s(n); s(0,0) = 1; ``` I'm trying to read the code but I can't make sense of that. The State class only seems to have 1 argument passed, but the programmer is passing 2 in his initialization. Also, what exactly is being set = to 1? As far as I can tell, the = operator isn't being overloaded but just in case I missed something I've included the full code below. Any help would be greatly appreciated. Thanks in advance ``` /* * D - Maximum Random Walk solution * ICPC 2012 Greater NY Regional * Solution by Adam Florence * Problem by Adam Florence */ #include <cstdio> // for printf #include <cstdlib> // for exit #include <algorithm> // for max #include <iostream> #include <vector> using namespace std; class State { public: State(int n) : _n(n), _p(2*n+1) { if (n < 1) { cout << "Ctor error, n = " << n << endl; exit(1); } for (int i = -n; i <= n; ++i) _p.at(i+_n) = vector<double>(n+1, 0.0); } void zero(const int n) { for (int i = -n; i < n; ++i) for (int m = 0; m <= n; ++m) _p[i+_n][m] = 0; } double operator()(int i, int m) const { #ifdef DEBUG if ((i < -_n) || (i > _n)) { cout << "Out of range error, i = " << i << ", n = " << _n << endl; exit(1); } if ((m < 0) || (m > _n)) { cout << "Out of range error, m = " << m << ", n = " << _n << endl; exit(1); } #endif return _p[i+_n][m]; } double& operator()(int i, int m) { #ifdef DEBUG if ((i < -_n) || (i > _n)) { cout << "Out of range error, i = " << i << ", n = " << _n << endl; exit(1); } if ((m < 0) || (m > _n)) { cout << "Out of range error, m = " << m << ", n = " << _n << endl; exit(1); } #endif return _p[i+_n][m]; } static int min(int x, int y) { return(x < y ? x : y); } static int max(int x, int y) { return(x > y ? x : y); } private: int _n; // First index is the current position, from -n to n. // Second index is the maximum position so far, from 0 to n. // Value is probability. vector< vector<double> > _p; }; void go(int ds) { // Read n, l, r int n, nds; double l, r; cin >> nds >> n >> l >> r; const double c = 1 - l - r; if(nds != ds){ cout << "Dataset number " << nds << " does not match " << ds << endl; return; } // Initialize state, probability 1 at (0,0) State s(n); s(0,0) = 1; State t(n); State* p1 = &s; State* p2 = &t; for (int k = 1; k <= n; ++k) { // Compute probabilities at step k p2->zero(k); // At step k, the farthest from the origin you can be is k for (int i = -k; i <= k; ++i) { const int mm = State::min( State::max(0, i+k), k); for (int m = 0; m <= mm; ++m) { // At step k-1, p = probability of (i,m) const double p = p1->operator()(i,m); if (p > 0) { // Step left p2->operator()(i-1, m) += p*l; // Step right p2->operator()(i+1, State::max(i+1,m)) += p*r; // Stay put p2->operator()(i, m) += p*c; } } } swap(p1, p2); } // Compute expected maximum position double p = 0; for (int i = -n; i <= n; ++i) for (int m = 0; m <= n; ++m) p += m * p1->operator()(i,m); printf("%d %0.4f\n", ds, p); } int main(int argc, char* argv[]) { // Read number of data sets to process int num; cin >> num; // Process each data set identically for (int i = 1; i <= num; ++i) go(i); // We're done return 0; } ```
2013/03/12
[ "https://Stackoverflow.com/questions/15363595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874415/" ]
You are confusing a call to `state::operator()(int, int)` with an initialization. That operator call lets you set the value of an element of the class instance. ``` State s(n); // this is the only initialization s(0,0) = 1; // this calls operator()(int, int) on instance s ```
This part: ``` State(int n) : _n(n), _p(2*n+1) ``` ...is a member initializer list. It's sort of similar to if you'd written the construct like: ``` state(int n) { _n = n; _p = 2*n+1; } ``` ...except that it initializes `_n` and `_p` instead of starting with them unitialized, then assigning values to them. In this specific case that may not make much difference, but when you have things like references that can only be initialized (not assigned) it becomes crucial. The `s(0,0) = 1` looks like `s` is intended to act a little like a 2D array, and they've overloaded `operator()` to act as a subscripting operator for that array. I posted a class that does that in a [previous answer](https://stackoverflow.com/a/2216055/179910).
17,020,311
I am getting this error whenever I leave my drop down lists blank: > > "String was not recognized as a valid DateTime" > > > My .aspx looks like below: ``` <asp:DropDownList ID="cboDay" runat="server" Width="55px" Height="32px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="cboMonth" runat="server" Width="80px" Height="30px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="cboYear" runat="server" Width="65px" Height="30px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> ``` Code behind: ``` protected void btnSave_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); SqlCommand cmd = new SqlCommand("qryINSERTprof", con); cmd.CommandType = System.Data.CommandType.Text; String str = cboDay.SelectedItem.Text + "/" + cboMonth.SelectedItem.Text + "/" + cboYear.SelectedItem.Text; lbltxtage.Text = str; DateTime dt = Convert.ToDateTime(str); string bdate = lbltxtage.Text; DateTime dts = DateTime.Parse(bdate); TimeSpan d = DateTime.Now.Subtract(dts); double years = d.TotalDays / 365; int months = (int)((years - (int)years) * 12); txtage.Text = ((int)years).ToString(); Response.Write(dt.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)); cmd.Parameters.AddWithValue("@Lname", txtlname.Text); cmd.Parameters.AddWithValue("@Mname", txtmname.Text); cmd.Parameters.AddWithValue("@Fname", txtfname.Text); cmd.Parameters.AddWithValue("@BirthDate", lbltxtage.Text); cmd.Parameters.AddWithValue("@age", txtage.Text); cmd.CommandType = System.Data.CommandType.StoredProcedure; con.Open(); cmd.ExecuteNonQuery(); ``` } Any help would be appreciated. Thanks in advance.
2013/06/10
[ "https://Stackoverflow.com/questions/17020311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388316/" ]
> > I am getting this error whenever I leave my drop down lists blank > > > Then don't leave it blank, or change your code to detect empty input. There are a few ways to do this, but for example you can do it like this: ``` protected void btnSave_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(cboDay.SelectedItem.Text) || String.IsNullOrEmpty(cboMonth.SelectedItem.Text) || String.IsNullOrEmpty(cboYear.SelectedItem.Text)) { // TOOD: notify your UI that the values must be supplied return; } String str = cboDay.SelectedItem.Text + "/" + cboMonth.SelectedItem.Text + "/" + cboYear.SelectedItem.Text; DateTime dt = Convert.ToDateTime(str); // ... } ```
Should you use a nullable datetime when the field is left blank? ``` DateTime? dt = null; DateTime tmp; if (DateTime.TryParse( String.Format("{0}/{1}/{2}", cboDay.SelectedItem.Text , cboMonth.SelectedItem.Text , cboYear.SelectedItem.Text ) , out tmp )) { dt = tmp; } ```
17,020,311
I am getting this error whenever I leave my drop down lists blank: > > "String was not recognized as a valid DateTime" > > > My .aspx looks like below: ``` <asp:DropDownList ID="cboDay" runat="server" Width="55px" Height="32px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="cboMonth" runat="server" Width="80px" Height="30px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="cboYear" runat="server" Width="65px" Height="30px" AppendDataBoundItems="true"> <asp:ListItem></asp:ListItem> </asp:DropDownList> ``` Code behind: ``` protected void btnSave_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); SqlCommand cmd = new SqlCommand("qryINSERTprof", con); cmd.CommandType = System.Data.CommandType.Text; String str = cboDay.SelectedItem.Text + "/" + cboMonth.SelectedItem.Text + "/" + cboYear.SelectedItem.Text; lbltxtage.Text = str; DateTime dt = Convert.ToDateTime(str); string bdate = lbltxtage.Text; DateTime dts = DateTime.Parse(bdate); TimeSpan d = DateTime.Now.Subtract(dts); double years = d.TotalDays / 365; int months = (int)((years - (int)years) * 12); txtage.Text = ((int)years).ToString(); Response.Write(dt.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)); cmd.Parameters.AddWithValue("@Lname", txtlname.Text); cmd.Parameters.AddWithValue("@Mname", txtmname.Text); cmd.Parameters.AddWithValue("@Fname", txtfname.Text); cmd.Parameters.AddWithValue("@BirthDate", lbltxtage.Text); cmd.Parameters.AddWithValue("@age", txtage.Text); cmd.CommandType = System.Data.CommandType.StoredProcedure; con.Open(); cmd.ExecuteNonQuery(); ``` } Any help would be appreciated. Thanks in advance.
2013/06/10
[ "https://Stackoverflow.com/questions/17020311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388316/" ]
> > I am getting this error whenever I leave my drop down lists blank > > > Then don't leave it blank, or change your code to detect empty input. There are a few ways to do this, but for example you can do it like this: ``` protected void btnSave_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(cboDay.SelectedItem.Text) || String.IsNullOrEmpty(cboMonth.SelectedItem.Text) || String.IsNullOrEmpty(cboYear.SelectedItem.Text)) { // TOOD: notify your UI that the values must be supplied return; } String str = cboDay.SelectedItem.Text + "/" + cboMonth.SelectedItem.Text + "/" + cboYear.SelectedItem.Text; DateTime dt = Convert.ToDateTime(str); // ... } ```
as you are using seperate dropdownlists for day month and year try this one ``` string date=cboDay.selectedtext+"/"+cbomonth.selectedtext+"/"+cboYear.selectedtext; convert.todatetime(date); ``` but before trying this make sure that your day format is like 01,02,...29,30 and month format as 01,02,..11,12 all two digit format.otherwise you'll get an error.
9,262,695
I'm trying to pull code comment blocks out of JavaScript files. I'm making a light code documentator. An example would be: ``` /** @Method: setSize * @Description: setSize DESCRIPTION * @param: setSize PARAMETER */ ``` I need to pull out the comments setup like this, ideally into an array. I had gotten as far as this, but realize it may not handle new lines tabs, etc.: ``` \/\*\*(.*?)\*\/ ``` (Okay, this seems like it would be simple, but I'm going in circles trying to get it to work.)
2012/02/13
[ "https://Stackoverflow.com/questions/9262695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148438/" ]
This should grab a comment block `\/\*\*[^/]+\/`. I don't think Regexp is the best way to generate an array from these blocks though. This regexp basically says: Find a `/**` (the asterisk and forward slashes are escaped with `\`) then find anything that isn't a `/` then find one `/` It's crude but is should generally work. Here's a live example <http://regexr.com?300c6>
What about some magic :) ```js comment.replace(/@(\w+)\s*\:\s*(\S+)\s+(\w+)/gim, function (match, tag, name, descr) { console.log(arguments); // Do sth. ... }); ``` I've not tested this so for the regex there is no guarantee, just to point you to a possibility do some RegExp-search the John Resig way 8-)
9,262,695
I'm trying to pull code comment blocks out of JavaScript files. I'm making a light code documentator. An example would be: ``` /** @Method: setSize * @Description: setSize DESCRIPTION * @param: setSize PARAMETER */ ``` I need to pull out the comments setup like this, ideally into an array. I had gotten as far as this, but realize it may not handle new lines tabs, etc.: ``` \/\*\*(.*?)\*\/ ``` (Okay, this seems like it would be simple, but I'm going in circles trying to get it to work.)
2012/02/13
[ "https://Stackoverflow.com/questions/9262695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148438/" ]
Depending on what you want to continue doing with the extracted docblocks, multiple approaches come to mind. If you simply need the docblocks without further references, String.match() may suffice. Otherwise you might need the index of the block. As others have already pointed out, javascript's RegEx machine is everything but powerful. if you're used to PCRE, this feels like working with your hands tied behind your back. `[\s\S]` (space-character, non-space-character) is equivalent to dotAll - also capturing linebreaks. This should get you started: ``` var string = 'var foo = "bar";' + '\n\n' + '/** @Method: setSize' + '\n * @Description: setSize DESCRIPTION' + '\n * @param: setSize PARAMETER' + '\n */' + '\n' + 'function setSize(setSize) { return true; }' + '\n\n' + '/** @Method: foo' + '\n * @Description: foo DESCRIPTION' + '\n * @param: bar PARAMETER' + '\n */' + '\n' + 'function foo(bar) { return true; }'; var docblock = /\/\*{2}([\s\S]+?)\*\//g, trim = function(string){ return string.replace(/^\s+|\s+$/g, ''); }, split = function(string) { return string.split(/[\r\n]\s*\*\s+/); }; // extract all doc-blocks console.log(string.match(docblock)); // extract all doc-blocks with access to character-index var match; while (match = docblock.exec(string)) { console.log( match.index + " characters from the beginning, found: ", trim(match[1]), split(match[1]) ); } ```
This should grab a comment block `\/\*\*[^/]+\/`. I don't think Regexp is the best way to generate an array from these blocks though. This regexp basically says: Find a `/**` (the asterisk and forward slashes are escaped with `\`) then find anything that isn't a `/` then find one `/` It's crude but is should generally work. Here's a live example <http://regexr.com?300c6>
9,262,695
I'm trying to pull code comment blocks out of JavaScript files. I'm making a light code documentator. An example would be: ``` /** @Method: setSize * @Description: setSize DESCRIPTION * @param: setSize PARAMETER */ ``` I need to pull out the comments setup like this, ideally into an array. I had gotten as far as this, but realize it may not handle new lines tabs, etc.: ``` \/\*\*(.*?)\*\/ ``` (Okay, this seems like it would be simple, but I'm going in circles trying to get it to work.)
2012/02/13
[ "https://Stackoverflow.com/questions/9262695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148438/" ]
Depending on what you want to continue doing with the extracted docblocks, multiple approaches come to mind. If you simply need the docblocks without further references, String.match() may suffice. Otherwise you might need the index of the block. As others have already pointed out, javascript's RegEx machine is everything but powerful. if you're used to PCRE, this feels like working with your hands tied behind your back. `[\s\S]` (space-character, non-space-character) is equivalent to dotAll - also capturing linebreaks. This should get you started: ``` var string = 'var foo = "bar";' + '\n\n' + '/** @Method: setSize' + '\n * @Description: setSize DESCRIPTION' + '\n * @param: setSize PARAMETER' + '\n */' + '\n' + 'function setSize(setSize) { return true; }' + '\n\n' + '/** @Method: foo' + '\n * @Description: foo DESCRIPTION' + '\n * @param: bar PARAMETER' + '\n */' + '\n' + 'function foo(bar) { return true; }'; var docblock = /\/\*{2}([\s\S]+?)\*\//g, trim = function(string){ return string.replace(/^\s+|\s+$/g, ''); }, split = function(string) { return string.split(/[\r\n]\s*\*\s+/); }; // extract all doc-blocks console.log(string.match(docblock)); // extract all doc-blocks with access to character-index var match; while (match = docblock.exec(string)) { console.log( match.index + " characters from the beginning, found: ", trim(match[1]), split(match[1]) ); } ```
What about some magic :) ```js comment.replace(/@(\w+)\s*\:\s*(\S+)\s+(\w+)/gim, function (match, tag, name, descr) { console.log(arguments); // Do sth. ... }); ``` I've not tested this so for the regex there is no guarantee, just to point you to a possibility do some RegExp-search the John Resig way 8-)
1,517,016
I have a small application which can be used to set reminders for future events. The app uses an AlarmManager to set the time for when the user should be reminded. When the alarm goes off, a BroadcastReceiver registers this and in turn starts a service to notify the user via a toast and a notification in the status bar. In order to display the correct information in the notification and toast, some extra information is passed along with the intent. The first time a reminder is registered, the info received by the BroadcastReceiver and passed on to the service is correct. But for each following reminder (i.e. each new intent received by the BroadcastReceiver) this information stays the same even when the information sent is different. As an example, if the string "foo" is put as an extra with the first intent, "foo" is correctly extracted by the BroadcastReceiver. If "bar" is put as an extra in the second intent, "foo" is still extracted by the BroadcastReceiver. This is the code that registers the alarm and passes the intent (main ui-class): ``` Intent intent = new Intent(ACTION_SET_ALARM); intent.putExtra("desc", desc); intent.putExtra("time", time); intent.putExtra("dbId", dbId); intent.putExtra("millis", millis); PendingIntent pIntent = PendingIntent.getBroadcast(quickAlert.this, 0, intent, 0); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, millis, pIntent); ``` The onReceive()-method in the BroadcastReceiver class: ``` @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AlertService.class); String desc = intent.getStringExtra("desc").equals("") ? "": ": " + intent.getStringExtra("desc"); String time = intent.getStringExtra("time"); long dbId = intent.getLongExtra("dbId", -1); long millis = intent.getLongExtra("millis", -1); i.putExtra("desc", desc); i.putExtra("time", time); i.putExtra("dbId", dbId); i.putExtra("millis", millis); Log.d(TAG, "AlertReceiver: " + desc + ", " + time + ", " + dbId + ", " + millis); Toast.makeText(context, "Reminder: " + desc, Toast.LENGTH_LONG).show(); context.startService(i); } ``` The intent-filter in the manifest: ``` <receiver android:name=".AlertReceiver"> <intent-filter> <action android:name="com.aspartame.quickAlert.ACTION_SET_ALARM" /> </intent-filter> </receiver> ``` I've been stuck with this for some time now, so help is very much appreciated!
2009/10/04
[ "https://Stackoverflow.com/questions/1517016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91098/" ]
Try adding [`FLAG_UPDATE_CURRENT`](http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_UPDATE_CURRENT) to your `PendingIntent` when you create it via `getBroadcast()`.
The above answers are correct, but they lack an explanation. It's worth noting this part of the [PendingIntent documentation](http://developer.android.com/reference/android/app/PendingIntent.html): > > A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. ... If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token > > > Note that "extra" data is specifically **not** included in the concept of PendingIntent-identity!
1,517,016
I have a small application which can be used to set reminders for future events. The app uses an AlarmManager to set the time for when the user should be reminded. When the alarm goes off, a BroadcastReceiver registers this and in turn starts a service to notify the user via a toast and a notification in the status bar. In order to display the correct information in the notification and toast, some extra information is passed along with the intent. The first time a reminder is registered, the info received by the BroadcastReceiver and passed on to the service is correct. But for each following reminder (i.e. each new intent received by the BroadcastReceiver) this information stays the same even when the information sent is different. As an example, if the string "foo" is put as an extra with the first intent, "foo" is correctly extracted by the BroadcastReceiver. If "bar" is put as an extra in the second intent, "foo" is still extracted by the BroadcastReceiver. This is the code that registers the alarm and passes the intent (main ui-class): ``` Intent intent = new Intent(ACTION_SET_ALARM); intent.putExtra("desc", desc); intent.putExtra("time", time); intent.putExtra("dbId", dbId); intent.putExtra("millis", millis); PendingIntent pIntent = PendingIntent.getBroadcast(quickAlert.this, 0, intent, 0); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, millis, pIntent); ``` The onReceive()-method in the BroadcastReceiver class: ``` @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AlertService.class); String desc = intent.getStringExtra("desc").equals("") ? "": ": " + intent.getStringExtra("desc"); String time = intent.getStringExtra("time"); long dbId = intent.getLongExtra("dbId", -1); long millis = intent.getLongExtra("millis", -1); i.putExtra("desc", desc); i.putExtra("time", time); i.putExtra("dbId", dbId); i.putExtra("millis", millis); Log.d(TAG, "AlertReceiver: " + desc + ", " + time + ", " + dbId + ", " + millis); Toast.makeText(context, "Reminder: " + desc, Toast.LENGTH_LONG).show(); context.startService(i); } ``` The intent-filter in the manifest: ``` <receiver android:name=".AlertReceiver"> <intent-filter> <action android:name="com.aspartame.quickAlert.ACTION_SET_ALARM" /> </intent-filter> </receiver> ``` I've been stuck with this for some time now, so help is very much appreciated!
2009/10/04
[ "https://Stackoverflow.com/questions/1517016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91098/" ]
Try adding [`FLAG_UPDATE_CURRENT`](http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_UPDATE_CURRENT) to your `PendingIntent` when you create it via `getBroadcast()`.
best Link I've found on this topic: <http://alvinalexander.com/source-code/android/android-how-attach-extra-intent-pendingintent-notification-solution-example> this is the clue: ``` int uniqueInt = (int) (System.currentTimeMillis() & 0xfffffff); PendingIntent.getService(context, uniqueInt, intent, 0) ```
314,723
**Problem** Many users (including me) found out from one moment to another that the usage disk space is really strange. One day I had 50Gb free and the next I had 3Gb, it is just crazy. This happened with different versions of Ubuntu (11.04, 12.04 and 12.10 just to mention). Some of those user have create question on this site, some of them: * [Disk Usage Very Strange](https://askubuntu.com/q/69267/62483) * [Ubuntu 12.10 recognizes me only 3GB of free space](https://askubuntu.com/q/206860/62483) * [Why am I getting low disk space usage?](https://askubuntu.com/q/314710/62483) **Solution** [@NathanWienand](https://askubuntu.com/users/107984/nathan-wienand) have [discovered](https://askubuntu.com/a/217045/62483) that the problem was caused by the `.xsession-errors.old` file (it can be found on the $HOME directory) and he and others user solved the problem removing the file. An example of the size that can have this file is ~100Gb, not reasonable.. **Question** * Why does this happen? * Is deleting the file the only way to solve it? * Isn't there another way to solve this with a large period effect? * Does this problem affect only to 64 bits system's users? --- If you have something to add here, feel free to edit the question.
2013/06/30
[ "https://askubuntu.com/questions/314723", "https://askubuntu.com", "https://askubuntu.com/users/62483/" ]
You could investigate the problem. Yes, I know it's a big file, but by throwing away data and letting the computer do the work, one could: ``` cat .xsession-errors* | \ egrep -v '^$' | \ sed -e 's/[0-9][0-9]\+/#NUM#/g' | \ sort | \ uniq -c | \ sort -rn | \ tee counts.out | \ less -XMersj3 ``` Some messages (on my system without the problem) like: ``` 38 /usr/share/software-center/softwarecenter/ui/gtk3/widgets/exhibits.py:#NUM#: Warning: Source ID #NUM# was not found when attempting to remove it 38 GLib.source_remove(self._timeout) 36 (nautilus:#NUM#): Gdk-CRITICAL **: gdk_window_get_origin: assertion 'GDK_IS_WINDOW (window)' failed ``` happen more often (38, 38, 36 times) than others, and therefore deserve more investigation. Others: ``` 1 compiz (core) - Info: Loading plugin: ccp 1 compiz (core) - Info: Loading plugin: animation ``` Another thing to do is to look for deleted, but still open files: ``` sudo lsof / | egrep 'PID|(deleted)' ``` Look for large SIZE/OFF values. And look for large open files: ``` sudo lsof / | \ awk '{if($7 > 1048576) print $7/1048576 "MB" " " $9 }' | \ sort -n -u ```
I am not sure why this happens, but this is a bit big for a comment. I would just stop them being created by running these command: `rm .xsession-errors.old` `touch .xsession-errors.old` `sudo chattr +i .xsession-errors.old` So delete the file, create a new one, and then set the immutable attribute to stop anything writing or reading it. You will need to logout. Hope it helps.
36,200
I am trying to build a neural net that will overfit random walk path. So, far I wasn't able to get a neural net that we shatter/overfit. I was wondering which parameters I should explore, or which guide lines I should follow to achieve this (wierd) task. ### Code: ``` from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD,Adam from keras import regularizers import numpy as np import matplotlib.pyplot as plt %matplotlib inline import random import math model=Sequential() num_units=100 model.add(Dense(num_units,input_shape=(1,),activation='tanh')) model.add(Dense(num_units,activation='tanh')) model.add(Dense(num_units,activation='tanh')) model.add(Dense(num_units,activation='tanh')) model.add(Dense(1, activation='tanh')) #output layer 1 unit model.compile(Adam(),'mean_squared_error',metrics=['mse']) num_of_steps=3000; step_size=0.01 x_all=list(range(0,num_of_steps)) ##########################random walk functino random_walk=[0] for i in x_all[1:]: f=np.random.uniform(0,1,1) if f<0.5: random_walk.append(random_walk[i-1]+step_size) else: random_walk.append(random_walk[i-1]-step_size) ######################## x1=list(range(1,1000,2)) x2=list(range(2,1000,2)) y1=[random_walk[x] for x in x1] y2=[random_walk[x] for x in x2] model.fit(x1,y1,epochs=2500,verbose=1) fit1=model.predict(x1) fit2=model.predict(x2) plt.plot(x1,y1,'k') plt.plot(x2, y2, 'r') plt.scatter(x1, fit1, facecolors='none', edgecolors='g') #plt.plot(x_value,sample,'bo') plt.scatter(x2, fit2, facecolors='none', edgecolors='b') #plt.plot(x_value,sample,'bo') ``` this is an example of the results I am getting: [![enter image description here](https://i.stack.imgur.com/sZ9zf.png)](https://i.stack.imgur.com/sZ9zf.png) And I would want to get a better fit (to my sample data: x1,y1).
2018/07/30
[ "https://datascience.stackexchange.com/questions/36200", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/56928/" ]
Generally, library that you use for k-means clustering will report "within cluster sum-of-squares" value after running k-means procedure. A smaller value means the cluster is tightly bound (most messages are similar to each other). You can use this value to order the cluster IDs.
Assuming you have clustered them according to some word/characters vectors, your clustering algorithm probably produced a centroid point for each cluster. Now, the next step depends on what you have defined as a 'higher ranking'. Do you see clusters having very dense distribution of text as having a good rank? Or do you want something else (e.g clusters with no outliers) This depends your own definition of (taken from your question): > > 'contains most similar text' > > > Now, the next step will be to calculate the average euclidean distance/cosine similarity/some kind of distance metric between each piece of text in the cluster. Assuming you are interested in clusters of text which are the most similar, then the cluster with the lowest average distance between centroid and text vectors will be the highest ranked cluster. **But wait! There are more subtleties involved.** Three important things to note: 1. The distance metric you use is crucial for success. Please read up on different metrics such as euclidean distance, manhattan distance, cosine similarity etc. Each of them is beneficial in their own ways and **it depends on what you define as text similarity**. You must know what you want - how would you treat texts with different lengths? Do you only want to consider uncommon/rare words in ranking similarity? Different metrics can be used depending on how you answer these questions. 2. You may want to feature engineer your texts beforehand. For example, you could end up with clusters grouping texts containing many 'a' and 'the' and 'I' (which are more common in narrative texts instead of, say, news articles). You could perhaps remove these words beforehand using some existing library and stemmers. 3. To visualise the spread of the clusters, you can try to use PCA to reduce the word vector space to 2D. Clustering algorithms are notorious for failing edge cases (see [No Free Lunch Theorem](https://en.wikipedia.org/wiki/No_free_lunch_theorem)). If your clustering algorithm has already failed in the first place, there is no point trying to rank them.
17,488,978
Suppose I have a bunch of students and a couple of professors. Each student needs to take an oral exam with one of the professors. For this, every student supplies an (ordered) list consisting of three professors he would prefer taking the exam with. Of course, each professor can only give a limited number of exams. I can use the Kuhn-Munkres algorithm to compute an assignment where as many students as possible are assigned to their first wish professor. Now suppose instead that every student has to take *two* exams, and accordingly supplies two wish lists. Again I want to assign as many students as possible to their first wish professors, but subject to the constraint that *a student must not take both his exams with the same professor*. Is there some algorithm for computing an optimal assignment efficiently? Maybe a generalization of the Kuhn-Munkres algorithm? Or is this new problem already NP-hard? What hard problem could one try to reduce to this one? I should emphasize that I am looking for an exact solution. It is pretty easy to think of some heuristics, like considering one type of exam after the other.
2013/07/05
[ "https://Stackoverflow.com/questions/17488978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2553174/" ]
You can model this *exactly* using Integer programming as an [Assignment Problem.](http://en.wikipedia.org/wiki/Assignment_problem) **Variables** Let there be **s** students and **p** professors. The decision variable ``` X_sp is 1 if student s takes an exam with professor p 0 otherwise Let Limit_p be the number of exams that professor p can handle. ``` **Handling Student Preferences** We can handle each student's preference through the costs (objective) ``` Let C_sp be the 'cost' of assigning student s to take an exam with professor p. ``` We keep progressively making the costs higher as the preference decreases. ``` C_sp = 1 if p is the *first* preference of s C_sp = 2 if p is the *second* preference of s C_sp = 3 if p is the *third* preference of s ... C_sp = n if p is the *n th* preference of s ``` **Formulation** **Case 1: One Exam** ``` Min (sum over s)(sum over p) C_sp X_sp subject to: (sum over p) X_sp = 1 for each student s # Every student must take an exam (sum over s) X_sp <= Limit_p for each professor p # Every prof can only handle so many exams X_sp = {0,1} # binary ``` **Case 2: student takes two Exams** ``` Min (sum over s)(sum over p) C_sp X_sp subject to: (sum over p) X_sp = 2 for each student s # Every student must take an exam (sum over s) X_sp <= Limit_p for each professor p # Every prof can only handle so many exams X_sp = {0,1} # binary ``` *Taking care of no student can take both exams with the same professor* Normally, we'd have to introduce *indicator variables* `Y_sp` to denote whether or not a student has taken an exam with professor p. However, in this case we don't even have to do that. The fact that `X_sp` is binary will ensure that no student ends up taking 2 exams with the same professor. If the student has a preference of *which* exam they'd like to take with a professor, then adding a subscript `e` to the decision variable is required. `X_spe` You can solve this either through the Hungarian method, or easier still, any available implementation of LP/IP solver. The [Hungarian algorithm's](http://en.wikipedia.org/wiki/Hungarian_algorithm) complexity is O(n^3), and since we haven't introduced any side constraints to spoil the *integrality property,* the linear solution will always be integral. **Update (A little bit of theory)** *Why are the solutions integral?* To understand why the solutions are guaranteed to be integral, a little bit of theory is necessary. Typically, when confronted with an IP, the first thought is to try solving the *linear relaxation* (Forget the integral values requirements and try.) This will give a lower bound to minimization problems. There are usually a few so-called *complicating constraints* that make integer solutions very difficult to find. One solution technique is to relax those by throwing them to the objective function, and solving the simpler problem (the *Lagrangian Relaxation* problem.) Now, if the solution to the Lagrangian doesn't change whether or not you have integrality (as is the case with Assignment Problems) then you always get integer solutions. For those who are really interested in learning about Integrality and Lagrangian duals, [this reference is quite readable.](http://athena.uwindsor.ca/users/b/baki%20fazle/73-605.nsf/0/a0f56d9f30b19b7485256a6300120aaf/$FILE/Fisher_Lagrangian.pdf) The example in Section 3 specifically covers the Assignment Problem. **Free MILP Solvers:** [This SO question is quite exhaustive for that.](https://stackoverflow.com/questions/502102/best-open-source-mixed-integer-optimization-solver) Hope that helps.
I think you can solve this optimally by solving a min cost flow problem. The Python code below illustrates how this can be done for 3 students using the networkx library. ``` import networkx as nx G=nx.DiGraph() multiple_prefs=[{'Tom':['Prof1','Prof2','Prof3'], 'Dick':['Prof2','Prof1','Prof3'], 'Harry':['Prof1','Prof3','Prof1']}, {'Tom':['Prof2','Prof1','Prof3'], 'Dick':['Prof2','Prof1','Prof3'], 'Harry':['Prof1','Prof3','Prof1']} ] workload={'Prof1':2,'Prof2':10,'Prof3':4} num_tests=len(multiple_prefs) num_students=len(multiple_prefs[0]) G.add_node('dest',demand=num_tests*num_students) A=[] for i,prefs in enumerate(multiple_prefs): testname='_test%d'%i for student,proflist in prefs.items(): node=student+testname A.append(node) G.add_node(node,demand=-1) for i,prof in enumerate(proflist): if i==0: cost=0 # happy to assign first choices elif i==1: cost=1 # Slightly unhappy to assign second choices else: cost=4 # Very unhappy to assign third choices n2=prof+'_with_'+student n3=prof G.add_edge(node,n2,capacity=1,weight=cost) # Edge taken if student takes this test with the professor G.add_edge(n2,n3,capacity=1,weight=0) # Capacity stops student taking both tests with the same professor G.add_edge(n3,'dest',capacity=workload[prof],weight=0) # Capacity stops professor exceeding his workload flowdict = nx.min_cost_flow(G) for student in A: for prof,flow in flowdict[student].items(): if flow: print student,'with',prof ``` The key is that we have a separate node (called n2 in the code) for each combination of student and professor. By giving n2 a capacity of 1 to the destination, we ensure that each student can only take a single test with that professor. The dictionary multiple\_prefs stores two dictionaries. The first dictionary contains the lists of preferences for each student for the first test. The second has the preferences for the second test. EDIT The code now also includes nodes n3 for each professor. The capacity on the edges between these nodes and the dest will limit the maximum workload for each professor. The dictionary workload stores the maximum number of allowed tests for each professor.
17,232,932
I am working on Quiz App. In my app I want to get difference between quiz start time and end time. How to get difference between start and end time. Thanks in advance.
2013/06/21
[ "https://Stackoverflow.com/questions/17232932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969269/" ]
You can use **NSDate** `- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate` for this purpose.
The `NSDate` class has a method `timeIntervalSinceDate` that does the trick. ``` NSTimeInterval interval = [firstDate timeIntervalSinceDate:secondDate]; ```
17,232,932
I am working on Quiz App. In my app I want to get difference between quiz start time and end time. How to get difference between start and end time. Thanks in advance.
2013/06/21
[ "https://Stackoverflow.com/questions/17232932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969269/" ]
You can use **NSDate** `- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate` for this purpose.
Use this ``` NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"MM/dd/yy"]; NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/yy"]; NSString *dateString11 = [dateFormat stringFromDate:today]; NSDate *today1 = [dateFormatter1 dateFromString:dateString11]; NSDate *ExpDate = [[NSUserDefaults standardUserDefaults]objectForKey:@"ExpDate"]; NSTimeInterval interval = [ExpDate timeIntervalSinceDate:today1]; int diff=interval/86400; ``` i hope this code useful for you. And Another code for you. ``` NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"MM/dd/yyyy"]; NSDate *ServerDate = [dateFormatter1 dateFromString:@"04/26/2013"]; [dateFormatter1 release]; NSTimeInterval interval = [date timeIntervalSinceDate:ServerDate]; int diff=interval/86400; NSLog(@"%d",diff); ```
17,232,932
I am working on Quiz App. In my app I want to get difference between quiz start time and end time. How to get difference between start and end time. Thanks in advance.
2013/06/21
[ "https://Stackoverflow.com/questions/17232932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969269/" ]
Use this ``` NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"MM/dd/yy"]; NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/yy"]; NSString *dateString11 = [dateFormat stringFromDate:today]; NSDate *today1 = [dateFormatter1 dateFromString:dateString11]; NSDate *ExpDate = [[NSUserDefaults standardUserDefaults]objectForKey:@"ExpDate"]; NSTimeInterval interval = [ExpDate timeIntervalSinceDate:today1]; int diff=interval/86400; ``` i hope this code useful for you. And Another code for you. ``` NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"MM/dd/yyyy"]; NSDate *ServerDate = [dateFormatter1 dateFromString:@"04/26/2013"]; [dateFormatter1 release]; NSTimeInterval interval = [date timeIntervalSinceDate:ServerDate]; int diff=interval/86400; NSLog(@"%d",diff); ```
The `NSDate` class has a method `timeIntervalSinceDate` that does the trick. ``` NSTimeInterval interval = [firstDate timeIntervalSinceDate:secondDate]; ```
25,208,968
Is there a function to do this? For example if I have an array like this: ``` array( 2014-08-05 10:23:34, 2014-08-08 13:12:56, 2014-08-07 08:02:21, 2014-08-06 11:22:33, 2014-08-03 6:02:44, 2014-08-08 10:23:34 ); ``` and I'd like to return all the dates BETWEEN 2014-08-03 AND 2014-08-06. There is a huge amount of data in these arrays, there may be even tens of thousands of data. I'm actually getting everything from the database and I'd like to divide the data by date (like 2 hours, 1 day, 3 days and so on, based on the time range a visitor selects). How is it possible, without making huge queries or extensive PHP functions? EDIT: ----- As per request I'm showing the data structure of the chart plugin (the values are just quick examples): ``` {x: '2014-08-05 10:23:34', y: 3, data1: 3, data2: 320, data3: 76}, {x: '2014-08-05 10:23:34', y: 2, data1: 1, data2: 300, data3: 27}, {x: '2014-08-05 10:23:34', y: 2, data1: 4, data2: 653, data3: 33}, {x: '2014-08-05 10:23:34', y: 3, data1: 3, data2: 120, data3: 54} ```
2014/08/08
[ "https://Stackoverflow.com/questions/25208968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2874194/" ]
Are you able to do your sorting in MySQL? If so, you can use the BETWEEN operator: 'SELECT \* FROM my\_table where date\_column BETWEEN '2014-08-03' and '2014-08-06' Edit: same as using >= and <=, so be careful with the second date. 2014-08-06 00:00:01 would not be returned by this query because it is greater than 2014-08-06.
You can try using array walk ``` function checkDate(&$item1, $key, $dateToCompare) { //Your Function to compare and echo or anything else } array_walk($fruits, 'checkDate', $dateToCompare); ```
25,208,968
Is there a function to do this? For example if I have an array like this: ``` array( 2014-08-05 10:23:34, 2014-08-08 13:12:56, 2014-08-07 08:02:21, 2014-08-06 11:22:33, 2014-08-03 6:02:44, 2014-08-08 10:23:34 ); ``` and I'd like to return all the dates BETWEEN 2014-08-03 AND 2014-08-06. There is a huge amount of data in these arrays, there may be even tens of thousands of data. I'm actually getting everything from the database and I'd like to divide the data by date (like 2 hours, 1 day, 3 days and so on, based on the time range a visitor selects). How is it possible, without making huge queries or extensive PHP functions? EDIT: ----- As per request I'm showing the data structure of the chart plugin (the values are just quick examples): ``` {x: '2014-08-05 10:23:34', y: 3, data1: 3, data2: 320, data3: 76}, {x: '2014-08-05 10:23:34', y: 2, data1: 1, data2: 300, data3: 27}, {x: '2014-08-05 10:23:34', y: 2, data1: 4, data2: 653, data3: 33}, {x: '2014-08-05 10:23:34', y: 3, data1: 3, data2: 120, data3: 54} ```
2014/08/08
[ "https://Stackoverflow.com/questions/25208968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2874194/" ]
Are you able to do your sorting in MySQL? If so, you can use the BETWEEN operator: 'SELECT \* FROM my\_table where date\_column BETWEEN '2014-08-03' and '2014-08-06' Edit: same as using >= and <=, so be careful with the second date. 2014-08-06 00:00:01 would not be returned by this query because it is greater than 2014-08-06.
As Pagerange mentioned, it would be best to use a SQL query, but if you must do this in PHP here is one solution: ``` // start date chosen by user $start_year = 2014; $start_month = 8; $start_day = 3; // end date chosen by user $end_year = 2014; $end_month = 8; $end_day = 6; $dates = array( '2014-08-05 10:23:34', '2014-08-08 13:12:56', '2014-08-07 08:02:21', '2014-08-06 11:22:33', '2014-08-03 6:02:44', '2014-08-08 10:23:34' ); $data_in_range = array(); // using FOR instead of FOREACH for performance // (assuming zero-based index for $dates array) for($i = 0; $i < count($dates); $i++) { $year = substr($dates[$i], 0, 4); // using intval for values with a leading 0 $month = intval(substr($dates[$i], 5, 2)); $day = intval(substr($dates[$i], 8, 2)); if ($year >= $start_year && $year <= $end_year) { if ($month >= $start_month && $month <= $end_month) { // depending on your definition of 'between' (MySQL // includes the boundaries), you may want // this conditional to read > && < if ($day >= $start_day && $day <= $end_day) { $data_in_range[] = $dates[$i]; } } } } print_r($data_in_range); ``` I am not recommending this answer, but offering a PHP solution.
193,115
I have a SP UIModal Pop-Up, in which I want show Alert to user when click on [X]. How can i do this in SPD 2013
2016/09/06
[ "https://sharepoint.stackexchange.com/questions/193115", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/58738/" ]
use option property of ModalDialog **dialogReturnValueCallback** ``` var options = { url: "/_layouts/myPage.aspx" , dialogReturnValueCallback: function (dialogResult,returnValue ) { if (dialogResult == SP.UI.DialogResult.cancel)//when user click on [X] alert ('popup canceled') } }; SP.UI.ModalDialog.showModalDialog(options); ```
This code work for me : ``` function fAddOnCloseHandler() { var oCloseButton = $("a[id^='DlgClose']"); $clearHandlers(oCloseButton.get(0)); $(oCloseButton).on("click", function (event) { fyourFun(event)} ); } _spBodyOnLoadFunctionNames.push( ExecuteOrDelayUntilScriptLoaded(fAddOnCloseHandler, "SP.js") ); ```
5,229,163
I want to create the rounded corner container in winform .net. My aim is to create a container such that if I dropped any other control within it, that control will also become round shape. Is this possible?
2011/03/08
[ "https://Stackoverflow.com/questions/5229163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408941/" ]
You're looking for the [**`Control.Region`** property](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.region.aspx), which allows you to set the window region associated with a particular control. The operating system will not draw or display any portion of a window that lies outside of a window region. The documentation gives a sample of how to use the `Region` property to create a round button: ``` // This method will change the square button to a circular button by // creating a new circle-shaped GraphicsPath object and setting it // to the RoundButton objects region. private void roundButton_Paint(object sender, PaintEventArgs e) { System.Drawing.Drawing2D.GraphicsPath buttonPath = new System.Drawing.Drawing2D.GraphicsPath(); // Set a new rectangle to the same size as the button's // ClientRectangle property. System.Drawing.Rectangle newRectangle = roundButton.ClientRectangle; // Decrease the size of the rectangle. newRectangle.Inflate(-10, -10); // Draw the button's border. e.Graphics.DrawEllipse(System.Drawing.Pens.Black, newRectangle); // Increase the size of the rectangle to include the border. newRectangle.Inflate( 1, 1); // Create a circle within the new rectangle. buttonPath.AddEllipse(newRectangle); // Set the button's Region property to the newly created // circle region. roundButton.Region = new System.Drawing.Region(buttonPath); } ```
[Control.ControlAdded Event](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controladded.aspx) [Control.Region](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.region.aspx) [Control.DesignMode](http://msdn.microsoft.com/en-us/library/system.web.ui.control.designmode.aspx) You can alter the Region of child controls when they are added to the parent control.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
Does John teach Universalism? Yes and NO! Let me be more specific. There is an important difference between the **provision** of salvation and the reality of salvation. The Bible clearly teaches that the **provision** of salvation is universal but the **actuality** is not. In the writings of John we have: * John 1:29, “Behold the Lamb of God who takes away the sin of the world.” * John 3:16, “God so loved the world that He gave …” * John 12:32, “I [Jesus] … will draw all people to myself.” * 1 John 2:2, “He Himself [Jesus] is the propitiation for our sins, and not for ours [Christians to whom John writes] only but also for the whole world.” Elsewhere in the Bible we also have: * Acts 17:30, “God … commands all people everywhere to repent.” * Rom 3:23, 24, “… for all have sinned … and all are freely forgiven...” * Rom 5:8, 10, “… while we were still sinners, Christ died for us. … if, while were God’s enemies, we were reconciled to him by the death of His Son, …” * Rom 5:15, “But the free gift is not like the offense. For if by the one man’s [Adam’s] offense many died, much more the grace of God and the gift by the grace of the one Man, Jesus Christ, abounded to the many.” [Note the same word, “many” applies to all people.] * Rom 5:18, “Therefore, as through one man’s offense judgment came to all people, resulting in condemnation, even so through one Man’s righteous act the free gift came to all people, resulting in justification of life.” * Rom 11:32, “For God has imprisoned everyone in disobedience so that He may show mercy to all.” * 2 Cor 5:14, “…we are convinced that one died for all, and therefore all died.” * 2 Cor 5:18, 19, “…God was reconciling the world to Himself in Christ …” * 1 Tim 2:3, 4, “For this is good and acceptable in the sight of God our Saviour, who desires all men to be saved and to come to the knowledge of the truth.” * 1 Tim 2:6, “[Jesus Christ] gave Himself as a ransom for all people.” * Titus 2:11, “For the grace of God appeared bringing salvation to all people.” * Heb 2:9, “But we see Jesus, who was made a little lower than the angels, now crowned with glory and honor because he suffered death, so that by the grace of God he might taste death for everyone.” * 2 Peter 3:9, “The Lord is not slow in keeping his promise, as some understand slowness. He is patient with you, not wanting anyone to perish, but everyone to come to repentance.” * Isa 53:6, “We all like sheep have gone astray … and the LORD has laid on him the iniquity of us all.” Now, the universal **provision** of salvation does not mean that all people will be saved - far from it. For example: * The Bible has many references to the final destruction of the wicked such as Ps 37:28, 92:7, 94:23, Prov 14:11, 2 Thess 2:8-10, Matt 5:29, 30, 10:28, 2 Peter 2:3, 3:6, 7, Rom 9:22, Phil 3:19, Ps 68:2. * The wicked are destroyed because they reject God and choose to be destroyed. Contrast the two groups at the second Advent of Jesus: . o Isa 25:9, “In that day they [the righteous] will say, ‘Surely this is our God; we trusted in him, and he saved us. This is the LORD, we trusted in him; let us rejoice and be glad in his salvation.’” . o Rev 6:16, “They called to the mountains and the rocks, ‘Fall on us and hide us from the face of him who sits on the throne and from the wrath of the Lamb!’” **CONCLUSION** Therefore, the **provision** of salvation is universal but the actuality means that many will reject God's gracious offer to be saved and many wicked will be destroyed.
I believe the correct answer is YES. In John 1:7 > > The same came for a witness, to bear witness of the Light, that **all men through him might believe**. > > > John 3:17 states that God sent the Son, who is the God's Word to save the world > > For God did not send his Son into the world to condemn the world, but to **save the world through him**. > > > according to Isaiah 55:11 the word will not return to God **until it accomplishes it's purpose** John 17:1-2 > > These words spake Jesus, and lifted up his eyes to heaven, and said, Father, the hour is come; glorify thy Son, that thy Son also may glorify thee: > > > As thou hast **given him power over all flesh**, that he should **give eternal life to as many as thou hast given him** > > > John 17:6-8 establishes that at that point only some were saved because only some out of the world had believed. > > I have manifested thy name unto **the men which thou gavest me out of the world**: thine they were, and thou gavest them me; and they have kept thy word. > > > Now they have known that all things whatsoever thou hast given me are of thee. > > > For I have given unto them the words which thou gavest me; and **they have received them, and have known surely that I came out from thee, and they have believed that thou didst send me**. > > > John 17:9 confirms that at this point this is only about the apostles > > I pray for them: **I pray not for the world**, but for them which thou hast given me; for they are thine. > > > later in the prayer Jesus expands the target: John 17:20 > > Neither pray I for these alone, but **for them also which shall believe on me through their word** > > > on 17:21 Jesus says that the entire world WILL believe that the Father sent Him (like the first group in 17:8) > > That they all may be one; as thou, Father, art in me, and I in thee, that they also may be one in us: **that the world may believe that thou hast sent me**. > > > Now, all these "might" and "may" that we see in 1:7, 17:2 and 17:21 are not mere possibilities, they express a purpose, an implication. These "may" are known as subjunctives, and are being used in Purpose Clauses and they indicate something that is not necessarily yet true, but that will be the outcome if the first part of the sentence occurs. See [this article](https://www.billmounce.com/monday-with-mounce/my-second-thoughts-about-subjunctives-purpose-clauses) from the greek scholar Bill Mounce (who is the founder and President of BiblicalTraining.org, serves on the Committee for Bible Translation, was the New Testament Chair for the ESV, and has written the best-selling biblical Greek textbook, Basics of Biblical Greek, and many other Greek resources)
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
Does John teach Universalism? Yes and NO! Let me be more specific. There is an important difference between the **provision** of salvation and the reality of salvation. The Bible clearly teaches that the **provision** of salvation is universal but the **actuality** is not. In the writings of John we have: * John 1:29, “Behold the Lamb of God who takes away the sin of the world.” * John 3:16, “God so loved the world that He gave …” * John 12:32, “I [Jesus] … will draw all people to myself.” * 1 John 2:2, “He Himself [Jesus] is the propitiation for our sins, and not for ours [Christians to whom John writes] only but also for the whole world.” Elsewhere in the Bible we also have: * Acts 17:30, “God … commands all people everywhere to repent.” * Rom 3:23, 24, “… for all have sinned … and all are freely forgiven...” * Rom 5:8, 10, “… while we were still sinners, Christ died for us. … if, while were God’s enemies, we were reconciled to him by the death of His Son, …” * Rom 5:15, “But the free gift is not like the offense. For if by the one man’s [Adam’s] offense many died, much more the grace of God and the gift by the grace of the one Man, Jesus Christ, abounded to the many.” [Note the same word, “many” applies to all people.] * Rom 5:18, “Therefore, as through one man’s offense judgment came to all people, resulting in condemnation, even so through one Man’s righteous act the free gift came to all people, resulting in justification of life.” * Rom 11:32, “For God has imprisoned everyone in disobedience so that He may show mercy to all.” * 2 Cor 5:14, “…we are convinced that one died for all, and therefore all died.” * 2 Cor 5:18, 19, “…God was reconciling the world to Himself in Christ …” * 1 Tim 2:3, 4, “For this is good and acceptable in the sight of God our Saviour, who desires all men to be saved and to come to the knowledge of the truth.” * 1 Tim 2:6, “[Jesus Christ] gave Himself as a ransom for all people.” * Titus 2:11, “For the grace of God appeared bringing salvation to all people.” * Heb 2:9, “But we see Jesus, who was made a little lower than the angels, now crowned with glory and honor because he suffered death, so that by the grace of God he might taste death for everyone.” * 2 Peter 3:9, “The Lord is not slow in keeping his promise, as some understand slowness. He is patient with you, not wanting anyone to perish, but everyone to come to repentance.” * Isa 53:6, “We all like sheep have gone astray … and the LORD has laid on him the iniquity of us all.” Now, the universal **provision** of salvation does not mean that all people will be saved - far from it. For example: * The Bible has many references to the final destruction of the wicked such as Ps 37:28, 92:7, 94:23, Prov 14:11, 2 Thess 2:8-10, Matt 5:29, 30, 10:28, 2 Peter 2:3, 3:6, 7, Rom 9:22, Phil 3:19, Ps 68:2. * The wicked are destroyed because they reject God and choose to be destroyed. Contrast the two groups at the second Advent of Jesus: . o Isa 25:9, “In that day they [the righteous] will say, ‘Surely this is our God; we trusted in him, and he saved us. This is the LORD, we trusted in him; let us rejoice and be glad in his salvation.’” . o Rev 6:16, “They called to the mountains and the rocks, ‘Fall on us and hide us from the face of him who sits on the throne and from the wrath of the Lamb!’” **CONCLUSION** Therefore, the **provision** of salvation is universal but the actuality means that many will reject God's gracious offer to be saved and many wicked will be destroyed.
The question is a bit ambiguous, for it gives two quotes - John 1:29 an John 12:47 - which have quite different connotations: the first clearly shows that according to John Jesus' ministry is for the entire world and not just for one chosen nation of Jews, and there are quite a few passages in John that confirm the same. Thus, if in "universalism" is meant this, then of course, quite unambiguously, John's Gospel speaks about it. However, the second quotation speaks about semantics of divine judgment and gives to this term a new twist, for we learn that Jesus who is God and equal to Father does not judge and neither does Father (John 5:22), but how then is God still the Judge who will judge all mankind? When names are applied to God, they change meaning drastically, and thus, we learn that God-the Judge does not judge - and if does not judge, then also does not condemn, for condemning is just a portion of judgment, which is a more general category - in the sense that He only forgives, He only loves, He only forbears, infinitely so, for He cannot help loving His creatures created in His image and likeness. Yet, when we reject all those divine actions towards us, close our hearts from them, then we condemn ourselves through the breach of communion with God and in a vulgar non-theological way this is called "God's condemnation", but, if one understands this vulgarly and in terms of positive human law-enforcement, one will obtain a sacrilegious calumny on all-merciful God, who in His own words "does judge nobody". Thus, if in "universalism" is meant whether God saves all humans, then the answer is YES, He indeed saves all humans and cannot help saving them according to His nature, which can be defined as "love" (1 John 4:8), however, as being created free, we can reject His love and exactly through this free rejection self-inflict the condemnation on ourselves, His infinite forgiveness notwithstanding; for such real and horrible our freedom and responsibility is.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
Does John teach Universalism? Yes and NO! Let me be more specific. There is an important difference between the **provision** of salvation and the reality of salvation. The Bible clearly teaches that the **provision** of salvation is universal but the **actuality** is not. In the writings of John we have: * John 1:29, “Behold the Lamb of God who takes away the sin of the world.” * John 3:16, “God so loved the world that He gave …” * John 12:32, “I [Jesus] … will draw all people to myself.” * 1 John 2:2, “He Himself [Jesus] is the propitiation for our sins, and not for ours [Christians to whom John writes] only but also for the whole world.” Elsewhere in the Bible we also have: * Acts 17:30, “God … commands all people everywhere to repent.” * Rom 3:23, 24, “… for all have sinned … and all are freely forgiven...” * Rom 5:8, 10, “… while we were still sinners, Christ died for us. … if, while were God’s enemies, we were reconciled to him by the death of His Son, …” * Rom 5:15, “But the free gift is not like the offense. For if by the one man’s [Adam’s] offense many died, much more the grace of God and the gift by the grace of the one Man, Jesus Christ, abounded to the many.” [Note the same word, “many” applies to all people.] * Rom 5:18, “Therefore, as through one man’s offense judgment came to all people, resulting in condemnation, even so through one Man’s righteous act the free gift came to all people, resulting in justification of life.” * Rom 11:32, “For God has imprisoned everyone in disobedience so that He may show mercy to all.” * 2 Cor 5:14, “…we are convinced that one died for all, and therefore all died.” * 2 Cor 5:18, 19, “…God was reconciling the world to Himself in Christ …” * 1 Tim 2:3, 4, “For this is good and acceptable in the sight of God our Saviour, who desires all men to be saved and to come to the knowledge of the truth.” * 1 Tim 2:6, “[Jesus Christ] gave Himself as a ransom for all people.” * Titus 2:11, “For the grace of God appeared bringing salvation to all people.” * Heb 2:9, “But we see Jesus, who was made a little lower than the angels, now crowned with glory and honor because he suffered death, so that by the grace of God he might taste death for everyone.” * 2 Peter 3:9, “The Lord is not slow in keeping his promise, as some understand slowness. He is patient with you, not wanting anyone to perish, but everyone to come to repentance.” * Isa 53:6, “We all like sheep have gone astray … and the LORD has laid on him the iniquity of us all.” Now, the universal **provision** of salvation does not mean that all people will be saved - far from it. For example: * The Bible has many references to the final destruction of the wicked such as Ps 37:28, 92:7, 94:23, Prov 14:11, 2 Thess 2:8-10, Matt 5:29, 30, 10:28, 2 Peter 2:3, 3:6, 7, Rom 9:22, Phil 3:19, Ps 68:2. * The wicked are destroyed because they reject God and choose to be destroyed. Contrast the two groups at the second Advent of Jesus: . o Isa 25:9, “In that day they [the righteous] will say, ‘Surely this is our God; we trusted in him, and he saved us. This is the LORD, we trusted in him; let us rejoice and be glad in his salvation.’” . o Rev 6:16, “They called to the mountains and the rocks, ‘Fall on us and hide us from the face of him who sits on the throne and from the wrath of the Lamb!’” **CONCLUSION** Therefore, the **provision** of salvation is universal but the actuality means that many will reject God's gracious offer to be saved and many wicked will be destroyed.
That the Father sent the Son to be the saviour of the world and that John declares of him ‘Behold the Lamb of God which taketh away the sin of the world’, does not suggest, in any way, a ‘Christian Universalism’, that is to say the notion that, automatically, all humankind shall be saved irrespective of their behaviour, irrespective of faith or irrespective of the purposes of God in salvation. In order that there should be a world to come, at all, necessitated the coming of Christ and the death of Christ. It is clear from what the scriptures teach regarding restoration (unhelpfully translated ‘reconciliation’) that salvation is effected by the death of Christ and by union with Him, under his Headship, in a righteous restoration out from under the headship of Adam and out of the former human state in Adam. Part of this restoration is the fact that Jesus Christ is the Lamb of God who taketh away the ‘sin of the world’ which does not refer to the specific actions of individuals (which is dealt with in other parts of the doctrine of Christ) but refers to the entry of sin into the world from the beginning, in Adam. Being ‘made’ sin, or being effected sin (some translate this as ‘being made a sin offering’ but I suggest that that falls short of the full concept) sin, itself, was condemned within the humanity of Jesus Christ - a clean humanity - and sin was eradicated in the sight of God, righteously. No individual is condemned, personally, for the liability of flesh and blood, or for the propensities of created humanity, or for the failure of man in the flesh, or for the transgression of the head of humanity, Adam. This liability and this sin is taken away by the Saviour and borne by him in his death. That removal, righteously, is necessary for there to be a world at all. That removal was necessary even to grant a continuance to humanity after the Flood. The judgment on the world, by water, was to end all flesh because of the consequences of sin and because of the multiplication of evil on earth to the extent it could not be tolerated any further. Eight persons were preserved and that preservation was in order for the purposes of God to be fulfilled, despite the transgression : a continuance being granted, due to a foreseen sacrifice (by Christ) that gave a righteous basis for the extension of the world, in time, for those divine purposes to progress. Else, in righteousness, there could be no world at all. The world would have ended at the time of the Flood. He is the ‘Saviour of the world’ in that humanity is granted existence, time, forbearance and the testimony of the gospel (whether by figure and ritual under the old covenant, or whether by full revelation under the New Testament) that they might be saved. But if there is unbelief and rejection then that is the responsibility of each individual. And the consequence is to their own account, personally. The further notion that the sufferings of Christ (within his body, prior to his death) were effective for the sins of all humankind (but only if certain individuals took advantage and added their own effectiveness) is nowhere expressed in scripture and is, in effect, salvation by works.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
John is a fascinating philosophical take. Its perception in scholarship has also evolved remarkably. Pretty much everything we thought we knew about John has changed in the 20th century, particularly since the 1980s. There has been new knowledge about John that has come from excavation of the pool of Bethesda to the relationship between the "children of light" and the "beloved teacher" in the documents uncovered in the Qumran scrolls from that community. I'll frame my answer as someone who has gone through a religious trajectory that has included traditional mainline protestantism as well as universalist frameworks. The distinction between universalism and particularism seems to bend around two separate takes. Calvinists, for example, believe in particularism, but that we have no say in the matter at all. This is called double predestination. From the beginning of time, everyone is already sorted into Heaven or Hell, and it is in no way up to us. It is important to note that Calvin was not a determinist. He believed we had enough free will to warrant all of us going to hell, and that it impossible for us to work to develop merit to goto heaven. Salvation was entirely up to God and was already determined. Today, through the theology of Karl Barth and others, the Presbyterians (those who inherit the Reformed church dogma of Calvin) have more of a universalist bent (at least in the PCUSA branch). This particularism is contrast with the catholic, methodist, episcopal, or evangelical doctrine that it is up to us to choose to accept Christ as our own savior. In this mind, we get to choose. And not everyone chooses. So only a particular set goto Heaven. This creates what we call the protestant work ethic upon which the USA is built. Unlike with Catholics, where a priest is all you need for salvation (and he will tell you this), for the protestants, we can never know if we are saved for sure, so we work work work... Given those two kinds of particularism (and they have their defenders in the Bible), Universalism stands in contrast. For a universalist, Jesus descended into hell, kicked open the doors, and all are saved. For the universalist, salvation is also not in our hands (as with the Calvinists). In John, support for this is drawn from the theme of John 1:12-13 where the text says that "for all who received him, he gave the power to become *children of God*, but not by their will or the will of others, but by God." Then in John 6:44 and John 14:6, we have this paradoxical pairing of statements. In 6:44, no one can come to Jesus unless they are "dragged against their will" by the father. The verb here is "[ἑλκύω](https://biblehub.com/greek/1670.htm)" and is a technical term in John used exactly six times. I suggest exploring those uses as it is enlightening and talks much about our ability to participate in our salvation. The BDB Lexicon has: "drag a person forcibly and against his will" And in John 14:6, we have the famous statement that no-one comes to the father except through Jesus. So there is this paradoxical framework that says that none of it us up to us. In fact, you might say that the idea that we have our own free will or merit is questioned entirely in John. The only way is through Jesus, you can't come to Jesus unless dragged against your will by God, and then in [John 12:32](https://biblehub.com/interlinear/john/12-32.htm), we have Jesus' statement that "if he is lifted up [on the cross], then he will drag all to himself." Again, the verb "to drag against your will" is used here, as well as the greek word "πάντας" meaning ALL. So with that trio of verses, you get this round rejection of our role in salvation and a statement that God is in charge of it, especially when coupled with the theme in John 1:12-13 that it is not up to us. Some scholars see a "protology" in John. This is that John points back to Eden. Instead of being born of blood/flesh, we are to be born of water and spirit, just like Adam was. Instead of eating food from the cursed ground, we are to eat food from above (end of John 6). These were the major punishments upon exile from eden. And the "sin" in eden was to reach out and grasp at something against God's will. But that was also paradoxically, the knowledge of right and wrong itself. So before this act, we could not have known right and wrong and would not have been moral agents in the act. Compare this idea to what Jesus says it means to be a child of God in John 5:19, "Jesus said to them, “Very truly, I tell you, the Son can do nothing on his own, but only what he sees the Father doing; for whatever the Father does, the Son does likewise." There is a sense here that Jesus is utterly obedient to God. This again is in contrast to the seeming disobedience in Eden. Furthermore, it would seem that the only reason that a person could reach out to choose to be saved in the first place is if they thought this was a "GOOD" thing to do... which, in the eden context, is more fruit of the knowledge of good and bad. The concept of "dragging against the will" and making it clear that we cannot do it ourselves removes the idea that we are chasing it because we think it is good, or chasing it because we are avoiding hell which we think is bad. In fact, there is simply no other reason that we can move as beings. We only act to achieve what we think is good or avoid what we think is bad. So it is literally impossible for us to act outside of the knowledge of good and bad. Hence you get a take that it simply cannot be up to us that is well supported in John. I'll frame this with some meta-commentary by saying that universalism has persisted throughout Christianity (Origen being one of the first recorded explicitly open Universalists). But it is extremely hard to sell this. There is no value proposition behind Universalism. You walk into a universalist church and they say, "nah, you're good, all are saved." Then you walk out and don't come back. It takes the fear of hell to keep you in the pews, which is why the Universalism doesn't play well. In the early history of the USA, there was a huge backlash against Universalists and Calvinists in a very similar way to the backlash against Atheists. There is an idea that if it is out of your hands, then there will be no motivation for these people to be moral. That is another long take, but it informs why it is challenging to find broad institutional support for Universalism even though it may be well supported in the text.
The greater question of the question posed is, ***“Does Scripture support the Universalism?”*** And do the passages-John 1:29 & 12:47 support the Universalism? **1. The Universalism** (differ from the Universal atonement) The modern-day Universalism -Christian Universalism - is a specific theological term for a belief that **ultimately all human beings - all people/ every person of all human history, and the fallen angelic beings eventually will come into final salvation and spend eternity with God in heaven** (often confused with the universal atonement view -the provision of salvation and our acceptance of the salvation.) (Note: Two main versions: The ultra-Universalism-everyone at death will have the second chance to accept the Salvation and go to heaven; The *Purgationists* - unsaved people after a certain cleansing period, God will free the inhabitants of hell and reconcile them to himself. Now the universalist prefers to call it, Universal restoration, Universal reconciliation, Universal restitution, and Universal salvation, or The victorious Gospel of Grace, Jesus, the Chosen One, Saves All.) The main arguments of the universalist are: * God is love, therefore, He “must” love all and will the salvation for all -all intelligent beings He created. * The loving God by nature would condemn no one to eternal torment in hell, * That after a certain cleansing period, God will free "all" inhabitants of hell and reconcile them to himself. * The word “all (πᾶς)” and the “world” in certain passages have universal implications and support the Universalism -i.e., justification and life(eternal) for “all men” ([Rom. 5:18, 11:32; 1 Cor. 15:22; John 1:29; 4:42; 12:32; Acts 3:21; Col. 1:20; Eph. 1:10; 1 John 2:2; 4:14)](http://localhost:8989/?q=version=ESV%7Creference=John.1.29%20John.4.42%20John.12.32%20Acts.3.21%20Rom.5.18%20Rom.11.32%201Cor.15.22%20Eph.1.10%20Col.1.20%201John.2.2%201John.4.14&options=HNVUG&pos=1) While the argument appears logical, but it is the ***same ol’*** circular reasoning - God cannot be perfect love while punishing sinners in hell. It is a logical fallacy imposing human judgment upon God, defective logic blinded by the love of God for creatures, but blinded to the love of God for His only-begotten Son. It is the faulty logic of **abstracting the eternal attributes of God** revealed in God’s revelations and is the same deception of the serpent first used at the Garden. Universalism ignores the fact that the loving God, forsaken His only-begotten Son, put through a cruel death on the cross to save the created beings who reveled against Him and condemned to eternal damnation in hell. In effect, according to their "perfect love" logic, God is still a failure because He loved created beings but NOT loved His only-begotten Son. Furthermore, according to their line of thinking, the loving and sovereign God could /should have prevented the causes of sin in the first place, and if He did not, He is NOT perfect love; if He could not, He is NOT almighty; if He did not see it coming, He is NOT all-knowing, etc. **All their logics and arguments are to make a total mockery of God of the Scripture!** **In sum**: The Scripture says, "There is a way that seems right to a man, but its end is the way to death" (Proverb 14:12). Here, "right **יָשָׁר**" has ranges of meanings - right, correct, pleasing, and smooth." The Universalism - though more palatable to many - is "***The Devil's Redemption***" (M. McClymond,) and that says it all! **2. The Universal Atonement** The Universal Atonement (Unlimited Atonement -Arminianism), though shares with the Universalism on - i.e., Christ died for all sins of the world, it entirely differs with it- from the scope and efficacy of the atonement to eschatological outcome. Most importantly, no human judgments on God and His Word- the Scripture! The universal atonement is one of the 5 points that differ from the limited atonement (Calvinism). Both Calvinism and Arminianism -two opposing views- have good Scriptural supports for all their 5 points, yet both are in agreement on the main point - Salvation by grace through the "faith" in Jesus Christ. One thing is clear: a) that two opposing views -as they are- cannot be right, nor totally represent the Scripture on every and all doctrinal points, unless both come to the Scripture. b) And also one’s belief in the scope of Christ's Atonement, and theological affiliation and familiarity of doctrines does not “save,” but the Word of Jesus gives the life ([John 6:63](http://localhost:8989/?q=version=ESV%7Creference=John.6.63&options=HNVUG&pos=1)). Jesus said, “truly, truly I say, unless one is born of water and the Spirit, he cannot enter the kingdom of God” (John 3:5), "Whoever has the Son has life; whoever does not have the Son of God does not have life (1John 5:12), “Blessed rather are those who hear the word of God and keep it" ([Luke 11:28](http://localhost:8989/?q=version=ESV%7Creference=Luke.11.28&options=HNVUG&pos=1)). Jesus says, "But to all who did receive him, who believed in his name, he gave the right to become children of God" (John 1:12-ESV). In Revelation, "And if anyone’s name was not found written in the book of life, he was thrown into the lake of fire" (Rev. 20:15). The Holy Spirit is the spirit of the truth, and He will guide and teach us the Word ([John 15:26,16:13](http://localhost:8989/?q=version=ESV%7Creference=John.15.26%20John.16.13&options=HNVUG&pos=1)). NO theologians and bible teachers can come to your help on that day. * \*\*Sola scriptura * Sola fide * Sola gratia * Solus Christus * Soli Deo gloria\*\* **3. Do John 1:29 & 12: 47 support the Universalism?** The text John 1:29 connotes the universal atonement, but NOT the universalism. John 12:47 (& 48), the very words - if any man hears my words, and believe not… the word that I have spoken will judge… speak against the Universalism. In sum, in the immediate, larger, and context of the whole Bible, are many conditional/restrictive words against Universalism.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
The greater question of the question posed is, ***“Does Scripture support the Universalism?”*** And do the passages-John 1:29 & 12:47 support the Universalism? **1. The Universalism** (differ from the Universal atonement) The modern-day Universalism -Christian Universalism - is a specific theological term for a belief that **ultimately all human beings - all people/ every person of all human history, and the fallen angelic beings eventually will come into final salvation and spend eternity with God in heaven** (often confused with the universal atonement view -the provision of salvation and our acceptance of the salvation.) (Note: Two main versions: The ultra-Universalism-everyone at death will have the second chance to accept the Salvation and go to heaven; The *Purgationists* - unsaved people after a certain cleansing period, God will free the inhabitants of hell and reconcile them to himself. Now the universalist prefers to call it, Universal restoration, Universal reconciliation, Universal restitution, and Universal salvation, or The victorious Gospel of Grace, Jesus, the Chosen One, Saves All.) The main arguments of the universalist are: * God is love, therefore, He “must” love all and will the salvation for all -all intelligent beings He created. * The loving God by nature would condemn no one to eternal torment in hell, * That after a certain cleansing period, God will free "all" inhabitants of hell and reconcile them to himself. * The word “all (πᾶς)” and the “world” in certain passages have universal implications and support the Universalism -i.e., justification and life(eternal) for “all men” ([Rom. 5:18, 11:32; 1 Cor. 15:22; John 1:29; 4:42; 12:32; Acts 3:21; Col. 1:20; Eph. 1:10; 1 John 2:2; 4:14)](http://localhost:8989/?q=version=ESV%7Creference=John.1.29%20John.4.42%20John.12.32%20Acts.3.21%20Rom.5.18%20Rom.11.32%201Cor.15.22%20Eph.1.10%20Col.1.20%201John.2.2%201John.4.14&options=HNVUG&pos=1) While the argument appears logical, but it is the ***same ol’*** circular reasoning - God cannot be perfect love while punishing sinners in hell. It is a logical fallacy imposing human judgment upon God, defective logic blinded by the love of God for creatures, but blinded to the love of God for His only-begotten Son. It is the faulty logic of **abstracting the eternal attributes of God** revealed in God’s revelations and is the same deception of the serpent first used at the Garden. Universalism ignores the fact that the loving God, forsaken His only-begotten Son, put through a cruel death on the cross to save the created beings who reveled against Him and condemned to eternal damnation in hell. In effect, according to their "perfect love" logic, God is still a failure because He loved created beings but NOT loved His only-begotten Son. Furthermore, according to their line of thinking, the loving and sovereign God could /should have prevented the causes of sin in the first place, and if He did not, He is NOT perfect love; if He could not, He is NOT almighty; if He did not see it coming, He is NOT all-knowing, etc. **All their logics and arguments are to make a total mockery of God of the Scripture!** **In sum**: The Scripture says, "There is a way that seems right to a man, but its end is the way to death" (Proverb 14:12). Here, "right **יָשָׁר**" has ranges of meanings - right, correct, pleasing, and smooth." The Universalism - though more palatable to many - is "***The Devil's Redemption***" (M. McClymond,) and that says it all! **2. The Universal Atonement** The Universal Atonement (Unlimited Atonement -Arminianism), though shares with the Universalism on - i.e., Christ died for all sins of the world, it entirely differs with it- from the scope and efficacy of the atonement to eschatological outcome. Most importantly, no human judgments on God and His Word- the Scripture! The universal atonement is one of the 5 points that differ from the limited atonement (Calvinism). Both Calvinism and Arminianism -two opposing views- have good Scriptural supports for all their 5 points, yet both are in agreement on the main point - Salvation by grace through the "faith" in Jesus Christ. One thing is clear: a) that two opposing views -as they are- cannot be right, nor totally represent the Scripture on every and all doctrinal points, unless both come to the Scripture. b) And also one’s belief in the scope of Christ's Atonement, and theological affiliation and familiarity of doctrines does not “save,” but the Word of Jesus gives the life ([John 6:63](http://localhost:8989/?q=version=ESV%7Creference=John.6.63&options=HNVUG&pos=1)). Jesus said, “truly, truly I say, unless one is born of water and the Spirit, he cannot enter the kingdom of God” (John 3:5), "Whoever has the Son has life; whoever does not have the Son of God does not have life (1John 5:12), “Blessed rather are those who hear the word of God and keep it" ([Luke 11:28](http://localhost:8989/?q=version=ESV%7Creference=Luke.11.28&options=HNVUG&pos=1)). Jesus says, "But to all who did receive him, who believed in his name, he gave the right to become children of God" (John 1:12-ESV). In Revelation, "And if anyone’s name was not found written in the book of life, he was thrown into the lake of fire" (Rev. 20:15). The Holy Spirit is the spirit of the truth, and He will guide and teach us the Word ([John 15:26,16:13](http://localhost:8989/?q=version=ESV%7Creference=John.15.26%20John.16.13&options=HNVUG&pos=1)). NO theologians and bible teachers can come to your help on that day. * \*\*Sola scriptura * Sola fide * Sola gratia * Solus Christus * Soli Deo gloria\*\* **3. Do John 1:29 & 12: 47 support the Universalism?** The text John 1:29 connotes the universal atonement, but NOT the universalism. John 12:47 (& 48), the very words - if any man hears my words, and believe not… the word that I have spoken will judge… speak against the Universalism. In sum, in the immediate, larger, and context of the whole Bible, are many conditional/restrictive words against Universalism.
The question is a bit ambiguous, for it gives two quotes - John 1:29 an John 12:47 - which have quite different connotations: the first clearly shows that according to John Jesus' ministry is for the entire world and not just for one chosen nation of Jews, and there are quite a few passages in John that confirm the same. Thus, if in "universalism" is meant this, then of course, quite unambiguously, John's Gospel speaks about it. However, the second quotation speaks about semantics of divine judgment and gives to this term a new twist, for we learn that Jesus who is God and equal to Father does not judge and neither does Father (John 5:22), but how then is God still the Judge who will judge all mankind? When names are applied to God, they change meaning drastically, and thus, we learn that God-the Judge does not judge - and if does not judge, then also does not condemn, for condemning is just a portion of judgment, which is a more general category - in the sense that He only forgives, He only loves, He only forbears, infinitely so, for He cannot help loving His creatures created in His image and likeness. Yet, when we reject all those divine actions towards us, close our hearts from them, then we condemn ourselves through the breach of communion with God and in a vulgar non-theological way this is called "God's condemnation", but, if one understands this vulgarly and in terms of positive human law-enforcement, one will obtain a sacrilegious calumny on all-merciful God, who in His own words "does judge nobody". Thus, if in "universalism" is meant whether God saves all humans, then the answer is YES, He indeed saves all humans and cannot help saving them according to His nature, which can be defined as "love" (1 John 4:8), however, as being created free, we can reject His love and exactly through this free rejection self-inflict the condemnation on ourselves, His infinite forgiveness notwithstanding; for such real and horrible our freedom and responsibility is.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
Does John teach Universalism? Yes and NO! Let me be more specific. There is an important difference between the **provision** of salvation and the reality of salvation. The Bible clearly teaches that the **provision** of salvation is universal but the **actuality** is not. In the writings of John we have: * John 1:29, “Behold the Lamb of God who takes away the sin of the world.” * John 3:16, “God so loved the world that He gave …” * John 12:32, “I [Jesus] … will draw all people to myself.” * 1 John 2:2, “He Himself [Jesus] is the propitiation for our sins, and not for ours [Christians to whom John writes] only but also for the whole world.” Elsewhere in the Bible we also have: * Acts 17:30, “God … commands all people everywhere to repent.” * Rom 3:23, 24, “… for all have sinned … and all are freely forgiven...” * Rom 5:8, 10, “… while we were still sinners, Christ died for us. … if, while were God’s enemies, we were reconciled to him by the death of His Son, …” * Rom 5:15, “But the free gift is not like the offense. For if by the one man’s [Adam’s] offense many died, much more the grace of God and the gift by the grace of the one Man, Jesus Christ, abounded to the many.” [Note the same word, “many” applies to all people.] * Rom 5:18, “Therefore, as through one man’s offense judgment came to all people, resulting in condemnation, even so through one Man’s righteous act the free gift came to all people, resulting in justification of life.” * Rom 11:32, “For God has imprisoned everyone in disobedience so that He may show mercy to all.” * 2 Cor 5:14, “…we are convinced that one died for all, and therefore all died.” * 2 Cor 5:18, 19, “…God was reconciling the world to Himself in Christ …” * 1 Tim 2:3, 4, “For this is good and acceptable in the sight of God our Saviour, who desires all men to be saved and to come to the knowledge of the truth.” * 1 Tim 2:6, “[Jesus Christ] gave Himself as a ransom for all people.” * Titus 2:11, “For the grace of God appeared bringing salvation to all people.” * Heb 2:9, “But we see Jesus, who was made a little lower than the angels, now crowned with glory and honor because he suffered death, so that by the grace of God he might taste death for everyone.” * 2 Peter 3:9, “The Lord is not slow in keeping his promise, as some understand slowness. He is patient with you, not wanting anyone to perish, but everyone to come to repentance.” * Isa 53:6, “We all like sheep have gone astray … and the LORD has laid on him the iniquity of us all.” Now, the universal **provision** of salvation does not mean that all people will be saved - far from it. For example: * The Bible has many references to the final destruction of the wicked such as Ps 37:28, 92:7, 94:23, Prov 14:11, 2 Thess 2:8-10, Matt 5:29, 30, 10:28, 2 Peter 2:3, 3:6, 7, Rom 9:22, Phil 3:19, Ps 68:2. * The wicked are destroyed because they reject God and choose to be destroyed. Contrast the two groups at the second Advent of Jesus: . o Isa 25:9, “In that day they [the righteous] will say, ‘Surely this is our God; we trusted in him, and he saved us. This is the LORD, we trusted in him; let us rejoice and be glad in his salvation.’” . o Rev 6:16, “They called to the mountains and the rocks, ‘Fall on us and hide us from the face of him who sits on the throne and from the wrath of the Lamb!’” **CONCLUSION** Therefore, the **provision** of salvation is universal but the actuality means that many will reject God's gracious offer to be saved and many wicked will be destroyed.
The greater question of the question posed is, ***“Does Scripture support the Universalism?”*** And do the passages-John 1:29 & 12:47 support the Universalism? **1. The Universalism** (differ from the Universal atonement) The modern-day Universalism -Christian Universalism - is a specific theological term for a belief that **ultimately all human beings - all people/ every person of all human history, and the fallen angelic beings eventually will come into final salvation and spend eternity with God in heaven** (often confused with the universal atonement view -the provision of salvation and our acceptance of the salvation.) (Note: Two main versions: The ultra-Universalism-everyone at death will have the second chance to accept the Salvation and go to heaven; The *Purgationists* - unsaved people after a certain cleansing period, God will free the inhabitants of hell and reconcile them to himself. Now the universalist prefers to call it, Universal restoration, Universal reconciliation, Universal restitution, and Universal salvation, or The victorious Gospel of Grace, Jesus, the Chosen One, Saves All.) The main arguments of the universalist are: * God is love, therefore, He “must” love all and will the salvation for all -all intelligent beings He created. * The loving God by nature would condemn no one to eternal torment in hell, * That after a certain cleansing period, God will free "all" inhabitants of hell and reconcile them to himself. * The word “all (πᾶς)” and the “world” in certain passages have universal implications and support the Universalism -i.e., justification and life(eternal) for “all men” ([Rom. 5:18, 11:32; 1 Cor. 15:22; John 1:29; 4:42; 12:32; Acts 3:21; Col. 1:20; Eph. 1:10; 1 John 2:2; 4:14)](http://localhost:8989/?q=version=ESV%7Creference=John.1.29%20John.4.42%20John.12.32%20Acts.3.21%20Rom.5.18%20Rom.11.32%201Cor.15.22%20Eph.1.10%20Col.1.20%201John.2.2%201John.4.14&options=HNVUG&pos=1) While the argument appears logical, but it is the ***same ol’*** circular reasoning - God cannot be perfect love while punishing sinners in hell. It is a logical fallacy imposing human judgment upon God, defective logic blinded by the love of God for creatures, but blinded to the love of God for His only-begotten Son. It is the faulty logic of **abstracting the eternal attributes of God** revealed in God’s revelations and is the same deception of the serpent first used at the Garden. Universalism ignores the fact that the loving God, forsaken His only-begotten Son, put through a cruel death on the cross to save the created beings who reveled against Him and condemned to eternal damnation in hell. In effect, according to their "perfect love" logic, God is still a failure because He loved created beings but NOT loved His only-begotten Son. Furthermore, according to their line of thinking, the loving and sovereign God could /should have prevented the causes of sin in the first place, and if He did not, He is NOT perfect love; if He could not, He is NOT almighty; if He did not see it coming, He is NOT all-knowing, etc. **All their logics and arguments are to make a total mockery of God of the Scripture!** **In sum**: The Scripture says, "There is a way that seems right to a man, but its end is the way to death" (Proverb 14:12). Here, "right **יָשָׁר**" has ranges of meanings - right, correct, pleasing, and smooth." The Universalism - though more palatable to many - is "***The Devil's Redemption***" (M. McClymond,) and that says it all! **2. The Universal Atonement** The Universal Atonement (Unlimited Atonement -Arminianism), though shares with the Universalism on - i.e., Christ died for all sins of the world, it entirely differs with it- from the scope and efficacy of the atonement to eschatological outcome. Most importantly, no human judgments on God and His Word- the Scripture! The universal atonement is one of the 5 points that differ from the limited atonement (Calvinism). Both Calvinism and Arminianism -two opposing views- have good Scriptural supports for all their 5 points, yet both are in agreement on the main point - Salvation by grace through the "faith" in Jesus Christ. One thing is clear: a) that two opposing views -as they are- cannot be right, nor totally represent the Scripture on every and all doctrinal points, unless both come to the Scripture. b) And also one’s belief in the scope of Christ's Atonement, and theological affiliation and familiarity of doctrines does not “save,” but the Word of Jesus gives the life ([John 6:63](http://localhost:8989/?q=version=ESV%7Creference=John.6.63&options=HNVUG&pos=1)). Jesus said, “truly, truly I say, unless one is born of water and the Spirit, he cannot enter the kingdom of God” (John 3:5), "Whoever has the Son has life; whoever does not have the Son of God does not have life (1John 5:12), “Blessed rather are those who hear the word of God and keep it" ([Luke 11:28](http://localhost:8989/?q=version=ESV%7Creference=Luke.11.28&options=HNVUG&pos=1)). Jesus says, "But to all who did receive him, who believed in his name, he gave the right to become children of God" (John 1:12-ESV). In Revelation, "And if anyone’s name was not found written in the book of life, he was thrown into the lake of fire" (Rev. 20:15). The Holy Spirit is the spirit of the truth, and He will guide and teach us the Word ([John 15:26,16:13](http://localhost:8989/?q=version=ESV%7Creference=John.15.26%20John.16.13&options=HNVUG&pos=1)). NO theologians and bible teachers can come to your help on that day. * \*\*Sola scriptura * Sola fide * Sola gratia * Solus Christus * Soli Deo gloria\*\* **3. Do John 1:29 & 12: 47 support the Universalism?** The text John 1:29 connotes the universal atonement, but NOT the universalism. John 12:47 (& 48), the very words - if any man hears my words, and believe not… the word that I have spoken will judge… speak against the Universalism. In sum, in the immediate, larger, and context of the whole Bible, are many conditional/restrictive words against Universalism.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
Does John teach Universalism? Yes and NO! Let me be more specific. There is an important difference between the **provision** of salvation and the reality of salvation. The Bible clearly teaches that the **provision** of salvation is universal but the **actuality** is not. In the writings of John we have: * John 1:29, “Behold the Lamb of God who takes away the sin of the world.” * John 3:16, “God so loved the world that He gave …” * John 12:32, “I [Jesus] … will draw all people to myself.” * 1 John 2:2, “He Himself [Jesus] is the propitiation for our sins, and not for ours [Christians to whom John writes] only but also for the whole world.” Elsewhere in the Bible we also have: * Acts 17:30, “God … commands all people everywhere to repent.” * Rom 3:23, 24, “… for all have sinned … and all are freely forgiven...” * Rom 5:8, 10, “… while we were still sinners, Christ died for us. … if, while were God’s enemies, we were reconciled to him by the death of His Son, …” * Rom 5:15, “But the free gift is not like the offense. For if by the one man’s [Adam’s] offense many died, much more the grace of God and the gift by the grace of the one Man, Jesus Christ, abounded to the many.” [Note the same word, “many” applies to all people.] * Rom 5:18, “Therefore, as through one man’s offense judgment came to all people, resulting in condemnation, even so through one Man’s righteous act the free gift came to all people, resulting in justification of life.” * Rom 11:32, “For God has imprisoned everyone in disobedience so that He may show mercy to all.” * 2 Cor 5:14, “…we are convinced that one died for all, and therefore all died.” * 2 Cor 5:18, 19, “…God was reconciling the world to Himself in Christ …” * 1 Tim 2:3, 4, “For this is good and acceptable in the sight of God our Saviour, who desires all men to be saved and to come to the knowledge of the truth.” * 1 Tim 2:6, “[Jesus Christ] gave Himself as a ransom for all people.” * Titus 2:11, “For the grace of God appeared bringing salvation to all people.” * Heb 2:9, “But we see Jesus, who was made a little lower than the angels, now crowned with glory and honor because he suffered death, so that by the grace of God he might taste death for everyone.” * 2 Peter 3:9, “The Lord is not slow in keeping his promise, as some understand slowness. He is patient with you, not wanting anyone to perish, but everyone to come to repentance.” * Isa 53:6, “We all like sheep have gone astray … and the LORD has laid on him the iniquity of us all.” Now, the universal **provision** of salvation does not mean that all people will be saved - far from it. For example: * The Bible has many references to the final destruction of the wicked such as Ps 37:28, 92:7, 94:23, Prov 14:11, 2 Thess 2:8-10, Matt 5:29, 30, 10:28, 2 Peter 2:3, 3:6, 7, Rom 9:22, Phil 3:19, Ps 68:2. * The wicked are destroyed because they reject God and choose to be destroyed. Contrast the two groups at the second Advent of Jesus: . o Isa 25:9, “In that day they [the righteous] will say, ‘Surely this is our God; we trusted in him, and he saved us. This is the LORD, we trusted in him; let us rejoice and be glad in his salvation.’” . o Rev 6:16, “They called to the mountains and the rocks, ‘Fall on us and hide us from the face of him who sits on the throne and from the wrath of the Lamb!’” **CONCLUSION** Therefore, the **provision** of salvation is universal but the actuality means that many will reject God's gracious offer to be saved and many wicked will be destroyed.
John is a fascinating philosophical take. Its perception in scholarship has also evolved remarkably. Pretty much everything we thought we knew about John has changed in the 20th century, particularly since the 1980s. There has been new knowledge about John that has come from excavation of the pool of Bethesda to the relationship between the "children of light" and the "beloved teacher" in the documents uncovered in the Qumran scrolls from that community. I'll frame my answer as someone who has gone through a religious trajectory that has included traditional mainline protestantism as well as universalist frameworks. The distinction between universalism and particularism seems to bend around two separate takes. Calvinists, for example, believe in particularism, but that we have no say in the matter at all. This is called double predestination. From the beginning of time, everyone is already sorted into Heaven or Hell, and it is in no way up to us. It is important to note that Calvin was not a determinist. He believed we had enough free will to warrant all of us going to hell, and that it impossible for us to work to develop merit to goto heaven. Salvation was entirely up to God and was already determined. Today, through the theology of Karl Barth and others, the Presbyterians (those who inherit the Reformed church dogma of Calvin) have more of a universalist bent (at least in the PCUSA branch). This particularism is contrast with the catholic, methodist, episcopal, or evangelical doctrine that it is up to us to choose to accept Christ as our own savior. In this mind, we get to choose. And not everyone chooses. So only a particular set goto Heaven. This creates what we call the protestant work ethic upon which the USA is built. Unlike with Catholics, where a priest is all you need for salvation (and he will tell you this), for the protestants, we can never know if we are saved for sure, so we work work work... Given those two kinds of particularism (and they have their defenders in the Bible), Universalism stands in contrast. For a universalist, Jesus descended into hell, kicked open the doors, and all are saved. For the universalist, salvation is also not in our hands (as with the Calvinists). In John, support for this is drawn from the theme of John 1:12-13 where the text says that "for all who received him, he gave the power to become *children of God*, but not by their will or the will of others, but by God." Then in John 6:44 and John 14:6, we have this paradoxical pairing of statements. In 6:44, no one can come to Jesus unless they are "dragged against their will" by the father. The verb here is "[ἑλκύω](https://biblehub.com/greek/1670.htm)" and is a technical term in John used exactly six times. I suggest exploring those uses as it is enlightening and talks much about our ability to participate in our salvation. The BDB Lexicon has: "drag a person forcibly and against his will" And in John 14:6, we have the famous statement that no-one comes to the father except through Jesus. So there is this paradoxical framework that says that none of it us up to us. In fact, you might say that the idea that we have our own free will or merit is questioned entirely in John. The only way is through Jesus, you can't come to Jesus unless dragged against your will by God, and then in [John 12:32](https://biblehub.com/interlinear/john/12-32.htm), we have Jesus' statement that "if he is lifted up [on the cross], then he will drag all to himself." Again, the verb "to drag against your will" is used here, as well as the greek word "πάντας" meaning ALL. So with that trio of verses, you get this round rejection of our role in salvation and a statement that God is in charge of it, especially when coupled with the theme in John 1:12-13 that it is not up to us. Some scholars see a "protology" in John. This is that John points back to Eden. Instead of being born of blood/flesh, we are to be born of water and spirit, just like Adam was. Instead of eating food from the cursed ground, we are to eat food from above (end of John 6). These were the major punishments upon exile from eden. And the "sin" in eden was to reach out and grasp at something against God's will. But that was also paradoxically, the knowledge of right and wrong itself. So before this act, we could not have known right and wrong and would not have been moral agents in the act. Compare this idea to what Jesus says it means to be a child of God in John 5:19, "Jesus said to them, “Very truly, I tell you, the Son can do nothing on his own, but only what he sees the Father doing; for whatever the Father does, the Son does likewise." There is a sense here that Jesus is utterly obedient to God. This again is in contrast to the seeming disobedience in Eden. Furthermore, it would seem that the only reason that a person could reach out to choose to be saved in the first place is if they thought this was a "GOOD" thing to do... which, in the eden context, is more fruit of the knowledge of good and bad. The concept of "dragging against the will" and making it clear that we cannot do it ourselves removes the idea that we are chasing it because we think it is good, or chasing it because we are avoiding hell which we think is bad. In fact, there is simply no other reason that we can move as beings. We only act to achieve what we think is good or avoid what we think is bad. So it is literally impossible for us to act outside of the knowledge of good and bad. Hence you get a take that it simply cannot be up to us that is well supported in John. I'll frame this with some meta-commentary by saying that universalism has persisted throughout Christianity (Origen being one of the first recorded explicitly open Universalists). But it is extremely hard to sell this. There is no value proposition behind Universalism. You walk into a universalist church and they say, "nah, you're good, all are saved." Then you walk out and don't come back. It takes the fear of hell to keep you in the pews, which is why the Universalism doesn't play well. In the early history of the USA, there was a huge backlash against Universalists and Calvinists in a very similar way to the backlash against Atheists. There is an idea that if it is out of your hands, then there will be no motivation for these people to be moral. That is another long take, but it informs why it is challenging to find broad institutional support for Universalism even though it may be well supported in the text.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
That the Father sent the Son to be the saviour of the world and that John declares of him ‘Behold the Lamb of God which taketh away the sin of the world’, does not suggest, in any way, a ‘Christian Universalism’, that is to say the notion that, automatically, all humankind shall be saved irrespective of their behaviour, irrespective of faith or irrespective of the purposes of God in salvation. In order that there should be a world to come, at all, necessitated the coming of Christ and the death of Christ. It is clear from what the scriptures teach regarding restoration (unhelpfully translated ‘reconciliation’) that salvation is effected by the death of Christ and by union with Him, under his Headship, in a righteous restoration out from under the headship of Adam and out of the former human state in Adam. Part of this restoration is the fact that Jesus Christ is the Lamb of God who taketh away the ‘sin of the world’ which does not refer to the specific actions of individuals (which is dealt with in other parts of the doctrine of Christ) but refers to the entry of sin into the world from the beginning, in Adam. Being ‘made’ sin, or being effected sin (some translate this as ‘being made a sin offering’ but I suggest that that falls short of the full concept) sin, itself, was condemned within the humanity of Jesus Christ - a clean humanity - and sin was eradicated in the sight of God, righteously. No individual is condemned, personally, for the liability of flesh and blood, or for the propensities of created humanity, or for the failure of man in the flesh, or for the transgression of the head of humanity, Adam. This liability and this sin is taken away by the Saviour and borne by him in his death. That removal, righteously, is necessary for there to be a world at all. That removal was necessary even to grant a continuance to humanity after the Flood. The judgment on the world, by water, was to end all flesh because of the consequences of sin and because of the multiplication of evil on earth to the extent it could not be tolerated any further. Eight persons were preserved and that preservation was in order for the purposes of God to be fulfilled, despite the transgression : a continuance being granted, due to a foreseen sacrifice (by Christ) that gave a righteous basis for the extension of the world, in time, for those divine purposes to progress. Else, in righteousness, there could be no world at all. The world would have ended at the time of the Flood. He is the ‘Saviour of the world’ in that humanity is granted existence, time, forbearance and the testimony of the gospel (whether by figure and ritual under the old covenant, or whether by full revelation under the New Testament) that they might be saved. But if there is unbelief and rejection then that is the responsibility of each individual. And the consequence is to their own account, personally. The further notion that the sufferings of Christ (within his body, prior to his death) were effective for the sins of all humankind (but only if certain individuals took advantage and added their own effectiveness) is nowhere expressed in scripture and is, in effect, salvation by works.
The question is a bit ambiguous, for it gives two quotes - John 1:29 an John 12:47 - which have quite different connotations: the first clearly shows that according to John Jesus' ministry is for the entire world and not just for one chosen nation of Jews, and there are quite a few passages in John that confirm the same. Thus, if in "universalism" is meant this, then of course, quite unambiguously, John's Gospel speaks about it. However, the second quotation speaks about semantics of divine judgment and gives to this term a new twist, for we learn that Jesus who is God and equal to Father does not judge and neither does Father (John 5:22), but how then is God still the Judge who will judge all mankind? When names are applied to God, they change meaning drastically, and thus, we learn that God-the Judge does not judge - and if does not judge, then also does not condemn, for condemning is just a portion of judgment, which is a more general category - in the sense that He only forgives, He only loves, He only forbears, infinitely so, for He cannot help loving His creatures created in His image and likeness. Yet, when we reject all those divine actions towards us, close our hearts from them, then we condemn ourselves through the breach of communion with God and in a vulgar non-theological way this is called "God's condemnation", but, if one understands this vulgarly and in terms of positive human law-enforcement, one will obtain a sacrilegious calumny on all-merciful God, who in His own words "does judge nobody". Thus, if in "universalism" is meant whether God saves all humans, then the answer is YES, He indeed saves all humans and cannot help saving them according to His nature, which can be defined as "love" (1 John 4:8), however, as being created free, we can reject His love and exactly through this free rejection self-inflict the condemnation on ourselves, His infinite forgiveness notwithstanding; for such real and horrible our freedom and responsibility is.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
I believe the correct answer is YES. In John 1:7 > > The same came for a witness, to bear witness of the Light, that **all men through him might believe**. > > > John 3:17 states that God sent the Son, who is the God's Word to save the world > > For God did not send his Son into the world to condemn the world, but to **save the world through him**. > > > according to Isaiah 55:11 the word will not return to God **until it accomplishes it's purpose** John 17:1-2 > > These words spake Jesus, and lifted up his eyes to heaven, and said, Father, the hour is come; glorify thy Son, that thy Son also may glorify thee: > > > As thou hast **given him power over all flesh**, that he should **give eternal life to as many as thou hast given him** > > > John 17:6-8 establishes that at that point only some were saved because only some out of the world had believed. > > I have manifested thy name unto **the men which thou gavest me out of the world**: thine they were, and thou gavest them me; and they have kept thy word. > > > Now they have known that all things whatsoever thou hast given me are of thee. > > > For I have given unto them the words which thou gavest me; and **they have received them, and have known surely that I came out from thee, and they have believed that thou didst send me**. > > > John 17:9 confirms that at this point this is only about the apostles > > I pray for them: **I pray not for the world**, but for them which thou hast given me; for they are thine. > > > later in the prayer Jesus expands the target: John 17:20 > > Neither pray I for these alone, but **for them also which shall believe on me through their word** > > > on 17:21 Jesus says that the entire world WILL believe that the Father sent Him (like the first group in 17:8) > > That they all may be one; as thou, Father, art in me, and I in thee, that they also may be one in us: **that the world may believe that thou hast sent me**. > > > Now, all these "might" and "may" that we see in 1:7, 17:2 and 17:21 are not mere possibilities, they express a purpose, an implication. These "may" are known as subjunctives, and are being used in Purpose Clauses and they indicate something that is not necessarily yet true, but that will be the outcome if the first part of the sentence occurs. See [this article](https://www.billmounce.com/monday-with-mounce/my-second-thoughts-about-subjunctives-purpose-clauses) from the greek scholar Bill Mounce (who is the founder and President of BiblicalTraining.org, serves on the Committee for Bible Translation, was the New Testament Chair for the ESV, and has written the best-selling biblical Greek textbook, Basics of Biblical Greek, and many other Greek resources)
The greater question of the question posed is, ***“Does Scripture support the Universalism?”*** And do the passages-John 1:29 & 12:47 support the Universalism? **1. The Universalism** (differ from the Universal atonement) The modern-day Universalism -Christian Universalism - is a specific theological term for a belief that **ultimately all human beings - all people/ every person of all human history, and the fallen angelic beings eventually will come into final salvation and spend eternity with God in heaven** (often confused with the universal atonement view -the provision of salvation and our acceptance of the salvation.) (Note: Two main versions: The ultra-Universalism-everyone at death will have the second chance to accept the Salvation and go to heaven; The *Purgationists* - unsaved people after a certain cleansing period, God will free the inhabitants of hell and reconcile them to himself. Now the universalist prefers to call it, Universal restoration, Universal reconciliation, Universal restitution, and Universal salvation, or The victorious Gospel of Grace, Jesus, the Chosen One, Saves All.) The main arguments of the universalist are: * God is love, therefore, He “must” love all and will the salvation for all -all intelligent beings He created. * The loving God by nature would condemn no one to eternal torment in hell, * That after a certain cleansing period, God will free "all" inhabitants of hell and reconcile them to himself. * The word “all (πᾶς)” and the “world” in certain passages have universal implications and support the Universalism -i.e., justification and life(eternal) for “all men” ([Rom. 5:18, 11:32; 1 Cor. 15:22; John 1:29; 4:42; 12:32; Acts 3:21; Col. 1:20; Eph. 1:10; 1 John 2:2; 4:14)](http://localhost:8989/?q=version=ESV%7Creference=John.1.29%20John.4.42%20John.12.32%20Acts.3.21%20Rom.5.18%20Rom.11.32%201Cor.15.22%20Eph.1.10%20Col.1.20%201John.2.2%201John.4.14&options=HNVUG&pos=1) While the argument appears logical, but it is the ***same ol’*** circular reasoning - God cannot be perfect love while punishing sinners in hell. It is a logical fallacy imposing human judgment upon God, defective logic blinded by the love of God for creatures, but blinded to the love of God for His only-begotten Son. It is the faulty logic of **abstracting the eternal attributes of God** revealed in God’s revelations and is the same deception of the serpent first used at the Garden. Universalism ignores the fact that the loving God, forsaken His only-begotten Son, put through a cruel death on the cross to save the created beings who reveled against Him and condemned to eternal damnation in hell. In effect, according to their "perfect love" logic, God is still a failure because He loved created beings but NOT loved His only-begotten Son. Furthermore, according to their line of thinking, the loving and sovereign God could /should have prevented the causes of sin in the first place, and if He did not, He is NOT perfect love; if He could not, He is NOT almighty; if He did not see it coming, He is NOT all-knowing, etc. **All their logics and arguments are to make a total mockery of God of the Scripture!** **In sum**: The Scripture says, "There is a way that seems right to a man, but its end is the way to death" (Proverb 14:12). Here, "right **יָשָׁר**" has ranges of meanings - right, correct, pleasing, and smooth." The Universalism - though more palatable to many - is "***The Devil's Redemption***" (M. McClymond,) and that says it all! **2. The Universal Atonement** The Universal Atonement (Unlimited Atonement -Arminianism), though shares with the Universalism on - i.e., Christ died for all sins of the world, it entirely differs with it- from the scope and efficacy of the atonement to eschatological outcome. Most importantly, no human judgments on God and His Word- the Scripture! The universal atonement is one of the 5 points that differ from the limited atonement (Calvinism). Both Calvinism and Arminianism -two opposing views- have good Scriptural supports for all their 5 points, yet both are in agreement on the main point - Salvation by grace through the "faith" in Jesus Christ. One thing is clear: a) that two opposing views -as they are- cannot be right, nor totally represent the Scripture on every and all doctrinal points, unless both come to the Scripture. b) And also one’s belief in the scope of Christ's Atonement, and theological affiliation and familiarity of doctrines does not “save,” but the Word of Jesus gives the life ([John 6:63](http://localhost:8989/?q=version=ESV%7Creference=John.6.63&options=HNVUG&pos=1)). Jesus said, “truly, truly I say, unless one is born of water and the Spirit, he cannot enter the kingdom of God” (John 3:5), "Whoever has the Son has life; whoever does not have the Son of God does not have life (1John 5:12), “Blessed rather are those who hear the word of God and keep it" ([Luke 11:28](http://localhost:8989/?q=version=ESV%7Creference=Luke.11.28&options=HNVUG&pos=1)). Jesus says, "But to all who did receive him, who believed in his name, he gave the right to become children of God" (John 1:12-ESV). In Revelation, "And if anyone’s name was not found written in the book of life, he was thrown into the lake of fire" (Rev. 20:15). The Holy Spirit is the spirit of the truth, and He will guide and teach us the Word ([John 15:26,16:13](http://localhost:8989/?q=version=ESV%7Creference=John.15.26%20John.16.13&options=HNVUG&pos=1)). NO theologians and bible teachers can come to your help on that day. * \*\*Sola scriptura * Sola fide * Sola gratia * Solus Christus * Soli Deo gloria\*\* **3. Do John 1:29 & 12: 47 support the Universalism?** The text John 1:29 connotes the universal atonement, but NOT the universalism. John 12:47 (& 48), the very words - if any man hears my words, and believe not… the word that I have spoken will judge… speak against the Universalism. In sum, in the immediate, larger, and context of the whole Bible, are many conditional/restrictive words against Universalism.
52,725
John 1:29 KJV The next day John seeth Jesus coming unto him, and saith, Behold the Lamb of God, which taketh away the sin of the world. John 12:47 KJV And if any man hear my words, and believe not, I judge him not: for I came not to judge the world, but to save the world.
2020/10/31
[ "https://hermeneutics.stackexchange.com/questions/52725", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/38999/" ]
That the Father sent the Son to be the saviour of the world and that John declares of him ‘Behold the Lamb of God which taketh away the sin of the world’, does not suggest, in any way, a ‘Christian Universalism’, that is to say the notion that, automatically, all humankind shall be saved irrespective of their behaviour, irrespective of faith or irrespective of the purposes of God in salvation. In order that there should be a world to come, at all, necessitated the coming of Christ and the death of Christ. It is clear from what the scriptures teach regarding restoration (unhelpfully translated ‘reconciliation’) that salvation is effected by the death of Christ and by union with Him, under his Headship, in a righteous restoration out from under the headship of Adam and out of the former human state in Adam. Part of this restoration is the fact that Jesus Christ is the Lamb of God who taketh away the ‘sin of the world’ which does not refer to the specific actions of individuals (which is dealt with in other parts of the doctrine of Christ) but refers to the entry of sin into the world from the beginning, in Adam. Being ‘made’ sin, or being effected sin (some translate this as ‘being made a sin offering’ but I suggest that that falls short of the full concept) sin, itself, was condemned within the humanity of Jesus Christ - a clean humanity - and sin was eradicated in the sight of God, righteously. No individual is condemned, personally, for the liability of flesh and blood, or for the propensities of created humanity, or for the failure of man in the flesh, or for the transgression of the head of humanity, Adam. This liability and this sin is taken away by the Saviour and borne by him in his death. That removal, righteously, is necessary for there to be a world at all. That removal was necessary even to grant a continuance to humanity after the Flood. The judgment on the world, by water, was to end all flesh because of the consequences of sin and because of the multiplication of evil on earth to the extent it could not be tolerated any further. Eight persons were preserved and that preservation was in order for the purposes of God to be fulfilled, despite the transgression : a continuance being granted, due to a foreseen sacrifice (by Christ) that gave a righteous basis for the extension of the world, in time, for those divine purposes to progress. Else, in righteousness, there could be no world at all. The world would have ended at the time of the Flood. He is the ‘Saviour of the world’ in that humanity is granted existence, time, forbearance and the testimony of the gospel (whether by figure and ritual under the old covenant, or whether by full revelation under the New Testament) that they might be saved. But if there is unbelief and rejection then that is the responsibility of each individual. And the consequence is to their own account, personally. The further notion that the sufferings of Christ (within his body, prior to his death) were effective for the sins of all humankind (but only if certain individuals took advantage and added their own effectiveness) is nowhere expressed in scripture and is, in effect, salvation by works.
The greater question of the question posed is, ***“Does Scripture support the Universalism?”*** And do the passages-John 1:29 & 12:47 support the Universalism? **1. The Universalism** (differ from the Universal atonement) The modern-day Universalism -Christian Universalism - is a specific theological term for a belief that **ultimately all human beings - all people/ every person of all human history, and the fallen angelic beings eventually will come into final salvation and spend eternity with God in heaven** (often confused with the universal atonement view -the provision of salvation and our acceptance of the salvation.) (Note: Two main versions: The ultra-Universalism-everyone at death will have the second chance to accept the Salvation and go to heaven; The *Purgationists* - unsaved people after a certain cleansing period, God will free the inhabitants of hell and reconcile them to himself. Now the universalist prefers to call it, Universal restoration, Universal reconciliation, Universal restitution, and Universal salvation, or The victorious Gospel of Grace, Jesus, the Chosen One, Saves All.) The main arguments of the universalist are: * God is love, therefore, He “must” love all and will the salvation for all -all intelligent beings He created. * The loving God by nature would condemn no one to eternal torment in hell, * That after a certain cleansing period, God will free "all" inhabitants of hell and reconcile them to himself. * The word “all (πᾶς)” and the “world” in certain passages have universal implications and support the Universalism -i.e., justification and life(eternal) for “all men” ([Rom. 5:18, 11:32; 1 Cor. 15:22; John 1:29; 4:42; 12:32; Acts 3:21; Col. 1:20; Eph. 1:10; 1 John 2:2; 4:14)](http://localhost:8989/?q=version=ESV%7Creference=John.1.29%20John.4.42%20John.12.32%20Acts.3.21%20Rom.5.18%20Rom.11.32%201Cor.15.22%20Eph.1.10%20Col.1.20%201John.2.2%201John.4.14&options=HNVUG&pos=1) While the argument appears logical, but it is the ***same ol’*** circular reasoning - God cannot be perfect love while punishing sinners in hell. It is a logical fallacy imposing human judgment upon God, defective logic blinded by the love of God for creatures, but blinded to the love of God for His only-begotten Son. It is the faulty logic of **abstracting the eternal attributes of God** revealed in God’s revelations and is the same deception of the serpent first used at the Garden. Universalism ignores the fact that the loving God, forsaken His only-begotten Son, put through a cruel death on the cross to save the created beings who reveled against Him and condemned to eternal damnation in hell. In effect, according to their "perfect love" logic, God is still a failure because He loved created beings but NOT loved His only-begotten Son. Furthermore, according to their line of thinking, the loving and sovereign God could /should have prevented the causes of sin in the first place, and if He did not, He is NOT perfect love; if He could not, He is NOT almighty; if He did not see it coming, He is NOT all-knowing, etc. **All their logics and arguments are to make a total mockery of God of the Scripture!** **In sum**: The Scripture says, "There is a way that seems right to a man, but its end is the way to death" (Proverb 14:12). Here, "right **יָשָׁר**" has ranges of meanings - right, correct, pleasing, and smooth." The Universalism - though more palatable to many - is "***The Devil's Redemption***" (M. McClymond,) and that says it all! **2. The Universal Atonement** The Universal Atonement (Unlimited Atonement -Arminianism), though shares with the Universalism on - i.e., Christ died for all sins of the world, it entirely differs with it- from the scope and efficacy of the atonement to eschatological outcome. Most importantly, no human judgments on God and His Word- the Scripture! The universal atonement is one of the 5 points that differ from the limited atonement (Calvinism). Both Calvinism and Arminianism -two opposing views- have good Scriptural supports for all their 5 points, yet both are in agreement on the main point - Salvation by grace through the "faith" in Jesus Christ. One thing is clear: a) that two opposing views -as they are- cannot be right, nor totally represent the Scripture on every and all doctrinal points, unless both come to the Scripture. b) And also one’s belief in the scope of Christ's Atonement, and theological affiliation and familiarity of doctrines does not “save,” but the Word of Jesus gives the life ([John 6:63](http://localhost:8989/?q=version=ESV%7Creference=John.6.63&options=HNVUG&pos=1)). Jesus said, “truly, truly I say, unless one is born of water and the Spirit, he cannot enter the kingdom of God” (John 3:5), "Whoever has the Son has life; whoever does not have the Son of God does not have life (1John 5:12), “Blessed rather are those who hear the word of God and keep it" ([Luke 11:28](http://localhost:8989/?q=version=ESV%7Creference=Luke.11.28&options=HNVUG&pos=1)). Jesus says, "But to all who did receive him, who believed in his name, he gave the right to become children of God" (John 1:12-ESV). In Revelation, "And if anyone’s name was not found written in the book of life, he was thrown into the lake of fire" (Rev. 20:15). The Holy Spirit is the spirit of the truth, and He will guide and teach us the Word ([John 15:26,16:13](http://localhost:8989/?q=version=ESV%7Creference=John.15.26%20John.16.13&options=HNVUG&pos=1)). NO theologians and bible teachers can come to your help on that day. * \*\*Sola scriptura * Sola fide * Sola gratia * Solus Christus * Soli Deo gloria\*\* **3. Do John 1:29 & 12: 47 support the Universalism?** The text John 1:29 connotes the universal atonement, but NOT the universalism. John 12:47 (& 48), the very words - if any man hears my words, and believe not… the word that I have spoken will judge… speak against the Universalism. In sum, in the immediate, larger, and context of the whole Bible, are many conditional/restrictive words against Universalism.
63,798,361
I have created a function day\_of\_week(dayy) and used switch-case statements in function. ``` function day_of_week(dayy) { var result; switch (dayy) { case 1: result = "monday"; case 2: result = "Tuesday"; case 3: result = "wednesday"; case 4: result = "thursday"; case 5: result = "friday"; case 6: result = "saturday"; case 7: result = "sunday"; default: result = "No day"; } document.write(result); } document.getElementById("switch").innerHTML = day_of_week(1); document.getElementById("switch").innerHTML = day_of_week(2); ``` Actually in switch-case statements if there is no "break" the code should execute randomly. But here when I declared variable called result and assigned the case values to it without "break". So, the code should execute all the cases randomly without any break. But, here the variable is under the instance of redeclaring the value and executing the last case. I am unable to know my mistake whether it is in declaring variable or using switch-case statements and all under the instance of function. please help...
2020/09/08
[ "https://Stackoverflow.com/questions/63798361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14037917/" ]
There is no break statement in your code. I hope this will work for you. ``` <!DOCTYPE html> <html> <head> <script> function day_of_week(dayy){ var result; switch(dayy){ case 1: result = "Monday"; break; case 2: result = "Tuesday"; break; case 3: result = "wednesday"; break; case 4: result = "Thursday"; break; case 5: result = "Friday"; break; case 6: result = "Saturday"; break; case 7: result = "Sunday"; break; default: result = "No day"; } document.write(result); } document.getElementById("switch").innerHTML = day_of_week(2); </script> </head> <body> </body> </html> ```
I would do something like this to get a random day: ``` function getDay() { const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]; return days[Math.floor(Math.random() * 7)]; } ```
63,798,361
I have created a function day\_of\_week(dayy) and used switch-case statements in function. ``` function day_of_week(dayy) { var result; switch (dayy) { case 1: result = "monday"; case 2: result = "Tuesday"; case 3: result = "wednesday"; case 4: result = "thursday"; case 5: result = "friday"; case 6: result = "saturday"; case 7: result = "sunday"; default: result = "No day"; } document.write(result); } document.getElementById("switch").innerHTML = day_of_week(1); document.getElementById("switch").innerHTML = day_of_week(2); ``` Actually in switch-case statements if there is no "break" the code should execute randomly. But here when I declared variable called result and assigned the case values to it without "break". So, the code should execute all the cases randomly without any break. But, here the variable is under the instance of redeclaring the value and executing the last case. I am unable to know my mistake whether it is in declaring variable or using switch-case statements and all under the instance of function. please help...
2020/09/08
[ "https://Stackoverflow.com/questions/63798361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14037917/" ]
There is no break statement in your code. I hope this will work for you. ``` <!DOCTYPE html> <html> <head> <script> function day_of_week(dayy){ var result; switch(dayy){ case 1: result = "Monday"; break; case 2: result = "Tuesday"; break; case 3: result = "wednesday"; break; case 4: result = "Thursday"; break; case 5: result = "Friday"; break; case 6: result = "Saturday"; break; case 7: result = "Sunday"; break; default: result = "No day"; } document.write(result); } document.getElementById("switch").innerHTML = day_of_week(2); </script> </head> <body> </body> </html> ```
I refactor this code by using berak and Math method ``` function day_of_week(day) { var result; switch (day) { case 1: result = "monday"; break; case 2: result = "Tuesday"; break; case 3: result = "wednesday"; break; case 4: result = "thursday"; break; case 5: result = "friday"; break; case 6: result = "saturday"; break; case 7: result = "sunday"; break; default: result = "No day"; } document.write(result); } document.getElementById("switch").innerHTML = day_of_week(Math.floor( Math.random()*10)); ```
970,828
Has anyone seen a library that tests WCF DataContracts? The motivation behind asking this is that I just found a bug in my app that resulted from my not annotating a property with the DataMember attribute - as a result, that property wasn't being serialized. What I have in mind is an API that, given a particular type of DataContract, will automatically populate its members with random data, including any child DataContracts, then serialize it via one of the WCF Serializers/Formatters and then check that all of the data has been carried across. Anyone?
2009/06/09
[ "https://Stackoverflow.com/questions/970828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1727/" ]
It's simple enough to use `DataContractSerializer` to serialise your object to a `MemoryStream`, then deserialise it back into existence as a new instance. Here's a class that demonstrates this round-trip serialisation: ``` public static class WcfTestHelper { /// <summary> /// Uses a <see cref="DataContractSerializer"/> to serialise the object into /// memory, then deserialise it again and return the result. This is useful /// in tests to validate that your object is serialisable, and that it /// serialises correctly. /// </summary> public static T DataContractSerializationRoundTrip<T>(T obj) { return DataContractSerializationRoundTrip(obj, null); } /// <summary> /// Uses a <see cref="DataContractSerializer"/> to serialise the object into /// memory, then deserialise it again and return the result. This is useful /// in tests to validate that your object is serialisable, and that it /// serialises correctly. /// </summary> public static T DataContractSerializationRoundTrip<T>(T obj, IEnumerable<Type> knownTypes) { var serializer = new DataContractSerializer(obj.GetType(), knownTypes); var memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; obj = (T)serializer.ReadObject(memoryStream); return obj; } } ``` Two tasks that you are responsible for: * Populating the instance in the first place with sensible data. You might choose to use reflection to set properties or supply a constructor with its arguments, but I've found this approach just won't work for anything other than incredibly simple types. * Comparing the two instances after you have round-trip de/serialised it. If you have a reliable `Equals/GetHashCode` implementation, then that might already be done for you. Again you might try using a generic reflective comparer, but this mightn't be completely reliable.
A better approach: create a proxy that serializes/deserializes all arguments when calling a method. Code can be found here: <http://mkramar.blogspot.com/2013/01/unit-test-wcf-with-serialization.html>
40,062,557
I'm allowing users to select/deselect cells in my collection view and then hit a save/delete button. When I'm selecting rows, I add them to a dictionary ``` var selectedIndexes = Dictionary<IndexPath, String> () ``` and when I deselect the row I set the selectedIndexes[indexPath] = nil When the user hits delete I run ``` for index in selectedIndexes.keys { indexesToDelete.append(index) } collectionView.deleteItems(at: indexesToDelete) ``` This goes into the selectedIndexes dictionary, grabs the indexes, adds those indexes into an array of indexes "indexesToDelete", and then after the forloop is over, I'm deleting that array of indexes. When I run this I get: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (5) must be equal to the number of items contained in that section before the update (5), plus or minus the number of items inserted or deleted from that section (0 inserted, 2 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).' I've printed everything out and the indexesToDelete are the correct indexes for what I'm trying to delete. I don't fully understand what the error message is saying.
2016/10/15
[ "https://Stackoverflow.com/questions/40062557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6820041/" ]
What it is saying is that your collection view is no longer in sync with your data source. So you also need to update whatever you are using as your dataSource to reflect your changes and then call deleteCells.
``` for index in selectedIndexes.keys { indexesToDelete.append(index) } yourCollectionViewDataSourceArray.remove(at: index) collectionView.deleteItems(at: indexesToDelete) ``` if your collectionView data source is yourCollectionViewDataSourceArray, both are synced together. Every time collectionView reloads data it uses the the function with argument numberOfItemsInSection. When it finds out that your array.count is different than the total of items after deletion it gives you this error. Take it as a rule every time you want to update your collectionView by code, update the data array before updating it. Hope that helps
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
You don't really define methods inside of methods in Ruby, but you can use `lambda`: ``` def f v = 5 g = lambda do v end g.call end ```
Short answer, no. Ruby's functions have different scoping rules than Javascript functions. Longer answer is that you can define objects in Ruby that preserve the scope in which they are defined (called a closure). These are called lambdas, Procs, and blocks in Ruby. Look [here](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) for a quick overview. Edit: blocks are not Ruby objects, but they can be converted into Procs, which are objects.
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Ruby has script scope, module/class/method definition scope and block scope. Only blocks create nested scopes. So, you need to use a block to define your method. Thankfully, there is a method for defining methods that takes a block: ``` def f v = 5 define_method :g do v end g end f # => 5 ``` However, note that this does *not* do what you think it does (and neither does your original code). It does *not* define a method `g` nested in method `f`. Ruby doesn't have nested methods. Methods always belong to modules (classes are modules), they cannot belong to methods. What this does is define a method `f`, which when you run it defines a method `g` and then calls that method. Observe: ``` methods.include?(:g) # => true ``` You have now defined a new top-level method (actually a private instance method of `Object`) called `g`, and you will define it over and over and over again, everytime `f` gets called. What you probably want is a lambda: ``` def f v = 5 g = -> { v } g.() end f # => 5 ``` In a comment to another answer you wrote: > > Okay, so I'm messing around with lambdas, and I noticed that anything I do to `v` inside of `g` is not reflected in `v` once `g` returns. Is there a way I can make my changes to `v` stick? > > > ``` def f v = 5 g = -> { v = 'Hello' } g.() v end f # => 'Hello' ``` As you can see, the change to `v` *does* "stick" after `g` returns.
You don't really define methods inside of methods in Ruby, but you can use `lambda`: ``` def f v = 5 g = lambda do v end g.call end ```
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
You don't really define methods inside of methods in Ruby, but you can use `lambda`: ``` def f v = 5 g = lambda do v end g.call end ```
To add to the other answers, for most consistency with your CoffeeScript code, you would probably write: ``` f = lambda do v = 5 g = lambda do v end g[] end f[] ```
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
You don't really define methods inside of methods in Ruby, but you can use `lambda`: ``` def f v = 5 g = lambda do v end g.call end ```
A closure is a named block of code (a function in some languages, a lambda or proc in Ruby) with the following characteristics: * It remembers the values of all variables that were available in the scope it was defined (outer scope), even when called on another scope or when those variables are no longer available (out of scope). * It is an object. Hence, it can be assigned to a variable, passed around, called from within different scopes, etc. Below is an example using a Lambda. The same could be done using a Proc. ``` minutes = 40 def meditate minutes return lambda { minutes } end p = meditate minutes minutes = nil p.call # Output: => 40 ``` Notice the lambda was created inside the meditate method, which took minutes as an argument. Later, when we called the lambda, the meditate method was already gone. We also set the value of minutes to nil. Nonetheless, the lambda remembered the value of "minutes". Ruby has two types of closures: Lambdas and Procs. Methods are not closures, neither are the Method objects. As stated by Yukihiro Matsumoto (Matz) in his book The Ruby Programming Language: > > One important difference between Method objects and Proc objects is that Method objects are not closures. Ruby's method are intended to be completely self-contained, and they never have access to local variables outside of their scope. The only binding retained by a Method object, therefore, is the value of self - the object on which the method is to be invoked. > > > See more at [this post about Methods in the Zen Ruby blog.](http://www.zenruby.info/2016/05/methods-in-ruby.html)
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Ruby has script scope, module/class/method definition scope and block scope. Only blocks create nested scopes. So, you need to use a block to define your method. Thankfully, there is a method for defining methods that takes a block: ``` def f v = 5 define_method :g do v end g end f # => 5 ``` However, note that this does *not* do what you think it does (and neither does your original code). It does *not* define a method `g` nested in method `f`. Ruby doesn't have nested methods. Methods always belong to modules (classes are modules), they cannot belong to methods. What this does is define a method `f`, which when you run it defines a method `g` and then calls that method. Observe: ``` methods.include?(:g) # => true ``` You have now defined a new top-level method (actually a private instance method of `Object`) called `g`, and you will define it over and over and over again, everytime `f` gets called. What you probably want is a lambda: ``` def f v = 5 g = -> { v } g.() end f # => 5 ``` In a comment to another answer you wrote: > > Okay, so I'm messing around with lambdas, and I noticed that anything I do to `v` inside of `g` is not reflected in `v` once `g` returns. Is there a way I can make my changes to `v` stick? > > > ``` def f v = 5 g = -> { v = 'Hello' } g.() v end f # => 'Hello' ``` As you can see, the change to `v` *does* "stick" after `g` returns.
Short answer, no. Ruby's functions have different scoping rules than Javascript functions. Longer answer is that you can define objects in Ruby that preserve the scope in which they are defined (called a closure). These are called lambdas, Procs, and blocks in Ruby. Look [here](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) for a quick overview. Edit: blocks are not Ruby objects, but they can be converted into Procs, which are objects.
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Short answer, no. Ruby's functions have different scoping rules than Javascript functions. Longer answer is that you can define objects in Ruby that preserve the scope in which they are defined (called a closure). These are called lambdas, Procs, and blocks in Ruby. Look [here](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) for a quick overview. Edit: blocks are not Ruby objects, but they can be converted into Procs, which are objects.
To add to the other answers, for most consistency with your CoffeeScript code, you would probably write: ``` f = lambda do v = 5 g = lambda do v end g[] end f[] ```
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Short answer, no. Ruby's functions have different scoping rules than Javascript functions. Longer answer is that you can define objects in Ruby that preserve the scope in which they are defined (called a closure). These are called lambdas, Procs, and blocks in Ruby. Look [here](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) for a quick overview. Edit: blocks are not Ruby objects, but they can be converted into Procs, which are objects.
A closure is a named block of code (a function in some languages, a lambda or proc in Ruby) with the following characteristics: * It remembers the values of all variables that were available in the scope it was defined (outer scope), even when called on another scope or when those variables are no longer available (out of scope). * It is an object. Hence, it can be assigned to a variable, passed around, called from within different scopes, etc. Below is an example using a Lambda. The same could be done using a Proc. ``` minutes = 40 def meditate minutes return lambda { minutes } end p = meditate minutes minutes = nil p.call # Output: => 40 ``` Notice the lambda was created inside the meditate method, which took minutes as an argument. Later, when we called the lambda, the meditate method was already gone. We also set the value of minutes to nil. Nonetheless, the lambda remembered the value of "minutes". Ruby has two types of closures: Lambdas and Procs. Methods are not closures, neither are the Method objects. As stated by Yukihiro Matsumoto (Matz) in his book The Ruby Programming Language: > > One important difference between Method objects and Proc objects is that Method objects are not closures. Ruby's method are intended to be completely self-contained, and they never have access to local variables outside of their scope. The only binding retained by a Method object, therefore, is the value of self - the object on which the method is to be invoked. > > > See more at [this post about Methods in the Zen Ruby blog.](http://www.zenruby.info/2016/05/methods-in-ruby.html)
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Ruby has script scope, module/class/method definition scope and block scope. Only blocks create nested scopes. So, you need to use a block to define your method. Thankfully, there is a method for defining methods that takes a block: ``` def f v = 5 define_method :g do v end g end f # => 5 ``` However, note that this does *not* do what you think it does (and neither does your original code). It does *not* define a method `g` nested in method `f`. Ruby doesn't have nested methods. Methods always belong to modules (classes are modules), they cannot belong to methods. What this does is define a method `f`, which when you run it defines a method `g` and then calls that method. Observe: ``` methods.include?(:g) # => true ``` You have now defined a new top-level method (actually a private instance method of `Object`) called `g`, and you will define it over and over and over again, everytime `f` gets called. What you probably want is a lambda: ``` def f v = 5 g = -> { v } g.() end f # => 5 ``` In a comment to another answer you wrote: > > Okay, so I'm messing around with lambdas, and I noticed that anything I do to `v` inside of `g` is not reflected in `v` once `g` returns. Is there a way I can make my changes to `v` stick? > > > ``` def f v = 5 g = -> { v = 'Hello' } g.() v end f # => 'Hello' ``` As you can see, the change to `v` *does* "stick" after `g` returns.
To add to the other answers, for most consistency with your CoffeeScript code, you would probably write: ``` f = lambda do v = 5 g = lambda do v end g[] end f[] ```
18,027,508
In CoffeeScript: ``` f = -> v = 5 g = -> v g() f() # returns 5 as expected ``` In Ruby: ``` def f v = 5 def g v # undefined local variable or method `v' for main:Object (NameError) end g end f ``` Okay, so apparently JavaScript functions are set up to capture variables in the scope they are created in, but Ruby's methods are not. Is there a way to make Ruby methods behave like JavaScript functions in this regard?
2013/08/02
[ "https://Stackoverflow.com/questions/18027508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291990/" ]
Ruby has script scope, module/class/method definition scope and block scope. Only blocks create nested scopes. So, you need to use a block to define your method. Thankfully, there is a method for defining methods that takes a block: ``` def f v = 5 define_method :g do v end g end f # => 5 ``` However, note that this does *not* do what you think it does (and neither does your original code). It does *not* define a method `g` nested in method `f`. Ruby doesn't have nested methods. Methods always belong to modules (classes are modules), they cannot belong to methods. What this does is define a method `f`, which when you run it defines a method `g` and then calls that method. Observe: ``` methods.include?(:g) # => true ``` You have now defined a new top-level method (actually a private instance method of `Object`) called `g`, and you will define it over and over and over again, everytime `f` gets called. What you probably want is a lambda: ``` def f v = 5 g = -> { v } g.() end f # => 5 ``` In a comment to another answer you wrote: > > Okay, so I'm messing around with lambdas, and I noticed that anything I do to `v` inside of `g` is not reflected in `v` once `g` returns. Is there a way I can make my changes to `v` stick? > > > ``` def f v = 5 g = -> { v = 'Hello' } g.() v end f # => 'Hello' ``` As you can see, the change to `v` *does* "stick" after `g` returns.
A closure is a named block of code (a function in some languages, a lambda or proc in Ruby) with the following characteristics: * It remembers the values of all variables that were available in the scope it was defined (outer scope), even when called on another scope or when those variables are no longer available (out of scope). * It is an object. Hence, it can be assigned to a variable, passed around, called from within different scopes, etc. Below is an example using a Lambda. The same could be done using a Proc. ``` minutes = 40 def meditate minutes return lambda { minutes } end p = meditate minutes minutes = nil p.call # Output: => 40 ``` Notice the lambda was created inside the meditate method, which took minutes as an argument. Later, when we called the lambda, the meditate method was already gone. We also set the value of minutes to nil. Nonetheless, the lambda remembered the value of "minutes". Ruby has two types of closures: Lambdas and Procs. Methods are not closures, neither are the Method objects. As stated by Yukihiro Matsumoto (Matz) in his book The Ruby Programming Language: > > One important difference between Method objects and Proc objects is that Method objects are not closures. Ruby's method are intended to be completely self-contained, and they never have access to local variables outside of their scope. The only binding retained by a Method object, therefore, is the value of self - the object on which the method is to be invoked. > > > See more at [this post about Methods in the Zen Ruby blog.](http://www.zenruby.info/2016/05/methods-in-ruby.html)
13,135,181
I have encountered some problem with QGLFrameBufferObject, when I change my OS from win7 to Ubuntu 12.04 LTS. After recompiling the code in the new ubuntu system, the color goes wrong. So I made a minimal test. I just clear the color buffer with color (1.0, 0.0, 0.0, 0.8), and that's it. I get the correct result when I render directly to the screen, with all pixels being (1.0, 0.0, 0.0, 0.8). However, the result from offline rendering (with QGLFrameBufferObject) is wrong, as given by offline.png. This color is (0.3, 0.0, 0.0, 0.8). This problem happens when alpha>0.0 and <1.0. For 0.0 and 1.0 it works fine. I've compiled this test code on another computer (computer A) with win7 OS, everything works fine. Also tried on one more computer (computer B) with ubuntu OS, everything works fine. I'm using a NVidia GeForce GTX 570 GPU, and have tried the latest stable driver (304.60) and an older version (290.10, used for computer B) for linux-64bit, but nothing changes. Anyone knows why? Below is the code. ``` mywidget::mywidget(QWidget * parent) : QGLWidget(parent) { } void mywidget::resizeGL(int width, int height ) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 1.0, 0.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void mywidget::paintGL() { glClearColor(1.0, 0.0, 0.0, 0.8); // DRAW ON THE SCREEN { glClear(GL_COLOR_BUFFER_BIT); } QGLFramebufferObject fbo(width(), height()); fbo.bind(); // DRAW ON THE FBO USING THE SAME CODE AND THE SAME CONTEXT { glClearColor(1.0, 0.0, 0.0, 0.8); glClear(GL_COLOR_BUFFER_BIT); } fbo.release(); fbo.toImage().save("offline.png"); } ``` I have noticed that there are two similar posts, but with no answer or detailed answer: [Wrong alpha blending when rendering on a QGLFramebufferObject](https://stackoverflow.com/questions/12306894/wrong-alpha-blending-when-rendering-on-a-qglframebufferobject); [Alpha compositing wrong when rendering to QGLFrameBufferObject vs screen](https://stackoverflow.com/questions/9913957/alpha-compositing-wrong-when-rendering-to-qglframebufferobject-vs-screen)
2012/10/30
[ "https://Stackoverflow.com/questions/13135181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784746/" ]
You could hold everything in one table with `contenttypes`: ``` from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class HistoryRecord(models.Model): history_date = models.DateTimeField() history_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) content = generic.GenericForeignKey('content_type', 'history_id') ``` then you would need to create those: ``` poll = Poll.history.all()[0] record = HistoryRecord(content=poll, history_date=poll.history_date) record.save() ``` or you could subclass `HistoricalRecords`: ``` class IndexedHistoricalRecords(HistoricalRecords): def create_historical_record(self, instance, type): history_user = getattr(instance, '_history_user', None) manager = getattr(instance, self.manager_name) attrs = {} for field in instance._meta.fields: attrs[field.attname] = getattr(instance, field.attname) content = manager.create(history_type=type, history_user=history_user, **attrs) record = HistoryRecord(content=poll, history_date=poll.history_date) record.save() ``` then you can query one table: ``` result_list = HistoryRecord.objects.all() paginator = Paginator(result_list, 100) ... ```
All models could inherit from one table (via `one-to-one` key). That way you can sort by django ORM on this field using base table and later on get proper instances. See [that discussion](https://stackoverflow.com/questions/5225556/determining-django-model-instance-types-after-a-query-on-a-base-class) for help with getting final instances.
48,577,331
How to update heap size in tomcat linux container using dockerfile
2018/02/02
[ "https://Stackoverflow.com/questions/48577331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Simply, you can check `@users` value: ``` <% if @uses.present? %> <% @users.each_with_index do |index| %> <tr> ... </tr> <% end %> <% end %> ``` Or give `@users` a value if its `nil`: ``` # In controller: @users = User.where(...) || [] ``` Hope it helps.
First of all `each_with_index` iterate over two arguments one is index and second is array object so here your syntax should be like this: - ``` <% unless @users.blank?%> <%@users.each_with_index do |user, index|%> <%= index +=1 %> <%=user.name%> #.... and so on <%end%> <%end%> ``` make sure that `@users` are defined in your action
63,058,283
I want to eject expo to bare react native cli but i can't because I am not able to enter android package name when asked. Basically when i type any android package name and hit enter it just return a blank value again.Looks like cmd is not taking input. But i degraded to expo sdk 36 from 38, then it works fine as There are different options to eject. [![enter image description here](https://i.stack.imgur.com/w0Jib.png)](https://i.stack.imgur.com/w0Jib.png)
2020/07/23
[ "https://Stackoverflow.com/questions/63058283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9631081/" ]
i also had the same issue Go to app.json in your react native project folder and add in ``` “ios”: { “bundleIdentifier”: “IOSName” }, “android”: { “package”: “AndroidName” } ``` and then save it and then go to your terminal and type ***expo eject*** When it asks for Android Package Name, give the name that you have given in your app.json file for android, and similarly for ios. Then it should work fine and finish the expo eject command.
I ran into this issue as well and found out you can only use alphanumeric characters, '.' and '\_', and for some reason you have to have at least one `.` or `_` in there. So something like `My.App` worked for me
63,058,283
I want to eject expo to bare react native cli but i can't because I am not able to enter android package name when asked. Basically when i type any android package name and hit enter it just return a blank value again.Looks like cmd is not taking input. But i degraded to expo sdk 36 from 38, then it works fine as There are different options to eject. [![enter image description here](https://i.stack.imgur.com/w0Jib.png)](https://i.stack.imgur.com/w0Jib.png)
2020/07/23
[ "https://Stackoverflow.com/questions/63058283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9631081/" ]
i also had the same issue Go to app.json in your react native project folder and add in ``` “ios”: { “bundleIdentifier”: “IOSName” }, “android”: { “package”: “AndroidName” } ``` and then save it and then go to your terminal and type ***expo eject*** When it asks for Android Package Name, give the name that you have given in your app.json file for android, and similarly for ios. Then it should work fine and finish the expo eject command.
by default package name & versionCode for android and bundleIdentifier & buildNumber for iOS is skipped in **app.json** [present in root directory of your project] when you start with expo react native project... so it is asking the package name when you expo eject. example of package name >>> "com.yourcompany.yourappname" so type package name as in example. Replace "com.yourcompany.yourappname" with whatever makes sense for your app. **or** go to app.json and edit manually, add missing fields for ios & android as necessary for your app and then expo eject. ```js { "expo": { "name": "Your App Name", "icon": "./path/to/your/app-icon.png", "version": "1.0.0", "slug": "your-app-slug", "ios": { "bundleIdentifier": "com.yourcompany.yourappname", "buildNumber": "1.0.0" }, "android": { "package": "com.yourcompany.yourappname", "versionCode": 1 } } } ``` Refer official docs for clear info : [Expo Docs Eject](https://docs.expo.io/expokit/eject/#3-eject)
35,046,343
1) [API for send here](https://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.send_to) returns `Result<usize>`. Why is that ? In my head, a UDP send is all or none. The return value seems to suggest that sending can succeed but entire data may not be written which makes me code like: ``` let mut bytes_written = 0; while bytes_written < data.len() { bytes_written += match udp_socket.send_to(&data[bytes_written..]) { Ok(bytes_tx) => bytes_tx, Err(_) => break, } } ``` Recently someone told me this is completely unnecessary. But I don't understand. If that were true why is the return not `Result<()>` instead, which is also what i was expecting ? 2) [For reads](https://doc.rust-lang.org/nightly/std/net/struct.UdpSocket.html#method.recv_from) though I understand. I could give it a buffer of size 100 bytes but the datagram might only be 50 bytes long. So essentially I should utilise only `read_buf[..size_read]`. Here my question is what happens if the buffer size is 100 but the datagram size is say 150 bytes ? Will `recv_from` fill in only 100 bytes and return `Ok(100, some_peer_addr)` ? If i re-read will it fill in the remaining of the datagram ? What if another datagram of 50 bytes arrived before my second read ? Will i get just the remaining 50 bytes the second time and 50 bytes of new datagram the 3rd time or complete 100 bytes the 2nd time which also contains the new datagram ? Or will be an error and i will lose the 1st datagram on my initial read and never be able to recover it ?
2016/01/27
[ "https://Stackoverflow.com/questions/35046343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060004/" ]
The answer to both of these questions lies in the documentation of the respective BSD sockets functions, `sendto()` and `recvfrom()`. If you use some \*nix system (OS X or Linux, for example), you can use `man sendto` and `man recvfrom` to find it. 1) `sendto()` man page is rather vague on this; [Windows](https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms740148(v=vs.85).aspx) API page explicitly says that it is possible for the return value be less than `len` argument. See also [this](https://stackoverflow.com/questions/8900474/when-will-send-return-less-than-the-length-argument) question. It looks like that this particular moment is somewhat under-documented. I think that it is probably safe to assume that the return value will always be equal either to `len` or to the error code. Problems may happen if the length of the data sent through `sendto()` exceeds the internal buffer size inside the OS kernel, but it seems that at least Windows will return an error in this case. 2) `recvfrom()` man page unambiguously states that the part of a datagram which does not fit into the buffer will be discarded: > > The recvfrom() function shall return the length of the message > written to the buffer pointed to by the buffer argument. For > message-based sockets, such as SOCK\_RAW, SOCK\_DGRAM, and > SOCK\_SEQPACKET, the entire message shall be read in a single > operation. If a message is too long to fit in the supplied buffer, > and MSG\_PEEK is not set in the flags argument, the excess bytes shall > be discarded. > > > So yes, `recv_from()` will fill exactly 100 bytes, the rest will be discarded, and further calls to `recv_from()` will return new datagrams.
If you [dig down](https://github.com/rust-lang/rust/blob/464cdff102993ff1900eebbf65209e0a3c0be0d5/src/libstd/sys/common/net.rs#L374), it just wrapping the [C sendto function](http://pubs.opengroup.org/onlinepubs/009695399/functions/sendto.html). This function returns number of bytes sent, so Rust just passes that on (while handling the -1 case and turning errno into actual errors).
36,820
I'm setting up products and tier prices in Magento, but I've noticed that a in Simple Product with Custom Options (example: blue t-shirt, red t-shirt), the Tier Price won't work if we combine them to reach the quantity. Tier Prices seem to work only when the quantity is reached from one product variation, but not a combination of two. I've read several answers on Stack Overflow and the Magento forums, and they recommend to create configurable products. However this can be pretty hard if a store has lots of products, or lots of variations. Do you know some workaround to get the Tier Price apply - with a combination of variations?
2014/09/23
[ "https://magento.stackexchange.com/questions/36820", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/14550/" ]
The problem here is that Magento treats products with different custom options as different line items in cart. So, the qty for the two variants of custom options never adds up to be able to qualify the quote item for a particular tier of tiered pricing. Now, making this work would involve custom work. I can give you pointers as to where you can look to make it work in the code. Checkout `Mage_Sales_Model_Quote_Address_Total_Subtotal::collect()` In this method you will need to loop through all the quote items and link the tiered quantity applicable on each of the quote items. So say, you have two variants A and B with quantity 1 and 3. You will loop through the quote items and do something like: ``` $quoteItemA->setTieredQty(1+3); $quoteItemB->setTieredQty(1+3); //ofcourse 1 and 3 are dynamic here ``` Then in `Mage_Sales_Model_Quote_Address_Total_Subtotal::_initItem` instead of using: `$finalPrice = $product->getFinalPrice($quoteItem->getQty()); //on line 115 use:` ``` $finalPrice = $product->getFinalPrice($quoteItem->getTieredQty()); ``` This involves custom work but the approach I'm listing should work with some on the fly adjustments as you work through it.
I can confirm, this works ``` /* hard coded - start */ $cart = Mage::getModel('checkout/cart')->getQuote(); $total_qty = 0; foreach ($cart->getAllItems() as $item2) { if ($item2->getProductId() == $quoteItem->getProductId()) $total_qty+= $item2->getQty(); } $finalPrice = $product->getFinalPrice($total_qty); // $finalPrice = $product->getFinalPrice($quoteItem->getQty()); /* hard coded - end */ ```
6,797,506
Hey looking through the net I can't seem to find a solution on how to pull these values out of this column of mine, I have only been developing for a year at Uni so this is all new to me. Basically I don't know how to do it, and reading up on Linq to SQL as well as conditional statements and loops hasn't brought me any closer to finding my solution. It's as simple as this statement below: ```cs public void SendToast(string title, string message) { var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" + "<wp:Toast>" + "<wp:Text1>{0}</wp:Text1>" + "<wp:Text2>{1}</wp:Text2>" + "</wp:Toast>" + "</wp:Notification>"; var messageBytes = System.Text.Encoding.UTF8.GetBytes(toastMessage); using (clientsDBDataContext clientDB = new clientsDBDataContext()) { var client = new ServiceFairy.clientURI(); foreach (string r in client.uri) { Uri rs = new Uri(r.ToString()); SendMessage(rs, messageBytes, NotificationType.Toast); } } } ``` I know for a fact I am doing it wrong but I just cant get my hands on how to fix this, if it wouldn't be too much to ask, please explain how I am doing this wrong as I feel useless when I have to ask others to help me out with stuff I can't figure out myself. Thanks :) This is the error Message I am getting: ```sh Error 1 Cannot convert type 'char' to 'string' ```
2011/07/23
[ "https://Stackoverflow.com/questions/6797506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/851326/" ]
What is this line doing? ``` var client = new ServiceFairy.clientURI(); ``` Aside from the fact that this wouldn't compile (it needs to be `new ServiceFairy()`), what does `clientURI()` return? You use it here like this: ``` foreach (string r in client.uri) ``` I suspect that `client.uri` is actually a *string*. If not, what is it? Assuming it's a string, then looping over any string in C# results in looping over the *characters* in the string. So I expect your compiler error is due to the fact that you are declaring `r` as a `string`, but it's actually a `char`. Most likely you don't need a loop at all, but I can't answer that until you explain what `client.uri` actually returns. And if you're feeling generous, perhaps you can explain why you have a class named `ServiceFairy`. ;) **Edit:** Based on the comments, the code should go from: ``` var client = new ServiceFairy.clientURI(); foreach (string r in client.uri) { Uri rs = new Uri(r.ToString()); SendMessage(rs, messageBytes, NotificationType.Toast); } ``` To: ``` var client = new ServiceFairy.clientURI(); Uri rs = new Uri(client.uri); SendMessage(rs, messageBytes, NotificationType.Toast); ```
I suspect `client.uri` is just a single `string`, not an array of `string[]`. So the `foreach` is iterating through each `char` in the string. So you can change it to: `foreach(char r in client.uri) {...` but I don't think that's what you want. Just ditch the whole foreach loop and do: ``` Uri rs = new Uri(client.uri); SendMessage(rs, messageBytes, NotificationtType.Toast); ```
12,937,704
I have a database containing movies Name, their description and their cover picture. The cover picture field type is as blob and the problem is that I can't retrieve it from the database. I want to display the movie name along their cover picture beside them... How to do it.. Here is my code.. ``` <?php include ("php/connection.php"); $ID = $_GET['id']; $listmovies = "SELECT * FROM movies where Genres LIKE '%$ID%'"; $result = mysql_query($listmovies); while ( $row = mysql_fetch_assoc($result) ) { ?> <table border="1" width="100%"> <tr> <td rowspan="2" width="90" height="120"> <?php // set the header for the image header("Content-type: image/jpeg"); echo $row['Image']; ?> </td> <td width="200" height="10"> <?php echo $row['Title']; ?></td> </tr> <tr> <td width="200" height="110"><a href="php/moredetails.php?id=<?php echo $row['ID']; ?>">More Detail</a></td> </tr> <?php } ?> </table> ``` I just want to display The Imgaes beside the title of the movie?
2012/10/17
[ "https://Stackoverflow.com/questions/12937704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753625/" ]
Yes it won't display because `any output above header would always generate error` ... you need to have a different page to output your image or include it has `base64` image Remove ``` header("Content-type: image/jpeg"); echo $row['Image']; ``` And add this : ``` printf("<img src=\"data:image/jpeg;base64,%s\" />",base64_encode($row['Image'])); ^--- Note this is only for jpeg images ```
I suggest something like that: Make a new php file called for example image.php; That file will replace physical image file. In that file you put the code from your post plus some logic to get image data from database; In parent template(php file maybe) you put code for image: ``` <img src="image.php?id_movie=<?php echo $id_movie; ?>" width ="200" height="200" /> More Detail ``` In image.php i suggest to be careful at spaces outside php tags (at the beniging and at the end). Also to image.php you need to give id of the movie to know what image to load from database.
21,021,821
I dont know what I have missed, but the thing is that I would like to have an action on my "add"-button so it can go to the next page "page2". The same will be with the "show" and "cancel" button to get to previous and next page. In my PhoneGap app I have a index.html and a index.js file, there is no page2.html and so on. Can someone help me & explain how its done. Thank you. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Last Time I Did It!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="lib/jquery-1.6.4.js"></script> <script src="lib/jquery.mobile-1.1.0.js"></script> <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet"> <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet"> </head> <body> <div data-role="page" id="page1"> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" onclick="addEvent" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="save">SAVE</a> </li> <li> <a data-role="button" id="cancel" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> <script type="text/javascript" src="phonegap.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html> ``` And this is my index.js file: ``` function addEvent() { window.location = "page2.html"; } ```
2014/01/09
[ "https://Stackoverflow.com/questions/21021821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127826/" ]
Hope this JSFiddle can help you [JSFiDDLE](http://jsfiddle.net/Gajotres/g5vAN/) For better understanding you can read here too [jQuery Mobile navigate or changePage?](https://stackoverflow.com/questions/16616538/jquery-mobile-navigate-or-changepage) ``` <div data-role="page" id="index"> <div data-theme="b" data-role="header"> <h1>Index page</h1> </div> <div data-role="content"> <a data-role="button" id="navigateButton">Navigate to the other page</a> </div> </div> <div data-role="page" id="second"> <div data-theme="b" data-role="header"> <h1>Second page</h1> </div> <div data-role="content"> </div> </div> $(document).on('pagebeforeshow', '#index', function(){ $(document).on('click', '#navigateButton', function(){ $.mobile.navigate( "#second", { transition : "slide", info: "info about the #bar hash" }); }); }); ```
try ``` window.location.href = "page2.html" ``` but how do you expect to go to page2 if there is no page2.html?
21,021,821
I dont know what I have missed, but the thing is that I would like to have an action on my "add"-button so it can go to the next page "page2". The same will be with the "show" and "cancel" button to get to previous and next page. In my PhoneGap app I have a index.html and a index.js file, there is no page2.html and so on. Can someone help me & explain how its done. Thank you. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Last Time I Did It!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="lib/jquery-1.6.4.js"></script> <script src="lib/jquery.mobile-1.1.0.js"></script> <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet"> <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet"> </head> <body> <div data-role="page" id="page1"> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" onclick="addEvent" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="save">SAVE</a> </li> <li> <a data-role="button" id="cancel" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> <script type="text/javascript" src="phonegap.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html> ``` And this is my index.js file: ``` function addEvent() { window.location = "page2.html"; } ```
2014/01/09
[ "https://Stackoverflow.com/questions/21021821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127826/" ]
Add following code in your body tag. ``` <div data-role="page" id="page1"> <div data-role="header"> <h1>Page 1</h1> </div> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" href="#page2" data-transition="slide" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="header"> <h1>Page 2</h1> </div> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" href="#page3" data-transition="slide" id="save">SAVE</a> </li> <li> <a data-role="button" href="#page1" id="cancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="header"> <a href="#page2" class="ui-btn-left" data-rel="back" data-transition="slide">Back</a> <h1>Page 3</h1> </div> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> ```
try ``` window.location.href = "page2.html" ``` but how do you expect to go to page2 if there is no page2.html?
21,021,821
I dont know what I have missed, but the thing is that I would like to have an action on my "add"-button so it can go to the next page "page2". The same will be with the "show" and "cancel" button to get to previous and next page. In my PhoneGap app I have a index.html and a index.js file, there is no page2.html and so on. Can someone help me & explain how its done. Thank you. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Last Time I Did It!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="lib/jquery-1.6.4.js"></script> <script src="lib/jquery.mobile-1.1.0.js"></script> <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet"> <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet"> </head> <body> <div data-role="page" id="page1"> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" onclick="addEvent" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="save">SAVE</a> </li> <li> <a data-role="button" id="cancel" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> <script type="text/javascript" src="phonegap.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html> ``` And this is my index.js file: ``` function addEvent() { window.location = "page2.html"; } ```
2014/01/09
[ "https://Stackoverflow.com/questions/21021821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127826/" ]
I recommend adding a **event listener** to the element which calls the **changepage** event. This helped me boost up user experience, since it fires quicker than the **href** anchor. ``` $(document).on('tap', '#add', function(e){ $.mobile.changePage('#page2'); }); ```
try ``` window.location.href = "page2.html" ``` but how do you expect to go to page2 if there is no page2.html?
21,021,821
I dont know what I have missed, but the thing is that I would like to have an action on my "add"-button so it can go to the next page "page2". The same will be with the "show" and "cancel" button to get to previous and next page. In my PhoneGap app I have a index.html and a index.js file, there is no page2.html and so on. Can someone help me & explain how its done. Thank you. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Last Time I Did It!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="lib/jquery-1.6.4.js"></script> <script src="lib/jquery.mobile-1.1.0.js"></script> <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet"> <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet"> </head> <body> <div data-role="page" id="page1"> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" onclick="addEvent" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="save">SAVE</a> </li> <li> <a data-role="button" id="cancel" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> <script type="text/javascript" src="phonegap.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html> ``` And this is my index.js file: ``` function addEvent() { window.location = "page2.html"; } ```
2014/01/09
[ "https://Stackoverflow.com/questions/21021821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127826/" ]
Hope this JSFiddle can help you [JSFiDDLE](http://jsfiddle.net/Gajotres/g5vAN/) For better understanding you can read here too [jQuery Mobile navigate or changePage?](https://stackoverflow.com/questions/16616538/jquery-mobile-navigate-or-changepage) ``` <div data-role="page" id="index"> <div data-theme="b" data-role="header"> <h1>Index page</h1> </div> <div data-role="content"> <a data-role="button" id="navigateButton">Navigate to the other page</a> </div> </div> <div data-role="page" id="second"> <div data-theme="b" data-role="header"> <h1>Second page</h1> </div> <div data-role="content"> </div> </div> $(document).on('pagebeforeshow', '#index', function(){ $(document).on('click', '#navigateButton', function(){ $.mobile.navigate( "#second", { transition : "slide", info: "info about the #bar hash" }); }); }); ```
I recommend adding a **event listener** to the element which calls the **changepage** event. This helped me boost up user experience, since it fires quicker than the **href** anchor. ``` $(document).on('tap', '#add', function(e){ $.mobile.changePage('#page2'); }); ```
21,021,821
I dont know what I have missed, but the thing is that I would like to have an action on my "add"-button so it can go to the next page "page2". The same will be with the "show" and "cancel" button to get to previous and next page. In my PhoneGap app I have a index.html and a index.js file, there is no page2.html and so on. Can someone help me & explain how its done. Thank you. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Last Time I Did It!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="lib/jquery-1.6.4.js"></script> <script src="lib/jquery.mobile-1.1.0.js"></script> <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet"> <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet"> </head> <body> <div data-role="page" id="page1"> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" onclick="addEvent" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="save">SAVE</a> </li> <li> <a data-role="button" id="cancel" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> <script type="text/javascript" src="phonegap.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html> ``` And this is my index.js file: ``` function addEvent() { window.location = "page2.html"; } ```
2014/01/09
[ "https://Stackoverflow.com/questions/21021821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127826/" ]
Add following code in your body tag. ``` <div data-role="page" id="page1"> <div data-role="header"> <h1>Page 1</h1> </div> <div data-role="content"></div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a> </li> <li> <a data-role="button" href="#page2" data-transition="slide" id="show" data-rel="page">SHOW</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page2"> <div data-role="header"> <h1>Page 2</h1> </div> <div data-role="content"> <textarea></textarea> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" href="#page3" data-transition="slide" id="save">SAVE</a> </li> <li> <a data-role="button" href="#page1" id="cancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a> </li> </ul> </div> </div> </div> <div data-role="page" id="page3"> <div data-role="header"> <a href="#page2" class="ui-btn-left" data-rel="back" data-transition="slide">Back</a> <h1>Page 3</h1> </div> <div data-role="content"> <ol data-role="listview" id="orderedList" data-inset="true"></ol> </div> <div data-role="footer"> <h1>Footer</h1> <div data-role="navbar"> <ul> <li> <a data-role="button" id="edit">EDIT</a> </li> <li> <a data-role="button" id="delete">DELETE</a> </li> </ul> </div> </div> </div> ```
I recommend adding a **event listener** to the element which calls the **changepage** event. This helped me boost up user experience, since it fires quicker than the **href** anchor. ``` $(document).on('tap', '#add', function(e){ $.mobile.changePage('#page2'); }); ```
52,774,628
Error i see on my console is *Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<http://localhost:3000>' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.* My Web-app is running at localhost:3000 My server is running at localhost:8081 I am able to hit the services using postman . Here are the things I already tried :- One the REST API side I have added CORS filter class :- ``` public class CORSFilter implements Filter { public static final String ACCESS_CONTROL_ALLOW_ORIGIN_NAME = "Access- Control-Allow-Origin"; public static final String DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*"; public static final String ACCESS_CONTROL_ALLOW_METHDOS_NAME = "Access- Control-Allow-Methods"; public static final String DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE = "*"; public static final String ACCESS_CONTROL_MAX_AGE_NAME = "Access-Control-Max- Age"; public static final String DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE = "3600"; public static final String ACCESS_CONTROL_ALLOW_HEADERS_NAME = "Access- Control-Allow-Headers"; public static final String DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "*"; private String accessControlAllowOrigin = DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE; private String accessControlAllowMethods = DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE; private String accessControlAllowMaxAge = DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE; private String accessControlAllowHeaders = D DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE; private Map<String,String> initConfig(){ Map<String, String> result = new HashMap<String,String>(); result.put(ACCESS_CONTROL_ALLOW_ORIGIN_NAME,"accessControlAllowOrigin"); result.put(ACCESS_CONTROL_ALLOW_METHDOS_NAME,"accessControlAllowMethods"); result.put(ACCESS_CONTROL_MAX_AGE_NAME,"accessControlAllowMaxAge"); result.put(ACCESS_CONTROL_ALLOW_HEADERS_NAME,"accessControlAllowHeaders"); return result; } @Override public void init(FilterConfig filterConfig) throws ServletException { String initParameterValue; Map<String, String> stringStringMap = initConfig(); for (Map.Entry<String, String> stringStringEntry : stringStringMap.entrySet()) { initParameterValue = filterConfig.getInitParameter(stringStringEntry.getKey()); if(initParameterValue!=null){ try { getClass().getDeclaredField(stringStringEntry.getValue()).set(this, initParameterValue); } catch(Exception ex) { } } } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_NAME, accessControlAllowOrigin); response.setHeader(ACCESS_CONTROL_ALLOW_METHDOS_NAME, accessControlAllowMethods); response.setHeader(ACCESS_CONTROL_MAX_AGE_NAME, accessControlAllowMaxAge); response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_NAME, accessControlAllowHeaders); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } ``` } My web.xml looks like this :- ``` <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <filter> <filter-name>CORSFilter</filter-name> <filter- class>com.barclaycardus.svc.agentprofile.config.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` On the react application i have added the following headers :- ``` headers1.append('Access-Control-Allow-Origin', '*'); headers1.append('Access-Control-Allow-Credentials', 'true'); ``` Still i am getting the same issue . ``` var request = new Request(url, { method: 'GET', headers:headers1, cache:'no-cache' // mode:'no-cors' }); ``` When I use no-cors mode in fetch API calls , I am getting 401 error , I guess no-cors mode is not sending Few of the headers . Other alternative I tries is using @CrossOrigin , but since i am using older version of spring ,I dont support @CrossOrigin , I cant upgrade my version of spring as other old code is breaking onupgradation .
2018/10/12
[ "https://Stackoverflow.com/questions/52774628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6519815/" ]
It seem you misconstrued something here. The header of CORS should be returned from server and not send from clients (react). ``` Access-Control-Allow-Origin Access-Control-Allow-Credentials ``` Example: You want to send a request from A -> server B. Browser will send HTTP OPTIONS firstly, to verify if the method is allowed or not, if not allowed it won't send a request. How browser verify it, it base on the returned header of Server B for HTTP OPTIONS request. ``` Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: * ```
You have to send back to the client from server that this domain is allowed or not ``` import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet Filter implementation class CORSFilter */ // Enable it for Servlet 3.x implementations /* @ WebFilter(asyncSupported = true, urlPatterns = { "/*" }) */ public class CORSFilter implements Filter { /** * Default constructor. */ public CORSFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("CORSFilter HTTP Request: " + request.getMethod()); // Authorize (allow) all domains to consume the content ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*"); ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST"); HttpServletResponse resp = (HttpServletResponse) servletResponse; // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake if (request.getMethod().equals("OPTIONS")) { resp.setStatus(HttpServletResponse.SC_ACCEPTED); return; } // pass the request along the filter chain chain.doFilter(request, servletResponse); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } } ``` Define that in xml as below : ``` <filter> <filter-name>CorsFilter</filter-name> <filter-class>com.ishant.examples.cors.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ```
26,480,993
I have two table users and Areas.Areas has a relation with users.So I have add users\_id in Areas table.After bake I get the output fine.But here in areas add form user field is showing users\_id in select box.Here I want to show users\_name.How can I change it? Here is the model code ``` MadAreas' => array( 'className' => 'MadAreas', 'foreignKey' => 'users_id' ) ``` In controller ``` $madAreas = $this->MadArea->Users->find('list'); ``` In add.ctp ``` echo $this->Form->input('users_id',array( 'label' => false, 'class'=>'form-control' )); ```
2014/10/21
[ "https://Stackoverflow.com/questions/26480993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4164819/" ]
Try specifying the fields you want in your find statement: ``` $madAreas = $this->MadArea->Users->find('list', array( 'fields' => array('id','username') ) ); ``` Changing the `$displayField` in the model as mentioned in @mponos-george's answer should do it anyways, just make sure you clear your Cache files after changing the model value.
Change the display field in your User model <http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield>
26,480,993
I have two table users and Areas.Areas has a relation with users.So I have add users\_id in Areas table.After bake I get the output fine.But here in areas add form user field is showing users\_id in select box.Here I want to show users\_name.How can I change it? Here is the model code ``` MadAreas' => array( 'className' => 'MadAreas', 'foreignKey' => 'users_id' ) ``` In controller ``` $madAreas = $this->MadArea->Users->find('list'); ``` In add.ctp ``` echo $this->Form->input('users_id',array( 'label' => false, 'class'=>'form-control' )); ```
2014/10/21
[ "https://Stackoverflow.com/questions/26480993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4164819/" ]
Try specifying the fields you want in your find statement: ``` $madAreas = $this->MadArea->Users->find('list', array( 'fields' => array('id','username') ) ); ``` Changing the `$displayField` in the model as mentioned in @mponos-george's answer should do it anyways, just make sure you clear your Cache files after changing the model value.
Have you set the data in your controller before rendering the view? ``` $this->Set(compact('madAreas')); ```
61,203,828
I have created a simple splash screen that is basically a `JFrame` with a background image, two `JLabels` and a `JProgressbar`. When I only render the frame with the background image it takes about 200 milliseconds which is a good time for the splash screen. But as soon as I add a JLabel (using Sansserif-font) it takes two seconds! So creating a string is 9 times as time intense as rendering an image. How can I reduce the rendering speed of the JLabels or of the panel? ``` private static final Dimension LOADINGSCREEN_DIMENSION = new Dimension(400, 400); private LoadingScreen() { super(); this.setUndecorated(true); this.setResizable(false); this.setLayout(new BorderLayout(0, 0)); this.setSize(LOADINGSCREEN_DIMENSION); this.setPreferredSize(LOADINGSCREEN_DIMENSION); this.setContentPane(createContentPane()); //UNCOMMENT THIS LINE and it will take about 2 seconds to create //this.add(createInformationLabel(), BorderLayout.SOUTH); //Set location and pack final Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); } private JLabel createInformationLabel() { JLabel infoLabel = new JLabel("Label"); infoLabel.setFont(new Font("SansSerif", Font.PLAIN, 12)); infoLabel.setHorizontalAlignment(SwingConstants.RIGHT); infoLabel.setBorder(new EmptyBorder(50, 0, 10, 20)); infoLabel.setOpaque(false); return infoLabel; } ```
2020/04/14
[ "https://Stackoverflow.com/questions/61203828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12707241/" ]
This has nothing to do with rendering speed. The rendering speed of all that is in the order of tens of milliseconds. The performance penalty you are witnessing has to do with loading classes. Before a `JFrame` can be rendered, its class needs to be loaded, and all classes that it depends on, and so on, and so forth. Then you are instantiating a `JLabel`. This class needs to be loaded, and all the classes that it depends on. Then you are instantiating a `Font`, so all font-related classes need to be loaded. I don't know, but there may even be some "font subsystem initialization" taking place. You get the picture. So, as it stands, you cannot avoid this overhead. You can try skipping the label and rendering the text yourself using "graphics", but I cannot promise that you will see any improvement this way. You can also look into the `SplashScreen` component, one would hope that it would be optimized, so as to involve as few classes as possible, so as to load as quickly as possible, but I have no experience with it. And, you might not be able to add text to it, either by `JLabel` or by rendering it yourself, or if you do, you will probably suffer all the overhead that you are currently experiencing.
I also have another answer for you. Your problem might be related to this issue, which is still open: **JDK-8179209 Text rendering has slow initialization time** <https://bugs.openjdk.java.net/browse/JDK-8179209> In short, java swing takes a long time to load fonts, and there is no solution to this other than to start loading fonts in the background, continue doing other application-startup-related things while the fonts are being loaded without trying to render any text, and then finally starting to render text once the fonts have been loaded. The openjdk issue contains some sample code for achieving this.
27,308,323
Trying to diagnose a work development laptop... What version of Clang and GCC come standard with OSX 10.10 Yosemite? This is what I have on my Mavericks... machine, will respond with my home iMac when it boots. ``` which clang /usr/bin/clang which gcc /usr/bin/gcc clang --version Apple LLVM version 4.2 (clang-425.0.27) (based on LLVM 3.2svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix gcc --version i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ```
2014/12/05
[ "https://Stackoverflow.com/questions/27308323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1655918/" ]
On my Mac OS X 10.10.1 with the current XCode (6.1.1 (6A2008a)), I get: ``` $ /usr/bin/clang --version Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix $ /usr/bin/gcc --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix $ ``` In other words, 'GCC' is no longer the real GNU `gcc` but is `clang`.
After many failed attempts at updating the C Compilers, we did a fresh install of Yosemite and it was fixed. Not a great solution, but without trying to hand build Clang the sane as Mac native it was the only solution.
27,308,323
Trying to diagnose a work development laptop... What version of Clang and GCC come standard with OSX 10.10 Yosemite? This is what I have on my Mavericks... machine, will respond with my home iMac when it boots. ``` which clang /usr/bin/clang which gcc /usr/bin/gcc clang --version Apple LLVM version 4.2 (clang-425.0.27) (based on LLVM 3.2svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix gcc --version i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ```
2014/12/05
[ "https://Stackoverflow.com/questions/27308323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1655918/" ]
Try running: `xcode-select --install`, followed by: `xcodebuild -license`
After many failed attempts at updating the C Compilers, we did a fresh install of Yosemite and it was fixed. Not a great solution, but without trying to hand build Clang the sane as Mac native it was the only solution.
63,232,480
I cannot figure out why this breaks it. I have an a element which uses CSS transitions to fade into a gradient background on hover. For whatever reason whenever I set the text color on hover to white the transition breaks? ```css .social-item { margin-left: 0.25vw; padding: 0.1vw; transition: 0.2s; color: white; } .social-item:hover { background: linear-gradient(to left, #8E2DE2, #DC0486); color: white; } ``` ```html <a href="https://google.com" class="social-item"><i class="fab fa-keybase"></i> Keybase</a> ``` I'm also using Bulma and Font Awesome.
2020/08/03
[ "https://Stackoverflow.com/questions/63232480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042866/" ]
Meanwhile here are the places (not all) where/how you can call a function ``` init() { self.testFunction() // non always good, but can } var body: some View { self.testFunction() // 1) return VStack { Text("TextBox") .onTapGesture { self.testFunction() // 2) } Text("SecondTextBox") } .onAppear { self.testFunction() // 3) } .onDisappear { self.testFunction() // 4) } } ``` ... and so on
**Using Swift 5.3 and Xcode 12.4** I use a little extension to debug inside the Views (VStack in the example), e.g. to inspect a geometryReader.size. It could be used to call any function in the View as follows: **NOTE: For debugging purposes only. I don't recommend including code like this in any production code** ``` VStack { Text.console("Hello, World") Text("TEXT" } extension Text { static func console<T>(_ value: T) -> EmptyView { print("\(value)") return EmptyView() } } ``` This will print "Hello, World" to the console.....
63,232,480
I cannot figure out why this breaks it. I have an a element which uses CSS transitions to fade into a gradient background on hover. For whatever reason whenever I set the text color on hover to white the transition breaks? ```css .social-item { margin-left: 0.25vw; padding: 0.1vw; transition: 0.2s; color: white; } .social-item:hover { background: linear-gradient(to left, #8E2DE2, #DC0486); color: white; } ``` ```html <a href="https://google.com" class="social-item"><i class="fab fa-keybase"></i> Keybase</a> ``` I'm also using Bulma and Font Awesome.
2020/08/03
[ "https://Stackoverflow.com/questions/63232480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042866/" ]
Meanwhile here are the places (not all) where/how you can call a function ``` init() { self.testFunction() // non always good, but can } var body: some View { self.testFunction() // 1) return VStack { Text("TextBox") .onTapGesture { self.testFunction() // 2) } Text("SecondTextBox") } .onAppear { self.testFunction() // 3) } .onDisappear { self.testFunction() // 4) } } ``` ... and so on
There is a reason, when writing in swift UI (iOS Apps), that there is a View protocol that needs to be followed. Calling functions from inside the structure is not compliant with the protocol. The best thing you can do is the .on(insertTimeORAction here). [Read more about it here](https://developer.apple.com/documentation/swiftui/text/onappear(perform:))
63,232,480
I cannot figure out why this breaks it. I have an a element which uses CSS transitions to fade into a gradient background on hover. For whatever reason whenever I set the text color on hover to white the transition breaks? ```css .social-item { margin-left: 0.25vw; padding: 0.1vw; transition: 0.2s; color: white; } .social-item:hover { background: linear-gradient(to left, #8E2DE2, #DC0486); color: white; } ``` ```html <a href="https://google.com" class="social-item"><i class="fab fa-keybase"></i> Keybase</a> ``` I'm also using Bulma and Font Awesome.
2020/08/03
[ "https://Stackoverflow.com/questions/63232480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042866/" ]
Meanwhile here are the places (not all) where/how you can call a function ``` init() { self.testFunction() // non always good, but can } var body: some View { self.testFunction() // 1) return VStack { Text("TextBox") .onTapGesture { self.testFunction() // 2) } Text("SecondTextBox") } .onAppear { self.testFunction() // 3) } .onDisappear { self.testFunction() // 4) } } ``` ... and so on
An additional method: Testing with Swift 5.8, you can also stick in a `let _ = self.testFunction()`. eg (this is extra-contrived so that it's possible to see the effect in Preview, because print() doesn't happen in Preview, at least for me) ``` import SwiftUI class MyClass { var counter = 0 } struct ContentView: View { var myClass: MyClass var body: some View { VStack { Text("TextBox counter = \(myClass.counter)") // v-------------------------------------------- // let _ = self.testFunction() // compiles happily // self.testFunction() // does not compile // // ^-------------------------------------------- Text("TextBox counter = \(myClass.counter)") } } func testFunction() { print("This is a Test.") myClass.counter += 1 } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(myClass: MyClass()) } } ```
63,232,480
I cannot figure out why this breaks it. I have an a element which uses CSS transitions to fade into a gradient background on hover. For whatever reason whenever I set the text color on hover to white the transition breaks? ```css .social-item { margin-left: 0.25vw; padding: 0.1vw; transition: 0.2s; color: white; } .social-item:hover { background: linear-gradient(to left, #8E2DE2, #DC0486); color: white; } ``` ```html <a href="https://google.com" class="social-item"><i class="fab fa-keybase"></i> Keybase</a> ``` I'm also using Bulma and Font Awesome.
2020/08/03
[ "https://Stackoverflow.com/questions/63232480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042866/" ]
**Using Swift 5.3 and Xcode 12.4** I use a little extension to debug inside the Views (VStack in the example), e.g. to inspect a geometryReader.size. It could be used to call any function in the View as follows: **NOTE: For debugging purposes only. I don't recommend including code like this in any production code** ``` VStack { Text.console("Hello, World") Text("TEXT" } extension Text { static func console<T>(_ value: T) -> EmptyView { print("\(value)") return EmptyView() } } ``` This will print "Hello, World" to the console.....
An additional method: Testing with Swift 5.8, you can also stick in a `let _ = self.testFunction()`. eg (this is extra-contrived so that it's possible to see the effect in Preview, because print() doesn't happen in Preview, at least for me) ``` import SwiftUI class MyClass { var counter = 0 } struct ContentView: View { var myClass: MyClass var body: some View { VStack { Text("TextBox counter = \(myClass.counter)") // v-------------------------------------------- // let _ = self.testFunction() // compiles happily // self.testFunction() // does not compile // // ^-------------------------------------------- Text("TextBox counter = \(myClass.counter)") } } func testFunction() { print("This is a Test.") myClass.counter += 1 } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(myClass: MyClass()) } } ```
63,232,480
I cannot figure out why this breaks it. I have an a element which uses CSS transitions to fade into a gradient background on hover. For whatever reason whenever I set the text color on hover to white the transition breaks? ```css .social-item { margin-left: 0.25vw; padding: 0.1vw; transition: 0.2s; color: white; } .social-item:hover { background: linear-gradient(to left, #8E2DE2, #DC0486); color: white; } ``` ```html <a href="https://google.com" class="social-item"><i class="fab fa-keybase"></i> Keybase</a> ``` I'm also using Bulma and Font Awesome.
2020/08/03
[ "https://Stackoverflow.com/questions/63232480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042866/" ]
There is a reason, when writing in swift UI (iOS Apps), that there is a View protocol that needs to be followed. Calling functions from inside the structure is not compliant with the protocol. The best thing you can do is the .on(insertTimeORAction here). [Read more about it here](https://developer.apple.com/documentation/swiftui/text/onappear(perform:))
An additional method: Testing with Swift 5.8, you can also stick in a `let _ = self.testFunction()`. eg (this is extra-contrived so that it's possible to see the effect in Preview, because print() doesn't happen in Preview, at least for me) ``` import SwiftUI class MyClass { var counter = 0 } struct ContentView: View { var myClass: MyClass var body: some View { VStack { Text("TextBox counter = \(myClass.counter)") // v-------------------------------------------- // let _ = self.testFunction() // compiles happily // self.testFunction() // does not compile // // ^-------------------------------------------- Text("TextBox counter = \(myClass.counter)") } } func testFunction() { print("This is a Test.") myClass.counter += 1 } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(myClass: MyClass()) } } ```
29,020,638
Currently if I set the TERM environment variable to 'xterm-1003' I can get mouse move events but I get crappy colors and curses.can\_change\_color() == False ``` os.environ['TERM'] = 'xterm-1003' ... curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION) ... while True: event = screen.getch() if event == curses.KEY_MOUSE: # I get nice events whenever I move the mouse (no click required) _, mx, my, _, _ = curses.getmouse() ``` and if I set the TERM env var to 'xterm-256color' I get a nice color palette plus curses.can\_change\_color() == True, however I do not receive mouse events unless I click a button! ``` >ls /usr/share/terminfo/x/ ``` reports ``` xfce xterm-256color xterm-hp xterm-r5 xterm-xf86-v32 xterm-xfree86 xterm xterm-88color xterm-new xterm-r6 xterm-xf86-v33 xterm-xi xterm-1002 xterm-8bit xterm-nic xterm-sco xterm-xf86-v333 xterms xterm-1003 xterm-basic xterm-noapp xterm-sun xterm-xf86-v40 xterm-16color xterm-bold xterm-old xterm-vt220 xterm-xf86-v43 xterm-24 xterm-color xterm-pcolor xterm-vt52 xterm-xf86-v44 ``` None of the ones I tried seem to support both curses.can\_change\_color() == True and mouse move events. Is there a way I can get both of them via setting an appropriate $TERM value or some other way? Thank you!
2015/03/12
[ "https://Stackoverflow.com/questions/29020638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4424383/" ]
You can always make your own, using [infocmp](http://invisible-island.net/ncurses/man/infocmp.1m.html) (to show the contents of an entry), and [tic](http://invisible-island.net/ncurses/man/tic.1m.html) (to compile an entry). If you do not have permission to write in the system area, it goes to $HOME/.terminfo Start by comparing [xterm-1003](http://invisible-island.net/ncurses/terminfo.src.html#tic-xterm-1003) and [xterm-256color](http://invisible-island.net/ncurses/terminfo.src.html#tic-xterm-256color): ``` > infocmp -x xterm-1003 xterm-256color comparing xterm-1003 to xterm-256color. comparing booleans. ccc: F:T. comparing numbers. colors: 8, 256. pairs: 64, 32767. comparing strings. initc: NULL, '\E]4;%p1%d;rgb\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\E\\'. setab: '\E[4%p1%dm', '\E[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m'. setaf: '\E[3%p1%dm', '\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m'. setb: '\E[4%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m', NULL. setf: '\E[3%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m', NULL. XM: '\E[?1003%?%p1%{1}%=%th%el%;', NULL. ``` Essentially, all you are interested in is adding the `XM` capability to a copy of `xterm-256color`. So... 1. `infocmp -x xterm-256color >foo` 2. edit `foo`, adding the `XM` string 3. `tic -x foo` The "-x" option is needed for `tic` to compile the `XM` capability, which is an *extended* (user-defined) capability which ncurses happens to recognize as noted in comments for the [terminal database](http://invisible-island.net/ncurses/terminfo.src.html#toc-_X_T_E_R_M__Extensions_).
The problem: **Mouse position reported even when no mouse button held down.** This answer is intended to be an extension of the other [answer here posted by Thomas Dickey](https://stackoverflow.com/a/29023361/7915759). Using the links provided and basic steps, I managed to find an XM string that gave me the mouse behavior I wanted. The problem I had with the XM string in the other answer is the mouse position was reported even when no mouse button was held down. I wanted mouse position only when a mouse button was down. In other words, I wanted "mouse drag" events. The constant reporting might be good for implementing a "mouse hover" feature, but I didn't need that so all the extra reporting was just causing wasted cycles in the app's event loop. The steps I took to find the right XM string were: 1. Create a 'foo' file as described in the other answer: `infocmp -x xterm-256color > foo` 2. Take the text from the [terminal database](https://invisible-island.net/ncurses/terminfo.src.html#toc-_X_T_E_R_M__Extensions_) link and extract all the XM strings (provided below). 3. Add one of the XM strings to my copy of 'foo' and issue `tic -x foo` (the new config is immediately active). 4. Run my program to see if the mouse position behaved as wanted. 5. If the behavior was different, go back to step 3 and try the next string. The (commented out) XM strings as extracted from the "terminal database" link: ``` # XM=\E[?9%?%p1%{1}%=%th%el%;, # XM=\E[?9%?%p1%{1}%=%th%el%;, # xm=\E[M%p3%' '%+%c%p2%'!'%+%c%p1%'!'%+%c, # XM=\E[?1000%?%p1%{1}%=%th%el%;, # xm=\E[M%?%p4%t%p3%e%{3}%;%'\s'%+%c%p2%'!'%+%c%p1%'!'%+%c, # XM=\E[?1001%?%p1%{1}%=%th%el%;, # XM=\E[?1002%?%p1%{1}%=%th%el%;, # XM=\E[?1003%?%p1%{1}%=%th%el%;, # XM=\E[?1005;1000%?%p1%{1}%=%th%el%;, # xm=\E[M%?%p4%t3%e%p3%'\s'%+%c%;%p2%'!'%+%u%p1%'!'%+%u, # XM=\E[?1006;1000%?%p1%{1}%=%th%el%;, # xm=\E[<%i%p3%d;%p1%d;%p2%d;%?%p4%tM%em%;, ``` The string that worked for my Ubuntu 20 sytem's bash terminal was: ``` XM=\E[?1002%?%p1%{1}%=%th%el%;, ``` I anticipate some extra future work enabling this behavior on other systems when my app is nearly ready for distribution. Another potential problem is this hack may affect bash behavior generally - not just when my app is running in a bash terminal. Maybe a better solution would be not to tweak the `xterm-256color` file, but create a custom file of another name unlikely to be confused with the standard files. Then in my application set the `TERM` environment variable to it before initiating `curses`. ```py os.environ['TERM'] = 'mouse-tweaked-xterm-256color' curses.wrapper(start_my_app) ``` Update: The new `xterm-256color` file produced by `tic` was located on my system under `${HOME}/.terminfo/x/`. I changed its name and implemented the above code to set `TERM` in the application.
39,021,119
I need build port with something as in shell: > > cd /usr/ports/www/nginx/ && make HTTP\_GEOIP=YES BATCH=yes > > > I can find [any](http://docs.ansible.com/ansible/portinstall_module.html) document, how run this with [ansible module portinstall](https://github.com/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py) =(
2016/08/18
[ "https://Stackoverflow.com/questions/39021119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948657/" ]
I'd propose to keep local file of customized build options and copy it to the host before portinstall. ``` - name: Copy customized build options copy: src="{{role_path}}/files/nginx-build-options" dest="/var/db/ports/www_nginx/options" - name: Install nginx from the port portinstall: name=nginx state=present ```
Seems like this operation is not implemented in the [port\_install module](http://docs.ansible.com/ansible/portinstall_module.html) The module is part of the [ansible-module-extra repository](http://docs.ansible.com/ansible/modules_extra.html) which means: > > These modules are currently shipped with Ansible, but might be shipped separately in the future. They are also mostly maintained by the community. Non-core modules are still fully usable, but may receive slightly lower response rates for issues and pull requests. > > > As BSD is (sadly) not very popular, chances that someone will implement the functionality is not very high. But it is possible to work around these limitations by using the `command` module like this: ``` - name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/ ``` I would recommend to write another task to check the state / version of the port installed on the system and add a `when` clause to the task otherwise Ansible would rebuild the port on every run.
39,021,119
I need build port with something as in shell: > > cd /usr/ports/www/nginx/ && make HTTP\_GEOIP=YES BATCH=yes > > > I can find [any](http://docs.ansible.com/ansible/portinstall_module.html) document, how run this with [ansible module portinstall](https://github.com/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py) =(
2016/08/18
[ "https://Stackoverflow.com/questions/39021119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948657/" ]
I'd like to add. Unfortunately, the proposed workaround is not idempotent. `- name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/` This means, that it will be always reported as "changed".
Seems like this operation is not implemented in the [port\_install module](http://docs.ansible.com/ansible/portinstall_module.html) The module is part of the [ansible-module-extra repository](http://docs.ansible.com/ansible/modules_extra.html) which means: > > These modules are currently shipped with Ansible, but might be shipped separately in the future. They are also mostly maintained by the community. Non-core modules are still fully usable, but may receive slightly lower response rates for issues and pull requests. > > > As BSD is (sadly) not very popular, chances that someone will implement the functionality is not very high. But it is possible to work around these limitations by using the `command` module like this: ``` - name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/ ``` I would recommend to write another task to check the state / version of the port installed on the system and add a `when` clause to the task otherwise Ansible would rebuild the port on every run.
39,021,119
I need build port with something as in shell: > > cd /usr/ports/www/nginx/ && make HTTP\_GEOIP=YES BATCH=yes > > > I can find [any](http://docs.ansible.com/ansible/portinstall_module.html) document, how run this with [ansible module portinstall](https://github.com/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py) =(
2016/08/18
[ "https://Stackoverflow.com/questions/39021119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948657/" ]
I'd like to add. Unfortunately, the proposed workaround is not idempotent. `- name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/` This means, that it will be always reported as "changed".
I'd propose to keep local file of customized build options and copy it to the host before portinstall. ``` - name: Copy customized build options copy: src="{{role_path}}/files/nginx-build-options" dest="/var/db/ports/www_nginx/options" - name: Install nginx from the port portinstall: name=nginx state=present ```
56,246,805
I have a Map and a HashSet. The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map. ``` // Map is defined in a class private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<A> hSet = new HashSet<>(); for (A a : ab){ hSet.add(a..a...); // Check if all elements added to hash Set are there in a Map // if not present, add it to Map } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56246805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477352/" ]
if you want to search in map values: ``` if(!map.values().contains(a)) // put a in the map ``` if you want to look for keys ``` if(!map.containsKey(a)) // put a in the map ``` keep in mind that contains calls equals so in your A class you have to implement hashCode and equals.
``` for (String element : hSet) { if (!sb.containsKey(element)) { sb.put(element, A); } } ```
56,246,805
I have a Map and a HashSet. The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map. ``` // Map is defined in a class private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<A> hSet = new HashSet<>(); for (A a : ab){ hSet.add(a..a...); // Check if all elements added to hash Set are there in a Map // if not present, add it to Map } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56246805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477352/" ]
``` public static void main(String[] args) { Set<String> set = Stream.of("a","b","c","d").collect(Collectors.toSet()); Map<String, String> map = new HashMap<String, String>(); map.put("a", "foo"); map.put("h", "bar"); map.put("c", "ipsum"); for (String string : set) { if(!map.containsKey(string)) { map.put(string,string); } } System.out.println(map); } ``` output ``` {a=foo, b=b, c=ipsum, d=d, h=bar} ```
``` for (String element : hSet) { if (!sb.containsKey(element)) { sb.put(element, A); } } ```
56,246,805
I have a Map and a HashSet. The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map. ``` // Map is defined in a class private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<A> hSet = new HashSet<>(); for (A a : ab){ hSet.add(a..a...); // Check if all elements added to hash Set are there in a Map // if not present, add it to Map } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56246805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477352/" ]
``` for (String element : hSet) { if (!sb.containsKey(element)) { sb.put(element, A); } } ```
Following could also be solution: ``` private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<String> set = new HashSet<>(); set.stream().filter(word -> !sb.containsKey(word)) .forEach(word -> sb.put(word, correspondingValueOfTypeA)); } ```
56,246,805
I have a Map and a HashSet. The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map. ``` // Map is defined in a class private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<A> hSet = new HashSet<>(); for (A a : ab){ hSet.add(a..a...); // Check if all elements added to hash Set are there in a Map // if not present, add it to Map } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56246805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477352/" ]
if you want to search in map values: ``` if(!map.values().contains(a)) // put a in the map ``` if you want to look for keys ``` if(!map.containsKey(a)) // put a in the map ``` keep in mind that contains calls equals so in your A class you have to implement hashCode and equals.
Following could also be solution: ``` private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<String> set = new HashSet<>(); set.stream().filter(word -> !sb.containsKey(word)) .forEach(word -> sb.put(word, correspondingValueOfTypeA)); } ```
56,246,805
I have a Map and a HashSet. The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map. ``` // Map is defined in a class private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<A> hSet = new HashSet<>(); for (A a : ab){ hSet.add(a..a...); // Check if all elements added to hash Set are there in a Map // if not present, add it to Map } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56246805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11477352/" ]
``` public static void main(String[] args) { Set<String> set = Stream.of("a","b","c","d").collect(Collectors.toSet()); Map<String, String> map = new HashMap<String, String>(); map.put("a", "foo"); map.put("h", "bar"); map.put("c", "ipsum"); for (String string : set) { if(!map.containsKey(string)) { map.put(string,string); } } System.out.println(map); } ``` output ``` {a=foo, b=b, c=ipsum, d=d, h=bar} ```
Following could also be solution: ``` private final Map<String, A> sb = new ConcurrentHashMap<>(); public void someMethod() { Set<String> set = new HashSet<>(); set.stream().filter(word -> !sb.containsKey(word)) .forEach(word -> sb.put(word, correspondingValueOfTypeA)); } ```
445,763
I have a few hundred files named hortstu01-01-14 then hortstu01-02-14... Do you get the idea? Well half of the files are named hortstu\_01-03-14 then hortstu\_01-04-14. This messes up sorting the files by name and getting them in the order I'd prefer them to be. So I'd like to rename the ones without the underscore to hortstu\_ Is it possible to do this in a batch operation? If so how?
2014/04/10
[ "https://askubuntu.com/questions/445763", "https://askubuntu.com", "https://askubuntu.com/users/121408/" ]
Open a terminal. Firstly, double check you have the perl `rename`, by typing `man rename`. At the bottom, it should say `perl v5.18.2` or similar. (I think Ubuntu always ships the perl `rename`, but other distros ship other versions.) If it's the correct version, then `cd` to the directory that contains these files. Then run ``` rename 's/^hortstu/hortstu_/' hortstu[!_]* ``` Explanation ----------- * This will rename all files that match `hortstu[!_]*`. This means files that start with `hortstu`, and do *not* have `_` next. * It will then rename them by + finding `^hortstu` (i.e. `hortstu` at the beginning of the string) + replacing it with `hortstu_`. * N.B. the format for `hortstu[!_]*` is a [bash glob](http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). The format for `^hortstu` is a regular expression.
Or a Bash one liner navigate to the folder with the files and then run this in terminal: ``` for file in hortsu*;do echo "$file" "${file/_/-}";done; ``` Basically what this does is for files with the name 'hortsu' followed by any characters '\*', echo the name of "$file" and also the name of file with all underscores replaced with dashes. When you feel comfortable with that just replace `echo` with `cp` to copy the files to the new name. A pythonic solution. Try this in a safe environement, maybe copy one or two files over to a new folder to test how it works. Save the following code in gedit and give it a name with a file extension of '.py' something like `rename_files_in_current_directory.py`: ``` # copy this code into gedit and save it to the directory with the files in it import os # for files in the current directory ('.') for file_names in os.listdir('.'): if '_' in file_names: # using os.system use cp (copy) to copy file_names to file-names by replacing # underscore with dash os.system('cp '+file_names+' '+file_names.replace('_','-')) ``` Make sure python is installed. 'sudo apt-get install python' Navigate to the folder in terminal with the script and the files and then run: ``` python the_name_given_to_the_python_script.py ``` **Note:** You can delete the dashes in the above commands and scripts will remove the underscores. ``` for file in hortsu*;do cp "$file" "${file/_/}";done; ``` or in the python script change: `file_names.replace('_','-')` to `file_names.replace('_','')`
445,763
I have a few hundred files named hortstu01-01-14 then hortstu01-02-14... Do you get the idea? Well half of the files are named hortstu\_01-03-14 then hortstu\_01-04-14. This messes up sorting the files by name and getting them in the order I'd prefer them to be. So I'd like to rename the ones without the underscore to hortstu\_ Is it possible to do this in a batch operation? If so how?
2014/04/10
[ "https://askubuntu.com/questions/445763", "https://askubuntu.com", "https://askubuntu.com/users/121408/" ]
Open a terminal. Firstly, double check you have the perl `rename`, by typing `man rename`. At the bottom, it should say `perl v5.18.2` or similar. (I think Ubuntu always ships the perl `rename`, but other distros ship other versions.) If it's the correct version, then `cd` to the directory that contains these files. Then run ``` rename 's/^hortstu/hortstu_/' hortstu[!_]* ``` Explanation ----------- * This will rename all files that match `hortstu[!_]*`. This means files that start with `hortstu`, and do *not* have `_` next. * It will then rename them by + finding `^hortstu` (i.e. `hortstu` at the beginning of the string) + replacing it with `hortstu_`. * N.B. the format for `hortstu[!_]*` is a [bash glob](http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). The format for `^hortstu` is a regular expression.
For those who prefer GUI applications or just like the ability to preview the result, you might want to install Thunar. It's the main file manager of XFCE; you find it in the repositories. When you select multiple files in Thunar and rename them (via context menu or F2), you get an elaborate dialog which support all kinds of rename operations. You can solve your problem like so: ![enter image description here](https://i.stack.imgur.com/iN737.png)
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Python, 54 bytes ---------------- ```py f=lambda n,a=1,b=1:n<1or b>n and a*f(n-a)or f(n,b,a+b) ``` Just some good old recursion.
Haskell, 44 bytes ================= Yay for mutual recursion: ``` (a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c f=0&1 ``` * `a` is the previous Fibonacci number * `b` is the current Fibonacci number * `c` is the input * `f` is the desired function Less golfed: ``` (a & b) c | c == 0 = 1 | c < b = a * f (c-a) | otherwise = b & (a + b) $ c f x = (0 & 1) x ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
[Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ========================================================== ``` ŒṗḟÐḟÆḞ€ṪP ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7pz/cMf/wBBDR9nDHvEdNax7uXBXw//9/MwMA "Jelly – Try It Online") Times out for \$n > 60\$ How it works ------------ ``` ŒṗḟÐḟÆḞ€ṪP - Main link. Takes n on the left Œṗ - Integer partitions of n ÆḞ€ - First n Fibonacci numbers Ðḟ - Keep the partitions p which yield an empty list under: ḟ - Remove all elements of p which are in the first n Fibonacci numbers Ṫ - Take the last element P - Product ```
Javascript (ES6) ~~134~~ ~~106~~ 92 bytes ========================================= Thanks for @cat for spotting a space. ``` n=>{for(c=[a=b=s=1,1];a+b<=n;)a+=b,c.unshift(b+=a,a);c.map(i=>i<=n&&(n-=i)&(s*=i));alert(s)} ``` Just an unoptimized version made on my phone, I golf it down, once I get home. Ideas are welcome.
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Python, 54 bytes ---------------- ```py f=lambda n,a=1,b=1:n<1or b>n and a*f(n-a)or f(n,b,a+b) ``` Just some good old recursion.
Q, 47 Bytes ----------- ``` m:{*/1_-':|(0<){y-x x bin y}[*+60(|+\)\1 0]\x} ``` **Test** ``` +(i;m'i:1 2 3 4 5 6 7 8 9 42 1000 12345) ``` read it as pairs (i,map(m,i)), where m is the calculating function and i the different args writes ``` 1 1 2 2 3 3 4 3 5 5 6 5 7 10 8 8 9 8 42 272 1000 12831 12345 138481852236 ``` **Explanation** `n funtion\arg` applies function(function(function(...function(args))) n times (internally uses tal recursion), and returns the sequence of results. We calculate the 60 first items of fibonnaci series as `*+60(|+\)\1 0`. In that case the function is (|+): +\ applied over a sequence calculates partial sums (ex +\1 2 3 is 1 3 6), and | reverses seq. So each 'iteration' we calculate partial sums of the two previous fibonacci number and return the partial sums reversed. `60(|+\)\1 0` generates sequences 1 0, 1 1, 2 1, 3 2, 5 3, 8 5, 13 8, 21 13, ... `*+` applied over this result flip (traspose) it and takes the first. Result is sequence 1 1 2 3 5 8 13 21 34 55 .. `(cond)function\args` applies function(function(..function(args))) while cond true, and returns the sequence of partial results `function[arg]` applied over a function of more than one argument creates a projection (partial application) We can give name to the args, but the implicit names are x,y,z `{y-x x bin y}[*+60(|+\)\1 0]` declares a lambda with args x,y with partial projection (arg x is fibonacci series, calculates as \*+60(|+)\1 0). x represent fibonacci values, and y the number to process. Binary search (bin) is used to locate the index of the greater fibonacci number <=y (`x bin y`), and substract the corresponding value of x. To calculate product from partial resuls we reverse them and calculate difference of each pair (`-':|`), drop the first (`1_` because is 0) and multiply over (`*/`). If we are interested in accumulated sum the code is the same, but with `+/` instead of `*/`. We can also use any other diadic operator instead of + or \* **About execution efficiency** I know that in this contest efficiency is not an issue. But in this problem we can range from lineal cost to exponential cost, so i'm curious about it. I developed a second version (length 48 Bytes excluding comment) and repeated test cases battery 1000 times on both versions. ``` f:*+60(|+\)\1 0;m:{*/1_-':|(0<){x-f f bin x}\x} /new version ``` execution time is: original version 0'212 seg, new version 0'037 seg Original version calculates fibbonaci serie once per function application; new version calculates fibonacci just one. In both cases calculation of fibonacci series uses tail recursion
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Haskell, 44 bytes ================= Yay for mutual recursion: ``` (a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c f=0&1 ``` * `a` is the previous Fibonacci number * `b` is the current Fibonacci number * `c` is the input * `f` is the desired function Less golfed: ``` (a & b) c | c == 0 = 1 | c < b = a * f (c-a) | otherwise = b & (a + b) $ c f x = (0 & 1) x ```
Actually, 22 bytes ------------------ ``` W;╗uR♂F;`╜≥`M░M;╜-WXkπ ``` [Try it online!](http://actually.tryitonline.net/#code=VzvilZd1UuKZgkY7YOKVnOKJpWBN4paRTTvilZwtV1hrz4A&input=MTAw) Explanation: ``` W;╗uR♂F;`╜≥`M░M;╜-WXkπ (implicit input) W W while top of stack is truthy: ;╗ push a copy of n to reg0 uR♂F; push 2 copies of [Fib(a) for a in range(1, n+2)] `╜≥`M░ filter: take values where n <= Fib(a) M; two copies of maximum (call it m) ╜- subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it) X discard the 0 left over after the loop ends kπ product of all stack values ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
[Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ========================================================================================================================== ``` Rf1+С¤ṪạµÐĿIAP ``` Not particularly fast or memory friendly, but efficient enough for all test cases. [Try it online!](http://jelly.tryitonline.net/#code=UmYxK8OQwqHCpOG5quG6ocK1w5DEv0lBUA&input=&args=MTIzNDU) ### How it works ``` Rf1+С¤ṪạµÐĿIAP Main link. Argument: n (integer) µ Combine the chain to the left into a link. ÐĿ Apply that link until the results are no longer unique. Return the list of unique results. ¤ Combine the two links to the left into a niladic chain. 1 Set the left (and right) argument to 1. +D¡ Apply + to the left and right argument, updating the left argument with the sum, and the right argument with the previous value of the left one. Return the list of results. Repeat this process n times. This yields n + 1 Fibonacci numbers, starting with 1, 2. R Range; map k to [1, ..., k]. f Filter; keep the items in the range that are Fibonacci numbers. Ṫ Tail; yield the last one or 0 if the list is empty. ạ Absolute difference with k. This is the argument of the next iteration. I Compute the increments of the arguments to the loop, yielding the selected Fibonacci numbers (with changed sign). A Apply absolute value to each. P Compute their product. ```
Actually, 22 bytes ------------------ ``` W;╗uR♂F;`╜≥`M░M;╜-WXkπ ``` [Try it online!](http://actually.tryitonline.net/#code=VzvilZd1UuKZgkY7YOKVnOKJpWBN4paRTTvilZwtV1hrz4A&input=MTAw) Explanation: ``` W;╗uR♂F;`╜≥`M░M;╜-WXkπ (implicit input) W W while top of stack is truthy: ;╗ push a copy of n to reg0 uR♂F; push 2 copies of [Fib(a) for a in range(1, n+2)] `╜≥`M░ filter: take values where n <= Fib(a) M; two copies of maximum (call it m) ╜- subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it) X discard the 0 left over after the loop ends kπ product of all stack values ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
[Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ========================================================================================================================== ``` Rf1+С¤ṪạµÐĿIAP ``` Not particularly fast or memory friendly, but efficient enough for all test cases. [Try it online!](http://jelly.tryitonline.net/#code=UmYxK8OQwqHCpOG5quG6ocK1w5DEv0lBUA&input=&args=MTIzNDU) ### How it works ``` Rf1+С¤ṪạµÐĿIAP Main link. Argument: n (integer) µ Combine the chain to the left into a link. ÐĿ Apply that link until the results are no longer unique. Return the list of unique results. ¤ Combine the two links to the left into a niladic chain. 1 Set the left (and right) argument to 1. +D¡ Apply + to the left and right argument, updating the left argument with the sum, and the right argument with the previous value of the left one. Return the list of results. Repeat this process n times. This yields n + 1 Fibonacci numbers, starting with 1, 2. R Range; map k to [1, ..., k]. f Filter; keep the items in the range that are Fibonacci numbers. Ṫ Tail; yield the last one or 0 if the list is empty. ạ Absolute difference with k. This is the argument of the next iteration. I Compute the increments of the arguments to the loop, yielding the selected Fibonacci numbers (with changed sign). A Apply absolute value to each. P Compute their product. ```
JavaScript (ES6), ~~78~~ 42 bytes --------------------------------- ``` f=(n,a=1,b=1)=>n?b>n?a*f(n-a):f(n,b,a+b):1 ``` Port of @Sp3000's answer. Original 78 byte version: ``` f=(n,a=[2,1])=>n>a[0]?f(n,[a[0]+a[1],...a]):a.map(e=>e>n?0:(r*=e,n-=e),r=1)&&r ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
[Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ========================================================== ``` ŒṗḟÐḟÆḞ€ṪP ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7pz/cMf/wBBDR9nDHvEdNax7uXBXw//9/MwMA "Jelly – Try It Online") Times out for \$n > 60\$ How it works ------------ ``` ŒṗḟÐḟÆḞ€ṪP - Main link. Takes n on the left Œṗ - Integer partitions of n ÆḞ€ - First n Fibonacci numbers Ðḟ - Keep the partitions p which yield an empty list under: ḟ - Remove all elements of p which are in the first n Fibonacci numbers Ṫ - Take the last element P - Product ```
Q, 47 Bytes ----------- ``` m:{*/1_-':|(0<){y-x x bin y}[*+60(|+\)\1 0]\x} ``` **Test** ``` +(i;m'i:1 2 3 4 5 6 7 8 9 42 1000 12345) ``` read it as pairs (i,map(m,i)), where m is the calculating function and i the different args writes ``` 1 1 2 2 3 3 4 3 5 5 6 5 7 10 8 8 9 8 42 272 1000 12831 12345 138481852236 ``` **Explanation** `n funtion\arg` applies function(function(function(...function(args))) n times (internally uses tal recursion), and returns the sequence of results. We calculate the 60 first items of fibonnaci series as `*+60(|+\)\1 0`. In that case the function is (|+): +\ applied over a sequence calculates partial sums (ex +\1 2 3 is 1 3 6), and | reverses seq. So each 'iteration' we calculate partial sums of the two previous fibonacci number and return the partial sums reversed. `60(|+\)\1 0` generates sequences 1 0, 1 1, 2 1, 3 2, 5 3, 8 5, 13 8, 21 13, ... `*+` applied over this result flip (traspose) it and takes the first. Result is sequence 1 1 2 3 5 8 13 21 34 55 .. `(cond)function\args` applies function(function(..function(args))) while cond true, and returns the sequence of partial results `function[arg]` applied over a function of more than one argument creates a projection (partial application) We can give name to the args, but the implicit names are x,y,z `{y-x x bin y}[*+60(|+\)\1 0]` declares a lambda with args x,y with partial projection (arg x is fibonacci series, calculates as \*+60(|+)\1 0). x represent fibonacci values, and y the number to process. Binary search (bin) is used to locate the index of the greater fibonacci number <=y (`x bin y`), and substract the corresponding value of x. To calculate product from partial resuls we reverse them and calculate difference of each pair (`-':|`), drop the first (`1_` because is 0) and multiply over (`*/`). If we are interested in accumulated sum the code is the same, but with `+/` instead of `*/`. We can also use any other diadic operator instead of + or \* **About execution efficiency** I know that in this contest efficiency is not an issue. But in this problem we can range from lineal cost to exponential cost, so i'm curious about it. I developed a second version (length 48 Bytes excluding comment) and repeated test cases battery 1000 times on both versions. ``` f:*+60(|+\)\1 0;m:{*/1_-':|(0<){x-f f bin x}\x} /new version ``` execution time is: original version 0'212 seg, new version 0'037 seg Original version calculates fibbonaci serie once per function application; new version calculates fibonacci just one. In both cases calculation of fibonacci series uses tail recursion
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Perl, ~~69~~ 63 + 4 (`-pl61` flag) = 67 bytes ============================================= ``` #!perl -pl61 while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{ ``` Using: ``` > echo 42 | perl -pl61e 'while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{' ``` Ungolfed: ```perl while (<>) { # code above added by -p # $_ has input value # $\ = 1 by -l61 while ($_ != 0) { my $n = 1; my $m = 1; while ($m <= $_) { ($n, $m) = ($m, $n + $m); } $_ -= $n; $\ *= $n; } } { # code below added by -p print; # prints $_ (undef here) and $\ } ``` [Ideone](http://ideone.com/Bt2ueH).
Haskell, 44 bytes ================= Yay for mutual recursion: ``` (a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c f=0&1 ``` * `a` is the previous Fibonacci number * `b` is the current Fibonacci number * `c` is the input * `f` is the desired function Less golfed: ``` (a & b) c | c == 0 = 1 | c < b = a * f (c-a) | otherwise = b & (a + b) $ c f x = (0 & 1) x ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Perl, ~~69~~ 63 + 4 (`-pl61` flag) = 67 bytes ============================================= ``` #!perl -pl61 while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{ ``` Using: ``` > echo 42 | perl -pl61e 'while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{' ``` Ungolfed: ```perl while (<>) { # code above added by -p # $_ has input value # $\ = 1 by -l61 while ($_ != 0) { my $n = 1; my $m = 1; while ($m <= $_) { ($n, $m) = ($m, $n + $m); } $_ -= $n; $\ *= $n; } } { # code below added by -p print; # prints $_ (undef here) and $\ } ``` [Ideone](http://ideone.com/Bt2ueH).
[RETURN](https://github.com/molarmanful/RETURN), 44 bytes ========================================================= ``` [a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#] ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Astonishingly inefficient anonymous lambda that leaves result on Stack2. Usage: ``` 12345[a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#]! ``` NOTE: ␌ and ␁ are placeholders for their respective unprintable chars: [Form Feed](http://unicode-table.com/en/240C/) and [Start of Heading](http://unicode-table.com/en/2401/). Explanation =========== ``` [ ] lambda a: store input to a [ ][ ]# while loop a; check if a is truthy 1$[¤¤+$a;->~][]#% if so, generate all fibonacci numbers less than a $␌ push copy of TOS to stack2 a;\-a: a-=TOS ␁[¤][×]# get product of stack2 ```
79,854
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.: ``` 1 = 1 2 = 2 3 = 3 4 = 3 + 1 12 = 8 + 3 + 1 13 = 13 100 = 89 + 8 + 3 ``` Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$. Write a program or function that given a positive integer *n* returns the Fibonacci product of that number. --- Testcases: ``` 1: 1 2: 2 3: 3 4: 3 5: 5 6: 5 7: 10 8: 8 9: 8 42: 272 1000: 12831 12345: 138481852236 ```
2016/05/13
[ "https://codegolf.stackexchange.com/questions/79854", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/4162/" ]
Perl, ~~69~~ 63 + 4 (`-pl61` flag) = 67 bytes ============================================= ``` #!perl -pl61 while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{ ``` Using: ``` > echo 42 | perl -pl61e 'while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{' ``` Ungolfed: ```perl while (<>) { # code above added by -p # $_ has input value # $\ = 1 by -l61 while ($_ != 0) { my $n = 1; my $m = 1; while ($m <= $_) { ($n, $m) = ($m, $n + $m); } $_ -= $n; $\ *= $n; } } { # code below added by -p print; # prints $_ (undef here) and $\ } ``` [Ideone](http://ideone.com/Bt2ueH).
Q, 47 Bytes ----------- ``` m:{*/1_-':|(0<){y-x x bin y}[*+60(|+\)\1 0]\x} ``` **Test** ``` +(i;m'i:1 2 3 4 5 6 7 8 9 42 1000 12345) ``` read it as pairs (i,map(m,i)), where m is the calculating function and i the different args writes ``` 1 1 2 2 3 3 4 3 5 5 6 5 7 10 8 8 9 8 42 272 1000 12831 12345 138481852236 ``` **Explanation** `n funtion\arg` applies function(function(function(...function(args))) n times (internally uses tal recursion), and returns the sequence of results. We calculate the 60 first items of fibonnaci series as `*+60(|+\)\1 0`. In that case the function is (|+): +\ applied over a sequence calculates partial sums (ex +\1 2 3 is 1 3 6), and | reverses seq. So each 'iteration' we calculate partial sums of the two previous fibonacci number and return the partial sums reversed. `60(|+\)\1 0` generates sequences 1 0, 1 1, 2 1, 3 2, 5 3, 8 5, 13 8, 21 13, ... `*+` applied over this result flip (traspose) it and takes the first. Result is sequence 1 1 2 3 5 8 13 21 34 55 .. `(cond)function\args` applies function(function(..function(args))) while cond true, and returns the sequence of partial results `function[arg]` applied over a function of more than one argument creates a projection (partial application) We can give name to the args, but the implicit names are x,y,z `{y-x x bin y}[*+60(|+\)\1 0]` declares a lambda with args x,y with partial projection (arg x is fibonacci series, calculates as \*+60(|+)\1 0). x represent fibonacci values, and y the number to process. Binary search (bin) is used to locate the index of the greater fibonacci number <=y (`x bin y`), and substract the corresponding value of x. To calculate product from partial resuls we reverse them and calculate difference of each pair (`-':|`), drop the first (`1_` because is 0) and multiply over (`*/`). If we are interested in accumulated sum the code is the same, but with `+/` instead of `*/`. We can also use any other diadic operator instead of + or \* **About execution efficiency** I know that in this contest efficiency is not an issue. But in this problem we can range from lineal cost to exponential cost, so i'm curious about it. I developed a second version (length 48 Bytes excluding comment) and repeated test cases battery 1000 times on both versions. ``` f:*+60(|+\)\1 0;m:{*/1_-':|(0<){x-f f bin x}\x} /new version ``` execution time is: original version 0'212 seg, new version 0'037 seg Original version calculates fibbonaci serie once per function application; new version calculates fibonacci just one. In both cases calculation of fibonacci series uses tail recursion
3,757,321
I am trying to use R to estimate a multinomial logit model with a manual specification. I have found a few packages that allow you to estimate MNL models [here](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/VGAM/html/multinomial.html) or [here](http://cran.r-project.org/web/packages/mlogit/index.html). I've found some other writings on "rolling" your own MLE function [here](http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html). However, from my digging around - all of these functions and packages rely on the internal `optim` function. In my benchmark tests, `optim` is the bottleneck. Using a simulated dataset with ~16000 observations and 7 parameters, R takes around 90 seconds on my machine. The equivalent model in [Biogeme](http://transp-or.epfl.ch/page63023.html) takes ~10 seconds. A colleague who writes his own code in [Ox](http://www.doornik.com/) reports around 4 seconds for this same model. Does anyone have experience with writing their own MLE function or can point me in the direction of something that is optimized beyond the default `optim` function (no pun intended)? If anyone wants the R code to recreate the model, let me know - I'll glady provide it. I haven't provided it since it isn't directly relevant to the problem of optimizing the `optim` function and to preserve space... *EDIT: Thanks to everyone for your thoughts. Based on a myriad of comments below, we were able to get R in the same ballpark as Biogeme for more complicated models, and R was actually faster for several smaller / simpler models that we ran. I think the long term solution to this problem is going to involve writing a separate maximization function that relies on a fortran or C library, but am certainly open to other approaches.*
2010/09/21
[ "https://Stackoverflow.com/questions/3757321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415635/" ]
Tried with the nlm() function already? Don't know if it's much faster, but it does improve speed. Also check the options. optim uses a slow algorithm as the default. You can gain a > 5-fold speedup by using the Quasi-Newton algorithm (method="BFGS") instead of the default. If you're not concerned too much about the last digits, you can also set the tolerance levels higher of nlm() to gain extra speed. ``` f <- function(x) sum((x-1:length(x))^2) a <- 1:5 system.time(replicate(500, optim(a,f) )) user system elapsed 0.78 0.00 0.79 system.time(replicate(500, optim(a,f,method="BFGS") )) user system elapsed 0.11 0.00 0.11 system.time(replicate(500, nlm(f,a) )) user system elapsed 0.10 0.00 0.09 system.time(replicate(500, nlm(f,a,steptol=1e-4,gradtol=1e-4) )) user system elapsed 0.03 0.00 0.03 ```
Did you consider the material on the [CRAN Task View for Optimization](http://cran.r-project.org/web/views/Optimization.html) ?
3,757,321
I am trying to use R to estimate a multinomial logit model with a manual specification. I have found a few packages that allow you to estimate MNL models [here](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/VGAM/html/multinomial.html) or [here](http://cran.r-project.org/web/packages/mlogit/index.html). I've found some other writings on "rolling" your own MLE function [here](http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html). However, from my digging around - all of these functions and packages rely on the internal `optim` function. In my benchmark tests, `optim` is the bottleneck. Using a simulated dataset with ~16000 observations and 7 parameters, R takes around 90 seconds on my machine. The equivalent model in [Biogeme](http://transp-or.epfl.ch/page63023.html) takes ~10 seconds. A colleague who writes his own code in [Ox](http://www.doornik.com/) reports around 4 seconds for this same model. Does anyone have experience with writing their own MLE function or can point me in the direction of something that is optimized beyond the default `optim` function (no pun intended)? If anyone wants the R code to recreate the model, let me know - I'll glady provide it. I haven't provided it since it isn't directly relevant to the problem of optimizing the `optim` function and to preserve space... *EDIT: Thanks to everyone for your thoughts. Based on a myriad of comments below, we were able to get R in the same ballpark as Biogeme for more complicated models, and R was actually faster for several smaller / simpler models that we ran. I think the long term solution to this problem is going to involve writing a separate maximization function that relies on a fortran or C library, but am certainly open to other approaches.*
2010/09/21
[ "https://Stackoverflow.com/questions/3757321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415635/" ]
Tried with the nlm() function already? Don't know if it's much faster, but it does improve speed. Also check the options. optim uses a slow algorithm as the default. You can gain a > 5-fold speedup by using the Quasi-Newton algorithm (method="BFGS") instead of the default. If you're not concerned too much about the last digits, you can also set the tolerance levels higher of nlm() to gain extra speed. ``` f <- function(x) sum((x-1:length(x))^2) a <- 1:5 system.time(replicate(500, optim(a,f) )) user system elapsed 0.78 0.00 0.79 system.time(replicate(500, optim(a,f,method="BFGS") )) user system elapsed 0.11 0.00 0.11 system.time(replicate(500, nlm(f,a) )) user system elapsed 0.10 0.00 0.09 system.time(replicate(500, nlm(f,a,steptol=1e-4,gradtol=1e-4) )) user system elapsed 0.03 0.00 0.03 ```
FWIW, I've done this in C-ish, using OPTIF9. You'd be hard-pressed to go faster than that. There are plenty of ways for something to go slower, such as by running an interpreter like R. Added: From the comments, it's clear that OPTIF9 is used as the optimizing engine. That means that most likely the bulk of the time is spent in evaluating the objective function in R. While it is possible that C functions are being used underneath for some of the operations, there still is interpreter overhead. There is a quick way to determine which lines of code and function calls in R are responsible for most of the time, and that is to pause it with the Escape key and examine the stack. If a statement costs X% of time, it is on the stack X% of the time. You may find that there are operations that are not going to C and should be. Any speedup factor you get this way will be preserved when you find a way to parallelize the R execution.
3,757,321
I am trying to use R to estimate a multinomial logit model with a manual specification. I have found a few packages that allow you to estimate MNL models [here](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/VGAM/html/multinomial.html) or [here](http://cran.r-project.org/web/packages/mlogit/index.html). I've found some other writings on "rolling" your own MLE function [here](http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html). However, from my digging around - all of these functions and packages rely on the internal `optim` function. In my benchmark tests, `optim` is the bottleneck. Using a simulated dataset with ~16000 observations and 7 parameters, R takes around 90 seconds on my machine. The equivalent model in [Biogeme](http://transp-or.epfl.ch/page63023.html) takes ~10 seconds. A colleague who writes his own code in [Ox](http://www.doornik.com/) reports around 4 seconds for this same model. Does anyone have experience with writing their own MLE function or can point me in the direction of something that is optimized beyond the default `optim` function (no pun intended)? If anyone wants the R code to recreate the model, let me know - I'll glady provide it. I haven't provided it since it isn't directly relevant to the problem of optimizing the `optim` function and to preserve space... *EDIT: Thanks to everyone for your thoughts. Based on a myriad of comments below, we were able to get R in the same ballpark as Biogeme for more complicated models, and R was actually faster for several smaller / simpler models that we ran. I think the long term solution to this problem is going to involve writing a separate maximization function that relies on a fortran or C library, but am certainly open to other approaches.*
2010/09/21
[ "https://Stackoverflow.com/questions/3757321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415635/" ]
Tried with the nlm() function already? Don't know if it's much faster, but it does improve speed. Also check the options. optim uses a slow algorithm as the default. You can gain a > 5-fold speedup by using the Quasi-Newton algorithm (method="BFGS") instead of the default. If you're not concerned too much about the last digits, you can also set the tolerance levels higher of nlm() to gain extra speed. ``` f <- function(x) sum((x-1:length(x))^2) a <- 1:5 system.time(replicate(500, optim(a,f) )) user system elapsed 0.78 0.00 0.79 system.time(replicate(500, optim(a,f,method="BFGS") )) user system elapsed 0.11 0.00 0.11 system.time(replicate(500, nlm(f,a) )) user system elapsed 0.10 0.00 0.09 system.time(replicate(500, nlm(f,a,steptol=1e-4,gradtol=1e-4) )) user system elapsed 0.03 0.00 0.03 ```
I am the author of the R package **optimParallel**, which could be helpful in your case. The package provides parallel versions of the gradient-based optimization methods of `optim()`. The main function of the package is `optimParallel()`, which has the same usage and output as `optim()`. Using `optimParallel()` can significantly reduce optimization times as illustrated in the following figure (`p` is the number of paramters). [![enter image description here](https://i.stack.imgur.com/PiEZM.png)](https://i.stack.imgur.com/PiEZM.png) See <https://cran.r-project.org/package=optimParallel> and <http://arxiv.org/abs/1804.11058> for more information.
3,757,321
I am trying to use R to estimate a multinomial logit model with a manual specification. I have found a few packages that allow you to estimate MNL models [here](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/VGAM/html/multinomial.html) or [here](http://cran.r-project.org/web/packages/mlogit/index.html). I've found some other writings on "rolling" your own MLE function [here](http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html). However, from my digging around - all of these functions and packages rely on the internal `optim` function. In my benchmark tests, `optim` is the bottleneck. Using a simulated dataset with ~16000 observations and 7 parameters, R takes around 90 seconds on my machine. The equivalent model in [Biogeme](http://transp-or.epfl.ch/page63023.html) takes ~10 seconds. A colleague who writes his own code in [Ox](http://www.doornik.com/) reports around 4 seconds for this same model. Does anyone have experience with writing their own MLE function or can point me in the direction of something that is optimized beyond the default `optim` function (no pun intended)? If anyone wants the R code to recreate the model, let me know - I'll glady provide it. I haven't provided it since it isn't directly relevant to the problem of optimizing the `optim` function and to preserve space... *EDIT: Thanks to everyone for your thoughts. Based on a myriad of comments below, we were able to get R in the same ballpark as Biogeme for more complicated models, and R was actually faster for several smaller / simpler models that we ran. I think the long term solution to this problem is going to involve writing a separate maximization function that relies on a fortran or C library, but am certainly open to other approaches.*
2010/09/21
[ "https://Stackoverflow.com/questions/3757321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415635/" ]
Did you consider the material on the [CRAN Task View for Optimization](http://cran.r-project.org/web/views/Optimization.html) ?
FWIW, I've done this in C-ish, using OPTIF9. You'd be hard-pressed to go faster than that. There are plenty of ways for something to go slower, such as by running an interpreter like R. Added: From the comments, it's clear that OPTIF9 is used as the optimizing engine. That means that most likely the bulk of the time is spent in evaluating the objective function in R. While it is possible that C functions are being used underneath for some of the operations, there still is interpreter overhead. There is a quick way to determine which lines of code and function calls in R are responsible for most of the time, and that is to pause it with the Escape key and examine the stack. If a statement costs X% of time, it is on the stack X% of the time. You may find that there are operations that are not going to C and should be. Any speedup factor you get this way will be preserved when you find a way to parallelize the R execution.
3,757,321
I am trying to use R to estimate a multinomial logit model with a manual specification. I have found a few packages that allow you to estimate MNL models [here](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/VGAM/html/multinomial.html) or [here](http://cran.r-project.org/web/packages/mlogit/index.html). I've found some other writings on "rolling" your own MLE function [here](http://www.mayin.org/ajayshah/KB/R/documents/mle/mle.html). However, from my digging around - all of these functions and packages rely on the internal `optim` function. In my benchmark tests, `optim` is the bottleneck. Using a simulated dataset with ~16000 observations and 7 parameters, R takes around 90 seconds on my machine. The equivalent model in [Biogeme](http://transp-or.epfl.ch/page63023.html) takes ~10 seconds. A colleague who writes his own code in [Ox](http://www.doornik.com/) reports around 4 seconds for this same model. Does anyone have experience with writing their own MLE function or can point me in the direction of something that is optimized beyond the default `optim` function (no pun intended)? If anyone wants the R code to recreate the model, let me know - I'll glady provide it. I haven't provided it since it isn't directly relevant to the problem of optimizing the `optim` function and to preserve space... *EDIT: Thanks to everyone for your thoughts. Based on a myriad of comments below, we were able to get R in the same ballpark as Biogeme for more complicated models, and R was actually faster for several smaller / simpler models that we ran. I think the long term solution to this problem is going to involve writing a separate maximization function that relies on a fortran or C library, but am certainly open to other approaches.*
2010/09/21
[ "https://Stackoverflow.com/questions/3757321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415635/" ]
I am the author of the R package **optimParallel**, which could be helpful in your case. The package provides parallel versions of the gradient-based optimization methods of `optim()`. The main function of the package is `optimParallel()`, which has the same usage and output as `optim()`. Using `optimParallel()` can significantly reduce optimization times as illustrated in the following figure (`p` is the number of paramters). [![enter image description here](https://i.stack.imgur.com/PiEZM.png)](https://i.stack.imgur.com/PiEZM.png) See <https://cran.r-project.org/package=optimParallel> and <http://arxiv.org/abs/1804.11058> for more information.
FWIW, I've done this in C-ish, using OPTIF9. You'd be hard-pressed to go faster than that. There are plenty of ways for something to go slower, such as by running an interpreter like R. Added: From the comments, it's clear that OPTIF9 is used as the optimizing engine. That means that most likely the bulk of the time is spent in evaluating the objective function in R. While it is possible that C functions are being used underneath for some of the operations, there still is interpreter overhead. There is a quick way to determine which lines of code and function calls in R are responsible for most of the time, and that is to pause it with the Escape key and examine the stack. If a statement costs X% of time, it is on the stack X% of the time. You may find that there are operations that are not going to C and should be. Any speedup factor you get this way will be preserved when you find a way to parallelize the R execution.
54,006
Does Virgin Galatic go into space high enough to experience real weightlessness? A CNBC article states it's more microgravity centrifugal: > > The spacecraft essentially does a slow back flip at the edge of space, with passengers spending a few minutes floating in microgravity > > > *[How SpaceX, Virgin Galactic, Blue Origin and others compete in the growing space tourism market](https://www.cnbc.com/2020/09/26/space-tourism-how-spacex-virgin-galactic-blue-origin-axiom-compete.html)* (CNBC)
2021/07/06
[ "https://space.stackexchange.com/questions/54006", "https://space.stackexchange.com", "https://space.stackexchange.com/users/42278/" ]
Yes, for a few minutes. It is similar to what is done in a zero gravity airplane flight, but a longer period of time. Also, orbital weightlessness is basically the same thing, the spacecraft and you are falling at the same rate.
Virgin Galactic's flights are sub-orbital and pass below the [Kármán line](https://en.wikipedia.org/wiki/K%C3%A1rm%C3%A1n_line) (about 100 km up), so technically the passengers don't qualify as astronauts in space, but while they experience weightlessness, this is a consequence of the trajectory of their spacecraft rather than them being unaffected by Earths gravity. The force of gravity on the occupants of their craft is actually very similar to that acting on us on the surface, but the astronauts are in freefall along with the spacecraft - this is exactly the same as what happens to occupants of the aircraft that follow a freefall trajectory ([vomit comet](https://en.wikipedia.org/wiki/Reduced-gravity_aircraft)) who also experience what is referred to as weightlessness. There is little difference between these two situations, and that of someone in deep space (say on route to Mars). However, the article you read is correct and the effect is really an effective matching of the force of gravity with the force that is attempting to keep them travelling in a straight line (as per Newton's first law of motion). Gravity is what is preventing the occupants and spacecraft from following the straight line they would otherwise have. Theoretically you can experience the same effect travelling on a train at hypersonic speeds on the surface of Earth. If the train was able to travel fast enough you would experience the same thing on a train (even if it was at same altitude throughout). Actually, if it was possible for the train to travel fast enough you could even experience -1g and be sat on the roof of the train (the -1g would in reality be centripetal force being twice the force of gravity, but in the opposite direction, and producing an overall force of -1g). p.s. Updated answer after obtaining confirmation that they only reached 53 miles altitude. It would seem that the astronaut wings awarded to the passengers are more symbolic than official recognition of entering space (it would seem a different standard it being met here).
54,006
Does Virgin Galatic go into space high enough to experience real weightlessness? A CNBC article states it's more microgravity centrifugal: > > The spacecraft essentially does a slow back flip at the edge of space, with passengers spending a few minutes floating in microgravity > > > *[How SpaceX, Virgin Galactic, Blue Origin and others compete in the growing space tourism market](https://www.cnbc.com/2020/09/26/space-tourism-how-spacex-virgin-galactic-blue-origin-axiom-compete.html)* (CNBC)
2021/07/06
[ "https://space.stackexchange.com/questions/54006", "https://space.stackexchange.com", "https://space.stackexchange.com/users/42278/" ]
This is a point worth emphasizing: When you dive off a high dive, or go on a free fall ride at an amusement park, or fly on Virgin Galactic, you are experiencing weightlessness in exactly the same way as the astronauts on the ISS. At the height of the ISS, the earth's gravity is about [90% of what it is at sea level](https://en.wikipedia.org/wiki/International_Space_Station#:%7E:text=Gravity%20at%20the%20altitude%20of,an%20apparent%20state%20of%20weightlessness.). You could launch a rocket straight up and hover until your engines ran out, and be walking around in your spacecraft while the ISS whizzed by at 5 miles a second. The reason the astronauts float around in the ISS is that they, like the space station, are themselves in orbit. When you dive off a diving board, you are technically in orbit too, but it is a *very* skinny orbit that intersects the surface of the earth. So the answer to your question is yes, the weightlessness advertised by Virgin Galactic is real. But they may not want you to think about how you could get the same weightlessness more cheaply (but without the probably amazing view).
Virgin Galactic's flights are sub-orbital and pass below the [Kármán line](https://en.wikipedia.org/wiki/K%C3%A1rm%C3%A1n_line) (about 100 km up), so technically the passengers don't qualify as astronauts in space, but while they experience weightlessness, this is a consequence of the trajectory of their spacecraft rather than them being unaffected by Earths gravity. The force of gravity on the occupants of their craft is actually very similar to that acting on us on the surface, but the astronauts are in freefall along with the spacecraft - this is exactly the same as what happens to occupants of the aircraft that follow a freefall trajectory ([vomit comet](https://en.wikipedia.org/wiki/Reduced-gravity_aircraft)) who also experience what is referred to as weightlessness. There is little difference between these two situations, and that of someone in deep space (say on route to Mars). However, the article you read is correct and the effect is really an effective matching of the force of gravity with the force that is attempting to keep them travelling in a straight line (as per Newton's first law of motion). Gravity is what is preventing the occupants and spacecraft from following the straight line they would otherwise have. Theoretically you can experience the same effect travelling on a train at hypersonic speeds on the surface of Earth. If the train was able to travel fast enough you would experience the same thing on a train (even if it was at same altitude throughout). Actually, if it was possible for the train to travel fast enough you could even experience -1g and be sat on the roof of the train (the -1g would in reality be centripetal force being twice the force of gravity, but in the opposite direction, and producing an overall force of -1g). p.s. Updated answer after obtaining confirmation that they only reached 53 miles altitude. It would seem that the astronaut wings awarded to the passengers are more symbolic than official recognition of entering space (it would seem a different standard it being met here).
114,561
I'm following the freecodecamp solidity tutorial and unfortunately I get a mistake when I try to get the nonce meaning. I use web3.py and ganache as it's shown in the tutorial. Here's my code: ``` from solcx import compile_standard, install_solc import json from web3 import Web3 with open("./SimpleStorage.sol", "r") as file: simple_storage_file = file.read() install_solc("0.6.0") compiled_sol = compile_standard( { "language": "Solidity", "sources": {"SimpleStorage.sol": {"content": simple_storage_file}}, "settings": { "outputSelection": { "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]} } }, }, solc_version="0.6.0", ) with open("compiled_code.json", "w") as file: json.dump(compiled_sol, file) # get bytecode bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][ "bytecode" ]["object"] # get abi abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"] # for connecting to ganache w3 = Web3(Web3.HTTPProvider("http://0.0.0.0:8545")) chain_id = 1337 my_address = "0xC674eC6962Ba5dEe7a1409187DE523663dbffB14" private_key = "0x0e6322ac24bdac2508bc4b888486e98dd4a090d954b47fcbc9c1efc06970953" # create the contract in python SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode) # get the latest transaction nonce = w3.eth.getTransactionCount(my_address) print(nonce) ``` It does create a contract at least when I print it gives me an answer. But when I try to create a nonce it gives the next mistake: ``` requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001B91C7468E0>: Failed to establish a new connection: [WinError 10049] ``` Does anyone know where the problem can be?
2021/11/29
[ "https://ethereum.stackexchange.com/questions/114561", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/86790/" ]
`http://0.0.0.0:8545` is not a valid Ethereum JSON-RPC node URL. PLease get a valid node. [Here are some examples](https://ethereumnodes.com/).
Please double check the address from RPC Server on Ganache
58,205,847
I'm trying to extract data between two quotes using the Google Sheets REGEXEXTRACT function. The regex works perfect: ``` (?<=actor_email":")(.*?)(?=") ``` Data in the cell is: ``` {"account_name":"Test","actor_email":"[email protected]","user_email":"[email protected]"} ``` However, placing it within the Google Sheet gives an error. Been trying a number of combinations with no luck. Tried using: `(?<=actor_email""":""")(.*?)(?=""")` The output should be: `[email protected]`
2019/10/02
[ "https://Stackoverflow.com/questions/58205847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193480/" ]
Restarting the "Azure Pipelines Agent (MyCompanyName.MyMachineName)" service on the build server solved this for me.
This is because you have committed your `bin` folder to source control. `bin` and `obj` folders should **never** be committed to source control. Remove it and ensure it is never re-added by making an appropriate `.tfignore` or `.gitignore` depending on whether you are using Git or TFVC for source control.
4,114,052
I need to 'scale' text to fill an antire HTML5 canvas. It appears that the `scale()` method does not affect text. I've seen approximation methods with iterative loops on the `measureText()` method but this doesn't get me exactly what I need. Ideally I'd like to fill both horizontally and vertically without conserving the aspect ratio. Would SVG possibly be able to help with this?
2010/11/06
[ "https://Stackoverflow.com/questions/4114052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/346490/" ]
My bad - Scale DOES apply to text. I've come up with a solution: ``` context.font = "20px 'Segoe UI'"; var metrics = context.measureText("Testing!"); var textWidth = metrics.width; var scalex = (canvas.width / textWidth); var scaley = (canvas.height / 23); var ypos = (canvas.height / (scaley * 1.25)); context.scale(scalex, scaley); context.fillText("Testing!", 0, ypos); ```
Scale does affect text. Try this: ``` var can = document.getElementById('test'); var ctx = can.getContext('2d'); ctx.fillText("test", 10, 10); // not scaled text ctx.scale(3,3); ctx.fillText("test", 10, 10); // scaled text ``` See it in action here: <http://jsfiddle.net/3zeBk/8/>
16,401,449
I am working on a project where I'm creating lots, (potentially x,000,000s) of images. When they are created, they are created on the fly and are blobs. e.g. ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAO... etc ``` Is it safe and efficient to save them as they are in MySQL or would you recommend saving them as actual images in a directory then storing just the path? And why? Completely new to me this so kind of a general question. I'm using PHP and MySQL db.
2013/05/06
[ "https://Stackoverflow.com/questions/16401449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/973552/" ]
Try this code -> ``` JSONObject dObject = output.getJSONObject("d") this.UserID = dObject.getInt("med_ID"); this.gebGUID = dObject.getString("geb_GUID"); // As your geb_GUID is String object ```
If you want to convert a json string into an object, you can use : ``` Type type = new TypeToken<HashMap<String, ArrayList<String>>>(){}.getType(); HashMap<String, ArrayList<String>> result = new Gson().fromJson(json, type); ``` You can change the type, in my case it was a `HashMap<String, ArrayList<String>>`.
177,098
<https://stackoverflow.com/a/16086837/438992> (10k+) The question is (redux) "Is there an advantage/difference" but it's a simple shortcut method, and the says so explicitly. Few of the other answers offer significantly more information, except for Stefan's. At least partially I suspect it's some intra-user hostility as I often need to correct the original commenter's answers, but I doubt that's all of it. So I want to know how it isn't an answer. (And, curiously, *after* the question was deleted, it got another downvote--AFAICT that means someone w/ an ability to undelete a question undeleted it, downvoted it, and re-deleted it?!)
2013/04/18
[ "https://meta.stackexchange.com/questions/177098", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/168933/" ]
It seems to me that your answer is too terse to qualify. 'The docs'? The docs of what? I know you mean jQuery, but to the google-landing reader, it's potentially opaque. A slightly more verbose formulation ("They do exactly the same thing, one is a notational shortcut for the other, see the jQuery doc") would pass in my book. Not that I'm one of the reviewers here.
Since it was my question, I would say that my only gripe with your answer was that I was interested in the theoretical, not the practical differences, and why people would have a preference. I stated in the question that I knew both methods worked, so while I didn't necessarily agree that yours wasn't a valid answer, it wasn't overly helpful in understanding the observed existence of a preference. And that was kind of the heart of the question, so telling me they both work, and overlooking the fact that the shortcut sets certain defaults and prevents using certain options, your answer missed the question. But I'm the newb, so I don't know if that's a fair criteria to say that it's *not* an answer.
177,098
<https://stackoverflow.com/a/16086837/438992> (10k+) The question is (redux) "Is there an advantage/difference" but it's a simple shortcut method, and the says so explicitly. Few of the other answers offer significantly more information, except for Stefan's. At least partially I suspect it's some intra-user hostility as I often need to correct the original commenter's answers, but I doubt that's all of it. So I want to know how it isn't an answer. (And, curiously, *after* the question was deleted, it got another downvote--AFAICT that means someone w/ an ability to undelete a question undeleted it, downvoted it, and re-deleted it?!)
2013/04/18
[ "https://meta.stackexchange.com/questions/177098", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/168933/" ]
It seems to me that your answer is too terse to qualify. 'The docs'? The docs of what? I know you mean jQuery, but to the google-landing reader, it's potentially opaque. A slightly more verbose formulation ("They do exactly the same thing, one is a notational shortcut for the other, see the jQuery doc") would pass in my book. Not that I'm one of the reviewers here.
I was going to answer "Too terse", but that was too terse.
62,055,789
In my React Native App, i have a simple FlatList. Flatlist's render item is a component "SearchItem.js" I need to re-initialize a state inside this component each time my component is called. Flatlist ``` <FlatList ListFooterComponent={<View style={{ paddingBottom: 30 }}></View>} data={temp} keyExtractor={(item) => item.id} renderItem={this.renderItem.bind(this)} //SearchItem component /> ``` render item: ``` renderItem({item}) { return <SearchItem item={item} onPress={() => {this.goToDetails(item)} ] /> ; } ``` Click the down arrow icon and message expands. click "^" and it collapses. SearchItem component below. Here state "arrowClicked" needs to be false every time the component is called. If we click the arrow icon and expand the message the state becomes "true". How do I re-initialise my state to "false" every time the component is called. Currently if a message is expanded it stays expanded. It should automatically collapse when the component is called again. ``` export default class SearchItem extends Component { constructor(props) { super(props) this.state = { arrowClicked: false } } setFullLength(bool){ this.setState({ arrowClicked: bool }) } . . render(){ return ( { arrowClicked === true ? <Icon type='materialicons' name='keyboard-arrow-up' onPress={()=>{this.setFullLength(false)}} /> : <Icon type='materialicons' name='keyboard-arrow-down' onPress={()=>{this.setFullLength(true)}} /> } ) } ``` How do I re-initialise my state arrowClicked = "false" ???? Please help!!! Update: Actually it's strange!! Example: imagine i search "hello" and 2 items in my flatlist render. I click the arrow icon on one of my message and the message expands. Now I clear "hello" text in my SearchBar. Flatlist renders again and all items are displayed. My message is still expanded (state: true). Now I search another text "hi" and 2 very different items in my flatlist render. I clear search text "hi". Flatlist renders again. Now my previously expanded message is collapsed (state is back to false). How??????? Focus issue??????
2020/05/28
[ "https://Stackoverflow.com/questions/62055789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13246365/" ]
Your last layer `model.add(layers.Dense(7))` is using linear activation function. To get probability of 7 classes, you should use `softmax` activation. Change your last layer to ``` model.add(layers.Dense(7 , activation='softmax')) ```
add an Activation Layer to convert your output value into value of [0,1]