qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | In MVC there are no longer Code-Behind classes. What you want is a Partial.
You'd use it like so:
```
<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %>
```
If this Menu is going to be in all of your pages you can make your controllers subclass a custom controller class that always fills the Menu data first.
If messing with the MVC inheritance hierarchy is overkill you can also make a MenuController class and use the RenderAction in your view/master:
```
<% Html.RenderAction<MenuController>(x => x.MainMenu()); %>
``` | Your master page is now a View, and Views should be passive. In other words, they shouldn't go look up things themselves.
It would be a much more correct approach (within the context of ASP.NET MVC) to pull the required data from the Model.
Take a look at [this SO question](https://stackoverflow.com/questions/1320516/asp-net-mvc-view-with-masterpage-binding-with-different-models/1320656#1320656) for a related discussion. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | You can still have code behind if you want. In your .master file put:
```
<%@ Master Language="C#" AutoEventWireup="true"
Inherits="Site_Master" CodeFile="Site.Master.cs" %>
```
Then in your .master.cs:
```
public partial class Site_Master : ViewMasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
``` | Your master page is now a View, and Views should be passive. In other words, they shouldn't go look up things themselves.
It would be a much more correct approach (within the context of ASP.NET MVC) to pull the required data from the Model.
Take a look at [this SO question](https://stackoverflow.com/questions/1320516/asp-net-mvc-view-with-masterpage-binding-with-different-models/1320656#1320656) for a related discussion. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | Your master page is now a View, and Views should be passive. In other words, they shouldn't go look up things themselves.
It would be a much more correct approach (within the context of ASP.NET MVC) to pull the required data from the Model.
Take a look at [this SO question](https://stackoverflow.com/questions/1320516/asp-net-mvc-view-with-masterpage-binding-with-different-models/1320656#1320656) for a related discussion. | Personally, I prefer using strongly typed views and ViewModels. If your master page requires data, then create a ViewModel for it. Ensure that every page's ViewModel inherits from this base ViewModel. Similarly, create a base controller that every other controller inherits from. Using Action Filters will allow you to ensure that the master ViewModel is populated implicitly. See [this](https://stackoverflow.com/questions/768236/how-to-create-a-strongly-typed-master-page-using-a-base-controller-in-asp-net-mvc) for an example. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | In MVC there are no longer Code-Behind classes. What you want is a Partial.
You'd use it like so:
```
<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %>
```
If this Menu is going to be in all of your pages you can make your controllers subclass a custom controller class that always fills the Menu data first.
If messing with the MVC inheritance hierarchy is overkill you can also make a MenuController class and use the RenderAction in your view/master:
```
<% Html.RenderAction<MenuController>(x => x.MainMenu()); %>
``` | There is a great tutorial on the [ASP.NET site](http://www.asp.net/learn/mvc/tutorial-13-cs.aspx) that shows how to do exactly this.
Briefly, you pass the data to the master page through the ViewData collection. To get the data into ViewData, create an application level controller. Have the page controllers inherit from the application controller instead of the base MVC controller.
Also, if you need to do things on your master page in reaction to the page being displayed, through this application controller you can tie into the ActionExecuting event. That will provide you information about the context of the page request currently being process. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | In MVC there are no longer Code-Behind classes. What you want is a Partial.
You'd use it like so:
```
<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %>
```
If this Menu is going to be in all of your pages you can make your controllers subclass a custom controller class that always fills the Menu data first.
If messing with the MVC inheritance hierarchy is overkill you can also make a MenuController class and use the RenderAction in your view/master:
```
<% Html.RenderAction<MenuController>(x => x.MainMenu()); %>
``` | Personally, I prefer using strongly typed views and ViewModels. If your master page requires data, then create a ViewModel for it. Ensure that every page's ViewModel inherits from this base ViewModel. Similarly, create a base controller that every other controller inherits from. Using Action Filters will allow you to ensure that the master ViewModel is populated implicitly. See [this](https://stackoverflow.com/questions/768236/how-to-create-a-strongly-typed-master-page-using-a-base-controller-in-asp-net-mvc) for an example. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | You can still have code behind if you want. In your .master file put:
```
<%@ Master Language="C#" AutoEventWireup="true"
Inherits="Site_Master" CodeFile="Site.Master.cs" %>
```
Then in your .master.cs:
```
public partial class Site_Master : ViewMasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
``` | There is a great tutorial on the [ASP.NET site](http://www.asp.net/learn/mvc/tutorial-13-cs.aspx) that shows how to do exactly this.
Briefly, you pass the data to the master page through the ViewData collection. To get the data into ViewData, create an application level controller. Have the page controllers inherit from the application controller instead of the base MVC controller.
Also, if you need to do things on your master page in reaction to the page being displayed, through this application controller you can tie into the ActionExecuting event. That will provide you information about the context of the page request currently being process. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | There is a great tutorial on the [ASP.NET site](http://www.asp.net/learn/mvc/tutorial-13-cs.aspx) that shows how to do exactly this.
Briefly, you pass the data to the master page through the ViewData collection. To get the data into ViewData, create an application level controller. Have the page controllers inherit from the application controller instead of the base MVC controller.
Also, if you need to do things on your master page in reaction to the page being displayed, through this application controller you can tie into the ActionExecuting event. That will provide you information about the context of the page request currently being process. | Personally, I prefer using strongly typed views and ViewModels. If your master page requires data, then create a ViewModel for it. Ensure that every page's ViewModel inherits from this base ViewModel. Similarly, create a base controller that every other controller inherits from. Using Action Filters will allow you to ensure that the master ViewModel is populated implicitly. See [this](https://stackoverflow.com/questions/768236/how-to-create-a-strongly-typed-master-page-using-a-base-controller-in-asp-net-mvc) for an example. |
1,699,836 | I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks | 2009/11/09 | [
"https://Stackoverflow.com/questions/1699836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] | You can still have code behind if you want. In your .master file put:
```
<%@ Master Language="C#" AutoEventWireup="true"
Inherits="Site_Master" CodeFile="Site.Master.cs" %>
```
Then in your .master.cs:
```
public partial class Site_Master : ViewMasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
``` | Personally, I prefer using strongly typed views and ViewModels. If your master page requires data, then create a ViewModel for it. Ensure that every page's ViewModel inherits from this base ViewModel. Similarly, create a base controller that every other controller inherits from. Using Action Filters will allow you to ensure that the master ViewModel is populated implicitly. See [this](https://stackoverflow.com/questions/768236/how-to-create-a-strongly-typed-master-page-using-a-base-controller-in-asp-net-mvc) for an example. |
277,955 | I have 10 servers running on Ubuntu 14.04 x64. Each server has a few Nvidia GPUs. I am looking for a monitoring program that would allow me to view the GPU usage on all servers at a glance. | 2016/04/20 | [
"https://unix.stackexchange.com/questions/277955",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16704/"
] | [munin](http://munin-monitoring.org/) has at least one [plugin](http://munin-monitoring.org/browser/munin-contrib/plugins/gpu/nvidia_gpu_) for monitoring nvidia GPUs (which uses the `nvidia-smi` utility to gather its data).
You could setup a `munin` server (perhaps on one of the GPU servers, or on the head node of your cluster), and then install the `munin-node` client and the nvidia plugin (plus whatever other plugins you might be interested in) on each of your GPU servers.
That would allow you to look in detail at the munin data for each server, or see an overview of the nvidia data for all servers. This would include graphs charting changes in, e.g., GPU temperature over time
Otherwise you could write a script to use ssh (or [pdsh](https://computing.llnl.gov/linux/pdsh.html)) to run the `nvidia-smi` utility on each server, extract the data you want, and present it in whatever format you want. | As cas [said](https://unix.stackexchange.com/a/278078/16704), I could write my own tool, so here it is (not polished at all, but it works.):
Client side (i.e., the GPU node)
--------------------------------
`gpu_monitoring.sh` (assumes that the IP of the server that serves the monitoring webpage is `128.52.200.39`)
```
while true;
do
nvidia-smi --query-gpu=utilization.gpu,utilization.memory,memory.total,memory.free,memory.used --format=csv >> gpu_utilization.log;
python gpu_monitoring.py
sshpass -p 'my_password' scp -o StrictHostKeyChecking=no ./gpu_utilization_100.png [email protected]:/var/www/html/gpu_utilization_100_server1.png
sshpass -p 'my_password' scp -o StrictHostKeyChecking=no ./gpu_utilization_10000.png [email protected]:/var/www/html/gpu_utilization_10000_server1.png
sleep 10;
done
```
`gpu_monitoring.py`:
```
'''
Monitor GPU use
'''
from __future__ import print_function
from __future__ import division
import numpy as np
import matplotlib
import os
matplotlib.use('Agg') # http://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined
import matplotlib.pyplot as plt
import time
import datetime
def get_current_milliseconds():
'''
http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python
'''
return(int(round(time.time() * 1000)))
def get_current_time_in_seconds():
'''
http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python
'''
return(time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime()))
def get_current_time_in_miliseconds():
'''
http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python
'''
return(get_current_time_in_seconds() + '-' + str(datetime.datetime.now().microsecond))
def generate_plot(gpu_log_filepath, max_history_size, graph_filepath):
'''
'''
# Get data
history_size = 0
number_of_gpus = -1
gpu_utilization = []
gpu_utilization_one_timestep = []
for line_number, line in enumerate(reversed(open(gpu_log_filepath).readlines())): # http://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python
if history_size > max_history_size: break
line = line.split(',')
if line[0].startswith('util') or len(gpu_utilization_one_timestep) == number_of_gpus:
if number_of_gpus == -1 and len(gpu_utilization_one_timestep) > 0:
number_of_gpus = len(gpu_utilization_one_timestep)
if len(gpu_utilization_one_timestep) == number_of_gpus:
gpu_utilization.append(list(reversed(gpu_utilization_one_timestep))) # reversed because since we read the log file from button to up, GPU order is reversed.
#print('gpu_utilization_one_timestep: {0}'.format(gpu_utilization_one_timestep))
history_size += 1
else: #len(gpu_utilization_one_timestep) <> number_of_gpus:
pass
#print('gpu_utilization_one_timestep: {0}'.format(gpu_utilization_one_timestep))
gpu_utilization_one_timestep = []
if line[0].startswith('util'): continue
try:
current_gpu_utilization = int(line[0].strip().replace(' %', ''))
except:
print('line: {0}'.format(line))
print('line_number: {0}'.format(line_number))
1/0
gpu_utilization_one_timestep.append(current_gpu_utilization)
# Plot graph
#print('gpu_utilization: {0}'.format(gpu_utilization))
gpu_utilization = np.array(list(reversed(gpu_utilization))) # We read the log backward, i.e., ante-chronological. We reverse again to get the chronological order.
#print('gpu_utilization.shape: {0}'.format(gpu_utilization.shape))
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(range(gpu_utilization.shape[0]), gpu_utilization)
ax.set_title('GPU utilization over time ({0})'.format(get_current_time_in_miliseconds()))
ax.set_xlabel('Time')
ax.set_ylabel('GPU utilization (%)')
gpu_utilization_mean_per_gpu = np.mean(gpu_utilization, axis=0)
lgd = ax.legend( [ 'GPU {0} (avg {1})'.format(gpu_number, np.round(gpu_utilization_mean, 1)) for gpu_number, gpu_utilization_mean in zip(range(gpu_utilization.shape[1]), gpu_utilization_mean_per_gpu)]
, loc='center right', bbox_to_anchor=(1.45, 0.5))
plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')
plt.close()
def main():
'''
This is the main function
'''
# Parameters
gpu_log_filepath = 'gpu_utilization.log'
max_history_size = 100
max_history_sizes =[100, 10000]
for max_history_size in max_history_sizes:
graph_filepath = 'gpu_utillization_{0}.png'.format(max_history_size)
generate_plot(gpu_log_filepath, max_history_size, graph_filepath)
if __name__ == "__main__":
main()
#cProfile.run('main()') # if you want to do some profiling
```
Server-side (i.e., the Web server)
----------------------------------
`gpu.html`:
```
<!DOCTYPE html>
<html>
<body>
<h2>gpu_utilization_server1.png</h2>
<img src="gpu_utilization_100_server1.png" alt="Mountain View" style="height:508px;"><img src="gpu_utilization_10000_server1.png" alt="Mountain View" style="height:508px;">
</body>
</html>
``` |
277,955 | I have 10 servers running on Ubuntu 14.04 x64. Each server has a few Nvidia GPUs. I am looking for a monitoring program that would allow me to view the GPU usage on all servers at a glance. | 2016/04/20 | [
"https://unix.stackexchange.com/questions/277955",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16704/"
] | [munin](http://munin-monitoring.org/) has at least one [plugin](http://munin-monitoring.org/browser/munin-contrib/plugins/gpu/nvidia_gpu_) for monitoring nvidia GPUs (which uses the `nvidia-smi` utility to gather its data).
You could setup a `munin` server (perhaps on one of the GPU servers, or on the head node of your cluster), and then install the `munin-node` client and the nvidia plugin (plus whatever other plugins you might be interested in) on each of your GPU servers.
That would allow you to look in detail at the munin data for each server, or see an overview of the nvidia data for all servers. This would include graphs charting changes in, e.g., GPU temperature over time
Otherwise you could write a script to use ssh (or [pdsh](https://computing.llnl.gov/linux/pdsh.html)) to run the `nvidia-smi` utility on each server, extract the data you want, and present it in whatever format you want. | Or simply use
<https://github.com/PatWie/cluster-smi>
which acts exactly in the same way as `nvidia-smi` in the terminal but gathers all information of nodes across your cluster, which are running the `cluster-smi-node`. The output will be
```
+---------+------------------------+---------------------+----------+----------+
| Node | Gpu | Memory-Usage | Mem-Util | GPU-Util |
+---------+------------------------+---------------------+----------+----------+
| node-00 | 0: TITAN Xp | 3857MiB / 12189MiB | 31% | 0% |
| | 1: TITAN Xp | 11689MiB / 12189MiB | 95% | 0% |
| | 2: TITAN Xp | 10787MiB / 12189MiB | 88% | 0% |
| | 3: TITAN Xp | 10965MiB / 12189MiB | 89% | 100% |
+---------+------------------------+---------------------+----------+----------+
| node-01 | 0: TITAN Xp | 11667MiB / 12189MiB | 95% | 100% |
| | 1: TITAN Xp | 11667MiB / 12189MiB | 95% | 96% |
| | 2: TITAN Xp | 8497MiB / 12189MiB | 69% | 100% |
| | 3: TITAN Xp | 8499MiB / 12189MiB | 69% | 98% |
+---------+------------------------+---------------------+----------+----------+
| node-02 | 0: GeForce GTX 1080 Ti | 1447MiB / 11172MiB | 12% | 8% |
| | 1: GeForce GTX 1080 Ti | 1453MiB / 11172MiB | 13% | 99% |
| | 2: GeForce GTX 1080 Ti | 1673MiB / 11172MiB | 14% | 0% |
| | 3: GeForce GTX 1080 Ti | 6812MiB / 11172MiB | 60% | 36% |
+---------+------------------------+---------------------+----------+----------+
```
when using 3 nodes.
It uses NVML to read these values directly for efficiency. I suggest to **not** parse the output of `nvidia-smi` as proposed in the other answers.
Further, you can track these information from `cluster-smi` using Python+ZMQ. |
277,955 | I have 10 servers running on Ubuntu 14.04 x64. Each server has a few Nvidia GPUs. I am looking for a monitoring program that would allow me to view the GPU usage on all servers at a glance. | 2016/04/20 | [
"https://unix.stackexchange.com/questions/277955",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16704/"
] | You can use the [ganglia](https://en.wikipedia.org/wiki/Ganglia_(software)) monitoring software (free of charge, open source). It has number of [user-contributed Gmond Python DSO metric modules](https://github.com/ganglia/gmond_python_modules), including a GPU Nvidia module ([`/ganglia/gmond_python_modules/gpu/nvidia/`](https://github.com/ganglia/gmond_python_modules/tree/master/gpu/nvidia)).
Its architecture is typical for a cluster monitoring software:
[](https://i.stack.imgur.com/ixJoV.png)
([source of the image](https://www.digitalocean.com/community/tutorials/introduction-to-ganglia-on-ubuntu-14-04))
It's straightforward to install (~ 30 minutes without rushing), except for the GPU Nvidia module, which lacks clear documentation. (I am still [stuck](https://serverfault.com/q/771854/126950))
---
To install ganglia, you can do as follows. On the server:
```
sudo apt-get install -y ganglia-monitor rrdtool gmetad ganglia-webfrontend
```
Choose `Yes` each time you are asking a question about Apache
[](https://i.stack.imgur.com/lhmHG.png)
**First**, we configure the Ganglia server, i.e. `gmetad`:
```
sudo cp /etc/ganglia-webfrontend/apache.conf /etc/apache2/sites-enabled/ganglia.conf
sudo nano /etc/ganglia/gmetad.conf
```
In `gmetad.conf`, make the following changes:
Replace:
```
data_source "my cluster" localhost
```
by (assuming that `192.168.10.22` is the IP of the server)
```
data_source "my cluster" 50 192.168.10.22:8649
```
It means that the Ganglia should listen on the 8649 port (which is the default port for Ganglia). You should make sure that the IP and the port is accessible to the Ganglia clients that will run on the machines you plan to monitor.
You can now launch the Ganglia server:
```
sudo /etc/init.d/gmetad restart
sudo /etc/init.d/apache2 restart
```
You can access the web interface on <http://192.168.10.22/ganglia/> (where `192.168.10.22` is the IP of the server)
**Second**, we configure the Ganglia client (i.e. `gmond`), either on the same machine or another machine.
```
sudo apt-get install -y ganglia-monitor
sudo nano /etc/ganglia/gmond.conf
```
In `gmond.conf` , make the following changes so that the Ganglia client, i.e. `gmond`, points to the server:
Replace:
```
cluster {
name = "unspecified"
owner = "unspecified"
latlong = "unspecified"
url = "unspecified"
}
```
to
```
cluster {
name = "my cluster"
owner = "unspecified"
latlong = "unspecified"
url = "unspecified"
}
```
Replace
```
udp_send_channel {
mcast_join = 239.2.11.71
port = 8649
ttl = 1
}
```
by
```
udp_send_channel {
# mcast_join = 239.2.11.71
host = 192.168.10.22
port = 8649
ttl = 1
}
```
Replace:
```
udp_recv_channel {
mcast_join = 239.2.11.71
port = 8649
bind = 239.2.11.71
}
```
to
```
udp_recv_channel {
# mcast_join = 239.2.11.71
port = 8649
# bind = 239.2.11.71
}
```
You can now start the Ganglia client:
```
sudo /etc/init.d/ganglia-monitor restart
```
It should appear within 30 seconds in the Ganglia web interface on the server (i.e., <http://192.168.10.22/ganglia/>).
Since the `gmond.conf` file is the same for all clients, you can add the ganglia monitoring on a new machine in a few seconds:
```
sudo apt-get install -y ganglia-monitor
wget http://somewebsite/gmond.conf # this gmond.conf is configured so that it points to the right ganglia server, as described above
sudo cp -f gmond.conf /etc/ganglia/gmond.conf
sudo /etc/init.d/ganglia-monitor restart
```
I used the following guides:
* <http://www.ubuntugeek.com/install-ganglia-on-ubuntu-14-04-server-trusty-tahr.html>
* <https://www.digitalocean.com/community/tutorials/introduction-to-ganglia-on-ubuntu-14-04>
---
A bash script to start or restart `gmond` on all the servers you want to monitor:
`deploy.sh`:
```
#!/usr/bin/env bash
# Some useful resources:
# while read ip user pass; do : http://unix.stackexchange.com/questions/92664/how-to-deploy-programs-on-multiple-machines
# -o StrictHostKeyChecking=no: http://askubuntu.com/questions/180860/regarding-host-key-verification-failed
# -T: http://stackoverflow.com/questions/21659637/how-to-fix-sudo-no-tty-present-and-no-askpass-program-specified-error
# echo $pass |: http://stackoverflow.com/questions/11955298/use-sudo-with-password-as-parameter
# http://stackoverflow.com/questions/36805184/why-is-this-while-loop-not-looping
while read ip user pass <&3; do
echo $ip
sshpass -p "$pass" ssh $user@$ip -o StrictHostKeyChecking=no -T "
echo $pass | sudo -S sudo /etc/init.d/ganglia-monitor restart
"
echo 'done'
done 3<servers.txt
```
`servers.txt`:
```
53.12.45.74 my_username my_password
54.12.45.74 my_username my_password
57.12.45.74 my_username my_password
```
---
Screenshots of the main page in the web interface:
[](https://i.stack.imgur.com/ERMzj.png)
[](https://i.stack.imgur.com/LYwsg.png)
<https://www.safaribooksonline.com/library/view/monitoring-with-ganglia/9781449330637/ch04.html> gives a nice overview of the Ganglia Web Interface:
[](https://i.stack.imgur.com/VjfOf.png) | As cas [said](https://unix.stackexchange.com/a/278078/16704), I could write my own tool, so here it is (not polished at all, but it works.):
Client side (i.e., the GPU node)
--------------------------------
`gpu_monitoring.sh` (assumes that the IP of the server that serves the monitoring webpage is `128.52.200.39`)
```
while true;
do
nvidia-smi --query-gpu=utilization.gpu,utilization.memory,memory.total,memory.free,memory.used --format=csv >> gpu_utilization.log;
python gpu_monitoring.py
sshpass -p 'my_password' scp -o StrictHostKeyChecking=no ./gpu_utilization_100.png [email protected]:/var/www/html/gpu_utilization_100_server1.png
sshpass -p 'my_password' scp -o StrictHostKeyChecking=no ./gpu_utilization_10000.png [email protected]:/var/www/html/gpu_utilization_10000_server1.png
sleep 10;
done
```
`gpu_monitoring.py`:
```
'''
Monitor GPU use
'''
from __future__ import print_function
from __future__ import division
import numpy as np
import matplotlib
import os
matplotlib.use('Agg') # http://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined
import matplotlib.pyplot as plt
import time
import datetime
def get_current_milliseconds():
'''
http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python
'''
return(int(round(time.time() * 1000)))
def get_current_time_in_seconds():
'''
http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python
'''
return(time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime()))
def get_current_time_in_miliseconds():
'''
http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python
'''
return(get_current_time_in_seconds() + '-' + str(datetime.datetime.now().microsecond))
def generate_plot(gpu_log_filepath, max_history_size, graph_filepath):
'''
'''
# Get data
history_size = 0
number_of_gpus = -1
gpu_utilization = []
gpu_utilization_one_timestep = []
for line_number, line in enumerate(reversed(open(gpu_log_filepath).readlines())): # http://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python
if history_size > max_history_size: break
line = line.split(',')
if line[0].startswith('util') or len(gpu_utilization_one_timestep) == number_of_gpus:
if number_of_gpus == -1 and len(gpu_utilization_one_timestep) > 0:
number_of_gpus = len(gpu_utilization_one_timestep)
if len(gpu_utilization_one_timestep) == number_of_gpus:
gpu_utilization.append(list(reversed(gpu_utilization_one_timestep))) # reversed because since we read the log file from button to up, GPU order is reversed.
#print('gpu_utilization_one_timestep: {0}'.format(gpu_utilization_one_timestep))
history_size += 1
else: #len(gpu_utilization_one_timestep) <> number_of_gpus:
pass
#print('gpu_utilization_one_timestep: {0}'.format(gpu_utilization_one_timestep))
gpu_utilization_one_timestep = []
if line[0].startswith('util'): continue
try:
current_gpu_utilization = int(line[0].strip().replace(' %', ''))
except:
print('line: {0}'.format(line))
print('line_number: {0}'.format(line_number))
1/0
gpu_utilization_one_timestep.append(current_gpu_utilization)
# Plot graph
#print('gpu_utilization: {0}'.format(gpu_utilization))
gpu_utilization = np.array(list(reversed(gpu_utilization))) # We read the log backward, i.e., ante-chronological. We reverse again to get the chronological order.
#print('gpu_utilization.shape: {0}'.format(gpu_utilization.shape))
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(range(gpu_utilization.shape[0]), gpu_utilization)
ax.set_title('GPU utilization over time ({0})'.format(get_current_time_in_miliseconds()))
ax.set_xlabel('Time')
ax.set_ylabel('GPU utilization (%)')
gpu_utilization_mean_per_gpu = np.mean(gpu_utilization, axis=0)
lgd = ax.legend( [ 'GPU {0} (avg {1})'.format(gpu_number, np.round(gpu_utilization_mean, 1)) for gpu_number, gpu_utilization_mean in zip(range(gpu_utilization.shape[1]), gpu_utilization_mean_per_gpu)]
, loc='center right', bbox_to_anchor=(1.45, 0.5))
plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')
plt.close()
def main():
'''
This is the main function
'''
# Parameters
gpu_log_filepath = 'gpu_utilization.log'
max_history_size = 100
max_history_sizes =[100, 10000]
for max_history_size in max_history_sizes:
graph_filepath = 'gpu_utillization_{0}.png'.format(max_history_size)
generate_plot(gpu_log_filepath, max_history_size, graph_filepath)
if __name__ == "__main__":
main()
#cProfile.run('main()') # if you want to do some profiling
```
Server-side (i.e., the Web server)
----------------------------------
`gpu.html`:
```
<!DOCTYPE html>
<html>
<body>
<h2>gpu_utilization_server1.png</h2>
<img src="gpu_utilization_100_server1.png" alt="Mountain View" style="height:508px;"><img src="gpu_utilization_10000_server1.png" alt="Mountain View" style="height:508px;">
</body>
</html>
``` |
277,955 | I have 10 servers running on Ubuntu 14.04 x64. Each server has a few Nvidia GPUs. I am looking for a monitoring program that would allow me to view the GPU usage on all servers at a glance. | 2016/04/20 | [
"https://unix.stackexchange.com/questions/277955",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16704/"
] | You can use the [ganglia](https://en.wikipedia.org/wiki/Ganglia_(software)) monitoring software (free of charge, open source). It has number of [user-contributed Gmond Python DSO metric modules](https://github.com/ganglia/gmond_python_modules), including a GPU Nvidia module ([`/ganglia/gmond_python_modules/gpu/nvidia/`](https://github.com/ganglia/gmond_python_modules/tree/master/gpu/nvidia)).
Its architecture is typical for a cluster monitoring software:
[](https://i.stack.imgur.com/ixJoV.png)
([source of the image](https://www.digitalocean.com/community/tutorials/introduction-to-ganglia-on-ubuntu-14-04))
It's straightforward to install (~ 30 minutes without rushing), except for the GPU Nvidia module, which lacks clear documentation. (I am still [stuck](https://serverfault.com/q/771854/126950))
---
To install ganglia, you can do as follows. On the server:
```
sudo apt-get install -y ganglia-monitor rrdtool gmetad ganglia-webfrontend
```
Choose `Yes` each time you are asking a question about Apache
[](https://i.stack.imgur.com/lhmHG.png)
**First**, we configure the Ganglia server, i.e. `gmetad`:
```
sudo cp /etc/ganglia-webfrontend/apache.conf /etc/apache2/sites-enabled/ganglia.conf
sudo nano /etc/ganglia/gmetad.conf
```
In `gmetad.conf`, make the following changes:
Replace:
```
data_source "my cluster" localhost
```
by (assuming that `192.168.10.22` is the IP of the server)
```
data_source "my cluster" 50 192.168.10.22:8649
```
It means that the Ganglia should listen on the 8649 port (which is the default port for Ganglia). You should make sure that the IP and the port is accessible to the Ganglia clients that will run on the machines you plan to monitor.
You can now launch the Ganglia server:
```
sudo /etc/init.d/gmetad restart
sudo /etc/init.d/apache2 restart
```
You can access the web interface on <http://192.168.10.22/ganglia/> (where `192.168.10.22` is the IP of the server)
**Second**, we configure the Ganglia client (i.e. `gmond`), either on the same machine or another machine.
```
sudo apt-get install -y ganglia-monitor
sudo nano /etc/ganglia/gmond.conf
```
In `gmond.conf` , make the following changes so that the Ganglia client, i.e. `gmond`, points to the server:
Replace:
```
cluster {
name = "unspecified"
owner = "unspecified"
latlong = "unspecified"
url = "unspecified"
}
```
to
```
cluster {
name = "my cluster"
owner = "unspecified"
latlong = "unspecified"
url = "unspecified"
}
```
Replace
```
udp_send_channel {
mcast_join = 239.2.11.71
port = 8649
ttl = 1
}
```
by
```
udp_send_channel {
# mcast_join = 239.2.11.71
host = 192.168.10.22
port = 8649
ttl = 1
}
```
Replace:
```
udp_recv_channel {
mcast_join = 239.2.11.71
port = 8649
bind = 239.2.11.71
}
```
to
```
udp_recv_channel {
# mcast_join = 239.2.11.71
port = 8649
# bind = 239.2.11.71
}
```
You can now start the Ganglia client:
```
sudo /etc/init.d/ganglia-monitor restart
```
It should appear within 30 seconds in the Ganglia web interface on the server (i.e., <http://192.168.10.22/ganglia/>).
Since the `gmond.conf` file is the same for all clients, you can add the ganglia monitoring on a new machine in a few seconds:
```
sudo apt-get install -y ganglia-monitor
wget http://somewebsite/gmond.conf # this gmond.conf is configured so that it points to the right ganglia server, as described above
sudo cp -f gmond.conf /etc/ganglia/gmond.conf
sudo /etc/init.d/ganglia-monitor restart
```
I used the following guides:
* <http://www.ubuntugeek.com/install-ganglia-on-ubuntu-14-04-server-trusty-tahr.html>
* <https://www.digitalocean.com/community/tutorials/introduction-to-ganglia-on-ubuntu-14-04>
---
A bash script to start or restart `gmond` on all the servers you want to monitor:
`deploy.sh`:
```
#!/usr/bin/env bash
# Some useful resources:
# while read ip user pass; do : http://unix.stackexchange.com/questions/92664/how-to-deploy-programs-on-multiple-machines
# -o StrictHostKeyChecking=no: http://askubuntu.com/questions/180860/regarding-host-key-verification-failed
# -T: http://stackoverflow.com/questions/21659637/how-to-fix-sudo-no-tty-present-and-no-askpass-program-specified-error
# echo $pass |: http://stackoverflow.com/questions/11955298/use-sudo-with-password-as-parameter
# http://stackoverflow.com/questions/36805184/why-is-this-while-loop-not-looping
while read ip user pass <&3; do
echo $ip
sshpass -p "$pass" ssh $user@$ip -o StrictHostKeyChecking=no -T "
echo $pass | sudo -S sudo /etc/init.d/ganglia-monitor restart
"
echo 'done'
done 3<servers.txt
```
`servers.txt`:
```
53.12.45.74 my_username my_password
54.12.45.74 my_username my_password
57.12.45.74 my_username my_password
```
---
Screenshots of the main page in the web interface:
[](https://i.stack.imgur.com/ERMzj.png)
[](https://i.stack.imgur.com/LYwsg.png)
<https://www.safaribooksonline.com/library/view/monitoring-with-ganglia/9781449330637/ch04.html> gives a nice overview of the Ganglia Web Interface:
[](https://i.stack.imgur.com/VjfOf.png) | Or simply use
<https://github.com/PatWie/cluster-smi>
which acts exactly in the same way as `nvidia-smi` in the terminal but gathers all information of nodes across your cluster, which are running the `cluster-smi-node`. The output will be
```
+---------+------------------------+---------------------+----------+----------+
| Node | Gpu | Memory-Usage | Mem-Util | GPU-Util |
+---------+------------------------+---------------------+----------+----------+
| node-00 | 0: TITAN Xp | 3857MiB / 12189MiB | 31% | 0% |
| | 1: TITAN Xp | 11689MiB / 12189MiB | 95% | 0% |
| | 2: TITAN Xp | 10787MiB / 12189MiB | 88% | 0% |
| | 3: TITAN Xp | 10965MiB / 12189MiB | 89% | 100% |
+---------+------------------------+---------------------+----------+----------+
| node-01 | 0: TITAN Xp | 11667MiB / 12189MiB | 95% | 100% |
| | 1: TITAN Xp | 11667MiB / 12189MiB | 95% | 96% |
| | 2: TITAN Xp | 8497MiB / 12189MiB | 69% | 100% |
| | 3: TITAN Xp | 8499MiB / 12189MiB | 69% | 98% |
+---------+------------------------+---------------------+----------+----------+
| node-02 | 0: GeForce GTX 1080 Ti | 1447MiB / 11172MiB | 12% | 8% |
| | 1: GeForce GTX 1080 Ti | 1453MiB / 11172MiB | 13% | 99% |
| | 2: GeForce GTX 1080 Ti | 1673MiB / 11172MiB | 14% | 0% |
| | 3: GeForce GTX 1080 Ti | 6812MiB / 11172MiB | 60% | 36% |
+---------+------------------------+---------------------+----------+----------+
```
when using 3 nodes.
It uses NVML to read these values directly for efficiency. I suggest to **not** parse the output of `nvidia-smi` as proposed in the other answers.
Further, you can track these information from `cluster-smi` using Python+ZMQ. |
28,185,048 | I've read several guides on how to use GTK+ for a GUI in C programs and I came across [this tutorial](https://wiki.gnome.org/Projects/GTK+/OSX/Building) for getting GTK+ on my system. Here's everything I ran, line by line:
```
chmod +x gtk-osx-build-setup.sh
./gtk-osx-build-setup.sh
cd ~/.local/bin
./jhbuild build python
./jhbuild bootstrap
./jhbuild build meta-gtk-osx-bootstrap
./jhbuild build meta-gtk-osx-core
```
At this point, I had not discovered the `pkg-config` tick hack for compiling C programs with GTK headers, so when I ran `gcc main.c -o main` I simply got the error `main.c:1:10: fatal error: 'gtk/gtk.h' file not found`, but I had found [another tutorial](https://developer.gnome.org/jhbuild/stable/getting-started.html.en) (Command-F "jhbuild build gtk+") that suggested I do this, so I ran:
```
./jhbuild build gtk+
```
After that, I finally found other sources that suggested to run the following commands to check if my system could find the packages, so when I run `pkg-config gtk+-3.0 --cflags` I get:
```
-D_REENTRANT -I/opt/local/include/gtk-3.0 -I/opt/local/include/at-spi2-atk/2.0 -I/opt/local/include/at-spi-2.0 -I/opt/local/include/dbus-1.0 -I/opt/local/lib/dbus-1.0/include -I/opt/local/include/gtk-3.0 -I/opt/local/include/gio-unix-2.0/ -I/opt/local/include -I/opt/local/include/cairo -I/opt/local/include/pango-1.0 -I/opt/local/include/harfbuzz -I/opt/local/include/pango-1.0 -I/opt/local/include/atk-1.0 -I/opt/local/include/cairo -I/opt/local/include/pixman-1 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include/libpng16 -I/opt/local/include -I/opt/local/include/gdk-pixbuf-2.0 -I/opt/local/include/libpng16 -I/opt/local/include/glib-2.0 -I/opt/local/lib/glib-2.0/include -I/opt/local/include
```
And when I run `pkg-config gtk+-3.0 --libs` I get:
```
-L/opt/local/lib -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpangoft2-1.0 -lpango-1.0 -lm -lfontconfig -lfreetype -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lintl
```
My `main.c` contains the following code from [this tutorial](https://developer.gnome.org/gtk3/stable/gtk-getting-started.html#id-1.2.3.3):
```
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Window");
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
When I run `gcc -Wall -Wextra -Werror `pkg-config gtk+-3.0 --cflags` main.c -o main `pkg-config gtk+-3.0 --libs``, `main` is created with no warnings or anything, but when I run `./main` I get this warning, and the program ends instantly:
```
(main:93199): Gtk-WARNING **: cannot open display:
```
My computer is a Mid 2012 MacBook Pro running OS X 10.9.5 with a 2.9 GHz Intel Core i7 processor (I really have no idea how much of that information is necessary for this). I just want to resolve this warning so I can get a simple window to display without any problems.
**UPDATE:** I noticed that I installed gtk+ instead of gtk+-3.0, so I ran `~/.local/bin/jhbuild build gtk+-3.0` to install it. When I run `~/.local/bin/jhbuild info gtk+-3.0`, I get:
```
Name: gtk+-3.0
Module Set: gtk-osx
Type: autogen
Install version: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Install date: 2015-01-27 23:49:55
URL: http://ftp.gnome.org/pub/GNOME/sources/gtk+/3.14/gtk+-3.14.5.tar.xz
Version: 3.14.5
Tree-ID: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Sourcedir: ~/gtk/source/gtk+-3.14.5
Requires: glib, pango, atk, gdk-pixbuf, gobject-introspection
Required by: meta-gtk-osx-gtk3, goocanvas2, gtkmm3
After: meta-gtk-osx-bootstrap
Before: gtk-mac-integration
```
I still get the same error, however, even after re-compiling the C program. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28185048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541563/"
] | My recommendation is to extract the meaningful portions of each handler into methods that can be called independently and can have useful return values. This is particularly important for your second button's handler, since the handler for button1 also depends on it.
Upon extracting the code, you can transform the extracted method into a boolean function, and can depend upon the return value to continue your process.
```
private void button1_click(object sender, EventArgs e)
{
ThingToDoForButton1();
}
private void button2_click(object sender, EventArgs e)
{
ThingToDoForButton2();
}
private void ThingToDoForButton1()
{
// do something
if (ThingToDoForButton2())
{
// do something else
}
}
private bool ThingToDoForButton2()
{
//Do something
if(/* some condition */) return false;
//Do something else
return true;
}
```
Of course, it is up to you to provide meaningful names for your methods, once extracted, and to consider breaking down your code into additional smaller functions if the "do something" and "do something else" parts are not insignificant. | I think, you want something like this
```
private void button1_click(object sender, EventArgs e)
{
//Do first stuffs
button2_click(sender, e);
//Reading the tag value of sender object that is assigned in that case
if (!(bool)(sender as Button).Tag)
return;
//Do second stuffs
}
private void button2_click(object sender, EventArgs e)
{
//Do something
//Since sender object is button1 in the example
Button button = sender as Button;
button.Tag = true;
if (myCondition)
{
button.Tag = false;
return;
}//Also return in button1_click
//Do somthing else
}
``` |
28,185,048 | I've read several guides on how to use GTK+ for a GUI in C programs and I came across [this tutorial](https://wiki.gnome.org/Projects/GTK+/OSX/Building) for getting GTK+ on my system. Here's everything I ran, line by line:
```
chmod +x gtk-osx-build-setup.sh
./gtk-osx-build-setup.sh
cd ~/.local/bin
./jhbuild build python
./jhbuild bootstrap
./jhbuild build meta-gtk-osx-bootstrap
./jhbuild build meta-gtk-osx-core
```
At this point, I had not discovered the `pkg-config` tick hack for compiling C programs with GTK headers, so when I ran `gcc main.c -o main` I simply got the error `main.c:1:10: fatal error: 'gtk/gtk.h' file not found`, but I had found [another tutorial](https://developer.gnome.org/jhbuild/stable/getting-started.html.en) (Command-F "jhbuild build gtk+") that suggested I do this, so I ran:
```
./jhbuild build gtk+
```
After that, I finally found other sources that suggested to run the following commands to check if my system could find the packages, so when I run `pkg-config gtk+-3.0 --cflags` I get:
```
-D_REENTRANT -I/opt/local/include/gtk-3.0 -I/opt/local/include/at-spi2-atk/2.0 -I/opt/local/include/at-spi-2.0 -I/opt/local/include/dbus-1.0 -I/opt/local/lib/dbus-1.0/include -I/opt/local/include/gtk-3.0 -I/opt/local/include/gio-unix-2.0/ -I/opt/local/include -I/opt/local/include/cairo -I/opt/local/include/pango-1.0 -I/opt/local/include/harfbuzz -I/opt/local/include/pango-1.0 -I/opt/local/include/atk-1.0 -I/opt/local/include/cairo -I/opt/local/include/pixman-1 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include -I/opt/local/include/freetype2 -I/opt/local/include/libpng16 -I/opt/local/include -I/opt/local/include/gdk-pixbuf-2.0 -I/opt/local/include/libpng16 -I/opt/local/include/glib-2.0 -I/opt/local/lib/glib-2.0/include -I/opt/local/include
```
And when I run `pkg-config gtk+-3.0 --libs` I get:
```
-L/opt/local/lib -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpangoft2-1.0 -lpango-1.0 -lm -lfontconfig -lfreetype -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lintl
```
My `main.c` contains the following code from [this tutorial](https://developer.gnome.org/gtk3/stable/gtk-getting-started.html#id-1.2.3.3):
```
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Window");
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
When I run `gcc -Wall -Wextra -Werror `pkg-config gtk+-3.0 --cflags` main.c -o main `pkg-config gtk+-3.0 --libs``, `main` is created with no warnings or anything, but when I run `./main` I get this warning, and the program ends instantly:
```
(main:93199): Gtk-WARNING **: cannot open display:
```
My computer is a Mid 2012 MacBook Pro running OS X 10.9.5 with a 2.9 GHz Intel Core i7 processor (I really have no idea how much of that information is necessary for this). I just want to resolve this warning so I can get a simple window to display without any problems.
**UPDATE:** I noticed that I installed gtk+ instead of gtk+-3.0, so I ran `~/.local/bin/jhbuild build gtk+-3.0` to install it. When I run `~/.local/bin/jhbuild info gtk+-3.0`, I get:
```
Name: gtk+-3.0
Module Set: gtk-osx
Type: autogen
Install version: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Install date: 2015-01-27 23:49:55
URL: http://ftp.gnome.org/pub/GNOME/sources/gtk+/3.14/gtk+-3.14.5.tar.xz
Version: 3.14.5
Tree-ID: 3.14.5-b4ea7a7455981175cb26a7a1a49b765e
Sourcedir: ~/gtk/source/gtk+-3.14.5
Requires: glib, pango, atk, gdk-pixbuf, gobject-introspection
Required by: meta-gtk-osx-gtk3, goocanvas2, gtkmm3
After: meta-gtk-osx-bootstrap
Before: gtk-mac-integration
```
I still get the same error, however, even after re-compiling the C program. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28185048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541563/"
] | My recommendation is to extract the meaningful portions of each handler into methods that can be called independently and can have useful return values. This is particularly important for your second button's handler, since the handler for button1 also depends on it.
Upon extracting the code, you can transform the extracted method into a boolean function, and can depend upon the return value to continue your process.
```
private void button1_click(object sender, EventArgs e)
{
ThingToDoForButton1();
}
private void button2_click(object sender, EventArgs e)
{
ThingToDoForButton2();
}
private void ThingToDoForButton1()
{
// do something
if (ThingToDoForButton2())
{
// do something else
}
}
private bool ThingToDoForButton2()
{
//Do something
if(/* some condition */) return false;
//Do something else
return true;
}
```
Of course, it is up to you to provide meaningful names for your methods, once extracted, and to consider breaking down your code into additional smaller functions if the "do something" and "do something else" parts are not insignificant. | You can use [CancelEventArgs Class](https://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs%28v=vs.110%29.aspx) like this:
```
private void button1_click(object sender, EventArgs e)
{
//Do first stuffs
var e1 = new CancelEventArgs();
button2_click(sender, e1);
if(e1.Cancel)
{
return;
}
//Do second stuffs
}
private void button2_click(object sender, CancelEventArgs e)
{
//Do somthing
if(myCondition)
{
e.Cancel = true;
return;
}
//Do somthing else
}
``` |
33,818 | I recently bought a Sandisk Cruzer USB drive. Part of the drive (6.66 MB) is formatted with CDFS and shows as a CD drive.
Why do they do this ? Is it to protect the software on that part of the disk to trick the OS (Vista) into not overwriting or amending, because it thinks this is a read-only CD ?
Is the 6.66 MB significant. Apart from being associated with the Devil ?
How can I format a partition on a USB drive to be CDFS ?
Why would I want to do something like that myself on my other flash drives ?
I'm a programmer, so how can I leverage this new knowledge ? Any Ideas ? | 2009/09/01 | [
"https://superuser.com/questions/33818",
"https://superuser.com",
"https://superuser.com/users/7891/"
] | This is part of the U3 software that comes on it. It is garbage and I always remove it, the link for the removal tool is here:<http://u3.com/support/default.aspx#CQ3>
Keep in mind, this will format your drive. | Most likely the reason they did this was to prevent overwriting their software from the flash drive.
If desired, you should be able to change the partition scheme to fully utilize the drive. The easiest way to do this is to boot into [a Linux LiveCD](http://www.ubuntu.com/) and use [gParted](http://www.wikihow.com/Use-Gparted) to fix it. Offhand I can't remember any [free partition managers for windows](http://www.google.com/search?q=free+windows+partition+managers). |
33,818 | I recently bought a Sandisk Cruzer USB drive. Part of the drive (6.66 MB) is formatted with CDFS and shows as a CD drive.
Why do they do this ? Is it to protect the software on that part of the disk to trick the OS (Vista) into not overwriting or amending, because it thinks this is a read-only CD ?
Is the 6.66 MB significant. Apart from being associated with the Devil ?
How can I format a partition on a USB drive to be CDFS ?
Why would I want to do something like that myself on my other flash drives ?
I'm a programmer, so how can I leverage this new knowledge ? Any Ideas ? | 2009/09/01 | [
"https://superuser.com/questions/33818",
"https://superuser.com",
"https://superuser.com/users/7891/"
] | This is part of the U3 software that comes on it. It is garbage and I always remove it, the link for the removal tool is here:<http://u3.com/support/default.aspx#CQ3>
Keep in mind, this will format your drive. | Does the pseudo-CD have an autorun.inf file on it?
This is sometimes done to take advantage of the CD autorun feature. When one of these devices is plugged into a computer that has autorun enabled, a program on the drive will start automatically. This is typically a small pop-up menu that allows the user to run, install, or uninstall programs from the drive. |
59,994,928 | We are using the excellent Tabulator JS library. We poll our server at intervals to refresh the data in our table. We are trying to achieve the following behaviour when this happens.
1. Update the existing data in the table
2. Add any new rows that "Match" the current filters
3. Remove any rows that have changed and don't match the filters
4. Keep the existing scroll position
5. Keep any selected rows.
6. If the filters are removed show the latest data.
There are 3 methods to update Tabulator
<http://tabulator.info/docs/4.5/update>
1. SetData (we use this when we first fetch)
2. updateData
3. updateOrAddData (we use this on repeated fetches but row edits don't get filtered out)
4. replaceData
In the documents is mentions that 'replaceData' will update existing table data with out resetting the scroll position or selected rows, this does not seem to be the case. 'updateData' does update the data and leaves the scroll pos and selected rows as is, BUT it does not apply the filters, for example if a row is updated out of the scope of the current filter it still shows?
Our code right now:
```
if (replace) {
table.updateOrAddData(data); //replaceData
} else {
table.setData(data);
}
```
We need the table to update and meet our requirements in my above points 1-6. I would expect one of the methods listed (replace, update) would do this and in the docs it seems they should, but in our tests this fails. How can we achieve the desired results?
We are using version 4.5 downgraded from 4.4.
Edit:
So for example if we update the table with data and one of the rows in the table does not exist in the new data, that update does not persist. Unless we use setData which resets the scroll position, undoes all selected rows and so on. | 2020/01/30 | [
"https://Stackoverflow.com/questions/59994928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141347/"
] | The latest version of Tabulator, 4.9, adds a [refreshFilter](http://tabulator.info/docs/4.9/filter#manage) function. This should accomplish most of your request.
My own testing also show that the sorters are also refreshed by this function.
`table.refreshFilter();` | You can either call manually [Redraw](http://tabulator.info/docs/4.5/layout#redraw)
```
table.redraw(true); //trigger full rerender including all data and rows
```
or just use [reactive data](http://tabulator.info/docs/4.5/reactivity#reactive-data)
```
reactiveData:true, //enable reactive data
data:tableData, //assign data array
``` |
59,994,928 | We are using the excellent Tabulator JS library. We poll our server at intervals to refresh the data in our table. We are trying to achieve the following behaviour when this happens.
1. Update the existing data in the table
2. Add any new rows that "Match" the current filters
3. Remove any rows that have changed and don't match the filters
4. Keep the existing scroll position
5. Keep any selected rows.
6. If the filters are removed show the latest data.
There are 3 methods to update Tabulator
<http://tabulator.info/docs/4.5/update>
1. SetData (we use this when we first fetch)
2. updateData
3. updateOrAddData (we use this on repeated fetches but row edits don't get filtered out)
4. replaceData
In the documents is mentions that 'replaceData' will update existing table data with out resetting the scroll position or selected rows, this does not seem to be the case. 'updateData' does update the data and leaves the scroll pos and selected rows as is, BUT it does not apply the filters, for example if a row is updated out of the scope of the current filter it still shows?
Our code right now:
```
if (replace) {
table.updateOrAddData(data); //replaceData
} else {
table.setData(data);
}
```
We need the table to update and meet our requirements in my above points 1-6. I would expect one of the methods listed (replace, update) would do this and in the docs it seems they should, but in our tests this fails. How can we achieve the desired results?
We are using version 4.5 downgraded from 4.4.
Edit:
So for example if we update the table with data and one of the rows in the table does not exist in the new data, that update does not persist. Unless we use setData which resets the scroll position, undoes all selected rows and so on. | 2020/01/30 | [
"https://Stackoverflow.com/questions/59994928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141347/"
] | The latest version of Tabulator, 4.9, adds a [refreshFilter](http://tabulator.info/docs/4.9/filter#manage) function. This should accomplish most of your request.
My own testing also show that the sorters are also refreshed by this function.
`table.refreshFilter();` | After much searching and looking through Tabulator 4.5 docs it seems that the table can not update existing data, re-apply filters, remove dead rows (those not in the new data from the server) from one of the update, replace methods. From what I can understand this can be achieved by the code I have written below, which uses the updateOrAddData method, the setFilter method and my own async function to loop the table and remove dead rows.
```
// var data= new data from server - any array.
// get the existing filters, update the data or add any new rows.
var f = table.getFilters();
table.updateOrAddData(data); //replaceData with server copy
var keys = [],
r = table.getRows();
// make a list of all the keys in our server data, this will make it faster to remove dead rows.
data.forEach(function(item) { keys.push(item.id); });
// remove any dead rows in the data that do not belong start at row 0
removeDeadRows(0, function() {
table.setFilter(f); //re-apply filters when finished.
});
// iterate the table test if each row is in our key list, if not remove it.
function removeDeadRows(pos, cb) {
if (!r[pos]) return cb();
var c = pos + 1;
try {
if (keys.indexOf(r[pos].getData().id) > 0) return removeDeadRows(c, cb);
r[pos].delete();
removeDeadRows(c, cb);
} catch (e) {
console.log(e);
cb();
}
}
``` |
59,994,928 | We are using the excellent Tabulator JS library. We poll our server at intervals to refresh the data in our table. We are trying to achieve the following behaviour when this happens.
1. Update the existing data in the table
2. Add any new rows that "Match" the current filters
3. Remove any rows that have changed and don't match the filters
4. Keep the existing scroll position
5. Keep any selected rows.
6. If the filters are removed show the latest data.
There are 3 methods to update Tabulator
<http://tabulator.info/docs/4.5/update>
1. SetData (we use this when we first fetch)
2. updateData
3. updateOrAddData (we use this on repeated fetches but row edits don't get filtered out)
4. replaceData
In the documents is mentions that 'replaceData' will update existing table data with out resetting the scroll position or selected rows, this does not seem to be the case. 'updateData' does update the data and leaves the scroll pos and selected rows as is, BUT it does not apply the filters, for example if a row is updated out of the scope of the current filter it still shows?
Our code right now:
```
if (replace) {
table.updateOrAddData(data); //replaceData
} else {
table.setData(data);
}
```
We need the table to update and meet our requirements in my above points 1-6. I would expect one of the methods listed (replace, update) would do this and in the docs it seems they should, but in our tests this fails. How can we achieve the desired results?
We are using version 4.5 downgraded from 4.4.
Edit:
So for example if we update the table with data and one of the rows in the table does not exist in the new data, that update does not persist. Unless we use setData which resets the scroll position, undoes all selected rows and so on. | 2020/01/30 | [
"https://Stackoverflow.com/questions/59994928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141347/"
] | The latest version of Tabulator, 4.9, adds a [refreshFilter](http://tabulator.info/docs/4.9/filter#manage) function. This should accomplish most of your request.
My own testing also show that the sorters are also refreshed by this function.
`table.refreshFilter();` | if I understand your OP, this is what you were looking for ?
```
var selected,visible;
var t = new Tabulator("#tabulator", {
data:[
{id:1,title:'One'},{id:2,title:'Two'},{id:3,title:'Three'},{id:4,title:'Four'},{id:5,title:'Five'},
{id:11,title:'Eleven'},{id:12,title:'Twelve'},{id:13,title:'Thirteen'},{id:14,title:'Fourteen'},{id:15,title:'Fifteen'},
],
height:"10em",
selectable:true,
columns:[ {title:'Title',field:'title',headerFilter:'input'}, ],
initialHeaderFilter:[{field:'title',value:'e'}],
dataLoading:function(d) { if (t) { selected = t.getSelectedData().map(o => o['id']); visible = t.getData('visible').map(o => o['id']); } },
dataLoaded:function(d) { if (t) { t.selectRow(selected); t.scrollToRow(visible); } }
});
t.selectRow([3,11,15]);
t.scrollToRow(15);
setTimeout(() => {
t.replaceData([
{id:3,title:'Three'},{id:5,title:'Five'},{id:6,title:'Six'},{id:7,title:'Seven'},{id:8,title:'Eight'},{id:9,title:'Nine'},{id:10,title:'Ten'},
{id:13,title:'Thirteen'},{id:15,title:'Fifteen'},{id:16,title:'Sixteen'},{id:17,title:'Seventeen'},{id:18,title:'Eighteen'},{id:19,title:'Nineteen'},{id:20,title:'Twenty'},
]);
},5000);
``` |
7,037,273 | I looking for way to animate text with jQuery.
I want to display 'logging in...' message where 3 dots should be hidden on page load and after every lets say 300ms 1 dot to become visible. Which all together should create animation.
Is there any jQuery function created to do exact that or I will have to right my own?
Any suggestions much appreciated. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7037273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616643/"
] | This can be done rather nicely with a jQuery plugin. This makes it re-usable and configurable.
Something like this is simple enough. It has 3 defaults, which can be overriden
* **text** defaulted to "Loading"
* **numDots** the number of dots to count up to before recycling back to zero, defaults to 3
* **delay** the delay inbetween adding new dots. defaults to 300ms
```
(function($) {
$.fn.elipsesAnimation = function(options) {
var settings = $.extend({}, { //defaults
text: 'Loading',
numDots: 3,
delay: 300
}, options);
var currentText = "";
var currentDots = 0;
return this.each(function() {
var $this = $(this);
currentText = settings.text;
$this.html(currentText);
setTimeout(function() {
addDots($this);
}, settings.delay);
});
function addDots($elem) {
if (currentDots >= settings.numDots) {
currentDots = 0;
currentText = settings.text;
}
currentText += ".";
currentDots++;
$elem.html(currentText);
setTimeout(function() {
addDots($elem);
}, settings.delay);
}
}
})(jQuery);
```
Usage could then be
```
// Writes "Hello World", counts up to 10 dots with a 0.5second delay
$('#testDiv').elipsesAnimation ({text:"Hello World",numDots:10,delay:500});
```
And a live example: <http://jsfiddle.net/6bbKk/> | <http://api.jquery.com/fadeOut/>
<http://api.jquery.com/fadeIn/>
Use with :
```
$(document).ready( function() {
//fadeIn your text, fake function for example
FadeInMyText();
setTimeout(function() {
// fadeOut your text, fake function for example
FadeOutMyText();
}, 300);
});
``` |
7,037,273 | I looking for way to animate text with jQuery.
I want to display 'logging in...' message where 3 dots should be hidden on page load and after every lets say 300ms 1 dot to become visible. Which all together should create animation.
Is there any jQuery function created to do exact that or I will have to right my own?
Any suggestions much appreciated. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7037273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616643/"
] | This can be done rather nicely with a jQuery plugin. This makes it re-usable and configurable.
Something like this is simple enough. It has 3 defaults, which can be overriden
* **text** defaulted to "Loading"
* **numDots** the number of dots to count up to before recycling back to zero, defaults to 3
* **delay** the delay inbetween adding new dots. defaults to 300ms
```
(function($) {
$.fn.elipsesAnimation = function(options) {
var settings = $.extend({}, { //defaults
text: 'Loading',
numDots: 3,
delay: 300
}, options);
var currentText = "";
var currentDots = 0;
return this.each(function() {
var $this = $(this);
currentText = settings.text;
$this.html(currentText);
setTimeout(function() {
addDots($this);
}, settings.delay);
});
function addDots($elem) {
if (currentDots >= settings.numDots) {
currentDots = 0;
currentText = settings.text;
}
currentText += ".";
currentDots++;
$elem.html(currentText);
setTimeout(function() {
addDots($elem);
}, settings.delay);
}
}
})(jQuery);
```
Usage could then be
```
// Writes "Hello World", counts up to 10 dots with a 0.5second delay
$('#testDiv').elipsesAnimation ({text:"Hello World",numDots:10,delay:500});
```
And a live example: <http://jsfiddle.net/6bbKk/> | In jQuery there is the delay(milliseconds, callback) function. You could use the callback function to orchestrate the delay. However for your purposes the [javascript window setTimeout](https://developer.mozilla.org/en/window.setTimeout) would probably be more appropriate as you can run window.clearTimeout as soon as your loading is complete, resulting in a more responsive UI.
An example:
```
var timeoutId;
$(document).ready( function() {
timeoutId = window.doTextUpdate(slowAlert, 2000);
});
function doTextUpdate() {
var current = $("#mytext").val();
if(current.indexOf("...")) {
$("#mytext").val("Loading");
} else {
$("#mytext").val(current + ".");
}
}
function loadComplete() {
window.clearTimeout(timeoutId);
}
``` |
7,037,273 | I looking for way to animate text with jQuery.
I want to display 'logging in...' message where 3 dots should be hidden on page load and after every lets say 300ms 1 dot to become visible. Which all together should create animation.
Is there any jQuery function created to do exact that or I will have to right my own?
Any suggestions much appreciated. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7037273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616643/"
] | This can be done rather nicely with a jQuery plugin. This makes it re-usable and configurable.
Something like this is simple enough. It has 3 defaults, which can be overriden
* **text** defaulted to "Loading"
* **numDots** the number of dots to count up to before recycling back to zero, defaults to 3
* **delay** the delay inbetween adding new dots. defaults to 300ms
```
(function($) {
$.fn.elipsesAnimation = function(options) {
var settings = $.extend({}, { //defaults
text: 'Loading',
numDots: 3,
delay: 300
}, options);
var currentText = "";
var currentDots = 0;
return this.each(function() {
var $this = $(this);
currentText = settings.text;
$this.html(currentText);
setTimeout(function() {
addDots($this);
}, settings.delay);
});
function addDots($elem) {
if (currentDots >= settings.numDots) {
currentDots = 0;
currentText = settings.text;
}
currentText += ".";
currentDots++;
$elem.html(currentText);
setTimeout(function() {
addDots($elem);
}, settings.delay);
}
}
})(jQuery);
```
Usage could then be
```
// Writes "Hello World", counts up to 10 dots with a 0.5second delay
$('#testDiv').elipsesAnimation ({text:"Hello World",numDots:10,delay:500});
```
And a live example: <http://jsfiddle.net/6bbKk/> | ```
<script type="text/javascript" language="javascript">
$(function(){launchAnimation('#animate');});
function launchAnimation(container){
var cont = $(container);
var i=0;
setInterval(function(){
++i;
if (i<4){
var dot=jQuery("<span class='dot'>.</span>").appendTo(cont);
}
else{
i=0;
cont.find('.dot').remove();
}
},300);
}
</script>
<div id='animate' style='border:1px solid red'>Logging in</div>
``` |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Sibling marriage, and later, "near kin" marriage, was the only initial option; the limited selection repeated with Noah's 3 sons and their wives following the great flood. Just 340 year later Abram, was 10 when his half-sister Sarai was born. During this time period sibling and "near kin" marriage was less common, but not certainly accepted and not prohibited yet; even forms of endogamy was still practiced at this time. Genesis 19:30-38 shows a good example of the times when the daughters of Abram's nephew, Lot, sleep with their father Lot out of necessity of circumstance; endogamy is demonstrated when Jacob, then Abraham's grandson, was instructed by his father Isaac to seek a marriage within the family, and Rebekah, daughter of Bethuel the son of Milcah, the wife of Abraham’s brother Nahor was chosen by God to be Isaac's wife. It was over 500 years later that near kin marriage was declared as wrong within Leviticus 18, 20 and Deuteronomy; it's interesting to note that marriage between a man and his step sister, his wife's niece or daughter are not prohibited specifically anywhere in those texts. | Abraham married his wife before his calling from God and before the 10 commandments. Every wrong action after the 10 commandments is a sin. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | During Abraham's time the law hadn't been written against a man taking his father's daughter as his wife. After the law was written in:
>
> **[Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NKJV)** (NKJV)
>
> 22 ‘Cursed *is* the one who lies with his sister, the daughter of his father or the daughter of his mother.’
>
> “And all the people shall say, ‘Amen!’
>
>
>
it forbade such a practice even today, but the lineage of Christ was coming through Abraham and Sarah. This also shows what happens when we are faced with fear that our faith is too weak to overcome. | In Genesis 11:31 the KJV reads "And Terah took Abram his son, and Lot the son of Haran his son's son, and Sarai his daughter in law, his son Abram's wife; and they went forth with them from Ur of the Chaldees, to go into the land of Canaan; and they came unto Haran, and dwelt there."
Why would it say "Sarai his daughter in law" if she was in fact Terah's daughter? It would be shorter and more accurate to say "Sarai his daughter, his son Abram's wife" rather than "Sarai his daughter in law, his son Abram's wife" as it does. Was the fact that she was married to Abraham more relevant in a patriarchal society, so that it should be repeated twice while leaving out the father-daughter relationship? Or perhaps the author of Genesis 11 wanted to obscure the fact that Abraham had committed incest? None of these seem very satisfactory to me.
This induces me to consider that in Genesis 20:12, Abraham is lying again to Abimelech, in order to cover up the fact that he lied about Sarah being his sister. He said she was his sister in order to deceive Abimelech about her being his wife, and now he's saying that she's his half-sister in order to deceive Abimelech about the fact that he lied to the king.
However, the first lie was justified (albeit through the mouth of Abraham, not the narrator). That the second lie would not be explained to the reader at all seems jarring.
I guess another interpretation is based on something that other posters have asserted, that the words for "daughter" and "father" should be read loosely according to the languages spoken by the people involved. In that case, Sarah could have been Terah's grand-daughter; then maybe 11:31 left out this detail because the genealogies were being precise about lineage; while Abraham was being imprecise with Abimelech partly to cover up his first obfuscation. However, I would like to see where else in the Bible a granddaughter or grandson, for example, is referred to as a daughter or son. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Abraham just lacked faith at that time and was telling lies. He did not trust God to protect him, so he used his wife and her beauty instead – that's why God kept revealing and exposing him where ever he went. | Abraham married his wife before his calling from God and before the 10 commandments. Every wrong action after the 10 commandments is a sin. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Like my answer [here](https://christianity.stackexchange.com/questions/5049/did-adam-and-eves-progeny-commit-incest), you need to keep the chronology right. There is no levitical law at the time of Abraham.
Thus, even if he did marry his sister, remember that he was breaking no covenantal restriction on doing so. As I said in that answer, you don't convict someone of a crime *ex post facto*. | During Abraham's time the law hadn't been written against a man taking his father's daughter as his wife. After the law was written in:
>
> **[Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NKJV)** (NKJV)
>
> 22 ‘Cursed *is* the one who lies with his sister, the daughter of his father or the daughter of his mother.’
>
> “And all the people shall say, ‘Amen!’
>
>
>
it forbade such a practice even today, but the lineage of Christ was coming through Abraham and Sarah. This also shows what happens when we are faced with fear that our faith is too weak to overcome. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Marrying a close relative was not forbidden at that time. The old question of "Where did Cain get his wife?" is answered by saying that he married a sister of his. It was not immoral at that time, since there was no law forbidding it.
Leviticus is where we find such laws, which was written over 400 years after the time of Abraham. We now understand that as the genetic pool has become degraded, it is best not to marry a close relative because of the possibility of both husband and wife having the same genetic deficiencies.
Early on in human history, these genetic deficiencies were quite minimal, so there wasn't an issue.
Marrying a sister may have been uncommon at that time, so Abraham appears to be fudging a bit to justify Sarah as his sister. He has to explain how she is his sister, because she isn't his direct sister. So, he's trying to justify his lie by a tenuous explanation.
So again, there was no law that he was breaking at that time. It would be as if the government passed a law against eating twinkies and then rounded up everyone who had ever eaten one before it was outlawed. The American Justice system strictly forbids this practice (Ex Post Facto). | In Ancient times, the word for "sister" also means "cousin" in Semitic languages. Aramaic word "Khtha" can mean sister or cousin. I believe the intended meaning here was Cousin.
Genesis 11:26-27 (NIV) - "After Terah had lived 70 years, he became the father of **Abram, Nahor and Haran**. This is the account of Terah’s family line. Terah became **the father of Abram, Nahor and Haran**."
If Sarai (later Sarah) was the daughter of Terah, then Sarai would have been listed along with Abram, Nahor, and Haran.
So we can confirm that the intended meaning was cousin.
In ancient Semitic languages, it must be noted that the word for father can also mean ancestor. For Example, Aramaic word "abba" can mean "father" or "ancestor/progenitor" (Source - Book "Introduction to Syriac" by Wheeler Thackston, Page 65)
Abraham was an Aramean (Deuteronomy 26:5) and Arameans spoke Aramaic. Abraham spoke Aramaic before he came to the land of Canaan where Old Hebrew was spoken. Laban the Aramean spoke Aramaic ("Jegar Sahadutha" in Genesis 31:47).
Check on Footnotes (at the bottom of the website) for ["Jegar Sahadutha"](http://www.biblegateway.com/passage/?search=Genesis%2031&version=NIV).
I also want to point out that the commandments were established as early as the time period when Noah lived. For Example, Noah knew about clean animals and unclean animals.
Genesis 7:2-4 - Take with you seven pairs of every kind of **clean animal**, a male and its mate, and one pair of every kind of **unclean animal**, a male and its mate, and also seven pairs of every kind of bird, male and female, to keep their various kinds alive throughout the earth. Seven days from now I will send rain on the earth for forty days and forty nights, and I will wipe from the face of the earth every living creature I have made.”
God gave Abraham commands, decrees, and instructions. Abraham obeyed God and kept all of what God taught him.
Genesis 26:4-5 - "I will make your descendants as numerous as the stars in the sky and will give them all these lands, and through your offspring all nations on earth will be blessed, because **Abraham obeyed me and did everything I required of him, keeping my commands, my decrees and my instructions**."
This is the same type of instruction God gave to Moses in Deuteronomy 11:1.
Deuteronomy 11:1 - "**Love the Lord your God and keep his requirements, his decrees, his laws and his commands always**."
But you may ask what about Moses' father marrying his aunt? In Hebrew Masoretic Text, it says this.
Exodus 6:20 (1917 JPS Tanakh English translation of Hebrew Masoretic Text) - "And Amram took him Jochebed **his father’s sister to wife**; and she bore him Aaron and Moses. And the years of the life of Amram were a hundred and thirty and seven years.“
This is confirmed as an error by Scholars, because Septuagint and Peshitta Tanakh (Aramaic Old Testament used in first century Israel) says Amram married his cousin.
Exodus 6:20 (Samuel Bagster & Sons' Translation from Septuagint) - "And Ambram took to wife Jochabed **the daughter of his father's brother**, and she bore to him both Aaron and Moses, and Mariam their sister; and the years of the life of Ambram were a hundred and thirty-two years."
Here is a [link](http://ecmarsh.com/lxx/Exodus/index.htm) to check this information.
Exodus 6:20 (Lamsa translation of Peshitta Tanakh)- "And Amram took **his uncle’s daughter** Jokhaber, and she bore him Aaron, Moses, and Miriam; and the years of the life of Amram were a hundred and thirty-seven years."
But Peshitta Tanakh (Aramaic Old Testament) agrees with Hebrew Masoretic Text about Ambram’s age.
Cousin Marriage is permitted in the Bible. It is not in the prohibited marriage list mentioned in Leviticus Chapter 18. Aside from Exodus 6:20, we see cousin marriages in Genesis 29, Joshua 15:17, Numbers 36:1-11, 1 Chronicles 23:22. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | During Abraham's time the law hadn't been written against a man taking his father's daughter as his wife. After the law was written in:
>
> **[Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NKJV)** (NKJV)
>
> 22 ‘Cursed *is* the one who lies with his sister, the daughter of his father or the daughter of his mother.’
>
> “And all the people shall say, ‘Amen!’
>
>
>
it forbade such a practice even today, but the lineage of Christ was coming through Abraham and Sarah. This also shows what happens when we are faced with fear that our faith is too weak to overcome. | "If Sarai (later Sarah) was the daughter of Terah, then Sarai would have been listed along with Abram, Nahor, and Haran.
So we can confirm that the intended meaning was cousin."
Hmm, but in Genesis 20 Abraham says ...
Abraham replied, “I said to myself, ‘There is surely no fear of God in this place, and they will kill me because of my wife.’ 12 Besides, she really is my sister, the daughter of my father though not of my mother; and she became my wife.
... So I guess she was his half-sister and the marraige very much was an incestuous one. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Like my answer [here](https://christianity.stackexchange.com/questions/5049/did-adam-and-eves-progeny-commit-incest), you need to keep the chronology right. There is no levitical law at the time of Abraham.
Thus, even if he did marry his sister, remember that he was breaking no covenantal restriction on doing so. As I said in that answer, you don't convict someone of a crime *ex post facto*. | "If Sarai (later Sarah) was the daughter of Terah, then Sarai would have been listed along with Abram, Nahor, and Haran.
So we can confirm that the intended meaning was cousin."
Hmm, but in Genesis 20 Abraham says ...
Abraham replied, “I said to myself, ‘There is surely no fear of God in this place, and they will kill me because of my wife.’ 12 Besides, she really is my sister, the daughter of my father though not of my mother; and she became my wife.
... So I guess she was his half-sister and the marraige very much was an incestuous one. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Marrying a close relative was not forbidden at that time. The old question of "Where did Cain get his wife?" is answered by saying that he married a sister of his. It was not immoral at that time, since there was no law forbidding it.
Leviticus is where we find such laws, which was written over 400 years after the time of Abraham. We now understand that as the genetic pool has become degraded, it is best not to marry a close relative because of the possibility of both husband and wife having the same genetic deficiencies.
Early on in human history, these genetic deficiencies were quite minimal, so there wasn't an issue.
Marrying a sister may have been uncommon at that time, so Abraham appears to be fudging a bit to justify Sarah as his sister. He has to explain how she is his sister, because she isn't his direct sister. So, he's trying to justify his lie by a tenuous explanation.
So again, there was no law that he was breaking at that time. It would be as if the government passed a law against eating twinkies and then rounded up everyone who had ever eaten one before it was outlawed. The American Justice system strictly forbids this practice (Ex Post Facto). | In Genesis 11:31 the KJV reads "And Terah took Abram his son, and Lot the son of Haran his son's son, and Sarai his daughter in law, his son Abram's wife; and they went forth with them from Ur of the Chaldees, to go into the land of Canaan; and they came unto Haran, and dwelt there."
Why would it say "Sarai his daughter in law" if she was in fact Terah's daughter? It would be shorter and more accurate to say "Sarai his daughter, his son Abram's wife" rather than "Sarai his daughter in law, his son Abram's wife" as it does. Was the fact that she was married to Abraham more relevant in a patriarchal society, so that it should be repeated twice while leaving out the father-daughter relationship? Or perhaps the author of Genesis 11 wanted to obscure the fact that Abraham had committed incest? None of these seem very satisfactory to me.
This induces me to consider that in Genesis 20:12, Abraham is lying again to Abimelech, in order to cover up the fact that he lied about Sarah being his sister. He said she was his sister in order to deceive Abimelech about her being his wife, and now he's saying that she's his half-sister in order to deceive Abimelech about the fact that he lied to the king.
However, the first lie was justified (albeit through the mouth of Abraham, not the narrator). That the second lie would not be explained to the reader at all seems jarring.
I guess another interpretation is based on something that other posters have asserted, that the words for "daughter" and "father" should be read loosely according to the languages spoken by the people involved. In that case, Sarah could have been Terah's grand-daughter; then maybe 11:31 left out this detail because the genealogies were being precise about lineage; while Abraham was being imprecise with Abimelech partly to cover up his first obfuscation. However, I would like to see where else in the Bible a granddaughter or grandson, for example, is referred to as a daughter or son. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | During Abraham's time the law hadn't been written against a man taking his father's daughter as his wife. After the law was written in:
>
> **[Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NKJV)** (NKJV)
>
> 22 ‘Cursed *is* the one who lies with his sister, the daughter of his father or the daughter of his mother.’
>
> “And all the people shall say, ‘Amen!’
>
>
>
it forbade such a practice even today, but the lineage of Christ was coming through Abraham and Sarah. This also shows what happens when we are faced with fear that our faith is too weak to overcome. | Abraham married his wife before his calling from God and before the 10 commandments. Every wrong action after the 10 commandments is a sin. |
5,389 | In the comments to [this answer](https://christianity.stackexchange.com/a/5258/85) to [the question of why Abraham lied to Pharaoh about his relationship with Sarah](https://christianity.stackexchange.com/questions/3524/why-did-abraham-lie-to-pharaoh-about-sarah-being-his-sister-in-gen-12/5258#5258), the following question which I am about to pose, appeared:
**Was the marriage between Abraham and Sarah incestuous?**
In two separate occasions, Abraham told the local ruler that Sarah was his sister. These two passages are found in in [Genesis 12:10-20](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV) and [Genesis 20](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV).
Let's examine the first passage:
[Genesis 12:10-20 (NIV)](http://www.biblegateway.com/passage/?search=Gen%2012:10-20&version=NIV)
>
> 10 Now there was a famine in the land, and Abram went down to Egypt to live there for a while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woman you are. **12 When the Egyptians see you, they will say, ‘This is his wife.’ Then they will kill me but will let you live. 13 Say you are my sister, so that I will be treated well for your sake and my life will be spared because of you.”**
>
>
> 14 When Abram came to Egypt, the Egyptians saw that Sarai was a very beautiful woman. 15 And when Pharaoh’s officials saw her, they praised her to Pharaoh, and she was taken into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and cattle, male and female donkeys, male and female servants, and camels.
>
>
> 17 But the LORD inflicted serious diseases on Pharaoh and his household because of Abram’s wife Sarai. **18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why didn’t you tell me she was your wife? 19 Why did you say, ‘She is my sister,’ so that I took her to be my wife? Now then, here is your wife. Take her and go!”** 20 Then Pharaoh gave orders about Abram to his men, and they sent him on his way, with his wife and everything he had.
>
>
>
This seems to imply that since Abraham told Pharaoh that Sarah was his sister, Sarah was believed to be his sister only and not his wife. This, in turns, makes me draw the conclusion that marriage between siblings was unusual.
Let's head on to the second passage:
[Genesis 20 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%2020&version=NIV)
>
> 1 Now Abraham moved on from there into the region of the Negev and
> lived between Kadesh and Shur. For a while he stayed in Gerar, **2 and
> there Abraham said of his wife Sarah, “She is my sister.” Then
> Abimelek king of Gerar sent for Sarah and took her.** 3 But God came to
> Abimelek in a dream one night and said to him, “You are as good as
> dead because of the woman you have taken; she is a married woman.”
>
>
> 4 Now Abimelek had not gone near her, so he said, “Lord, will you
> destroy an innocent nation? **5 Did he not say to me, ‘She is my
> sister,’ and didn’t she also say, ‘He is my brother’? I have done this
> with a clear conscience and clean hands.”**
>
>
> 6 Then God said to him in the dream, “Yes, I know you did this with a
> clear conscience, and so I have kept you from sinning against me. That
> is why I did not let you touch her. 7 Now return the man’s wife, for
> he is a prophet, and he will pray for you and you will live. But if
> you do not return her, you may be sure that you and all who belong to
> you will die.”
>
>
> 8 Early the next morning Abimelek summoned all his officials, and
> when he told them all that had happened, they were very much afraid. 9
> Then Abimelek called Abraham in and said, “What have you done to us?
> How have I wronged you that you have brought such great guilt upon me
> and my kingdom? You have done things to me that should never be done.”
> 10 And Abimelek asked Abraham, “What was your reason for doing this?”
>
>
> 11 Abraham replied, “I said to myself, ‘There is surely no fear of
> God in this place, and they will kill me because of my wife.’ **12
> Besides, she really is my sister, the daughter of my father though not
> of my mother; and she became my wife. 13 And when God had me wander
> from my father’s household, I said to her, ‘This is how you can show
> your love to me: Everywhere we go, say of me, “He is my brother.”’”**
>
>
> 14 Then Abimelek brought sheep and cattle and male and female slaves
> and gave them to Abraham, and he returned Sarah his wife to him. 15
> And Abimelek said, “My land is before you; live wherever you like.”
>
>
> 16 To Sarah he said, “I am giving your brother a thousand shekels[a]
> of silver. This is to cover the offense against you before all who are
> with you; you are completely vindicated.”
>
>
> 17 Then Abraham prayed to God, and God healed Abimelek, his wife and
> his female slaves so they could have children again, 18 for the LORD
> had kept all the women in Abimelek’s household from conceiving because
> of Abraham’s wife Sarah.
>
>
>
This second passage also tells us that marriage between siblings was unusual. It also tells us that Abraham did not really lie when he said that Sarah was his sister, since she was his half-sister. *Also note that nowhere in the two passages Abraham is accused of lying!* This is a quite interesting fact. In any way, it is clear that our definition of incest in today's western society, is not the same as it was in that time and place. Still, [Deuteronomy 27:22](http://www.biblegateway.com/passage/?search=Deuteronomy%2027:22&version=NIV) clearly states that for a man to marry his father's daughter (as Abraham did) is a sin!
How does one reconcile these passages? Was Abraham's and Sarah's marriage a sin? Was it considered incest? | 2012/01/13 | [
"https://christianity.stackexchange.com/questions/5389",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/85/"
] | Marrying a close relative was not forbidden at that time. The old question of "Where did Cain get his wife?" is answered by saying that he married a sister of his. It was not immoral at that time, since there was no law forbidding it.
Leviticus is where we find such laws, which was written over 400 years after the time of Abraham. We now understand that as the genetic pool has become degraded, it is best not to marry a close relative because of the possibility of both husband and wife having the same genetic deficiencies.
Early on in human history, these genetic deficiencies were quite minimal, so there wasn't an issue.
Marrying a sister may have been uncommon at that time, so Abraham appears to be fudging a bit to justify Sarah as his sister. He has to explain how she is his sister, because she isn't his direct sister. So, he's trying to justify his lie by a tenuous explanation.
So again, there was no law that he was breaking at that time. It would be as if the government passed a law against eating twinkies and then rounded up everyone who had ever eaten one before it was outlawed. The American Justice system strictly forbids this practice (Ex Post Facto). | "If Sarai (later Sarah) was the daughter of Terah, then Sarai would have been listed along with Abram, Nahor, and Haran.
So we can confirm that the intended meaning was cousin."
Hmm, but in Genesis 20 Abraham says ...
Abraham replied, “I said to myself, ‘There is surely no fear of God in this place, and they will kill me because of my wife.’ 12 Besides, she really is my sister, the daughter of my father though not of my mother; and she became my wife.
... So I guess she was his half-sister and the marraige very much was an incestuous one. |
719,342 | I have no idea how to solve these two, any help?
$\mathtt{i)}$ $$\frac{1}{2\pi i}\int\_{a-i\infty}^{a+i\infty}\frac{e^{tz}}{\sqrt{z+1}}dz$$ $$ a,t\gt0$$
$\mathtt{ii)}$
$$ \sum\_{n=1}^\infty \frac{\coth (n\pi)}{n^3}=\frac{7\pi^3}{180}$$ | 2014/03/20 | [
"https://math.stackexchange.com/questions/719342",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/135386/"
] | I'll do (i). Consider the contour integral
$$\oint\_C dz \frac{e^{t z}}{\sqrt{z+1}}$$
where $C$ is the contour consisting of the line $\Re{z}=a$, $\Im{z} \in [-R,R]$; a circular arc of radius $R$ from $a+i R$ to $R e^{i \pi}$; a line from $R e^{i \pi}$ to $((1+\epsilon) e^{i \pi}$; a circle arc about $z=-1$ of radius $\epsilon$ from $((1+\epsilon) e^{i \pi}$ to $((1+\epsilon) e^{-i \pi}$; a line from $((1+\epsilon) e^{-i \pi}$ to $R e^{-i \pi}$; and a circular arc of radius $R$ from $R e^{-i \pi}$ to $a-i R$. Note that the integrals over all the circular arcs vanish as $R \to \infty$ and $\epsilon \to 0$. Thus we have, by Cauchy's theorem:
$$ \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} + e^{i \pi} e^{-t} \int\_{\infty}^0 dx \, \frac{e^{-t x}}{e^{i \pi/2} \sqrt{x}}+ e^{-i \pi} e^{-t} \int\_{\infty}^0 dx \, \frac{e^{-t x}}{e^{-i \pi/2} \sqrt{x}} =0$$
Thus,
$$\frac1{i 2 \pi} \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} = \frac{1}{\pi} e^{-t} \int\_0^{\infty} dx \, x^{-1/2} \, e^{-x t} $$
Using a substitution $x=u^2$ and a rescaling in the integral, we find that
$$\frac1{i 2 \pi} \int\_{a-i \infty}^{a+i \infty} dz \frac{e^{z t}}{\sqrt{z+1}} = \frac{e^{-t}}{\sqrt{\pi t}}$$ | For the second problem, let $ \displaystyle f(z) = \frac{\pi\cot (\pi z) \coth(\pi z)}{z^{3}}$ and integrate around a square ($C\_{N}$) with vertices at $\pm (N+\frac{1}{2}) \pm (N+\frac{1}{2})$ where $N$ is a positive integer.
Both $\cot (\pi z)$ and $\coth(\pi z)$ are uniformly bounded on the contour.
So $ \displaystyle \int\_{C\_{N}} f(z) \ dz$ vanishes as $N$ goes to infinity through the integers..
And we have
$$ 2 \sum\_{n=1}^{\infty} \frac{\coth (\pi n)}{n^{3}} + \text{Res}[f(z),0] + \sum\_{n=1}^{\infty} \text{Res} [f(z),in] + \sum\_{n=1}^{\infty} \text{Res} [f(z),-in] =0 $$
where
$$ \text{Res} [f(z),in] = \lim\_{z \to in} \frac{\pi \cot (\pi z)}{\frac{d}{dz} (z^{3} \tanh (\pi z) )} = \lim\_{z \to in} \frac{\pi \cot (\pi z)}{3z^{2} \tanh (\pi z) + \pi z^{3} \text{sech}^{2} (\pi z) } = \frac{\coth(\pi n)}{n^{3}}$$
and similarly
$$ \text{Res} [f(z),-in] = \frac{\coth (\pi n)}{n^{3}} \ .$$
And expanding $\cot (\pi z)$ and $\coth(\pi z)$ in Laurent expansions about the origin,
$$ \begin{align} \frac{\pi\cot (\pi z) \coth(\pi z)}{z^{3}} &= \frac{\pi}{z^{3}} \left( \frac{1}{\pi z} - \frac{\pi z}{3} - \frac{\pi^{3}z^{3}}{45} + \ldots \right) \left( \frac{1}{\pi z} + \frac{\pi z}{3} - \frac{\pi^{3}z^{3}}{45} + \ldots \right) \\ &= \frac{\pi}{z^{3}} \left(\frac{1}{\pi^{2}z^{2}} + \frac{1}{3} - \frac{\pi^{2}z^{2}}{45} - \frac{1}{3} - \frac{\pi^{2} z^{2}}{9} - \frac{\pi^{2}z^{2}}{45} + \ldots \right) \\ &= \frac{1}{\pi z^{5}} - \frac{7 \pi^{3}}{45 z} + \ldots \ \ .\end{align}$$
Therefore, $$\text{Res}[f(z),0] = - \frac{7 \pi^{3}}{45}$$
and $$\sum\_{n=1}^{\infty} \frac{\coth (\pi n)}{n^{3}} = \frac{1}{4} \left( \frac{7 \pi^{3}}{45} \right) = \frac{7 \pi^{3}}{180} .$$ |
15,007,104 | I have a script I'm writing that makes a connection to a SOAP service. After the connection is made, I need to pass in a the username/pass with every command I send. The problem I have is that when I use read-host to do this, my password is shown in cleartext and remains in the shell:
```
PS C:\Users\Egr> Read-Host "Enter Pass"
Enter Pass: MyPassword
MyPassword
```
If I hide it with -AsSecureString, the value can no longer be passed to the service because it is now a System.Security.SecureString object:
```
PS C:\Users\gross> Read-Host "Enter Pass" -AsSecureString
Enter Pass: **********
System.Security.SecureString
```
When I pass this, it does not work. I don't care about the passwords being passed to the service in cleartext, I just don't want them sticking around on a user's shell after they enter their password. Is it possible to hide the Read-Host input, but still have the password stored as cleartext? If not, is there a way I can pass the System.Security.SecureString object as cleartext?
Thanks | 2013/02/21 | [
"https://Stackoverflow.com/questions/15007104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776890/"
] | $Password is a Securestring, and this will return the plain text password.
```
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
``` | You can save the password(input) as a variable and pass it to your service. If the code is run in a script or as a function, the variable containing the password will be deleted after it's done(they are stored in a temp. local scope). If you run the commands in the console(or dot-source the script like `. .\myscript.ps1`), the password variable will stay in the session scope, and they will be stored until you delete it or close the session. If you want to be sure the variable is removed after your script is run, you can delete it yourself. Like this:
```
#Get password in cleartext and store in $password variable
$password = Read-Host "Enter Pass"
#run code that needs password stored in $password
#Delete password
Remove-Variable password
```
To read more about how variables are stored in scopes, check out [about\_Scopes](http://technet.microsoft.com/en-us/library/hh847849.aspx) |
15,007,104 | I have a script I'm writing that makes a connection to a SOAP service. After the connection is made, I need to pass in a the username/pass with every command I send. The problem I have is that when I use read-host to do this, my password is shown in cleartext and remains in the shell:
```
PS C:\Users\Egr> Read-Host "Enter Pass"
Enter Pass: MyPassword
MyPassword
```
If I hide it with -AsSecureString, the value can no longer be passed to the service because it is now a System.Security.SecureString object:
```
PS C:\Users\gross> Read-Host "Enter Pass" -AsSecureString
Enter Pass: **********
System.Security.SecureString
```
When I pass this, it does not work. I don't care about the passwords being passed to the service in cleartext, I just don't want them sticking around on a user's shell after they enter their password. Is it possible to hide the Read-Host input, but still have the password stored as cleartext? If not, is there a way I can pass the System.Security.SecureString object as cleartext?
Thanks | 2013/02/21 | [
"https://Stackoverflow.com/questions/15007104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776890/"
] | $Password is a Securestring, and this will return the plain text password.
```
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
``` | There is a way to do this in PowerShell versions 6.x+:
```
$password = read-host -maskinput "Enter password"
```
, thanks to jborean93 for pointing this out to me. |
15,007,104 | I have a script I'm writing that makes a connection to a SOAP service. After the connection is made, I need to pass in a the username/pass with every command I send. The problem I have is that when I use read-host to do this, my password is shown in cleartext and remains in the shell:
```
PS C:\Users\Egr> Read-Host "Enter Pass"
Enter Pass: MyPassword
MyPassword
```
If I hide it with -AsSecureString, the value can no longer be passed to the service because it is now a System.Security.SecureString object:
```
PS C:\Users\gross> Read-Host "Enter Pass" -AsSecureString
Enter Pass: **********
System.Security.SecureString
```
When I pass this, it does not work. I don't care about the passwords being passed to the service in cleartext, I just don't want them sticking around on a user's shell after they enter their password. Is it possible to hide the Read-Host input, but still have the password stored as cleartext? If not, is there a way I can pass the System.Security.SecureString object as cleartext?
Thanks | 2013/02/21 | [
"https://Stackoverflow.com/questions/15007104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776890/"
] | You can save the password(input) as a variable and pass it to your service. If the code is run in a script or as a function, the variable containing the password will be deleted after it's done(they are stored in a temp. local scope). If you run the commands in the console(or dot-source the script like `. .\myscript.ps1`), the password variable will stay in the session scope, and they will be stored until you delete it or close the session. If you want to be sure the variable is removed after your script is run, you can delete it yourself. Like this:
```
#Get password in cleartext and store in $password variable
$password = Read-Host "Enter Pass"
#run code that needs password stored in $password
#Delete password
Remove-Variable password
```
To read more about how variables are stored in scopes, check out [about\_Scopes](http://technet.microsoft.com/en-us/library/hh847849.aspx) | There is a way to do this in PowerShell versions 6.x+:
```
$password = read-host -maskinput "Enter password"
```
, thanks to jborean93 for pointing this out to me. |
39,713,134 | I have a circle, consisting of 12 arc segments and I want to allow the user to see the transition from the start pattern to the end pattern. (there will be many start and end patterns).
I have included the transition property in the css file, so that is not the issue.
Here is my code so far:
```
function playAnimations(){
console.log("gets inside playanimations")
var totalLength = document.getElementsByClassName("container")[0].children.length
console.log(totalLength)
for(var i = 0; i < totalLength; i++){
var current_pattern = document.getElementsByClassName("container")[0].children[i]
for(var j = 0; j < 12; j++){
$('#LED' + (j+1) ).css('transition-duration', '0s');
$('#LED' + (j+1) ).css({fill: current_pattern.children[1].children[j].style.backgroundColor});
}
for(var k = 0; k < 12; k++){
$('#LED' + (k+1) ).css('transition-duration', "" + current_pattern.children[3].children[0].value + "ms");
$('#LED' + (k+1) ).css({fill: current_pattern.children[2].children[k].style.backgroundColor});
}
}
}
```
The outer for loop traverses through all the patterns while the inner two for loops traverse through the start and end values for that particular pattern. The problem I am having is that I only see the end colors on the circle and not the start colors.
Does anyone know a good workaround or what I could possibly do to rectify this issue? Any feedback or help is appreciated. | 2016/09/26 | [
"https://Stackoverflow.com/questions/39713134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162438/"
] | Give your Elements a `transition-delay` value. Of course a different one for each, like this
```
#LED1 {
transition-delay: 0.1s;
}
#LED2 {
transition-delay: 0.2s;
}
...
#LED2 {
transition-delay: 1.2s;
}
```
That should do it. You should be able to set the `transition-duration` directly in the **CSS** as well, no need for JavaScript I think.
Is there a special reason to have 2 inner for loops? Shouldn't one doing both be sufficient? | 1. Check the transition properties you need to define
```
transition-property*
transition-duration*
transition-timing-function
transition-delay
```
transition-delay could help you to concatenate transitions if you set it using a js loop.
2. Check your function is getting and setting the right values (a quick check in chrome's dev console will help you)
3. Are you sure you want to get elements by **container** as class? As it's a common name for divs, you may be getting some unwanted elements in your function. I'd recommend changing the class to another less common name.
4. Why two loops? I imagine the first one is for resetting the colors before the actual transition as you define `transition-duration:0s;` The second one would be the actual transition?.
5. The problem I see in each loop is you set css in two lines (separated with a ;).
Try `$('#LED' + (k+1) ).css('transition-duration', "" + current_pattern.children[3].children[0].value + "ms").css({fill: current_pattern.children[2].children[k].style.backgroundColor});`.
And maybe changing fill to background-color
`$('#LED' + (k+1) ).css('transition-duration', "" + current_pattern.children[3].children[0].value + "ms").css('background-color', current_pattern.children[2].children[k].style.backgroundColor);`
You can find all the docs about transitions at [W3C](https://www.w3.org/TR/css3-transitions/)! |
4,299,089 | I'm working on a journaling system in C# at our local church, but I've run into trouble with the database connection when storing birth dates. According to [MSDN](http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx?appId=Dev10IDEF1&l=EN-US&k=k%28SYSTEM.DATETIME%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&rd=true) the earlist date possible to represent is January 1st year 1. How am I supposed to record the birth date of Jesus Christ and earlier personalities that are important us? | 2010/11/28 | [
"https://Stackoverflow.com/questions/4299089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523204/"
] | You are going to have to roll your own class to handle BC dates in .NET, and store them in the database either as strings or as separate fields for year, month day (depending on what accuracy is required) if you require searching and sorting to be performed on the database side (which I assume you would).
SQL Server's support for dates is more restrictive than .NET's (it only goes back as far as 1753 or 1752 or thereabouts).
[This blog post](http://blog.flipbit.co.uk/2009/03/representing-large-ad-and-bc-dates-in-c.html) is one possible implementation, albeit a pretty limited one as it only stores the year. But I am sure you could modify it as necessary for your needs. For instance, it could probably do well to implement some interfaces such as IComparable, IEquatable, IFormattable and possibly IConvertible as well if you're keen so it can better interact with the rest of the framework. | Simple answer - store the day, month and year as separate numeric fields. The day and month can be combined into a day-of-the-year value, but you need to watch out for leap years.
Alternative answer - there are standard ways to convert a date into a day-number and back...
<http://en.wikipedia.org/wiki/Julian_day>
If you do the conversion yourself, you're basically storing a number (that just happens to represent a date) so you should have no problems. Well - other than making sure your conversions are correct. |
4,299,089 | I'm working on a journaling system in C# at our local church, but I've run into trouble with the database connection when storing birth dates. According to [MSDN](http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx?appId=Dev10IDEF1&l=EN-US&k=k%28SYSTEM.DATETIME%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&rd=true) the earlist date possible to represent is January 1st year 1. How am I supposed to record the birth date of Jesus Christ and earlier personalities that are important us? | 2010/11/28 | [
"https://Stackoverflow.com/questions/4299089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523204/"
] | If you are free to decide on type of calendar then I would recommend you to go-ahead with the Gregorian calendar, which has the
>
> ability to recognize two eras: B.C.
> and A.D.
>
>
>
<http://msdn.microsoft.com/en-us/library/system.globalization.gregoriancalendar.aspx> | Simple answer - store the day, month and year as separate numeric fields. The day and month can be combined into a day-of-the-year value, but you need to watch out for leap years.
Alternative answer - there are standard ways to convert a date into a day-number and back...
<http://en.wikipedia.org/wiki/Julian_day>
If you do the conversion yourself, you're basically storing a number (that just happens to represent a date) so you should have no problems. Well - other than making sure your conversions are correct. |
4,299,089 | I'm working on a journaling system in C# at our local church, but I've run into trouble with the database connection when storing birth dates. According to [MSDN](http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx?appId=Dev10IDEF1&l=EN-US&k=k%28SYSTEM.DATETIME%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&rd=true) the earlist date possible to represent is January 1st year 1. How am I supposed to record the birth date of Jesus Christ and earlier personalities that are important us? | 2010/11/28 | [
"https://Stackoverflow.com/questions/4299089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523204/"
] | <http://msdn.microsoft.com/en-us/library/system.globalization.gregoriancalendar.getera(v=VS.100).aspx> | Simple answer - store the day, month and year as separate numeric fields. The day and month can be combined into a day-of-the-year value, but you need to watch out for leap years.
Alternative answer - there are standard ways to convert a date into a day-number and back...
<http://en.wikipedia.org/wiki/Julian_day>
If you do the conversion yourself, you're basically storing a number (that just happens to represent a date) so you should have no problems. Well - other than making sure your conversions are correct. |
19,814,890 | well this is my problem..
```
<html>
<body>
<marquee id="introtext" scrollamount="150" behavior="slide" direction="left">
<p>
this is the sliding text.
</p>
</marquee>
</body>
</html>
```
What chrome does is just weard.
it repeats the "marquee" action after 4 seconds.
what can i do to prevent this? or just fully disable this marquee but still keep this id ,
because this is used for other css effects?
sincerely,
santino | 2013/11/06 | [
"https://Stackoverflow.com/questions/19814890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2960837/"
] | try loop="0" :
```
<marquee id="introtext" scrollamount="150" behavior="slide" direction="left" loop="0">
``` | >
> what can i do to prevent this? or just fully disable this marquee but
> still keep this id , because this is used for other css effects?
>
>
>
From `<marquee id="introtext" scrollamount="150" behavior="slide" direction="left">`
To `<div id="introtext">`
If you want just to remain with ID of block. But that deletes marquee. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instance variables are shared by all methods in the class. When one method changes the data, another method can be affected by it. It means that you can't understand any one method on its own since it is affected by the code in the other methods in the class. The order in which methods are called can affect the outcome. The methods may not be reentrant. That means that if the method is called, again, before it finishes its execution (say it calls a method that then calls it, or fires an event which then a listener calls the method) then it may fail or behave incorrectly since the data is shared. If that wasn't enough potential problems, when you have multithreading, the data could be changed while you are using it causing inconsistent and hard to reproduce bugs (race conditions).
Using local variables keeps the scope minimized to the smallest amount of code that needs it. This makes it easier to understand, and to debug. It avoids race conditions. It is easier to ensure the method is reentrant. It is a good practice to minimize the scope of data. | It's not a yes/no question. It basically depends on the situation and your needs. Declaring the variable in the smallest scope as possible is considered the best practice. However there may be some cases (like in this one) where, depending on the task, it's better to declare it inside/outside the methods. If you declare them outside it will be one instance, and it will be two on the other hand. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instance variables are shared by all methods in the class. When one method changes the data, another method can be affected by it. It means that you can't understand any one method on its own since it is affected by the code in the other methods in the class. The order in which methods are called can affect the outcome. The methods may not be reentrant. That means that if the method is called, again, before it finishes its execution (say it calls a method that then calls it, or fires an event which then a listener calls the method) then it may fail or behave incorrectly since the data is shared. If that wasn't enough potential problems, when you have multithreading, the data could be changed while you are using it causing inconsistent and hard to reproduce bugs (race conditions).
Using local variables keeps the scope minimized to the smallest amount of code that needs it. This makes it easier to understand, and to debug. It avoids race conditions. It is easier to ensure the method is reentrant. It is a good practice to minimize the scope of data. | Instance properties represent the state of a specific instance of that Class. It might make more sense to think about a concrete example. If the class is Engine, one of the properties that might represent the state of the Engine might be
```
private boolean running;
```
... so given an instance of Engine, you could call engine.isRunning() to check the state.
If a given property is not part of the state (or composition) of your Class, then it might be best suited to be a local variable within a method, as implementation detail. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instance variables are shared by all methods in the class. When one method changes the data, another method can be affected by it. It means that you can't understand any one method on its own since it is affected by the code in the other methods in the class. The order in which methods are called can affect the outcome. The methods may not be reentrant. That means that if the method is called, again, before it finishes its execution (say it calls a method that then calls it, or fires an event which then a listener calls the method) then it may fail or behave incorrectly since the data is shared. If that wasn't enough potential problems, when you have multithreading, the data could be changed while you are using it causing inconsistent and hard to reproduce bugs (race conditions).
Using local variables keeps the scope minimized to the smallest amount of code that needs it. This makes it easier to understand, and to debug. It avoids race conditions. It is easier to ensure the method is reentrant. It is a good practice to minimize the scope of data. | Your class name should have been `Foo`.
The two versions you have are not the same, and it should depend on your use case.
The first version returns the same `AClass` object when different callers call `returnAClassSetted()` method using the same `Foo` object. If one of them changes the state of the returned `AClass` object, all of them will get see the change. Your `Foo` class is effectively a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern).
The second version returns a new `AClass` object every time a caller calls `returnAClassSetted()` method using either the same or different `Foo` object. Your `Foo` class is effectively a [Builder](https://en.wikipedia.org/wiki/Builder_pattern).
Also, if you want the second version, remove the `AClass aVar = new AClass();` and just use `AClass aVar = doStuff();`. Because you are throwing away the first `AClass` object created by `new AClass();` |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instance variables are shared by all methods in the class. When one method changes the data, another method can be affected by it. It means that you can't understand any one method on its own since it is affected by the code in the other methods in the class. The order in which methods are called can affect the outcome. The methods may not be reentrant. That means that if the method is called, again, before it finishes its execution (say it calls a method that then calls it, or fires an event which then a listener calls the method) then it may fail or behave incorrectly since the data is shared. If that wasn't enough potential problems, when you have multithreading, the data could be changed while you are using it causing inconsistent and hard to reproduce bugs (race conditions).
Using local variables keeps the scope minimized to the smallest amount of code that needs it. This makes it easier to understand, and to debug. It avoids race conditions. It is easier to ensure the method is reentrant. It is a good practice to minimize the scope of data. | In Instance variables values given are default values means null so if it's an object reference, 0 if it's and int.
Local variables usually don't get default values, and therefore need to be explicitly initialized and the compiler generates an error if you fail to do so.
Further,
Local variables are only visible in the method or block in which they are declared whereas the instance variable can be seen by all methods in the class. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your class name should have been `Foo`.
The two versions you have are not the same, and it should depend on your use case.
The first version returns the same `AClass` object when different callers call `returnAClassSetted()` method using the same `Foo` object. If one of them changes the state of the returned `AClass` object, all of them will get see the change. Your `Foo` class is effectively a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern).
The second version returns a new `AClass` object every time a caller calls `returnAClassSetted()` method using either the same or different `Foo` object. Your `Foo` class is effectively a [Builder](https://en.wikipedia.org/wiki/Builder_pattern).
Also, if you want the second version, remove the `AClass aVar = new AClass();` and just use `AClass aVar = doStuff();`. Because you are throwing away the first `AClass` object created by `new AClass();` | It's not a yes/no question. It basically depends on the situation and your needs. Declaring the variable in the smallest scope as possible is considered the best practice. However there may be some cases (like in this one) where, depending on the task, it's better to declare it inside/outside the methods. If you declare them outside it will be one instance, and it will be two on the other hand. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your class name should have been `Foo`.
The two versions you have are not the same, and it should depend on your use case.
The first version returns the same `AClass` object when different callers call `returnAClassSetted()` method using the same `Foo` object. If one of them changes the state of the returned `AClass` object, all of them will get see the change. Your `Foo` class is effectively a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern).
The second version returns a new `AClass` object every time a caller calls `returnAClassSetted()` method using either the same or different `Foo` object. Your `Foo` class is effectively a [Builder](https://en.wikipedia.org/wiki/Builder_pattern).
Also, if you want the second version, remove the `AClass aVar = new AClass();` and just use `AClass aVar = doStuff();`. Because you are throwing away the first `AClass` object created by `new AClass();` | Instance properties represent the state of a specific instance of that Class. It might make more sense to think about a concrete example. If the class is Engine, one of the properties that might represent the state of the Engine might be
```
private boolean running;
```
... so given an instance of Engine, you could call engine.isRunning() to check the state.
If a given property is not part of the state (or composition) of your Class, then it might be best suited to be a local variable within a method, as implementation detail. |
31,972,045 | Is there a reason to prefer using shared instance variable in class vs. local variable and have methods return the instance to it? Or is either one a bad practice?
```
import package.AClass;
public class foo {
private AClass aVar = new AClass();
// ... Constructor
public AClass returnAClassSetted() {
doStuff(aVar);
return avar;
}
private void doStuff(AClass a) {
aVar = a.setSomething("");
}
}
```
vs.
```
import package.AClass;
public class foo {
// ... Constructor
public AClass returnAClassSetted() {
AClass aVar = new AClass();
aVar = doStuff();
return aVar;
}
private AClass doStuff() {
AClass aVar1 = new AClass();
aVar1.setSomething("");
return aVar1;
}
}
```
First one makes more sense to me in so many ways but I often see code that does the second. Thanks! | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your class name should have been `Foo`.
The two versions you have are not the same, and it should depend on your use case.
The first version returns the same `AClass` object when different callers call `returnAClassSetted()` method using the same `Foo` object. If one of them changes the state of the returned `AClass` object, all of them will get see the change. Your `Foo` class is effectively a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern).
The second version returns a new `AClass` object every time a caller calls `returnAClassSetted()` method using either the same or different `Foo` object. Your `Foo` class is effectively a [Builder](https://en.wikipedia.org/wiki/Builder_pattern).
Also, if you want the second version, remove the `AClass aVar = new AClass();` and just use `AClass aVar = doStuff();`. Because you are throwing away the first `AClass` object created by `new AClass();` | In Instance variables values given are default values means null so if it's an object reference, 0 if it's and int.
Local variables usually don't get default values, and therefore need to be explicitly initialized and the compiler generates an error if you fail to do so.
Further,
Local variables are only visible in the method or block in which they are declared whereas the instance variable can be seen by all methods in the class. |
494,571 | I am currently studying for the GRE Physics subject test by working through published past tests. My question is about problem 44 from the test GR8677:
>
> [](https://i.stack.imgur.com/DzNMT.png)
>
>
> $44.$ A uniform stick of length $L$ and mass $M$ lies on a frictionless horizontal surface. A point particle of mass $m$ approaches the stick with speed $v$ on a straight line perpendicular to the stick that intersects the stick at one end, as shown above. After the collision, which is elastic, the particle is at rest. The speed $V$ of the center of mass of the stick after the collision is
>
> (A) $\frac{m}{M}v$
>
> (B) $\frac{m}{M+m}v$
>
> (C) $\sqrt{\frac{m}{M}}v$
>
> (D) $\sqrt{\frac{m}{M+m}}v$
>
> (E) $\frac{3m}{M}v$
>
>
>
My approach was to first write down expressions for the conservation of energy, linear momentum, and angular momentum. The problem states that the particle is at rest after the collision, which simplifies the equations:
$$\frac{1}{2} m v^2 = \frac{1}{2} M V^2 + \frac{1}{2} I \omega^2$$
$$m v = M V$$
$$\frac{1}{2} L m v = I \omega$$
where $I=ML^2/12$ is the moment of inertia of the stick about its CM and $\omega$ is the stick's angular velocity. The most natural next step is to solve the linear momentum equation, giving us the correct answer (A). This is the solution used [here](http://physics-problems-solutions.blogspot.com/2014/04/classical-mechanics-elastic-collision.html) and [here](http://grephysics.net/ans/8677/44).
However, adhering to my penchant for valuing understanding above efficiency, I attempted to verify this answer by combining the other two conservation equations. I solved the angular momentum equation for $\omega$ to obtain $$\omega = \frac{L m v}{2 I}.$$ I then solved the energy equation for $V$ and substituted in this result: $$V^2 = \frac{1}{M}(m v^2 - I \omega^2)$$ $$= \frac{1}{M}\left( m v^2 - I \left( \frac{L m v}{2 I} \right)^2 \right)$$ $$= \frac{1}{M}\left( m v^2 - \frac{(L m v)^2}{4 I} \right)$$ $$= \frac{m v^2}{M}\left( 1 - \frac{L^2 m}{4 (M L^2 / 12)} \right)$$ $$= \frac{m v^2}{M} \left( 1 - 3\frac{m}{M} \right)$$ $$\Longrightarrow V = v \sqrt{ \frac{m}{M} \left( 1 - 3\frac{m}{M} \right) }$$ $$= v \frac{m}{M} \sqrt{ \frac{M}{m} - 3 }$$
I see several problems with this result. First, it does not immediately resemble any of the answers, though it can be made to match either (A) or (E) with a choice of $M/m=4$ or $M/m=12$, respectively. Second, if $M/m < 3$, the velocity of the stick becomes imaginary which (to me) does not have an obvious physical interpretation. I also do not see why there should be any restriction on the mass ratio in the first place.
**Is this approach illegitimate or does it contain an error? If so, why/where? If not, why does the result not coincide with the first approach?**
In the first solution link above, there are many comments going back-and-forth on the reasons for the discrepancy but, frustratingly, no conclusion. Any insights would be greatly appreciated. | 2019/07/31 | [
"https://physics.stackexchange.com/questions/494571",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/237071/"
] | The GRE question seems to be erroneous. You see, if one specifies that the collision is elastic then they cannot also specify what would be the speed of the ball (the mass $m$) after the collision. That over-constraints the problem. That is the reason you are finding inconsistencies in your two ways to approach the problem. Put another way, there are two variables $V$ and $ω$ but there are three equations. So, it is expected that one would find inconsistent solutions.
The correct way to pose the question would be to either delete the word elastic (then the kinetic energy equation goes away and we have two equations for two variables) or to keep the word elastic but do not specify what happens to the ball after the collision (then we will have three variables to solve out of three equations). | What you've done is to find the condition under which an elastic collision can end with the incoming particle at rest. Conservation of momentum with that condition gives $MV=mv$, and conservation of angular momentum fixes $\omega$. If you require energy conservation as well, you find an inconsistency unless $\sqrt{M/m-3}=1$.
This constraint means that, if you did this experiment with $M\neq 4m$ and observed the incoming ball to stop, the collision should have either been inelastic (energy lost to heat, noise, etc.) or super-elastic (energy added from some internal source that isn't specified here). |
494,571 | I am currently studying for the GRE Physics subject test by working through published past tests. My question is about problem 44 from the test GR8677:
>
> [](https://i.stack.imgur.com/DzNMT.png)
>
>
> $44.$ A uniform stick of length $L$ and mass $M$ lies on a frictionless horizontal surface. A point particle of mass $m$ approaches the stick with speed $v$ on a straight line perpendicular to the stick that intersects the stick at one end, as shown above. After the collision, which is elastic, the particle is at rest. The speed $V$ of the center of mass of the stick after the collision is
>
> (A) $\frac{m}{M}v$
>
> (B) $\frac{m}{M+m}v$
>
> (C) $\sqrt{\frac{m}{M}}v$
>
> (D) $\sqrt{\frac{m}{M+m}}v$
>
> (E) $\frac{3m}{M}v$
>
>
>
My approach was to first write down expressions for the conservation of energy, linear momentum, and angular momentum. The problem states that the particle is at rest after the collision, which simplifies the equations:
$$\frac{1}{2} m v^2 = \frac{1}{2} M V^2 + \frac{1}{2} I \omega^2$$
$$m v = M V$$
$$\frac{1}{2} L m v = I \omega$$
where $I=ML^2/12$ is the moment of inertia of the stick about its CM and $\omega$ is the stick's angular velocity. The most natural next step is to solve the linear momentum equation, giving us the correct answer (A). This is the solution used [here](http://physics-problems-solutions.blogspot.com/2014/04/classical-mechanics-elastic-collision.html) and [here](http://grephysics.net/ans/8677/44).
However, adhering to my penchant for valuing understanding above efficiency, I attempted to verify this answer by combining the other two conservation equations. I solved the angular momentum equation for $\omega$ to obtain $$\omega = \frac{L m v}{2 I}.$$ I then solved the energy equation for $V$ and substituted in this result: $$V^2 = \frac{1}{M}(m v^2 - I \omega^2)$$ $$= \frac{1}{M}\left( m v^2 - I \left( \frac{L m v}{2 I} \right)^2 \right)$$ $$= \frac{1}{M}\left( m v^2 - \frac{(L m v)^2}{4 I} \right)$$ $$= \frac{m v^2}{M}\left( 1 - \frac{L^2 m}{4 (M L^2 / 12)} \right)$$ $$= \frac{m v^2}{M} \left( 1 - 3\frac{m}{M} \right)$$ $$\Longrightarrow V = v \sqrt{ \frac{m}{M} \left( 1 - 3\frac{m}{M} \right) }$$ $$= v \frac{m}{M} \sqrt{ \frac{M}{m} - 3 }$$
I see several problems with this result. First, it does not immediately resemble any of the answers, though it can be made to match either (A) or (E) with a choice of $M/m=4$ or $M/m=12$, respectively. Second, if $M/m < 3$, the velocity of the stick becomes imaginary which (to me) does not have an obvious physical interpretation. I also do not see why there should be any restriction on the mass ratio in the first place.
**Is this approach illegitimate or does it contain an error? If so, why/where? If not, why does the result not coincide with the first approach?**
In the first solution link above, there are many comments going back-and-forth on the reasons for the discrepancy but, frustratingly, no conclusion. Any insights would be greatly appreciated. | 2019/07/31 | [
"https://physics.stackexchange.com/questions/494571",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/237071/"
] | The GRE question seems to be erroneous. You see, if one specifies that the collision is elastic then they cannot also specify what would be the speed of the ball (the mass $m$) after the collision. That over-constraints the problem. That is the reason you are finding inconsistencies in your two ways to approach the problem. Put another way, there are two variables $V$ and $ω$ but there are three equations. So, it is expected that one would find inconsistent solutions.
The correct way to pose the question would be to either delete the word elastic (then the kinetic energy equation goes away and we have two equations for two variables) or to keep the word elastic but do not specify what happens to the ball after the collision (then we will have three variables to solve out of three equations). | I think they just want you to ignore irrelevant information. Linear momentum is conserved, so we get
$$V=\frac mMv$$
They threw in the extra information about an elastic collision I guess to throw students off. Unfortunately it leads to an actual contradictory situation. |
494,571 | I am currently studying for the GRE Physics subject test by working through published past tests. My question is about problem 44 from the test GR8677:
>
> [](https://i.stack.imgur.com/DzNMT.png)
>
>
> $44.$ A uniform stick of length $L$ and mass $M$ lies on a frictionless horizontal surface. A point particle of mass $m$ approaches the stick with speed $v$ on a straight line perpendicular to the stick that intersects the stick at one end, as shown above. After the collision, which is elastic, the particle is at rest. The speed $V$ of the center of mass of the stick after the collision is
>
> (A) $\frac{m}{M}v$
>
> (B) $\frac{m}{M+m}v$
>
> (C) $\sqrt{\frac{m}{M}}v$
>
> (D) $\sqrt{\frac{m}{M+m}}v$
>
> (E) $\frac{3m}{M}v$
>
>
>
My approach was to first write down expressions for the conservation of energy, linear momentum, and angular momentum. The problem states that the particle is at rest after the collision, which simplifies the equations:
$$\frac{1}{2} m v^2 = \frac{1}{2} M V^2 + \frac{1}{2} I \omega^2$$
$$m v = M V$$
$$\frac{1}{2} L m v = I \omega$$
where $I=ML^2/12$ is the moment of inertia of the stick about its CM and $\omega$ is the stick's angular velocity. The most natural next step is to solve the linear momentum equation, giving us the correct answer (A). This is the solution used [here](http://physics-problems-solutions.blogspot.com/2014/04/classical-mechanics-elastic-collision.html) and [here](http://grephysics.net/ans/8677/44).
However, adhering to my penchant for valuing understanding above efficiency, I attempted to verify this answer by combining the other two conservation equations. I solved the angular momentum equation for $\omega$ to obtain $$\omega = \frac{L m v}{2 I}.$$ I then solved the energy equation for $V$ and substituted in this result: $$V^2 = \frac{1}{M}(m v^2 - I \omega^2)$$ $$= \frac{1}{M}\left( m v^2 - I \left( \frac{L m v}{2 I} \right)^2 \right)$$ $$= \frac{1}{M}\left( m v^2 - \frac{(L m v)^2}{4 I} \right)$$ $$= \frac{m v^2}{M}\left( 1 - \frac{L^2 m}{4 (M L^2 / 12)} \right)$$ $$= \frac{m v^2}{M} \left( 1 - 3\frac{m}{M} \right)$$ $$\Longrightarrow V = v \sqrt{ \frac{m}{M} \left( 1 - 3\frac{m}{M} \right) }$$ $$= v \frac{m}{M} \sqrt{ \frac{M}{m} - 3 }$$
I see several problems with this result. First, it does not immediately resemble any of the answers, though it can be made to match either (A) or (E) with a choice of $M/m=4$ or $M/m=12$, respectively. Second, if $M/m < 3$, the velocity of the stick becomes imaginary which (to me) does not have an obvious physical interpretation. I also do not see why there should be any restriction on the mass ratio in the first place.
**Is this approach illegitimate or does it contain an error? If so, why/where? If not, why does the result not coincide with the first approach?**
In the first solution link above, there are many comments going back-and-forth on the reasons for the discrepancy but, frustratingly, no conclusion. Any insights would be greatly appreciated. | 2019/07/31 | [
"https://physics.stackexchange.com/questions/494571",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/237071/"
] | What you've done is to find the condition under which an elastic collision can end with the incoming particle at rest. Conservation of momentum with that condition gives $MV=mv$, and conservation of angular momentum fixes $\omega$. If you require energy conservation as well, you find an inconsistency unless $\sqrt{M/m-3}=1$.
This constraint means that, if you did this experiment with $M\neq 4m$ and observed the incoming ball to stop, the collision should have either been inelastic (energy lost to heat, noise, etc.) or super-elastic (energy added from some internal source that isn't specified here). | I think they just want you to ignore irrelevant information. Linear momentum is conserved, so we get
$$V=\frac mMv$$
They threw in the extra information about an elastic collision I guess to throw students off. Unfortunately it leads to an actual contradictory situation. |
59,344,426 | The input can only include two chemical elements: `C` and `H`
The program must control.
How can I provide that?
```
if (formul.Contains('C') == true && formul.Contains('H') == true)
return true;
```
When my input is `HCA` it is still true. I want it only includes `C` and `H`. | 2019/12/15 | [
"https://Stackoverflow.com/questions/59344426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12278081/"
] | ```cs
using System.Linq; \\put this on top
return formul.All(c => c == 'C' || c == 'H');
```
This will return `true` if all characters of `formul` string are either 'C' or 'H' | Chemical formulas (as far as I know) can contain also numbers, so you have to take that into account as well, here is my idea of solving problem:
```
return ! formula.Any(ch => char.IsLetter(ch) && ch != 'C' && ch != 'H');
```
It checks wheter any letter in a formula is different from `C` or `H`. If there's letter other than `C` or `H`, it returns false, true otherwise. |
59,344,426 | The input can only include two chemical elements: `C` and `H`
The program must control.
How can I provide that?
```
if (formul.Contains('C') == true && formul.Contains('H') == true)
return true;
```
When my input is `HCA` it is still true. I want it only includes `C` and `H`. | 2019/12/15 | [
"https://Stackoverflow.com/questions/59344426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12278081/"
] | ```cs
using System.Linq; \\put this on top
return formul.All(c => c == 'C' || c == 'H');
```
This will return `true` if all characters of `formul` string are either 'C' or 'H' | Using LINQ as suggested by @Piotr is fine for something this simple, but in general it is preferable to use Regular Expressions (regexes) for text pattern matching, like this:
```
Regex.IsMatch(input, @"^[CH]+$");
```
This will return `true` if and only if `input` comprises a string of one or more characters, each being 'C' or 'H'.
You can test this here: <https://regex101.com/r/X6pzqa/1/> |
59,344,426 | The input can only include two chemical elements: `C` and `H`
The program must control.
How can I provide that?
```
if (formul.Contains('C') == true && formul.Contains('H') == true)
return true;
```
When my input is `HCA` it is still true. I want it only includes `C` and `H`. | 2019/12/15 | [
"https://Stackoverflow.com/questions/59344426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12278081/"
] | Using LINQ as suggested by @Piotr is fine for something this simple, but in general it is preferable to use Regular Expressions (regexes) for text pattern matching, like this:
```
Regex.IsMatch(input, @"^[CH]+$");
```
This will return `true` if and only if `input` comprises a string of one or more characters, each being 'C' or 'H'.
You can test this here: <https://regex101.com/r/X6pzqa/1/> | Chemical formulas (as far as I know) can contain also numbers, so you have to take that into account as well, here is my idea of solving problem:
```
return ! formula.Any(ch => char.IsLetter(ch) && ch != 'C' && ch != 'H');
```
It checks wheter any letter in a formula is different from `C` or `H`. If there's letter other than `C` or `H`, it returns false, true otherwise. |
12,091 | Concerning "[Uranium-series dating](https://en.wikipedia.org/wiki/Uranium%E2%80%93thorium_dating)", also known as "Uranium-thorium dating".
Uranium is present in deposits, "typically at levels of between a few parts per billion and few parts per million by weight", according to the wikipedia article on the subject.
As an example, with carbon dating, the amount of carbon-14 originally present in any given sample is consistent with the amount of carbon-14 created by the activity of sunlight in the atmosphere.
How do we know how much uranium-234 was in any given sample of rock when it was created/deposited? | 2017/08/15 | [
"https://earthscience.stackexchange.com/questions/12091",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/10777/"
] | The chemistry of lead is very different from that of uranium and thorium. There are key kinds of rock that could not possibly have been formed with even the smallest amount of primordial lead. The lithophilic nature of uranium and thorium means that those same kinds of rock could easily have readily accepted primordial uranium or thorium.
Any lead in those kinds of rocks must necessarily be the result of decay of uranium or thorium after the rock formed. | **Lead and uranium have completely different electro-chemical properties**. So as David mentioned it does not matter how much uranium the sample had (as long as it is enough to measure) what matters is whether it contained any lead when it formed. Uranium and lead do not form the same kinds of bonds with other elements, so what you do is look for a uranium based crystal or uranium incorporating crystal. Crystals have a very regular bonding pattern, so you know when the crystal formed it was uranium and not lead, becasue lead cannot form those types of bonds with the smale materials uranium can. So when you find lead locked in those crystals you know it is because when it crystallized it was uranium and later decayed into lead.
Most samples used are crystals for this reason. We pick materials that could not normally include lead, by doing this you can add up the total amount of lead and uranium and that will tell you how much uranium there was originally. **Zircon** is especially common for this becasue it will readily incorporate uranium but strongly rejects lead, so even if there is lead present in the solution (molten rock) in will not be incorporated into the crystal, because it is actively repelled by the crystal surface, thus insuring any lead you find came after the crystal was already solid and the repulsion could not push it out. |
12,091 | Concerning "[Uranium-series dating](https://en.wikipedia.org/wiki/Uranium%E2%80%93thorium_dating)", also known as "Uranium-thorium dating".
Uranium is present in deposits, "typically at levels of between a few parts per billion and few parts per million by weight", according to the wikipedia article on the subject.
As an example, with carbon dating, the amount of carbon-14 originally present in any given sample is consistent with the amount of carbon-14 created by the activity of sunlight in the atmosphere.
How do we know how much uranium-234 was in any given sample of rock when it was created/deposited? | 2017/08/15 | [
"https://earthscience.stackexchange.com/questions/12091",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/10777/"
] | The field of nuclear physics has established the [radioactive decay](https://en.wikipedia.org/wiki/Radioactive_decay) series for radioactive elements (see [here](https://www.boundless.com/physics/textbooks/boundless-physics-textbook/nuclear-physics-and-radioactivity-30/radioactivity-190/radioactive-decay-series-introduction-708-1301/) as well).
Unlike [Uranium 238](https://en.wikipedia.org/wiki/Uranium-238), [Uranium 234](http://www.nuclear-power.net/nuclear-power-plant/nuclear-fuel/uranium/uranium-234/) is not [primordial nuclide](http://www.nuclear-power.net/glossary/primordial-matter/). It is a indirect decay product of Uranium 238.
By knowing what elements, and their isotopes, are present in rocks and how much of these isotopes are present, combined with the radioactive decay chain it is possible to determine the amount of Uranium 234 that was once present when the rocks formed. | **Lead and uranium have completely different electro-chemical properties**. So as David mentioned it does not matter how much uranium the sample had (as long as it is enough to measure) what matters is whether it contained any lead when it formed. Uranium and lead do not form the same kinds of bonds with other elements, so what you do is look for a uranium based crystal or uranium incorporating crystal. Crystals have a very regular bonding pattern, so you know when the crystal formed it was uranium and not lead, becasue lead cannot form those types of bonds with the smale materials uranium can. So when you find lead locked in those crystals you know it is because when it crystallized it was uranium and later decayed into lead.
Most samples used are crystals for this reason. We pick materials that could not normally include lead, by doing this you can add up the total amount of lead and uranium and that will tell you how much uranium there was originally. **Zircon** is especially common for this becasue it will readily incorporate uranium but strongly rejects lead, so even if there is lead present in the solution (molten rock) in will not be incorporated into the crystal, because it is actively repelled by the crystal surface, thus insuring any lead you find came after the crystal was already solid and the repulsion could not push it out. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | Put all of your "state" data in one place and use a [pickle](http://docs.python.org/library/pickle.html).
>
> The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1](http://docs.python.org/library/pickle.html) or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
>
>
> | If you want to save everything, including the entire namespace and the line of code currently executing to be restarted at any time, there is not a standard library module to do that.
As another poster said, the pickle module can save pretty much everything into a file and then load it again, but you would have to specifically design your program around the pickle module (i.e. saving your "state" -- including variables, etc -- in a class). |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | Put all of your "state" data in one place and use a [pickle](http://docs.python.org/library/pickle.html).
>
> The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1](http://docs.python.org/library/pickle.html) or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
>
>
> | If you ok with OOP, consider creating a method for each class that output a serialised version ( using pickle ) to file. Then add a second method to load in the instance the data, and if the pickled file is there you call the load method instead of the processing one.
I use this approach for ML and it really seed up my workflow. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | Put all of your "state" data in one place and use a [pickle](http://docs.python.org/library/pickle.html).
>
> The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1](http://docs.python.org/library/pickle.html) or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
>
>
> | In the traditional programming approach the obvious way to save a state of variables or objects after some point of execution is serialization.
So if you want to execute the program after some heavy already computed state we need to start only from the deserialization part.
These steps will be mostly needed mostly in data science modelling where we load a huge CSV or some other data and compute it and we do not want to recompute every time we run a program.
<http://jupyter.org/> - A tool which does these serialization/deserialization automatically without you doing any manual work.
All you need to do is do execute a selected portion of your python code let us say line 10-15, which are dependent on pervious lines 1-9. Jupyter saves the state of 1-9 for you. Explore a tutorial it and give it a try. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | If you want to save everything, including the entire namespace and the line of code currently executing to be restarted at any time, there is not a standard library module to do that.
As another poster said, the pickle module can save pretty much everything into a file and then load it again, but you would have to specifically design your program around the pickle module (i.e. saving your "state" -- including variables, etc -- in a class). | If you ok with OOP, consider creating a method for each class that output a serialised version ( using pickle ) to file. Then add a second method to load in the instance the data, and if the pickled file is there you call the load method instead of the processing one.
I use this approach for ML and it really seed up my workflow. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | If you want to save everything, including the entire namespace and the line of code currently executing to be restarted at any time, there is not a standard library module to do that.
As another poster said, the pickle module can save pretty much everything into a file and then load it again, but you would have to specifically design your program around the pickle module (i.e. saving your "state" -- including variables, etc -- in a class). | In the traditional programming approach the obvious way to save a state of variables or objects after some point of execution is serialization.
So if you want to execute the program after some heavy already computed state we need to start only from the deserialization part.
These steps will be mostly needed mostly in data science modelling where we load a huge CSV or some other data and compute it and we do not want to recompute every time we run a program.
<http://jupyter.org/> - A tool which does these serialization/deserialization automatically without you doing any manual work.
All you need to do is do execute a selected portion of your python code let us say line 10-15, which are dependent on pervious lines 1-9. Jupyter saves the state of 1-9 for you. Explore a tutorial it and give it a try. |
5,568,904 | I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting? | 2011/04/06 | [
"https://Stackoverflow.com/questions/5568904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619962/"
] | If you ok with OOP, consider creating a method for each class that output a serialised version ( using pickle ) to file. Then add a second method to load in the instance the data, and if the pickled file is there you call the load method instead of the processing one.
I use this approach for ML and it really seed up my workflow. | In the traditional programming approach the obvious way to save a state of variables or objects after some point of execution is serialization.
So if you want to execute the program after some heavy already computed state we need to start only from the deserialization part.
These steps will be mostly needed mostly in data science modelling where we load a huge CSV or some other data and compute it and we do not want to recompute every time we run a program.
<http://jupyter.org/> - A tool which does these serialization/deserialization automatically without you doing any manual work.
All you need to do is do execute a selected portion of your python code let us say line 10-15, which are dependent on pervious lines 1-9. Jupyter saves the state of 1-9 for you. Explore a tutorial it and give it a try. |
54,186,894 | We are using .NET Core 2.1 and Entity Framework Core 2.1.1
I have the following setup in Azure West Europe
* Azure SQL Database
-- Premium P2 250 DTU
-- Public endpoint, no VNET peering
-- "Allow access to Azure Services" = ON
* Azure Functions
-- Consumption Plan
-- Timeout 10 Minutes
* Azure Blob storage
-- hot tier
Multiple blobs are uploaded to Azure Blob storage, Azure Functions (up to 5 concurrently) are fired via Azure Event Grid. Azure Functions check structure of the blobs against metadata stored in Azure SQL DB. Each blob contains up to 500K records and 5 columns of payload data. For each record Azure Functions makes a call against Azure SQL DB, so no caching.
I am getting often, when multiple blobs are processed in parallel (up to 5 asynchronous Azure Functions call at the same time), and when the blob size is larger 200K-500K records, the following transient and connection errors from .NET Core Entity Framework:
1.
An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
2.
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)
3.
Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. This failure occurred while attempting to connect to the routing destination. The duration spent while attempting to connect to the original server was - [Pre-Login] initialization=13633; handshake=535; [Login] initialization=1; authentication=0; [Post-Login] complete=156; The duration spent while attempting to connect to this server was - [Pre-Login] initialization=5679; handshake=2044;
4.
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)
5. Server provided routing information, but timeout already expired.
At the same time there are any/no health events reported for the Azure SQL Database during the test, and the metrics look awesome: MAX Workers < 3.5%, Sum Successful Connections < 35, MAX Sessions Percentage < 0.045%, Max Log UI percentage < 0.024%, Sum Failed Connections = 0, MAX DTU < 10%, Max Data IO < 0.055%, MAX CPU < 10%.
Running connection stats on Azure SQL DB (sys.database\_connection\_stats\_ex): No failed, aborted or throttled connections.
```
select *
from sys.database_connection_stats_ex
where start_time >= CAST(FLOOR(CAST(getdate() AS float)) AS DATETIME)
order by start_time desc
```
Has anyone faced similar issues in combintation with .Net Core Entity Framework and Azure SQL Database. Why I am getting those transient errors, why Azure SQL Database metrics look so good not reflecting at all that there are issues?
Thanks a lot in advance for any help.
```
using Microsoft.EntityFrameworkCore;
namespace MyProject.Domain.Data
{
public sealed class ApplicationDbContextFactory : IApplicationDbContextFactory
{
private readonly IConfigurationDbConfiguration _configuration;
private readonly IDateTimeService _dateTimeService;
public ApplicationDbContextFactory(IConfigurationDbConfiguration configuration, IDateTimeService dateTimeService)
{
_configuration = configuration;
_dateTimeService = dateTimeService;
}
public ApplicationDbContext Create()
{
//Not initialized in ctor due to unit testing static functions.
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(_configuration.ConfigurationDbConnectionString).Options;
return new ApplicationDbContext(options, _dateTimeService);
}
}
}
``` | 2019/01/14 | [
"https://Stackoverflow.com/questions/54186894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10871024/"
] | I've found this good documentation around sql database transient errors:
* [Working with SQL Database connection issues and transient errors](https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connectivity-issues)
From the documentation:
>
> A transient error has an underlying cause that soon resolves itself. An occasional cause of transient errors is when the Azure system quickly shifts hardware resources to better load-balance various workloads. Most of these reconfiguration events finish in less than 60 seconds. During this reconfiguration time span, you might have connectivity issues to SQL Database. Applications that connect to SQL Database should be built to expect these transient errors. To handle them, implement retry logic in their code instead of surfacing them to users as application errors.
>
>
>
Then it explains in details how to build retry logic for transient errors.
Entity Framework with SQL server implements a retry logic:
```
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer("<connection string>", options => options.EnableRetryOnFailure());
}
```
You can find more information here:
* [EF Core - Connection Resiliency](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency) | Remove and recreate database user and make sure to fill Login Name box just below the User Name. This will fix same issue on older SQL versions too. |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | In Theravada Buddhism, when we talk about conditions and conditioning there are 24 conditions found in the [Patthana](http://sanskritdocuments.org/articles/Notes_on_PATTHANA_DHAMMA.pdf)
The Patthana Dhamma are packed into 24 Paccaya or 24 conditions.
They are:
1.Root condition ( Hetu Paccayo )
2.Object condition ( Arammana Paccayo )
3.Predominance condition ( Adhipati Paccayo )
4.Proximity condition ( Anantara Paccayo )... etc... | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. | I see two ambiguities here which might be the responsible for the confusion.
>
> with the six sense bases as condition, contact;
>
>
> -- SN 12:1
>
>
>
The above is one link of conditioned arising chain, which explain how many things are conditioned. Would it be correct to, according to the above, conclude that the six senses *cause* (or produce) contact? That would be awkward.
This quote means that if a "contact experience" is present, then the corresponding sense is present. A more verbose reading of the above would be "six sense bases are a supporting condition for contact".
As another (unrelated to buddhism, and perhaps poorly chosen) example, if you study, you become more knowledgeable. But your knowledge, at any given point, is not constituted by "studies". There is an ambiguity in how we can interpret "conditioned". Conditioned ≠ caused by.
The matter in question is that it is more a statement about a ["necessary condition"](https://en.wikipedia.org/wiki/Necessity_and_sufficiency) than a statement about a particular cause.
There is also another ambiguity in play here. Nibbāna is unconditioned in the sense that **it** has no supporting condition. Echoing [yuttadhammo's answer](https://buddhism.stackexchange.com/a/9083/382), nibbāna is "one thing" and the experience of attaining nibbāna (which requires all the proverbial effort) is "something else". |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | No, the practices are causes of the unconditional result of Nibbana. Things in the past or future do not even exist to ultimate reality. We can't understand this without practicing virtue and witnessing what really is in the present moment(mindfulness or Vipassana) moment by moment | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. | In the material world alls phenomena arises and passes based on conditionality (as opposed to totally random). In Nibbana there is no arising and passing away of phenomena.
It is true that realising Nibbana is the result of practising the path to realise it, hence if you have realised Nibbana then this is because you practice the path. |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. | When it says that "Anicca vata sankhara" ( Impermanent are all conditioned things). "Uppadavaya dhammino" ( Of the nature to rise and fall).
It is saying that things arise dependent on conditions, things "exist" because of the conditions that support them. So we are talking about characteristic nature of things or its attribute.
The attributes of nibbana as pointed out above is permanent, does not arise depending on conditions. |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | In the material world alls phenomena arises and passes based on conditionality (as opposed to totally random). In Nibbana there is no arising and passing away of phenomena.
It is true that realising Nibbana is the result of practising the path to realise it, hence if you have realised Nibbana then this is because you practice the path. | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | When it says that "Anicca vata sankhara" ( Impermanent are all conditioned things). "Uppadavaya dhammino" ( Of the nature to rise and fall).
It is saying that things arise dependent on conditions, things "exist" because of the conditions that support them. So we are talking about characteristic nature of things or its attribute.
The attributes of nibbana as pointed out above is permanent, does not arise depending on conditions. | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | The practice of the eightfold noble path leads to the *experience* of nibbāna, just like the act of adverting the mind to the eye door leads to seeing light. Light, the object of seeing, is saṅkhata (conditioned), but nibbāna, the object of supermundane consciousness, is asaṅkhata (unconditioned). So nibbāna isn't the result of the eightfold noble path, the experience of it is. | Nibbana as stated in the [Patthana](http://wisdomlib.org/buddhism/book/patthana-dhamma/d/doc1829.html) with my summary below:
* `[]` square brackets indicate my extra notes
* `*` asterisk indicates I've changed to the English rendering according to Nyanamoli as it appeals to me to be a closer rendering, otherwise it is straight from the Patthana.
>
> Nibbana the term derives from nivana or nirvana. Ni means nikkhanta or liberated from vana or binding. Vana is the dhamma that bind various different lives in the samsara. So nibbana means liberated from binding in the samsara. This binding is tanha. [Thanissaro Bhikkhu uses unbinding in most of his translation instead of using nibbana]
>
>
> From view point of contemplation [at the time of release], there are three kinds of nibbana.
> They are sunnata nibbana [\*emptiness - attained thru seeing anatta],
> animitta nibbana [\*signless - attained thru seeing anicca],
> and appanihita nibbana [\*desireless - attained thru seeing dukkha]
>
>
>
All 3 are just one same nibbana perceived through different modes of release.
Nibbana is not in one of the 5 aggregates, [it is there all the time but we don't have the mental capacity to see it]. It can be an object of the mind (arammana).
Who can see nibbana? Arahants, and Anagamis only when he enters (\*the state of ceasation of consciousness) nirodha samapatti.
[Sotapanas, Sakadagamis and Anagamis only have a glimps of nibbana]
>
> Sankhata dhatu [\*conditioned elements] are those whose arising and existence are influenced by one of four causes namely kamma [\*action], citta [\*consciousness], utu [\*climate], and ahara [\*nutriment]. Nibbana cannot be influenced by these four causes. Nibbana is asankhata dhatu [\*unconditioned element].
>
>
> |
9,073 | It is often said that Nibbana is unconditioned. But isn't Nibbana to be attained through practice of the Noble Eightfold Path (abandoning desire, meditation, realizing paticcasamuppada etc)? Aren't those practices conditions for Nibbana? What am I missing here :) ? | 2015/05/18 | [
"https://buddhism.stackexchange.com/questions/9073",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/125/"
] | Nibbana as stated in the [Patthana](http://wisdomlib.org/buddhism/book/patthana-dhamma/d/doc1829.html) with my summary below:
* `[]` square brackets indicate my extra notes
* `*` asterisk indicates I've changed to the English rendering according to Nyanamoli as it appeals to me to be a closer rendering, otherwise it is straight from the Patthana.
>
> Nibbana the term derives from nivana or nirvana. Ni means nikkhanta or liberated from vana or binding. Vana is the dhamma that bind various different lives in the samsara. So nibbana means liberated from binding in the samsara. This binding is tanha. [Thanissaro Bhikkhu uses unbinding in most of his translation instead of using nibbana]
>
>
> From view point of contemplation [at the time of release], there are three kinds of nibbana.
> They are sunnata nibbana [\*emptiness - attained thru seeing anatta],
> animitta nibbana [\*signless - attained thru seeing anicca],
> and appanihita nibbana [\*desireless - attained thru seeing dukkha]
>
>
>
All 3 are just one same nibbana perceived through different modes of release.
Nibbana is not in one of the 5 aggregates, [it is there all the time but we don't have the mental capacity to see it]. It can be an object of the mind (arammana).
Who can see nibbana? Arahants, and Anagamis only when he enters (\*the state of ceasation of consciousness) nirodha samapatti.
[Sotapanas, Sakadagamis and Anagamis only have a glimps of nibbana]
>
> Sankhata dhatu [\*conditioned elements] are those whose arising and existence are influenced by one of four causes namely kamma [\*action], citta [\*consciousness], utu [\*climate], and ahara [\*nutriment]. Nibbana cannot be influenced by these four causes. Nibbana is asankhata dhatu [\*unconditioned element].
>
>
> | I do not have sufficent knowledge to answer the question in a satisfactory way.
So i will instead point you to some great ressources regarding your question.
The first one is a book called [*"On the Nature of Nibbana"*](http://www.saraniya.com/books/mahasi-sayadaw/pdf/mahasi_sayadaw-1964_on_the_nature_of_nibbana.pdf) by Ven. Mahasi Sayadaw.
In this book Nibbana is being discussed e.g. *"What is Nibbana and what is the meaning of it?, Mental Formation and Nibbana, The Nature and Attributes of Nibbana and many more things regarding Nibbana"*.
The second source is a great audio dhamma talk called [*"Nibbana"*](https://www.youtube.com/watch?v=IBNMqqmZI6E) by Ven. Bhikkhu Bodhi.
Here is also some text material on *Nibbana* by Ven. Bhikkhu Bodhi. A short quote from the section [*"Nibbana is an existing reality"*](http://www.beyondthenet.net/dhamma/nibbanaReal.htm):
>
> "Regarding the nature of Nibbana, the question is often asked: Does Nibbana signify only extinction of the defilements and liberation from samsara or does it signify some reality existing in itself? Nibbana is not only the destruction of defilements and the end of samsara but a reality transcendent to the entire world of mundane experience, a reality transcendent to all the realms of phenomenal existence.
>
>
> The Buddha refers to Nibbana as a 'dhamma'. For example, he says "of all dhammas, conditioned or unconditioned, the most excellent dhamma, the supreme dhamma is, Nibbana". 'Dhamma' signifies actual realities, the existing realities as opposed to conceptual things. Dhammas are of two types, conditioned and unconditioned. A conditioned dhamma is an actuality which has come into being through causes or conditions, something which arises through the workings of various conditions. The conditioned dhammas are the five aggregates: material form, feeling, perception, mental formations and consciousness. The conditioned dhammas, do not remain static. They go through a ceaseless process of becoming. They arise, undergo transformation and fall away due to its conditionality.
>
>
> However, the unconditioned dhamma is not produced by causes and conditions. It has the opposite characteristics from the conditioned: it has no arising, no falling away and it undergoes no transformation. Nevertheless, it is an actuality, and the Buddha refers to Nibbana as an unconditioned Dhamma."
>
>
>
May this be of some help to you.
Lanka |
132,551 | I have a Ubuntu 9.10 server. I have installed apache2 and php5 using the apt-get commands.
How does one install php extensions? Are there commands like apt-get to get them? Or should I manually look for the files on the php website and set them up in the php.ini?
More specifically, I need mcrypt, curl and gd.
Thanks | 2010/04/15 | [
"https://serverfault.com/questions/132551",
"https://serverfault.com",
"https://serverfault.com/users/24213/"
] | All you need to do is:
```
sudo apt-get install php5-mcrypt php5-curl php5-gd
```
If you need to check what is installed php-wise you can:
```
dpkg --list | grep php
```
EDIT: Removed sudo in the command above as it's not needed with dpkg --list. | Additionally, you can review the available PHP extensions on your Debian/Ubuntu system by:
```
apt-cache search php|egrep ^php5-
``` |
7,924,782 | I'm searching for following issue i have.
The class file names of our project are named logon.class.php
But the interface file for that class is named logon.interface.php
My issue i have is that when the autoload method runs I should be able to detect if it is a class call or an interface call.
```
<?php
function __autoload($name){
if($name === is_class){
include_once($name.'class.php');
}elseif ($name === is_interface){
include_once($name.'interface.php');
}
}
?>
``` | 2011/10/28 | [
"https://Stackoverflow.com/questions/7924782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896201/"
] | You can use [ReflectionClass::isInterface](http://au.php.net/manual/en/reflectionclass.isinterface.php) to determine if the class is an interface.
```
$reflection = new ReflectionClass($name);
if ($reflection->isInterface()){
//Is an interface
}else{
//Not an interface
}
```
In your case, you would probably have to use `file_exist` first on `$name.interface.php` and `$name.class.php` to determine if they exist, require the one that exists, then check if it's an interface.
However, my opinion is that this might cause problems down the track. What if you have `MyClass.class.php` and `MyClass.interface.php`? | You should have some naming conventions for your classes and interfaces e.g. your class name is `logon` and interface name `logon_interface`, then you can easily differentiate between the two. For example, explode `$name` by underscore and check if last element is `interface`. |
7,924,782 | I'm searching for following issue i have.
The class file names of our project are named logon.class.php
But the interface file for that class is named logon.interface.php
My issue i have is that when the autoload method runs I should be able to detect if it is a class call or an interface call.
```
<?php
function __autoload($name){
if($name === is_class){
include_once($name.'class.php');
}elseif ($name === is_interface){
include_once($name.'interface.php');
}
}
?>
``` | 2011/10/28 | [
"https://Stackoverflow.com/questions/7924782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896201/"
] | You can use [ReflectionClass::isInterface](http://au.php.net/manual/en/reflectionclass.isinterface.php) to determine if the class is an interface.
```
$reflection = new ReflectionClass($name);
if ($reflection->isInterface()){
//Is an interface
}else{
//Not an interface
}
```
In your case, you would probably have to use `file_exist` first on `$name.interface.php` and `$name.class.php` to determine if they exist, require the one that exists, then check if it's an interface.
However, my opinion is that this might cause problems down the track. What if you have `MyClass.class.php` and `MyClass.interface.php`? | To avoid class name clashes you can use namespaces. Check The PSR-0 specifications.
Also check this [post](https://stackoverflow.com/questions/928928/determining-what-classes-are-defined-in-a-php-class-file/11114724#11114724). If you read the contents of the file before including it, you can tokenize it and figure if the file contains an Interface or a class, without actually loading the class/interface. Keep in mind that interfaces and classes can't have the same name
Note: Using this method you can actually change the name of the interface at runtime (before loading the class, although that does seem very good practice) |
27,863,830 | Is there a way using `CSS3` or `javascript` to highlight a table row containing 2 elements where each table element is highlighted a different background color upon hovering over that row?
So for example you have a table row with two values like
```
1.45 | 2.56
```
and the table element containing `1.45` would have a blue background and element containing `2.56` would be red.
At the moment I have it so it changes the background color for the entire row like so:
```
.graph-table tbody > tr:hover {
background-color: #6ab1b0;
}
``` | 2015/01/09 | [
"https://Stackoverflow.com/questions/27863830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3922295/"
] | Use [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-ch) selector, like this:
```css
td {
padding: 15px;
}
tr:hover td {
background-color: red;
color: white;
cursor:pointer;
}
tr:hover td:nth-child(1) {
background-color: blue;
}
```
```html
<table>
<tr>
<td>2.00</td>
<td>3.45</td>
</tr>
</table>
``` | you can use `:nth-of-type()` like so:
```
tr td:nth-of-type(1):hover{
background: red;
}
tr td:nth-of-type(2):hover{
background: blue;
}
```
[**EXAMPLE 1**](http://jsfiddle.net/wetLy72h/1/)
And by targeting the `td` as a descendant of `tr` you can assure that it works on multiple rows:
[**EXAMPLE 2**](http://jsfiddle.net/wetLy72h/2/) |
27,863,830 | Is there a way using `CSS3` or `javascript` to highlight a table row containing 2 elements where each table element is highlighted a different background color upon hovering over that row?
So for example you have a table row with two values like
```
1.45 | 2.56
```
and the table element containing `1.45` would have a blue background and element containing `2.56` would be red.
At the moment I have it so it changes the background color for the entire row like so:
```
.graph-table tbody > tr:hover {
background-color: #6ab1b0;
}
``` | 2015/01/09 | [
"https://Stackoverflow.com/questions/27863830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3922295/"
] | Use [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-ch) selector, like this:
```css
td {
padding: 15px;
}
tr:hover td {
background-color: red;
color: white;
cursor:pointer;
}
tr:hover td:nth-child(1) {
background-color: blue;
}
```
```html
<table>
<tr>
<td>2.00</td>
<td>3.45</td>
</tr>
</table>
``` | :nth-child(even){background-color: #ffd800;}
or
:nth-child(odd) |
1,317,256 | I'm trying to learn BNF and attempting to assemble some Z80 ASM code. Since I'm new to both fields, my question is, am I even on the right track? I am trying to write the format of Z80 ASM as EBNF so that I can then figure out where to go from there to create machine code from the source. At the moment I have the following:
```
Assignment = Identifier, ":" ;
Instruction = Opcode, [ Operand ], [ Operand ] ;
Operand = Identifier | Something* ;
Something* = "(" , Identifier, ")" ;
Identifier = Alpha, { Numeric | Alpha } ;
Opcode = Alpha, Alpha ;
Int = [ "-" ], Numeric, { Numeric } ;
Alpha = "A" | "B" | "C" | "D" | "E" | "F" |
"G" | "H" | "I" | "J" | "K" | "L" |
"M" | "N" | "O" | "P" | "Q" | "R" |
"S" | "T" | "U" | "V" | "W" | "X" |
"Y" | "Z" ;
Numeric = "0" | "1" | "2" | "3"| "4" |
"5" | "6" | "7" | "8" | "9" ;
```
Any directional feedback if I am going wrong would be excellent. | 2009/08/22 | [
"https://Stackoverflow.com/questions/1317256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385364/"
] | Old-school assemblers were typically hand-coded in assembler and used adhoc parsing techniques to process assembly source lines to produce actual assembler code.
When assembler syntax is simple (e.g. always OPCODE REG, OPERAND) this worked well enough.
Modern machines have messy, nasty instruction sets with lots of instruction variations and operands, which may be expressed with complex syntax allowing multiple index registers to participate in the operand expression. Allowing sophisticated assembly-time expressions with fixed and relocatable constants with various types of addition operators complicates this. Sophisticated assemblers allowing conditional compilation, macros, structured data declarations, etc. all add new demands on syntax. Processing all this syntax by ad hoc methods is very hard and is the reason that parser generators were invented.
Using a BNF and a parser generator is very reasonable way to build a modern assembler, even for a legacy processor such as the Z80. I have built such assemblers for Motorola 8 bit machines such as the 6800/6809, and am getting ready to do the same for a modern x86. I think you're headed down exactly the right path.
\*\*\*\*\*\*\*\*\*\* EDIT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
The OP asked for example lexer and parser definitions.
I've provided both here.
These are excerpts from real specifications for a 6809 asssembler.
The complete definitions are 2-3x the size of the samples here.
To keep space down, I have edited out much of the dark-corner complexity
which is the point of these definitions.
One might be dismayed by the apparant complexity; the
point is that with such definitions, you are trying to *describe* the
shape of the language, not code it procedurally.
You will pay a significantly higher complexity if you
code all this in an ad hoc manner, and it will be far
less maintainable.
It will also be of some help to know that these definitions
are used with a high-end program analysis system that
has lexing/parsing tools as subsystems, called the
[The DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html). DMS will automatically build ASTs from the
grammar rules in the parser specfication, which makes it a
lot easier to buid parsing tools. Lastly,
the parser specification contains so-called "prettyprinter"
declarations, which allows DMS to regenreate source text from the ASTs.
(The real purpose of the grammer was to allow us to build ASTs representing assembler
instructions, and then spit them out to be fed to a real assembler!)
One thing of note: how lexemes and grammar rules are stated (the metasyntxax!)
varies somewhat between different lexer/parser generator systems. The
syntax of DMS-based specifications is no exception. DMS has relatively sophisticated
grammar rules of its own, that really aren't practical to explain in the space available here. You'll have to live with idea that other systems use similar notations, for
EBNF for rules and and regular expression variants for lexemes.
Given the OP's interests, he can implement similar lexer/parsers
with any lexer/parser generator tool, e.g., FLEX/YACC,
JAVACC, ANTLR, ...
\*\*\*\*\*\*\*\*\*\* LEXER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.lex: Lexical Description for M6809
-- Copyright (C) 1989,1999-2002 Ira D. Baxter
%%
#mainmode Label
#macro digit "[0-9]"
#macro hexadecimaldigit "<digit>|[a-fA-F]"
#macro comment_body_character "[\u0009 \u0020-\u007E]" -- does not include NEWLINE
#macro blank "[\u0000 \ \u0009]"
#macro hblanks "<blank>+"
#macro newline "\u000d \u000a? \u000c? | \u000a \u000c?" -- form feed allowed only after newline
#macro bare_semicolon_comment "\; <comment_body_character>* "
#macro bare_asterisk_comment "\* <comment_body_character>* "
...[snip]
#macro hexadecimal_digit "<digit> | [a-fA-F]"
#macro binary_digit "[01]"
#macro squoted_character "\' [\u0021-\u007E]"
#macro string_character "[\u0009 \u0020-\u007E]"
%%Label -- (First mode) processes left hand side of line: labels, opcodes, etc.
#skip "(<blank>*<newline>)+"
#skip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
#precomment "<comment_line><newline>"
#preskip "(<blank>*<newline>)+"
#preskip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
-- Note that an apparant register name is accepted as a label in this mode
#token LABEL [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoLabelList ?)
>>
%%OpcodeField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Opcode field tokens
#token 'ABA' "[aA][bB][aA]"
<< (GotoEOLComment ?) >>
#token 'ABX' "[aA][bB][xX]"
<< (GotoEOLComment ?) >>
#token 'ADC' "[aA][dD][cC]"
<< (GotoABregister ?) >>
#token 'ADCA' "[aA][dD][cC][aA]"
<< (GotoOperand ?) >>
#token 'ADCB' "[aA][dD][cC][bB]"
<< (GotoOperand ?) >>
#token 'ADCD' "[aA][dD][cC][dD]"
<< (GotoOperand ?) >>
#token 'ADD' "[aA][dD][dD]"
<< (GotoABregister ?) >>
#token 'ADDA' "[aA][dD][dD][aA]"
<< (GotoOperand ?) >>
#token 'ADDB' "[aA][dD][dD][bB]"
<< (GotoOperand ?) >>
#token 'ADDD' "[aA][dD][dD][dD]"
<< (GotoOperand ?) >>
#token 'AND' "[aA][nN][dD]"
<< (GotoABregister ?) >>
#token 'ANDA' "[aA][nN][dD][aA]"
<< (GotoOperand ?) >>
#token 'ANDB' "[aA][nN][dD][bB]"
<< (GotoOperand ?) >>
#token 'ANDCC' "[aA][nN][dD][cC][cC]"
<< (GotoRegister ?) >>
...[long list of opcodes snipped]
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoOperandField ?)
>>
#token '#' "\#" -- special constant introduction (FDB)
<< (GotoDataField ?) >>
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token CHARACTER [CHARACTER] "<squoted_character>"
<< (= ?:Lexeme:Literal:Character:Value (TokenStringCharacter ? 2))
(= ?:Lexeme:Literal:Character:Format (LiteralFormat:MakeCompactCharacterLiteralFormat 0 0)) ; nothing special about character
(GotoOperandField ?)
>>
%%OperandField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Tokens signalling switch to index register modes
#token ',' "\,"
<<(GotoRegisterField ?)>>
#token '[' "\["
<<(GotoRegisterField ?)>>
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '//' "\/\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '</' "\<\/"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>/' "\>\/"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
-- Notice that an apparent register is accepted as a label in this mode
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
>>
%%Register -- operand field for TFR, ANDCC, ORCC, EXG opcodes
#skip "<hblanks>"
#ifnotoken << (GotoRegisterField ?) >>
%%RegisterField -- handles registers and indexing mode syntax
-- In this mode, names that look like registers are recognized as registers
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
#token '[' "\["
#token ']' "\]"
#token '--' "\-\-"
#token '++' "\+\+"
#token 'A' "[aA]"
#token 'B' "[bB]"
#token 'CC' "[cC][cC]"
#token 'DP' "[dD][pP] | [dD][pP][rR]" -- DPR shouldnt be needed, but found one instance
#token 'D' "[dD]"
#token 'Z' "[zZ]"
-- Index register designations
#token 'X' "[xX]"
#token 'Y' "[yY]"
#token 'U' "[uU]"
#token 'S' "[sS]"
#token 'PCR' "[pP][cC][rR]"
#token 'PC' "[pP][cC]"
#token ',' "\,"
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '<|' "\<\|"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>|' "\>\|"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
... [snip]
%% -- end M6809.lex
```
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* PARSER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.ATG: Motorola 6809 assembly code parser
-- (C) Copyright 1989;1999-2002 Ira D. Baxter; All Rights Reserved
m6809 = sourcelines ;
sourcelines = ;
sourcelines = sourcelines sourceline EOL ;
<<PrettyPrinter>>: { V(CV(sourcelines[1]),H(sourceline,A<eol>(EOL))); }
-- leading opcode field symbol should be treated as keyword.
sourceline = ;
sourceline = labels ;
sourceline = optional_labels 'EQU' expression ;
<<PrettyPrinter>>: { H(optional_labels,A<opcode>('EQU'),A<operand>(expression)); }
sourceline = LABEL 'SET' expression ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),A<opcode>('SET'),A<operand>(expression)); }
sourceline = optional_label instruction ;
<<PrettyPrinter>>: { H(optional_label,instruction); }
sourceline = optional_label optlabelleddirective ;
<<PrettyPrinter>>: { H(optional_label,optlabelleddirective); }
sourceline = optional_label implicitdatadirective ;
<<PrettyPrinter>>: { H(optional_label,implicitdatadirective); }
sourceline = unlabelleddirective ;
sourceline = '?ERROR' ;
<<PrettyPrinter>>: { A<opcode>('?ERROR'); }
optional_label = labels ;
optional_label = LABEL ':' ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),':'); }
optional_label = ;
optional_labels = ;
optional_labels = labels ;
labels = LABEL ;
<<PrettyPrinter>>: { A<firstlabel>(LABEL); }
labels = labels ',' LABEL ;
<<PrettyPrinter>>: { H(labels[1],',',A<otherlabels>(LABEL)); }
unlabelleddirective = 'END' ;
<<PrettyPrinter>>: { A<opcode>('END'); }
unlabelleddirective = 'END' expression ;
<<PrettyPrinter>>: { H(A<opcode>('END'),A<operand>(expression)); }
unlabelleddirective = 'IF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFDEF' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFDEF'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFUND' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFUND'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'INCLUDE' FILENAME ;
<<PrettyPrinter>>: { H(A<opcode>('INCLUDE'),A<operand>(FILENAME)); }
unlabelleddirective = 'LIST' expression ;
<<PrettyPrinter>>: { H(A<opcode>('LIST'),A<operand>(expression)); }
unlabelleddirective = 'NAME' IDENTIFIER ;
<<PrettyPrinter>>: { H(A<opcode>('NAME'),A<operand>(IDENTIFIER)); }
unlabelleddirective = 'ORG' expression ;
<<PrettyPrinter>>: { H(A<opcode>('ORG'),A<operand>(expression)); }
unlabelleddirective = 'PAGE' ;
<<PrettyPrinter>>: { A<opcode>('PAGE'); }
unlabelleddirective = 'PAGE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('PAGE'),A<operand>(HEADING)); }
unlabelleddirective = 'PCA' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCA'),A<operand>(expression)); }
unlabelleddirective = 'PCC' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCC'),A<operand>(expression)); }
unlabelleddirective = 'PSR' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PSR'),A<operand>(expression)); }
unlabelleddirective = 'TABS' numberlist ;
<<PrettyPrinter>>: { H(A<opcode>('TABS'),A<operand>(numberlist)); }
unlabelleddirective = 'TITLE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('TITLE'),A<operand>(HEADING)); }
unlabelleddirective = 'WITH' settings ;
<<PrettyPrinter>>: { H(A<opcode>('WITH'),A<operand>(settings)); }
settings = setting ;
settings = settings ',' setting ;
<<PrettyPrinter>>: { H*; }
setting = 'WI' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'DE' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'M6800' ;
setting = 'M6801' ;
setting = 'M6809' ;
setting = 'M6811' ;
-- collects lines of conditional code into blocks
conditional = 'ELSEIF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSEIF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional[1])); }
conditional = 'ELSE' EOL else ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSE'),A<eol>(EOL)),CV(else)); }
conditional = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
conditional = sourceline EOL conditional ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(conditional[1])); }
else = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
else = sourceline EOL else ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(else[1])); }
-- keyword-less directive, generates data tables
implicitdatadirective = implicitdatadirective ',' implicitdataitem ;
<<PrettyPrinter>>: { H*; }
implicitdatadirective = implicitdataitem ;
implicitdataitem = '#' expression ;
<<PrettyPrinter>>: { A<operand>(H('#',expression)); }
implicitdataitem = '+' expression ;
<<PrettyPrinter>>: { A<operand>(H('+',expression)); }
implicitdataitem = '-' expression ;
<<PrettyPrinter>>: { A<operand>(H('-',expression)); }
implicitdataitem = expression ;
<<PrettyPrinter>>: { A<operand>(expression); }
implicitdataitem = STRING ;
<<PrettyPrinter>>: { A<operand>(STRING); }
-- instructions valid for m680C (see Software Dynamics ASM manual)
instruction = 'ABA' ;
<<PrettyPrinter>>: { A<opcode>('ABA'); }
instruction = 'ABX' ;
<<PrettyPrinter>>: { A<opcode>('ABX'); }
instruction = 'ADC' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','A')),A<operand>(operandfetch)); }
instruction = 'ADC' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','B')),A<operand>(operandfetch)); }
instruction = 'ADCA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCA'),A<operand>(operandfetch)); }
instruction = 'ADCB' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCB'),A<operand>(operandfetch)); }
instruction = 'ADCD' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCD'),A<operand>(operandfetch)); }
instruction = 'ADD' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','A')),A<operand>(operandfetch)); }
instruction = 'ADD' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','B')),A<operand>(operandfetch)); }
instruction = 'ADDA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADDA'),A<operand>(operandfetch)); }
[..snip...]
-- condition code mask for ANDCC and ORCC
conditionmask = '#' expression ;
<<PrettyPrinter>>: { H*; }
conditionmask = expression ;
target = expression ;
operandfetch = '#' expression ; --immediate
<<PrettyPrinter>>: { H*; }
operandfetch = memoryreference ;
operandstore = memoryreference ;
memoryreference = '[' indexedreference ']' ;
<<PrettyPrinter>>: { H*; }
memoryreference = indexedreference ;
indexedreference = offset ;
indexedreference = offset ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '--' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '-' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '++' ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '+' ;
<<PrettyPrinter>>: { H*; }
offset = '>' expression ; -- page zero ref
<<PrettyPrinter>>: { H*; }
offset = '<' expression ; -- long reference
<<PrettyPrinter>>: { H*; }
offset = expression ;
offset = 'A' ;
offset = 'B' ;
offset = 'D' ;
registerlist = registername ;
registerlist = registerlist ',' registername ;
<<PrettyPrinter>>: { H*; }
registername = 'A' ;
registername = 'B' ;
registername = 'CC' ;
registername = 'DP' ;
registername = 'D' ;
registername = 'Z' ;
registername = indexregister ;
indexregister = 'X' ;
indexregister = 'Y' ;
indexregister = 'U' ; -- not legal on M6811
indexregister = 'S' ;
indexregister = 'PCR' ;
indexregister = 'PC' ;
expression = sum '=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '</' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>/' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '#' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum ;
sum = product ;
sum = sum '+' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '-' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!!' product ;
<<PrettyPrinter>>: { H*; }
product = term '*' product ;
<<PrettyPrinter>>: { H*; }
product = term '||' product ; -- wrong?
<<PrettyPrinter>>: { H*; }
product = term '/' product ;
<<PrettyPrinter>>: { H*; }
product = term '//' product ;
<<PrettyPrinter>>: { H*; }
product = term '&' product ;
<<PrettyPrinter>>: { H*; }
product = term '##' product ;
<<PrettyPrinter>>: { H*; }
product = term ;
term = '+' term ;
<<PrettyPrinter>>: { H*; }
term = '-' term ;
<<PrettyPrinter>>: { H*; }
term = '\\' term ; -- complement
<<PrettyPrinter>>: { H*; }
term = '&' term ; -- not
term = IDENTIFIER ;
term = NUMBER ;
term = CHARACTER ;
term = '*' ;
term = '(' expression ')' ;
<<PrettyPrinter>>: { H*; }
numberlist = NUMBER ;
numberlist = numberlist ',' NUMBER ;
<<PrettyPrinter>>: { H*; }
``` | BNF is more generally used for structured, nested languages like Pascal, C++, or really anything derived from the Algol family (which includes modern languages like C#). If I were implementing an assembler, I might use some simple regular expressions to pattern-match the opcode and operands. It's been a while since I've used Z80 assembly language, but you might use something like:
```
/\s*(\w{2,3})\s+((\w+)(,\w+)?)?/
```
This would match any line which consists of a two- or three-letter opcode followed by one or two operands separated by a comma. After extracting an assembler line like this, you would look at the opcode and generate the correct bytes for the instruction, including the values of the operands if applicable.
The type of parser I've outlined above using regular expressions would be called an "ad hoc" parser, which essentially means you split and examine the input on some kind of block basis (in the case of assembly language, by text line). |
1,317,256 | I'm trying to learn BNF and attempting to assemble some Z80 ASM code. Since I'm new to both fields, my question is, am I even on the right track? I am trying to write the format of Z80 ASM as EBNF so that I can then figure out where to go from there to create machine code from the source. At the moment I have the following:
```
Assignment = Identifier, ":" ;
Instruction = Opcode, [ Operand ], [ Operand ] ;
Operand = Identifier | Something* ;
Something* = "(" , Identifier, ")" ;
Identifier = Alpha, { Numeric | Alpha } ;
Opcode = Alpha, Alpha ;
Int = [ "-" ], Numeric, { Numeric } ;
Alpha = "A" | "B" | "C" | "D" | "E" | "F" |
"G" | "H" | "I" | "J" | "K" | "L" |
"M" | "N" | "O" | "P" | "Q" | "R" |
"S" | "T" | "U" | "V" | "W" | "X" |
"Y" | "Z" ;
Numeric = "0" | "1" | "2" | "3"| "4" |
"5" | "6" | "7" | "8" | "9" ;
```
Any directional feedback if I am going wrong would be excellent. | 2009/08/22 | [
"https://Stackoverflow.com/questions/1317256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385364/"
] | Old-school assemblers were typically hand-coded in assembler and used adhoc parsing techniques to process assembly source lines to produce actual assembler code.
When assembler syntax is simple (e.g. always OPCODE REG, OPERAND) this worked well enough.
Modern machines have messy, nasty instruction sets with lots of instruction variations and operands, which may be expressed with complex syntax allowing multiple index registers to participate in the operand expression. Allowing sophisticated assembly-time expressions with fixed and relocatable constants with various types of addition operators complicates this. Sophisticated assemblers allowing conditional compilation, macros, structured data declarations, etc. all add new demands on syntax. Processing all this syntax by ad hoc methods is very hard and is the reason that parser generators were invented.
Using a BNF and a parser generator is very reasonable way to build a modern assembler, even for a legacy processor such as the Z80. I have built such assemblers for Motorola 8 bit machines such as the 6800/6809, and am getting ready to do the same for a modern x86. I think you're headed down exactly the right path.
\*\*\*\*\*\*\*\*\*\* EDIT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
The OP asked for example lexer and parser definitions.
I've provided both here.
These are excerpts from real specifications for a 6809 asssembler.
The complete definitions are 2-3x the size of the samples here.
To keep space down, I have edited out much of the dark-corner complexity
which is the point of these definitions.
One might be dismayed by the apparant complexity; the
point is that with such definitions, you are trying to *describe* the
shape of the language, not code it procedurally.
You will pay a significantly higher complexity if you
code all this in an ad hoc manner, and it will be far
less maintainable.
It will also be of some help to know that these definitions
are used with a high-end program analysis system that
has lexing/parsing tools as subsystems, called the
[The DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html). DMS will automatically build ASTs from the
grammar rules in the parser specfication, which makes it a
lot easier to buid parsing tools. Lastly,
the parser specification contains so-called "prettyprinter"
declarations, which allows DMS to regenreate source text from the ASTs.
(The real purpose of the grammer was to allow us to build ASTs representing assembler
instructions, and then spit them out to be fed to a real assembler!)
One thing of note: how lexemes and grammar rules are stated (the metasyntxax!)
varies somewhat between different lexer/parser generator systems. The
syntax of DMS-based specifications is no exception. DMS has relatively sophisticated
grammar rules of its own, that really aren't practical to explain in the space available here. You'll have to live with idea that other systems use similar notations, for
EBNF for rules and and regular expression variants for lexemes.
Given the OP's interests, he can implement similar lexer/parsers
with any lexer/parser generator tool, e.g., FLEX/YACC,
JAVACC, ANTLR, ...
\*\*\*\*\*\*\*\*\*\* LEXER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.lex: Lexical Description for M6809
-- Copyright (C) 1989,1999-2002 Ira D. Baxter
%%
#mainmode Label
#macro digit "[0-9]"
#macro hexadecimaldigit "<digit>|[a-fA-F]"
#macro comment_body_character "[\u0009 \u0020-\u007E]" -- does not include NEWLINE
#macro blank "[\u0000 \ \u0009]"
#macro hblanks "<blank>+"
#macro newline "\u000d \u000a? \u000c? | \u000a \u000c?" -- form feed allowed only after newline
#macro bare_semicolon_comment "\; <comment_body_character>* "
#macro bare_asterisk_comment "\* <comment_body_character>* "
...[snip]
#macro hexadecimal_digit "<digit> | [a-fA-F]"
#macro binary_digit "[01]"
#macro squoted_character "\' [\u0021-\u007E]"
#macro string_character "[\u0009 \u0020-\u007E]"
%%Label -- (First mode) processes left hand side of line: labels, opcodes, etc.
#skip "(<blank>*<newline>)+"
#skip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
#precomment "<comment_line><newline>"
#preskip "(<blank>*<newline>)+"
#preskip "(<blank>*<newline>)*<blank>+"
<< (GotoOpcodeField ?) >>
-- Note that an apparant register name is accepted as a label in this mode
#token LABEL [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoLabelList ?)
>>
%%OpcodeField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Opcode field tokens
#token 'ABA' "[aA][bB][aA]"
<< (GotoEOLComment ?) >>
#token 'ABX' "[aA][bB][xX]"
<< (GotoEOLComment ?) >>
#token 'ADC' "[aA][dD][cC]"
<< (GotoABregister ?) >>
#token 'ADCA' "[aA][dD][cC][aA]"
<< (GotoOperand ?) >>
#token 'ADCB' "[aA][dD][cC][bB]"
<< (GotoOperand ?) >>
#token 'ADCD' "[aA][dD][cC][dD]"
<< (GotoOperand ?) >>
#token 'ADD' "[aA][dD][dD]"
<< (GotoABregister ?) >>
#token 'ADDA' "[aA][dD][dD][aA]"
<< (GotoOperand ?) >>
#token 'ADDB' "[aA][dD][dD][bB]"
<< (GotoOperand ?) >>
#token 'ADDD' "[aA][dD][dD][dD]"
<< (GotoOperand ?) >>
#token 'AND' "[aA][nN][dD]"
<< (GotoABregister ?) >>
#token 'ANDA' "[aA][nN][dD][aA]"
<< (GotoOperand ?) >>
#token 'ANDB' "[aA][nN][dD][bB]"
<< (GotoOperand ?) >>
#token 'ANDCC' "[aA][nN][dD][cC][cC]"
<< (GotoRegister ?) >>
...[long list of opcodes snipped]
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
(GotoOperandField ?)
>>
#token '#' "\#" -- special constant introduction (FDB)
<< (GotoDataField ?) >>
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
(GotoOperandField ?)
>>
#token CHARACTER [CHARACTER] "<squoted_character>"
<< (= ?:Lexeme:Literal:Character:Value (TokenStringCharacter ? 2))
(= ?:Lexeme:Literal:Character:Format (LiteralFormat:MakeCompactCharacterLiteralFormat 0 0)) ; nothing special about character
(GotoOperandField ?)
>>
%%OperandField
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
-- Tokens signalling switch to index register modes
#token ',' "\,"
<<(GotoRegisterField ?)>>
#token '[' "\["
<<(GotoRegisterField ?)>>
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '//' "\/\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '</' "\<\/"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>/' "\>\/"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\$ <hexadecimal_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertHexadecimalTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
#token NUMBER [NATURAL] "\% <binary_digit>+"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertBinaryTokenStringToNatural (. format) ? 1 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
-- Notice that an apparent register is accepted as a label in this mode
#token IDENTIFIER [STRING] "<identifier>"
<< (local (;; (= [TokenScan natural] 1) ; process all string characters
(= [TokenLength natural] ?:TokenCharacterCount)=
(= [TokenString (reference TokenBodyT)] (. ?:TokenCharacters))
(= [Result (reference string)] (. ?:Lexeme:Literal:String:Value))
[ThisCharacterCode natural]
(define Ordinala #61)
(define Ordinalf #66)
(define OrdinalA #41)
(define OrdinalF #46)
);;
(;; (= (@ Result) `') ; start with empty string
(while (<= TokenScan TokenLength)
(;; (= ThisCharacterCode (coerce natural TokenString:TokenScan))
(+= TokenScan) ; bump past character
(ifthen (>= ThisCharacterCode Ordinala)
(-= ThisCharacterCode #20) ; fold to upper case
)ifthen
(= (@ Result) (append (@ Result) (coerce character ThisCharacterCode)))=
);;
)while
);;
)local
(= ?:Lexeme:Literal:String:Format (LiteralFormat:MakeCompactStringLiteralFormat 0)) ; nothing interesting in string
>>
%%Register -- operand field for TFR, ANDCC, ORCC, EXG opcodes
#skip "<hblanks>"
#ifnotoken << (GotoRegisterField ?) >>
%%RegisterField -- handles registers and indexing mode syntax
-- In this mode, names that look like registers are recognized as registers
#skip "<hblanks>"
<< (GotoEOLComment ?) >>
#ifnotoken
<< (GotoEOLComment ?) >>
#token '[' "\["
#token ']' "\]"
#token '--' "\-\-"
#token '++' "\+\+"
#token 'A' "[aA]"
#token 'B' "[bB]"
#token 'CC' "[cC][cC]"
#token 'DP' "[dD][pP] | [dD][pP][rR]" -- DPR shouldnt be needed, but found one instance
#token 'D' "[dD]"
#token 'Z' "[zZ]"
-- Index register designations
#token 'X' "[xX]"
#token 'Y' "[yY]"
#token 'U' "[uU]"
#token 'S' "[sS]"
#token 'PCR' "[pP][cC][rR]"
#token 'PC' "[pP][cC]"
#token ',' "\,"
-- Operators for arithmetic syntax
#token '!!' "\!\!"
#token '!' "\!"
#token '##' "\#\#"
#token '#' "\#"
#token '&' "\&"
#token '(' "\("
#token ')' "\)"
#token '*' "\*"
#token '+' "\+"
#token '-' "\-"
#token '/' "\/"
#token '<' "\<"
#token '<' "\<"
#token '<<' "\<\<"
#token '<=' "\<\="
#token '<|' "\<\|"
#token '=' "\="
#token '>' "\>"
#token '>' "\>"
#token '>=' "\>\="
#token '>>' "\>\>"
#token '>|' "\>\|"
#token '\\' "\\"
#token '|' "\|"
#token '||' "\|\|"
#token NUMBER [NATURAL] "<decimal_number>"
<< (local [format LiteralFormat:NaturalLiteralFormat]
(;; (= ?:Lexeme:Literal:Natural:Value (ConvertDecimalTokenStringToNatural (. format) ? 0 0))
(= ?:Lexeme:Literal:Natural:Format (LiteralFormat:MakeCompactNaturalLiteralFormat format))
);;
)local
>>
... [snip]
%% -- end M6809.lex
```
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* PARSER \*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
-- M6809.ATG: Motorola 6809 assembly code parser
-- (C) Copyright 1989;1999-2002 Ira D. Baxter; All Rights Reserved
m6809 = sourcelines ;
sourcelines = ;
sourcelines = sourcelines sourceline EOL ;
<<PrettyPrinter>>: { V(CV(sourcelines[1]),H(sourceline,A<eol>(EOL))); }
-- leading opcode field symbol should be treated as keyword.
sourceline = ;
sourceline = labels ;
sourceline = optional_labels 'EQU' expression ;
<<PrettyPrinter>>: { H(optional_labels,A<opcode>('EQU'),A<operand>(expression)); }
sourceline = LABEL 'SET' expression ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),A<opcode>('SET'),A<operand>(expression)); }
sourceline = optional_label instruction ;
<<PrettyPrinter>>: { H(optional_label,instruction); }
sourceline = optional_label optlabelleddirective ;
<<PrettyPrinter>>: { H(optional_label,optlabelleddirective); }
sourceline = optional_label implicitdatadirective ;
<<PrettyPrinter>>: { H(optional_label,implicitdatadirective); }
sourceline = unlabelleddirective ;
sourceline = '?ERROR' ;
<<PrettyPrinter>>: { A<opcode>('?ERROR'); }
optional_label = labels ;
optional_label = LABEL ':' ;
<<PrettyPrinter>>: { H(A<firstlabel>(LABEL),':'); }
optional_label = ;
optional_labels = ;
optional_labels = labels ;
labels = LABEL ;
<<PrettyPrinter>>: { A<firstlabel>(LABEL); }
labels = labels ',' LABEL ;
<<PrettyPrinter>>: { H(labels[1],',',A<otherlabels>(LABEL)); }
unlabelleddirective = 'END' ;
<<PrettyPrinter>>: { A<opcode>('END'); }
unlabelleddirective = 'END' expression ;
<<PrettyPrinter>>: { H(A<opcode>('END'),A<operand>(expression)); }
unlabelleddirective = 'IF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFDEF' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFDEF'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'IFUND' IDENTIFIER EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('IFUND'),H(A<operand>(IDENTIFIER),A<eol>(EOL))),CV(conditional)); }
unlabelleddirective = 'INCLUDE' FILENAME ;
<<PrettyPrinter>>: { H(A<opcode>('INCLUDE'),A<operand>(FILENAME)); }
unlabelleddirective = 'LIST' expression ;
<<PrettyPrinter>>: { H(A<opcode>('LIST'),A<operand>(expression)); }
unlabelleddirective = 'NAME' IDENTIFIER ;
<<PrettyPrinter>>: { H(A<opcode>('NAME'),A<operand>(IDENTIFIER)); }
unlabelleddirective = 'ORG' expression ;
<<PrettyPrinter>>: { H(A<opcode>('ORG'),A<operand>(expression)); }
unlabelleddirective = 'PAGE' ;
<<PrettyPrinter>>: { A<opcode>('PAGE'); }
unlabelleddirective = 'PAGE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('PAGE'),A<operand>(HEADING)); }
unlabelleddirective = 'PCA' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCA'),A<operand>(expression)); }
unlabelleddirective = 'PCC' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PCC'),A<operand>(expression)); }
unlabelleddirective = 'PSR' expression ;
<<PrettyPrinter>>: { H(A<opcode>('PSR'),A<operand>(expression)); }
unlabelleddirective = 'TABS' numberlist ;
<<PrettyPrinter>>: { H(A<opcode>('TABS'),A<operand>(numberlist)); }
unlabelleddirective = 'TITLE' HEADING ;
<<PrettyPrinter>>: { H(A<opcode>('TITLE'),A<operand>(HEADING)); }
unlabelleddirective = 'WITH' settings ;
<<PrettyPrinter>>: { H(A<opcode>('WITH'),A<operand>(settings)); }
settings = setting ;
settings = settings ',' setting ;
<<PrettyPrinter>>: { H*; }
setting = 'WI' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'DE' '=' NUMBER ;
<<PrettyPrinter>>: { H*; }
setting = 'M6800' ;
setting = 'M6801' ;
setting = 'M6809' ;
setting = 'M6811' ;
-- collects lines of conditional code into blocks
conditional = 'ELSEIF' expression EOL conditional ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSEIF'),H(A<operand>(expression),A<eol>(EOL))),CV(conditional[1])); }
conditional = 'ELSE' EOL else ;
<<PrettyPrinter>>: { V(H(A<opcode>('ELSE'),A<eol>(EOL)),CV(else)); }
conditional = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
conditional = sourceline EOL conditional ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(conditional[1])); }
else = 'FIN' ;
<<PrettyPrinter>>: { A<opcode>('FIN'); }
else = sourceline EOL else ;
<<PrettyPrinter>>: { V(H(sourceline,A<eol>(EOL)),CV(else[1])); }
-- keyword-less directive, generates data tables
implicitdatadirective = implicitdatadirective ',' implicitdataitem ;
<<PrettyPrinter>>: { H*; }
implicitdatadirective = implicitdataitem ;
implicitdataitem = '#' expression ;
<<PrettyPrinter>>: { A<operand>(H('#',expression)); }
implicitdataitem = '+' expression ;
<<PrettyPrinter>>: { A<operand>(H('+',expression)); }
implicitdataitem = '-' expression ;
<<PrettyPrinter>>: { A<operand>(H('-',expression)); }
implicitdataitem = expression ;
<<PrettyPrinter>>: { A<operand>(expression); }
implicitdataitem = STRING ;
<<PrettyPrinter>>: { A<operand>(STRING); }
-- instructions valid for m680C (see Software Dynamics ASM manual)
instruction = 'ABA' ;
<<PrettyPrinter>>: { A<opcode>('ABA'); }
instruction = 'ABX' ;
<<PrettyPrinter>>: { A<opcode>('ABX'); }
instruction = 'ADC' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','A')),A<operand>(operandfetch)); }
instruction = 'ADC' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADC','B')),A<operand>(operandfetch)); }
instruction = 'ADCA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCA'),A<operand>(operandfetch)); }
instruction = 'ADCB' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCB'),A<operand>(operandfetch)); }
instruction = 'ADCD' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADCD'),A<operand>(operandfetch)); }
instruction = 'ADD' 'A' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','A')),A<operand>(operandfetch)); }
instruction = 'ADD' 'B' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>(H('ADD','B')),A<operand>(operandfetch)); }
instruction = 'ADDA' operandfetch ;
<<PrettyPrinter>>: { H(A<opcode>('ADDA'),A<operand>(operandfetch)); }
[..snip...]
-- condition code mask for ANDCC and ORCC
conditionmask = '#' expression ;
<<PrettyPrinter>>: { H*; }
conditionmask = expression ;
target = expression ;
operandfetch = '#' expression ; --immediate
<<PrettyPrinter>>: { H*; }
operandfetch = memoryreference ;
operandstore = memoryreference ;
memoryreference = '[' indexedreference ']' ;
<<PrettyPrinter>>: { H*; }
memoryreference = indexedreference ;
indexedreference = offset ;
indexedreference = offset ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '--' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' '-' indexregister ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '++' ;
<<PrettyPrinter>>: { H*; }
indexedreference = ',' indexregister '+' ;
<<PrettyPrinter>>: { H*; }
offset = '>' expression ; -- page zero ref
<<PrettyPrinter>>: { H*; }
offset = '<' expression ; -- long reference
<<PrettyPrinter>>: { H*; }
offset = expression ;
offset = 'A' ;
offset = 'B' ;
offset = 'D' ;
registerlist = registername ;
registerlist = registerlist ',' registername ;
<<PrettyPrinter>>: { H*; }
registername = 'A' ;
registername = 'B' ;
registername = 'CC' ;
registername = 'DP' ;
registername = 'D' ;
registername = 'Z' ;
registername = indexregister ;
indexregister = 'X' ;
indexregister = 'Y' ;
indexregister = 'U' ; -- not legal on M6811
indexregister = 'S' ;
indexregister = 'PCR' ;
indexregister = 'PC' ;
expression = sum '=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '</' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '<' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>/' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>=' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '>' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum '#' sum ;
<<PrettyPrinter>>: { H*; }
expression = sum ;
sum = product ;
sum = sum '+' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '-' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!' product ;
<<PrettyPrinter>>: { H*; }
sum = sum '!!' product ;
<<PrettyPrinter>>: { H*; }
product = term '*' product ;
<<PrettyPrinter>>: { H*; }
product = term '||' product ; -- wrong?
<<PrettyPrinter>>: { H*; }
product = term '/' product ;
<<PrettyPrinter>>: { H*; }
product = term '//' product ;
<<PrettyPrinter>>: { H*; }
product = term '&' product ;
<<PrettyPrinter>>: { H*; }
product = term '##' product ;
<<PrettyPrinter>>: { H*; }
product = term ;
term = '+' term ;
<<PrettyPrinter>>: { H*; }
term = '-' term ;
<<PrettyPrinter>>: { H*; }
term = '\\' term ; -- complement
<<PrettyPrinter>>: { H*; }
term = '&' term ; -- not
term = IDENTIFIER ;
term = NUMBER ;
term = CHARACTER ;
term = '*' ;
term = '(' expression ')' ;
<<PrettyPrinter>>: { H*; }
numberlist = NUMBER ;
numberlist = numberlist ',' NUMBER ;
<<PrettyPrinter>>: { H*; }
``` | I don't think you need overthink it. There's no point making a parser that takes apart “LD A,A” into a load operation, destination and source register, when you can just string match the whole thing (modulo case and whitespace) into one opcode directly.
There aren't that many opcodes, and they aren't arranged in such a way that you really get much benefit from parsing and understanding the assembler IMO. Obviously you'd need a parser for the byte/address/indexing arguments, but other than that I'd just have a one-to-one lookup. |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | It is possible, but the solution inverts the problem a little. Here's a sample written up as a golang test.
```
package redirects
import (
"github.com/codegangsta/martini-contrib/auth"
"github.com/go-martini/martini"
"net/http"
"net/http/httptest"
"testing"
)
func TestBasicAuthRedirect(t *testing.T) {
// Start a test server
server := setupBasicAuthServer()
defer server.Close()
// Set up the HTTP request
req, err := http.NewRequest("GET", server.URL+"/redirect", nil)
req.SetBasicAuth("username", "password")
if err != nil {
t.Fatal(err)
}
transport := http.Transport{}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
// Check if you received the status codes you expect. There may
// status codes other than 200 which are acceptable.
if resp.StatusCode != 200 && resp.StatusCode != 302 {
t.Fatal("Failed with status", resp.Status)
}
t.Log(resp.Header.Get("Location"))
}
// Create an HTTP server that protects a URL using Basic Auth
func setupBasicAuthServer() *httptest.Server {
m := martini.Classic()
m.Use(auth.Basic("username", "password"))
m.Get("/ping", func() string { return "pong" })
m.Get("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ping", 302)
})
server := httptest.NewServer(m)
return server
}
```
You should be able to put the above code into it's own package called "redirects" and run it after fetching the required dependencies using
```
mkdir redirects
cd redirects
# Add the above code to a file with an _test.go suffix
go get github.com/codegangsta/martini-contrib/auth
go get github.com/go-martini/martini
go test -v
```
Hope this helps! | To make request with Basic Auth that does not follow redirect use [RoundTrip](http://golang.org/pkg/net/http/#Transport.RoundTrip) function that accepts \*[Request](http://golang.org/pkg/net/http/#Request)
This code
```
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
var DefaultTransport http.RoundTripper = &http.Transport{}
req, _ := http.NewRequest("GET", "http://httpbin.org/headers", nil)
req.SetBasicAuth("user", "password")
resp, _ := DefaultTransport.RoundTrip(req)
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
```
outputs
```
{
"headers": {
"Accept-Encoding": "gzip",
"Authorization": "Basic dXNlcjpwYXNzd29yZA==",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go 1.1 package http",
"X-Request-Id": "45b512f1-22e9-4e49-8acb-2f017e0a4e35"
}
}
``` |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | Another option, using the client itself, without the RoundTrip:
```go
// create a custom error to know if a redirect happened
var RedirectAttemptedError = errors.New("redirect")
client := &http.Client{}
// return the error, so client won't attempt redirects
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return RedirectAttemptedError
}
// Work with the client...
resp, err := client.Head(urlToAccess)
// test if we got the custom error
if urlError, ok := err.(*url.Error); ok && urlError.Err == RedirectAttemptedError{
err = nil
}
```
**UPDATE:** this solution is for go < 1.7 | It is possible, but the solution inverts the problem a little. Here's a sample written up as a golang test.
```
package redirects
import (
"github.com/codegangsta/martini-contrib/auth"
"github.com/go-martini/martini"
"net/http"
"net/http/httptest"
"testing"
)
func TestBasicAuthRedirect(t *testing.T) {
// Start a test server
server := setupBasicAuthServer()
defer server.Close()
// Set up the HTTP request
req, err := http.NewRequest("GET", server.URL+"/redirect", nil)
req.SetBasicAuth("username", "password")
if err != nil {
t.Fatal(err)
}
transport := http.Transport{}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
// Check if you received the status codes you expect. There may
// status codes other than 200 which are acceptable.
if resp.StatusCode != 200 && resp.StatusCode != 302 {
t.Fatal("Failed with status", resp.Status)
}
t.Log(resp.Header.Get("Location"))
}
// Create an HTTP server that protects a URL using Basic Auth
func setupBasicAuthServer() *httptest.Server {
m := martini.Classic()
m.Use(auth.Basic("username", "password"))
m.Get("/ping", func() string { return "pong" })
m.Get("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ping", 302)
})
server := httptest.NewServer(m)
return server
}
```
You should be able to put the above code into it's own package called "redirects" and run it after fetching the required dependencies using
```
mkdir redirects
cd redirects
# Add the above code to a file with an _test.go suffix
go get github.com/codegangsta/martini-contrib/auth
go get github.com/go-martini/martini
go test -v
```
Hope this helps! |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | There's a much simpler solution right now:
```
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
```
This way, the `http` package automatically knows: "Ah, I shouldn't follow any redirects", but does not throw any error. From the comment in the source code:
>
> As a special case, if CheckRedirect returns ErrUseLastResponse,
> then the most recent response is returned with its body
> unclosed, along with a nil error.
>
>
> | It is possible, but the solution inverts the problem a little. Here's a sample written up as a golang test.
```
package redirects
import (
"github.com/codegangsta/martini-contrib/auth"
"github.com/go-martini/martini"
"net/http"
"net/http/httptest"
"testing"
)
func TestBasicAuthRedirect(t *testing.T) {
// Start a test server
server := setupBasicAuthServer()
defer server.Close()
// Set up the HTTP request
req, err := http.NewRequest("GET", server.URL+"/redirect", nil)
req.SetBasicAuth("username", "password")
if err != nil {
t.Fatal(err)
}
transport := http.Transport{}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
// Check if you received the status codes you expect. There may
// status codes other than 200 which are acceptable.
if resp.StatusCode != 200 && resp.StatusCode != 302 {
t.Fatal("Failed with status", resp.Status)
}
t.Log(resp.Header.Get("Location"))
}
// Create an HTTP server that protects a URL using Basic Auth
func setupBasicAuthServer() *httptest.Server {
m := martini.Classic()
m.Use(auth.Basic("username", "password"))
m.Get("/ping", func() string { return "pong" })
m.Get("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ping", 302)
})
server := httptest.NewServer(m)
return server
}
```
You should be able to put the above code into it's own package called "redirects" and run it after fetching the required dependencies using
```
mkdir redirects
cd redirects
# Add the above code to a file with an _test.go suffix
go get github.com/codegangsta/martini-contrib/auth
go get github.com/go-martini/martini
go test -v
```
Hope this helps! |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | It is possible, but the solution inverts the problem a little. Here's a sample written up as a golang test.
```
package redirects
import (
"github.com/codegangsta/martini-contrib/auth"
"github.com/go-martini/martini"
"net/http"
"net/http/httptest"
"testing"
)
func TestBasicAuthRedirect(t *testing.T) {
// Start a test server
server := setupBasicAuthServer()
defer server.Close()
// Set up the HTTP request
req, err := http.NewRequest("GET", server.URL+"/redirect", nil)
req.SetBasicAuth("username", "password")
if err != nil {
t.Fatal(err)
}
transport := http.Transport{}
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
// Check if you received the status codes you expect. There may
// status codes other than 200 which are acceptable.
if resp.StatusCode != 200 && resp.StatusCode != 302 {
t.Fatal("Failed with status", resp.Status)
}
t.Log(resp.Header.Get("Location"))
}
// Create an HTTP server that protects a URL using Basic Auth
func setupBasicAuthServer() *httptest.Server {
m := martini.Classic()
m.Use(auth.Basic("username", "password"))
m.Get("/ping", func() string { return "pong" })
m.Get("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ping", 302)
})
server := httptest.NewServer(m)
return server
}
```
You should be able to put the above code into it's own package called "redirects" and run it after fetching the required dependencies using
```
mkdir redirects
cd redirects
# Add the above code to a file with an _test.go suffix
go get github.com/codegangsta/martini-contrib/auth
go get github.com/go-martini/martini
go test -v
```
Hope this helps! | As an addition of top rated answer,
You can control the particle size
```
func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
err := fmt.Errorf("redirect policy: stopped after %d times", times)
if len(via) >= times {
return err
}
return nil
}
...
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return myCheckRedirect(req, via, 1)
},
}
```
ref: <https://golangbyexample.com/http-no-redirect-client-golang/> |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | Another option, using the client itself, without the RoundTrip:
```go
// create a custom error to know if a redirect happened
var RedirectAttemptedError = errors.New("redirect")
client := &http.Client{}
// return the error, so client won't attempt redirects
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return RedirectAttemptedError
}
// Work with the client...
resp, err := client.Head(urlToAccess)
// test if we got the custom error
if urlError, ok := err.(*url.Error); ok && urlError.Err == RedirectAttemptedError{
err = nil
}
```
**UPDATE:** this solution is for go < 1.7 | To make request with Basic Auth that does not follow redirect use [RoundTrip](http://golang.org/pkg/net/http/#Transport.RoundTrip) function that accepts \*[Request](http://golang.org/pkg/net/http/#Request)
This code
```
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
var DefaultTransport http.RoundTripper = &http.Transport{}
req, _ := http.NewRequest("GET", "http://httpbin.org/headers", nil)
req.SetBasicAuth("user", "password")
resp, _ := DefaultTransport.RoundTrip(req)
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
```
outputs
```
{
"headers": {
"Accept-Encoding": "gzip",
"Authorization": "Basic dXNlcjpwYXNzd29yZA==",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go 1.1 package http",
"X-Request-Id": "45b512f1-22e9-4e49-8acb-2f017e0a4e35"
}
}
``` |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | There's a much simpler solution right now:
```
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
```
This way, the `http` package automatically knows: "Ah, I shouldn't follow any redirects", but does not throw any error. From the comment in the source code:
>
> As a special case, if CheckRedirect returns ErrUseLastResponse,
> then the most recent response is returned with its body
> unclosed, along with a nil error.
>
>
> | To make request with Basic Auth that does not follow redirect use [RoundTrip](http://golang.org/pkg/net/http/#Transport.RoundTrip) function that accepts \*[Request](http://golang.org/pkg/net/http/#Request)
This code
```
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
var DefaultTransport http.RoundTripper = &http.Transport{}
req, _ := http.NewRequest("GET", "http://httpbin.org/headers", nil)
req.SetBasicAuth("user", "password")
resp, _ := DefaultTransport.RoundTrip(req)
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
```
outputs
```
{
"headers": {
"Accept-Encoding": "gzip",
"Authorization": "Basic dXNlcjpwYXNzd29yZA==",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go 1.1 package http",
"X-Request-Id": "45b512f1-22e9-4e49-8acb-2f017e0a4e35"
}
}
``` |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | To make request with Basic Auth that does not follow redirect use [RoundTrip](http://golang.org/pkg/net/http/#Transport.RoundTrip) function that accepts \*[Request](http://golang.org/pkg/net/http/#Request)
This code
```
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
var DefaultTransport http.RoundTripper = &http.Transport{}
req, _ := http.NewRequest("GET", "http://httpbin.org/headers", nil)
req.SetBasicAuth("user", "password")
resp, _ := DefaultTransport.RoundTrip(req)
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
```
outputs
```
{
"headers": {
"Accept-Encoding": "gzip",
"Authorization": "Basic dXNlcjpwYXNzd29yZA==",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go 1.1 package http",
"X-Request-Id": "45b512f1-22e9-4e49-8acb-2f017e0a4e35"
}
}
``` | As an addition of top rated answer,
You can control the particle size
```
func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
err := fmt.Errorf("redirect policy: stopped after %d times", times)
if len(via) >= times {
return err
}
return nil
}
...
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return myCheckRedirect(req, via, 1)
},
}
```
ref: <https://golangbyexample.com/http-no-redirect-client-golang/> |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | There's a much simpler solution right now:
```
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
```
This way, the `http` package automatically knows: "Ah, I shouldn't follow any redirects", but does not throw any error. From the comment in the source code:
>
> As a special case, if CheckRedirect returns ErrUseLastResponse,
> then the most recent response is returned with its body
> unclosed, along with a nil error.
>
>
> | Another option, using the client itself, without the RoundTrip:
```go
// create a custom error to know if a redirect happened
var RedirectAttemptedError = errors.New("redirect")
client := &http.Client{}
// return the error, so client won't attempt redirects
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return RedirectAttemptedError
}
// Work with the client...
resp, err := client.Head(urlToAccess)
// test if we got the custom error
if urlError, ok := err.(*url.Error); ok && urlError.Err == RedirectAttemptedError{
err = nil
}
```
**UPDATE:** this solution is for go < 1.7 |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | Another option, using the client itself, without the RoundTrip:
```go
// create a custom error to know if a redirect happened
var RedirectAttemptedError = errors.New("redirect")
client := &http.Client{}
// return the error, so client won't attempt redirects
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return RedirectAttemptedError
}
// Work with the client...
resp, err := client.Head(urlToAccess)
// test if we got the custom error
if urlError, ok := err.(*url.Error); ok && urlError.Err == RedirectAttemptedError{
err = nil
}
```
**UPDATE:** this solution is for go < 1.7 | As an addition of top rated answer,
You can control the particle size
```
func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
err := fmt.Errorf("redirect policy: stopped after %d times", times)
if len(via) >= times {
return err
}
return nil
}
...
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return myCheckRedirect(req, via, 1)
},
}
```
ref: <https://golangbyexample.com/http-no-redirect-client-golang/> |
23,297,520 | I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.
I'm trying to use my Go script to grab the HTTP Location header for later processing.
Here's what I'm currently doing to achieve this functionality:
```
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
```
This feels like a bit of a hack to me. By overriding the `http.Client`'s `CheckRedirect` function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).
I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.
Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling? | 2014/04/25 | [
"https://Stackoverflow.com/questions/23297520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194175/"
] | There's a much simpler solution right now:
```
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
```
This way, the `http` package automatically knows: "Ah, I shouldn't follow any redirects", but does not throw any error. From the comment in the source code:
>
> As a special case, if CheckRedirect returns ErrUseLastResponse,
> then the most recent response is returned with its body
> unclosed, along with a nil error.
>
>
> | As an addition of top rated answer,
You can control the particle size
```
func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
err := fmt.Errorf("redirect policy: stopped after %d times", times)
if len(via) >= times {
return err
}
return nil
}
...
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return myCheckRedirect(req, via, 1)
},
}
```
ref: <https://golangbyexample.com/http-no-redirect-client-golang/> |
33,511,462 | I have to write a code that counts the number of odd numbers, even numbers, and zeros in a multi-digit long variable, here is what I have so far:
```
#include <iostream>
using namespace std;
int lab14(long num, int &even, int &odd, int &zero){
while (num > 0){
long w = num;
w = num%10;
if (w % 2 == 1){
odd++;
}
else if (w % 2 == 0 && w != 0){
even++;
}
else if (w == 0 ){
zero++;
}
num = num/10;
}
return odd;
return even;
return zero;
}
int main() {
int even = 0, odd = 0, zero = 0;
int num;
cout << "#############################" << endl;
cout << "## Even, odd, zero counter " << endl;
bool flag = true;
while (flag){
cout << "## Please enter a #: "; cin >>num;
lab14(num, even, odd, zero);
cout << "## Even numbers: "<< even << endl
<< "## Odd Numbers: " << odd << endl
<< "## Zeros: " << zero << endl;
cout << "## Enter 1 to go again, 0 to exit: "; cin >> flag ; cout << endl;
}
return 0;
}
```
For some reason, I'm getting really weird outputs. Can anyone help me out, for example:
```
## Please enter a #: 245
## Even numbers: 3
## Odd Numbers: 13
## Zeros: 0
## Enter 1 to go again, 0 to exit: 1
## Please enter a #: 342
## Even numbers: 5
## Odd Numbers: 14
## Zeros: 0
## Enter 1 to go again, 0 to exit:
``` | 2015/11/04 | [
"https://Stackoverflow.com/questions/33511462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505001/"
] | As I mentioned in my [comment](https://stackoverflow.com/questions/33511461/how-do-i-dereference-this-hash-in-perl#comment54806600_33511461), you're flattening a list when you create `%hash`. The fat comma (`=>`) is a synonym for the comma that causes barewords on the left to be interpreted as strings, but it doesn't matter in this case because you've already got a string on the left. In effect, your hash assignment really looks like this:
```
my %hash = ("a", 1, 2, 3, "b", 3, 4, 5);
```
It looks like you were trying to assign arrays to `a` and `b`, but in Perl, hash values are always scalars, so you need to use references to anonymous arrays instead:
```
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
```
It's also worth noting that your subroutine is making a shallow copy of the hash reference you pass in, which may have unintended/unforeseen consequences. Consider the following:
```
use Data::Dump;
sub giveMeARef {
my %hash = %{$_[0]};
pop(@{$hash{a}});
}
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
dd(\%hash);
giveMeARef(\%hash);
dd(\%hash);
```
Which outputs:
```
{ a => [1, 2, 3], b => [3, 4, 5] }
{ a => [1, 2], b => [3, 4, 5] }
``` | The code is fine, but your test hash is not what you think it is.
You cannot construct a hash like that. The lists in there got flattened out. You need to use array-refs instead:
```
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
```
Since you are going to take a reference to that hash anyway, you might as well start there:
```
my $hash_ref = { a => [1,2,3], b => [3,4,5] };
``` |
33,511,462 | I have to write a code that counts the number of odd numbers, even numbers, and zeros in a multi-digit long variable, here is what I have so far:
```
#include <iostream>
using namespace std;
int lab14(long num, int &even, int &odd, int &zero){
while (num > 0){
long w = num;
w = num%10;
if (w % 2 == 1){
odd++;
}
else if (w % 2 == 0 && w != 0){
even++;
}
else if (w == 0 ){
zero++;
}
num = num/10;
}
return odd;
return even;
return zero;
}
int main() {
int even = 0, odd = 0, zero = 0;
int num;
cout << "#############################" << endl;
cout << "## Even, odd, zero counter " << endl;
bool flag = true;
while (flag){
cout << "## Please enter a #: "; cin >>num;
lab14(num, even, odd, zero);
cout << "## Even numbers: "<< even << endl
<< "## Odd Numbers: " << odd << endl
<< "## Zeros: " << zero << endl;
cout << "## Enter 1 to go again, 0 to exit: "; cin >> flag ; cout << endl;
}
return 0;
}
```
For some reason, I'm getting really weird outputs. Can anyone help me out, for example:
```
## Please enter a #: 245
## Even numbers: 3
## Odd Numbers: 13
## Zeros: 0
## Enter 1 to go again, 0 to exit: 1
## Please enter a #: 342
## Even numbers: 5
## Odd Numbers: 14
## Zeros: 0
## Enter 1 to go again, 0 to exit:
``` | 2015/11/04 | [
"https://Stackoverflow.com/questions/33511462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505001/"
] | The code is fine, but your test hash is not what you think it is.
You cannot construct a hash like that. The lists in there got flattened out. You need to use array-refs instead:
```
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
```
Since you are going to take a reference to that hash anyway, you might as well start there:
```
my $hash_ref = { a => [1,2,3], b => [3,4,5] };
``` | There are two issues here:
* The way Dumper is used to print the hash without passing reference wherein it resolves to print all the elements as $VAR1, $VAR2, etc.
Dumper(\%hash)
* The way the hash is initialized. Since the value is a list, it should be initialized as
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
A more correct code.
```
#!/usr/bin/perl
use Data::Dumper;
sub giveMeARef {
my %hash = %{$_[0]};
print "arg: ", Dumper($_[0]); #Dumper is passed a Ref.
print "deref: ", Dumper(\%hash); # Dumper should be called with a hash ref.
}
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
giveMeARef(\%hash);
``` |
33,511,462 | I have to write a code that counts the number of odd numbers, even numbers, and zeros in a multi-digit long variable, here is what I have so far:
```
#include <iostream>
using namespace std;
int lab14(long num, int &even, int &odd, int &zero){
while (num > 0){
long w = num;
w = num%10;
if (w % 2 == 1){
odd++;
}
else if (w % 2 == 0 && w != 0){
even++;
}
else if (w == 0 ){
zero++;
}
num = num/10;
}
return odd;
return even;
return zero;
}
int main() {
int even = 0, odd = 0, zero = 0;
int num;
cout << "#############################" << endl;
cout << "## Even, odd, zero counter " << endl;
bool flag = true;
while (flag){
cout << "## Please enter a #: "; cin >>num;
lab14(num, even, odd, zero);
cout << "## Even numbers: "<< even << endl
<< "## Odd Numbers: " << odd << endl
<< "## Zeros: " << zero << endl;
cout << "## Enter 1 to go again, 0 to exit: "; cin >> flag ; cout << endl;
}
return 0;
}
```
For some reason, I'm getting really weird outputs. Can anyone help me out, for example:
```
## Please enter a #: 245
## Even numbers: 3
## Odd Numbers: 13
## Zeros: 0
## Enter 1 to go again, 0 to exit: 1
## Please enter a #: 342
## Even numbers: 5
## Odd Numbers: 14
## Zeros: 0
## Enter 1 to go again, 0 to exit:
``` | 2015/11/04 | [
"https://Stackoverflow.com/questions/33511462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505001/"
] | As I mentioned in my [comment](https://stackoverflow.com/questions/33511461/how-do-i-dereference-this-hash-in-perl#comment54806600_33511461), you're flattening a list when you create `%hash`. The fat comma (`=>`) is a synonym for the comma that causes barewords on the left to be interpreted as strings, but it doesn't matter in this case because you've already got a string on the left. In effect, your hash assignment really looks like this:
```
my %hash = ("a", 1, 2, 3, "b", 3, 4, 5);
```
It looks like you were trying to assign arrays to `a` and `b`, but in Perl, hash values are always scalars, so you need to use references to anonymous arrays instead:
```
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
```
It's also worth noting that your subroutine is making a shallow copy of the hash reference you pass in, which may have unintended/unforeseen consequences. Consider the following:
```
use Data::Dump;
sub giveMeARef {
my %hash = %{$_[0]};
pop(@{$hash{a}});
}
my %hash = (a => [1, 2, 3], b => [3, 4, 5]);
dd(\%hash);
giveMeARef(\%hash);
dd(\%hash);
```
Which outputs:
```
{ a => [1, 2, 3], b => [3, 4, 5] }
{ a => [1, 2], b => [3, 4, 5] }
``` | There are two issues here:
* The way Dumper is used to print the hash without passing reference wherein it resolves to print all the elements as $VAR1, $VAR2, etc.
Dumper(\%hash)
* The way the hash is initialized. Since the value is a list, it should be initialized as
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
A more correct code.
```
#!/usr/bin/perl
use Data::Dumper;
sub giveMeARef {
my %hash = %{$_[0]};
print "arg: ", Dumper($_[0]); #Dumper is passed a Ref.
print "deref: ", Dumper(\%hash); # Dumper should be called with a hash ref.
}
my %hash = ( "a" => [1,2,3], "b" => [3,4,5]);
giveMeARef(\%hash);
``` |
56,412,227 | My angular 7 app is running using `ng serve` on port 4200. I have a node server running inside of a docker container, located at localhost:8081.
I have verified that the server is up, and accessible, using postman. The url was `localhost:8081/login`. I was able to receive the data I expected when the POST request was submitted.
When I click the login button in my login.html form, it calls `onSubmit()` from the login component class. This calls `login()`, which then calls a function from the authentication service which creates a POST request to `localhost:8081/login`.
**login.component.ts**
```
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private authenticationService: AuthenticationService) { }
loginForm = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
ngOnInit() {
}
// Called when login form submits
onSubmit() {
this.login();
}
login() : void {
this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value);
}
}
```
**authentication.service.ts**
```
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../models/user';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
private currentUser: Observable<User>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(email: string, password: string) {
return this.http.post<any>('localhost:8081/login', {email, password})
.pipe(map(user => {
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
```
Finally, my node server's endpoint that is being called.
**account.js**
```
// Verifies that the email and password exist in the database.
app.post('/login', (req, res) => {
console.log("in login post");
res.json({ firstName: 'test', lastName: 'user', email: '[email protected]', password: 'pass' });
});
```
I removed the other logic so that I can test this with the simplest case; just returning hard coded values.
When I make the request with postman, I see that "in login post" is logged. However, when I make the request from Angular, "in login post" is NOT logged.
Why can I not reach the endpoint from Angular, but I can from postman? The address & port are the same. | 2019/06/02 | [
"https://Stackoverflow.com/questions/56412227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5237611/"
] | As mentioned by @Austaras, an `Observable` must have at least one active subscription in order to execute it.
You must subscribe to the `login()` method of `AuthenticationService` in the `LoginComponent`
```
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private authenticationService: AuthenticationService) { }
loginForm = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
ngOnInit() {
}
// Called when login form submits
onSubmit() {
this.login();
}
login() : void {
this.authenticationService
.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value)
.subscribe( // <-- Subscription required here
(res) => {
console.log(res);
});
}
}
```
Read more about [Observables](https://medium.com/@luukgruijs/understanding-creating-and-subscribing-to-observables-in-angular-426dbf0b04a3) | You must subscribe your login service method when you use its in `login.component.ts`.
For example:
```
login() : void {
this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value).subscribe();
}
``` |
65,379,890 | I have a database with four tables and I want my PHP to execute the query dynamically for one of these tables, based on the user's input.
```
$company = $_POST['company'];
$model = $_POST['model'];
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "ref";
if ($company == "ford") {
$table = "ref_ford";
} else if ($company = "hyundai") {
$table == "ref_hyundai";
} else if ($company = "renault") {
$table == "ref_renault";
} else {
$table = "ref_fiat";
}
```
With this code, PHP doesn´t recognize the table, as when I selected it manually
```
$table = "ref_ford"
```
it does the query correctly.
I´ve also tried several different comparisons, both `==`and `===`, as well as,
```
$company == $_POST["ford"]
```
Any idea on how can I select the table based on the user's input?
```
<select name="company">
<option value = "ford">Ford</option>
<option value = "hyundai">Hyundai</option>
<option value = "renault">Renault</option>
<option value = "fiat">Fiat</option>
</select>
``` | 2020/12/20 | [
"https://Stackoverflow.com/questions/65379890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14857827/"
] | The problem has already been pointed out (in your if-statements, you have `=` when it should be `==` and `==` where it should be `=`) so I just wanted to show a, in my opinion, cleaner way of doing the same thing.
I would be to use an array for this. It's not only easier to read the relationships, but it also makes it easier to add/remove companies. Just add/remove them from the array.
```
$companyTables = [
'ford' => 'ref_ford',
'hyundai' => 'ref_hyundai',
'renault' => 'ref_renault',
'fiat' => 'ref_fiat',
];
// This will return the correct table if the array key exists, otherwise default to `fiat`.
$table = $companyTables[$company] ?? $companyTables['fiat'];
```
This would do the same as your current `if/else`'s. | All comparison operations should be using "==" instead of "=". On the other hand,all assignment should be using "=" instead of "=="
Hence, please change
```
if ($company == "ford") {
$table = "ref_ford";
} else if ($company = "hyundai") {
$table == "ref_hyundai";
} else if ($company = "renault") {
$table == "ref_renault";
} else {
$table = "ref_fiat";
}
```
to
```
if ($company == "ford") {
$table = "ref_ford";
} else if ($company == "hyundai") {
$table = "ref_hyundai";
} else if ($company == "renault") {
$table = "ref_renault";
} else {
$table = "ref_fiat";
}
``` |
14,468,001 | Output I'm getting:
* The base array
* 7290 5184 6174 8003 7427 2245 6522 6669 8939 4814 The
* Sorted array
* -33686019 2245 4814 5184 6174 6522 6669 7290 7427 8003
* Press any key to continue . . .
I have no idea where this, -33686019, number is coming from. I've posted all of the code because I really don't know what could be causing it.
The Bubble Sort:
```
#include "Sorting.h"
double Sorting::bubbleSort( int size )
{
//Make a copy of our "master key" array for us to sort
int *toSort = whichArray(size);
int *theArray = copyArray( toSort, size );
double time;
cout << "The base array" << endl;
for(int i = 0; i < 10; i++ )
{
cout << theArray[i] << endl;
}
//The sort
//Begin time
timer.startClock();
bool swapped = true;
int temp = 0;
while( swapped == true )
{
swapped = false;
for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
{
/*temp = theArray[i+1];
theArray[i+1] = theArray[i];
theArray[i] = temp;*/
swap(theArray[i + 1], theArray[i]);
swapped = true;
}
}
}
time = timer.getTime();
cout << "The Sorted array" << endl;
for(int x = 0; x < 10; x++ )
{
cout << theArray[x] << endl;
}
return time;
}
```
The Sorting Class:
```
#ifndef SORTING_H
#define SORTING_H
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//^For random numbers
#include <iostream>
#include "TimerSystem.h"
#include <iomanip>
using namespace std;
class Sorting
{
private:
//The below pointers will point to arrays that hold the data sets
int *n10;
int *n100;
int *n1000;
int *n10000;
TimerSystem timer;
double runs[4][4];
public:
Sorting();
~Sorting(){};
//Testing functions
void printArray();
void print2DArray();
void dryRun();
//Data manging and creating
int randomNumGen();
int* arrayGen( int size );//Returning a pointer
int* copyArray( int *toCopy, int size );//Makes an array that the program can sort. The leaves the original array intact
int* whichArray( int size );
void datasetRun( int whichSort );//Does three runs of a sort and gets the average for all 4 array sizes
//Sorts
double bubbleSort( int size );
};
#endif
```
Other Called Functions:
```
#include "Sorting.h"
int Sorting::randomNumGen()
{
int randomNumber = rand() % 10000 + 1;
if( randomNumber > 10000 || randomNumber < 0 )
{
system("pause");
}
return randomNumber;
}
int* Sorting::arrayGen( int size )
{
int *theArray= new int[size];
for( int i = 0; i < size; i++ )
{
theArray[i] = randomNumGen();
}
return theArray;
}
int* Sorting::copyArray( int *toCopy, int size )
{
int *newArray = new int[size];
for( int i = 0; i < size; i++ )
{
newArray[i] = toCopy[i];
}
return newArray;
}
int* Sorting::whichArray( int size )
{
if( size == 10 )
{
return n10;
}
else if( size == 100 )
{
return n100;
}
else if( size == 1000 )
{
return n100;
}
else if( size == 10000 )
{
return n1000;
}
return NULL;
}
void Sorting::datasetRun( int whichSort )
{
//1: Bubble
//2: Insertion
//3: Selection
//4: Shell
//5: Quick
//6: Merge
int col = 0;
int row = 0;
int set = 10;
bool runDone = false;
if( whichSort == 1 )
{
for( int row = 0; row < 4; row++ )
{
for( int col = 0; col < 4; col++ )
{
runs[row][col] = bubbleSort( set );
}
//set = set * 10;
}
}
}
//Constructor
Sorting::Sorting()
{
//For the random number generator
srand( time(NULL) );
n10 = arrayGen( 10 );
n100 = arrayGen( 100 );
n1000 = arrayGen( 1000 );
n10000 = arrayGen( 10000 );
}
//Functions for testing
void Sorting::printArray()
{
int size = 10000;
for( int i = 0; i < size; i++ )
{
cout << n10000[i] << " ";
}
}
void Sorting::print2DArray()
{
for( int height = 0; height < 4; height++ )
{
for( int width = 0; width < 4; width++ )
{
cout << runs[height][width] << endl;
}
cout << "\n\n";
}
}
```
The Main Function:
```
#include "Sorting.h"
void main()
{
//Makes the numbers easily readable
cout.setf(ios::fixed | ios::showpoint);
cout.precision(16);
Sorting theSorting;
//theSorting.printArray();
//cout << theSorting.bubbleSort( 10 ) << endl;
//theSorting.datasetRun(1);
//theSorting.print2DArray();
theSorting.bubbleSort( 10 );
system("pause");
}
``` | 2013/01/22 | [
"https://Stackoverflow.com/questions/14468001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715979/"
] | The following bit is not correct:
```
for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
```
It is accessing one beyond the boundary of the array. The `for` loop should probably be:
```
for( int i = 0; i < size - 1; i++ )
``` | Look at this:
```
for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
```
theArray[i+1] is undefined on the last iteration of the loop.
Change the loop's continuation expression from `i < size` to `i < (size-1)` |
701,086 | I am running a 10.04LTE server where I do want to upgrade openssl for apache.
Therefore I downloaded openssl 1.0.2c and apache 2.2.29 and compiled both. The server is starting, but is using the old ssl version:
```
curl --head http://localhost
HTTP/1.1 200 OK
Date: Mon, 22 Jun 2015 06:00:06 GMT
Server: Apache/2.2.29 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8k
Last-Modified: Sun, 18 Mar 2012 19:56:07 GMT
```
However, Openssl is installed in new version:
```
/usr/local/ssl/bin/openssl version
OpenSSL 1.0.2c 12 Jun 2015
```
While the original version stayes in place:
```
openssl version
OpenSSL 0.9.8k 25 Mar 2009
```
I compiled apache with:
```
./configure --with-included-apr --prefix=/usr/local/apache2 --enable-so
--enable-rewrite --with-ssl=/usr/local/ssl --enable-ssl=shared
--enable-deflate --enable-expires --enable-headers
```
Apache did not start before I included:
```
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so
```
According to the mod ssl website this is only available for apache 1.x
Not sure what is going wrong here. Thank you for any help! | 2015/06/23 | [
"https://serverfault.com/questions/701086",
"https://serverfault.com",
"https://serverfault.com/users/84332/"
] | The problem is that your Apache installation is unable to link the shared libraries of your new OpenSSL installation. Run the command `ldd /usr/local/apache/modules/mod_ssl.so` (with the apporpriate path to your mod\_ssl.so). You'll see that mod\_ssl.so is not linking to the libraries in `/usr/local/ssl/lib`
You have a couple options to fix the problem:
**Option #1 - Link in the libraries:**
Open `/etc/ld.so.conf.d/local.conf` for editing and add the following line: `/usr/local/openssl/lib`
Re-compile Apache (remember to `make clean`) and it should work.
If that doesn't work. You could also try specifying `LDFLAGS` directly with your `configure` command:
```
LDFLAGS=-L/usr/local/ssl/lib \ ./configure --with-included-apr --prefix=/usr/local/apache2 --enable-so
--enable-rewrite --with-ssl=/usr/local/ssl --enable-ssl=shared
--enable-deflate --enable-expires --enable-headers
```
**Option #2 - Upgrade the system OpenSSL:**
Re-install OpenSSL with the config line `./config --prefix=/usr --openssldir=/usr/local/openssl shared`
When the prefix is not specified in your config line, the OpenSSL installer will default to `/usr/local/ssl`.
Quick install instructions:
```
cd /usr/local/src
wget https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz
tar -zxf openssl-1.0.2*
cd openssl-1.0.2*
./config --prefix=/usr --openssldir=/usr/local/openssl shared
make
make test
make install
``` | Download the 1.0.2k zip file from this site.
<https://indy.fulgan.com/SSL/>
Extract the files.
Stop the Apache service.
Make a backup of these 3 files in C:\xampp\apache\bin
ssleay32.dll
libeay32.dll
openssl.exe
Copy the same 3 files from the extract files location to C:\xampp\apache\bin
Start the Apache service. |
10,864,333 | Here's a strange one. We have a Google App Engine (GAE) app and a custom domain <http://www.tradeos.com> CNAME'd to ghs.google.com. In China we regularly get no response whatsoever from the server for 20 minutes or so then it works fine for a a while, sometimes for a few hours.
Other non-Chinese sites like CNN seem to work continuously so it's not a general problem with the international Internet going down. From other countries we see no problem.
By the way the non-custom Google domains x.appspot.com don't seem to be accessible at all presumably blocked by the Great Firewall.
Any ideas? Thanks! | 2012/06/02 | [
"https://Stackoverflow.com/questions/10864333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176505/"
] | Read portions of bytes to byte array and store them in new files when buffer is full or it is end of file.
For example (code is not perfect, but it should help understanding the process)
```
class FileSplit {
public static void splitFile(File f) throws IOException {
int partCounter = 1;//I like to name parts from 001, 002, 003, ...
//you can change it to 0 if you want 000, 001, ...
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
String fileName = f.getName();
//try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
String filePartName = String.format("%s.%03d", fileName, partCounter++);
File newFile = new File(f.getParent(), filePartName);
try (FileOutputStream out = new FileOutputStream(newFile)) {
out.write(buffer, 0, bytesAmount);
}
}
}
}
public static void main(String[] args) throws IOException {
splitFile(new File("D:\\destination\\myFile.mp4"));
}
}
```
myFile.mp4 size=12,7 MB
After split I had 13 files
* `myFile.mp4.001` - `myFile.mp4.012` with size 1 MB
* `myFile.mp4.013` with size 806 KB
---
If you want to merge these files you can use
```
public static void mergeFiles(List<File> files, File into)
throws IOException {
try (FileOutputStream fos = new FileOutputStream(into);
BufferedOutputStream mergingStream = new BufferedOutputStream(fos)) {
for (File f : files) {
Files.copy(f.toPath(), mergingStream);
}
}
}
```
You can also create some additional methods to make your life easier. For instance method which will create list of files containing separated parts based on name (and location) of one of these files.
```
public static List<File> listOfFilesToMerge(File oneOfFiles) {
String tmpName = oneOfFiles.getName();//{name}.{number}
String destFileName = tmpName.substring(0, tmpName.lastIndexOf('.'));//remove .{number}
File[] files = oneOfFiles.getParentFile().listFiles(
(File dir, String name) -> name.matches(destFileName + "[.]\\d+"));
Arrays.sort(files);//ensuring order 001, 002, ..., 010, ...
return Arrays.asList(files);
}
```
With that method we can overload `mergeFiles` method to use only one of the files `File oneOfFiles` instead of whole list `List<File>` (we will generate that list based on one of the files)
```
public static void mergeFiles(File oneOfFiles, File into)
throws IOException {
mergeFiles(listOfFilesToMerge(oneOfFiles), into);
}
```
You can also overload these methods to use `String` instead of `File` (we will wrap each String in File when needed)
```
public static List<File> listOfFilesToMerge(String oneOfFiles) {
return listOfFilesToMerge(new File(oneOfFiles));
}
public static void mergeFiles(String oneOfFiles, String into) throws IOException{
mergeFiles(new File(oneOfFiles), new File(into));
}
``` | Read & write streams as raw `byte[]`. Avoid the text streams and readers.
In your last question your were apparently breaking up the files according to 'line'. To replicate that behavior, simply used a fixed size of `byte[]` to read. Note carefully the warnings in comments to your last question, to check how many bytes are read. A `byte[2^16]` will not necessarily be filled in a single read. |
35,015,850 | Given that I have a `Supervisor` actor which is injected with a `child` actor how do I send the child a PoisonPill message and test this using TestKit?
Here is my Superivisor.
```
class Supervisor(child: ActorRef) extends Actor {
...
child ! "hello"
child ! PoisonPill
}
```
here is my test code
```
val probe = TestProbe()
val supervisor = system.actorOf(Props(classOf[Supervisor], probe.ref))
probe.expectMsg("hello")
probe.expectMsg(PoisonPill)
```
The problem is that the `PoisonPill` message is not received.
Possibly because the probe is terminated by the `PoisonPill` message?
The assertion fails with
```
java.lang.AssertionError: assertion failed: timeout (3 seconds)
during expectMsg while waiting for PoisonPill
``` | 2016/01/26 | [
"https://Stackoverflow.com/questions/35015850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532383/"
] | I think this [Testing Actor Systems](http://doc.akka.io/docs/akka/current/scala/testing.html) should answer your question:
**Watching Other Actors from Probes**
A TestProbe can register itself for DeathWatch of any other actor:
```
val probe = TestProbe()
probe watch target
target ! PoisonPill
probe.expectTerminated(target)
``` | In a test case, which extends the testkit, you can use the following code:
```
"receives ShutDown" must {
"sends PosionPill to other actor" in {
val other = TestProbe("Other")
val testee = TestActorRef(new Testee(actor.ref))
testee ! Testee.ShutDown
watch(other.ref)
expectTerminated(other.ref)
}
}
``` |
2,573,501 | * Given a triangle $\mathrm{A}\left(2,0\right),\ \mathrm{B}\left(1,3\right),\
\mathrm{C}\left(5,2\right)\ \mbox{with}\ \rho\left(x,y\right) = x$; I need to find it's centre of mass ?.
* I know I need to integrate the density formula over the region, but I don't understand how to get the limits for the integrals to calculate the area.
* Do I need to find formulas for the lines and somehow use those ?. | 2017/12/19 | [
"https://math.stackexchange.com/questions/2573501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/392788/"
] | Denote by $\;AB,AC,BC\;$ the respective lines on which the sides $\;AB,AC,BC\;$ lie, thus:
$$\begin{cases}AB:\;y=-3x+6\\{}\\AC:\;y=\cfrac23x-\cfrac43\\{}\\BC:\;y=-\cfrac14x+\cfrac{13}4\end{cases}$$
You should try to do a diagram, and then you need for the mass you need the integrals
$$M=\int\_1^2\int\_{-3x+6}^{-\frac14x+\frac{13}4} x\,dy\,dx+\int\_2^5\int\_{\frac23x-\frac43}^{-\frac14x+\frac{13}4}x\,dy\,dx$$
Take it from here. | Yes find lines equation is a way to set the correct integral.
Firstly make a graph of the points and then find the equations you need. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.