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
|
---|---|---|---|---|---|
40,142,675 | The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order.
For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6).
Is there something I am missing?
```
public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) {
List<E> result = new ArrayList<E>();
PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator());
PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator());
while (aIter.hasNext() && bIter.hasNext()) {
if (aIter.next().compareTo(bIter.next()) < 0) {
result.add(aIter.next());
}
if (bIter.next().compareTo(bIter.next()) > 0){
result.add(bIter.next());
}
}
while (aIter.hasNext()) {
result.add(aIter.next());
}
while (bIter.hasNext()) {
result.add(bIter.next());
}
return result;
}
``` | 2016/10/19 | [
"https://Stackoverflow.com/questions/40142675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900887/"
] | In order to perform a merge, you need to peek at the next value, so see which next value to use.
Eventually, one of the lists will run out of values before the other, so you need to check for that.
One trick is to use `null` as an End-Of-Data marker, assuming that lists cannot contain `null` values, which is a fair assumption since they have to be sorted. In that case, code will be like this:
```
public static <E extends Comparable<E>> List<E> mergeSortedLists(List<E> list1, List<E> list2) {
List<E> merged = new ArrayList<>(list1.size() + list2.size());
// Get list iterators and fetch first value from each, if available
Iterator<E> iter1 = list1.iterator();
Iterator<E> iter2 = list2.iterator();
E value1 = (iter1.hasNext() ? iter1.next() : null);
E value2 = (iter2.hasNext() ? iter2.next() : null);
// Loop while values remain in either list
while (value1 != null || value2 != null) {
// Choose list to pull value from
if (value2 == null || (value1 != null && value1.compareTo(value2) <= 0)) {
// Add list1 value to result and fetch next value, if available
merged.add(value1);
value1 = (iter1.hasNext() ? iter1.next() : null);
} else {
// Add list2 value to result and fetch next value, if available
merged.add(value2);
value2 = (iter2.hasNext() ? iter2.next() : null);
}
}
// Return merged result
return merged;
}
```
*Test*
```
System.out.println(mergeSortedLists(Arrays.asList(1, 4, 5),
Arrays.asList(2, 3, 6)));
```
*Output*
```
[1, 2, 3, 4, 5, 6]
``` | If you are willing to use a library, the cleanest solution would be to use Collection-utils4 and *IteratorUtils.collatedIterator()*.
You need to provide a *Comparator* in order to pick the right element. |
40,142,675 | The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order.
For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6).
Is there something I am missing?
```
public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) {
List<E> result = new ArrayList<E>();
PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator());
PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator());
while (aIter.hasNext() && bIter.hasNext()) {
if (aIter.next().compareTo(bIter.next()) < 0) {
result.add(aIter.next());
}
if (bIter.next().compareTo(bIter.next()) > 0){
result.add(bIter.next());
}
}
while (aIter.hasNext()) {
result.add(aIter.next());
}
while (bIter.hasNext()) {
result.add(bIter.next());
}
return result;
}
``` | 2016/10/19 | [
"https://Stackoverflow.com/questions/40142675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900887/"
] | I'm going to assume you intended something like this with your use of `PushbackIterator`:
```
while (aIter.hasNext() && bIter.hasNext()) {
E aElem = aIter.next();
E bElem = bIter.next();
if (aElem.compareTo(bElem) <= 0) {
result.add(aElem);
bIter.pushback(bElem);
} else {
result.add(bElem);
aIter.pushback(aElem);
}
}
``` | Same approach of merging 2 arrays can also be used with iterators tweaking a little bit. you can use adding elements instead of printing if needed.
```
static void printItr(Iterator<String> it1, Iterator<String> it2) {
String firstString=null,secondString = null;
boolean moveAheadIt1 = true, moveAheadIt2 = true;
while(it1.hasNext() && it2.hasNext()){
firstString = moveAheadIt1 ? it1.next() : firstString ;
secondString = moveAheadIt2 ? it2.next() : secondString;
if(firstString.compareTo(secondString) < 0){
System.out.println(firstString);
moveAheadIt2 = false;
moveAheadIt1 = true;
}else {
System.out.println(secondString);
moveAheadIt1 = false;
moveAheadIt2 = true;
}
}
while(it1.hasNext()){
System.out.println(it1.next());
}
while(it2.hasNext()){
System.out.println(it2.next());
}
}
``` |
40,142,675 | The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order.
For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6).
Is there something I am missing?
```
public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) {
List<E> result = new ArrayList<E>();
PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator());
PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator());
while (aIter.hasNext() && bIter.hasNext()) {
if (aIter.next().compareTo(bIter.next()) < 0) {
result.add(aIter.next());
}
if (bIter.next().compareTo(bIter.next()) > 0){
result.add(bIter.next());
}
}
while (aIter.hasNext()) {
result.add(aIter.next());
}
while (bIter.hasNext()) {
result.add(bIter.next());
}
return result;
}
``` | 2016/10/19 | [
"https://Stackoverflow.com/questions/40142675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900887/"
] | I'm going to assume you intended something like this with your use of `PushbackIterator`:
```
while (aIter.hasNext() && bIter.hasNext()) {
E aElem = aIter.next();
E bElem = bIter.next();
if (aElem.compareTo(bElem) <= 0) {
result.add(aElem);
bIter.pushback(bElem);
} else {
result.add(bElem);
aIter.pushback(aElem);
}
}
``` | If you are willing to use a library, the cleanest solution would be to use Collection-utils4 and *IteratorUtils.collatedIterator()*.
You need to provide a *Comparator* in order to pick the right element. |
44,691,438 | I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] | This usually happens when the plugin providing the authorization strategy is not installed or enabled.
Make sure the `matrix-auth` plugin is installed and that it's not disabled (no `matrix-auth.jpi.disabled` file (or similar) in `$JENKINS_HOME/plugins/`). | It can happen if a newer version of a plugin is incompatible with older version of Jenkins. It's recommended to upgrade Jenkins to latest version.
This is how I do it:
```
ssh jenkins "cd /tmp; wget https://updates.jenkins-ci.org/latest/jenkins.war"
ssh jenkins "cp /usr/share/jenkins/jenkins.war /tmp/jenkins.war.previous.version"
ssh jenkins "sudo systemctl status jenkins"
ssh jenkins "sudo cp /tmp/jenkins.war /usr/share/jenkins/"
ssh jenkins "sudo systemctl restart jenkins"
``` |
44,691,438 | I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] | This usually happens when the plugin providing the authorization strategy is not installed or enabled.
Make sure the `matrix-auth` plugin is installed and that it's not disabled (no `matrix-auth.jpi.disabled` file (or similar) in `$JENKINS_HOME/plugins/`). | usually, this error ours when there is a mismatch between Jenkins Version and Plugins version.
Best solution is always to keep updated Jenkins and plugin or installed appropriate versions of jenkins according to the Jenkins version.
For centos, Redhat, amazon Linux follow the below steps.
```
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
yum update Jenkins.
```
For an ubuntu machine, you can follow the steps given by hit3k.
```
cd /tmp; wget https://updates.jenkins-ci.org/latest/jenkins.war
cp /usr/share/jenkins/jenkins.war /tmp/jenkins.war.previous.version
sudo systemctl status jenkins
sudo cp /tmp/jenkins.war /usr/share/jenkins/
sudo systemctl restart jenkins
``` |
44,691,438 | I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] | This usually happens when the plugin providing the authorization strategy is not installed or enabled.
Make sure the `matrix-auth` plugin is installed and that it's not disabled (no `matrix-auth.jpi.disabled` file (or similar) in `$JENKINS_HOME/plugins/`). | If you cannot even log in because of this error, you can disable security in jenkins config file /config.xml.
Search for `<useSecurity>true</useSecurity>` and change the value to `false`. Then restart jenkins from command line and you should be able to login and make change to plugin/auth configurations as suggested in other answers. |
44,691,438 | I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] | It can happen if a newer version of a plugin is incompatible with older version of Jenkins. It's recommended to upgrade Jenkins to latest version.
This is how I do it:
```
ssh jenkins "cd /tmp; wget https://updates.jenkins-ci.org/latest/jenkins.war"
ssh jenkins "cp /usr/share/jenkins/jenkins.war /tmp/jenkins.war.previous.version"
ssh jenkins "sudo systemctl status jenkins"
ssh jenkins "sudo cp /tmp/jenkins.war /usr/share/jenkins/"
ssh jenkins "sudo systemctl restart jenkins"
``` | usually, this error ours when there is a mismatch between Jenkins Version and Plugins version.
Best solution is always to keep updated Jenkins and plugin or installed appropriate versions of jenkins according to the Jenkins version.
For centos, Redhat, amazon Linux follow the below steps.
```
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
yum update Jenkins.
```
For an ubuntu machine, you can follow the steps given by hit3k.
```
cd /tmp; wget https://updates.jenkins-ci.org/latest/jenkins.war
cp /usr/share/jenkins/jenkins.war /tmp/jenkins.war.previous.version
sudo systemctl status jenkins
sudo cp /tmp/jenkins.war /usr/share/jenkins/
sudo systemctl restart jenkins
``` |
44,691,438 | I was trying to restore jenkins on a new machine by tacking up backup from old machine . I replaced the jenkins home directory of new machine from old one. When i launch jenkins it gives me this error.
```
Caused: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
```
There is also
```
Caused: hudson.util.HudsonFailedToLoad
Caused: org.jvnet.hudson.reactor.ReactorException
```
Debug info is
---- Debugging information ----
```
message : hudson.security.ProjectMatrixAuthorizationStrategy
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message : hudson.security.ProjectMatrixAuthorizationStrategy
class : hudson.model.Hudson
required-type : hudson.model.Hudson
converter-type : hudson.util.RobustReflectionConverter
path : /hudson/authorizationStrategy
line number : 11
version : not available
-------------------------------
```
This is what my config.xml look like
```
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Hudson.Administer:visha</permission>
</authorizationStrategy>
```
Can someone please help ? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44691438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2991413/"
] | If you cannot even log in because of this error, you can disable security in jenkins config file /config.xml.
Search for `<useSecurity>true</useSecurity>` and change the value to `false`. Then restart jenkins from command line and you should be able to login and make change to plugin/auth configurations as suggested in other answers. | usually, this error ours when there is a mismatch between Jenkins Version and Plugins version.
Best solution is always to keep updated Jenkins and plugin or installed appropriate versions of jenkins according to the Jenkins version.
For centos, Redhat, amazon Linux follow the below steps.
```
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
yum update Jenkins.
```
For an ubuntu machine, you can follow the steps given by hit3k.
```
cd /tmp; wget https://updates.jenkins-ci.org/latest/jenkins.war
cp /usr/share/jenkins/jenkins.war /tmp/jenkins.war.previous.version
sudo systemctl status jenkins
sudo cp /tmp/jenkins.war /usr/share/jenkins/
sudo systemctl restart jenkins
``` |
52,205,476 | **Now Playing Activity**
```js
public class NowPlayingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nowplaying);
// The buttons on the screen
ImageButton playButton = findViewById(R.id.playButton);
ImageButton previousSongButton = findViewById(R.id.previousButton);
ImageButton nextSongButton = findViewById(R.id.nextButton);
ImageButton repeatButton = findViewById(R.id.repeatButton);
ImageButton shuffleButton = findViewById(R.id.shuffleButton);
Button albumsMenu = (Button) findViewById(R.id.albumsMenu);
Button artistsMenu = (Button) findViewById(R.id.artistsMenu);
albumsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent albumsIntent = new Intent(NowPlayingActivity.this, AlbumsActivity.class);
startActivity(albumsIntent);
}
});
artistsMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ArtistIntent = new Intent(NowPlayingActivity.this, ArtistsActivity.class);
startActivity(ArtistIntent);
}
});
}
}
```
```html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF7DA"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/nowplaying"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FD8E09"
android:gravity="center_horizontal"
android:text="Now Playing" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Now Playing"
android:src="@drawable/playicon" />
<TextView
android:id="@+id/artists"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#379237"
android:gravity="center_horizontal"
android:text="Artists" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Artists"
android:src="@drawable/artisticon" />
<TextView
android:id="@+id/albums"
style="@style/CategoryStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#8800A0"
android:gravity="center_horizontal"
android:text="Albums" />
<ImageView
style="@style/CategoryIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Albums"
android:src="@drawable/albumicon" />
</LinearLayout>
```
**When I click on the error it takes me to nowPlaying.setOnClickListener(new View.OnClickListener() but I'm not sure what to do.**
```js
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the View that shows the now playing category
LinearLayout nowPlaying = findViewById(R.id.activity_nowPlaying);
//Find the View that shows the artists category
LinearLayout artists = findViewById(R.id.activity_artists);
//Find the View that shows the albums category
LinearLayout albums = findViewById(R.id.activity_albums);
nowPlaying.setOnClickListener(new View.OnClickListener() {
// This method will be executed when the now playing category is clicked on.
@Override
public void onClick(View view) {
// Create a new intent to open the {@link NowPlayingActivity}
Intent nowPlayingIntent = new Intent(MainActivity.this, NowPlayingActivity.class);
// Start the new activity
startActivity(nowPlayingIntent);
}
});
```
```html
**
This is the error I'm receiving.
-----------
**
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.alexaquinones.musicalstructure.MainActivity.onCreate(MainActivity.java:24)
``` | 2018/09/06 | [
"https://Stackoverflow.com/questions/52205476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10256304/"
] | Installing @types/moment as a dev dependency solved it for me. | try to install Moment.js:
npm i moment |
20,764,375 | I have 2 videos. Each 7 seconds long. I need the top video to fadeout after it is halfway done playing, revealing the bottom video for 3.5 seconds, then fading back in, in an infinite loop.
I am unable to get the video to fade and not sure how to make it start at a specific time. This is what I have:
JS
```
<script type="text/javascript">
video.addEventListener('ended', function () {
$('#vid').addClass('hide');
$('video').delay(100).fadeOut();
}, false);
video.play();
var vid1=document.getElementById("video-loop");
vid1.addEventListener(function () {
$('video').delay(100);
}, false);
vid1.play();
</script>
```
HTML
```
<div id="#video">
<video id="vid" autoplay preload="auto">
<source src="videos/interactive2_3.mp4.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>
<video id="video-loop" preload="auto" loop>
<source src="videos/interactive2-loop.mp4.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>
</div>
``` | 2013/12/24 | [
"https://Stackoverflow.com/questions/20764375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2482256/"
] | to track the time in the video and make decisions based on that, you'll want to track the `timeupdate` event on the video, and then use the `currentTime` property to decide what to do.
This fragment will allow you to swap one video out at the 2.5s mark, play the second for 3.5s then swap back to the first ... you can elaborate based on the timer events to make it more flexible for your scenario...
```
<script>
var showing = 1 // which of the two videos are showing at the moment
var video1 = document.getElementById('vid');
var video2 = document.getElementById('video-loop');
video1.addEventListener('timeupdate',function(e){
if ((showing == 1) && (video1.currentTime > 2.5)) {
showing=2
video1.pause()
$('#vid').delay(100).fadeOut();
$('#video-loop').delay(100).fadeIn();
video2.play()
}
});
video2.addEventListener('timeupdate',function(e){
if ((showing == 2) && (video2.currentTime > 3.5)) {
video2.pause()
$('#video-loop').delay(100).fadeOut();
$('#vid').delay(100).fadeIn();
video1.play()
}
});
</script>
``` | ```
<div>Iteration: <span id="iteration"></span></div>
<video id="video-background" autoplay="" muted="" controls>
<source src="https://res.cloudinary.com/video/upload/ac_none,q_60/bgvid.mp4" type="video/mp4">
</video><div>Iteration: <span id="iteration"></span></div>
var iterations = 1;
var flag = false;
document.getElementById('iteration').innerText = iterations;
var myVideo = document.getElementById('video-background');
myVideo.addEventListener('ended', function () {
alert('end');
if (iterations < 2) {
this.currentTime = 0;
this.play();
iterations ++;
document.getElementById('iteration').innerText = iterations;
} else {
flag = true;
this.play();
}
}, false);
myVideo.addEventListener('timeupdate', function () {
if (flag == true) {
console.log(this.currentTime);
if (this.currentTime > 5.5) {
console.log(this.currentTime);
this.pause();
}
}
}, false);
// Please note that loop attribute should not be there in video element in order for the 'ended' event to work in ie and firefox
``` |
237,697 | In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question. | 2022/11/06 | [
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] | Impossibility 1: Ring magnets as depicted
-----------------------------------------
All magnetic fields need to be closed curves. The ring magnet as depicted would require a magnetic source at the very center of the ring, which is forbidden.
The problem can be alleviated by placing many magnets on the outside in the correct orientation but with small wedge-shaped gaps between every two magnets. Technically you only need a few (1-3) long magnet rail tracks, which allows orientation control of the payload and considerably reduces construction costs.
It's by the way better to use permanent magnets *attracting* to the track than repulsing from it, that way the payload can not *overturn* and slip out of the magnetic track. A simple set of ring motors could be used to give the capsule any wanted orientation by rotating the magnet tracks around the tube or their receptors on the payload - even allowing to simulate *rifling* to achieve spin stabilization.
Impossibility 2: only permanent magnet accelerator
--------------------------------------------------
The maglev track is perfect to get minimal drag, and as explained above, does work. However, it does not accelerate on its own - it simply provides a means to have extremely low friction to the guide rail.
If you take a slice from real Maglev trains, a set of coils inside the train car is electrified to create repulsing forces in some areas and attracting in others, which all in all accelerate the vehicle.
Impossibility 3: architectural constraints
------------------------------------------
You have a $\pu{30 km}$ pipe extending for up to about $\pu{22 km}$ above the point we leave the tip of Mt Everest. It is supported on stilts up to $\pu{25 km}$ long, assuming that the highland below is *just* about $\pu{5 km}$ above sea level. That is well beyond what **any** material can do. Steel is typically blessed with allowing $\pu{25000 psi}\ (\pu{172 MPa})$ compressible force before failure, which is [6 times that of concrete](https://blog.redguard.com/compressive-strength-of-steel). But well-made steel can get better, up to $\pu{250 MPa}$ are possible. That's $\pu{250 000 000 N/m² }$. Above that, the column collapses under its own weight
But the column itself weighs a lot: assuming we have a crossection of one square meter of steel, then each meter height (and thus each cubic-meter) weighs 7.85 tons $(\pu{7850 kg})$, exerting roughly $\pu{78500 N}$ each. At which point *stacking bricks* makes the lowest one crumble? Well... incidentally the compressive strength would itself allow for being 3184.71 meters tall. so roundabout 3 Kilometers. Or at **best** a tiny fraction of the pillar length needed to support the tube - and we haven't even assigned any weight to that.
The pipe goes up to maybe 10 kilometers... and then it breaks down, having to end as it can't be supported with any material or construction.
Exotic materials, such as Graphene fare much worse: Graphene's compressive strength is [only](https://aip.scitation.org/doi/pdf/10.1063/1.5020547) $\pu{8.5 MPa}$ under normal conditions but could be driven to $\pu{28.8 MPa}$ at $\pu{2267 kg/m³}$. As a result for a maximum pillar height of Graphene is just $\pu{375 m}$ or, with the special tricks,
$\pu{1270 m}$
A 10-inch graphene rod fares exactly the same: It has $\pu{78.5 in²}$ or almost exactly $\pu{0.05 m²}$ area. Let's keep that. It can sustain the same pressure before collapsing, so the lowest piece can carry $\pu{0.05m²}\times \pu{28.8 kg/m²}$ load. Each Meter height weighs in at $\pu{0.05m³}\times \pu{2267kg/m³}$. As a result, we get exactly the same height for a stable column as before: 375 to $\pu{1270 m}$. | >
> Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?
>
>
>
**Two Big Flaws**
1. How does it stay up?
2. How come it's so fast?
You claim the graphite stilts will support the track no problem. How are they so dang strong? I feel safe to assume that no known material is strong enough to support a 30km tall 500km railway on stilts alone. The Earth moves and the air moves.
I suggest you replace the stilts with a 500km tall solid unobtanium pyramid.
On second thoughts why do we need supports at all? Just point Space Tube sideways. You need to launch things sideways to get to orbit anyway. And launching in a straight line in any direction will get you into space:
[](https://i.stack.imgur.com/EfAVL.png)
You will need some supports if you desire a perfectly straight tube. But it is not obvious why that would help. Just accelerate along the Earth's curvature instead of a straight line. Of course the image is only accurate if the Earth is round. If your Earth is flat then your Space Ramp Tube is a good idea.
The second problem, is how you claim the projectile exits at 40km/s. But how does it go so dang fast? You explain how it is levitated but not how it is accelerated. Maglev stuff, sure, there are real Maglev trains and they work somehow. But those bad boys go only 100ish m/s. That's much slower than Space Tube. Maybe Space Tube uses Particle accelerator tech to go fast. Those things are lined with magnets too. And they go very fast indeed. But particles are famously smaller than spaceships.
There is also this:
>
> Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
>
>
>
You give this problem but don't explain your solution. It sounds like Space Tube Mk. II is just as vulnerable to burning up as Space Tube Mk I. To fix this I suggest the inside of the tube have all the air pumped out. |
237,697 | In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question. | 2022/11/06 | [
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] | Impossibility 1: Ring magnets as depicted
-----------------------------------------
All magnetic fields need to be closed curves. The ring magnet as depicted would require a magnetic source at the very center of the ring, which is forbidden.
The problem can be alleviated by placing many magnets on the outside in the correct orientation but with small wedge-shaped gaps between every two magnets. Technically you only need a few (1-3) long magnet rail tracks, which allows orientation control of the payload and considerably reduces construction costs.
It's by the way better to use permanent magnets *attracting* to the track than repulsing from it, that way the payload can not *overturn* and slip out of the magnetic track. A simple set of ring motors could be used to give the capsule any wanted orientation by rotating the magnet tracks around the tube or their receptors on the payload - even allowing to simulate *rifling* to achieve spin stabilization.
Impossibility 2: only permanent magnet accelerator
--------------------------------------------------
The maglev track is perfect to get minimal drag, and as explained above, does work. However, it does not accelerate on its own - it simply provides a means to have extremely low friction to the guide rail.
If you take a slice from real Maglev trains, a set of coils inside the train car is electrified to create repulsing forces in some areas and attracting in others, which all in all accelerate the vehicle.
Impossibility 3: architectural constraints
------------------------------------------
You have a $\pu{30 km}$ pipe extending for up to about $\pu{22 km}$ above the point we leave the tip of Mt Everest. It is supported on stilts up to $\pu{25 km}$ long, assuming that the highland below is *just* about $\pu{5 km}$ above sea level. That is well beyond what **any** material can do. Steel is typically blessed with allowing $\pu{25000 psi}\ (\pu{172 MPa})$ compressible force before failure, which is [6 times that of concrete](https://blog.redguard.com/compressive-strength-of-steel). But well-made steel can get better, up to $\pu{250 MPa}$ are possible. That's $\pu{250 000 000 N/m² }$. Above that, the column collapses under its own weight
But the column itself weighs a lot: assuming we have a crossection of one square meter of steel, then each meter height (and thus each cubic-meter) weighs 7.85 tons $(\pu{7850 kg})$, exerting roughly $\pu{78500 N}$ each. At which point *stacking bricks* makes the lowest one crumble? Well... incidentally the compressive strength would itself allow for being 3184.71 meters tall. so roundabout 3 Kilometers. Or at **best** a tiny fraction of the pillar length needed to support the tube - and we haven't even assigned any weight to that.
The pipe goes up to maybe 10 kilometers... and then it breaks down, having to end as it can't be supported with any material or construction.
Exotic materials, such as Graphene fare much worse: Graphene's compressive strength is [only](https://aip.scitation.org/doi/pdf/10.1063/1.5020547) $\pu{8.5 MPa}$ under normal conditions but could be driven to $\pu{28.8 MPa}$ at $\pu{2267 kg/m³}$. As a result for a maximum pillar height of Graphene is just $\pu{375 m}$ or, with the special tricks,
$\pu{1270 m}$
A 10-inch graphene rod fares exactly the same: It has $\pu{78.5 in²}$ or almost exactly $\pu{0.05 m²}$ area. Let's keep that. It can sustain the same pressure before collapsing, so the lowest piece can carry $\pu{0.05m²}\times \pu{28.8 kg/m²}$ load. Each Meter height weighs in at $\pu{0.05m³}\times \pu{2267kg/m³}$. As a result, we get exactly the same height for a stable column as before: 375 to $\pu{1270 m}$. | Ditch Everest. Switch to Chimborazo in Ecuador. Two reasons:
1. Because it is closer to the equator, it's peak is actually farther from the center of the Earth.
2. Because it is closer to the equator, you get more of a boost from rotation of the Earth. Everest at 29.59 degrees North loses almost 14% of the rotational velocity.
So launching from Chimborazo gets you additional altitude, and about 223 km/hr extra launch velocity.
The structure you have envisioned is massively beyond our current tech. At both ends.
Digging a slanted tunnel roughly 100 km long is getting to silly proportions. The [deepest mine right now is](https://en.wikipedia.org/wiki/List_of_deepest_mines) 4 km deep. This is getting pretty close to the limits of our tech right now.
The truss you envision holding the launch tube is grotesquely beyond what we can build now.
The launch energy needs to be supplied. You need electromagnets up the length of the tube. The energy they need to supply, assuming a constant acceleration, increases as the speed increases. So you need to run gargantuan power cables up the structure as well.
You might get someplace by forgetting the extension above and below the mountain. You could have some sort of electromagnetic launcher that pushed a sled that carried your orbiter. Assuming a 50 km track and only 1g, you get 1 km/s in 100 seconds, pretty close to Mach 1, up the mountain. This is fast enough that the sled could detach and the orbiter take over its own burn. The first 25 km or so of the track would be level then curve up the mountain.
There are lots of variations on this. For example, the sled could also be a rocket motor that acted as a first stage. Or you could amp up the acceleration up the hill. At 4 g you get pretty close to Mach 2, in 25 seconds.
You can get an idea of what you are gaining from launching from the mountain. At 4g you are basically getting the first 25 seconds of rocket power from your launch sled. Suppose you were able to build the truss and extend the ramp another 50 km. This gives you only about another 10 seconds. The part on the mountain might be worth it. Building this currently-impossible truss seems to be a diminishing return. |
237,697 | In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question. | 2022/11/06 | [
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] | Though I don't see any reference to it in this question or your previous one, you should probably read about [StarTram](https://en.wikipedia.org/wiki/StarTram), because it was a project that considers many of the same things you're looking at. The StarTram authors used to have all their interesting stuff available for free on their website, but the main ebook is now paid-only.
StarTram uses an evacuated tube with a "conventional" superconducting electromagnetic accelerator.
Here's a diagram that looks a little like your own:
[](https://i.stack.imgur.com/xvRna.png)
The Gen 1 design, which has the muzzle of the accelerator at the top of a suitable mountain, is intended for cargo only as it has a 30G peak acceleration and a 6-12G peak decelleration when it hits the atmosphere upon exiting the muzzle. It uses a clever [plasma window](https://en.wikipedia.org/wiki/Plasma_window) to maintain vacuum in the tube but still allow the projectile to egress the accelerator. It comes out at near orbital velocity, requiring some small boost rockets (<1km/s delta-V) to finish the job.
The Gen 2 design uses a somewhat gonzo electromagnetic repulsion architecture using massive supercondcting cables. I won't regurgitate the exact details of this here, but suffice to say that the authors were well aware that massive scaffolding structures and balloons can't work. Whether or not their solution would is something I won't consider here.
[](https://i.stack.imgur.com/FwDdt.png)
(image credit [NASA](https://en.wikipedia.org/wiki/File:Startramgeneration2.jpg))
>
> The high altitude evacuated launch tube has a set of high current superconducting (SC) cables that magnetically interact with a second set of high current SC cables on the surface beneath to create a magnet levitation force of several metric tons per meter of tube length. The levitation force is greater than the weight of the launch tube plus its SC cables and tethers, resulting in a net upward force on the structure. In turn, the levitated structure is anchored to the ground by a network of high tensile strength, lightweight Kevlar or Spectra tethers
>
>
>
So, now I've shown you the competition, lets look at the details of your design.
1. Permanent magnet accelerator
I can't see that this could ever work, even if you could get powerful enough permanent magnets (you probably can't) in sufficient quantity (you probably can't) that are light enough for your 30km high suspended section to work (almost certainly no). Just use a superconducting electromagnetic accelerator... it is something that could conceivably be built with present-day technology, after all.
2. Giant graphene rods
Graphene has excellent tensile strength, but its compressive strength is less exciting, and a 30km tall tower that needs to withstand launch stresses and weather patterns is a fearsome undertaking to say the least. Other answers already go into more detail on this matter, but if you want a structure this tall then it needs to be suspended by some other means. I won't go into detail on this here, but maybe you could ask another question?
3. 60km/s muzzle velocity
Brownlee lamented the commonly repeated story of the Pascal B test, because it resulted in a lot of people mocking his terrible understanding of aerodynamics. He just estimated the speed of the cap, but made no claims about it getting into space, and assumed it was vaporized in the lower atmosphere.
Anyway, that niggle aside, I'm not sure you've necessarily consider the effects of hitting the atmosphere, even at 30km, at that sort of speed. Sure, the projectile will not be in the atmosphere for long, but not being there long enough to slow down below orbital velocity or burn up is not the same as being safe for the cargo. The initial forces on leaving the muzzle of the accelerator are too difficult for me to calculate, but I'm pretty certain they'll be extremely unpleasant if not outright dangerous.
I'm not going to commit to these figures, but at an atmospheric density of ~0.01841kg/m3 ([wolfram alpha](https://www.wolframalpha.com/input?i=density%20of%20air%20at%2030000m)), a vehicle with a drag coefficient of 0.09 (from the StarTram design) and travelling at 60 km/s is going to experience a drag force of the order of 10MN. A mass of 40 tonnes (from the StarTram design) will therefore experience a (probably transient) acceleration of ~24 gravities. That is a potentially aorta-dissecting amount of acceleration to apply to a human cargo, especiially given how rapidly it will be applied. For more reading on the subject, have a read of some of the many papers on the subject... here's one I found with a minute or two of searching: [Human Tolerance to Rapidly Applied Accelerations](https://ntrs.nasa.gov/citations/19980228043).
I might be quite wrong here, but you're talking about a speed far too high to be safe even in a fairly thin atmosphere.
>
> Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?
>
>
>
Honestly, your design seems to be a combination of overkill and, uh, not-enough-kill.
Lets gloss over whether or not the passengers of your craft will die instantly as their coffin leaves the muzzle of your death-cannon for now (but I suspect that the flight is likely to be physically traumatic if not fatal) and consider the other aspects of your idea.
The StarTram design dealt with merely surface-to-orbit construction, with the reasonable assumption that if you've cracked the difficult issue of getting out of the Earth's gravity well then you can built much more appropriate interplanetary infrastructure in space.
Thing is, your fixed accelerator makes it very difficult to aim... you get to fiddle with muzzle velocity to some degree, but everything else is limited by time of year and time of day. This in turn limits the number of targets you can reach in a convenient timespan. From space though, you have much more flexibility.
Even aside from that is the issue of safety... a suborbital flight that requires active boosting into orbit can fail safe (assuming your launch vehicles can safely re-enter, which you should ensure) because you re-enter and can land. Your capsule on the other hand is not only going much faster than terrestrial escape velocity, but can easily exceed solar escape velocity! At Earth's orbit, solar escape velocity is ~42km/s. Earth's own orbital velocity is 30km/s, which means unless you're shooting in a retrograde direction then any problems mean you shoot out into interstellar space, and rescue is likely to be challenging.
Don't be so impatient. You can launch your interplanetary vehicle into orbit and renezvous with a secondary propulsion system (eg. laser ablative, or plasma-push magsail or whatever) to hoof you in the right direction at the right time. The additional wait isn't going to be more than an hour or two, and the additional safety and considerable reduction in your accelerator size, cost and complexity will be well worth the tradeoff.
(Note that you already have to have some kind of mechanism to impart a delta-V of tens of kilometers per second to your capsule, because you have to slow it down at its destination! As this is a required ability anyway, you may as well use it for the boost phase as well as the brake phase and save yourself a lot of hassle) | >
> Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?
>
>
>
**Two Big Flaws**
1. How does it stay up?
2. How come it's so fast?
You claim the graphite stilts will support the track no problem. How are they so dang strong? I feel safe to assume that no known material is strong enough to support a 30km tall 500km railway on stilts alone. The Earth moves and the air moves.
I suggest you replace the stilts with a 500km tall solid unobtanium pyramid.
On second thoughts why do we need supports at all? Just point Space Tube sideways. You need to launch things sideways to get to orbit anyway. And launching in a straight line in any direction will get you into space:
[](https://i.stack.imgur.com/EfAVL.png)
You will need some supports if you desire a perfectly straight tube. But it is not obvious why that would help. Just accelerate along the Earth's curvature instead of a straight line. Of course the image is only accurate if the Earth is round. If your Earth is flat then your Space Ramp Tube is a good idea.
The second problem, is how you claim the projectile exits at 40km/s. But how does it go so dang fast? You explain how it is levitated but not how it is accelerated. Maglev stuff, sure, there are real Maglev trains and they work somehow. But those bad boys go only 100ish m/s. That's much slower than Space Tube. Maybe Space Tube uses Particle accelerator tech to go fast. Those things are lined with magnets too. And they go very fast indeed. But particles are famously smaller than spaceships.
There is also this:
>
> Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
>
>
>
You give this problem but don't explain your solution. It sounds like Space Tube Mk. II is just as vulnerable to burning up as Space Tube Mk I. To fix this I suggest the inside of the tube have all the air pumped out. |
237,697 | In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question. | 2022/11/06 | [
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] | >
> Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?
>
>
>
**Two Big Flaws**
1. How does it stay up?
2. How come it's so fast?
You claim the graphite stilts will support the track no problem. How are they so dang strong? I feel safe to assume that no known material is strong enough to support a 30km tall 500km railway on stilts alone. The Earth moves and the air moves.
I suggest you replace the stilts with a 500km tall solid unobtanium pyramid.
On second thoughts why do we need supports at all? Just point Space Tube sideways. You need to launch things sideways to get to orbit anyway. And launching in a straight line in any direction will get you into space:
[](https://i.stack.imgur.com/EfAVL.png)
You will need some supports if you desire a perfectly straight tube. But it is not obvious why that would help. Just accelerate along the Earth's curvature instead of a straight line. Of course the image is only accurate if the Earth is round. If your Earth is flat then your Space Ramp Tube is a good idea.
The second problem, is how you claim the projectile exits at 40km/s. But how does it go so dang fast? You explain how it is levitated but not how it is accelerated. Maglev stuff, sure, there are real Maglev trains and they work somehow. But those bad boys go only 100ish m/s. That's much slower than Space Tube. Maybe Space Tube uses Particle accelerator tech to go fast. Those things are lined with magnets too. And they go very fast indeed. But particles are famously smaller than spaceships.
There is also this:
>
> Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
>
>
>
You give this problem but don't explain your solution. It sounds like Space Tube Mk. II is just as vulnerable to burning up as Space Tube Mk I. To fix this I suggest the inside of the tube have all the air pumped out. | Ditch Everest. Switch to Chimborazo in Ecuador. Two reasons:
1. Because it is closer to the equator, it's peak is actually farther from the center of the Earth.
2. Because it is closer to the equator, you get more of a boost from rotation of the Earth. Everest at 29.59 degrees North loses almost 14% of the rotational velocity.
So launching from Chimborazo gets you additional altitude, and about 223 km/hr extra launch velocity.
The structure you have envisioned is massively beyond our current tech. At both ends.
Digging a slanted tunnel roughly 100 km long is getting to silly proportions. The [deepest mine right now is](https://en.wikipedia.org/wiki/List_of_deepest_mines) 4 km deep. This is getting pretty close to the limits of our tech right now.
The truss you envision holding the launch tube is grotesquely beyond what we can build now.
The launch energy needs to be supplied. You need electromagnets up the length of the tube. The energy they need to supply, assuming a constant acceleration, increases as the speed increases. So you need to run gargantuan power cables up the structure as well.
You might get someplace by forgetting the extension above and below the mountain. You could have some sort of electromagnetic launcher that pushed a sled that carried your orbiter. Assuming a 50 km track and only 1g, you get 1 km/s in 100 seconds, pretty close to Mach 1, up the mountain. This is fast enough that the sled could detach and the orbiter take over its own burn. The first 25 km or so of the track would be level then curve up the mountain.
There are lots of variations on this. For example, the sled could also be a rocket motor that acted as a first stage. Or you could amp up the acceleration up the hill. At 4 g you get pretty close to Mach 2, in 25 seconds.
You can get an idea of what you are gaining from launching from the mountain. At 4g you are basically getting the first 25 seconds of rocket power from your launch sled. Suppose you were able to build the truss and extend the ramp another 50 km. This gives you only about another 10 seconds. The part on the mountain might be worth it. Building this currently-impossible truss seems to be a diminishing return. |
237,697 | In my [previous question](https://worldbuilding.stackexchange.com/questions/234454/i-designed-a-maglev-space-propulsion-tube-on-mt-everest-do-you-see-any-issues), I was discussing about the possibility of using a mass-driver on Mt. Everest, to propel payloads to space, and reduce the amount of fuel needed (RIP bulky rockets). A diagram below of my former design:[](https://i.stack.imgur.com/g18Ua.png)
However, there was a ton of issues with this design:
* Dangling a tube from a balloon is a really risky idea as the balloon can be torn apart by the wind and jet-stream on top of Mt. Everest. This could result in collapse of the structure. Firing a payload is even worse, as a tube that is dangling could suddenly jerk and tear the balloon cord, with catastrophic consequences.
* The Himalayas are an earthquake zone. The structure would break apart during earthquakes.
* Even if you managed not to exceed 3-4gs acceleration, then the curve above the ground could cause a dramatic acceleration spike, this can lead to serious consequences for astronauts.
* Mass drivers may work on airless planets like Moon and Mercury, but on Earth, the air is thick enough to burn the payload long before it attained orbit.
So, after a lot of thoughts, and ideas, I came up with a grander and more realistic design for the **Mt. Everest Maglev Accelerator**, this time with no ridiculous balloons, or spikes. So here is the design and its principles.
Design
=======
* This design consists of a large tube that is erected on giant graphene rods about 10 inches wide in diameter. This provides immense strength, as graphene is strong enough not to crush its base and be rigid.
* This design is a **ring-gun magnet** type accelerator. This means that the magnets are placed in rings that have the same poles facing the track. The interior of the tube would look sort of like this:[](https://i.stack.imgur.com/B7wYE.png)
* Cross-section of propulsion tube.[](https://i.stack.imgur.com/FIksn.png)
* The ring-magnets are still permanent and have a greater strength of 10 teslas. They are not electromagnets.
* The payload itself is attached with ring-magnets with like poles, i.e. south pole facing outwards. This generates strong repulsion that propel the rocket at high speeds. The ring-magnet themselves are reusable, they are detached from the payload, and fall back to earth, whereas the payload will gain even more momentum, due to conservation of I-can't-remember, as the ring-magnets are detached.
* The tube viewed above from ground, looks sort of like this. (Apologies, I am crappy at photoshop, so this is the best depiction I can make). It is about 30 km tall, and stretches into the lower stratosphere.
[](https://i.stack.imgur.com/LxKJ0.jpg)
* The tube's actual length is however astounding. It is about 500 km long, and is mostly built underground. It is made of titanium in order to withstand the stress and pressure from the weight of the mountains above it, and withstands earthquakes.
* The curve of the tube is gradual instead of sudden, as to prevent "jerks"(i.e. sudden high-Gs)
Principles
===========
The aim of the ~~mass driver~~ Maglev Accelerator is to make it travel so fast, that it won't have time to burn up in the atmosphere. I mean literally fast. The payload's velocity upon exiting the barrel is about 60-70 km/s (yes, Kms per second). The idea came from the [Plumbbob Pascal-B Borecap](https://www.businessinsider.com/fastest-object-robert-brownlee-2016-2?IR=T#since-then-brownlees-concludedit-was-going-too-fast-to-burn-up-before-reaching-outer-spaceafter-i-was-in-the-business-and-did-my-own-missile-launches-he-said-i-realized-that-that-piece-of-iron-didnt-have-time-to-burn-all-the-way-up-in-the-atmosphere-14), where it was theorised that it was moving so fast that it had literally no time to burn up in the atmosphere before reaching space.
Although this would mean that the payload is moving too fast for it to be able to remain in orbit (about 6x Earth's Escape Velocity), that is not a problem as this accelerator is meant for interplanetary journey, such as travelling to Saturn, Mars and Moon. I will discuss a **orbit-grade accelerator** in a future question, but for now, this accelerator cannot be used for orbiting payloads.
The reason why I am using Mt. Everest and not Chimborazo for the accelerator, is that Mt. Everest is actually closer to space than Chimborazo is. This may seem odd, but Mt. Everest's 9km height makes it closer to space than Chimborazo's 6km is. Although Earth being oblate makes Chimborazo cheat and get "taller" technically, Everest is still the victor, as the atmosphere is oblate like the Earth. The air pressure at the top of Mt. Chimborazo is just that at sea-level, whereas the air at the top of Mt. Everest is literally a partial vacuum, with just over a third that at sea-level. Everest's great height also provides structural support to the colossal accelerator to reach the required velocity.
**Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?**
Clarifications:
* No, this accelerator is absolutely not used for orbital journeys. This accelerator is used for interplanetary journeys, such as Earth-Mars, or Earth-Saturn journeys
Note: I'd like to avoid extended discussions in comments, as I have created [a chat room](https://chat.stackexchange.com/rooms/140455/mt-everest-maglev-accelerator-v2) for this question. | 2022/11/06 | [
"https://worldbuilding.stackexchange.com/questions/237697",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/97694/"
] | Though I don't see any reference to it in this question or your previous one, you should probably read about [StarTram](https://en.wikipedia.org/wiki/StarTram), because it was a project that considers many of the same things you're looking at. The StarTram authors used to have all their interesting stuff available for free on their website, but the main ebook is now paid-only.
StarTram uses an evacuated tube with a "conventional" superconducting electromagnetic accelerator.
Here's a diagram that looks a little like your own:
[](https://i.stack.imgur.com/xvRna.png)
The Gen 1 design, which has the muzzle of the accelerator at the top of a suitable mountain, is intended for cargo only as it has a 30G peak acceleration and a 6-12G peak decelleration when it hits the atmosphere upon exiting the muzzle. It uses a clever [plasma window](https://en.wikipedia.org/wiki/Plasma_window) to maintain vacuum in the tube but still allow the projectile to egress the accelerator. It comes out at near orbital velocity, requiring some small boost rockets (<1km/s delta-V) to finish the job.
The Gen 2 design uses a somewhat gonzo electromagnetic repulsion architecture using massive supercondcting cables. I won't regurgitate the exact details of this here, but suffice to say that the authors were well aware that massive scaffolding structures and balloons can't work. Whether or not their solution would is something I won't consider here.
[](https://i.stack.imgur.com/FwDdt.png)
(image credit [NASA](https://en.wikipedia.org/wiki/File:Startramgeneration2.jpg))
>
> The high altitude evacuated launch tube has a set of high current superconducting (SC) cables that magnetically interact with a second set of high current SC cables on the surface beneath to create a magnet levitation force of several metric tons per meter of tube length. The levitation force is greater than the weight of the launch tube plus its SC cables and tethers, resulting in a net upward force on the structure. In turn, the levitated structure is anchored to the ground by a network of high tensile strength, lightweight Kevlar or Spectra tethers
>
>
>
So, now I've shown you the competition, lets look at the details of your design.
1. Permanent magnet accelerator
I can't see that this could ever work, even if you could get powerful enough permanent magnets (you probably can't) in sufficient quantity (you probably can't) that are light enough for your 30km high suspended section to work (almost certainly no). Just use a superconducting electromagnetic accelerator... it is something that could conceivably be built with present-day technology, after all.
2. Giant graphene rods
Graphene has excellent tensile strength, but its compressive strength is less exciting, and a 30km tall tower that needs to withstand launch stresses and weather patterns is a fearsome undertaking to say the least. Other answers already go into more detail on this matter, but if you want a structure this tall then it needs to be suspended by some other means. I won't go into detail on this here, but maybe you could ask another question?
3. 60km/s muzzle velocity
Brownlee lamented the commonly repeated story of the Pascal B test, because it resulted in a lot of people mocking his terrible understanding of aerodynamics. He just estimated the speed of the cap, but made no claims about it getting into space, and assumed it was vaporized in the lower atmosphere.
Anyway, that niggle aside, I'm not sure you've necessarily consider the effects of hitting the atmosphere, even at 30km, at that sort of speed. Sure, the projectile will not be in the atmosphere for long, but not being there long enough to slow down below orbital velocity or burn up is not the same as being safe for the cargo. The initial forces on leaving the muzzle of the accelerator are too difficult for me to calculate, but I'm pretty certain they'll be extremely unpleasant if not outright dangerous.
I'm not going to commit to these figures, but at an atmospheric density of ~0.01841kg/m3 ([wolfram alpha](https://www.wolframalpha.com/input?i=density%20of%20air%20at%2030000m)), a vehicle with a drag coefficient of 0.09 (from the StarTram design) and travelling at 60 km/s is going to experience a drag force of the order of 10MN. A mass of 40 tonnes (from the StarTram design) will therefore experience a (probably transient) acceleration of ~24 gravities. That is a potentially aorta-dissecting amount of acceleration to apply to a human cargo, especiially given how rapidly it will be applied. For more reading on the subject, have a read of some of the many papers on the subject... here's one I found with a minute or two of searching: [Human Tolerance to Rapidly Applied Accelerations](https://ntrs.nasa.gov/citations/19980228043).
I might be quite wrong here, but you're talking about a speed far too high to be safe even in a fairly thin atmosphere.
>
> Is this design more better for propelling payloads/passengers to space? If no, then what flaws do I have to fix?
>
>
>
Honestly, your design seems to be a combination of overkill and, uh, not-enough-kill.
Lets gloss over whether or not the passengers of your craft will die instantly as their coffin leaves the muzzle of your death-cannon for now (but I suspect that the flight is likely to be physically traumatic if not fatal) and consider the other aspects of your idea.
The StarTram design dealt with merely surface-to-orbit construction, with the reasonable assumption that if you've cracked the difficult issue of getting out of the Earth's gravity well then you can built much more appropriate interplanetary infrastructure in space.
Thing is, your fixed accelerator makes it very difficult to aim... you get to fiddle with muzzle velocity to some degree, but everything else is limited by time of year and time of day. This in turn limits the number of targets you can reach in a convenient timespan. From space though, you have much more flexibility.
Even aside from that is the issue of safety... a suborbital flight that requires active boosting into orbit can fail safe (assuming your launch vehicles can safely re-enter, which you should ensure) because you re-enter and can land. Your capsule on the other hand is not only going much faster than terrestrial escape velocity, but can easily exceed solar escape velocity! At Earth's orbit, solar escape velocity is ~42km/s. Earth's own orbital velocity is 30km/s, which means unless you're shooting in a retrograde direction then any problems mean you shoot out into interstellar space, and rescue is likely to be challenging.
Don't be so impatient. You can launch your interplanetary vehicle into orbit and renezvous with a secondary propulsion system (eg. laser ablative, or plasma-push magsail or whatever) to hoof you in the right direction at the right time. The additional wait isn't going to be more than an hour or two, and the additional safety and considerable reduction in your accelerator size, cost and complexity will be well worth the tradeoff.
(Note that you already have to have some kind of mechanism to impart a delta-V of tens of kilometers per second to your capsule, because you have to slow it down at its destination! As this is a required ability anyway, you may as well use it for the boost phase as well as the brake phase and save yourself a lot of hassle) | Ditch Everest. Switch to Chimborazo in Ecuador. Two reasons:
1. Because it is closer to the equator, it's peak is actually farther from the center of the Earth.
2. Because it is closer to the equator, you get more of a boost from rotation of the Earth. Everest at 29.59 degrees North loses almost 14% of the rotational velocity.
So launching from Chimborazo gets you additional altitude, and about 223 km/hr extra launch velocity.
The structure you have envisioned is massively beyond our current tech. At both ends.
Digging a slanted tunnel roughly 100 km long is getting to silly proportions. The [deepest mine right now is](https://en.wikipedia.org/wiki/List_of_deepest_mines) 4 km deep. This is getting pretty close to the limits of our tech right now.
The truss you envision holding the launch tube is grotesquely beyond what we can build now.
The launch energy needs to be supplied. You need electromagnets up the length of the tube. The energy they need to supply, assuming a constant acceleration, increases as the speed increases. So you need to run gargantuan power cables up the structure as well.
You might get someplace by forgetting the extension above and below the mountain. You could have some sort of electromagnetic launcher that pushed a sled that carried your orbiter. Assuming a 50 km track and only 1g, you get 1 km/s in 100 seconds, pretty close to Mach 1, up the mountain. This is fast enough that the sled could detach and the orbiter take over its own burn. The first 25 km or so of the track would be level then curve up the mountain.
There are lots of variations on this. For example, the sled could also be a rocket motor that acted as a first stage. Or you could amp up the acceleration up the hill. At 4 g you get pretty close to Mach 2, in 25 seconds.
You can get an idea of what you are gaining from launching from the mountain. At 4g you are basically getting the first 25 seconds of rocket power from your launch sled. Suppose you were able to build the truss and extend the ramp another 50 km. This gives you only about another 10 seconds. The part on the mountain might be worth it. Building this currently-impossible truss seems to be a diminishing return. |
72,630,214 | I have this laravel project, but due the specific version of it's dependencies it need php 8 to run, but I need it to run with php 7.4, is there a way so that we can downgrade the dependencies?
```
....
"require": {
"php": "^8.0.2",
"barryvdh/laravel-debugbar": "^3.6",
"fruitcake/laravel-cors": "^2.0.5",
"guzzlehttp/guzzle": "^7.2",
"intervention/image": "^2.7",
"laravel/framework": "^9.0",
"laravel/sanctum": "^2.14",
"laravel/tinker": "^2.7",
"laravel/ui": "^3.4",
"laravelcollective/html": "^6.3"
},
"require-dev": {
"brianium/paratest": "^6.4",
"fakerphp/faker": "^1.9.1",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"pestphp/pest-plugin-laravel": "^1.2",
"pestphp/pest-plugin-parallel": "^1.0",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
...
```
Note: So far I could only found that manually searching for proper version compatible to php 7.4 and adjust it inside composer.json manually is an option. | 2022/06/15 | [
"https://Stackoverflow.com/questions/72630214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7995302/"
] | Laravel 9 [works only](https://github.com/laravel/framework/blob/9.x/composer.json) on PHP 8, so you can't, unless you are up to downgrading Laravel version too. But installing newer PHP will be faster. | I recently did the same to one of my projects, so I did it like so
1. Backup your project (just C/P it so you have a reserve if something goes wrong);
2. Change the dependencies you need;
3. Delete the vendor folder;
4. I also deleted the `composer.lock` but I think you can actually skip this step;
5. Run `composer install`; |
72,630,214 | I have this laravel project, but due the specific version of it's dependencies it need php 8 to run, but I need it to run with php 7.4, is there a way so that we can downgrade the dependencies?
```
....
"require": {
"php": "^8.0.2",
"barryvdh/laravel-debugbar": "^3.6",
"fruitcake/laravel-cors": "^2.0.5",
"guzzlehttp/guzzle": "^7.2",
"intervention/image": "^2.7",
"laravel/framework": "^9.0",
"laravel/sanctum": "^2.14",
"laravel/tinker": "^2.7",
"laravel/ui": "^3.4",
"laravelcollective/html": "^6.3"
},
"require-dev": {
"brianium/paratest": "^6.4",
"fakerphp/faker": "^1.9.1",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"pestphp/pest-plugin-laravel": "^1.2",
"pestphp/pest-plugin-parallel": "^1.0",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
...
```
Note: So far I could only found that manually searching for proper version compatible to php 7.4 and adjust it inside composer.json manually is an option. | 2022/06/15 | [
"https://Stackoverflow.com/questions/72630214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7995302/"
] | Laravel 9 works on > php8 so you can't downgrade php version to 7.4
[laravel support policy](https://laravel.com/docs/9.x/releases#support-policy) | I recently did the same to one of my projects, so I did it like so
1. Backup your project (just C/P it so you have a reserve if something goes wrong);
2. Change the dependencies you need;
3. Delete the vendor folder;
4. I also deleted the `composer.lock` but I think you can actually skip this step;
5. Run `composer install`; |
279,607 | I've encountered the following notation several times (for example, when discussing Noether's Theorem):
$$\frac{\partial L}{\partial(\partial\_\mu \phi)}$$
And it's not immediately clear to me what this operator $\frac{\partial}{\partial(\partial\_\mu \phi)}$ refers to. Based on the answer to [this question](https://physics.stackexchange.com/questions/88935/derivative-with-respect-to-a-vector-is-a-gradient) and the structure of the covariant derivative, I'm guessing it's just a short-hand for the following operator:
$$\frac{\partial}{\partial(\partial\_\mu \phi)}\equiv\pm(\frac{\partial}{\partial\dot{\phi}},-\frac{\partial}{\partial(\nabla\phi)})$$
I.e.
$$\frac{\partial L}{\partial(\partial\_\mu \phi)}\equiv\pm(\frac{\partial L}{\partial\dot{\phi}},-\frac{\partial L}{\partial(\nabla\phi)})$$
where the $\pm$ comes from your convention for the Minkowski metric.
This is just a guess. Can someone verify, perhaps with a source? | 2016/09/11 | [
"https://physics.stackexchange.com/questions/279607",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/52072/"
] | In field theory usually you have a Lagrangian density function of fields and first derivative of fields or
$$\mathscr{L}(\phi,\partial\_\mu\phi).$$ It is well know that higher derivative of field than first are in some way problematic (Hamiltonian not bounded from below). Field equations follow from Euler-Lagrange equations in which you treat $\phi$ and $\partial\_\mu\phi$ as independent variables. The same happen in Classical Mechanic where your Lagrangian is a function of two variables $q$ and $\dot{q}$. So if you are familiar with $$\frac{\partial L}{\partial\dot{q}}$$ you should become familiar with the field theoretic version. | This article is a useful start.
<https://en.wikipedia.org/wiki/Matrix_calculus>
So throughout the discussions with the kind folks here I think that I've sorted out my confusion, although there wasn't any particular answer that did it. Here I'll analyze my confusion over this notation in case anyone comes to this thread with similar confusions.
The most straightforward answer (IMO) to the question "how do I interpret $\frac{\partial}{\partial(\partial\_\mu\phi)}$?" is to interpret as four distinct operators. I.e.
$$
\frac{\partial L}{\partial(\partial\_\mu\phi)} = [\frac{\partial L}{\partial(\partial\_0\phi)}, \frac{\partial L}{\partial(\partial\_1\phi)}, \frac{\partial L}{\partial(\partial\_2\phi)}, \frac{\partial L}{\partial(\partial\_3\phi)}]
$$
This is essentially what I suggested in my question, but it wasn't obvious to me that it was necessarily correct. The reason I didn't immediately jump to this conclusion when I saw this is that we often (usually?) talk about four-vectors (using the $\mu$ notation $\partial\_\mu$) as composite objects, not as elements of composite objects. For example, whether it's strictly speaking correct or not, I have often seen people refer to $\partial\_\mu$ as the covariant derivative, **not** the $\mu$th element of the covariant derivative. Similarly, I see the notation $x\_\mu = [t,x,y,z]$ and *not* $x\_\mu = [t,x,y,z]\_\mu$, which would more strongly reinforce the idea that $x\_\mu$ is referring to a single but arbitrary element of the collection $[t,x,y,z]$. All of these things encouraged me to think of the term $x\_\mu$ as the entire collection, not as an arbitrary element of said collection. In fact these seem like incompatible interpretations to me. For example, if I interpret these objects as arbitrary elements of said collections, then the term $x\_\nu g\_{\nu\mu}$ (which I have directly seen in work before) is perfectly well-defined, while if I interpret $x\_\nu$ as a vector and $g\_{\nu\mu}$ as a matrix, then it clearly isn't.
However there does seem to be another consistent way to work with these derivatives which **does** abstract out the $\partial\_\mu\phi$ as an entire object, like $x$, for the derivative to be taken with respect to. Sean Carroll briefly describes how to work with this in his book "Spacetime and Geometry". It seems a bit tricky though. He gives the guidelines that, to be careful, to make sure that the "derivitee" is expressed with tensors with subscripts in the same places as the parameter the derivative is with respect to, and to use different subscripts for the two as well. For example,
$$
\frac{\partial}{\partial(\partial\_\xi \phi)} (\frac{1}{2}\partial^\mu\phi\partial\_\mu\phi) = \frac{\partial}{\partial(\partial\_\xi\phi)} (\frac{1}{2}g^{\nu\mu}\partial\_\nu\phi\partial\_\mu\phi) = \frac{1}{2}g^{\nu\mu}(\frac{\partial}{\partial(\partial\_\xi\phi)} (\partial\_\nu\phi)\partial\_\mu\phi + \partial\_\nu\phi \frac{\partial}{\partial(\partial\_\xi\phi)} (\partial\_\mu\phi))
= \frac{1}{2}g^{\nu\mu}(\delta^\xi\_\nu\partial\_\mu\phi + \partial\_\nu\phi \delta^\xi\_\mu) = g^{\mu\nu}\partial\_\nu\phi = \partial^\nu\phi
$$
It seems to me like there might be cases in which this sort of approach breaks down, such as if I ever had a Lagrangian (or other thing that I wanted to take the derivative of) like $L = \nabla^2\phi$. Maybe dealing with that's trivial and I just don't see it, but at this point I'd return to my previous interpretation, as while less compact, it seems a little more trustworthy.
Sorry if I seem a bit thick as I try to grapple with this notation but I've had an unusually hard time working with it and this result was not obvious to me. Let me know if I've still got something wrong in here. Thanks all. |
251,179 | How do I let a few specified non-subscriber email addresses post to an otherwise closed GNU Mailman mailing list? | 2011/03/24 | [
"https://serverfault.com/questions/251179",
"https://serverfault.com",
"https://serverfault.com/users/10813/"
] | I finally figured out how to do this!
Go to the list's Privacy Options, click on Sender Filters, then add the emails to the option called `accept_these_nonmembers`. | I'm not familiar with Mailman itself, but an external workaround would be to give them a dummy address to send to that will auto-forward to the list on their behalf. The dummy account can be a 'Subscriber", and restrict incoming mail to only accept from your desired contributors. |
23,374,985 | I'm using Susy 2 with breakpoint-sass to create my media queries.
It's outputting like:
```
@media (min-width: 1000px)
```
I'm wondering why the screen is missing? It should read:
```
@media screen (min-width: 1000px)
```
I'm trying to add css3-mediaqueries-js which isn't working and I think that might be why. | 2014/04/29 | [
"https://Stackoverflow.com/questions/23374985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823239/"
] | If you want to use `HashSet`, you can override `hashCode` and `equals` to exclusively look at those two members.
Hash code: (`31` is just a prime popularly used for hashing in Java)
```
return 31*id_a + id_b;
```
Equals: (to which you'll obviously need to add `instanceof` checks and type conversion)
```
return id_a == other.id_a && id_b == other.id_b;
```
If you don't want to bind these functions to the class because it's used differently elsewhere, but you still want to use `HashSet`, you could consider:
* Creating an intermediate class to be stored in the set, which will contain your class as a member and implement the above methods appropriately.
* Use your string approach
* Use `HashSet<Point>` - `Point` is not ideal for non-coordinate purposes as the members are simply named `x` and `y`, but I do find it useful to have such a class available, at least for non-production code.
---
Alternatively, if you want to use `TreeSet`, you could have your class implement `Comparable` (overriding `compareTo`) or provide a `Comparator` for the `TreeSet`, both of which would compare primarily on the one id, and secondarily on the other.
The basic idea would look something like this:
```
if (objectA.id_a != objectB.id_a)
return Integer.compare(objectA.id_a, objectB.id_a);
return Integer.compare(objectA.id_b, objectB.id_b);
``` | See this, Here I override the equals() and hashcode() to ensure uniqueness on "name" field of a Person object
```
public class SetObjectEquals {
Person p1 = new Person("harley");
Person p2 = new Person("harley");
public void method1() {
Set<Person> set = new HashSet<Person>();
set.add(p1);
set.add(p2);
System.out.println(set);
}
public static void main(String[] args) {
SetObjectEquals obj = new SetObjectEquals();
obj.method1();
}
}
class Person {
String name;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
Person(String name) {
this.name = name;
}
}
``` |
23,374,985 | I'm using Susy 2 with breakpoint-sass to create my media queries.
It's outputting like:
```
@media (min-width: 1000px)
```
I'm wondering why the screen is missing? It should read:
```
@media screen (min-width: 1000px)
```
I'm trying to add css3-mediaqueries-js which isn't working and I think that might be why. | 2014/04/29 | [
"https://Stackoverflow.com/questions/23374985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823239/"
] | Not sure this is any more efficient or less kludgy. You could keep the original hashcode/equals using the main id (as per your comment) and then create a wrapper that has a hashcode/equals for the composite ida, idb. Maybe over the top for what you need though.
CompositeIdEntity.java
```
public interface CompositeIdEntity {
long getIdA();
long getIdB();
}
```
Entity.java
```
public class Entity implements CompositeIdEntity {
private final long mainId;
private final long idA;
private final long idB;
public Entity(long mainId, long idA, long idB) {
this.mainId = mainId;
this.idA = idA;
this.idB = idB;
}
@Override
public long getIdA() {
return idA;
}
@Override
public long getIdB() {
return idB;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (mainId ^ (mainId >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (mainId != other.mainId)
return false;
return true;
}
@Override
public String toString() {
return "Entity [mainId=" + mainId + ", idA=" + idA + ", idB=" + idB
+ "]";
}
}
```
CompositeIdWrapper.java
```
public class CompositeIdWrapper {
private final CompositeIdEntity compositeIdEntity;
public CompositeIdWrapper(CompositeIdEntity compositeIdEntity) {
this.compositeIdEntity = compositeIdEntity;
}
public CompositeIdEntity getCompositeIdEntity() {
return compositeIdEntity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (int) (compositeIdEntity.getIdA() ^ (compositeIdEntity
.getIdA() >>> 32));
result = prime * result
+ (int) (compositeIdEntity.getIdB() ^ (compositeIdEntity
.getIdB() >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CompositeIdWrapper other = (CompositeIdWrapper) obj;
if (compositeIdEntity.getIdA() != other.compositeIdEntity.getIdA())
return false;
if (compositeIdEntity.getIdB() != other.compositeIdEntity.getIdB())
return false;
return true;
}
}
```
Test.java
```
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Entity en1 = new Entity(0, 123, 456);
Entity en2 = new Entity(1, 123, 456);
Entity en3 = new Entity(2, 123, 789);
Entity en4 = new Entity(2, 123, 456);
Entity en5 = new Entity(1, 123, 789);
// Set based on main id
Set<Entity> mainIdSet = new HashSet<>();
mainIdSet.add(en1);
mainIdSet.add(en2);
mainIdSet.add(en3);
mainIdSet.add(en4);
mainIdSet.add(en5);
System.out.println("Main id set:");
for (Entity entity : mainIdSet) {
System.out.println(entity);
}
// Set based on ida, idb
Set<CompositeIdWrapper> compositeIdSet = new HashSet<>();
compositeIdSet.add(new CompositeIdWrapper(en1));
compositeIdSet.add(new CompositeIdWrapper(en2));
compositeIdSet.add(new CompositeIdWrapper(en3));
compositeIdSet.add(new CompositeIdWrapper(en4));
compositeIdSet.add(new CompositeIdWrapper(en5));
System.out.println("Composite id set:");
for (CompositeIdWrapper wrapped : compositeIdSet) {
System.out.println(wrapped.getCompositeIdEntity());
}
}
}
```
Output
```
Main id set:
Entity [mainId=1, idA=123, idB=456]
Entity [mainId=2, idA=123, idB=789]
Entity [mainId=0, idA=123, idB=456]
Composite id set:
Entity [mainId=0, idA=123, idB=456]
Entity [mainId=2, idA=123, idB=789]
``` | See this, Here I override the equals() and hashcode() to ensure uniqueness on "name" field of a Person object
```
public class SetObjectEquals {
Person p1 = new Person("harley");
Person p2 = new Person("harley");
public void method1() {
Set<Person> set = new HashSet<Person>();
set.add(p1);
set.add(p2);
System.out.println(set);
}
public static void main(String[] args) {
SetObjectEquals obj = new SetObjectEquals();
obj.method1();
}
}
class Person {
String name;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
Person(String name) {
this.name = name;
}
}
``` |
23,374,985 | I'm using Susy 2 with breakpoint-sass to create my media queries.
It's outputting like:
```
@media (min-width: 1000px)
```
I'm wondering why the screen is missing? It should read:
```
@media screen (min-width: 1000px)
```
I'm trying to add css3-mediaqueries-js which isn't working and I think that might be why. | 2014/04/29 | [
"https://Stackoverflow.com/questions/23374985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823239/"
] | If you want to use `HashSet`, you can override `hashCode` and `equals` to exclusively look at those two members.
Hash code: (`31` is just a prime popularly used for hashing in Java)
```
return 31*id_a + id_b;
```
Equals: (to which you'll obviously need to add `instanceof` checks and type conversion)
```
return id_a == other.id_a && id_b == other.id_b;
```
If you don't want to bind these functions to the class because it's used differently elsewhere, but you still want to use `HashSet`, you could consider:
* Creating an intermediate class to be stored in the set, which will contain your class as a member and implement the above methods appropriately.
* Use your string approach
* Use `HashSet<Point>` - `Point` is not ideal for non-coordinate purposes as the members are simply named `x` and `y`, but I do find it useful to have such a class available, at least for non-production code.
---
Alternatively, if you want to use `TreeSet`, you could have your class implement `Comparable` (overriding `compareTo`) or provide a `Comparator` for the `TreeSet`, both of which would compare primarily on the one id, and secondarily on the other.
The basic idea would look something like this:
```
if (objectA.id_a != objectB.id_a)
return Integer.compare(objectA.id_a, objectB.id_a);
return Integer.compare(objectA.id_b, objectB.id_b);
``` | Not sure this is any more efficient or less kludgy. You could keep the original hashcode/equals using the main id (as per your comment) and then create a wrapper that has a hashcode/equals for the composite ida, idb. Maybe over the top for what you need though.
CompositeIdEntity.java
```
public interface CompositeIdEntity {
long getIdA();
long getIdB();
}
```
Entity.java
```
public class Entity implements CompositeIdEntity {
private final long mainId;
private final long idA;
private final long idB;
public Entity(long mainId, long idA, long idB) {
this.mainId = mainId;
this.idA = idA;
this.idB = idB;
}
@Override
public long getIdA() {
return idA;
}
@Override
public long getIdB() {
return idB;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (mainId ^ (mainId >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (mainId != other.mainId)
return false;
return true;
}
@Override
public String toString() {
return "Entity [mainId=" + mainId + ", idA=" + idA + ", idB=" + idB
+ "]";
}
}
```
CompositeIdWrapper.java
```
public class CompositeIdWrapper {
private final CompositeIdEntity compositeIdEntity;
public CompositeIdWrapper(CompositeIdEntity compositeIdEntity) {
this.compositeIdEntity = compositeIdEntity;
}
public CompositeIdEntity getCompositeIdEntity() {
return compositeIdEntity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (int) (compositeIdEntity.getIdA() ^ (compositeIdEntity
.getIdA() >>> 32));
result = prime * result
+ (int) (compositeIdEntity.getIdB() ^ (compositeIdEntity
.getIdB() >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CompositeIdWrapper other = (CompositeIdWrapper) obj;
if (compositeIdEntity.getIdA() != other.compositeIdEntity.getIdA())
return false;
if (compositeIdEntity.getIdB() != other.compositeIdEntity.getIdB())
return false;
return true;
}
}
```
Test.java
```
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Entity en1 = new Entity(0, 123, 456);
Entity en2 = new Entity(1, 123, 456);
Entity en3 = new Entity(2, 123, 789);
Entity en4 = new Entity(2, 123, 456);
Entity en5 = new Entity(1, 123, 789);
// Set based on main id
Set<Entity> mainIdSet = new HashSet<>();
mainIdSet.add(en1);
mainIdSet.add(en2);
mainIdSet.add(en3);
mainIdSet.add(en4);
mainIdSet.add(en5);
System.out.println("Main id set:");
for (Entity entity : mainIdSet) {
System.out.println(entity);
}
// Set based on ida, idb
Set<CompositeIdWrapper> compositeIdSet = new HashSet<>();
compositeIdSet.add(new CompositeIdWrapper(en1));
compositeIdSet.add(new CompositeIdWrapper(en2));
compositeIdSet.add(new CompositeIdWrapper(en3));
compositeIdSet.add(new CompositeIdWrapper(en4));
compositeIdSet.add(new CompositeIdWrapper(en5));
System.out.println("Composite id set:");
for (CompositeIdWrapper wrapped : compositeIdSet) {
System.out.println(wrapped.getCompositeIdEntity());
}
}
}
```
Output
```
Main id set:
Entity [mainId=1, idA=123, idB=456]
Entity [mainId=2, idA=123, idB=789]
Entity [mainId=0, idA=123, idB=456]
Composite id set:
Entity [mainId=0, idA=123, idB=456]
Entity [mainId=2, idA=123, idB=789]
``` |
49,929,034 | Trying to figure out this error. I am attempting to call on an API, and map the JSON data from the API call to a CurrencyModel. No issues with that, but when I am calling on a method that returns an observable (as it is waiting for two other API calls), it's throwing the following error to the provider property:
>
> Type '{}' is not assignable to type 'CurrencyModel'.
>
>
>
**src/models/currency.ts**
```ts
export class CurrencyModel{
private _base_currency_code: string;
private _base_currency_symbol: string;
private _default_display_currency_code: string;
private _default_display_currency_symbol: string;
private _available_currency_codes: Array<string> = [];
private _exchange_rates: Array<CurrencyExchangeRateModel> = [];
//extension attributes
get base_currency_code(): string{
return this._base_currency_code;
}
set base_currency_code(value: string){
this._base_currency_code = value;
}
get base_currency_symbol(): string{
return this._base_currency_symbol;
}
set base_currency_symbol(value: string){
this._base_currency_symbol = value;
}
get default_display_currency_code(): string{
return this._default_display_currency_code;
}
set default_display_currency_code(value: string){
this._default_display_currency_code = value;
}
get default_display_currency_symbol(): string{
return this._default_display_currency_symbol;
}
set default_display_currency_symbol(value: string){
this._default_display_currency_symbol = value;
}
get available_currency_codes(): Array<string>{
return this._available_currency_codes;
}
getAvailableCurrencyCode(key: number): string{
return this.available_currency_codes[key];
}
set available_currency_codes(value: Array<string>){
this._available_currency_codes = value;
}
setAvailableCurrencyCode(value: string): void{
this.available_currency_codes.push(value);
}
get exchange_rates(): Array<CurrencyExchangeRateModel>{
return this._exchange_rates;
}
getExchangeRate(key: number): CurrencyExchangeRateModel{
return this.exchange_rates[key];
}
set exchange_rates(value: Array<CurrencyExchangeRateModel>){
this._exchange_rates = value;
}
setExchangeRate(value: CurrencyExchangeRateModel): void{
this.exchange_rates.push(value);
}
constructor(response?: any){
if(response){
this.base_currency_code = response.base_currency_code;
this.base_currency_symbol = response.base_currency_symbol;
this.default_display_currency_code = response.default_display_currency_code;
this.default_display_currency_symbol = response.default_display_currency_symbol;
this.available_currency_codes = response.available_currency_codes ;
if(response.exchange_rates){
for(let rate of response.exchange_rates){
this.setExchangeRate( new CurrencyExchangeRateModel(rate) );
}
}
}
}
}
```
**src/providers/store/store.ts**
```ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { CurrencyModel } from '../../models/store/currency';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin";
import { map } from 'rxjs/operators';
@Injectable()
export class StoreProvider {
private apiUrl:string;
// Defaults
config: ConfigModel;
countries: Array<CountryModel> = [];
currency: CurrencyModel;
constructor(public http: HttpClient){}
readCurrency(): Observable<CurrencyModel>{
return this.http.get<CurrencyModel>(this.apiUrl + '/directory/currency').pipe(
map(data => new CurrencyModel(data))
);
}
readConfig(): any{
return this.http.get(this.apiUrl + '/store/storeConfigs');
}
//readCountries is the same, just different url
getProperties(): Observable<boolean>{
return Observable.create(observer => {
let requests: Array<any> = [
this.readConfig(),
this.readCountries(),
this.readCurrency()
];
forkJoin(requests).subscribe(data => {
this.config = this.getConfig(data[0][0]);
this.countries = this.getCountries(data[1]);
this.currency = data[2]; // Problem area
observer.next(true);
}, err => {
observer.error(err);
});
});
}
}
```
Purpose with the getProperties is to get data from the website that will need to be loaded first before anything else.
**Data structure of response (Magento 2 Currency)**
```json
{
"base_currency_code": "string",
"base_currency_symbol": "string",
"default_display_currency_code": "string",
"default_display_currency_symbol": "string",
"available_currency_codes": [
"string"
],
"exchange_rates": [
{
"currency_to": "string",
"rate": 0,
"extension_attributes": {}
}
],
"extension_attributes": {}
}
```
EDIT: Added the JSON data structure and CurrencyModel | 2018/04/19 | [
"https://Stackoverflow.com/questions/49929034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008500/"
] | if you use the `elif` construct, it will be tested only when the previous condition was false, so in the end only one of the code blocks will run.
```
if some_condition:
# code
elif another_condition:
# code
elif yet_another_condition:
# code
else:
# code
``` | Create a list of sequences and messages, like below, activate a boolean flag if found and test only one for each sequence.
Look below.
For coloring and font choice, try to output results as HTML, for instance. You can get your results in a browser.
```
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 16:45:55 2018
@author: Carlos
"""
sequences1 = ['aataaa', 'aatgga','aataaa', 'aatgga']
sequences2 = ['aatxaaa', 'aatggxa','aatxaaa', 'aatxgga']
def scan(seq):
trouble = ['aataaa', 'aatgga']
message = ['Canonical Poly-A Signal', 'Pea Poly-A Signal']
ftrouble = False
for key in range(len(trouble)):
if trouble[key] in seq:
print('The trouble sequence, {}, is present'.format(message[key]))
ftrouble = True
### the same format for the previous if statements is repeated for different sequences
if not ftrouble:
print('No trouble sequences are present')
scan(sequences1)
scan(sequences2)
``` |
49,929,034 | Trying to figure out this error. I am attempting to call on an API, and map the JSON data from the API call to a CurrencyModel. No issues with that, but when I am calling on a method that returns an observable (as it is waiting for two other API calls), it's throwing the following error to the provider property:
>
> Type '{}' is not assignable to type 'CurrencyModel'.
>
>
>
**src/models/currency.ts**
```ts
export class CurrencyModel{
private _base_currency_code: string;
private _base_currency_symbol: string;
private _default_display_currency_code: string;
private _default_display_currency_symbol: string;
private _available_currency_codes: Array<string> = [];
private _exchange_rates: Array<CurrencyExchangeRateModel> = [];
//extension attributes
get base_currency_code(): string{
return this._base_currency_code;
}
set base_currency_code(value: string){
this._base_currency_code = value;
}
get base_currency_symbol(): string{
return this._base_currency_symbol;
}
set base_currency_symbol(value: string){
this._base_currency_symbol = value;
}
get default_display_currency_code(): string{
return this._default_display_currency_code;
}
set default_display_currency_code(value: string){
this._default_display_currency_code = value;
}
get default_display_currency_symbol(): string{
return this._default_display_currency_symbol;
}
set default_display_currency_symbol(value: string){
this._default_display_currency_symbol = value;
}
get available_currency_codes(): Array<string>{
return this._available_currency_codes;
}
getAvailableCurrencyCode(key: number): string{
return this.available_currency_codes[key];
}
set available_currency_codes(value: Array<string>){
this._available_currency_codes = value;
}
setAvailableCurrencyCode(value: string): void{
this.available_currency_codes.push(value);
}
get exchange_rates(): Array<CurrencyExchangeRateModel>{
return this._exchange_rates;
}
getExchangeRate(key: number): CurrencyExchangeRateModel{
return this.exchange_rates[key];
}
set exchange_rates(value: Array<CurrencyExchangeRateModel>){
this._exchange_rates = value;
}
setExchangeRate(value: CurrencyExchangeRateModel): void{
this.exchange_rates.push(value);
}
constructor(response?: any){
if(response){
this.base_currency_code = response.base_currency_code;
this.base_currency_symbol = response.base_currency_symbol;
this.default_display_currency_code = response.default_display_currency_code;
this.default_display_currency_symbol = response.default_display_currency_symbol;
this.available_currency_codes = response.available_currency_codes ;
if(response.exchange_rates){
for(let rate of response.exchange_rates){
this.setExchangeRate( new CurrencyExchangeRateModel(rate) );
}
}
}
}
}
```
**src/providers/store/store.ts**
```ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { CurrencyModel } from '../../models/store/currency';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin";
import { map } from 'rxjs/operators';
@Injectable()
export class StoreProvider {
private apiUrl:string;
// Defaults
config: ConfigModel;
countries: Array<CountryModel> = [];
currency: CurrencyModel;
constructor(public http: HttpClient){}
readCurrency(): Observable<CurrencyModel>{
return this.http.get<CurrencyModel>(this.apiUrl + '/directory/currency').pipe(
map(data => new CurrencyModel(data))
);
}
readConfig(): any{
return this.http.get(this.apiUrl + '/store/storeConfigs');
}
//readCountries is the same, just different url
getProperties(): Observable<boolean>{
return Observable.create(observer => {
let requests: Array<any> = [
this.readConfig(),
this.readCountries(),
this.readCurrency()
];
forkJoin(requests).subscribe(data => {
this.config = this.getConfig(data[0][0]);
this.countries = this.getCountries(data[1]);
this.currency = data[2]; // Problem area
observer.next(true);
}, err => {
observer.error(err);
});
});
}
}
```
Purpose with the getProperties is to get data from the website that will need to be loaded first before anything else.
**Data structure of response (Magento 2 Currency)**
```json
{
"base_currency_code": "string",
"base_currency_symbol": "string",
"default_display_currency_code": "string",
"default_display_currency_symbol": "string",
"available_currency_codes": [
"string"
],
"exchange_rates": [
{
"currency_to": "string",
"rate": 0,
"extension_attributes": {}
}
],
"extension_attributes": {}
}
```
EDIT: Added the JSON data structure and CurrencyModel | 2018/04/19 | [
"https://Stackoverflow.com/questions/49929034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008500/"
] | You can't have multiple `if` statements and just one `else` block and have them work together. Each `if` part starts a separate, indepdendent statement, so the first `if` is one statement, and then `if...else` is another statement, independent from the first. It doesn't matter what happened in the first `if`, the second `if` doesn't care.
If you want your second and first `if` tests to work together, you need to use `elif` instead; that makes one whole `if` statement with extra tests:
```
if 'aataaa' in scan(): # if this one doesn't match
# ...
elif 'aatgga' in scan(): # only then test this one
# ...
else: # and if either failed then go here
# ...
```
`elif`, like `else`, are parts of a single `if` statement. You can add more `elif` parts as needed, and each test is then tried, in order, until one passes or you run out of `elif` tests, at which point if nothing matched the `else` part is executed.
See the [*`if` statement* documentation](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement):
>
> [*The `if` statement*] selects exactly one of the suites by evaluating the expressions one by one until one is found to be true *[...]*; then that suite is executed (and no other part of the `if` statement is executed or evaluated). If all expressions are false, the suite of the `else` clause, if present, is executed.
>
>
>
and the grammar shows a single `if` statement can have *one* `if` part, any number of `elif` parts (`( ... )*` means *0 or more*), and an optional `else` part (`[...]` means *optional*):
>
>
> ```
> if_stmt ::= "if" expression ":" suite
> ( "elif" expression ":" suite )*
> ["else" ":" suite]
>
> ```
>
>
If, on the other hand, you wanted to execute **all** tests, and a separate block if nothing matched, you need to use a loop; set a flag to indicate no tests were matched, or keep a count, or something else, and at the end test the flag or count:
```
def scan(seq):
tests = [
('aataaa', 'The trouble sequence, Canonical Poly-A Signal, is present'),
('aatgga', 'The trouble sequence, Pea Poly-A Signal, is present'),
# more tests
]
found_match = False
for value, message in tests:
if value in seq:
print(message)
found_match = True
if not found_match:
print(color.GREEN + 'No trouble sequences are present' + color.END)
``` | Create a list of sequences and messages, like below, activate a boolean flag if found and test only one for each sequence.
Look below.
For coloring and font choice, try to output results as HTML, for instance. You can get your results in a browser.
```
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 16:45:55 2018
@author: Carlos
"""
sequences1 = ['aataaa', 'aatgga','aataaa', 'aatgga']
sequences2 = ['aatxaaa', 'aatggxa','aatxaaa', 'aatxgga']
def scan(seq):
trouble = ['aataaa', 'aatgga']
message = ['Canonical Poly-A Signal', 'Pea Poly-A Signal']
ftrouble = False
for key in range(len(trouble)):
if trouble[key] in seq:
print('The trouble sequence, {}, is present'.format(message[key]))
ftrouble = True
### the same format for the previous if statements is repeated for different sequences
if not ftrouble:
print('No trouble sequences are present')
scan(sequences1)
scan(sequences2)
``` |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | Do you have an Android Developer Phone? If so, you can't purchase your own app by design. Since ADPs are unlocked, there's nothing preventing an ADP from easily pirating any app it downloads, so they are purposely cut off from downloading paid apps. | Yeah, I ran into the same problem. I uninstalled the APK from my phone so that I could download it from the market. It works fine for my free apps but not my paid apps. I guess there is no need for QA and the customer to use the same process lol |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | Do you have an Android Developer Phone? If so, you can't purchase your own app by design. Since ADPs are unlocked, there's nothing preventing an ADP from easily pirating any app it downloads, so they are purposely cut off from downloading paid apps. | Yes, the Google account associated with your market seller account cannot purchase it's own apps.
Personally I think this is a mistake on Google's part. I found some issues I couldn't solve until I had a market downloaded copy of my app - for some reason the debug version worked with the license service all the time, but downloaded ones didn't. I ended up buying it on my wife's phone.
Personally I wish I'd created a new Google account to use for selling my apps. |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | 'Please note that it is against Google Checkout's policies to purchase your own application. You will receive an error message when you try to purchase your own application.'
Doesn't look like it. Why are you wanting to buy your own app? | Yeah, I ran into the same problem. I uninstalled the APK from my phone so that I could download it from the market. It works fine for my free apps but not my paid apps. I guess there is no need for QA and the customer to use the same process lol |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | 'Please note that it is against Google Checkout's policies to purchase your own application. You will receive an error message when you try to purchase your own application.'
Doesn't look like it. Why are you wanting to buy your own app? | Yes, the Google account associated with your market seller account cannot purchase it's own apps.
Personally I think this is a mistake on Google's part. I found some issues I couldn't solve until I had a market downloaded copy of my app - for some reason the debug version worked with the license service all the time, but downloaded ones didn't. I ended up buying it on my wife's phone.
Personally I wish I'd created a new Google account to use for selling my apps. |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | Yes, the Google account associated with your market seller account cannot purchase it's own apps.
Personally I think this is a mistake on Google's part. I found some issues I couldn't solve until I had a market downloaded copy of my app - for some reason the debug version worked with the license service all the time, but downloaded ones didn't. I ended up buying it on my wife's phone.
Personally I wish I'd created a new Google account to use for selling my apps. | Yeah, I ran into the same problem. I uninstalled the APK from my phone so that I could download it from the market. It works fine for my free apps but not my paid apps. I guess there is no need for QA and the customer to use the same process lol |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | There's definitely validity in trying to buy your own app, simply for the licensing service.
I tried to do the same thing, and received the same error on the server. My purpose for buying my own app is that even when I install the signed .apk file on my phone, the Licensing Verification Library that I use to check License validity does not cache licensing checks UNLESS it is purchased from the market. So there was absolutely no way that I could test the true Licensing experience that users would have on there phones before publishing!
In my case, my brother bought the app right away and tested it, and it worked great coming from the market, where it works a bit differently on my phone. Because of this, I have to wait for it to do the License check every time I run my own app. This wouldn't be bad, except for the fact that I can't run my app when I don't have a connection, such as airplane mode, because it doesn't cache the successful licensing responses!
I would really appreciate Google changing it so you just couldn't rate or comment on your own apps, but that you COULD purchase them. After all, you're actually losing money by purchasing it, since they take 30% for the carrier fees, etc. | Yeah, I ran into the same problem. I uninstalled the APK from my phone so that I could download it from the market. It works fine for my free apps but not my paid apps. I guess there is no need for QA and the customer to use the same process lol |
2,185,846 | I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).
I saw [here](http://market.android.com/support/bin/answer.py?hl=en&answer=141659) that it seems to be *made by design*, but then why the error message is `Server Error try again` ?
Is there a way to bypass that ? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2185846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231417/"
] | There's definitely validity in trying to buy your own app, simply for the licensing service.
I tried to do the same thing, and received the same error on the server. My purpose for buying my own app is that even when I install the signed .apk file on my phone, the Licensing Verification Library that I use to check License validity does not cache licensing checks UNLESS it is purchased from the market. So there was absolutely no way that I could test the true Licensing experience that users would have on there phones before publishing!
In my case, my brother bought the app right away and tested it, and it worked great coming from the market, where it works a bit differently on my phone. Because of this, I have to wait for it to do the License check every time I run my own app. This wouldn't be bad, except for the fact that I can't run my app when I don't have a connection, such as airplane mode, because it doesn't cache the successful licensing responses!
I would really appreciate Google changing it so you just couldn't rate or comment on your own apps, but that you COULD purchase them. After all, you're actually losing money by purchasing it, since they take 30% for the carrier fees, etc. | Yes, the Google account associated with your market seller account cannot purchase it's own apps.
Personally I think this is a mistake on Google's part. I found some issues I couldn't solve until I had a market downloaded copy of my app - for some reason the debug version worked with the license service all the time, but downloaded ones didn't. I ended up buying it on my wife's phone.
Personally I wish I'd created a new Google account to use for selling my apps. |
50,046,938 | I'm working with places, and I need to get the latitude and longitude of my location. I successfully got it like this
```
mLatLang = placeLikelihood.getPlace().getLatLng();
```
where mLatLang is `LatLng mLatLang;`
Now, the output of this line is
```
(-31.54254542,62.56524)
```
but since I'm using an URL to query results by the latitude and longitude, I can't put that data inside the query with the parenthesis `()`.
So far I have searched Stack Overflow for all kinds of Regex to remove this, but it seems I can't do it. I have tried this with no success:
```
types = placeLikelihood.getPlace().getPlaceTypes();
mLatLang = placeLikelihood.getPlace().getLatLng();
String latlongshrink = mLatLang.toString();
latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
I have also tried a lot more `replaceAll` Regex, but I can't remove them.
My output should be like this:
```
-31.54254542,62.56524
``` | 2018/04/26 | [
"https://Stackoverflow.com/questions/50046938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9164141/"
] | What you are missing in your logic is that `replaceAll` returns the resultant string. But you are not storing the result, and that's why it's not working. So try as following:
```
latlongshrink = latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
Now try to print the result. It'll give the expected result. See [this](https://www.javatpoint.com/java-string-replaceall) for more information about `replaceAll()` function. | If you have a String like "(abc)" and you want to get the content of parenthesis, maybe you can use substring to cut out first and last character.
Something likes that may work in your case (and you do not have to deal with regexp):
```
String withParenthesis = "(abc)";
String content = withParenthesis.substring(1, withParenthesis.length()-1);
System.out.println(content); // print abc
``` |
50,046,938 | I'm working with places, and I need to get the latitude and longitude of my location. I successfully got it like this
```
mLatLang = placeLikelihood.getPlace().getLatLng();
```
where mLatLang is `LatLng mLatLang;`
Now, the output of this line is
```
(-31.54254542,62.56524)
```
but since I'm using an URL to query results by the latitude and longitude, I can't put that data inside the query with the parenthesis `()`.
So far I have searched Stack Overflow for all kinds of Regex to remove this, but it seems I can't do it. I have tried this with no success:
```
types = placeLikelihood.getPlace().getPlaceTypes();
mLatLang = placeLikelihood.getPlace().getLatLng();
String latlongshrink = mLatLang.toString();
latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
I have also tried a lot more `replaceAll` Regex, but I can't remove them.
My output should be like this:
```
-31.54254542,62.56524
``` | 2018/04/26 | [
"https://Stackoverflow.com/questions/50046938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9164141/"
] | What you are missing in your logic is that `replaceAll` returns the resultant string. But you are not storing the result, and that's why it's not working. So try as following:
```
latlongshrink = latlongshrink.replaceAll("[\\\\[\\\\](){}]","");
```
Now try to print the result. It'll give the expected result. See [this](https://www.javatpoint.com/java-string-replaceall) for more information about `replaceAll()` function. | I just solved it with a Matcher
```
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(latlongshrink);
while(m.find()) {
Log.e("Test",""+m.group(1));
latlongshrink = m.group(1);
}
``` |
41,196,867 | This is a question I always had, but now is the time to solve it:
I'm trying to implement the composition of objects using public attributes like:
```
Person {
public Car car;
}
Owner {
public Person person;
public Car car;
}
Car {
public Person person;
}
```
Really my question is: Is a good practice to set that composition properties public or private?
The difference:
a) **Public**: doing public, the access is fast and not complicated, because I only need to reference the property directly with the instance like:
```
$instancePerson.car.getNumberOfGearsGood()
```
The problem: the car propertie is available to be modified by anybody from anywhere.
b) **Private**: doing private, the access if slow and is necessary to use methods to get these properties like:
```
$instancePerson.getCar().getNumberOfGearsGood()
```
When I say slow is because you need to do a method two method call, while in the Public solution only you need to do one.
I know many developers and software engineers here will prefer Private solution, but can you explain the performance there? | 2016/12/17 | [
"https://Stackoverflow.com/questions/41196867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900879/"
] | If you are doing OO, there should be no such thing as a "public" attribute. All the attributes are implementation details of the object, therefore are hidden from everybody. Only the methods associated with the object's responsibility are public.
So to answer the question:
* All "attributes" should be private
* *And* there should be no getter on a private attribute
Yes, there should be no
```java
person.getCar().getNumberOfGears();
```
This is sometimes called the [Law of Demeter](https://en.wikipedia.org/wiki/Law_of_Demeter). The person should have methods that do stuff connected to the responsibility of the Person class, therefore there is no performance penalty accessing attributes, because this access is always internal to the class and direct. | the short answer is that, except for very few cases, you want those variables to be private, and often technologies in the JVM will make access faster than you think it would be (and sometimes even faster than in C/C++).
For a bit more detailed answer:
The main question is: who should be able to modify those variables? for example, you may want `Car` to be created passing a `Person` to its constructor, and never allow the person to change (in a world where there is no market for used vehicles). In this case, if the field is public another object can modify it and change the owner of the car. But if you make the field private, and provide a `getOwner()` method, nobody can modify it. If the get method is `final`, and therefore can't be overridden in a subclass, the JVM might even transform internally any invocation of `x.getOwner()` in the equivalent of `x.owner`. In your example however it's not possible to pass all elements in the constructor, as they reference each other. In fact, it seems to me your model has one too many classes. Let's try to write it a bit differently:
```
Person {
public Car car;
}
Car {
public Person owner;
}
```
Now, with assuming that every car has an owner, and every person own a car, this model is dangerous, because you could do something like this:
```
Person p = new Person()
Car c = new Car();
p.car = c;
```
As you can see, I forgot to set `c.owner = p`.
Let's see how we can fix this:
```
Person {
private Car car;
public void setCar(Car c) {
if (car == c)
return;
car = c;
c.setOwner(this);
}
}
Car {
private Person owner;
public void setOwner(Person o) {
if (o == owner)
return;
owner = o;
o.setCar(this);
}
}
```
I can now do :
```
Person p = new Person();
Car c = new Car();
p.setCar(c);
```
or
```
Person p = new Person();
Car c = new Car();
c.setOwner(p);
```
and either way both relationship will be set correctly.
In other words, being forced to go through accessors allows to set more than just a simple field, which is useful to establish coherent state across model elements involved in a relationship. |
1,015,017 | Simple as that, can we emulate the "protected" visibility in Javascript somehow? | 2009/06/18 | [
"https://Stackoverflow.com/questions/1015017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] | Do this:
```
/* Note: Do not break/touch this object */
...code...
```
Or a bit of google found this on the first page:
<http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html> | What could that possibly mean? You don't have *classes*.
I suppose you could analyze `caller` to determine whether it meets some set of criteria for being permitted to call a method. This will be hideously inefficient and your criteria will always be spoofable. |
1,015,017 | Simple as that, can we emulate the "protected" visibility in Javascript somehow? | 2009/06/18 | [
"https://Stackoverflow.com/questions/1015017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] | Do this:
```
/* Note: Do not break/touch this object */
...code...
```
Or a bit of google found this on the first page:
<http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html> | There's an interesting pattern worth mentioning here: a JavaScript contructor function may return any object (not necesserily *this*). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:
```
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
```
The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: <http://idya.github.com/oolib/> |
1,015,017 | Simple as that, can we emulate the "protected" visibility in Javascript somehow? | 2009/06/18 | [
"https://Stackoverflow.com/questions/1015017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] | [Sure](http://webreflection.blogspot.com/2008/02/how-to-inject-protected-methods-in.html) you can. Here's another [example](http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html). | What could that possibly mean? You don't have *classes*.
I suppose you could analyze `caller` to determine whether it meets some set of criteria for being permitted to call a method. This will be hideously inefficient and your criteria will always be spoofable. |
1,015,017 | Simple as that, can we emulate the "protected" visibility in Javascript somehow? | 2009/06/18 | [
"https://Stackoverflow.com/questions/1015017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540/"
] | [Sure](http://webreflection.blogspot.com/2008/02/how-to-inject-protected-methods-in.html) you can. Here's another [example](http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html). | There's an interesting pattern worth mentioning here: a JavaScript contructor function may return any object (not necesserily *this*). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:
```
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
```
The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: <http://idya.github.com/oolib/> |
10,476,265 | I have a PDF form that needs to be filled out a bunch of times (it's a timesheet to be exact). Now since I don't want to do this by hand, I was looking for a way to fill them out using a python script or tools that could be used in a bash script.
Does anyone have experience with this? | 2012/05/07 | [
"https://Stackoverflow.com/questions/10476265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/701409/"
] | **For Python you'll need the fdfgen lib and pdftk**
@Hugh Bothwell's comment is 100% correct so I'll extend that answer with a working implementation.
If you're in windows you'll also need to make sure both python and pdftk are contained in the system path (unless you want to use long folder names).
Here's the code to auto-batch-fill a collection of PDF forms from a CSV data file:
```
import csv
from fdfgen import forge_fdf
import os
import sys
sys.path.insert(0, os.getcwd())
filename_prefix = "NVC"
csv_file = "NVC.csv"
pdf_file = "NVC.pdf"
tmp_file = "tmp.fdf"
output_folder = './output/'
def process_csv(file):
headers = []
data = []
csv_data = csv.reader(open(file))
for i, row in enumerate(csv_data):
if i == 0:
headers = row
continue;
field = []
for i in range(len(headers)):
field.append((headers[i], row[i]))
data.append(field)
return data
def form_fill(fields):
fdf = forge_fdf("",fields,[],[],[])
fdf_file = open(tmp_file,"w")
fdf_file.write(fdf)
fdf_file.close()
output_file = '{0}{1} {2}.pdf'.format(output_folder, filename_prefix, fields[1][1])
cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
os.system(cmd)
os.remove(tmp_file)
data = process_csv(csv_file)
print('Generating Forms:')
print('-----------------------')
for i in data:
if i[0][1] == 'Yes':
continue
print('{0} {1} created...'.format(filename_prefix, i[1][1]))
form_fill(i)
```
*Note: It shouldn't be rocket-surgery to figure out how to customize this. The initial variable declarations contain the custom configuration.*
In the CSV, in the first row each column will contain the name of the corresponding field name in the PDF file. Any columns that don't have corresponding fields in the template will be ignored.
In the PDF template, just create editable fields where you want your data to fill and make sure the names match up with the CSV data.
For this specific configuration, just put this file in the same folder as your NVC.csv, NVC.pdf, and a folder named 'output'. Run it and it automagically does the rest. | Replace Original File
```
os.system('pdftk "original.pdf" fill_form "data.fdf" output "output.pdf"')
os.remove("data.fdf")
os.remove("original.pdf")
os.rename("output.pdf","original.pdf")
``` |
10,476,265 | I have a PDF form that needs to be filled out a bunch of times (it's a timesheet to be exact). Now since I don't want to do this by hand, I was looking for a way to fill them out using a python script or tools that could be used in a bash script.
Does anyone have experience with this? | 2012/05/07 | [
"https://Stackoverflow.com/questions/10476265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/701409/"
] | **For Python you'll need the fdfgen lib and pdftk**
@Hugh Bothwell's comment is 100% correct so I'll extend that answer with a working implementation.
If you're in windows you'll also need to make sure both python and pdftk are contained in the system path (unless you want to use long folder names).
Here's the code to auto-batch-fill a collection of PDF forms from a CSV data file:
```
import csv
from fdfgen import forge_fdf
import os
import sys
sys.path.insert(0, os.getcwd())
filename_prefix = "NVC"
csv_file = "NVC.csv"
pdf_file = "NVC.pdf"
tmp_file = "tmp.fdf"
output_folder = './output/'
def process_csv(file):
headers = []
data = []
csv_data = csv.reader(open(file))
for i, row in enumerate(csv_data):
if i == 0:
headers = row
continue;
field = []
for i in range(len(headers)):
field.append((headers[i], row[i]))
data.append(field)
return data
def form_fill(fields):
fdf = forge_fdf("",fields,[],[],[])
fdf_file = open(tmp_file,"w")
fdf_file.write(fdf)
fdf_file.close()
output_file = '{0}{1} {2}.pdf'.format(output_folder, filename_prefix, fields[1][1])
cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
os.system(cmd)
os.remove(tmp_file)
data = process_csv(csv_file)
print('Generating Forms:')
print('-----------------------')
for i in data:
if i[0][1] == 'Yes':
continue
print('{0} {1} created...'.format(filename_prefix, i[1][1]))
form_fill(i)
```
*Note: It shouldn't be rocket-surgery to figure out how to customize this. The initial variable declarations contain the custom configuration.*
In the CSV, in the first row each column will contain the name of the corresponding field name in the PDF file. Any columns that don't have corresponding fields in the template will be ignored.
In the PDF template, just create editable fields where you want your data to fill and make sure the names match up with the CSV data.
For this specific configuration, just put this file in the same folder as your NVC.csv, NVC.pdf, and a folder named 'output'. Run it and it automagically does the rest. | I wrote a library built upon:'pdfrw', 'pdf2image', 'Pillow', 'PyPDF2' called fillpdf (`pip install fillpdf` and poppler dependency `conda install -c conda-forge poppler`)
Basic usage:
```
from fillpdf import fillpdfs
fillpdfs.get_form_fields("blank.pdf")
# returns a dictionary of fields
# Set the returned dictionary values a save to a variable
# For radio boxes ('Off' = not filled, 'Yes' = filled)
data_dict = {
'Text2': 'Name',
'Text4': 'LastName',
'box': 'Yes',
}
fillpdfs.write_fillable_pdf('blank.pdf', 'new.pdf', data_dict)
# If you want it flattened:
fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf')
```
More info here:
<https://github.com/t-houssian/fillpdf>
If some fields don't fill, use can use fitz (`pip install PyMuPDF`) and PyPDF2 (`pip install PyPDF2`) like the following altering the points as needed:
```
import fitz
from PyPDF2 import PdfFileReader
file_handle = fitz.open('blank.pdf')
pdf = PdfFileReader(open('blank.pdf','rb'))
box = pdf.getPage(0).mediaBox
w = box.getWidth()
h = box.getHeight()
# For images
image_rectangle = fitz.Rect((w/2)-200,h-255,(w/2)-100,h-118)
pages = pdf.getNumPages() - 1
last_page = file_handle[pages]
last_page._wrapContents()
last_page.insertImage(image_rectangle, filename=f'image.png')
# For text
last_page.insertText(fitz.Point((w/2)-247 , h-478), 'John Smith', fontsize=14, fontname="times-bold")
file_handle.save(f'newpdf.pdf')
``` |
10,476,265 | I have a PDF form that needs to be filled out a bunch of times (it's a timesheet to be exact). Now since I don't want to do this by hand, I was looking for a way to fill them out using a python script or tools that could be used in a bash script.
Does anyone have experience with this? | 2012/05/07 | [
"https://Stackoverflow.com/questions/10476265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/701409/"
] | Much faster version, no pdftk nor fdfgen needed, pure Python 3.6+:
```
# -*- coding: utf-8 -*-
from collections import OrderedDict
from PyPDF2 import PdfFileWriter, PdfFileReader
def _getFields(obj, tree=None, retval=None, fileobj=None):
"""
Extracts field data if this PDF contains interactive form fields.
The *tree* and *retval* parameters are for recursive use.
:param fileobj: A file object (usually a text file) to write
a report to on all interactive form fields found.
:return: A dictionary where each key is a field name, and each
value is a :class:`Field<PyPDF2.generic.Field>` object. By
default, the mapping name is used for keys.
:rtype: dict, or ``None`` if form data could not be located.
"""
fieldAttributes = {'/FT': 'Field Type', '/Parent': 'Parent', '/T': 'Field Name', '/TU': 'Alternate Field Name',
'/TM': 'Mapping Name', '/Ff': 'Field Flags', '/V': 'Value', '/DV': 'Default Value'}
if retval is None:
retval = OrderedDict()
catalog = obj.trailer["/Root"]
# get the AcroForm tree
if "/AcroForm" in catalog:
tree = catalog["/AcroForm"]
else:
return None
if tree is None:
return retval
obj._checkKids(tree, retval, fileobj)
for attr in fieldAttributes:
if attr in tree:
# Tree is a field
obj._buildField(tree, retval, fileobj, fieldAttributes)
break
if "/Fields" in tree:
fields = tree["/Fields"]
for f in fields:
field = f.getObject()
obj._buildField(field, retval, fileobj, fieldAttributes)
return retval
def get_form_fields(infile):
infile = PdfFileReader(open(infile, 'rb'))
fields = _getFields(infile)
return OrderedDict((k, v.get('/V', '')) for k, v in fields.items())
def update_form_values(infile, outfile, newvals=None):
pdf = PdfFileReader(open(infile, 'rb'))
writer = PdfFileWriter()
for i in range(pdf.getNumPages()):
page = pdf.getPage(i)
try:
if newvals:
writer.updatePageFormFieldValues(page, newvals)
else:
writer.updatePageFormFieldValues(page,
{k: f'#{i} {k}={v}'
for i, (k, v) in enumerate(get_form_fields(infile).items())
})
writer.addPage(page)
except Exception as e:
print(repr(e))
writer.addPage(page)
with open(outfile, 'wb') as out:
writer.write(out)
if __name__ == '__main__':
from pprint import pprint
pdf_file_name = '2PagesFormExample.pdf'
pprint(get_form_fields(pdf_file_name))
update_form_values(pdf_file_name, 'out-' + pdf_file_name) # enumerate & fill the fields with their own names
update_form_values(pdf_file_name, 'out2-' + pdf_file_name,
{'my_fieldname_1': 'My Value',
'my_fieldname_2': 'My Another alue'}) # update the form fields
``` | Replace Original File
```
os.system('pdftk "original.pdf" fill_form "data.fdf" output "output.pdf"')
os.remove("data.fdf")
os.remove("original.pdf")
os.rename("output.pdf","original.pdf")
``` |
10,476,265 | I have a PDF form that needs to be filled out a bunch of times (it's a timesheet to be exact). Now since I don't want to do this by hand, I was looking for a way to fill them out using a python script or tools that could be used in a bash script.
Does anyone have experience with this? | 2012/05/07 | [
"https://Stackoverflow.com/questions/10476265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/701409/"
] | Much faster version, no pdftk nor fdfgen needed, pure Python 3.6+:
```
# -*- coding: utf-8 -*-
from collections import OrderedDict
from PyPDF2 import PdfFileWriter, PdfFileReader
def _getFields(obj, tree=None, retval=None, fileobj=None):
"""
Extracts field data if this PDF contains interactive form fields.
The *tree* and *retval* parameters are for recursive use.
:param fileobj: A file object (usually a text file) to write
a report to on all interactive form fields found.
:return: A dictionary where each key is a field name, and each
value is a :class:`Field<PyPDF2.generic.Field>` object. By
default, the mapping name is used for keys.
:rtype: dict, or ``None`` if form data could not be located.
"""
fieldAttributes = {'/FT': 'Field Type', '/Parent': 'Parent', '/T': 'Field Name', '/TU': 'Alternate Field Name',
'/TM': 'Mapping Name', '/Ff': 'Field Flags', '/V': 'Value', '/DV': 'Default Value'}
if retval is None:
retval = OrderedDict()
catalog = obj.trailer["/Root"]
# get the AcroForm tree
if "/AcroForm" in catalog:
tree = catalog["/AcroForm"]
else:
return None
if tree is None:
return retval
obj._checkKids(tree, retval, fileobj)
for attr in fieldAttributes:
if attr in tree:
# Tree is a field
obj._buildField(tree, retval, fileobj, fieldAttributes)
break
if "/Fields" in tree:
fields = tree["/Fields"]
for f in fields:
field = f.getObject()
obj._buildField(field, retval, fileobj, fieldAttributes)
return retval
def get_form_fields(infile):
infile = PdfFileReader(open(infile, 'rb'))
fields = _getFields(infile)
return OrderedDict((k, v.get('/V', '')) for k, v in fields.items())
def update_form_values(infile, outfile, newvals=None):
pdf = PdfFileReader(open(infile, 'rb'))
writer = PdfFileWriter()
for i in range(pdf.getNumPages()):
page = pdf.getPage(i)
try:
if newvals:
writer.updatePageFormFieldValues(page, newvals)
else:
writer.updatePageFormFieldValues(page,
{k: f'#{i} {k}={v}'
for i, (k, v) in enumerate(get_form_fields(infile).items())
})
writer.addPage(page)
except Exception as e:
print(repr(e))
writer.addPage(page)
with open(outfile, 'wb') as out:
writer.write(out)
if __name__ == '__main__':
from pprint import pprint
pdf_file_name = '2PagesFormExample.pdf'
pprint(get_form_fields(pdf_file_name))
update_form_values(pdf_file_name, 'out-' + pdf_file_name) # enumerate & fill the fields with their own names
update_form_values(pdf_file_name, 'out2-' + pdf_file_name,
{'my_fieldname_1': 'My Value',
'my_fieldname_2': 'My Another alue'}) # update the form fields
``` | I wrote a library built upon:'pdfrw', 'pdf2image', 'Pillow', 'PyPDF2' called fillpdf (`pip install fillpdf` and poppler dependency `conda install -c conda-forge poppler`)
Basic usage:
```
from fillpdf import fillpdfs
fillpdfs.get_form_fields("blank.pdf")
# returns a dictionary of fields
# Set the returned dictionary values a save to a variable
# For radio boxes ('Off' = not filled, 'Yes' = filled)
data_dict = {
'Text2': 'Name',
'Text4': 'LastName',
'box': 'Yes',
}
fillpdfs.write_fillable_pdf('blank.pdf', 'new.pdf', data_dict)
# If you want it flattened:
fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf')
```
More info here:
<https://github.com/t-houssian/fillpdf>
If some fields don't fill, use can use fitz (`pip install PyMuPDF`) and PyPDF2 (`pip install PyPDF2`) like the following altering the points as needed:
```
import fitz
from PyPDF2 import PdfFileReader
file_handle = fitz.open('blank.pdf')
pdf = PdfFileReader(open('blank.pdf','rb'))
box = pdf.getPage(0).mediaBox
w = box.getWidth()
h = box.getHeight()
# For images
image_rectangle = fitz.Rect((w/2)-200,h-255,(w/2)-100,h-118)
pages = pdf.getNumPages() - 1
last_page = file_handle[pages]
last_page._wrapContents()
last_page.insertImage(image_rectangle, filename=f'image.png')
# For text
last_page.insertText(fitz.Point((w/2)-247 , h-478), 'John Smith', fontsize=14, fontname="times-bold")
file_handle.save(f'newpdf.pdf')
``` |
275,889 | In quantum mechanics it is usually the case that when degrees of freedom in a system are traced out (i.e. ignored), the evolution of the remaining system is no longer unitary and this is formally described as the entropy of the reduced density matrix ($S = Tr(\rho\ln{\rho}$)) attaining a nonzero value.
Why is it then that there exist certain quantum mechanical systems which have unitary evolution, but for which we clearly do not keep track of all degrees of freedom? Practically any non-relativistic quantum system such as atomic structure, spin chains, any implementation of a quantum computer etc. are clearly just effective theories which ignore the massive number of degrees of freedom underlying the more fundamental physics, i.e. quantum field theory. But somehow we are able to trace away all of this underlying physics into an effective potential/interaction term in a Hamiltonian and thus retain unitarity.
Now this does not work entirely for all systems, particularly it is impossible to hide away the full coupling of an atom to the EM field because you have spontaneous emission, a non-unitary effect. But still a large part of the electron/proton interaction (which is really mediated through the EM field) can be captured by the Coulomb potential, which ignores the EM field yet is still unitary. On the other hand, some systems, such as certain implementations of quantum computing/simulation claim to be able to achieve perfect unitarity and are only limited by imperfections in the system. At least, I have never heard of anyone talking about intrinsic unitarity limitations to a quantum computer.
My questions are:
-Under what conditions can underlying degrees of freedom be hidden away into a unitary interaction?
-Are there intrinsic limits to unitarity of any quantum system (such as an atom's unitarity being limited by spon. emission), assuming that you will always trace out a portion of the underlying field theory? | 2016/08/23 | [
"https://physics.stackexchange.com/questions/275889",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/41152/"
] | The answer to your question is a bit subtle and has to do with the various ways we can ignore degrees of freedom in physics. One way, as you mentioned, is if you have a system interacting with its environment but you don't care about the state of the environment. Then you can perform a partial trace over environmental states and obtain a reduced density matrix describing the quantum state of the system. This reduced density matrix will $not$ evolve unitarily.
However, there is another way to remove degrees of freedom in order to simplify your problem. This is called integrating out variables/fields. Suppose you have a theory that works to arbitrarily high energy, but you only care about low energy excitations of your system. You can "integrate out" the high energy modes of your system and obtain a low-energy effective field theory that is still unitary (as long as you remain at low energy). If you are familiar with QFT, a common example of this is the Four Fermi theory obtained by integrating out the very heavy W and Z bosons of the standard model.
The reason you can integrate out the W and Z bosons at low energy is that they are extremely massive compared to the other particles in the theory. Thus, at low energy they can never be produced. So when you integrate out the W and Z, you are not actually ignoring anything $physical$ as you are if you perform a partial trace over an environment. (If you were working at high enough energies to produce W and Z bosons then you would be ignoring physical particles, so your theory would no longer be unitary).
To use an example you mentioned: why can you not integrate out EM fields to get an effective theory for hydrogen atoms? The reason is that photons are massless, so no matter what energies you are working at, photons can always be created. Thus, integrating out photons would involve ignoring physical objects and would result in non-unitary behavior.
To recap: there are two ways of ignoring degrees of freedom:
(1) If you ignore physical things eg though partial traces, then you will not have unitary behavior.
(2) If you are working at low energy but simplify your theory by ignoring high energy physics, then you can obtain a low energy effective theory that is unitary. However if you push this low energy theory to high energy, it will (usually) fail to be unitary. | Mathematically it is quite simple: If your overall system unitary $U\_{tot}$ can be expressed as $U\_{tot} = U\_1 \otimes U\_2$, then the subsystems 1 and 2 have unitary evolution even when you trace out the partner.
Parameter counting can give you some very rough idea of how easy or hard this is. For instance, in a 2-qubit system the general unitary operator has 16 free parameters. A 1-qubit unitary has 4 parameters. So the total dimensionality of the separable space of unitaries is 8 out of the total 16 dimensions. As your system get bigger, the separable unitary gets to be a smaller and smaller sub-space of the total system. In the real world of course this is a gross oversimplification. Some of those parameters are automatically small or zero, others are very hard to control.
However, there is not any known intrinsic limit to how accurately a subsystem can be made unitary. Even your example of an atom in an excited state is not so limited. Spontaneous emission is a unitary and reversible process, so we can control it. By placing an atom in a cavity it is possible to suppress or enhance the spontaneous emission rate. This is known as the [Purcell Effect](https://en.wikipedia.org/wiki/Purcell_effect). The ultimate limit of the atomic lifetime is then given by how well the cavity can be engineered. |
5,817,526 | So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else. | 2011/04/28 | [
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] | how about simply rewriting the setTimeout function to sort of inject custom logging functionality?
like
```
var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
console.log("timeout started");
return oldTimeout(function() {
console.log('timeout finished');
callback();
}, timeout);
}
```
might work? | No, even the [HTML5 spec](http://www.w3.org/TR/html5/timers.html#timers) (which is a rationalisation of the HTML 4.01 behaviour in current browsers, with additional features) doesn't specify a way to list the available callbacks. |
5,817,526 | So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else. | 2011/04/28 | [
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] | No, even the [HTML5 spec](http://www.w3.org/TR/html5/timers.html#timers) (which is a rationalisation of the HTML 4.01 behaviour in current browsers, with additional features) doesn't specify a way to list the available callbacks. | We've just published a package solving this exact issue.
```
npm install time-events-manager
```
With that, you can view them via `timeoutCollection` & `intervalCollection` objects. |
5,817,526 | So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else. | 2011/04/28 | [
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] | No, even the [HTML5 spec](http://www.w3.org/TR/html5/timers.html#timers) (which is a rationalisation of the HTML 4.01 behaviour in current browsers, with additional features) doesn't specify a way to list the available callbacks. | You could also create a *timer manager* module which will keep track of current timers and allow you to get, add, stop and stop all timers.
```js
var timers = (function() {
//
var timers = []
//
const getIndex = (array, attr, value) => {
for (let i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return i
}
}
return -1
};
// add
const add = (callback, time) => {
var id = setTimeout(() => {
let index = getIndex(timers, 'id', id)
timers.splice(index, 1)
callback()
}, time)
timers.push({
id: id,
time: time,
debug: callback.toString()
})
};
// get all active timers
const all = () => timers
// stop timer by timer id
const stop = (id) => {
if (!isNaN(id)) {
let index = getIndex(timers, 'id', id)
if (index !== -1) {
clearTimeout(timers[index].id)
timers.splice(index, 1)
}
}
};
// stop all timers
const stopAll = () => {
for (let i = 0; i < timers.length; i++) {
clearTimeout(timers[i].id)
}
timers = []
};
return {
add: add,
all: all,
stop: stop,
stopAll: stopAll,
};
})();
//
timers.add(function() {
console.log("timeout 1 fired");
}, 1000)
timers.add(function() {
console.log("timeout 2 wont get fired");
}, 2000)
timers.add(function() {
console.log("timeout 3 fired");
}, 3000)
timers.add(function() {
console.log("timeout 4 fired, timers", timers.all());
}, 4000)
timers.add(function() {
console.log("timeout 5 fired");
}, 5000)
console.log('All timers', timers.all())
console.log("kill timer 2")
timers.stop(2)
```
Run the snippet to see it in action. |
5,817,526 | So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else. | 2011/04/28 | [
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] | how about simply rewriting the setTimeout function to sort of inject custom logging functionality?
like
```
var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
console.log("timeout started");
return oldTimeout(function() {
console.log('timeout finished');
callback();
}, timeout);
}
```
might work? | We've just published a package solving this exact issue.
```
npm install time-events-manager
```
With that, you can view them via `timeoutCollection` & `intervalCollection` objects. |
5,817,526 | So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know `setTimeout` and `setInterval` return a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:
```
setTimeout("alert('test');", 30000);
```
Is there some code I can execute at this point that will tell me that the browser will execute `alert('test');` 30 seconds from now?
It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else. | 2011/04/28 | [
"https://Stackoverflow.com/questions/5817526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609251/"
] | how about simply rewriting the setTimeout function to sort of inject custom logging functionality?
like
```
var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
console.log("timeout started");
return oldTimeout(function() {
console.log('timeout finished');
callback();
}, timeout);
}
```
might work? | You could also create a *timer manager* module which will keep track of current timers and allow you to get, add, stop and stop all timers.
```js
var timers = (function() {
//
var timers = []
//
const getIndex = (array, attr, value) => {
for (let i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return i
}
}
return -1
};
// add
const add = (callback, time) => {
var id = setTimeout(() => {
let index = getIndex(timers, 'id', id)
timers.splice(index, 1)
callback()
}, time)
timers.push({
id: id,
time: time,
debug: callback.toString()
})
};
// get all active timers
const all = () => timers
// stop timer by timer id
const stop = (id) => {
if (!isNaN(id)) {
let index = getIndex(timers, 'id', id)
if (index !== -1) {
clearTimeout(timers[index].id)
timers.splice(index, 1)
}
}
};
// stop all timers
const stopAll = () => {
for (let i = 0; i < timers.length; i++) {
clearTimeout(timers[i].id)
}
timers = []
};
return {
add: add,
all: all,
stop: stop,
stopAll: stopAll,
};
})();
//
timers.add(function() {
console.log("timeout 1 fired");
}, 1000)
timers.add(function() {
console.log("timeout 2 wont get fired");
}, 2000)
timers.add(function() {
console.log("timeout 3 fired");
}, 3000)
timers.add(function() {
console.log("timeout 4 fired, timers", timers.all());
}, 4000)
timers.add(function() {
console.log("timeout 5 fired");
}, 5000)
console.log('All timers', timers.all())
console.log("kill timer 2")
timers.stop(2)
```
Run the snippet to see it in action. |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | If your table has no primary key defined then you have to give `-m 1` option for importing the data or you have to provide `--split-by` argument with some column name, otherwise it gives the error:
```
ERROR tool.ImportTool: Error during import: No primary key could be found for table <table_name>. Please specify one with --split-by or perform a sequential import with '-m 1'
```
then your sqoop command will look like
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
-m 1
```
or
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
--split-by created_date
``` | In the first scenario using 1 Mapper ... If the size of the file is very large this process is going to take more time to respond or might fail. Check the size of the data before using mapper = 1 . |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | If your table has no primary key defined then you have to give `-m 1` option for importing the data or you have to provide `--split-by` argument with some column name, otherwise it gives the error:
```
ERROR tool.ImportTool: Error during import: No primary key could be found for table <table_name>. Please specify one with --split-by or perform a sequential import with '-m 1'
```
then your sqoop command will look like
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
-m 1
```
or
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
--split-by created_date
``` | You can import data from RDBMS into hive without Primarykey.
First you need to create a table in hive.After that you need to write the following code:
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table <RDBMS-Table-name> \
--target-dir /user/root/user_data \
--hive-import \
--hive-table <hive-table-name> \
--create-hive-table \
-m 1 (or) --split-by <RDBMS-Column>
``` |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | If your table has no primary key defined then you have to give `-m 1` option for importing the data or you have to provide `--split-by` argument with some column name, otherwise it gives the error:
```
ERROR tool.ImportTool: Error during import: No primary key could be found for table <table_name>. Please specify one with --split-by or perform a sequential import with '-m 1'
```
then your sqoop command will look like
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
-m 1
```
or
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
--split-by created_date
``` | Quick view:
The Sqoop job fails and the error looks like this" Error during import: No primary key could be found for the table . Please specify one with --split-by or perform a sequential import with '-m 1' "
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Description:
Usually, when you perform a Sqoop job internally it searches for the primary key in the table. If there is no primary key the Sqoop job fails and the error looks like this" Error during import: No primary key could be found for the table . Please specify one with --split-by or perform a sequential import with '-m 1' ". The suggestion describes there are two alternative approaches to this scenario.
Best way is option 2
1. To specify the number of mappers as 1 (default it takes 4). So by specifying the number of mappers to 1, the task will be sequential and identical to a single threaded task. This will succeed only when you are targeting a small table if in case if you are looking for a large import this will fail as the task tends to run forever.
2. The best approach is to use split-by where you can specify the number of mappers on the bases of indexed columns or splitting column manually( with queries ). |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | If your table has no primary key defined then you have to give `-m 1` option for importing the data or you have to provide `--split-by` argument with some column name, otherwise it gives the error:
```
ERROR tool.ImportTool: Error during import: No primary key could be found for table <table_name>. Please specify one with --split-by or perform a sequential import with '-m 1'
```
then your sqoop command will look like
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
-m 1
```
or
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table user \
--target-dir /user/root/user_data \
--columns "first_name, last_name, created_date"
--split-by created_date
``` | Use the following in your command:
```
--autoreset-to-one-mapper
```
`Import` should use one mapper if a table has no primary key and no split-by column is provided. It cannot be used with `--split-by <col>` option. |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | In the first scenario using 1 Mapper ... If the size of the file is very large this process is going to take more time to respond or might fail. Check the size of the data before using mapper = 1 . | Use the following in your command:
```
--autoreset-to-one-mapper
```
`Import` should use one mapper if a table has no primary key and no split-by column is provided. It cannot be used with `--split-by <col>` option. |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | You can import data from RDBMS into hive without Primarykey.
First you need to create a table in hive.After that you need to write the following code:
```
sqoop import \
--connect jdbc:mysql://localhost/test_db \
--username root \
--password **** \
--table <RDBMS-Table-name> \
--target-dir /user/root/user_data \
--hive-import \
--hive-table <hive-table-name> \
--create-hive-table \
-m 1 (or) --split-by <RDBMS-Column>
``` | Use the following in your command:
```
--autoreset-to-one-mapper
```
`Import` should use one mapper if a table has no primary key and no split-by column is provided. It cannot be used with `--split-by <col>` option. |
29,138,498 | Can I import RDBMS table data (table doesn't have a primary key) to hive using sqoop? If yes, then can you please give the sqoop import command.
I have tried with sqoop import general command, but it failed. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29138498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688490/"
] | Quick view:
The Sqoop job fails and the error looks like this" Error during import: No primary key could be found for the table . Please specify one with --split-by or perform a sequential import with '-m 1' "
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Description:
Usually, when you perform a Sqoop job internally it searches for the primary key in the table. If there is no primary key the Sqoop job fails and the error looks like this" Error during import: No primary key could be found for the table . Please specify one with --split-by or perform a sequential import with '-m 1' ". The suggestion describes there are two alternative approaches to this scenario.
Best way is option 2
1. To specify the number of mappers as 1 (default it takes 4). So by specifying the number of mappers to 1, the task will be sequential and identical to a single threaded task. This will succeed only when you are targeting a small table if in case if you are looking for a large import this will fail as the task tends to run forever.
2. The best approach is to use split-by where you can specify the number of mappers on the bases of indexed columns or splitting column manually( with queries ). | Use the following in your command:
```
--autoreset-to-one-mapper
```
`Import` should use one mapper if a table has no primary key and no split-by column is provided. It cannot be used with `--split-by <col>` option. |
3,585 | I have recently setup Wordpress Multisite and have that working well. Now to complete the branding, I want to use `feeds.mydomain.com` for the MyBrand integration to Feedburner. I have setup the CNAME to point to the server that Feedburner has specified, but when I visit the site (after ensuring the entry could propagate), WordPress takes over thinking I want to create a new website. I am guessing this is a DNS issue, but I am not sure where to begin to troubleshoot this further. | 2010/10/06 | [
"https://webmasters.stackexchange.com/questions/3585",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/835/"
] | This is probably a DNS issue. Make sure `feeds.mydomain.com` points to Feedburner. You can easily check it running a DNS query.
With Linux/MacOSX, use the `dig` command.
```
$ dig feeds.engadget.com
; <<>> DiG 9.6.0-APPLE-P2 <<>> feeds.engadget.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19666
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;feeds.engadget.com. IN A
;; ANSWER SECTION:
feeds.engadget.com. 2010 IN CNAME weblogsinc.feedproxy.ghs.google.com.
weblogsinc.feedproxy.ghs.google.com. 28 IN CNAME ghs.l.google.com.
ghs.l.google.com. 200 IN A 74.125.77.121
;; Query time: 78 msec
;; SERVER: 85.37.17.16#53(85.37.17.16)
;; WHEN: Wed Oct 6 20:56:36 2010
;; MSG SIZE rcvd: 118
```
You can also run a DNS query using an online service, e.g. [DNS Query](http://www.dnsqueries.com/en/dns_query.php). The DNS response should be a CNAME record pointing to `ghs.l.google.com`. If it is an `A` record, the DNS hasn't been property set. | It's definitely a DNS cache issue. I just tried a different computer and it worked. I didn't think about that until after I posted this. |
23,996 | Let me introduce my idea.
Given:
* sizeof( Blockchain ) = 16Gb
* Downloading of one avi film 16GB from the pirate bay ( 5mb/s ) = 2-3 hours
* Downloading of bitcoin's blockchain ( 5mb/s ) = 2-3 days
* One day = 6 \* 24 = 144 blocks.
* Drag - cryptography.
Task:
* Accelerate boot of fresh client to the torrent speed. Similar to **Bootstrap**.
---
As I can see, downloading of blockchain is the same hard as mining, because there is every time recalculation of hash, comparing, checking of signs, etc...
What if client will only download this 144 blocks for a day and one super block with 144 hashs of the last valid blocks, thereafter only compare current wallet's addresses with addresses in this 144 blocks without any calculation of its hash.
Is there any alt-coin with such accelerator?
---
E.g. this super blocks might be archived into another ultra-block for a month. Than we have similar to sha(sha(text)) cascade shield against bruteforce attack.
Downloading of blockchain should takes at max the same time as downloading of 16GB avi from the pirate bay. Say, 5mb/s internet channel + p2p / 16 Gb = 2, may be 3 hours ( in the `no peers case` ), but I spent 2 - 3 days, and I see that this is no internet speed reason, it is CPU + harddisk very very hard job. | 2014/03/26 | [
"https://bitcoin.stackexchange.com/questions/23996",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/12645/"
] | When a node learns of a transaction, some validity tests are performed and if the transaction is not yet in the blockchain it knows of with the longest height and the transaction also is valid (i.e., not a double spend) then that transaction is added to that node's memory pool.
If a later transaction arrives at a node but is an attempt to double spending of a transaction that is either already in the blockchain with the longest height or is already in the memory pool, then that later transaction is ignored.
A transaction propagates to nearly all miners within seconds, so most miners would immediately reject your later double-spend attempt since they would already know of the earlier transaction.
Blockchain forks happen all the time (i.e., multiple times each day). So it is entirely possible to have conflicts where a transaction is included in a block on one side of the fork but is not yet in the block (or blocks) on the other side of the fork. Eventually one of the several competing blockchain forks will emerge as the longest chain and the transactions in that chain are the ones reflected in the Bitcoin ledger from then on. That's why exchanges wait until three or six confirmations -- as it is technically possible for there to be variations between sides should a fork occur.
Attackers might use this temporary inconsistency in an attempt to defraud by employing a race attack or other approach. This is requisite reading on the topic: <http://en.bitcoin.it/wiki/Double-spending> | If chain X becomes dominant, all transactions in the now-orphan chain Y are returned to the "memory pool". When this happens, transaction 2 will not confirm because it spends an output that was already spent by transaction 1.
Likewise, if chain Y becomes dominant, all transactions in the now-orphan chain X are returned to the "memory pool". When this happens, transaction 1 will not confirm because it spends an output that was already spent by transaction 2. |
23,996 | Let me introduce my idea.
Given:
* sizeof( Blockchain ) = 16Gb
* Downloading of one avi film 16GB from the pirate bay ( 5mb/s ) = 2-3 hours
* Downloading of bitcoin's blockchain ( 5mb/s ) = 2-3 days
* One day = 6 \* 24 = 144 blocks.
* Drag - cryptography.
Task:
* Accelerate boot of fresh client to the torrent speed. Similar to **Bootstrap**.
---
As I can see, downloading of blockchain is the same hard as mining, because there is every time recalculation of hash, comparing, checking of signs, etc...
What if client will only download this 144 blocks for a day and one super block with 144 hashs of the last valid blocks, thereafter only compare current wallet's addresses with addresses in this 144 blocks without any calculation of its hash.
Is there any alt-coin with such accelerator?
---
E.g. this super blocks might be archived into another ultra-block for a month. Than we have similar to sha(sha(text)) cascade shield against bruteforce attack.
Downloading of blockchain should takes at max the same time as downloading of 16GB avi from the pirate bay. Say, 5mb/s internet channel + p2p / 16 Gb = 2, may be 3 hours ( in the `no peers case` ), but I spent 2 - 3 days, and I see that this is no internet speed reason, it is CPU + harddisk very very hard job. | 2014/03/26 | [
"https://bitcoin.stackexchange.com/questions/23996",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/12645/"
] | When a node learns of a transaction, some validity tests are performed and if the transaction is not yet in the blockchain it knows of with the longest height and the transaction also is valid (i.e., not a double spend) then that transaction is added to that node's memory pool.
If a later transaction arrives at a node but is an attempt to double spending of a transaction that is either already in the blockchain with the longest height or is already in the memory pool, then that later transaction is ignored.
A transaction propagates to nearly all miners within seconds, so most miners would immediately reject your later double-spend attempt since they would already know of the earlier transaction.
Blockchain forks happen all the time (i.e., multiple times each day). So it is entirely possible to have conflicts where a transaction is included in a block on one side of the fork but is not yet in the block (or blocks) on the other side of the fork. Eventually one of the several competing blockchain forks will emerge as the longest chain and the transactions in that chain are the ones reflected in the Bitcoin ledger from then on. That's why exchanges wait until three or six confirmations -- as it is technically possible for there to be variations between sides should a fork occur.
Attackers might use this temporary inconsistency in an attempt to defraud by employing a race attack or other approach. This is requisite reading on the topic: <http://en.bitcoin.it/wiki/Double-spending> | It isn't! The only way to be sure that a transaction is permanent (and thus be sure that the recipient will be able to spend the funds he received) is to wait until a reasonable number of confirmations (blocks mined after the block containing the transaction) |
79,602 | I'm learning Salesforce Marketing Cloud and experienced some unexpected behavior today.
I sent a message to a number of data extensions. The number of recipients was upwards of 70,000. Before I sent the official email I sent a test specifically to my address. Everything looked good so I used Guided Send to send to the data extensions.
This was 4 hours ago and I have not received the message yet but my coworker who sits across from me has. This coworker and I likely would have been in the same data extension.
I verified that my name and email address are in the data extension. Does it just take this long to distribute to a huge list? Did it not send to me since I received a test send? Or is something likely wrong?
I checked all folders in my email and do not see it.
Thank you | 2015/06/11 | [
"https://salesforce.stackexchange.com/questions/79602",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/21233/"
] | Also you can directly query in child object using relationship fields,
```
[select ISOOffice__Merchant_Location__c,Account__r.Name
from ISOOffice__Merchant_Opportunity__c where
ISOOffice__Opportunity_Type__c = 'New Merchant' AND
Account__r.Name = 'Goodwill of Southwestern Pennsylvania']
```
You need to prefix ISOOffice\_\_Merchant\_Location\_\_c with Account\_\_r, if this field is in account. | Not sure I fully follow your data model, but a [parent-child relationship query](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_and_custom_objects.htm#sforce_api_calls_soql_relationships_and_custom_objects) would look like this:
```
Account a = [
select (
select ISOOffice__Merchant_Location__c
from ISOOffice__Merchant_Opportunities__r
where ISOOffice__Opportunity_Type__c = 'New Merchant'
)
from Account
where Name = 'Goodwill of Southwestern Pennsylvania'
];
for (ISOOffice__Merchant_Opportunity__c o : a.ISOOffice__Merchant_Opportunities__r) {
String mainLocationId = o.ISOOffice__Merchant_Location__c;
...
}
```
assuming the conventional plural has been used for the relationship name. |
40,910,892 | I am trying to call Application insights API using pageviews Event and i get this error message
```
{
"error": {
"message": "Rate limit is exceeded",
"code": "ThrottledError",
"innererror": {
"code": "ThrottledError",
"message": "Rate limit of 0 per day is exceeded.",
"limitValue": 0,
"moreInfo": "https://aka.ms/api-limits"
}
}
}
```
can anyone help me fix this ? | 2016/12/01 | [
"https://Stackoverflow.com/questions/40910892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7236177/"
] | You get this issue if you are on the old pricing model, and you don't if you are on the new pricing model.
Unless you created a brand new Application Insights instance very recently, you are probably are on the old pricing model. Easiest way to tell is if you see "Features + pricing" in your Application Insights, you are on the new model.
[](https://i.stack.imgur.com/YShvQ.png)
There is no difference between changing the pricing plan (between free/standard/premium), the throttle is still there.
If you want to move to the new pricing model, Microsoft offer two options:
>
> If you’re willing to wait until February 1st, 2017, we will handle the transition automatically for you, and this will be the best option for most customers. Under this approach, we will transition your application to Application Insights Basic in most cases. (Applications using continuous export or the Connector for OMS Log Analytics will be transitioned to Application Insights Enterprise.)
>
>
> However, if you prefer to use one of the new pricing options immediately, you can also do this. It involves choosing to stop billing for your existing plan (Standard or Premium), then creating a new Application Insights resource within the Azure portal, choosing the pricing option you prefer, and then updating the Instrumentation Key within your application. One downside of doing this is that you will lose the continuity of reporting because you will have the old Instrumentation Key for your application under the Preview plan, and a new Instrumentation Key for your application under the new pricing model.
>
>
>
This can be found as the last FAQ item on the [Application Insights pricing page](https://azure.microsoft.com/en-us/pricing/details/application-insights/) | according to the link in the result you got back:
<https://aka.ms/api-limits>
it depends on what the response code was, and what other headers you get back:
>
> If requests are being made at a rate higher than this, then these requests will receive a status code 429 (Too Many Requests) along with the header Retry-After: 60 which indicates the number of seconds until requests to this application are likely to be accepted.
>
>
> In the event that the Application Insights service is under high load or is down for maintenance, a status code 503 (Service Unavailable) will be returned, and in some cases a Retry-After header may be returned.
>
>
> |
21,586,409 | I want to get notified when a test fails. Ideally, I want to know if the test is passed or failed in my @After annotated method. I understand that their is a RunListener which can be used for this purpose but it works only if we run the test with JunitCore. Is there a way to get notified if a test case fails or something similar to RunListener which can be used with SpringJUnit4ClassRunner? | 2014/02/05 | [
"https://Stackoverflow.com/questions/21586409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2943317/"
] | The Spring TestContext Framework provides a `TestExecutionListener` SPI that can be used to achieve this.
Basically, if you implement `TestExecutionListener` (or better yet extend `AbstractTestExecutionListener`), you can implement the `afterTestMethod(TestContext)` method. From the `TestContext` that is passed in you can access the exception that was thrown (if there is one).
Here's the Javadoc for `org.springframework.test.context.TestContext.getTestException()`:
>
> Get the exception that was thrown during execution of the test method.
>
>
> Note: this is a mutable property.
>
>
> Returns: the exception that was thrown, or null if no exception was
> thrown
>
>
>
FYI: you can register your customer listener via the `@TestExecutionListeners` annotation.
Regards,
Sam | An alternative is JUnits builtin `TestWatcher` Rule.
The rule allows you to opt into what things you want to be notified for. Here is a compacted example from [JUnit Github Docs](https://github.com/junit-team/junit4/wiki/Rules#testwatchmantestwatcher-rules)
```
@Test
public class WatcherTest {
@Rule
public final TestRule watcher = new TestWatcher() {
@Override
protected void failed(Throwable e, Description) {}
// More overrides exists for starting, finished, succeeded etc
};
@Test
public void test() {}
}
``` |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | There is no bi-directional link since you can not link to a non-running container.
Unless you are [disabling inter-container communication](https://docs.docker.com/articles/networking/#between-containers), all containers on the same host can *see* any other containers on the network. All you need is to provide them the ip address of the container you want to contact.
The simplest way of knowing the ip address of a container is to run:
```
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container1
```
You can look it up after starting both containers (just don't use `--link`).
If you need to know the IP of *container2* from inside *container1* automatically, there are a few options:
1. Mount the docker socket as a volume and use the remote API
docker run -i -t --name container1 -v /var/run/docker.sock:docker.sock ubuntu:trusty /bin/bash
echo -e "GET /containers/container2/json HTTP/1.0\r\n" | nc -U /docker.sock | sed 's/.*IPAddress":"([0-9.]*).\*/\1/'
2. Use an orchestration service… there are so many to choose from, but I personally like the DNS-based ones like [Skydock](https://github.com/crosbymichael/skydock) or [registrator](https://github.com/progrium/registrator) and access containers by dns name.
3. Use a docker management service (such as dockerize.it —disclaimer: I am working on it—) that will setup the DNS services for you. | Here's how I've solved this for myself:
First, I go through all my containers (which need to know from each other) and create dnsmasq entries like so:
```
for f in container1 container2 container3; do
IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $f 2>/dev/null`
if [ -n "$IP" ]; then
echo $f "$IP"
echo "host-record=$f,$IP" > /etc/dnsmasq.d/0host_$f
else
rm -f /etc/dnsmasq.d/0host_$f
fi
done
```
Then I start a dns container which has dnsmasq-base installed and starts the dnsmasq service:
```
docker run -d -P -h dns --name dns -v /etc/dnsmasq.d:/etc/dnsmasq.d:ro dns
```
then I get the IP address of this container:
```
DNS_IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' dns`
```
And start the containers like so:
```
docker run -d -P -h container1 --name container1 --dns $DNS_IP container1
docker run -d -P -h container2 --name container2 --dns $DNS_IP container2
docker run -d -P -h container3 --name container3 --dns $DNS_IP container3
```
This is a simplified version of my setup but it shows the gist. I've also added a mechanism that forces dnsmasq to rescan when files in /etc/dnsmasq.d change via inotify-tools. That way all containers get the new ip address whenever one container is restarted. |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | There is no bi-directional link since you can not link to a non-running container.
Unless you are [disabling inter-container communication](https://docs.docker.com/articles/networking/#between-containers), all containers on the same host can *see* any other containers on the network. All you need is to provide them the ip address of the container you want to contact.
The simplest way of knowing the ip address of a container is to run:
```
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container1
```
You can look it up after starting both containers (just don't use `--link`).
If you need to know the IP of *container2* from inside *container1* automatically, there are a few options:
1. Mount the docker socket as a volume and use the remote API
docker run -i -t --name container1 -v /var/run/docker.sock:docker.sock ubuntu:trusty /bin/bash
echo -e "GET /containers/container2/json HTTP/1.0\r\n" | nc -U /docker.sock | sed 's/.*IPAddress":"([0-9.]*).\*/\1/'
2. Use an orchestration service… there are so many to choose from, but I personally like the DNS-based ones like [Skydock](https://github.com/crosbymichael/skydock) or [registrator](https://github.com/progrium/registrator) and access containers by dns name.
3. Use a docker management service (such as dockerize.it —disclaimer: I am working on it—) that will setup the DNS services for you. | I solved this by appending an ip-table into /etc/hosts of each container, for
[example](https://github.com/Wei1234c/dockerfiles/blob/master/ARMv7/hadoop/cluster/start.sh) |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Docker 1.10 addresses this very nicely by introducing advanced container networking.
(Details: <https://docs.docker.com/engine/userguide/networking/dockernetworks/> )
First, create a network. The example below creates a basic "bridge" network, which works on one host only. You can check out docker's more complete documentation to do this across hosts using an overlay network.
```
docker network create my-fancy-network
```
Docker networks in 1.10 now create a special DNS resolution inside of containers that can resolve the names in a special way. First, you can continue to use --link, but as you've pointed out your example doesn't work. What I recommend is using --net-alias= in your docker run commands:
```
docker run -i -t --name container1 --net=my-fancy-network --net-alias=container1 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --net=my-fancy-network --net-alias=container2 ubuntu:trusty /bin/bash
```
Note that having --name container2 is setting the container name, which also creates a DNS entry and --net-alias=container2 just creates a DNS entry on the network, so in this particular example you could omit --net-alias but I left it there in case you wanted to rename your containers and still have a DNS alias that does not match your container name.
(Details here: <https://docs.docker.com/engine/userguide/networking/configure-dns/> )
And here you go:
```
root@4dff6c762785:/# ping container1
PING container1 (172.19.0.2) 56(84) bytes of data.
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
```
And from container1
```
root@4f16381fca06:/# ping container2
PING container2 (172.19.0.3) 56(84) bytes of data.
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=3 ttl=64 time=0.062 ms
``` | There is no bi-directional link since you can not link to a non-running container.
Unless you are [disabling inter-container communication](https://docs.docker.com/articles/networking/#between-containers), all containers on the same host can *see* any other containers on the network. All you need is to provide them the ip address of the container you want to contact.
The simplest way of knowing the ip address of a container is to run:
```
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container1
```
You can look it up after starting both containers (just don't use `--link`).
If you need to know the IP of *container2* from inside *container1* automatically, there are a few options:
1. Mount the docker socket as a volume and use the remote API
docker run -i -t --name container1 -v /var/run/docker.sock:docker.sock ubuntu:trusty /bin/bash
echo -e "GET /containers/container2/json HTTP/1.0\r\n" | nc -U /docker.sock | sed 's/.*IPAddress":"([0-9.]*).\*/\1/'
2. Use an orchestration service… there are so many to choose from, but I personally like the DNS-based ones like [Skydock](https://github.com/crosbymichael/skydock) or [registrator](https://github.com/progrium/registrator) and access containers by dns name.
3. Use a docker management service (such as dockerize.it —disclaimer: I am working on it—) that will setup the DNS services for you. |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Since there is no bidirectional link I solved this issue with the [--net](https://docs.docker.com/reference/commandline/cli/#run) argument. That way they are using the same network stack and can therefore access each other over the loopback device (localhost).
```
docker run -d --name web me/myserver
docker run -d --name selenium --net container:web me/myotherserver
```
So I can access from web the selenium server (port 4444) and my selenium server can access my web server (port 80). | Here's how I've solved this for myself:
First, I go through all my containers (which need to know from each other) and create dnsmasq entries like so:
```
for f in container1 container2 container3; do
IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $f 2>/dev/null`
if [ -n "$IP" ]; then
echo $f "$IP"
echo "host-record=$f,$IP" > /etc/dnsmasq.d/0host_$f
else
rm -f /etc/dnsmasq.d/0host_$f
fi
done
```
Then I start a dns container which has dnsmasq-base installed and starts the dnsmasq service:
```
docker run -d -P -h dns --name dns -v /etc/dnsmasq.d:/etc/dnsmasq.d:ro dns
```
then I get the IP address of this container:
```
DNS_IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' dns`
```
And start the containers like so:
```
docker run -d -P -h container1 --name container1 --dns $DNS_IP container1
docker run -d -P -h container2 --name container2 --dns $DNS_IP container2
docker run -d -P -h container3 --name container3 --dns $DNS_IP container3
```
This is a simplified version of my setup but it shows the gist. I've also added a mechanism that forces dnsmasq to rescan when files in /etc/dnsmasq.d change via inotify-tools. That way all containers get the new ip address whenever one container is restarted. |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Here's how I've solved this for myself:
First, I go through all my containers (which need to know from each other) and create dnsmasq entries like so:
```
for f in container1 container2 container3; do
IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $f 2>/dev/null`
if [ -n "$IP" ]; then
echo $f "$IP"
echo "host-record=$f,$IP" > /etc/dnsmasq.d/0host_$f
else
rm -f /etc/dnsmasq.d/0host_$f
fi
done
```
Then I start a dns container which has dnsmasq-base installed and starts the dnsmasq service:
```
docker run -d -P -h dns --name dns -v /etc/dnsmasq.d:/etc/dnsmasq.d:ro dns
```
then I get the IP address of this container:
```
DNS_IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' dns`
```
And start the containers like so:
```
docker run -d -P -h container1 --name container1 --dns $DNS_IP container1
docker run -d -P -h container2 --name container2 --dns $DNS_IP container2
docker run -d -P -h container3 --name container3 --dns $DNS_IP container3
```
This is a simplified version of my setup but it shows the gist. I've also added a mechanism that forces dnsmasq to rescan when files in /etc/dnsmasq.d change via inotify-tools. That way all containers get the new ip address whenever one container is restarted. | I solved this by appending an ip-table into /etc/hosts of each container, for
[example](https://github.com/Wei1234c/dockerfiles/blob/master/ARMv7/hadoop/cluster/start.sh) |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Docker 1.10 addresses this very nicely by introducing advanced container networking.
(Details: <https://docs.docker.com/engine/userguide/networking/dockernetworks/> )
First, create a network. The example below creates a basic "bridge" network, which works on one host only. You can check out docker's more complete documentation to do this across hosts using an overlay network.
```
docker network create my-fancy-network
```
Docker networks in 1.10 now create a special DNS resolution inside of containers that can resolve the names in a special way. First, you can continue to use --link, but as you've pointed out your example doesn't work. What I recommend is using --net-alias= in your docker run commands:
```
docker run -i -t --name container1 --net=my-fancy-network --net-alias=container1 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --net=my-fancy-network --net-alias=container2 ubuntu:trusty /bin/bash
```
Note that having --name container2 is setting the container name, which also creates a DNS entry and --net-alias=container2 just creates a DNS entry on the network, so in this particular example you could omit --net-alias but I left it there in case you wanted to rename your containers and still have a DNS alias that does not match your container name.
(Details here: <https://docs.docker.com/engine/userguide/networking/configure-dns/> )
And here you go:
```
root@4dff6c762785:/# ping container1
PING container1 (172.19.0.2) 56(84) bytes of data.
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
```
And from container1
```
root@4f16381fca06:/# ping container2
PING container2 (172.19.0.3) 56(84) bytes of data.
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=3 ttl=64 time=0.062 ms
``` | Here's how I've solved this for myself:
First, I go through all my containers (which need to know from each other) and create dnsmasq entries like so:
```
for f in container1 container2 container3; do
IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $f 2>/dev/null`
if [ -n "$IP" ]; then
echo $f "$IP"
echo "host-record=$f,$IP" > /etc/dnsmasq.d/0host_$f
else
rm -f /etc/dnsmasq.d/0host_$f
fi
done
```
Then I start a dns container which has dnsmasq-base installed and starts the dnsmasq service:
```
docker run -d -P -h dns --name dns -v /etc/dnsmasq.d:/etc/dnsmasq.d:ro dns
```
then I get the IP address of this container:
```
DNS_IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' dns`
```
And start the containers like so:
```
docker run -d -P -h container1 --name container1 --dns $DNS_IP container1
docker run -d -P -h container2 --name container2 --dns $DNS_IP container2
docker run -d -P -h container3 --name container3 --dns $DNS_IP container3
```
This is a simplified version of my setup but it shows the gist. I've also added a mechanism that forces dnsmasq to rescan when files in /etc/dnsmasq.d change via inotify-tools. That way all containers get the new ip address whenever one container is restarted. |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Since there is no bidirectional link I solved this issue with the [--net](https://docs.docker.com/reference/commandline/cli/#run) argument. That way they are using the same network stack and can therefore access each other over the loopback device (localhost).
```
docker run -d --name web me/myserver
docker run -d --name selenium --net container:web me/myotherserver
```
So I can access from web the selenium server (port 4444) and my selenium server can access my web server (port 80). | I solved this by appending an ip-table into /etc/hosts of each container, for
[example](https://github.com/Wei1234c/dockerfiles/blob/master/ARMv7/hadoop/cluster/start.sh) |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Docker 1.10 addresses this very nicely by introducing advanced container networking.
(Details: <https://docs.docker.com/engine/userguide/networking/dockernetworks/> )
First, create a network. The example below creates a basic "bridge" network, which works on one host only. You can check out docker's more complete documentation to do this across hosts using an overlay network.
```
docker network create my-fancy-network
```
Docker networks in 1.10 now create a special DNS resolution inside of containers that can resolve the names in a special way. First, you can continue to use --link, but as you've pointed out your example doesn't work. What I recommend is using --net-alias= in your docker run commands:
```
docker run -i -t --name container1 --net=my-fancy-network --net-alias=container1 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --net=my-fancy-network --net-alias=container2 ubuntu:trusty /bin/bash
```
Note that having --name container2 is setting the container name, which also creates a DNS entry and --net-alias=container2 just creates a DNS entry on the network, so in this particular example you could omit --net-alias but I left it there in case you wanted to rename your containers and still have a DNS alias that does not match your container name.
(Details here: <https://docs.docker.com/engine/userguide/networking/configure-dns/> )
And here you go:
```
root@4dff6c762785:/# ping container1
PING container1 (172.19.0.2) 56(84) bytes of data.
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
```
And from container1
```
root@4f16381fca06:/# ping container2
PING container2 (172.19.0.3) 56(84) bytes of data.
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=3 ttl=64 time=0.062 ms
``` | Since there is no bidirectional link I solved this issue with the [--net](https://docs.docker.com/reference/commandline/cli/#run) argument. That way they are using the same network stack and can therefore access each other over the loopback device (localhost).
```
docker run -d --name web me/myserver
docker run -d --name selenium --net container:web me/myotherserver
```
So I can access from web the selenium server (port 4444) and my selenium server can access my web server (port 80). |
25,324,860 | I have to link two containers so they can see each other. Of course the following...
```
docker run -i -t --name container1 --link container2:container2 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --link container1:container1 ubuntu:trusty /bin/bash
```
...fails at line 1 because a container needs to be up and running in order to be a link target:
```
2014/08/15 03:20:27 Error response from daemon: Could not find entity for container2
```
What is the simplest way to create a bidirectional link? | 2014/08/15 | [
"https://Stackoverflow.com/questions/25324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644958/"
] | Docker 1.10 addresses this very nicely by introducing advanced container networking.
(Details: <https://docs.docker.com/engine/userguide/networking/dockernetworks/> )
First, create a network. The example below creates a basic "bridge" network, which works on one host only. You can check out docker's more complete documentation to do this across hosts using an overlay network.
```
docker network create my-fancy-network
```
Docker networks in 1.10 now create a special DNS resolution inside of containers that can resolve the names in a special way. First, you can continue to use --link, but as you've pointed out your example doesn't work. What I recommend is using --net-alias= in your docker run commands:
```
docker run -i -t --name container1 --net=my-fancy-network --net-alias=container1 ubuntu:trusty /bin/bash
docker run -i -t --name container2 --net=my-fancy-network --net-alias=container2 ubuntu:trusty /bin/bash
```
Note that having --name container2 is setting the container name, which also creates a DNS entry and --net-alias=container2 just creates a DNS entry on the network, so in this particular example you could omit --net-alias but I left it there in case you wanted to rename your containers and still have a DNS alias that does not match your container name.
(Details here: <https://docs.docker.com/engine/userguide/networking/configure-dns/> )
And here you go:
```
root@4dff6c762785:/# ping container1
PING container1 (172.19.0.2) 56(84) bytes of data.
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=1 ttl=64 time=0.101 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=2 ttl=64 time=0.074 ms
64 bytes from container1.my-fancy-network (172.19.0.2): icmp_seq=3 ttl=64 time=0.072 ms
```
And from container1
```
root@4f16381fca06:/# ping container2
PING container2 (172.19.0.3) 56(84) bytes of data.
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from container2.my-fancy-network (172.19.0.3): icmp_seq=3 ttl=64 time=0.062 ms
``` | I solved this by appending an ip-table into /etc/hosts of each container, for
[example](https://github.com/Wei1234c/dockerfiles/blob/master/ARMv7/hadoop/cluster/start.sh) |
5,309,206 | I use HtmlUnit to fill form.
I have a select `SELECT_A`. After selecting option the additional elements must appear in the page. But it's not working! I simulate Firefox 3.6.
What do you think?
I tried to use `NicelyResynchronizingAjaxController()` but it does not help. | 2011/03/15 | [
"https://Stackoverflow.com/questions/5309206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/660203/"
] | One note: fireEvent should be called with `"change"` parameter, not `"onchange"`. Or `fireEvent(Event.TYPE_CHANGE);` is even better. | You can use the method `fireevent("EventName")` and pass eventname as a paramenter:
```
HtmlSelect fromselect = form.getSelectByName("droplist");
fromselect.fireEvent("onchange");
``` |
63,919,101 | I have one almost completed Java application with authentication and need to add to this project another one app to reuse auth code, for example.
As I heard there could be some kind of two "main activities" with different icons to launch them separately. Also I cannot check this info, because don't know how this named and any tries before leads me in other way.
So the question is how to register those activities in `Manifest` and how to configure `run` menu?
Or if I'm wrong - what else ways exists which could fit for my requiremrnts?
Thanks. | 2020/09/16 | [
"https://Stackoverflow.com/questions/63919101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974229/"
] | You should consider using flavors for your apps. This allows you setting different app name, icons, code for each flavor.
Here is an example for defining two flavors in your main module's build.gradle:
```
buildTypes {
debug{...}
release{...}
}
// Specifies one flavor dimension.
flavorDimensions "main"
productFlavors {
demo {
// Assigns this product flavor to the "main" flavor dimension.
// If you are using only one dimension, this property is optional,
// and the plugin automatically assigns all the module's flavors to
// that dimension.
dimension "main"
applicationId "com.appdemo"
versionNameSuffix "-demo"
}
full {
dimension "main"
applicationId "com.appfull"
versionNameSuffix "-full"
}
}
```
You can then set the resources of each app (images, code, strings...) by overriding the default files in each flavor's subdirectory i.e. yourmodule/demo/ and yourmodule/full/ | Basically need to create two entrance points using activities and add icons inside them.
So left this here just in case.
```
<activity android:name=".MainActivity_1"
android:icon="@mipmap/icon_1">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity_2"
android:icon="@mipmap/icon_2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
``` |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Using the basic recursive method for printing all binary sequence all that remains is to enforce your constraints:
```
private static void binSeq(int n, int k, String seq) {
if (n == 0) {
System.out.println(seq);
return;
}
if (n > k) {
binSeq(n - 1, k, seq + "0");
}
if (k > 0) {
binSeq(n - 1, k - 1, seq + "1");
}
}
``` | One approach is to generate all combinations of `k` values from the set of `n` numbers 0..`n-1`, and use these values to set the corresponding bits in the output.
[This Q&A](https://stackoverflow.com/q/127704/335858) explains how to generate all combinations of `k` elements from `n`. With these combinations in hand, use bitwise OR of `1 << v[c][i]` to produce the final result, where `v[c][i]` represents `i`-th number from combination number `c`. |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Here's my non-recursive take on this algorithm. Because there are `2^n` permutations of binary strings, we can use a for-loop to iterate through every possible string and check if the amount of "1"s is not equal to `k`:
```
private static void generate(int n, int k) {
for (int i = 0; i < Math.pow(2, n); i++) {
if (Integer.bitCount(i) != k) {
continue;
}
String binary = Integer.toBinaryString(i);
if (binary.length() < n) {
System.out.format("%0" + (n - binary.length()) + "d%s\n", 0, binary);
} else {
System.out.println(binary);
}
}
}
``` | One approach is to generate all combinations of `k` values from the set of `n` numbers 0..`n-1`, and use these values to set the corresponding bits in the output.
[This Q&A](https://stackoverflow.com/q/127704/335858) explains how to generate all combinations of `k` elements from `n`. With these combinations in hand, use bitwise OR of `1 << v[c][i]` to produce the final result, where `v[c][i]` represents `i`-th number from combination number `c`. |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | One approach is to generate all combinations of `k` values from the set of `n` numbers 0..`n-1`, and use these values to set the corresponding bits in the output.
[This Q&A](https://stackoverflow.com/q/127704/335858) explains how to generate all combinations of `k` elements from `n`. With these combinations in hand, use bitwise OR of `1 << v[c][i]` to produce the final result, where `v[c][i]` represents `i`-th number from combination number `c`. | int n = 4, k=2;
```
for (int i = 0; i < Math.pow(2,n) ; i++) {
int a = Integer.bitCount(i);
if (a == k) System.out.println(Integer.toBinaryString(i));
}
```
I think this is the simplest answer. |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Using the basic recursive method for printing all binary sequence all that remains is to enforce your constraints:
```
private static void binSeq(int n, int k, String seq) {
if (n == 0) {
System.out.println(seq);
return;
}
if (n > k) {
binSeq(n - 1, k, seq + "0");
}
if (k > 0) {
binSeq(n - 1, k - 1, seq + "1");
}
}
``` | int n = 4, k=2;
```
for (int i = 0; i < Math.pow(2,n) ; i++) {
int a = Integer.bitCount(i);
if (a == k) System.out.println(Integer.toBinaryString(i));
}
```
I think this is the simplest answer. |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Using the basic recursive method for printing all binary sequence all that remains is to enforce your constraints:
```
private static void binSeq(int n, int k, String seq) {
if (n == 0) {
System.out.println(seq);
return;
}
if (n > k) {
binSeq(n - 1, k, seq + "0");
}
if (k > 0) {
binSeq(n - 1, k - 1, seq + "1");
}
}
``` | **Below is the solution using Recursion as an approach in java**
```
public class NumberOfBinaryPatternsSpecificOnes {
static int[] bitArray = new int[]{0,1}; // kept binary bits in array
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int n = 4;
int k = 2;
drawBinaryPattern(n,"",k,0);
}
private static void drawBinaryPattern(int n,String seed,int numberOfOnes,int currentCount)
{
if(n==0)
{
if(currentCount==numberOfOnes){
System.out.println(seed);
}
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
int currentcountTemp = bitArray[j]==1?(currentCount+1):(currentCount);
if(currentcountTemp>numberOfOnes)
{
return;
}
drawBinaryPattern(n-1,temp,numberOfOnes,currentcountTemp);
}
}
}
``` |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Here's my non-recursive take on this algorithm. Because there are `2^n` permutations of binary strings, we can use a for-loop to iterate through every possible string and check if the amount of "1"s is not equal to `k`:
```
private static void generate(int n, int k) {
for (int i = 0; i < Math.pow(2, n); i++) {
if (Integer.bitCount(i) != k) {
continue;
}
String binary = Integer.toBinaryString(i);
if (binary.length() < n) {
System.out.format("%0" + (n - binary.length()) + "d%s\n", 0, binary);
} else {
System.out.println(binary);
}
}
}
``` | int n = 4, k=2;
```
for (int i = 0; i < Math.pow(2,n) ; i++) {
int a = Integer.bitCount(i);
if (a == k) System.out.println(Integer.toBinaryString(i));
}
```
I think this is the simplest answer. |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | Here's my non-recursive take on this algorithm. Because there are `2^n` permutations of binary strings, we can use a for-loop to iterate through every possible string and check if the amount of "1"s is not equal to `k`:
```
private static void generate(int n, int k) {
for (int i = 0; i < Math.pow(2, n); i++) {
if (Integer.bitCount(i) != k) {
continue;
}
String binary = Integer.toBinaryString(i);
if (binary.length() < n) {
System.out.format("%0" + (n - binary.length()) + "d%s\n", 0, binary);
} else {
System.out.println(binary);
}
}
}
``` | **Below is the solution using Recursion as an approach in java**
```
public class NumberOfBinaryPatternsSpecificOnes {
static int[] bitArray = new int[]{0,1}; // kept binary bits in array
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int n = 4;
int k = 2;
drawBinaryPattern(n,"",k,0);
}
private static void drawBinaryPattern(int n,String seed,int numberOfOnes,int currentCount)
{
if(n==0)
{
if(currentCount==numberOfOnes){
System.out.println(seed);
}
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
int currentcountTemp = bitArray[j]==1?(currentCount+1):(currentCount);
if(currentcountTemp>numberOfOnes)
{
return;
}
drawBinaryPattern(n-1,temp,numberOfOnes,currentcountTemp);
}
}
}
``` |
43,355,774 | So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e
for size n = 4, k=2, (there is 2 over 4 combinations)
```
1100
1010
1001
0110
0101
0011
```
I'm stuck and can't figure out how to generate this. | 2017/04/11 | [
"https://Stackoverflow.com/questions/43355774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6915563/"
] | **Below is the solution using Recursion as an approach in java**
```
public class NumberOfBinaryPatternsSpecificOnes {
static int[] bitArray = new int[]{0,1}; // kept binary bits in array
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int n = 4;
int k = 2;
drawBinaryPattern(n,"",k,0);
}
private static void drawBinaryPattern(int n,String seed,int numberOfOnes,int currentCount)
{
if(n==0)
{
if(currentCount==numberOfOnes){
System.out.println(seed);
}
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
int currentcountTemp = bitArray[j]==1?(currentCount+1):(currentCount);
if(currentcountTemp>numberOfOnes)
{
return;
}
drawBinaryPattern(n-1,temp,numberOfOnes,currentcountTemp);
}
}
}
``` | int n = 4, k=2;
```
for (int i = 0; i < Math.pow(2,n) ; i++) {
int a = Integer.bitCount(i);
if (a == k) System.out.println(Integer.toBinaryString(i));
}
```
I think this is the simplest answer. |
989,381 | I have Intel NUC i5 with Latest OpenElec installed on it.
I would like to wake it up from suspend using Wake On Lan feature (sent from another device on my home network), but I am having difficulties with that.
I have verified WOL is enabled in the BIOS, and I have tried to use the WOL Windows GUI provided in Depicious web site - www.depicus.com/wake-on-lan/wake-on-lan-gui
I have put those values in the GUI:
MAC address of the NUC
Internet address - I tried both my router IP and my NUC internal IP
Subnet mask - I've put the mask I found in the OpenElec network screen
Port - I tried ports 7 and 9.
I have also tried to configure my router (DLink) to forward port 7 to the broadcast address (10.0.0.255) - but it doesn't allow configuring port forwarding (or virtual server as it is called) to that address.
Anything I am missing? Would really appreciate help here.
Thanks! | 2015/10/20 | [
"https://superuser.com/questions/989381",
"https://superuser.com",
"https://superuser.com/users/511927/"
] | I was looking for an answer to this and just tested out a number of syncing services on my Mac by trying to copy an OSX framework. The only one that successfully copied the internal symbolic links between folders was...
* **[Copy.com](https://copy.com)** (Edit: **Service will shut down on May 1, 2016**. So that leaves us with... none.)
It seemed to work fine, symbolic links were copied as expected. I don't really know anything else about the service - I just found out about it today.
The following completely ignored the symbolic links: **Google Drive, Box, OneDrive, Mega, iCloud Drive**
The following copied the contents of the symbolic link like it was a folder (thus resulting in duplicate files): **Dropbox** | BitTorrent sync will do what the OP requests. It will copy and sync symlinks as links, without following them. It differs somewhat from services like Dropbox in that there is no cloud involved - just peer to peer communication. There is a free service and a paid service. I dropped Dropbox for this very reason, and have used BitTorrent Sync for over a year without major problem. |
989,381 | I have Intel NUC i5 with Latest OpenElec installed on it.
I would like to wake it up from suspend using Wake On Lan feature (sent from another device on my home network), but I am having difficulties with that.
I have verified WOL is enabled in the BIOS, and I have tried to use the WOL Windows GUI provided in Depicious web site - www.depicus.com/wake-on-lan/wake-on-lan-gui
I have put those values in the GUI:
MAC address of the NUC
Internet address - I tried both my router IP and my NUC internal IP
Subnet mask - I've put the mask I found in the OpenElec network screen
Port - I tried ports 7 and 9.
I have also tried to configure my router (DLink) to forward port 7 to the broadcast address (10.0.0.255) - but it doesn't allow configuring port forwarding (or virtual server as it is called) to that address.
Anything I am missing? Would really appreciate help here.
Thanks! | 2015/10/20 | [
"https://superuser.com/questions/989381",
"https://superuser.com",
"https://superuser.com/users/511927/"
] | I was looking for an answer to this and just tested out a number of syncing services on my Mac by trying to copy an OSX framework. The only one that successfully copied the internal symbolic links between folders was...
* **[Copy.com](https://copy.com)** (Edit: **Service will shut down on May 1, 2016**. So that leaves us with... none.)
It seemed to work fine, symbolic links were copied as expected. I don't really know anything else about the service - I just found out about it today.
The following completely ignored the symbolic links: **Google Drive, Box, OneDrive, Mega, iCloud Drive**
The following copied the contents of the symbolic link like it was a folder (thus resulting in duplicate files): **Dropbox** | It seems syncthing will also handle symlinks correctly (symlinks are not followed but copied as symlinks);
see relevant discussions:
<https://github.com/syncthing/syncthing/issues/262>
<https://github.com/syncthing/syncthing/issues/2358>
But I'd love to see a cloud hosted solution (unlike bt sync and syncthing) that handles symlinks correctly. |
11,230,424 | I am uncompressing a .gz-file and putting the output into `tar` with php.
My code looks like
```
$tar = proc_open('tar -xvf -', array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'a')), &$pipes);
$datalen = filesize('archive.tar.gz');
$datapos = 0;
$data = gzopen('archive.tar.gz', 'rb');
while (!gzeof($data))
{
$step = 512;
fwrite($pipes[0], gzread($data, $step));
$datapos += $step;
}
gzclose($data);
proc_close($tar);
```
It works great (tar extracts a couple directories and files) until a bit more than halfway in (according to my `$datapos`) the compressed file, then the script will get stuck at the `fwrite($pipes...)` line forever (i waited a few minutes for it to advance).
The compressed archive is 8425648 bytes (8.1M) large, the uncompressed archive is 36720640 bytes (36M) large.
What am I possibly doing wrong here, since I havn't found any resources considering a similar issue?
I'm running php5-cli version 5.3.3-7+squeeze3 (with Suhosin 0.9.32.1) on a 2.6.32-5-amd64 linux machine. | 2012/06/27 | [
"https://Stackoverflow.com/questions/11230424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522479/"
] | `1 => array('pipe', 'w')`
You have tar giving you data (file names) on stdout. You should empty that buffer. (I normally just read it.)
You can also send it to a file so you don't have to deal with it.
`1 => array('file', '[file for filelist output]', 'a')`
if you're on Linux, I like to do
`1 => array('file', '/dev/null', 'a')`
[Edit: Once it outputs enough, it'll wait for you to read from standard out, which is where you are hanging.] | Your problem is one of buffer, like [@EPB](https://stackoverflow.com/a/11231062/492901) said. Empty the stream buffer (e.g.: using `fread` on `$pipes[1]` in non-blocking mode; or simply remove the `v` switch).
I want to point out however, that `$datalen` will contain the compressed length of the data, while `$datapos` will contain the uncompressed one, because the `$step` passed to `gzread` is the *uncompressed length to read* in bytes. If you want to populate `$datalen` with the actual uncompressed archive size, use something like this:
```
$info = shell_exec('gzip -l archive.tar.gz');
$temp = preg_split('/\s+/', $info);
$datalen = $temp[6]; // the actual uncompressed filesize
```
Otherwise you'd end up with `$datapos` always being bigger than `$datalen`. |
2,079,812 | What is the difference between WPF and Silverlight?
Is it just the same as winforms vs asp as in desktop apps versus web app or is there an overlap? | 2010/01/17 | [
"https://Stackoverflow.com/questions/2079812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231822/"
] | Silverlight is a subset of the functionality in WPF. WPF is desktops, silverlight is cross-platform web apps. Silverlight can run out-of-browser with limited functionality. if you want full blown WPF and access to everything WPF can access on the client, you can't do silverlight out-of-browser - just build a WPF app.
WPF and silverlight use XAML at its core to describe the layout. There is a MS document that highlights the differences between the two. I just can't find it right now.
WPF is not dead like some bloggers are reporting. Due to its web and cross-platform capabilities it is doubtful SL will ever truly contain 100% of the functionality of its bigger brother WPF. WPF includes some very Windows-specific functionality.
Found the document mentioned above. [Here](http://wpfslguidance.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28278) it is... | WPF is a desktop API that is a replacement to the venerable pixel-based GDI Winforms library. It uses XML layout (XAML) and binding, partial classes and is no longer pixel-based (it deals in units so apps still work where the user has the DPI set differently).
Silverlight is a subset of WPF that runs within a browser, much like Flash.
Silverlight 3 [extended its reach onto the desktop](http://www.infoworld.com/d/developer-world/first-look-microsoft-silverlight-3-challenges-adobe-air-216) as a counter to Adobe Air so there isn't much of a gap between Silverlight and WPF to the point where one has to question the future of WPF. See [Silverlight 3 might kill Windows Presentation Foundation](http://www.sdtimes.com/link/33355). |
2,079,812 | What is the difference between WPF and Silverlight?
Is it just the same as winforms vs asp as in desktop apps versus web app or is there an overlap? | 2010/01/17 | [
"https://Stackoverflow.com/questions/2079812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231822/"
] | WPF is a desktop API that is a replacement to the venerable pixel-based GDI Winforms library. It uses XML layout (XAML) and binding, partial classes and is no longer pixel-based (it deals in units so apps still work where the user has the DPI set differently).
Silverlight is a subset of WPF that runs within a browser, much like Flash.
Silverlight 3 [extended its reach onto the desktop](http://www.infoworld.com/d/developer-world/first-look-microsoft-silverlight-3-challenges-adobe-air-216) as a counter to Adobe Air so there isn't much of a gap between Silverlight and WPF to the point where one has to question the future of WPF. See [Silverlight 3 might kill Windows Presentation Foundation](http://www.sdtimes.com/link/33355). | [One](https://stackoverflow.com/questions/944608/wpf-vs-silverlight) and [two](https://stackoverflow.com/questions/629927/what-is-the-difference-between-wpf-and-silverlight-application). |
2,079,812 | What is the difference between WPF and Silverlight?
Is it just the same as winforms vs asp as in desktop apps versus web app or is there an overlap? | 2010/01/17 | [
"https://Stackoverflow.com/questions/2079812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231822/"
] | Silverlight is a subset of the functionality in WPF. WPF is desktops, silverlight is cross-platform web apps. Silverlight can run out-of-browser with limited functionality. if you want full blown WPF and access to everything WPF can access on the client, you can't do silverlight out-of-browser - just build a WPF app.
WPF and silverlight use XAML at its core to describe the layout. There is a MS document that highlights the differences between the two. I just can't find it right now.
WPF is not dead like some bloggers are reporting. Due to its web and cross-platform capabilities it is doubtful SL will ever truly contain 100% of the functionality of its bigger brother WPF. WPF includes some very Windows-specific functionality.
Found the document mentioned above. [Here](http://wpfslguidance.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28278) it is... | [One](https://stackoverflow.com/questions/944608/wpf-vs-silverlight) and [two](https://stackoverflow.com/questions/629927/what-is-the-difference-between-wpf-and-silverlight-application). |
45,149 | I imported some 2000 photos into Lightroom 5 on the Mac, and then removed most of the ones in them, bringing it down to 40 photos. I did this by selecting photos I didn't like, pressing the Delete button and selecting Remove (not Delete From Disk). These removed photos are still on the filesystem, taking up 30 GB. How do I move them into the Trash on the Mac? I want to permanently delete them.
I thought Lightroom has its own trash bin, and an Empty Trash option, like iPhoto does, but it doesn't seem to.
Is there a simpler workflow to use here? I want to go through my collection, remove files I don't want, press Cmd-Z to undo a remove if I accidentally removed something and, when I'm all done, permanently delete the removed files. Is there a simpler workflow for this that I can adopt in the future? Thanks. | 2013/11/13 | [
"https://photo.stackexchange.com/questions/45149",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/22575/"
] | The problem is that Lightroom does not know about these images, so it cannot do anything about it. Essentially you want to know which photos are *not* in Lightroom. I have no idea how to do that but I think this will work:
From Lightroom, select the folder or tree where these photos are and synchronize it. It will popup the import dialog, just continue the import as usual. As an extra precaution add a keyword during import, something like "DELETE\_ME\_AGAIN".
Once done, all these photos *should* appear under the Previous Import folder. From there see if you can do a Delete From Disk. If not, go to the library view and do it from there by selecting all images matching the "DELETE\_ME\_AGAIN" keyword. | You needed to use the Delete From Disk option. You removed your reference to the images in Lightroom and it now has no more idea about them than it does about your Word documents and internet browsing history.
One thing you could do since you have so few images is you could make a new folder, drag the photos to keep in to that folder in the Library view (which will move the files on disk to the new folder.) After confirming they have been moved to the new folder, you can simply delete the contents of the previous folder by hand and then move the images back in Lightroom. Note that this will only work if all the files in that folder other than the ones in Lightroom should be deleted. |
43,675,036 | I'm quite new to SQL and databases.
I'm trying to make a preference table of an user.
The fields will be `user_id`, `pref_no`, `prg_code`.
Now if I create the table making `pref_no` `auto_increment` then it will automatically increase irrespective of the `user_id`.
So, my question is - Is there a way to define the table in such a way that it will be `auto_incremented` taking `user_id` into account or I have to explicitly find the last `pref_no` that has occurred for an user and then increment it by 1 before insertion?
Any help is appreciated. Thanks in advance. | 2017/04/28 | [
"https://Stackoverflow.com/questions/43675036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5771617/"
] | Following what `Mjh` and `Fahmina` suggested, we can create a procedure for the insertion.
```
DELIMITER //
CREATE PROCEDURE test(IN u_id INT(7), p_code INT(5))
BEGIN
SELECT @pno:= MAX(pref_no) FROM temp_choice WHERE user_id = u_id;
IF @pno IS NULL THEN
SET @pno = 1;
ELSE
SET @pno = @pno + 1;
END IF;
INSERT INTO temp_choice VALUES (u_id, @pno, p_code);
END //
DELIMITER ;
```
Now we can easily insert data by using
```
CALL test(1234567, 10101);
``` | To manage user's preference, you don't need `user_id` to be auto\_incremented in this table, but `pref_no` has to be.
`user_id` will just be a refence (or foreign key in sql) to your user table (where `user_id` should be auto\_incremented).
And to request preference for a given user your request would be :
`SELECT * FROM [user table] INNER JOIN [pref table] ON ([user table].user_id = [pref table].user_id) WHERE [user table].user_id = ?`
(replace '?' by the user\_id you want) |
34,278,600 | As per Java Concurrency in Practice below code can throw assertion Error:
If a thread other than the publishing thread were to call
assertSanity, it could throw AssertionError
```
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
```
Question is: If I save, an object which refers to other objects in a ConcurrentHashMap, is there a possibility that certain updates on this object graph will not be in sync, in a multi-threaded environment due to same reasons as mentioned for above example?
Though root node in object graph will always be updated in map for all threads, but what about other objects which are referred as fields in root node, if these are not final or volatile ? | 2015/12/14 | [
"https://Stackoverflow.com/questions/34278600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008171/"
] | Answering my own question, I should have read complete chapter before asking question. This is what later part of chapter says:
>
> Mutable objects: If an object may be modified after construction, safe
> publication ensures only the visibility of the as-published state.
> Synchronization must be used not only to publish a mutable object, but
> also every time the object is accessed to ensure visibility of
> subsequent modifications. To share mutable objects safely, they must
> be safely published and be either thread-safe or guarded by a lock.
>
>
>
So using CHM or any thread safe collection is unsafe in a multithreaded environment, unless you synchronize changes to your mutable objects in CHM or these objects are immutable. | A ConcurrentHashMap guarantee that all operation with reference (link to object), that be saved in a ConcurrentHashMap, are thread-safe, however, of course, a ConcurrentHashMap can not guarantee a thread-safe every objects, with reference(link) be stored in a ConcurrentHashMap. |
4,968,504 | I am using spring tags to in my jsp page.
Now I have a situation where I am using form:select for a dropdown.
If I select first value in the dropdown "normal.jsp" page should be diaplayed. If I select second value "reverse.jsp" page should be displayed.
Both these jsp pages should be displayed in the main page below the dropdown.
What is the best way to achieve this in jsp?
I am trying to use jstl tags but the form is not getting displayed.
This is the code I wrote
```
<tr>
<td>Types of Auction :-</td>
<td>
<form:select id="auctionType" path="auctionType">
<form:option value="0" label="Select" />
<form:options items="${auctionTypesList}" itemValue="auctionTypeId" itemLabel="auctionTypeDesc" />
</form:select>
</td>
</tr>
<tr>
<td>
<c:choose>
<c:when test="${param.auctionType == 1}">
<c:import url="/normalAuction.jsp" var="normal"/>
</c:when>
<c:when test="${param.auctionType == 2}">
<c:import url="/reverseAuction.jsp" var="reverse"/>
</c:when>
</c:choose>
</td>
</tr>
```
Can someone let me know where am I going wrong?
Thanks | 2011/02/11 | [
"https://Stackoverflow.com/questions/4968504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557068/"
] | You've not been very clear with your problem description but I can give you a place to start looking. When ever any subview of a UIScrollView is made a first responder that UISCrollView calls scrollsRectToVisible. If the scrollView is scrolling to the wrong location that may be because the tap gesture is setting the wrong UITextField to the first responder. Why this is happening, I can't say (not without code). Hope this leads you in the right direction.
Nathan
Please remember to vote. | I've answered to the same problem here: [Disable UIScrollView scrolling when UITextField becomes first responder](https://stackoverflow.com/questions/4585718/disable-uiscrollview-scrolling-when-uitextfield-becomes-first-responder/5673026#5673026)
Hope this helps! |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | Have you tried [mb-convert-encoding](http://php.net/manual/en/function.mb-convert-encoding.php) ?
Think it would be:
```
$str = mb_convert_encoding($str, "macintosh", "UTF-8");
``` | Just curious, have you tried copying the salt, saving as UTF-8 and then pasting the salt back in place and saving again? |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | You don't give enough information to confirm this, but I guess the salt is used in its binary form. In that case, changing the encoding of the file will corrupt the salt if this binary stream is changed, even if the characters are correctly converted.
Since the first 128 characters are similar in UTF-8 and Mac OS Roman, you don't have to worry if the salt is written using only these characters.
Let's say the salt is somewhere:
```
$salt = "a!c‡Œ";
```
You could write instead:
```
$salt = "a!c\xE0\xCE";
```
You could map all to their hexadecimal representation, as it might be easier to automate:
```
$salt = "\x61\x21\x63\xE0\xCE";
```
See the table [here](http://en.wikipedia.org/wiki/MacRoman).
The following snippet can automate this conversion:
```
$res = "";
foreach (str_split($salt) as $c) {
$res .= "\\x".dechex(ord($c));
}
echo $res;
``` | Have you tried [mb-convert-encoding](http://php.net/manual/en/function.mb-convert-encoding.php) ?
Think it would be:
```
$str = mb_convert_encoding($str, "macintosh", "UTF-8");
``` |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | Thanks for the input, pointed me in the right direction. The solution is:
```
$salt = iconv('UTF-8', 'macintosh', $string);
``` | Have you tried [mb-convert-encoding](http://php.net/manual/en/function.mb-convert-encoding.php) ?
Think it would be:
```
$str = mb_convert_encoding($str, "macintosh", "UTF-8");
``` |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | For those who do not have access to iconv here is a function in PHP:
<http://sebastienguillon.com/test/jeux-de-caracteres/MacRoman_to_utf8.txt.php>
It will properly convert MacRoman text to UTF-8 and you can even decide how you want to break ligatures.
```
<?php
function MacRoman_to_utf8($str, $break_ligatures='none')
{
// $break_ligatures : 'none' | 'fifl' | 'all'
// 'none' : don't break any MacRoman ligatures, transform them into their utf-8 counterparts
// 'fifl' : break only fi ("\xDE" => "fi") and fl ("\xDF"=>"fl")
// 'all' : break fi, fl and also AE ("\xAE"=>"AE"), ae ("\xBE"=>"ae"), OE ("\xCE"=>"OE") and oe ("\xCF"=>"oe")
if($break_ligatures == 'fifl')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl"));
}
if($break_ligatures == 'all')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl", "\xAE"=>"AE", "\xBE"=>"ae", "\xCE"=>"OE", "\xCF"=>"oe"));
}
$str = strtr($str, array("\x7F"=>"\x20", "\x80"=>"\xC3\x84", "\x81"=>"\xC3\x85",
"\x82"=>"\xC3\x87", "\x83"=>"\xC3\x89", "\x84"=>"\xC3\x91", "\x85"=>"\xC3\x96",
"\x86"=>"\xC3\x9C", "\x87"=>"\xC3\xA1", "\x88"=>"\xC3\xA0", "\x89"=>"\xC3\xA2",
"\x8A"=>"\xC3\xA4", "\x8B"=>"\xC3\xA3", "\x8C"=>"\xC3\xA5", "\x8D"=>"\xC3\xA7",
"\x8E"=>"\xC3\xA9", "\x8F"=>"\xC3\xA8", "\x90"=>"\xC3\xAA", "\x91"=>"\xC3\xAB",
"\x92"=>"\xC3\xAD", "\x93"=>"\xC3\xAC", "\x94"=>"\xC3\xAE", "\x95"=>"\xC3\xAF",
"\x96"=>"\xC3\xB1", "\x97"=>"\xC3\xB3", "\x98"=>"\xC3\xB2", "\x99"=>"\xC3\xB4",
"\x9A"=>"\xC3\xB6", "\x9B"=>"\xC3\xB5", "\x9C"=>"\xC3\xBA", "\x9D"=>"\xC3\xB9",
"\x9E"=>"\xC3\xBB", "\x9F"=>"\xC3\xBC", "\xA0"=>"\xE2\x80\xA0", "\xA1"=>"\xC2\xB0",
"\xA2"=>"\xC2\xA2", "\xA3"=>"\xC2\xA3", "\xA4"=>"\xC2\xA7", "\xA5"=>"\xE2\x80\xA2",
"\xA6"=>"\xC2\xB6", "\xA7"=>"\xC3\x9F", "\xA8"=>"\xC2\xAE", "\xA9"=>"\xC2\xA9",
"\xAA"=>"\xE2\x84\xA2", "\xAB"=>"\xC2\xB4", "\xAC"=>"\xC2\xA8", "\xAD"=>"\xE2\x89\xA0",
"\xAE"=>"\xC3\x86", "\xAF"=>"\xC3\x98", "\xB0"=>"\xE2\x88\x9E", "\xB1"=>"\xC2\xB1",
"\xB2"=>"\xE2\x89\xA4", "\xB3"=>"\xE2\x89\xA5", "\xB4"=>"\xC2\xA5", "\xB5"=>"\xC2\xB5",
"\xB6"=>"\xE2\x88\x82", "\xB7"=>"\xE2\x88\x91", "\xB8"=>"\xE2\x88\x8F", "\xB9"=>"\xCF\x80",
"\xBA"=>"\xE2\x88\xAB", "\xBB"=>"\xC2\xAA", "\xBC"=>"\xC2\xBA", "\xBD"=>"\xCE\xA9",
"\xBE"=>"\xC3\xA6", "\xBF"=>"\xC3\xB8", "\xC0"=>"\xC2\xBF", "\xC1"=>"\xC2\xA1",
"\xC2"=>"\xC2\xAC", "\xC3"=>"\xE2\x88\x9A", "\xC4"=>"\xC6\x92", "\xC5"=>"\xE2\x89\x88",
"\xC6"=>"\xE2\x88\x86", "\xC7"=>"\xC2\xAB", "\xC8"=>"\xC2\xBB", "\xC9"=>"\xE2\x80\xA6",
"\xCA"=>"\xC2\xA0", "\xCB"=>"\xC3\x80", "\xCC"=>"\xC3\x83", "\xCD"=>"\xC3\x95",
"\xCE"=>"\xC5\x92", "\xCF"=>"\xC5\x93", "\xD0"=>"\xE2\x80\x93", "\xD1"=>"\xE2\x80\x94",
"\xD2"=>"\xE2\x80\x9C", "\xD3"=>"\xE2\x80\x9D", "\xD4"=>"\xE2\x80\x98", "\xD5"=>"\xE2\x80\x99",
"\xD6"=>"\xC3\xB7", "\xD7"=>"\xE2\x97\x8A", "\xD8"=>"\xC3\xBF", "\xD9"=>"\xC5\xB8",
"\xDA"=>"\xE2\x81\x84", "\xDB"=>"\xE2\x82\xAC", "\xDC"=>"\xE2\x80\xB9", "\xDD"=>"\xE2\x80\xBA",
"\xDE"=>"\xEF\xAC\x81", "\xDF"=>"\xEF\xAC\x82", "\xE0"=>"\xE2\x80\xA1", "\xE1"=>"\xC2\xB7",
"\xE2"=>"\xE2\x80\x9A", "\xE3"=>"\xE2\x80\x9E", "\xE4"=>"\xE2\x80\xB0", "\xE5"=>"\xC3\x82",
"\xE6"=>"\xC3\x8A", "\xE7"=>"\xC3\x81", "\xE8"=>"\xC3\x8B", "\xE9"=>"\xC3\x88",
"\xEA"=>"\xC3\x8D", "\xEB"=>"\xC3\x8E", "\xEC"=>"\xC3\x8F", "\xED"=>"\xC3\x8C",
"\xEE"=>"\xC3\x93", "\xEF"=>"\xC3\x94", "\xF0"=>"\xEF\xA3\xBF", "\xF1"=>"\xC3\x92",
"\xF2"=>"\xC3\x9A", "\xF3"=>"\xC3\x9B", "\xF4"=>"\xC3\x99", "\xF5"=>"\xC4\xB1",
"\xF6"=>"\xCB\x86", "\xF7"=>"\xCB\x9C", "\xF8"=>"\xC2\xAF", "\xF9"=>"\xCB\x98",
"\xFA"=>"\xCB\x99", "\xFB"=>"\xCB\x9A", "\xFC"=>"\xC2\xB8", "\xFD"=>"\xCB\x9D",
"\xFE"=>"\xCB\x9B", "\xFF"=>"\xCB\x87", "\x00"=>"\x20", "\x01"=>"\x20",
"\x02"=>"\x20", "\x03"=>"\x20", "\x04"=>"\x20", "\x05"=>"\x20",
"\x06"=>"\x20", "\x07"=>"\x20", "\x08"=>"\x20", "\x0B"=>"\x20",
"\x0C"=>"\x20", "\x0E"=>"\x20", "\x0F"=>"\x20", "\x10"=>"\x20",
"\x11"=>"\x20", "\x12"=>"\x20", "\x13"=>"\x20", "\x14"=>"\x20",
"\x15"=>"\x20", "\x16"=>"\x20", "\x17"=>"\x20", "\x18"=>"\x20",
"\x19"=>"\x20", "\x1A"=>"\x20", "\x1B"=>"\x20", "\x1C"=>"\x20",
"\1D"=>"\x20", "\x1E"=>"\x20", "\x1F"=>"\x20", "\xF0"=>""));
return $str;
}
?>
``` | Have you tried [mb-convert-encoding](http://php.net/manual/en/function.mb-convert-encoding.php) ?
Think it would be:
```
$str = mb_convert_encoding($str, "macintosh", "UTF-8");
``` |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | You don't give enough information to confirm this, but I guess the salt is used in its binary form. In that case, changing the encoding of the file will corrupt the salt if this binary stream is changed, even if the characters are correctly converted.
Since the first 128 characters are similar in UTF-8 and Mac OS Roman, you don't have to worry if the salt is written using only these characters.
Let's say the salt is somewhere:
```
$salt = "a!c‡Œ";
```
You could write instead:
```
$salt = "a!c\xE0\xCE";
```
You could map all to their hexadecimal representation, as it might be easier to automate:
```
$salt = "\x61\x21\x63\xE0\xCE";
```
See the table [here](http://en.wikipedia.org/wiki/MacRoman).
The following snippet can automate this conversion:
```
$res = "";
foreach (str_split($salt) as $c) {
$res .= "\\x".dechex(ord($c));
}
echo $res;
``` | Just curious, have you tried copying the salt, saving as UTF-8 and then pasting the salt back in place and saving again? |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | Thanks for the input, pointed me in the right direction. The solution is:
```
$salt = iconv('UTF-8', 'macintosh', $string);
``` | Just curious, have you tried copying the salt, saving as UTF-8 and then pasting the salt back in place and saving again? |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | For those who do not have access to iconv here is a function in PHP:
<http://sebastienguillon.com/test/jeux-de-caracteres/MacRoman_to_utf8.txt.php>
It will properly convert MacRoman text to UTF-8 and you can even decide how you want to break ligatures.
```
<?php
function MacRoman_to_utf8($str, $break_ligatures='none')
{
// $break_ligatures : 'none' | 'fifl' | 'all'
// 'none' : don't break any MacRoman ligatures, transform them into their utf-8 counterparts
// 'fifl' : break only fi ("\xDE" => "fi") and fl ("\xDF"=>"fl")
// 'all' : break fi, fl and also AE ("\xAE"=>"AE"), ae ("\xBE"=>"ae"), OE ("\xCE"=>"OE") and oe ("\xCF"=>"oe")
if($break_ligatures == 'fifl')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl"));
}
if($break_ligatures == 'all')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl", "\xAE"=>"AE", "\xBE"=>"ae", "\xCE"=>"OE", "\xCF"=>"oe"));
}
$str = strtr($str, array("\x7F"=>"\x20", "\x80"=>"\xC3\x84", "\x81"=>"\xC3\x85",
"\x82"=>"\xC3\x87", "\x83"=>"\xC3\x89", "\x84"=>"\xC3\x91", "\x85"=>"\xC3\x96",
"\x86"=>"\xC3\x9C", "\x87"=>"\xC3\xA1", "\x88"=>"\xC3\xA0", "\x89"=>"\xC3\xA2",
"\x8A"=>"\xC3\xA4", "\x8B"=>"\xC3\xA3", "\x8C"=>"\xC3\xA5", "\x8D"=>"\xC3\xA7",
"\x8E"=>"\xC3\xA9", "\x8F"=>"\xC3\xA8", "\x90"=>"\xC3\xAA", "\x91"=>"\xC3\xAB",
"\x92"=>"\xC3\xAD", "\x93"=>"\xC3\xAC", "\x94"=>"\xC3\xAE", "\x95"=>"\xC3\xAF",
"\x96"=>"\xC3\xB1", "\x97"=>"\xC3\xB3", "\x98"=>"\xC3\xB2", "\x99"=>"\xC3\xB4",
"\x9A"=>"\xC3\xB6", "\x9B"=>"\xC3\xB5", "\x9C"=>"\xC3\xBA", "\x9D"=>"\xC3\xB9",
"\x9E"=>"\xC3\xBB", "\x9F"=>"\xC3\xBC", "\xA0"=>"\xE2\x80\xA0", "\xA1"=>"\xC2\xB0",
"\xA2"=>"\xC2\xA2", "\xA3"=>"\xC2\xA3", "\xA4"=>"\xC2\xA7", "\xA5"=>"\xE2\x80\xA2",
"\xA6"=>"\xC2\xB6", "\xA7"=>"\xC3\x9F", "\xA8"=>"\xC2\xAE", "\xA9"=>"\xC2\xA9",
"\xAA"=>"\xE2\x84\xA2", "\xAB"=>"\xC2\xB4", "\xAC"=>"\xC2\xA8", "\xAD"=>"\xE2\x89\xA0",
"\xAE"=>"\xC3\x86", "\xAF"=>"\xC3\x98", "\xB0"=>"\xE2\x88\x9E", "\xB1"=>"\xC2\xB1",
"\xB2"=>"\xE2\x89\xA4", "\xB3"=>"\xE2\x89\xA5", "\xB4"=>"\xC2\xA5", "\xB5"=>"\xC2\xB5",
"\xB6"=>"\xE2\x88\x82", "\xB7"=>"\xE2\x88\x91", "\xB8"=>"\xE2\x88\x8F", "\xB9"=>"\xCF\x80",
"\xBA"=>"\xE2\x88\xAB", "\xBB"=>"\xC2\xAA", "\xBC"=>"\xC2\xBA", "\xBD"=>"\xCE\xA9",
"\xBE"=>"\xC3\xA6", "\xBF"=>"\xC3\xB8", "\xC0"=>"\xC2\xBF", "\xC1"=>"\xC2\xA1",
"\xC2"=>"\xC2\xAC", "\xC3"=>"\xE2\x88\x9A", "\xC4"=>"\xC6\x92", "\xC5"=>"\xE2\x89\x88",
"\xC6"=>"\xE2\x88\x86", "\xC7"=>"\xC2\xAB", "\xC8"=>"\xC2\xBB", "\xC9"=>"\xE2\x80\xA6",
"\xCA"=>"\xC2\xA0", "\xCB"=>"\xC3\x80", "\xCC"=>"\xC3\x83", "\xCD"=>"\xC3\x95",
"\xCE"=>"\xC5\x92", "\xCF"=>"\xC5\x93", "\xD0"=>"\xE2\x80\x93", "\xD1"=>"\xE2\x80\x94",
"\xD2"=>"\xE2\x80\x9C", "\xD3"=>"\xE2\x80\x9D", "\xD4"=>"\xE2\x80\x98", "\xD5"=>"\xE2\x80\x99",
"\xD6"=>"\xC3\xB7", "\xD7"=>"\xE2\x97\x8A", "\xD8"=>"\xC3\xBF", "\xD9"=>"\xC5\xB8",
"\xDA"=>"\xE2\x81\x84", "\xDB"=>"\xE2\x82\xAC", "\xDC"=>"\xE2\x80\xB9", "\xDD"=>"\xE2\x80\xBA",
"\xDE"=>"\xEF\xAC\x81", "\xDF"=>"\xEF\xAC\x82", "\xE0"=>"\xE2\x80\xA1", "\xE1"=>"\xC2\xB7",
"\xE2"=>"\xE2\x80\x9A", "\xE3"=>"\xE2\x80\x9E", "\xE4"=>"\xE2\x80\xB0", "\xE5"=>"\xC3\x82",
"\xE6"=>"\xC3\x8A", "\xE7"=>"\xC3\x81", "\xE8"=>"\xC3\x8B", "\xE9"=>"\xC3\x88",
"\xEA"=>"\xC3\x8D", "\xEB"=>"\xC3\x8E", "\xEC"=>"\xC3\x8F", "\xED"=>"\xC3\x8C",
"\xEE"=>"\xC3\x93", "\xEF"=>"\xC3\x94", "\xF0"=>"\xEF\xA3\xBF", "\xF1"=>"\xC3\x92",
"\xF2"=>"\xC3\x9A", "\xF3"=>"\xC3\x9B", "\xF4"=>"\xC3\x99", "\xF5"=>"\xC4\xB1",
"\xF6"=>"\xCB\x86", "\xF7"=>"\xCB\x9C", "\xF8"=>"\xC2\xAF", "\xF9"=>"\xCB\x98",
"\xFA"=>"\xCB\x99", "\xFB"=>"\xCB\x9A", "\xFC"=>"\xC2\xB8", "\xFD"=>"\xCB\x9D",
"\xFE"=>"\xCB\x9B", "\xFF"=>"\xCB\x87", "\x00"=>"\x20", "\x01"=>"\x20",
"\x02"=>"\x20", "\x03"=>"\x20", "\x04"=>"\x20", "\x05"=>"\x20",
"\x06"=>"\x20", "\x07"=>"\x20", "\x08"=>"\x20", "\x0B"=>"\x20",
"\x0C"=>"\x20", "\x0E"=>"\x20", "\x0F"=>"\x20", "\x10"=>"\x20",
"\x11"=>"\x20", "\x12"=>"\x20", "\x13"=>"\x20", "\x14"=>"\x20",
"\x15"=>"\x20", "\x16"=>"\x20", "\x17"=>"\x20", "\x18"=>"\x20",
"\x19"=>"\x20", "\x1A"=>"\x20", "\x1B"=>"\x20", "\x1C"=>"\x20",
"\1D"=>"\x20", "\x1E"=>"\x20", "\x1F"=>"\x20", "\xF0"=>""));
return $str;
}
?>
``` | Just curious, have you tried copying the salt, saving as UTF-8 and then pasting the salt back in place and saving again? |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | You don't give enough information to confirm this, but I guess the salt is used in its binary form. In that case, changing the encoding of the file will corrupt the salt if this binary stream is changed, even if the characters are correctly converted.
Since the first 128 characters are similar in UTF-8 and Mac OS Roman, you don't have to worry if the salt is written using only these characters.
Let's say the salt is somewhere:
```
$salt = "a!c‡Œ";
```
You could write instead:
```
$salt = "a!c\xE0\xCE";
```
You could map all to their hexadecimal representation, as it might be easier to automate:
```
$salt = "\x61\x21\x63\xE0\xCE";
```
See the table [here](http://en.wikipedia.org/wiki/MacRoman).
The following snippet can automate this conversion:
```
$res = "";
foreach (str_split($salt) as $c) {
$res .= "\\x".dechex(ord($c));
}
echo $res;
``` | Thanks for the input, pointed me in the right direction. The solution is:
```
$salt = iconv('UTF-8', 'macintosh', $string);
``` |
3,211,437 | HI
I have the following (apparently simple) problem: I have to install a simple website, made by someone else, on a web hosting account. The site consists of lot and lot of HTML pages, no dynamic content, created some in MS Word and saved as html, some in frontpage, etc. A mixed bag.
I uploaded initially on a test account on my server (Win Server 2003) and it works ok.
Then I uploaded on the real web hosting (fedora / apache).
When I loaded the site in browser I see lot of odd craracters (instead of diacritics, used in html pages). Duacritics were saved as escape code, like & #350; for Ș (using codepage 1252).
The problem is, when I load the page from my own test server, the browser select automatically correct codepage (1252).
But when I load the site from public host, the same bowser loads the page using utf-8 encoding, rendering page with odd caracrets.
The test site on my server can be seen at <http://radu-stanian.dnsalias.com> and on public server at <http://radustanian.scoli.edu.ro/>
This happens no matter what browser I use (IE, ff or chrome)
What should I do to force browsers to load the pages in correct codepage?
Making changes to every page is not an option, because there are hundreds of pages, created by various peoples which could edit them further for update
Thank you | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163124/"
] | You don't give enough information to confirm this, but I guess the salt is used in its binary form. In that case, changing the encoding of the file will corrupt the salt if this binary stream is changed, even if the characters are correctly converted.
Since the first 128 characters are similar in UTF-8 and Mac OS Roman, you don't have to worry if the salt is written using only these characters.
Let's say the salt is somewhere:
```
$salt = "a!c‡Œ";
```
You could write instead:
```
$salt = "a!c\xE0\xCE";
```
You could map all to their hexadecimal representation, as it might be easier to automate:
```
$salt = "\x61\x21\x63\xE0\xCE";
```
See the table [here](http://en.wikipedia.org/wiki/MacRoman).
The following snippet can automate this conversion:
```
$res = "";
foreach (str_split($salt) as $c) {
$res .= "\\x".dechex(ord($c));
}
echo $res;
``` | For those who do not have access to iconv here is a function in PHP:
<http://sebastienguillon.com/test/jeux-de-caracteres/MacRoman_to_utf8.txt.php>
It will properly convert MacRoman text to UTF-8 and you can even decide how you want to break ligatures.
```
<?php
function MacRoman_to_utf8($str, $break_ligatures='none')
{
// $break_ligatures : 'none' | 'fifl' | 'all'
// 'none' : don't break any MacRoman ligatures, transform them into their utf-8 counterparts
// 'fifl' : break only fi ("\xDE" => "fi") and fl ("\xDF"=>"fl")
// 'all' : break fi, fl and also AE ("\xAE"=>"AE"), ae ("\xBE"=>"ae"), OE ("\xCE"=>"OE") and oe ("\xCF"=>"oe")
if($break_ligatures == 'fifl')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl"));
}
if($break_ligatures == 'all')
{
$str = strtr($str, array("\xDE"=>"fi", "\xDF"=>"fl", "\xAE"=>"AE", "\xBE"=>"ae", "\xCE"=>"OE", "\xCF"=>"oe"));
}
$str = strtr($str, array("\x7F"=>"\x20", "\x80"=>"\xC3\x84", "\x81"=>"\xC3\x85",
"\x82"=>"\xC3\x87", "\x83"=>"\xC3\x89", "\x84"=>"\xC3\x91", "\x85"=>"\xC3\x96",
"\x86"=>"\xC3\x9C", "\x87"=>"\xC3\xA1", "\x88"=>"\xC3\xA0", "\x89"=>"\xC3\xA2",
"\x8A"=>"\xC3\xA4", "\x8B"=>"\xC3\xA3", "\x8C"=>"\xC3\xA5", "\x8D"=>"\xC3\xA7",
"\x8E"=>"\xC3\xA9", "\x8F"=>"\xC3\xA8", "\x90"=>"\xC3\xAA", "\x91"=>"\xC3\xAB",
"\x92"=>"\xC3\xAD", "\x93"=>"\xC3\xAC", "\x94"=>"\xC3\xAE", "\x95"=>"\xC3\xAF",
"\x96"=>"\xC3\xB1", "\x97"=>"\xC3\xB3", "\x98"=>"\xC3\xB2", "\x99"=>"\xC3\xB4",
"\x9A"=>"\xC3\xB6", "\x9B"=>"\xC3\xB5", "\x9C"=>"\xC3\xBA", "\x9D"=>"\xC3\xB9",
"\x9E"=>"\xC3\xBB", "\x9F"=>"\xC3\xBC", "\xA0"=>"\xE2\x80\xA0", "\xA1"=>"\xC2\xB0",
"\xA2"=>"\xC2\xA2", "\xA3"=>"\xC2\xA3", "\xA4"=>"\xC2\xA7", "\xA5"=>"\xE2\x80\xA2",
"\xA6"=>"\xC2\xB6", "\xA7"=>"\xC3\x9F", "\xA8"=>"\xC2\xAE", "\xA9"=>"\xC2\xA9",
"\xAA"=>"\xE2\x84\xA2", "\xAB"=>"\xC2\xB4", "\xAC"=>"\xC2\xA8", "\xAD"=>"\xE2\x89\xA0",
"\xAE"=>"\xC3\x86", "\xAF"=>"\xC3\x98", "\xB0"=>"\xE2\x88\x9E", "\xB1"=>"\xC2\xB1",
"\xB2"=>"\xE2\x89\xA4", "\xB3"=>"\xE2\x89\xA5", "\xB4"=>"\xC2\xA5", "\xB5"=>"\xC2\xB5",
"\xB6"=>"\xE2\x88\x82", "\xB7"=>"\xE2\x88\x91", "\xB8"=>"\xE2\x88\x8F", "\xB9"=>"\xCF\x80",
"\xBA"=>"\xE2\x88\xAB", "\xBB"=>"\xC2\xAA", "\xBC"=>"\xC2\xBA", "\xBD"=>"\xCE\xA9",
"\xBE"=>"\xC3\xA6", "\xBF"=>"\xC3\xB8", "\xC0"=>"\xC2\xBF", "\xC1"=>"\xC2\xA1",
"\xC2"=>"\xC2\xAC", "\xC3"=>"\xE2\x88\x9A", "\xC4"=>"\xC6\x92", "\xC5"=>"\xE2\x89\x88",
"\xC6"=>"\xE2\x88\x86", "\xC7"=>"\xC2\xAB", "\xC8"=>"\xC2\xBB", "\xC9"=>"\xE2\x80\xA6",
"\xCA"=>"\xC2\xA0", "\xCB"=>"\xC3\x80", "\xCC"=>"\xC3\x83", "\xCD"=>"\xC3\x95",
"\xCE"=>"\xC5\x92", "\xCF"=>"\xC5\x93", "\xD0"=>"\xE2\x80\x93", "\xD1"=>"\xE2\x80\x94",
"\xD2"=>"\xE2\x80\x9C", "\xD3"=>"\xE2\x80\x9D", "\xD4"=>"\xE2\x80\x98", "\xD5"=>"\xE2\x80\x99",
"\xD6"=>"\xC3\xB7", "\xD7"=>"\xE2\x97\x8A", "\xD8"=>"\xC3\xBF", "\xD9"=>"\xC5\xB8",
"\xDA"=>"\xE2\x81\x84", "\xDB"=>"\xE2\x82\xAC", "\xDC"=>"\xE2\x80\xB9", "\xDD"=>"\xE2\x80\xBA",
"\xDE"=>"\xEF\xAC\x81", "\xDF"=>"\xEF\xAC\x82", "\xE0"=>"\xE2\x80\xA1", "\xE1"=>"\xC2\xB7",
"\xE2"=>"\xE2\x80\x9A", "\xE3"=>"\xE2\x80\x9E", "\xE4"=>"\xE2\x80\xB0", "\xE5"=>"\xC3\x82",
"\xE6"=>"\xC3\x8A", "\xE7"=>"\xC3\x81", "\xE8"=>"\xC3\x8B", "\xE9"=>"\xC3\x88",
"\xEA"=>"\xC3\x8D", "\xEB"=>"\xC3\x8E", "\xEC"=>"\xC3\x8F", "\xED"=>"\xC3\x8C",
"\xEE"=>"\xC3\x93", "\xEF"=>"\xC3\x94", "\xF0"=>"\xEF\xA3\xBF", "\xF1"=>"\xC3\x92",
"\xF2"=>"\xC3\x9A", "\xF3"=>"\xC3\x9B", "\xF4"=>"\xC3\x99", "\xF5"=>"\xC4\xB1",
"\xF6"=>"\xCB\x86", "\xF7"=>"\xCB\x9C", "\xF8"=>"\xC2\xAF", "\xF9"=>"\xCB\x98",
"\xFA"=>"\xCB\x99", "\xFB"=>"\xCB\x9A", "\xFC"=>"\xC2\xB8", "\xFD"=>"\xCB\x9D",
"\xFE"=>"\xCB\x9B", "\xFF"=>"\xCB\x87", "\x00"=>"\x20", "\x01"=>"\x20",
"\x02"=>"\x20", "\x03"=>"\x20", "\x04"=>"\x20", "\x05"=>"\x20",
"\x06"=>"\x20", "\x07"=>"\x20", "\x08"=>"\x20", "\x0B"=>"\x20",
"\x0C"=>"\x20", "\x0E"=>"\x20", "\x0F"=>"\x20", "\x10"=>"\x20",
"\x11"=>"\x20", "\x12"=>"\x20", "\x13"=>"\x20", "\x14"=>"\x20",
"\x15"=>"\x20", "\x16"=>"\x20", "\x17"=>"\x20", "\x18"=>"\x20",
"\x19"=>"\x20", "\x1A"=>"\x20", "\x1B"=>"\x20", "\x1C"=>"\x20",
"\1D"=>"\x20", "\x1E"=>"\x20", "\x1F"=>"\x20", "\xF0"=>""));
return $str;
}
?>
``` |
289,429 | I just added a second user to my Exchange 2010 box, it is in coexistence with exc2003. My account is already set up and working with a personal archive folder.
The user I just set up however is unable to see the archive in Outlook. It is visible in OWA but not outlook. I have created a test profile on my PC with the users account and still no archive, if I jump back to my profile on the same box the archive is there so I know it is not an office versions issue.
UPDATE:
I have deleted all profiles from Outlook (one of which worked with the archive) now any new profiles including my own no longer show up. I think I have broken something In exchange. I get an auto discover certificate error which I am in the process of fixing. Perhaps the 2 problems are related. Also OWA on this server runs on a custom SSL port. | 2011/07/12 | [
"https://serverfault.com/questions/289429",
"https://serverfault.com",
"https://serverfault.com/users/87374/"
] | Change the configuration of the `origin` remote. See the **REMOTES** section of the `git-push(1)` man page for details. | If I understood the situation, the following commands should set the information that you desire in for git configuration.
```
git config --global user.name "Your Name Comes Here"
git config --global user.email [email protected]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.