qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
324,562
``` telnet www.ietf.org 80 GET /rfc.html HTTP/1.1 Host: www.ietf.org ``` This sequence of commands starts up a telnet (i.e., TCP) connection to port 80 on IETF’s Web server, www.ietf.org. Then comes the GET command naming the path of the URL and the protocol. Try servers and URLs of your choosing. The next line is the mandatory Host header. 1. Can we use `ssh` instead of `telnet`, something like ``` ssh www.ietf.org 80 GET /rfc.html HTTP/1.1 Host: www.ietf.org ``` ? 2. What **other programs** besides `ssh` can be used in place of `telnet` in the above example to establish a connection from a local host to a remote http server, so that we can send a http request to the http server and receive a http response from it? What **kind of programs** can be used in place of `telent` in the above example? Thanks.
2016/11/19
[ "https://unix.stackexchange.com/questions/324562", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/674/" ]
To reconfigure the keyboard in Debian, run (as `root`, or using `sudo`): ``` dpkg-reconfigure keyboard-configuration ``` Link to official Debian documentation [here](https://wiki.debian.org/Keyboard). If your keys are "random" (I have been there, not fun!), try to find the characters needed to execute the command above.
I've come up with an alternate solution to my problem. Ultimately, my issue was the keyboard was registered as `gb` (great britain) instead of `us`. To fix this, I had the prerequisites of `keyboard-configuration` and `console-setup` installed (not sure if the latter is actually necessary) and changed the file `/etc/default/keyboard`. A quick script to do this ``` sed -i 's/gb/us/g' /etc/default/keyboard service keyboard-setup restart ```
72,315,325
Using react native with typescript and redux toolkit Hi I'm bothering with render a list of messages via FlatList. By ScrollView everything rendering good but I need to implement infiniti scroll. So I'm doing something like this ``` const MessagesScreen = () => { const companyId = useAppSelector(getCompanyId); const userId = useAppSelector(getUserId); const { data: messages, isLoading, refetch } = useGetMessagesQuery({ userId, companyId }); useFocusEffect(refetch); return ( <FlatList data={messages} renderItem={() => { <Messages messages={messages} />; }} /> ); }; ``` In `return()` I'm trying to render FlatList with component Messages which is down here: ``` const Messages = ({ messages }: { messages: Message[] }) => { const navigation = useNavigation<RootStackScreenProps<'DrawerNavigator'>['navigation']>(); const { colors } = useTheme(); return ( <View style={styles.container}> {messages.map(message => { const createdAt = message.created_at; const isRead = message.read; const icon = isRead ? 'email-open-outline' : 'email-outline'; const onClick = () => { navigation.navigate('Message', { messageId: message.id }); }; return ( <TouchableOpacity key={message.id} onPress={onClick}> <View style={[styles.message, { borderBottomColor: colors.separator }]} > <View style={styles.iconPart}> <Icon name={icon} type="material-community" style={ isRead ? { color: colors.separator } : { color: colors.inputFocus } } size={24} ></Icon> </View> <View style={styles.bodyPart}> <Text numberOfLines={1} style={[isRead ? styles.readSubject : styles.unReadSubject]} > {message.subject} </Text> <Text numberOfLines={1} style={[isRead ? styles.readBody : styles.unReadBody]} > {message.body} </Text> </View> <View style={styles.datePart}> <Text style={{ color: colors.shadow }}> {dayjs(createdAt).fromNow()} </Text> </View> </View> </TouchableOpacity> ); })} </View> ); }; ``` Actually behaviour is just rendering white screen with error ``` Possible Unhandled Promise Rejection (id: 17): Error: Objects are not valid as a React child (found: object with keys {id, msg_type, created_at, subject, body, author, company_id, read}). If you meant to render a collection of children, use an array instead. ```
2022/05/20
[ "https://Stackoverflow.com/questions/72315325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15032294/" ]
there is problem with your call back function: **you are not returning Messages component** **1:Remove curly braces** ```js return ( <FlatList data={messages} renderItem={() => <Messages messages={messages}/> } /> ); ``` **2:Add return statement** ```js return ( <FlatList data={messages} renderItem={() => { return <Messages messages={messages} />; }} /> ); ```
Couple things: You're using the renderItem callback incorrectly: ``` <FlatList data={messages} renderItem={() => { // ^ ignoring the renderItem props return <Messages messages={messages} />; }} /> ``` Here, for each item in the messages array, you're rendering a component and passing *all* the messages into it. So you'll get repeated elements. The `renderItem` callback is passed `{item, index}` where item is the CURRENT item in the array (index is the index into the array) See docs here: <https://reactnative.dev/docs/flatlist> The usual thing is the renderItem callback renders ONE item at a time, like this: ``` <FlatList data={messages} renderItem={({item}) => { return <Message message={item} />; }} /> ``` e.g. I'd make a `<Message/>` component that renders one item only.
33,576,572
[![Vector plot made in Python](https://i.stack.imgur.com/y4Odp.png)](https://i.stack.imgur.com/y4Odp.png) I am solving a lid-driven cavity flow problem. For creating the figure, I chose Python because it was the only language I know that has such a feature. For the figure, I have to plot streamlines and vector arrows. See the figure. Here is the line of code in question: `plt.quiver(x, y, u, v, color='black', headwidth=1, scale = 10, headlength=4)` My problem is the size of the black vector arrows, not the blue streamlines. I would like to have larger vector arrows with less arrow density. Is there anyway I can do this in Python? I have not seen this elsewhere.
2015/11/06
[ "https://Stackoverflow.com/questions/33576572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Based on the [answer provided here](https://stackoverflow.com/a/25343170/5067311), you can prune your input arrays into `quiver` by using strides, as in `x[::2,::2]` etc. to use only every second element of the arrays. To spare some writing, you can define a `slice` to do the bulk of the notation for you: ``` skip = (slice(None, None, 2), slice(None, None, 2)) plt.quiver(x[skip], y[skip], u[skip], v[skip], color='black', headwidth=1, scale=10, headlength=4) ``` This will use every second data point. Obviously, for a different factor for rarification, change the integers in the definition of `skip`. The automatic arrow scaling of `plt.quiver` should do most of the job for you, you just have to find a satisfactory input point density.
Based on @Andras Deak's excellent answer above, you can implement a similar slice for data from an `xarray` dataset. To explain further, if you use the positional indexing `x[skip],y[skip]`, you can potentially slice the wrong dimensions. For example, if the `u` variable has dimensions `(time,x,y)`, you could slice the time dimension, when you meant to slice along the x and y dimensions. In xarray, you can use the dimension names to only index into the correct dimensions. So, here would be the equivalent example as above, if we assumed the variables are contained in an xarray dataset `ds`, with dimension names `xdim` and `ydim` and coordinates `x` and `y` . ``` skip = dict(xdim=slice(None,None,2),ydim=slice(None,None,2)) plt.quiver(ds.x.isel(skip),ds.y.isel(skip),ds.u.isel(skip),ds.v.isel(skip) ```
64,632,871
hello everyone I have two dataframes and I'd like to join information from one df to another one in a specific way. I'm gonna explain better. Here is my first df where i'd like to add 6 columns (general col named col1, col2 and so on..): ``` res1 res4 aa1234 1 AAAAAA 1 4 IVGG 2 AAAAAA 8 11 RPRQ 3 AAAAAA 10 13 RQFP 4 AAAAAA 12 15 FPFL 5 AAAAAA 20 23 NQGR 6 AAAAAA 32 35 HARF ``` here is the 2nd df: ``` res1 dist 1 3.711846 1 3.698985 2 4.180874 2 3.112819 3 3.559737 3 3.722107 4 3.842375 4 3.914970 5 3.361647 5 2.982788 6 3.245118 6 3.224230 7 3.538315 7 3.602273 8 3.185184 8 2.771583 9 4.276871 9 3.157737 10 3.933783 10 2.956738 ``` Considering "res1" I'd like to add to the 1st df in my new 6 columns the first 6th values contained in "dist" of second df corresponding to res1 = 1. After, in the 1st df I have res1 = 8, so I'd like to add in the new 6 columns the 6 values from res1 = 8 contained in "dist" of 2nd df. I'd like to obtain something like this ``` res1 res4 aa1234 col1 col2 col3 col4 col5 col6 1 4 IVGG 3.71 3.79 4.18 3.11 3.55 3.72 8 11 RPRQ 3.18 2.77 4.27 3.15 3.93 2.95 10 13 RQFP 12 15 FPFL 20 23 NQGR 32 35 HARF ``` Please consider that I have to do it on a large dataset and for 1000 and more files... thanks!
2020/11/01
[ "https://Stackoverflow.com/questions/64632871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14467368/" ]
All of this is not necessary. You can simply try to convert the input to a `float`. If it throws an error, it means that the input is not a valid number. You can catch this error using a `try-except` block and print `Invalid`: ``` while True: num1 = input("Enter First Number: ") try: num1 = float(num1) break except ValueError: print("Invalid") ``` Output: ``` Enter First Number: >? 1` Invalid Enter First Number: >? 1-0-0 Invalid Enter First Number: >? 100 ```
Instead of checking whether the string contains an alphabetic character or a special character, you can check directly whether it represents a number or not: ```py def input_number(prompt_msg, err_msg): we_got_a_number = False while not we_got_a_number: num_string = input(prompt_msg) try: num = int(num_string) we_got_a_number = True except ValueError: print(err_msg) return num num1 = input_number("Enter First Number: ", "Invalid, Try Again.") ``` If you want to use `float`s instead of `int`s, just replace `int(num_string)` with `float(num_string)`.
64,632,871
hello everyone I have two dataframes and I'd like to join information from one df to another one in a specific way. I'm gonna explain better. Here is my first df where i'd like to add 6 columns (general col named col1, col2 and so on..): ``` res1 res4 aa1234 1 AAAAAA 1 4 IVGG 2 AAAAAA 8 11 RPRQ 3 AAAAAA 10 13 RQFP 4 AAAAAA 12 15 FPFL 5 AAAAAA 20 23 NQGR 6 AAAAAA 32 35 HARF ``` here is the 2nd df: ``` res1 dist 1 3.711846 1 3.698985 2 4.180874 2 3.112819 3 3.559737 3 3.722107 4 3.842375 4 3.914970 5 3.361647 5 2.982788 6 3.245118 6 3.224230 7 3.538315 7 3.602273 8 3.185184 8 2.771583 9 4.276871 9 3.157737 10 3.933783 10 2.956738 ``` Considering "res1" I'd like to add to the 1st df in my new 6 columns the first 6th values contained in "dist" of second df corresponding to res1 = 1. After, in the 1st df I have res1 = 8, so I'd like to add in the new 6 columns the 6 values from res1 = 8 contained in "dist" of 2nd df. I'd like to obtain something like this ``` res1 res4 aa1234 col1 col2 col3 col4 col5 col6 1 4 IVGG 3.71 3.79 4.18 3.11 3.55 3.72 8 11 RPRQ 3.18 2.77 4.27 3.15 3.93 2.95 10 13 RQFP 12 15 FPFL 20 23 NQGR 32 35 HARF ``` Please consider that I have to do it on a large dataset and for 1000 and more files... thanks!
2020/11/01
[ "https://Stackoverflow.com/questions/64632871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14467368/" ]
All of this is not necessary. You can simply try to convert the input to a `float`. If it throws an error, it means that the input is not a valid number. You can catch this error using a `try-except` block and print `Invalid`: ``` while True: num1 = input("Enter First Number: ") try: num1 = float(num1) break except ValueError: print("Invalid") ``` Output: ``` Enter First Number: >? 1` Invalid Enter First Number: >? 1-0-0 Invalid Enter First Number: >? 100 ```
Instead of warn for alpha, you can warn for non digit : ``` if !num1.isisdigit(): print("Invalid, Try Again.") continue ```
25,963,818
I have an issue that relates to threading, cleaning up unmanaged resources and shutting down my app. In the main UI thread I have a method that creates a new instance of class Worker. In Worker's constructor I start a new thread that has a while(Scanning) loop that updates some controls in my UI using Invoke() continuously (until Scanning bool is set to false). In the UI thread I raise the event FormClosing() whenever the application is closing down (through X button or Application.Exit() etc.). In FormClosing() I set Scanning to false and do some cleanup of unmanaged resources (that can only be done after the worker thread is done, because it uses those resources. The problem is that when I close the app down the MainForm apparently gets instantly disposed, so the app crashes at the Invoke (because it is trying to make a delegate run from UI thread, but that thread is disposed). In an attempt to make the worker finish before the UI closes I tried to create a method StopWorker() in the worker class where I put Scanning = false, and then Thread.Join. As you can imagine the Join caused a deadlock as it makes the UI thread sleep but the Invoke needs the UI thread to move on. In summary I need to cleanup unmanaged resources in FormClosing. I need the worker thread to be done before I do that though, as it uses these resources. The worker thread cannot finish (it uses Invoke) if the MainForm is disposed, therefore creating a tricky situation.
2014/09/21
[ "https://Stackoverflow.com/questions/25963818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059350/" ]
Based on Hans Passant's answer [here](https://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event/1732361#1732361), I created the below solution. It seems to be working very well. In UI class/thread: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { var button = sender as Button; if (button != null && string.Equals(button.Name, @"CloseButton")) { //FormClosing event raised by a user-created button action } else { //FormClosing event raised by program or the X in top right corner //Do cleanup work (stop threads and clean up unmanaged resources) if (_bw.Scanning) { _bw.Scanning = false; ClosePending = true; e.Cancel = true; return; } //Code to clean up unmanaged resources goes here (dummy code below) ApplicationLogger.Get.Log("Doing final cleanup work and exiting application..."); MemoryHandler.Get.Dispose(); ApplicationLogger.Get.Dispose(); } } ``` My worker thread is in another class that has a public bool property called Scanning. It also has this while loop (notice the line at the bottom): ``` private void Worker() { while (Scanning) { Thread.Sleep(50); _sendBackValue[0] = "lbOne"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbTwo"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbThree"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); } MainForm.Get.Invoke((Action)(() => MainForm.Get.StopScanning())); } ``` Finally, back in the UI class/thread I have this method: ``` public void StopScanning() { if (!ClosePending) return; ApplicationLogger.Get.Log("Worker thread is closing the application..."); Close(); } ```
Could you not better use the BackgroundWorker class/control? It is much easier to use because it has already a lot of synchronization stuff in it. But if you have a separate thread, in your FormClosing event, use: ``` yourThread.Abort(); yourThread.Join(); // or yourThread.Join(1000); where 1000 is some kind of time out value ``` in your thread use try-excpet-finally construct ``` try { // do your stuff } catch (ThreadAbortException) { // do someting when your thread is aborted } finally { // do the clean up. Don't let it take too long. } ``` Note that the Join command will block further execution until the thread has stopped. Therefore, I would recommend a not too high value for the time out parameter, otherwise the user interface will be blocked and will irritate users.
25,963,818
I have an issue that relates to threading, cleaning up unmanaged resources and shutting down my app. In the main UI thread I have a method that creates a new instance of class Worker. In Worker's constructor I start a new thread that has a while(Scanning) loop that updates some controls in my UI using Invoke() continuously (until Scanning bool is set to false). In the UI thread I raise the event FormClosing() whenever the application is closing down (through X button or Application.Exit() etc.). In FormClosing() I set Scanning to false and do some cleanup of unmanaged resources (that can only be done after the worker thread is done, because it uses those resources. The problem is that when I close the app down the MainForm apparently gets instantly disposed, so the app crashes at the Invoke (because it is trying to make a delegate run from UI thread, but that thread is disposed). In an attempt to make the worker finish before the UI closes I tried to create a method StopWorker() in the worker class where I put Scanning = false, and then Thread.Join. As you can imagine the Join caused a deadlock as it makes the UI thread sleep but the Invoke needs the UI thread to move on. In summary I need to cleanup unmanaged resources in FormClosing. I need the worker thread to be done before I do that though, as it uses these resources. The worker thread cannot finish (it uses Invoke) if the MainForm is disposed, therefore creating a tricky situation.
2014/09/21
[ "https://Stackoverflow.com/questions/25963818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059350/" ]
Based on Hans Passant's answer [here](https://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event/1732361#1732361), I created the below solution. It seems to be working very well. In UI class/thread: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { var button = sender as Button; if (button != null && string.Equals(button.Name, @"CloseButton")) { //FormClosing event raised by a user-created button action } else { //FormClosing event raised by program or the X in top right corner //Do cleanup work (stop threads and clean up unmanaged resources) if (_bw.Scanning) { _bw.Scanning = false; ClosePending = true; e.Cancel = true; return; } //Code to clean up unmanaged resources goes here (dummy code below) ApplicationLogger.Get.Log("Doing final cleanup work and exiting application..."); MemoryHandler.Get.Dispose(); ApplicationLogger.Get.Dispose(); } } ``` My worker thread is in another class that has a public bool property called Scanning. It also has this while loop (notice the line at the bottom): ``` private void Worker() { while (Scanning) { Thread.Sleep(50); _sendBackValue[0] = "lbOne"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbTwo"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbThree"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); } MainForm.Get.Invoke((Action)(() => MainForm.Get.StopScanning())); } ``` Finally, back in the UI class/thread I have this method: ``` public void StopScanning() { if (!ClosePending) return; ApplicationLogger.Get.Log("Worker thread is closing the application..."); Close(); } ```
Disclaimer: *I do not advocate the use of `Thread`, `ManualResetEvent` and, above all, `volatile` in the .NET 4.5+ era, but since the .NET version was not specified I've done my best to address the problem while keeping things as backwards-compatible as possible.* Here's a solution which uses a polling variable and a `ManualResetEvent` to block the execution of the `FormClosing` handler until the loop has completed - without any deadlocks. In your scenario if you have a class-level reference to the `Thread` which runs the loop, you can use `Thread.Join` instead of `ManualResetEvent.WaitOne` in the `FormClosing` handler - the semantics will be the same. ``` using System; using System.Threading; using System.Windows.Forms; namespace FormClosingExample { public partial class Form1 : Form { private volatile bool Scanning = true; private readonly ManualResetEvent LoopFinishedMre = new ManualResetEvent(false); private readonly SynchronizationContext UiContext; public Form1() { this.InitializeComponent(); // Capture UI context. this.UiContext = SynchronizationContext.Current; // Spin up the worker thread. new Thread(this.Loop).Start(); } private void Loop() { int i = 0; while (this.Scanning) { // Some operation on unmanaged resource. i++; // Asynchronous UI-bound action (progress reporting). // We can't use Send here because it will deadlock if // the call to WaitOne sneaks in between the Scanning // check and sync context dispatch. this.UiContext.Post(_ => { // Note that it is possible that this will // execute *after* Scanning is set to false // (read: when the form has already closed), // in which case the control *might* have // already been disposed. if (this.Scanning) { this.Text = i.ToString(); } }, null); // Artifical delay. Thread.Sleep(1000); } // Tell the FormClosing handler that the // loop has finished and it is safe to // dispose of the unmanaged resource. this.LoopFinishedMre.Set(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Tell the worker that it needs // to break out of the loop. this.Scanning = false; // Block UI thread until Loop() has finished. this.LoopFinishedMre.WaitOne(); // The loop has finished. It is safe to do cleanup. MessageBox.Show("It is now safe to dispose of the unmanaged resource."); } } } ``` Now, while this solution is (somewhat) tailored to your *description* of the problem (which I interpreted to the best of my ability), I had to make a large number of assumptions. If you want a *better* answer, you'll need to post a concise repro of the problem - not necessarily your production code, but at least a trimmed down *working* version which still has all the main nuts and bolts in place and exhibits the problem you've described.
41,881
I would like to use the title color of my `beamer` presentation (some kind of blue) to write some inline text with the same color. Therefore I want to know the color definition. Is there a command for using the same color as the title? My preamble definitions are: ``` \mode<presentation> { \usetheme{Warsaw} } \usecolortheme{crane} ``` **EDIT:** ``` \documentclass{beamer} \usepackage{caption} \mode<presentation> { \usetheme{Warsaw} } \usecolortheme{crane} \begin{document} \begin{frame}{\bf This is the title's color I want to ``copy''} \begin{itemize} \item I want to use the ``blue'' color from the title for the caption of the table. \end{itemize} \vspace{1.5\baselineskip} \begin{table} \begin{tabular}{c|c} table1 & trial \\ \hline \hline 1 & 2 \\ 3 & 4 \end{tabular} \caption*{My table} \end{table} \end{frame} \end{document} ```
2012/01/22
[ "https://tex.stackexchange.com/questions/41881", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10529/" ]
You can copy the color from the frame title this way: ``` \caption*{\usebeamercolor[fg]{frametitle}{My table}} ```
The command `\usebeamercolor[fg]{title in head/foot}` (see p. 186 <http://www.tex.ac.uk/CTAN/macros/latex/contrib/beamer/doc/beameruserguide.pdf>) should provide you with the (text) color used in the header, even if you later decide to change your theme or change the title text color yourself in the preamble.
57,239,371
I want to disable caching or restrict the cache to 24 hours. My ApolloClient runs exclusively on the Server side. My environment: * apollo-boost 0.4.3 * graphql 14.1.1 * apollo-link-batch-http - 1.2.12 Right now, that's how I configure my `ApolloClient`. ``` new ApolloClient({ ssrMode: true, cache: new InMemoryCache(), link: WithApollo.BatchLink(), credentials: 'same-origin', }); ``` [The closest thing I saw in docs is `FetchOptions`](https://www.apollographql.com/docs/react/essentials/get-started/#configuration-options) ... But it doesn't specify what options i can actually pass to achieve my need for disabling or restricting the cache.
2019/07/28
[ "https://Stackoverflow.com/questions/57239371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631086/" ]
This is where `pandas` library comes with real power and conciseness: with [`pandas.read_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)/[`pandas.Dataframe.to_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html) one-liner: ``` import pandas as pd pd.read_csv('input.csv', sep=',').to_csv('output.csv', sep=';', index=False) ``` The final `output.csv` contents: ``` DCA.P/C.05820;5707119001793;P/C STEELSERIES SURFACE QcK MINI;5,4;Yes DCA.P/C.05821;5707119001779;P/C STEELSERIES SURFACE QcK;7,2;No DCA.P/C.05823;5707119001762;P/C STEELSERIES SURFACE QcK+;11,9;No ```
You don't have to worry about comma - csv will care of it ``` import csv with open('input.csv') as file_in, open('output.csv', 'w') as file_out: csv_in = csv.reader(file_in, delimiter=',') csv_out = csv.writer(file_out, delimiter=';') for row in csv_in: csv_out.writerow(row) ``` or even using `writerows()` to write all rows ``` import csv with open('input.csv') as file_in, open('output.csv', 'w') as file_out: csv_in = csv.reader(file_in, delimiter=',') csv_out = csv.writer(file_out, delimiter=';') csv_out.writerows(csv_in) ```
11,415,365
I am fairly new to webworks. I am trying to get the camera api to work and I keep getting the error: Error in supported: TypeError: 'undefined' is not an object (evaluating 'blackberry.media.camera') The page I am trying to use is on a hosted server. The code is as follows: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" id="viewport" content="height=device-height,width=device-width,user-scalable=no" /> <script language="javascript" type="text/JavaScript" > function takePicture() { try { blackberry.media.camera.takePicture(successCB, closedCB, errorCB); } catch(e) { alert("Error in supported: " + e); } } function successCB(filePath) { document.getElementById("path").innerHTML = filePath; //alert("Succeed: " + filePath); } function closedCB() { // alert("Camera closed event"); } function errorCB(e) { alert("Error occured: " + e); } </script> <title>Camera Test Widget</title> </head> <body > <p>Test the Camera by pressing the button below</p> <b><a href="#" onclick="takePicture();">Take a Picture</a></b> <div id="path"></div> </body> </html> ``` And my config.xml file is as follows: ``` <?xml version="1.0" encoding="UTF-8"?> <widget xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets" version="1.0.0.0" rim:header="WebWorks Sample"> <access uri="http://www.flyloops.net/" subdomains="true"> <feature id="blackberry.app.event" required="true" version="1.0.0.0"/> <feature id="blackberry.media.camera" /> </access> <name>Flyloops.net</name> <description>This is a sample application.</description> <content src="index.html"/> </widget> ``` The page is hosted at: <http://www.flyloops.net/mobile/bb/camera.html> I have been tearing my hair out for the past 3 hours...any help would be greatly appreciated.
2012/07/10
[ "https://Stackoverflow.com/questions/11415365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515055/" ]
If using PlayBook, make sure to have the correct element(s) defined <https://developer.blackberry.com/html5/apis/blackberry.media.camera.html> otherwise, if you are trying to access the blackberry.media.camera API *from* a remote website, then you need to white list that correctly in config.xml like this: ``` <access uri="http://www.flyloops.net/" subdomains="true"> <feature id="blackberry.media.camera" /> </access> ```
What device are you running? The code seems fine and it should work. You can get the eventlogs from the device and see what exceptions are being thrown. Thanks Naveen M
61,160,922
I want to be able to import SVG files from the file system, layer them, change their fill colors, and then export them as a single vector file.
2020/04/11
[ "https://Stackoverflow.com/questions/61160922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7214070/" ]
The solution to this problem was simply to import the SVG data as a string, swap out constants for various properties, and then write the new string to the file system. For example, the following svg displays an orange circle: ```html <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <circle cx="500" cy="500" r="500" fill="orange"/> </svg> ``` If you wanted to be able to dynamically change the color of the circle, you could just replace the "orange" text with a placeholder name, such as "{FILL\_COLOR}". Now, the SVG should look like this: ```html <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/> </svg> ``` In your code, you can load the file from the file system as a string and then make changes to it as needed; you could then write the result to the file system. This solution also works perfectly on frontends. Instead of loading the SVG from the file system, simply have it as a hard-coded constant. Once you make the changes to the SVG, you can use the result however you want. ```js function getCircle(color) { const svg = `<svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"><circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/></svg>`; return svg.replace('{FILL_COLOR}', color); } ```
The best source to refer would be their official docs: <https://svgjs.dev/docs/3.0/getting-started/> The next in the line source would be stack-overflow's search by svg.js tag: <https://stackoverflow.com/questions/tagged/svg.js> Now a quick intro from my side. SVG.JS lets you work very extensively with SVGs. You can import an SVG into your code and start manipulating it. You can change color, size and even add events and animations. However before you start working with SVGs, you should make sure that the SVG is compressed using some online tool like this: <https://jakearchibald.github.io/svgomg/> and after compressions you should edit your SVG file by adding class selectors within your SVG for paths (regions) so that you can select these paths from your JS code. Example of SVG from one of the projects where I used this technique (trimmed for the sake of simplicity): ``` <svg id="svg-map" class="svg-map" version="1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 363 624"> <path class="svg-path-1" fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10" d="M114 ... 24 42z"/> <path class="svg-path-2" fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10" d="M114 ... 24 42z"/> <path class="svg-path-3" fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10" d="M114 ... 24 42z"/> </svg> ``` You can save your SVG in some folder and render it using the image tag on your HTML page. Install in your project (Example using NodeJS): ``` npm install svg.js ``` Then import this library into your JS code like this: ``` import { SVG } from '@svgdotjs/svg.js' ``` And now you can select the SVG from your page using the code like this: ``` let mapContainer = SVG.select('.some-svg-class'); let myMapObject = mapContainer.first(); ``` And set the viewport: ``` myMapObject.viewbox(0, 0, 500, 700); ``` Now you can loop across all the paths (regions) of the map and perform some manipulation like this: ``` let svgRegionPaths = myMapObject.select('path'); svgRegionPaths.each(function(i, children) { this.opacity(0.7); }); ``` This is just an example. You can do a lot more with this library. I haven't shown the example of selecting paths by class selectors but I hope you get the idea. I was able to pair this with React and make it work more in line with my coding style and requirements for the application.
56,765,872
I am trying to achieve that C interprets my string as macro. Hey, let's suppose there is a defined macro as, ``` #define ABC 900 ``` If i define; ``` char* s[] = "ABC" ; ``` then, ``` printf("%d",s) ; ``` Is there any way the compiler understands that "ABC" as macro ABC and passes 900 integer value to printf ? ``` #include<stdio.h> #define abc 15 int main(void) { char a[] = "abc" ; printf("%d",a); return 0; } ``` When i try the above code, instead of my desired output 15 , i get 6487568 which i guess the integer equivalent of that string. Edit : those were random values , or address of strings. ( as stated below by others )
2019/06/26
[ "https://Stackoverflow.com/questions/56765872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11701071/" ]
No, what you're trying to do is double impossible. You can't access variables by name at runtime (string -> variable) because the compiled machine code knows nothing about the names in your C code, and you can't access macros from the compiler because the compiler knows nothing about macros (they're expanded by the preprocessor before the compiler even sees the code). In other words, compilation / execution happens in multiple stages: 1. C source code is preprocessed (which gets rid of directives like `#include` or `#define` and expands macros). 2. The preprocessed token stream is passed to the compiler, which converts it to machine code (a runnable program). 3. Finally the program runs. Simplified example: ``` // original C code #define FOO 42 ... int x = y + FOO; ``` After preprocessing: ``` ... int x = y + 42; ``` After compilation: ``` movl %ecx, %eax addl $42, %eax ``` There is no trace of `FOO` in step 2, and the final code knows nothing about `x` or `y`. Variable values such as strings only exist at runtime, in step 3. You can't get back to step 1 from there. If you wanted to access information about macros at runtime, you'd have to keep it explicitly in some sort of data structure, but none of this is automatic.
Macros are simple copy paste and they are pretty limited. A macro will not expand if it's quoted or commented. One solution would be: ``` #define ABC "900" char s[] = ABC; ``` But no, macros cannot be used for what you're trying to do. > > When i try the above code, instead of my desired output 15 , i get 6487568 which i guess the integer equivalent of that string. > > > It's undefined behavior. Most likely it's the address of the string. If you compile with `-Wall` you will get a warning for this.
3,571,792
I am trying to structure a database for optimal use. But I have no idea how to make that happen. Here is what i will have A category which will have many products and a count for each on of those products For example Restaurants will be the category and the products will be the computer system, cash register and each one of these products has a count so maybe there will be 2 cash registers and 3 computer systems and so on. Another catagory might be a bar, which might or might not have the same products. Then the user has the option of choosing a 2 restarant package which might have a discount rate for getting all the products. I just need to structure the ERB if i can get some help, Thanks
2010/08/26
[ "https://Stackoverflow.com/questions/3571792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223367/" ]
PRODUCTS -------- * PRODUCT\_ID (primary key) * PRODUCT\_NAME CATEGORIES ---------- * CATEGORY\_ID (primary key) * CATEGORY\_NAME PRODUCT\_CATEGORIES\_MAP ------------------------ * PRODUCT\_ID (primary key, foreign key to `PRODUCTS`) * CATEGORY\_ID (primary key, foreign key to `CATEGORIES`) * QUANTITY This'll allow you to associate a product to more than one category, but not allow duplicates.
### Establishment * ID * Name * <address info> ### Product * ID * Name ### Estab\_Prod\_Bridge * ID\_Product * ID\_Establishment * Quantity ### Discounts * ID\_Establishment * Percent\_Purchase * Discount --- **Note:** 1. Establishment is a long word, I just used it here for example. You could easily replace it with location/loc, venue, or anything else you see fit. 2. Depending on how the data changes, I added the discount table, thinking there would be different discounts for variant amount of products purchased. **Example:** *80% of products purchased would yield a 5% discount, but 100% of purchases might yield a 10% discount.*
31,895,473
I'm trying to compile and install an open source application on Ubuntu. I can make the application, make the installer, and make the package. I don't see any error during those steps. when I issue the dpkg -i to install it if fails with the following error. dpkg: error processing archive application.deb (--install): corrupted filesystem tarfile - corrupted package archive dpkg-deb: error: subprocess paste was killed by signal (Broken pipe) I can only find references to fixing the issue when downloading files and say to issue apt-get clean and purge. I've done that and it doesn't work and it doesn't seem applicable since I'm creating the install file. When I issue dpkg -c application.deb, it shows me the contents, so the file isn't total corrupted. Any suggestions on how to get this application to install?
2015/08/08
[ "https://Stackoverflow.com/questions/31895473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/719989/" ]
Following the description on <https://github.com/Brewtarget/brewtarget> on a newly installed Ubuntu 14.04.3 gives me a .deb that installs. These are the commands I ran: ``` $ sudo apt-get install cmake git qtbase5-dev qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5webkit5-dev libqt5sql5-sqlite libqt5svg5 libqt5multimedia5-plugins doxygen $ git clone https://github.com/Brewtarget/brewtarget.git $ mkdir brewtarget-build $ cd brewtarget-build $ cmake ../brewtarget $ make $ make package $ sudo apt-get install libphonon4 libqt4-webkit phonon phonon-backend-vlc $ sudo dpkg -i brewtarget*.deb Selecting previously unselected package brewtarget_2.2.0. (Reading database ... 175209 files and directories currently installed.) Preparing to unpack brewtarget_2.2.0_x86_64.deb ... Unpacking brewtarget_2.2.0 (2.2.0-1) ... Setting up brewtarget_2.2.0 (2.2.0-1) ... $ file *.deb brewtarget_2.2.0_x86_64.deb: Debian binary package (format 2.0) ``` What version of Ubuntu are you running? It is odd that your error message says "application.deb", as I got a .deb named "brewtarget\_2.2.0\_x86\_64.deb" when following the instructions.
Try these commands ``` # sudo dpkg -i --force-overwrite application.deb ``` After that run ``` # sudo apt-get -f install ```
34,364,289
I'm trying out the new Core CLR type ASP.Net on my Mac and running in to no end of problems. I've managed to get StructureMap referenced and installed via dnu and dnu restore, but now I'm getting errors in VS Code stating that: ``` The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'. [dnx451] ``` I've done a good amount of googling but all I can find are things stating I need to add a using for System, that doesn't fix the problem. Startup.cs: ``` using System; using System.Reflection; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using StructureMap; namespace Authorization { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public IServiceProvider ConfigureServices(IServiceCollection services) { var container = new Container(); container.Configure(x => { x.Scan(scanning => { scanning.Assembly(Assembly.GetExecutingAssembly()); scanning.TheCallingAssembly(); scanning.WithDefaultConventions(); }); }); container.Populate(services); return container.GetInstance<IServiceCollection>(services); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } } ``` project.json: ``` { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "tooling": { "defaultNamespace": "Authorization" }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "StructureMap.Dnx": "0.4.0-alpha4" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel" }, "frameworks": { "dnx451": {}, "dnxcore50": {} }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } ``` Any help gratefully received! Thanks
2015/12/18
[ "https://Stackoverflow.com/questions/34364289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333417/" ]
I tried a little and can suggest you two versions to fix the problem with compilation. The first way is removing `dnxcore50` and making some changes in `Startup.cs`. To be exactly one can use the following `project.json`: ```json { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "structuremap": "4.0.1.318", "StructureMap.Dnx": "0.4.0-alpha4" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel" }, "frameworks": { "dnx451": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } ``` and the following `Startup.cs`: ```cs using System.Reflection; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using StructureMap; using StructureMap.Graph; namespace HelloWorldWebApplication { public class Startup { public IServiceCollection ConfigureServices(IServiceCollection services) { var container = new Container(); container.Configure(x => { x.Scan(scanning => { scanning.Assembly(typeof(Startup).GetTypeInfo().Assembly); scanning.TheCallingAssembly(); scanning.WithDefaultConventions(); }); }); container.Populate(services); return container.GetInstance<IServiceCollection>(); } public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async context => { await context.Response.WriteAsync("Hello World!"); }); } public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } } ``` Alternatively one can add back `"dnxcore50": { }` in the `"frameworks"` part, but comment the line `scanning.TheCallingAssembly();` and `using StructureMap.Graph;`
I also get this error. I just deleted all the packages from dnx folder and restore all packages again by "dnu restore" and It is fix.
62,866,512
I am using the following CSS to centre the text on the page but it seems to be creating a large CLS (Cumulative Layout Shift), is there a more efficient way to centre the text? ``` @media only screen and (min-width: 1000px) { .page { width: 1000px; margin: 0 auto; font-size: 1.0em; line-height: 1.6em; font-family: Arial, sans-serif; word-wrap: break-word; } } @media only screen and (max-width: 999px) { .page { margin: 0 auto; font-size: 1.0em; line-height: 1.6em; font-family: Arial, sans-serif; word-wrap: break-word; } } ``` The CLS issue only occurs in the Desktop version and not the Mobile version which makes me think it is the `width` option.
2020/07/12
[ "https://Stackoverflow.com/questions/62866512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203146/" ]
It turns out the cause of Cumulative Layout Shift was caused by an image incorrectly sized with the wrong width, I said 700 when the image was actually 702. Strangely, the error was being reported in the wrong place, the error was being reported in another div rather than where the image was. If you are looking for the cause of CLS, look at the image sizings. It wasn't caused by the style width css. The Mobile version worked because I sized that correctly.
You don't have a defined `width`, so the default setting `auto` applies to width, which is 100%. Centering a 100% wide element (with `margin: 0 auto`) in a parent element makes no sense: It takes the whole width of the parent. So you *need* to define a `width` for your mobile version.
68,891,149
can anyone help me on how to remove the huge white space between the two images? Both images are in their respective divs with layer effects when hovered. I have tried changing display to inline-block and setting font-size to 0 but nothing works. I also want the two images to be at the center when adjusted. I may have incorrectly apply the mentioned efforts to different classes or divs throughout the process but I am not sure where I did wrong. Attached are the html and css along with a screenshot of how it looks like on local server. I hope the attachments are useful. Thank you. [![enter image description here](https://i.stack.imgur.com/Ei366.png)](https://i.stack.imgur.com/Ei366.png) ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
2021/08/23
[ "https://Stackoverflow.com/questions/68891149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16713796/" ]
Like this? If so you just need to use `display: flex` and `align-items: flex-start` ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; align-items: flex-start } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; position: absolute; top: 0; left: 0; right: 0; bottom: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; text-align: center; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
you can use bootstrap class for width .campus-col or use custom width
68,891,149
can anyone help me on how to remove the huge white space between the two images? Both images are in their respective divs with layer effects when hovered. I have tried changing display to inline-block and setting font-size to 0 but nothing works. I also want the two images to be at the center when adjusted. I may have incorrectly apply the mentioned efforts to different classes or divs throughout the process but I am not sure where I did wrong. Attached are the html and css along with a screenshot of how it looks like on local server. I hope the attachments are useful. Thank you. [![enter image description here](https://i.stack.imgur.com/Ei366.png)](https://i.stack.imgur.com/Ei366.png) ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
2021/08/23
[ "https://Stackoverflow.com/questions/68891149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16713796/" ]
Like this? If so you just need to use `display: flex` and `align-items: flex-start` ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; align-items: flex-start } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; position: absolute; top: 0; left: 0; right: 0; bottom: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; text-align: center; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
You can use (`justify-content: center`) to *center* the `children` in the `flex` displayed `parent`, in short: center the `.img` in `.row`. Then you can add `margin` for spaces between them (the method used in the code below). Or you can use (`justtify-content: space-between`) and set the `width` of the *parent* (`.row`), then each `.img` will be at the edge or it's direction (left or right) Check this for more detalis: [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) **The Code:** ```css .row { display: flex; justify-content: center; } .img { width: 200px; height: 300px; border: 1px solid; border-radius: 6px; } .img { margin: 0 20px; } ``` ```html <div class="row"> <div class="img img1"></div> <div class="img img2"></div> </div> ``` **Solution based on your code:** Edited: ``` .row { display: flex; justify-content: center; } .campus-col{ height: 200px; /* delete later, added to see the changes */ border: 1px solid #ddd; /* delete later, added to see the changes */ margin: 0 10px; /* add/remove spaces (left right of each one) */ } ``` **The Code:** ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; justify-content: center; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; height: 200px; border: 1px solid #ddd; margin: 0 10px; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; } ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
68,891,149
can anyone help me on how to remove the huge white space between the two images? Both images are in their respective divs with layer effects when hovered. I have tried changing display to inline-block and setting font-size to 0 but nothing works. I also want the two images to be at the center when adjusted. I may have incorrectly apply the mentioned efforts to different classes or divs throughout the process but I am not sure where I did wrong. Attached are the html and css along with a screenshot of how it looks like on local server. I hope the attachments are useful. Thank you. [![enter image description here](https://i.stack.imgur.com/Ei366.png)](https://i.stack.imgur.com/Ei366.png) ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
2021/08/23
[ "https://Stackoverflow.com/questions/68891149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16713796/" ]
Try to make row flex container, then align content to center, with gap you can make space between images: ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; justify-content: center; gap: 1em; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="https://picsum.photos/200"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="https://picsum.photos/200"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
you can use bootstrap class for width .campus-col or use custom width
68,891,149
can anyone help me on how to remove the huge white space between the two images? Both images are in their respective divs with layer effects when hovered. I have tried changing display to inline-block and setting font-size to 0 but nothing works. I also want the two images to be at the center when adjusted. I may have incorrectly apply the mentioned efforts to different classes or divs throughout the process but I am not sure where I did wrong. Attached are the html and css along with a screenshot of how it looks like on local server. I hope the attachments are useful. Thank you. [![enter image description here](https://i.stack.imgur.com/Ei366.png)](https://i.stack.imgur.com/Ei366.png) ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
2021/08/23
[ "https://Stackoverflow.com/questions/68891149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16713796/" ]
Try to make row flex container, then align content to center, with gap you can make space between images: ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; justify-content: center; gap: 1em; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="https://picsum.photos/200"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="https://picsum.photos/200"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
You can use (`justify-content: center`) to *center* the `children` in the `flex` displayed `parent`, in short: center the `.img` in `.row`. Then you can add `margin` for spaces between them (the method used in the code below). Or you can use (`justtify-content: space-between`) and set the `width` of the *parent* (`.row`), then each `.img` will be at the edge or it's direction (left or right) Check this for more detalis: [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) **The Code:** ```css .row { display: flex; justify-content: center; } .img { width: 200px; height: 300px; border: 1px solid; border-radius: 6px; } .img { margin: 0 20px; } ``` ```html <div class="row"> <div class="img img1"></div> <div class="img img2"></div> </div> ``` **Solution based on your code:** Edited: ``` .row { display: flex; justify-content: center; } .campus-col{ height: 200px; /* delete later, added to see the changes */ border: 1px solid #ddd; /* delete later, added to see the changes */ margin: 0 10px; /* add/remove spaces (left right of each one) */ } ``` **The Code:** ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; justify-content: center; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; height: 200px; border: 1px solid #ddd; margin: 0 10px; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; } ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
17,538,167
I have a String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nice formatting plus syntax highlight. I don't want to use a web framework or web browser for such a simple thing. How do I do this? ``` | unformattedXml formattedXml | unformattedXml := '<tag><nested>hello</nested></tag>'. formattedXml := UnknownClass new format: unformattedXml. ``` Note: My input is a String. My output is a String.
2013/07/09
[ "https://Stackoverflow.com/questions/17538167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562583/" ]
To pretty print your xml string you can use the following ``` xmlString := '<a><b><c></c></b></a>'. xml := XMLDOMParser parseDocumentFrom: xmlString. ^ String streamContents: [:stream| xml prettyPrintOn: stream ] ``` That should give you ``` <a> <b> <c /> </b> </a> ``` I don't know what would be the best option for syntax highlighting
Take a look at the XML packages on [squeaksource.com](http://squeaksource.com), [ss3.gemstone.com](http://ss3.gemstone.com) and [smalltalkhub.com](http://smalltalkhub.com). There's bound to be something suitable for pretty printing. Syntax highlighting is a different story since it depends on the medium you want to print on. What is your goal? You say that you don't want to use a web browser so I can only assume you want syntax highlighting in the Smalltalk environment? If so, you might have to resort to [PetitParser](http://www.moosetechnology.org/tools/petitparser) and possibly write your own parser (you probably don't want to do that). Maybe you could give us some more details about what you are trying to accomplish?
8,252,759
I am developing a taskmanager on Android 2.1. I want to reset date and time on clicking the reset button to current date and time. Help me with the code.. ``` public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText next = (EditText) findViewById(R.id.editText1); final Button sub = (Button) findViewById(R.id.button1); final Button res = (Button) findViewById(R.id.button2); final DatePicker dp= (DatePicker) findViewById(R.id.datePicker1); final TimePicker tp = (TimePicker) findViewById(R.id.timePicker1); res.setOnClickListener(new View.OnClickListener() { public void onClick(final View view) { next.setText(""); dp.refreshDrawableState(); } }); }} ```
2011/11/24
[ "https://Stackoverflow.com/questions/8252759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031045/" ]
``` //get current time Time now = new Time(); now.setToNow(); //update the TimePicker tp.setHour(now.hour); tp.setMinute(now.minute); //update the DatePicker dp.updateDate(now.year, now.month, now.monthDay); ```
`Time` is now deprecated. Use `Calendar` instead: ``` Calendar calendar = Calendar.getInstance(); tp.setHour(calendar.get(Calendar.HOUR_OF_DAY)); tp.setMinute(calendar.get(Calendar.MINUTE)); dp.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); ```
7,029,870
I have this code for drawpath and nothing shows up and I cant figure out why. ``` //i move the path's starting point somewhere up here to a point. //get center x and y are the centers of a picture. it works when i //do drawline and store the different starting points //but i want it to look continuous not like a lot of different //lines path.lineTo(a.getCenterX(), a.getCenterY()); path.moveTo(a.getCenterX(), a.getCenterY()); p.setStrokeWidth(50); p.setColor(Color.BLACK); canvas.drawPath(path,p); ``` ![drawpath image](https://i.stack.imgur.com/4g17b.png) thanks in advance
2011/08/11
[ "https://Stackoverflow.com/questions/7029870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782117/" ]
i had to add this to paint in order to make it work. dunno why. ``` mPaint.setDither(true); mPaint.setColor(0xFFFFFF00); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(3); ```
I think the best way to solve your problem is by changing the code as follows: ``` private final int strokeWidth = 50; path.lineTo(a.getCenterX() + strokewidth / 2, a.getCenterY() + strokeWidth / 2); path.moveTo(a.getCenterX(), a.getCenterY()); p.setStrokeWidth(strokeWidth); p.setColor(Color.BLACK); canvas.drawPath(path,p); ``` You may have to play with this, but this should basically overlap the lines so it looks like they are continuous. You will likely have to put a switch statement in for which direction you are drawing in, but that should be fairly trivial. I hope this helps!
7,029,870
I have this code for drawpath and nothing shows up and I cant figure out why. ``` //i move the path's starting point somewhere up here to a point. //get center x and y are the centers of a picture. it works when i //do drawline and store the different starting points //but i want it to look continuous not like a lot of different //lines path.lineTo(a.getCenterX(), a.getCenterY()); path.moveTo(a.getCenterX(), a.getCenterY()); p.setStrokeWidth(50); p.setColor(Color.BLACK); canvas.drawPath(path,p); ``` ![drawpath image](https://i.stack.imgur.com/4g17b.png) thanks in advance
2011/08/11
[ "https://Stackoverflow.com/questions/7029870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782117/" ]
A new Paint instance only *fills* paths. To **stroke** paths, set the Paint style: ``` paint.setStyle(Paint.Style.STROKE); ``` If the background you're painting on is black, change the color, so you can see the paint: ``` paint.setColor(Color.RED); // something other than the background color ``` Optional: ``` paint.setStrokeWidth(10); // makes the line thicker ```
I think the best way to solve your problem is by changing the code as follows: ``` private final int strokeWidth = 50; path.lineTo(a.getCenterX() + strokewidth / 2, a.getCenterY() + strokeWidth / 2); path.moveTo(a.getCenterX(), a.getCenterY()); p.setStrokeWidth(strokeWidth); p.setColor(Color.BLACK); canvas.drawPath(path,p); ``` You may have to play with this, but this should basically overlap the lines so it looks like they are continuous. You will likely have to put a switch statement in for which direction you are drawing in, but that should be fairly trivial. I hope this helps!
346,195
So I've been looking all over the internet for a Decimal to Binary converter but all I've been able to find are Binary to Decimal converters, and Decimal to BCD circuits, does anyone have one?
2017/12/21
[ "https://electronics.stackexchange.com/questions/346195", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/172586/" ]
Yes, you'll struggle to find one. The reason for this is that there is no common reason for a BCD to binary converter. Where do the BCD digits come from that you need to convert? The purpose of the many binary to BCD converter ICs that are around are to support 7-segment displays in the pre-cheap-microcontroller era. You used to use a binary to BCD converter to break out each digit from your ADC or counter, then you would use a BCD to 7-segment driver to run each LED/LCD/VFD display to provide a human readable display of the binary measurement. As you can imagine, this was a rather common function in electronics devices, hence why the chips are readily available. Without knowing much more about the problem you are trying to solve, your best bet is to use a cheap microcontroller. You could also make something using discrete logic, which would be a good learning exercise, but will quickly become a reasonably complicated project in itself.
For a complete 3 digits BCD to binary converter you need 10 output bits for numbers from 0 to 999. 8 bits are good for numbers from 0 to 255. There was a TTL chip for that purpose, the SN74184A, see this [PDF](http://pdf.datasheetcatalog.com/datasheets/400/220358_DS.pdf) or that [PDF](https://www.utm.edu/staff/leeb/DM74185.pdf) datasheet. On page 6 or 3-736 there is a cascaded circuit using 6 chips for 3 BCD digits input and 10 binary output bits. If you can't buy the SN74184A, you may program its function table (page 2 or 3-732) into a PROM with 5 inputs and 5 outputs. Of course you may use a PROM with 8 inputs and 8 outputs too. Or you do a single chip solution using a PROM with 12 inputs and 10 outputs. 16 outputs may be used also, just don't use 6 outputs. Or 2 EPROMs with 4096 bytes of 8 bits. Larger EPROMs may be used too. The least significant bit of the lowest BCD digit needs no processing, therefore a PROM with 11 inputs and 9 outputs will do it too.
346,195
So I've been looking all over the internet for a Decimal to Binary converter but all I've been able to find are Binary to Decimal converters, and Decimal to BCD circuits, does anyone have one?
2017/12/21
[ "https://electronics.stackexchange.com/questions/346195", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/172586/" ]
As has been pointed out in other answers, you can use the venerable (and I do mean venerable) 74184. Of course, those things have been obsolete for decades, so finding them is .... interesting. If you go on eBay, you can get 20 year old Russian knockoffs for a couple of bucks apiece. You'll need 6 for converting 0 to 255. You'll also need some extra protection logic, since with a 3-digit input there is always the chance that you will inadvertently try to enter a number in excess of 255, and the results of that will not be pretty. Then, of course, your 6 ICs will draw (worst case) as much as 100 mA each, so you're looking at 600 mA. Overall, in terms of circuit board size, power dissipation and error resistance, you're much better off programming a 4k x 8 PROM such as a 2732. This comes in a 28 pin DIP, and they are readily available and easily programmed.
For a complete 3 digits BCD to binary converter you need 10 output bits for numbers from 0 to 999. 8 bits are good for numbers from 0 to 255. There was a TTL chip for that purpose, the SN74184A, see this [PDF](http://pdf.datasheetcatalog.com/datasheets/400/220358_DS.pdf) or that [PDF](https://www.utm.edu/staff/leeb/DM74185.pdf) datasheet. On page 6 or 3-736 there is a cascaded circuit using 6 chips for 3 BCD digits input and 10 binary output bits. If you can't buy the SN74184A, you may program its function table (page 2 or 3-732) into a PROM with 5 inputs and 5 outputs. Of course you may use a PROM with 8 inputs and 8 outputs too. Or you do a single chip solution using a PROM with 12 inputs and 10 outputs. 16 outputs may be used also, just don't use 6 outputs. Or 2 EPROMs with 4096 bytes of 8 bits. Larger EPROMs may be used too. The least significant bit of the lowest BCD digit needs no processing, therefore a PROM with 11 inputs and 9 outputs will do it too.
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
I saw another related answer here, maybe this is a valid solution too? <https://github.com/jquense/yup/issues/1114> Copying code from there: ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) }) ```
this will help you ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) ``` })
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
this will help you ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) ``` })
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
this will help you ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) ``` })
You need to handle with manually, not with required. Just you need to keep a state of the each field. And check it if its value is present then you need to show it. Some like this ```js const [email, setEmail]= useState(null); const onChange=(e)=>{ setEmail(e.target.value) } return ( <input type="text" onChange={onChnage}/> ) ``` And pass this email to your parent where you checking for validation. If there is any thin in **email** then show it do other validation. Or if it is empty or Null then don't show it. Thanks
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
I modify the schema on the fly with a transform ``` const updateUserValidator = yup.object().shape({ email: yup.string(), updateBy: yup.string() }).transform(function (current, original) { this.fields.email = original?.email?.length === undefined ? yup().string().email() : yup().string().email().required() return current; }) ```
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
this will help you ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) ``` })
I modify the schema on the fly with a transform ``` const updateUserValidator = yup.object().shape({ email: yup.string(), updateBy: yup.string() }).transform(function (current, original) { this.fields.email = original?.email?.length === undefined ? yup().string().email() : yup().string().email().required() return current; }) ```
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
I saw another related answer here, maybe this is a valid solution too? <https://github.com/jquense/yup/issues/1114> Copying code from there: ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) }) ```
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
You can use Cyclic Dependency for make this. Example: ``` const YOUR_SCHEMA_NAME = yup.object().shape({ email: yup.string().when('email', { is: (exists) => !!exists, then: yup.string().email(), otherwise: yup.string(), }), }, [['email', 'email']]); ```
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
this will help you ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) ``` })
You can use Cyclic Dependency for make this. Example: ``` const YOUR_SCHEMA_NAME = yup.object().shape({ email: yup.string().when('email', { is: (exists) => !!exists, then: yup.string().email(), otherwise: yup.string(), }), }, [['email', 'email']]); ```
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
You need to handle with manually, not with required. Just you need to keep a state of the each field. And check it if its value is present then you need to show it. Some like this ```js const [email, setEmail]= useState(null); const onChange=(e)=>{ setEmail(e.target.value) } return ( <input type="text" onChange={onChnage}/> ) ``` And pass this email to your parent where you checking for validation. If there is any thin in **email** then show it do other validation. Or if it is empty or Null then don't show it. Thanks
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
I saw another related answer here, maybe this is a valid solution too? <https://github.com/jquense/yup/issues/1114> Copying code from there: ``` const schema = yup.object({ phone: yup.string().when('$exist', { is: exist => exist, then: yup.string().required(), otherwise: yup.string() }) }) ```
You can use Cyclic Dependency for make this. Example: ``` const YOUR_SCHEMA_NAME = yup.object().shape({ email: yup.string().when('email', { is: (exists) => !!exists, then: yup.string().email(), otherwise: yup.string(), }), }, [['email', 'email']]); ```
4,098,493
I need to find remote data such as RAM usage, swap usage, number of processors, etc, using a php script from the local computer and 10 other remote computers. How can I go about it? The remote computers are all running Linux, and they can run any service that is needed of the machine. What I have in mind is that I can somehow use ssh using the PHP script. Then use top or something to find what I need. It also needs to be a single PHP file that displays all the information.
2010/11/04
[ "https://Stackoverflow.com/questions/4098493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357538/" ]
I think you will probably want to look at PHP Expect, it allows you to do something like connect to a remote host, and provide input/responses to output on the remote. <http://us3.php.net/manual/en/book.expect.php>
Have you considered a monitoring suite like [Nagios](http://www.nagios.org/) instead of PHP? I think Nagios can give you all this data in a central web-based interface. As far as I know, it has a learning curve that is not entirely trivial, but it may still beat building a PHP solution.
4,098,493
I need to find remote data such as RAM usage, swap usage, number of processors, etc, using a php script from the local computer and 10 other remote computers. How can I go about it? The remote computers are all running Linux, and they can run any service that is needed of the machine. What I have in mind is that I can somehow use ssh using the PHP script. Then use top or something to find what I need. It also needs to be a single PHP file that displays all the information.
2010/11/04
[ "https://Stackoverflow.com/questions/4098493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357538/" ]
Have you considered a monitoring suite like [Nagios](http://www.nagios.org/) instead of PHP? I think Nagios can give you all this data in a central web-based interface. As far as I know, it has a learning curve that is not entirely trivial, but it may still beat building a PHP solution.
You can use PHP [sockets](http://www.php.net/manual/en/book.sockets.php) to communicate with servers remotely via [SNMP](http://php.net/manual/en/book.snmp.php). The remote servers need to have SNMP activated and configured to provide the data you need, such as hardware info, bandwidth, disk space, swap usage, etc.
4,098,493
I need to find remote data such as RAM usage, swap usage, number of processors, etc, using a php script from the local computer and 10 other remote computers. How can I go about it? The remote computers are all running Linux, and they can run any service that is needed of the machine. What I have in mind is that I can somehow use ssh using the PHP script. Then use top or something to find what I need. It also needs to be a single PHP file that displays all the information.
2010/11/04
[ "https://Stackoverflow.com/questions/4098493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357538/" ]
I think you will probably want to look at PHP Expect, it allows you to do something like connect to a remote host, and provide input/responses to output on the remote. <http://us3.php.net/manual/en/book.expect.php>
You can use PHP [sockets](http://www.php.net/manual/en/book.sockets.php) to communicate with servers remotely via [SNMP](http://php.net/manual/en/book.snmp.php). The remote servers need to have SNMP activated and configured to provide the data you need, such as hardware info, bandwidth, disk space, swap usage, etc.
9,909,932
Consider following code: ``` SwingWorker<Void, Void> sworker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); try { for (int j = 0; j < 5; j++) { Callable<Object> worker = new MyCallableImpl(); Future<Object> future = executor.submit(worker); array[j] = future.get(); } } catch (InterruptedException e) { // some code here } catch (ExecutionException e) { // some code here } // some code here executor.shutdown(); return null; } }; sworker.execute(); ``` As I said in the title: is this a good practice to invoke ExecutorService inside doInBackground() method of SwingWorker? It works for me (JDK1.7), GUI is not blocked and multiple threads from Executor pool are running in background, but still I have some doubts...
2012/03/28
[ "https://Stackoverflow.com/questions/9909932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699908/" ]
It is entirely dependent on your compiler and architecture. In your case it looks as if the fields are indeed being 8-byte-aligned, perhaps for performance reasons.
My guess is that by default everything on 64bit architecture will be aligned to 64bit boundaries same as on 32bit architecture everything is aligned to 4 bytes. You can specify packing pragma directives to get rid of the padding. For example ``` #pragma pack(0) ``` in gcc.
9,909,932
Consider following code: ``` SwingWorker<Void, Void> sworker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); try { for (int j = 0; j < 5; j++) { Callable<Object> worker = new MyCallableImpl(); Future<Object> future = executor.submit(worker); array[j] = future.get(); } } catch (InterruptedException e) { // some code here } catch (ExecutionException e) { // some code here } // some code here executor.shutdown(); return null; } }; sworker.execute(); ``` As I said in the title: is this a good practice to invoke ExecutorService inside doInBackground() method of SwingWorker? It works for me (JDK1.7), GUI is not blocked and multiple threads from Executor pool are running in background, but still I have some doubts...
2012/03/28
[ "https://Stackoverflow.com/questions/9909932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699908/" ]
My guess is that by default everything on 64bit architecture will be aligned to 64bit boundaries same as on 32bit architecture everything is aligned to 4 bytes. You can specify packing pragma directives to get rid of the padding. For example ``` #pragma pack(0) ``` in gcc.
On linux with gcc and a 64 bit CPU I get what you would expect; the size of a struct with two short ints, is 4, two 32 bit ints is 8 and two 64 bit ints is 16.
9,909,932
Consider following code: ``` SwingWorker<Void, Void> sworker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); try { for (int j = 0; j < 5; j++) { Callable<Object> worker = new MyCallableImpl(); Future<Object> future = executor.submit(worker); array[j] = future.get(); } } catch (InterruptedException e) { // some code here } catch (ExecutionException e) { // some code here } // some code here executor.shutdown(); return null; } }; sworker.execute(); ``` As I said in the title: is this a good practice to invoke ExecutorService inside doInBackground() method of SwingWorker? It works for me (JDK1.7), GUI is not blocked and multiple threads from Executor pool are running in background, but still I have some doubts...
2012/03/28
[ "https://Stackoverflow.com/questions/9909932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699908/" ]
It is entirely dependent on your compiler and architecture. In your case it looks as if the fields are indeed being 8-byte-aligned, perhaps for performance reasons.
On linux with gcc and a 64 bit CPU I get what you would expect; the size of a struct with two short ints, is 4, two 32 bit ints is 8 and two 64 bit ints is 16.
61,308,766
I have a requirement where i want to skip all the upcoming tasks if a "Release artifacts" task is run. Release artifact task runs only if one of the variable is set to "true" while running the pipeline. ``` parameters: release: $(release) - task: Bash@3 displayName: Release artifacts condition: and(succeeded(), eq('${{ parameters.release }}', true)) inputs: targetType: 'inline' script: | # Write your commands here # Steps to release the artifacts ( gradle release plugin) gradle release -Prelease.useAutomaticVersion=true - task: Bash@3 - task: Bash@3 ``` Is there a way to exit/truncate the pipeline with exit code 0 ? I am looking for a functionality to skip all the upcoming tasks if one of the conditions is true without having to add that check in all the tasks ? Reason : gradle release will make modification to gradle.properties which will trigger CI again.
2020/04/19
[ "https://Stackoverflow.com/questions/61308766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768610/" ]
You may have a race condition which may cause undefined behavior. In create\_serv\_and\_init\_client() you define a local variable serv. The address of this variable is passed to the thread. When create\_serv\_and\_init\_client completes serv will go out of scope, even if the thread is still using it. As a result the value of serv may no longer be correct.
Note a multi-threaded program can really only `fork` to execute a new program using `execve`. For example from Linux manuals: > > * After a `fork()` in a multithreaded program, the child can safely call only async-signal-safe functions (see signal-safety(7)) until such time as it calls `execve(2)`. > > > `printf` for example can lock the `stdout`. If you happen to fork in while the `printf` lock is held by another thread then crazy things might or might not happen.
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Let me take your last sentences to tell you my opinion: > > Sobald ich Zeit habe, werde ich dir helfen. > > Ich werde dir helfen, sobald ich Zeit habe. > > Ich werde dir, sobald ich Zeit habe, helfen. > > > The second sentence is the most common to use, I guess, followed by the first and then the third. Personally, I wouldn’t use the third one and I think no German do so in spoken language. I would only use a sentence like the third one when writing a text or similar, but even then extremely rarely. I am a native speaker of German, but as I said all of this is just my opinion. But all of these sentences are grammatically correct.
Actually, all of the above are correct. Especially the last three examples are all correct. You are safe using your first example - the one you came up with yourself. If you want to read about subordinate clauses in German, go to the following page: <http://www.mein-deutschbuch.de/lernen.php?menu_id=123>
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Don't let the third sentence type confuse you. The subordinate clause is an insertion and the outer sentence structure is not changed by it. The normal sentences would be > > Jeder ist für das verantwortlich. > > > Ich werde dir helfen. > > > The conjugated verb is at the second position as usual. The tricky part is were to insert the subordinate clauses. In the first example right after the part that is restricted by it. In the second example I would assume it is inserted behind the object. However, there are [dependent subordinate clauses](http://canoonet.eu/services/OnlineGrammar/Satz/Komplex/Ordnung/Subordination.html) which work differently.
Actually, all of the above are correct. Especially the last three examples are all correct. You are safe using your first example - the one you came up with yourself. If you want to read about subordinate clauses in German, go to the following page: <http://www.mein-deutschbuch.de/lernen.php?menu_id=123>
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Concerning "Jeder ist für das, was er gesagt hat, verantwortlich.": ------------------------------------------------------------------- Think about the "das, was er gesagt hat" as a noun. The whole phrase can be used anywhere a noun is used. It's called a noun phrase. Examples: > > **Das Auto** gefällt mir nicht. > > > can be replaced with > > **Das, was er gesagt hat,** gefällt mir nicht. > > > > > Mir gefällt **das Auto** nicht. > > > can be replaced with > > Mir gefällt **das, was er gesagt hat,** nicht. > > > > > Hast du **das Auto** nicht gehört? > > > can be replaced with > > Hast du **das, was er gesagt hat,** nicht gehört? > > > > > Was hat dir gut gefallen? – **Das Auto**. > > > can be replaced with > > Was hat dir gut gefallen? – **Das, was er gesagt hat.** > > > Concerning "Ich werde dir, sobald ich Zeit habe, helfen.": ---------------------------------------------------------- Think about the whole sentence "sobald ich Zeit habe" as an adverb (of time). The whole sentence can be used anywhere an adverb is used. It's called an adverbial phrase. > > Ich komme **morgen** nach Hause. > > > can be replaced with > > Ich komme **sobald ich Zeit habe** nach Hause. > > > > > **Morgen** komme ich nach Hause. > > > can be replaced with > > **Sobald ich Zeit habe,** komme ich nach Hause. > > > > > Erst **um 15 Uhr** komme ich nach Hause. > > > can be replaced with > > Erst **sobald ich Zeit habe,** komme ich nach Hause. > > > > > Wann kommst du? – **Morgen.** > > > can be replaced with > > Wann kommst du? – **Sobald ich Zeit habe.** > > >
Actually, all of the above are correct. Especially the last three examples are all correct. You are safe using your first example - the one you came up with yourself. If you want to read about subordinate clauses in German, go to the following page: <http://www.mein-deutschbuch.de/lernen.php?menu_id=123>
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Maybe this is also a matter of emphasis. When arguing with someone you sometimes want to point out something in particular. > > "Kein Argument, das du nennen kannst, wird mich überzeugen" (nice example, thank you) > > > "Kein Argument *(of all arguments in the world)*, das **du** nennen kannst *(pointing at the person directly)*, wird mich überzeugen." So we doubt the other person will bring something useful forward, in gerenal. > > > On the oher hand > > "Mich wird kein Argument, das du nennen kannst, **überzeugen**." > > > seems to imply that the other person actually is capable of telling something useful. But anyway, no matter what it is (if good or bad) it won't convince me. So the sentence in the middle is more like some extra information. Well, emphasis is slightly subjective sometimes but I hope this helps :)
Actually, all of the above are correct. Especially the last three examples are all correct. You are safe using your first example - the one you came up with yourself. If you want to read about subordinate clauses in German, go to the following page: <http://www.mein-deutschbuch.de/lernen.php?menu_id=123>
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Don't let the third sentence type confuse you. The subordinate clause is an insertion and the outer sentence structure is not changed by it. The normal sentences would be > > Jeder ist für das verantwortlich. > > > Ich werde dir helfen. > > > The conjugated verb is at the second position as usual. The tricky part is were to insert the subordinate clauses. In the first example right after the part that is restricted by it. In the second example I would assume it is inserted behind the object. However, there are [dependent subordinate clauses](http://canoonet.eu/services/OnlineGrammar/Satz/Komplex/Ordnung/Subordination.html) which work differently.
Let me take your last sentences to tell you my opinion: > > Sobald ich Zeit habe, werde ich dir helfen. > > Ich werde dir helfen, sobald ich Zeit habe. > > Ich werde dir, sobald ich Zeit habe, helfen. > > > The second sentence is the most common to use, I guess, followed by the first and then the third. Personally, I wouldn’t use the third one and I think no German do so in spoken language. I would only use a sentence like the third one when writing a text or similar, but even then extremely rarely. I am a native speaker of German, but as I said all of this is just my opinion. But all of these sentences are grammatically correct.
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Concerning "Jeder ist für das, was er gesagt hat, verantwortlich.": ------------------------------------------------------------------- Think about the "das, was er gesagt hat" as a noun. The whole phrase can be used anywhere a noun is used. It's called a noun phrase. Examples: > > **Das Auto** gefällt mir nicht. > > > can be replaced with > > **Das, was er gesagt hat,** gefällt mir nicht. > > > > > Mir gefällt **das Auto** nicht. > > > can be replaced with > > Mir gefällt **das, was er gesagt hat,** nicht. > > > > > Hast du **das Auto** nicht gehört? > > > can be replaced with > > Hast du **das, was er gesagt hat,** nicht gehört? > > > > > Was hat dir gut gefallen? – **Das Auto**. > > > can be replaced with > > Was hat dir gut gefallen? – **Das, was er gesagt hat.** > > > Concerning "Ich werde dir, sobald ich Zeit habe, helfen.": ---------------------------------------------------------- Think about the whole sentence "sobald ich Zeit habe" as an adverb (of time). The whole sentence can be used anywhere an adverb is used. It's called an adverbial phrase. > > Ich komme **morgen** nach Hause. > > > can be replaced with > > Ich komme **sobald ich Zeit habe** nach Hause. > > > > > **Morgen** komme ich nach Hause. > > > can be replaced with > > **Sobald ich Zeit habe,** komme ich nach Hause. > > > > > Erst **um 15 Uhr** komme ich nach Hause. > > > can be replaced with > > Erst **sobald ich Zeit habe,** komme ich nach Hause. > > > > > Wann kommst du? – **Morgen.** > > > can be replaced with > > Wann kommst du? – **Sobald ich Zeit habe.** > > >
Let me take your last sentences to tell you my opinion: > > Sobald ich Zeit habe, werde ich dir helfen. > > Ich werde dir helfen, sobald ich Zeit habe. > > Ich werde dir, sobald ich Zeit habe, helfen. > > > The second sentence is the most common to use, I guess, followed by the first and then the third. Personally, I wouldn’t use the third one and I think no German do so in spoken language. I would only use a sentence like the third one when writing a text or similar, but even then extremely rarely. I am a native speaker of German, but as I said all of this is just my opinion. But all of these sentences are grammatically correct.
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Don't let the third sentence type confuse you. The subordinate clause is an insertion and the outer sentence structure is not changed by it. The normal sentences would be > > Jeder ist für das verantwortlich. > > > Ich werde dir helfen. > > > The conjugated verb is at the second position as usual. The tricky part is were to insert the subordinate clauses. In the first example right after the part that is restricted by it. In the second example I would assume it is inserted behind the object. However, there are [dependent subordinate clauses](http://canoonet.eu/services/OnlineGrammar/Satz/Komplex/Ordnung/Subordination.html) which work differently.
Maybe this is also a matter of emphasis. When arguing with someone you sometimes want to point out something in particular. > > "Kein Argument, das du nennen kannst, wird mich überzeugen" (nice example, thank you) > > > "Kein Argument *(of all arguments in the world)*, das **du** nennen kannst *(pointing at the person directly)*, wird mich überzeugen." So we doubt the other person will bring something useful forward, in gerenal. > > > On the oher hand > > "Mich wird kein Argument, das du nennen kannst, **überzeugen**." > > > seems to imply that the other person actually is capable of telling something useful. But anyway, no matter what it is (if good or bad) it won't convince me. So the sentence in the middle is more like some extra information. Well, emphasis is slightly subjective sometimes but I hope this helps :)
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Concerning "Jeder ist für das, was er gesagt hat, verantwortlich.": ------------------------------------------------------------------- Think about the "das, was er gesagt hat" as a noun. The whole phrase can be used anywhere a noun is used. It's called a noun phrase. Examples: > > **Das Auto** gefällt mir nicht. > > > can be replaced with > > **Das, was er gesagt hat,** gefällt mir nicht. > > > > > Mir gefällt **das Auto** nicht. > > > can be replaced with > > Mir gefällt **das, was er gesagt hat,** nicht. > > > > > Hast du **das Auto** nicht gehört? > > > can be replaced with > > Hast du **das, was er gesagt hat,** nicht gehört? > > > > > Was hat dir gut gefallen? – **Das Auto**. > > > can be replaced with > > Was hat dir gut gefallen? – **Das, was er gesagt hat.** > > > Concerning "Ich werde dir, sobald ich Zeit habe, helfen.": ---------------------------------------------------------- Think about the whole sentence "sobald ich Zeit habe" as an adverb (of time). The whole sentence can be used anywhere an adverb is used. It's called an adverbial phrase. > > Ich komme **morgen** nach Hause. > > > can be replaced with > > Ich komme **sobald ich Zeit habe** nach Hause. > > > > > **Morgen** komme ich nach Hause. > > > can be replaced with > > **Sobald ich Zeit habe,** komme ich nach Hause. > > > > > Erst **um 15 Uhr** komme ich nach Hause. > > > can be replaced with > > Erst **sobald ich Zeit habe,** komme ich nach Hause. > > > > > Wann kommst du? – **Morgen.** > > > can be replaced with > > Wann kommst du? – **Sobald ich Zeit habe.** > > >
Maybe this is also a matter of emphasis. When arguing with someone you sometimes want to point out something in particular. > > "Kein Argument, das du nennen kannst, wird mich überzeugen" (nice example, thank you) > > > "Kein Argument *(of all arguments in the world)*, das **du** nennen kannst *(pointing at the person directly)*, wird mich überzeugen." So we doubt the other person will bring something useful forward, in gerenal. > > > On the oher hand > > "Mich wird kein Argument, das du nennen kannst, **überzeugen**." > > > seems to imply that the other person actually is capable of telling something useful. But anyway, no matter what it is (if good or bad) it won't convince me. So the sentence in the middle is more like some extra information. Well, emphasis is slightly subjective sometimes but I hope this helps :)
64,606,542
Merge 2 dataframes. I have dataframe A that has a value in a non constant timestamp: ``` creation_time value_A 2020-09-22 00:00:35 83.0 2020-09-22 00:00:43 83.0 2020-09-22 00:02:20 82.0 2020-09-22 00:03:09 77.0 2020-09-22 00:03:04 77.0 2020-09-22 00:03:44 77.0 2020-09-22 00:07:10 71.0 ... 2020-10-23 11:42:31 136.0 2020-10-23 11:42:32 136.0 2020-10-23 11:42:35 136.0 2020-10-29 11:42:31 136.0 2020-10-29 11:42:32 136.0 2020-10-29 11:42:35 136.0 ``` and dataframe B. The first column is a range. For example, from 0 to 75 on 2020-09-22 the value\_B should be 60. ``` value_A_range creation_time value_B 0 2020-09-22 00:00:00.000000 60 75 2020-09-22 00:00:00.000000 65 124 2020-09-22 00:00:00.000000 300 143 2020-09-22 00:00:00.000000 360 0 2020-10-16 12:23:25.000000 60 75 2020-10-16 12:23:25.000000 400 124 2020-10-16 12:23:25.000000 400 143 2020-10-16 12:23:25.000000 450 0 2020-10-28 15:53:31.000000 10 82 2020-10-28 15:53:31.000000 30 114 2020-10-28 15:53:31.000000 40 129 2020-10-28 15:53:31.000000 60 139 2020-10-28 15:53:31.000000 110 ``` Expected result: Get value\_B for each timestamp in dataframe A. Match on range for value\_A on the available timestamp. ``` creation_time value_A value_B 2020-09-22 00:00:35 83.0 65 2020-09-22 00:00:43 83.0 65 2020-09-22 00:02:20 82.0 65 2020-09-22 00:03:09 60.0 60 2020-09-22 00:03:04 60.0 60 2020-09-22 00:03:44 60.0 60 2020-09-22 00:07:10 129.0 300 ... 2020-10-23 11:42:31 136.0 400 2020-10-23 11:42:32 156.0 450 2020-10-23 11:42:35 136.0 400 2020-10-29 11:42:31 85.0 30 2020-10-29 11:42:32 120.0 40 2020-10-29 11:42:35 160.0 110 ``` Resources I'm trying: [range](https://stackoverflow.com/questions/44367672/best-way-to-join-merge-by-range-in-pandas) and [merge\_asof](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html)
2020/10/30
[ "https://Stackoverflow.com/questions/64606542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6587020/" ]
Tensorflow isn't in the "defaults" anaconda channel. It is on conda-forge instead. In order to add conda-forge to your channels: 1. Click on "channels" (left of where you searched for tensorflow) 2. Click on "add" 3. Paste this URL in: <https://conda.anaconda.org/conda-forge/> 4. Press enter 5. Press "Update channels" 6. Now search again, and it should be there! [conda-forge added to channels](https://i.stack.imgur.com/4g29c.png) Source: <https://conda-forge.org/docs/user/introduction.html>
Additionally to the steps described above (with the version @aysebilgegunduz mentioned), I also had to "Update index..." after adding "conda-forge" to the environment's channels. Afterwards, I found the desired package.
64,606,542
Merge 2 dataframes. I have dataframe A that has a value in a non constant timestamp: ``` creation_time value_A 2020-09-22 00:00:35 83.0 2020-09-22 00:00:43 83.0 2020-09-22 00:02:20 82.0 2020-09-22 00:03:09 77.0 2020-09-22 00:03:04 77.0 2020-09-22 00:03:44 77.0 2020-09-22 00:07:10 71.0 ... 2020-10-23 11:42:31 136.0 2020-10-23 11:42:32 136.0 2020-10-23 11:42:35 136.0 2020-10-29 11:42:31 136.0 2020-10-29 11:42:32 136.0 2020-10-29 11:42:35 136.0 ``` and dataframe B. The first column is a range. For example, from 0 to 75 on 2020-09-22 the value\_B should be 60. ``` value_A_range creation_time value_B 0 2020-09-22 00:00:00.000000 60 75 2020-09-22 00:00:00.000000 65 124 2020-09-22 00:00:00.000000 300 143 2020-09-22 00:00:00.000000 360 0 2020-10-16 12:23:25.000000 60 75 2020-10-16 12:23:25.000000 400 124 2020-10-16 12:23:25.000000 400 143 2020-10-16 12:23:25.000000 450 0 2020-10-28 15:53:31.000000 10 82 2020-10-28 15:53:31.000000 30 114 2020-10-28 15:53:31.000000 40 129 2020-10-28 15:53:31.000000 60 139 2020-10-28 15:53:31.000000 110 ``` Expected result: Get value\_B for each timestamp in dataframe A. Match on range for value\_A on the available timestamp. ``` creation_time value_A value_B 2020-09-22 00:00:35 83.0 65 2020-09-22 00:00:43 83.0 65 2020-09-22 00:02:20 82.0 65 2020-09-22 00:03:09 60.0 60 2020-09-22 00:03:04 60.0 60 2020-09-22 00:03:44 60.0 60 2020-09-22 00:07:10 129.0 300 ... 2020-10-23 11:42:31 136.0 400 2020-10-23 11:42:32 156.0 450 2020-10-23 11:42:35 136.0 400 2020-10-29 11:42:31 85.0 30 2020-10-29 11:42:32 120.0 40 2020-10-29 11:42:35 160.0 110 ``` Resources I'm trying: [range](https://stackoverflow.com/questions/44367672/best-way-to-join-merge-by-range-in-pandas) and [merge\_asof](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html)
2020/10/30
[ "https://Stackoverflow.com/questions/64606542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6587020/" ]
Tensorflow isn't in the "defaults" anaconda channel. It is on conda-forge instead. In order to add conda-forge to your channels: 1. Click on "channels" (left of where you searched for tensorflow) 2. Click on "add" 3. Paste this URL in: <https://conda.anaconda.org/conda-forge/> 4. Press enter 5. Press "Update channels" 6. Now search again, and it should be there! [conda-forge added to channels](https://i.stack.imgur.com/4g29c.png) Source: <https://conda-forge.org/docs/user/introduction.html>
Tensorflow isn't in the "defaults" anaconda channel. It is on conda-forge instead. In order to add conda-forge to your channels: Click on "channels" (left of where you searched for tensorflow) Click on "add" Paste this URL in: <https://conda.anaconda.org/conda-forge/> Press enter Press "Update channels" Now search again, and it should be there!
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
You can use `typeof`, like this: ``` if (typeof something != "undefined") { // ... } ```
In [this article](http://flippinawesome.org/2013/12/09/exploring-the-abyss-of-null-and-undefined-in-javascript/) I read that frameworks like [Underscore.js](https://en.wikipedia.org/wiki/Underscore.js) use this function: ``` function isUndefined(obj){ return obj === void 0; } ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
**2020 Update** One of my reasons for preferring a `typeof` check (namely, that `undefined` can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use `typeof` to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations: ``` myVariable === undefined ``` **Original answer from 2010** Using `typeof` is my preference. It will work when the variable has never been declared, unlike any comparison with the `==` or `===` operators or type coercion using `if`. (`undefined`, unlike `null`, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above). ``` if (typeof someUndeclaredVariable == "undefined") { // Works } if (someUndeclaredVariable === undefined) { // Throws an error } ```
Since none of the other answers helped me, I suggest doing this. It worked for me in Internet Explorer 8: ``` if (typeof variable_name.value === 'undefined') { // variable_name is undefined } ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
Personally, I always use the following: ``` var x; if( x === undefined) { //Do something here } else { //Do something else here } ``` The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined>, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined. I prefer to have the approach of using ``` x === undefined ``` because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.
``` var x; if (x === undefined) { alert ("I am declared, but not defined.") }; if (typeof y === "undefined") { alert ("I am not even declared.") }; /* One more thing to understand: typeof ==='undefined' also checks for if a variable is declared, but no value is assigned. In other words, the variable is declared, but not defined. */ // Will repeat above logic of x for typeof === 'undefined' if (x === undefined) { alert ("I am declared, but not defined.") }; /* So typeof === 'undefined' works for both, but x === undefined only works for a variable which is at least declared. */ /* Say if I try using typeof === undefined (not in quotes) for a variable which is not even declared, we will get run a time error. */ if (z === undefined) { alert ("I am neither declared nor defined.") }; // I got this error for z ReferenceError: z is not defined ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
``` if (typeof foo == 'undefined') { // Do something }; ``` Note that strict comparison (`!==`) is not necessary in this case, since `typeof` will always return a string.
I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source. ``` undefined = 2; (function (undefined) { console.log(undefined); // prints out undefined // and for comparison: if (undeclaredvar === undefined) console.log("it works!") })() ``` Of course you could just use `typeof` though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
``` if (typeof foo == 'undefined') { // Do something }; ``` Note that strict comparison (`!==`) is not necessary in this case, since `typeof` will always return a string.
On the contrary of @Thomas Eding answer: If I forget to declare `myVar` in my code, then I'll get `myVar is not defined`. Let's take a real example: I've a variable name, but I am not sure if it is declared somewhere or not. Then @Anurag's answer will help: ``` var myVariableToCheck = 'myVar'; if (window[myVariableToCheck] === undefined) console.log("Not declared or declared, but undefined."); // Or you can check it directly if (window['myVar'] === undefined) console.log("Not declared or declared, but undefined."); ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
The most reliable way I know of checking for `undefined` is to use `void 0`. This is compatible with newer and older browsers, alike, and cannot be overwritten like `window.undefined` can in some cases. ``` if( myVar === void 0){ //yup it's undefined } ```
Since none of the other answers helped me, I suggest doing this. It worked for me in Internet Explorer 8: ``` if (typeof variable_name.value === 'undefined') { // variable_name is undefined } ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
``` if (typeof foo == 'undefined') { // Do something }; ``` Note that strict comparison (`!==`) is not necessary in this case, since `typeof` will always return a string.
The most reliable way I know of checking for `undefined` is to use `void 0`. This is compatible with newer and older browsers, alike, and cannot be overwritten like `window.undefined` can in some cases. ``` if( myVar === void 0){ //yup it's undefined } ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
Update 2018-07-25 ================= It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods: * `abc === undefined` * `abc === void 0` * `typeof abc == 'undefined'` * `typeof abc === 'undefined'` Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend `abc === undefined` for clarity. Relevant content from `chrome://version`: * Google Chrome: 67.0.3396.99 (Official Build) (64-bit) (cohort: Stable) * Revision: a337fbf3c2ab8ebc6b64b0bfdce73a20e2e2252b-refs/branch-heads/3396@{#790} * OS: Windows * JavaScript: V8 6.7.288.46 * User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 Original post 2013-11-01 ======================== In Google Chrome, the following was ever so slightly faster than a `typeof` test: ``` if (abc === void 0) { // Undefined } ``` The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what `void 0` means. Note, however, that `abc` **must still be declared**. Both `typeof` and `void` were significantly faster than comparing directly against `undefined`. I used the following test format in the Chrome developer console: ``` var abc; start = +new Date(); for (var i = 0; i < 10000000; i++) { if (TEST) { void 1; } } end = +new Date(); end - start; ``` The results were as follows: ``` Test: | abc === undefined abc === void 0 typeof abc == 'undefined' ------+--------------------------------------------------------------------- x10M | 13678 ms 9854 ms 9888 ms x1 | 1367.8 ns 985.4 ns 988.8 ns ``` Note that the first row is in *milli*seconds, while the second row is in *nano*seconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.
``` // x has not been defined before if (typeof x === 'undefined') { // Evaluates to true without errors. // These statements execute. } if (x === undefined) { // Throws a ReferenceError } ```
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
**2020 Update** One of my reasons for preferring a `typeof` check (namely, that `undefined` can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use `typeof` to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations: ``` myVariable === undefined ``` **Original answer from 2010** Using `typeof` is my preference. It will work when the variable has never been declared, unlike any comparison with the `==` or `===` operators or type coercion using `if`. (`undefined`, unlike `null`, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above). ``` if (typeof someUndeclaredVariable == "undefined") { // Works } if (someUndeclaredVariable === undefined) { // Throws an error } ```
I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source. ``` undefined = 2; (function (undefined) { console.log(undefined); // prints out undefined // and for comparison: if (undeclaredvar === undefined) console.log("it works!") })() ``` Of course you could just use `typeof` though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined. You can check the type of the variable: ``` if (typeof(something) != "undefined") ... ``` Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example: ``` if (something) { something(param); } ```
``` var x; if (x === undefined) { alert ("I am declared, but not defined.") }; if (typeof y === "undefined") { alert ("I am not even declared.") }; /* One more thing to understand: typeof ==='undefined' also checks for if a variable is declared, but no value is assigned. In other words, the variable is declared, but not defined. */ // Will repeat above logic of x for typeof === 'undefined' if (x === undefined) { alert ("I am declared, but not defined.") }; /* So typeof === 'undefined' works for both, but x === undefined only works for a variable which is at least declared. */ /* Say if I try using typeof === undefined (not in quotes) for a variable which is not even declared, we will get run a time error. */ if (z === undefined) { alert ("I am neither declared nor defined.") }; // I got this error for z ReferenceError: z is not defined ```
464,802
Take a look at this here: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{align*} \Leftrightarrow \qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow \qquad e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{align*} \end{document} ``` Is it possible to have the equivalences below each other like the equations are? ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{alignat*}{4} P'_1(t)&=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow &&\qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow && e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignat*} \end{document} ``` This almost works but i have the mention problem that the first line is pulled to the very left.
2018/12/14
[ "https://tex.stackexchange.com/questions/464802", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/173831/" ]
Like so? ``` \documentclass{article} \usepackage{amsmath} \begin{document} \begin{align} \Leftrightarrow&& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \tag{2.6} \\ \Leftrightarrow&& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \notag \end{align} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/82Cbm.png)](https://i.stack.imgur.com/82Cbm.png)
You can also use `alignat`: [![enter image description here](https://i.stack.imgur.com/3UOxi.png)](https://i.stack.imgur.com/3UOxi.png) Code: ----- ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{alignat*}{4} \Leftrightarrow &&\qquad P'_1(t)+\lambda P_1(t) &=\lambda e^{-\lambda t} && (2.6) \\ \Leftrightarrow &&\qquad e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t) &=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \end{alignat*} \end{document} ```
464,802
Take a look at this here: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{align*} \Leftrightarrow \qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow \qquad e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{align*} \end{document} ``` Is it possible to have the equivalences below each other like the equations are? ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{alignat*}{4} P'_1(t)&=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow &&\qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow && e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignat*} \end{document} ``` This almost works but i have the mention problem that the first line is pulled to the very left.
2018/12/14
[ "https://tex.stackexchange.com/questions/464802", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/173831/" ]
Like so? ``` \documentclass{article} \usepackage{amsmath} \begin{document} \begin{align} \Leftrightarrow&& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \tag{2.6} \\ \Leftrightarrow&& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \notag \end{align} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/82Cbm.png)](https://i.stack.imgur.com/82Cbm.png)
You *don't* want to manually number your equations and not because of the fact that the numbers would be unaligned to each other, but because maintaining manual numbering is essentially impossible. Use the `\label`-`\ref` mechanism for this. Your problem can be solved with `alignedat`: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amssymb} \numberwithin{equation}{section} \begin{document} % let's emulate being in section 2 with five % numbered equations before this one; a real document % will have nothing like this \setcounter{section}{2}\setcounter{equation}{5} \begin{equation}\label{equivalenteqs} \begin{alignedat}{2} \Leftrightarrow &\qquad& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \\ \Leftrightarrow &\qquad& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t) &=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignedat} \end{equation} As we see in equation~\eqref{equivalenteqs} we can blah blah. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/dLTdX.png)](https://i.stack.imgur.com/dLTdX.png) If you happen to have a first line without the arrows, just add the suitable number of alignment points: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amssymb} \numberwithin{equation}{section} \begin{document} % let's emulate being in section 2 with five % numbered equations before this one \setcounter{section}{2}\setcounter{equation}{5} \begin{equation} \begin{alignedat}{2} &\qquad& P'_1(t)&=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow & & P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \\ \Leftrightarrow & & e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \Leftrightarrow & & \frac{d}{dt}(e^{\lambda t}P_1(t))&=e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)=\lambda\\ \end{alignedat} \end{equation} As we see in equation~\eqref{equivalenteqs} we can blah blah. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/uc9ki.png)](https://i.stack.imgur.com/uc9ki.png) On the other hand, I see no reason for aligning at the equals signs. ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amssymb} \numberwithin{equation}{section} \begin{document} % let's emulate being in section 2 with five % numbered equations before this one \setcounter{section}{2}\setcounter{equation}{5} \begin{equation}\label{equivalenteqs} \begin{aligned} && & P'_1(t)=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow && & P'_1(t)+\lambda P_1(t)=\lambda e^{-\lambda t} \\ \Leftrightarrow && & e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \Leftrightarrow && & \frac{d}{dt}(e^{\lambda t}P_1(t))=e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)=\lambda\\ \end{aligned} \end{equation} As we see in equation~\eqref{equivalenteqs} we can blah blah. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/SSqNx.png)](https://i.stack.imgur.com/SSqNx.png)
464,802
Take a look at this here: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{align*} \Leftrightarrow \qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow \qquad e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{align*} \end{document} ``` Is it possible to have the equivalences below each other like the equations are? ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{alignat*}{4} P'_1(t)&=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow &&\qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow && e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignat*} \end{document} ``` This almost works but i have the mention problem that the first line is pulled to the very left.
2018/12/14
[ "https://tex.stackexchange.com/questions/464802", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/173831/" ]
Like so? ``` \documentclass{article} \usepackage{amsmath} \begin{document} \begin{align} \Leftrightarrow&& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \tag{2.6} \\ \Leftrightarrow&& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \notag \end{align} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/82Cbm.png)](https://i.stack.imgur.com/82Cbm.png)
You also might be interested in the `ArrowBetweenLines` from `mathtools`: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{mathtools} \usepackage{amssymb} \numberwithin{equation}{section} \begin{document} \setcounter{section}{2}\setcounter{equation}{5} \begin{equation}\label{equivalenteqs} \begin{alignedat}{2} & & abc & =def \\ \ArrowBetweenLines &\qquad& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \\ \ArrowBetweenLines &\qquad& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t) &=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignedat} \end{equation} As we see in equation~\eqref{equivalenteqs} we can blah blah. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/oecOb.png)](https://i.stack.imgur.com/oecOb.png)
40,368,293
I have a stylesheet that specifies a style for `<LABEL>`. But some `<LABEL>`s are special: Currently I inline style them like this: ``` <LABEL style="text-align:right; line-height:15pt"> <div style="padding-right:20px">My Label Text</div> </LABEL> ``` I suspect there's a way to specify a CSS class, perhaps called `rightlabel`, to render the preceding using something simple like this: ``` <LABEL class="rightlabel">My Label Text</LABEL> ``` What would the correct way be to do that? I.e., is there a way to define `rightlabel` in CSS to produce the overridden `<LABEL>` **while automatically wrapping its children in a padded child container** (because the style doesn't work correctly unless that is done, and it doesn't seem proper to depend on the coder to implement two elements to get the style right)? **Amendment:** I can get most of the way there using a child selector – as shown in [this fiddle](https://jsfiddle.net/c3h9a2b9/) with this CSS: ``` .rightLabel {text-align: right} .rightLabel > * {padding-right: 20px} ``` But I can't find a way to apply the padding to the label contents without explicitly wrapping the contents in some container. I.e., the above CSS works correctly on ``` <LABEL class="rightLabel"> <div>This is what we wanted!</div> </LABEL> ``` but not on ``` <LABEL class="rightLabel">Why am I not padded?</LABEL> ``` Is it possible to apply a style to the `<LABEL>` contents without explicitly coding them inside another HTML element (child)?
2016/11/01
[ "https://Stackoverflow.com/questions/40368293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2662901/" ]
Usually, faces stores indices of each triangle in the vertices array. So the first face is a triangle consisting of vertices[0], vertices[1], vertices[2]. The second one consists of vertices[3], vertices[4], vertices[5] and so on.
For triangular meshes, a face is a triangle defined by 3 vertices. Normally, a mesh is composed by a list of n vertices and m faces. For example: Vertices: ``` Point_0 = {0,0,0} Point_1 = {2,0,0} Point_3 = {0,2,0} Point_4 = {0,3,0} ... Point_n = {30,0,0} ``` Faces: ``` Face_0 = {Point_1, Point_4, Point_5} Face_1 = {Point_2, Point_4, Point_7} ... Face_m = {Point_1, Point_2, Point_n} ``` For the sake of brevity, you can define Face\_0 as a set of indices: {1,4,5}. In addition, the normal vector is computed as a cross product between the vertices of a face. By convention, the direction of the normal vector is directed outside the mesh. For example: ``` normal_face_0 = CrossProcuct ( (Point_4 - Point_1) , (Point_5 - Point_4) ) ``` In your case, it is quite weird to see four indices in a face definition. Normally, there should be only 3 items in the array. Are you sure this is not a mistake?
5,257,198
How can I measure time that ListView/ListActivity takes for rendering its list? I have a ListActivity that takes a long time to show (on older devices it's ~3s) and I'd like to optimize that. EDIT: I already have time between Activity1 and Activity2. During this time, Activity2 is doing some stuff (initializing). Among other things, it renders its list. I want to get time this activity takes to render that list. If total time between activities is 3s, I want to know whether rendering list takes 2.9s or 0.5s....
2011/03/10
[ "https://Stackoverflow.com/questions/5257198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133648/" ]
You could simply ouput the time. For example you could use the logcat ``` final long t0 = System.currentTimeMillis(); // code to measure Log.w(TAG, "TEXT" + System.currentTimeMillis()-t0); ``` Of course you could use any other system for the ouput like a dialog or stuff. Just use what you like. EDIT: If you don't want to use a debug message in your code all the time you could do it like this: Create a class called settings: ``` public class Settings { public static final boolean DEBUG = true; // If you prefer you could do use an enum // enum debugLevel {SHOW_EVERYMESSAGE, ERRORS, IMPORTANT_MESSAGES, ...} // In your classes you would have to check that DEBUG is less or equal than // the debugLevel you want } ``` In classes where you want to use a debug message simply do this ``` import xxx.yyy.Settings class foo { final static boolean DEBUG = Settings.DEBUG; if(DEBUG){ // Debug messages } } ``` Now if you want to disable DEBUG messages you could simply set `DEBUG = false` in your Settings class. If you want to measure between two activities you could use intents and send t0 with an intent to the other activity to compute the time. Of course you could include this with `if(DEBUG){ /* code */ }` statements to spare the sending of the intent in the final release. The if statements should not increase the computation of your code too dramatically.
I cannot tell if Java offers a better implementation using `System.currentTimeMillis()` or `System.nanoTime()`. Nevertheless, you should give the [TimingLogger](http://developer.android.com/reference/android/util/TimingLogger.html) class a try. Take a look at this [article describing the usage of the TimingLogger helper class](http://hoccer.com/2010/09/measuring-performance-with-android/).
26,871,085
I'm trying to save the contents of an entire Wordpress site using python and without ftp / server access. In other words, I want to save a "complete copy, or closest possible" of the Wordpress site to disk and I can't download everything from ftp / server. I've found some options to iterate through the various pages that make up the site, but nothing that will "save the site as a whole."
2014/11/11
[ "https://Stackoverflow.com/questions/26871085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114926/" ]
Not using python (although I'm sure you could hack up something -- or possibly find something on pypi), but why not just use wget. Something like: ``` wget -rkp -l3 -np -nH --cut-dirs=1 http://example.com ``` Of course if you REALLY want to do it in python, you could: ``` import subprocess subprocess.call(['wget', '-rkp', '-l3', '-np', '-nH', '--cut-dirs=1', 'http://example.com']) ```
If you can, and you should, mantain all WordPress modeling tables, you might want to use a WordPress feature (also plugin) called Migrate...You might have it, so, if you can go to your Administration Panel (aka /wp-admin) you can loggin and use <http://yourdomain.com/wp-admin/export.php> This way, you will get a XML that you can use to import to your python project. There are also some plugins that export a full .sql file Remember, all content is basically into the MySQL tables, so that all you need there
26,871,085
I'm trying to save the contents of an entire Wordpress site using python and without ftp / server access. In other words, I want to save a "complete copy, or closest possible" of the Wordpress site to disk and I can't download everything from ftp / server. I've found some options to iterate through the various pages that make up the site, but nothing that will "save the site as a whole."
2014/11/11
[ "https://Stackoverflow.com/questions/26871085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114926/" ]
If you really want to use Python and nothing else, you could use [wpull](http://wpull.readthedocs.org/en/master/index.html), which is a wget clone written in Python. They have an example for archiving/downloading an entire website in their docs. ``` wpull billy.blogsite.example --warc-file blogsite-billy \ --no-check-certificate \ --no-robots --user-agent "InconspiuousWebBrowser/1.0" \ --wait 0.5 --random-wait --waitretry 600 \ --page-requisites --recursive --level inf \ --span-hosts --domains blogsitecdn.example,cloudspeeder.example \ --hostnames billy.blogsite.example \ --reject-regex "/login\.php" \ --tries inf --retry-connrefused --retry-dns-error \ --delete-after --database blogsite-billy.db \ --quiet --output-file blogsite-billy.log ```
Not using python (although I'm sure you could hack up something -- or possibly find something on pypi), but why not just use wget. Something like: ``` wget -rkp -l3 -np -nH --cut-dirs=1 http://example.com ``` Of course if you REALLY want to do it in python, you could: ``` import subprocess subprocess.call(['wget', '-rkp', '-l3', '-np', '-nH', '--cut-dirs=1', 'http://example.com']) ```
26,871,085
I'm trying to save the contents of an entire Wordpress site using python and without ftp / server access. In other words, I want to save a "complete copy, or closest possible" of the Wordpress site to disk and I can't download everything from ftp / server. I've found some options to iterate through the various pages that make up the site, but nothing that will "save the site as a whole."
2014/11/11
[ "https://Stackoverflow.com/questions/26871085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114926/" ]
If you really want to use Python and nothing else, you could use [wpull](http://wpull.readthedocs.org/en/master/index.html), which is a wget clone written in Python. They have an example for archiving/downloading an entire website in their docs. ``` wpull billy.blogsite.example --warc-file blogsite-billy \ --no-check-certificate \ --no-robots --user-agent "InconspiuousWebBrowser/1.0" \ --wait 0.5 --random-wait --waitretry 600 \ --page-requisites --recursive --level inf \ --span-hosts --domains blogsitecdn.example,cloudspeeder.example \ --hostnames billy.blogsite.example \ --reject-regex "/login\.php" \ --tries inf --retry-connrefused --retry-dns-error \ --delete-after --database blogsite-billy.db \ --quiet --output-file blogsite-billy.log ```
If you can, and you should, mantain all WordPress modeling tables, you might want to use a WordPress feature (also plugin) called Migrate...You might have it, so, if you can go to your Administration Panel (aka /wp-admin) you can loggin and use <http://yourdomain.com/wp-admin/export.php> This way, you will get a XML that you can use to import to your python project. There are also some plugins that export a full .sql file Remember, all content is basically into the MySQL tables, so that all you need there
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
Here's a very concise and recursive solution that allows you to input the size of the output permutations similar to the statistical operator nPr. "5 permutation 3". This allows you to get all possible permutations with a specific size. ``` function generatePermutations(list, size=list.length) { if (size > list.length) return []; else if (size == 1) return list.map(d=>[d]); return list.flatMap(d => generatePermutations(list.filter(a => a !== d), size - 1).map(item => [d, ...item])); } ``` `generatePermutations([1,2,3])` ``` [[1, 2, 3],[1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] ``` `generatePermutations([1,2,3],2)` ``` [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] ```
here is a visualization for the recursive function => <https://recursion.vercel.app/> ``` var permute = function (nums) { let answer = []; var permuter = function (arr, permutation = []) { if (arr.length === 0) { return answer.push(permutation); } else { for (let i = 0; i < arr.length; i++) { let currentArr = arr.slice(); let next = currentArr.splice(i, 1); permuter(currentArr, permutation.concat(next)); ///we use concat because splice returns an array. } } }; permuter(nums); return answer; }; ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
Most of the other answers do not utilize the new javascript generator functions which is a perfect solution to this type of problem. You probably only need one permutation at time in memory. Also, I prefer to generate a permutation of a range of indices as this allows me to index each permutation and jump straight to any particular permutation as well as be used to permutate any other collection. ```js // ES6 generator version of python itertools [permutations and combinations] const range = function*(l) { for (let i = 0; i < l; i+=1) yield i; } const isEmpty = arr => arr.length === 0; const permutations = function*(a) { const r = arguments[1] || []; if (isEmpty(a)) yield r; for (let i of range(a.length)) { const aa = [...a]; const rr = [...r, ...aa.splice(i, 1)]; yield* permutations(aa, rr); } } console.log('permutations of ABC'); console.log(JSON.stringify([...permutations([...'ABC'])])); const combinations = function*(a, count) { const r = arguments[2] || []; if (count) { count = count - 1; for (let i of range(a.length - count)) { const aa = a.slice(i); const rr = [...r, ...aa.splice(0, 1)]; yield* combinations(aa, count, rr); } } else { yield r; } } console.log('combinations of 2 of ABC'); console.log(JSON.stringify([...combinations([...'ABC'], 2)])); const permutator = function() { const range = function*(args) { let {begin = 0, count} = args; for (let i = begin; count; count--, i+=1) { yield i; } } const factorial = fact => fact ? fact * factorial(fact - 1) : 1; return { perm: function(n, permutationId) { const indexCount = factorial(n); permutationId = ((permutationId%indexCount)+indexCount)%indexCount; let permutation = [0]; for (const choiceCount of range({begin: 2, count: n-1})) { const choice = permutationId % choiceCount; const lastIndex = permutation.length; permutation.push(choice); permutation = permutation.map((cv, i, orig) => (cv < choice || i == lastIndex) ? cv : cv + 1 ); permutationId = Math.floor(permutationId / choiceCount); } return permutation.reverse(); }, perms: function*(n) { for (let i of range({count: factorial(n)})) { yield this.perm(n, i); } } }; }(); console.log('indexing type permutator'); let i = 0; for (let elem of permutator.perms(3)) { console.log(`${i}: ${elem}`); i+=1; } console.log(); console.log(`3: ${permutator.perm(3,3)}`); ```
``` function swap(array1, index1, index2) { var temp; temp = array1[index1]; array1[index1] = array1[index2]; array1[index2] = temp; } function permute(a, l, r) { var i; if (l == r) { console.log(a.join('')); } else { for (i = l; i <= r; i++) { swap(a, l, i); permute(a, l + 1, r); swap(a, l, i); } } } permute(["A","B","C", "D"],0,3); ``` // sample execution //for more details refer this link // <http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/>
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
Answer without the need for a exterior array or additional function ``` function permutator (arr) { var permutations = []; if (arr.length === 1) { return [ arr ]; } for (var i = 0; i < arr.length; i++) { var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1))); for (var j = 0; j < subPerms.length; j++) { subPerms[j].unshift(arr[i]); permutations.push(subPerms[j]); } } return permutations; } ```
This is just little bit more succinct version of delimited's ```js function permutator (inputArr) { const result = [] function permute (arr, m = []) { if (arr.length) { arr.forEach((item, i) => { const restArr = [...arr.slice(0, i), ...arr.slice(i + 1)] permute(restArr, [...m, item]) }) } else { result.push(m) } } permute(inputArr) return result } ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
The following very efficient algorithm uses [Heap's method](http://homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf) to generate all permutations of N elements with runtime complexity in O(N!): ```js function permute(permutation) { var length = permutation.length, result = [permutation.slice()], c = new Array(length).fill(0), i = 1, k, p; while (i < length) { if (c[i] < i) { k = i % 2 && c[i]; p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; result.push(permutation.slice()); } else { c[i] = 0; ++i; } } return result; } console.log(permute([1, 2, 3])); ``` The same algorithm implemented as a [generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) with space complexity in O(N): ```js function* permute(permutation) { var length = permutation.length, c = Array(length).fill(0), i = 1, k, p; yield permutation.slice(); while (i < length) { if (c[i] < i) { k = i % 2 && c[i]; p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; yield permutation.slice(); } else { c[i] = 0; ++i; } } } // Memory efficient iteration through permutations: for (var permutation of permute([1, 2, 3])) console.log(permutation); // Simple array conversion: var permutations = [...permute([1, 2, 3])]; ``` ### Performance comparison Feel free to add your implementation to the following [benchmark.js](https://benchmarkjs.com/) test suite: ```js function permute_SiGanteng(input) { var permArr = [], usedChars = []; function permute(input) { var i, ch; for (i = 0; i < input.length; i++) { ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } permute(input); input.splice(i, 0, ch); usedChars.pop(); } return permArr } return permute(input); } function permute_delimited(inputArr) { var results = []; function permute(arr, memo) { var cur, memo = memo || []; for (var i = 0; i < arr.length; i++) { cur = arr.splice(i, 1); if (arr.length === 0) { results.push(memo.concat(cur)); } permute(arr.slice(), memo.concat(cur)); arr.splice(i, 0, cur[0]); } return results; } return permute(inputArr); } function permute_monkey(inputArray) { return inputArray.reduce(function permute(res, item, key, arr) { return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item); }, []); } function permute_Oriol(input) { var permArr = [], usedChars = []; return (function main() { for (var i = 0; i < input.length; i++) { var ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } main(); input.splice(i, 0, ch); usedChars.pop(); } return permArr; })(); } function permute_MarkusT(input) { function permutate(array, callback) { function p(array, index, callback) { function swap(a, i1, i2) { var t = a[i1]; a[i1] = a[i2]; a[i2] = t; } if (index == array.length - 1) { callback(array); return 1; } else { var count = p(array, index + 1, callback); for (var i = index + 1; i < array.length; i++) { swap(array, i, index); count += p(array, index + 1, callback); swap(array, i, index); } return count; } } if (!array || array.length == 0) { return 0; } return p(array, 0, callback); } var result = []; permutate(input, function(a) { result.push(a.slice(0)); }); return result; } function permute_le_m(permutation) { var length = permutation.length, result = [permutation.slice()], c = new Array(length).fill(0), i = 1, k, p; while (i < length) { if (c[i] < i) { k = i % 2 && c[i], p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; result.push(permutation.slice()); } else { c[i] = 0; ++i; } } return result; } function permute_Urielzen(arr) { var finalArr = []; var iterator = function (arrayTaken, tree) { for (var i = 0; i < tree; i++) { var temp = arrayTaken.slice(); temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]); if (tree >= arr.length) { finalArr.push(temp); } else { iterator(temp, tree + 1); } } } iterator(arr, 1); return finalArr; } function permute_Taylor_Hakes(arr) { var permutations = []; if (arr.length === 1) { return [ arr ]; } for (var i = 0; i < arr.length; i++) { var subPerms = permute_Taylor_Hakes(arr.slice(0, i).concat(arr.slice(i + 1))); for (var j = 0; j < subPerms.length; j++) { subPerms[j].unshift(arr[i]); permutations.push(subPerms[j]); } } return permutations; } var Combinatorics = (function () { 'use strict'; var version = "0.5.2"; /* combinatory arithmetics */ var P = function(m, n) { var p = 1; while (n--) p *= m--; return p; }; var C = function(m, n) { if (n > m) { return 0; } return P(m, n) / P(n, n); }; var factorial = function(n) { return P(n, n); }; var factoradic = function(n, d) { var f = 1; if (!d) { for (d = 1; f < n; f *= ++d); if (f > n) f /= d--; } else { f = factorial(d); } var result = [0]; for (; d; f /= d--) { result[d] = Math.floor(n / f); n %= f; } return result; }; /* common methods */ var addProperties = function(dst, src) { Object.keys(src).forEach(function(p) { Object.defineProperty(dst, p, { value: src[p], configurable: p == 'next' }); }); }; var hideProperty = function(o, p) { Object.defineProperty(o, p, { writable: true }); }; var toArray = function(f) { var e, result = []; this.init(); while (e = this.next()) result.push(f ? f(e) : e); this.init(); return result; }; var common = { toArray: toArray, map: toArray, forEach: function(f) { var e; this.init(); while (e = this.next()) f(e); this.init(); }, filter: function(f) { var e, result = []; this.init(); while (e = this.next()) if (f(e)) result.push(e); this.init(); return result; }, lazyMap: function(f) { this._lazyMap = f; return this; }, lazyFilter: function(f) { Object.defineProperty(this, 'next', { writable: true }); if (typeof f !== 'function') { this.next = this._next; } else { if (typeof (this._next) !== 'function') { this._next = this.next; } var _next = this._next.bind(this); this.next = (function() { var e; while (e = _next()) { if (f(e)) return e; } return e; }).bind(this); } Object.defineProperty(this, 'next', { writable: false }); return this; } }; /* power set */ var power = function(ary, fun) { var size = 1 << ary.length, sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'index'); addProperties(that, { valueOf: sizeOf, init: function() { that.index = 0; }, nth: function(n) { if (n >= size) return; var i = 0, result = []; for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]); return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; }, next: function() { return this.nth(this.index++); } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* combination */ var nextIndex = function(n) { var smallest = n & -n, ripple = n + smallest, new_smallest = ripple & -ripple, ones = ((new_smallest / smallest) >> 1) - 1; return ripple | ones; }; var combination = function(ary, nelem, fun) { if (!nelem) nelem = ary.length; if (nelem < 1) throw new RangeError; if (nelem > ary.length) throw new RangeError; var first = (1 << nelem) - 1, size = C(ary.length, nelem), maxIndex = 1 << ary.length, sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'index'); addProperties(that, { valueOf: sizeOf, init: function() { this.index = first; }, next: function() { if (this.index >= maxIndex) return; var i = 0, n = this.index, result = []; for (; n; n >>>= 1, i++) { if (n & 1) result[result.length] = this[i]; } this.index = nextIndex(this.index); return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* permutation */ var _permutation = function(ary) { var that = ary.slice(), size = factorial(that.length); that.index = 0; that.next = function() { if (this.index >= size) return; var copy = this.slice(), digits = factoradic(this.index, this.length), result = [], i = this.length - 1; for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]); this.index++; return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; }; return that; }; // which is really a permutation of combination var permutation = function(ary, nelem, fun) { if (!nelem) nelem = ary.length; if (nelem < 1) throw new RangeError; if (nelem > ary.length) throw new RangeError; var size = P(ary.length, nelem), sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'cmb'); hideProperty(that, 'per'); addProperties(that, { valueOf: function() { return size; }, init: function() { this.cmb = combination(ary, nelem); this.per = _permutation(this.cmb.next()); }, next: function() { var result = this.per.next(); if (!result) { var cmb = this.cmb.next(); if (!cmb) return; this.per = _permutation(cmb); return this.next(); } return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* export */ var Combinatorics = Object.create(null); addProperties(Combinatorics, { C: C, P: P, factorial: factorial, factoradic: factoradic, permutation: permutation, }); return Combinatorics; })(); function permute_Technicalbloke(inputArray) { if (inputArray.length === 1) return inputArray; return inputArray.reduce( function(accumulator,_,index){ permute_Technicalbloke([...inputArray.slice(0,index),...inputArray.slice(index+1)]) .map(value=>accumulator.push([inputArray[index],value])); return accumulator; },[]); } var suite = new Benchmark.Suite; var input = [0, 1, 2, 3, 4]; suite.add('permute_SiGanteng', function() { permute_SiGanteng(input); }) .add('permute_delimited', function() { permute_delimited(input); }) .add('permute_monkey', function() { permute_monkey(input); }) .add('permute_Oriol', function() { permute_Oriol(input); }) .add('permute_MarkusT', function() { permute_MarkusT(input); }) .add('permute_le_m', function() { permute_le_m(input); }) .add('permute_Urielzen', function() { permute_Urielzen(input); }) .add('permute_Taylor_Hakes', function() { permute_Taylor_Hakes(input); }) .add('permute_Combinatorics', function() { Combinatorics.permutation(input).toArray(); }) .add('permute_Technicalbloke', function() { permute_Technicalbloke(input); }) .on('cycle', function(event) { console.log(String(event.target)); }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run({async: true}); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.4/platform.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script> ``` Run-time results for Chrome 48: * 99.152ms **This algorithm** * 153.115ms [MarkusT](https://stackoverflow.com/a/11629015/1647737) * 401.255ms [js-combinatorics](https://stackoverflow.com/a/30013816/1647737) * 497.037ms [Urielzen](https://stackoverflow.com/a/24622772/1647737) * 925.669ms [Oriol](https://stackoverflow.com/a/11509565/1647737) * 1026.571ms [SiGanteng](https://stackoverflow.com/a/9960925/1647737) * 2529.841ms [delimited](https://stackoverflow.com/a/20871714/1647737) * 3992.622ms [monkey](https://stackoverflow.com/a/22063440/1647737) * 4514.665ms [Oriol](https://stackoverflow.com/a/32551801/1647737)
I wrote a [post](http://www.pixelstech.net/article/1316620955-Permutation-algorithm-with-JavaScript) to demonstrate how to permute an array in JavaScript. Here is the code which does this. ``` var count=0; function permute(pre,cur){ var len=cur.length; for(var i=0;i<len;i++){ var p=clone(pre); var c=clone(cur); p.push(cur[i]); remove(c,cur[i]); if(len>1){ permute(p,c); }else{ print(p); count++; } } } function print(arr){ var len=arr.length; for(var i=0;i<len;i++){ document.write(arr[i]+" "); } document.write("<br />"); } function remove(arr,item){ if(contains(arr,item)){ var len=arr.length; for(var i = len-1; i >= 0; i--){ // STEP 1 if(arr[i] == item){ // STEP 2 arr.splice(i,1); // STEP 3 } } } } function contains(arr,value){ for(var i=0;i<arr.length;i++){ if(arr[i]==value){ return true; } } return false; } function clone(arr){ var a=new Array(); var len=arr.length; for(var i=0;i<len;i++){ a.push(arr[i]); } return a; } ``` Just call > > permute([], [1,2,3,4]) > > > will work. For details on how this works, please refer to the explanation in that post.
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
If you notice, the code actually splits the chars into an array prior to do any permutation, so you simply remove the join and split operation ```js var permArr = [], usedChars = []; function permute(input) { var i, ch; for (i = 0; i < input.length; i++) { ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } permute(input); input.splice(i, 0, ch); usedChars.pop(); } return permArr }; document.write(JSON.stringify(permute([5, 3, 7, 1]))); ```
``` #!/usr/bin/env node "use strict"; function perm(arr) { if(arr.length<2) return [arr]; var res = []; arr.forEach(function(x, i) { perm(arr.slice(0,i).concat(arr.slice(i+1))).forEach(function(a) { res.push([x].concat(a)); }); }); return res; } console.log(perm([1,2,3,4])); ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
```js "use strict"; function getPermutations(arrP) { var results = []; var arr = arrP; arr.unshift(null); var length = arr.length; while (arr[0] === null) { results.push(arr.slice(1).join('')); let less = null; let lessIndex = null; for (let i = length - 1; i > 0; i--) { if(arr[i - 1] < arr[i]){ less = arr[i - 1]; lessIndex = i - 1; break; } } for (let i = length - 1; i > lessIndex; i--) { if(arr[i] > less){ arr[lessIndex] = arr[i]; arr[i] = less; break; } } for(let i = lessIndex + 1; i<length; i++){ for(let j = i + 1; j < length; j++){ if(arr[i] > arr[j] ){ arr[i] = arr[i] + arr[j]; arr[j] = arr[i] - arr[j]; arr[i] = arr[i] - arr[j]; } } } } return results; } var res = getPermutations([1,2,3,4,5]); var out = document.getElementById('myTxtArr'); res.forEach(function(i){ out.value+=i+', '}); ``` ```css textarea{ height:500px; width:500px; } ``` ```html <textarea id='myTxtArr'></textarea> ``` Outputs lexicographically ordered permutations. Works only with numbers. In other case, you have to change the swap method on line 34.
I think you'll may like this one: ``` const permute1 = (arr: any[]): any[][] => arr.reduce( (acc, curr) => acc.length > 0 ? acc .map((p) => Array.from({ length: p.length + 1 }, (_, i) => p.slice(0, i).concat(curr, p.slice(i)) ) ) .flat() : [[curr]], [] ); ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
The following very efficient algorithm uses [Heap's method](http://homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf) to generate all permutations of N elements with runtime complexity in O(N!): ```js function permute(permutation) { var length = permutation.length, result = [permutation.slice()], c = new Array(length).fill(0), i = 1, k, p; while (i < length) { if (c[i] < i) { k = i % 2 && c[i]; p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; result.push(permutation.slice()); } else { c[i] = 0; ++i; } } return result; } console.log(permute([1, 2, 3])); ``` The same algorithm implemented as a [generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) with space complexity in O(N): ```js function* permute(permutation) { var length = permutation.length, c = Array(length).fill(0), i = 1, k, p; yield permutation.slice(); while (i < length) { if (c[i] < i) { k = i % 2 && c[i]; p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; yield permutation.slice(); } else { c[i] = 0; ++i; } } } // Memory efficient iteration through permutations: for (var permutation of permute([1, 2, 3])) console.log(permutation); // Simple array conversion: var permutations = [...permute([1, 2, 3])]; ``` ### Performance comparison Feel free to add your implementation to the following [benchmark.js](https://benchmarkjs.com/) test suite: ```js function permute_SiGanteng(input) { var permArr = [], usedChars = []; function permute(input) { var i, ch; for (i = 0; i < input.length; i++) { ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } permute(input); input.splice(i, 0, ch); usedChars.pop(); } return permArr } return permute(input); } function permute_delimited(inputArr) { var results = []; function permute(arr, memo) { var cur, memo = memo || []; for (var i = 0; i < arr.length; i++) { cur = arr.splice(i, 1); if (arr.length === 0) { results.push(memo.concat(cur)); } permute(arr.slice(), memo.concat(cur)); arr.splice(i, 0, cur[0]); } return results; } return permute(inputArr); } function permute_monkey(inputArray) { return inputArray.reduce(function permute(res, item, key, arr) { return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item); }, []); } function permute_Oriol(input) { var permArr = [], usedChars = []; return (function main() { for (var i = 0; i < input.length; i++) { var ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } main(); input.splice(i, 0, ch); usedChars.pop(); } return permArr; })(); } function permute_MarkusT(input) { function permutate(array, callback) { function p(array, index, callback) { function swap(a, i1, i2) { var t = a[i1]; a[i1] = a[i2]; a[i2] = t; } if (index == array.length - 1) { callback(array); return 1; } else { var count = p(array, index + 1, callback); for (var i = index + 1; i < array.length; i++) { swap(array, i, index); count += p(array, index + 1, callback); swap(array, i, index); } return count; } } if (!array || array.length == 0) { return 0; } return p(array, 0, callback); } var result = []; permutate(input, function(a) { result.push(a.slice(0)); }); return result; } function permute_le_m(permutation) { var length = permutation.length, result = [permutation.slice()], c = new Array(length).fill(0), i = 1, k, p; while (i < length) { if (c[i] < i) { k = i % 2 && c[i], p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; result.push(permutation.slice()); } else { c[i] = 0; ++i; } } return result; } function permute_Urielzen(arr) { var finalArr = []; var iterator = function (arrayTaken, tree) { for (var i = 0; i < tree; i++) { var temp = arrayTaken.slice(); temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]); if (tree >= arr.length) { finalArr.push(temp); } else { iterator(temp, tree + 1); } } } iterator(arr, 1); return finalArr; } function permute_Taylor_Hakes(arr) { var permutations = []; if (arr.length === 1) { return [ arr ]; } for (var i = 0; i < arr.length; i++) { var subPerms = permute_Taylor_Hakes(arr.slice(0, i).concat(arr.slice(i + 1))); for (var j = 0; j < subPerms.length; j++) { subPerms[j].unshift(arr[i]); permutations.push(subPerms[j]); } } return permutations; } var Combinatorics = (function () { 'use strict'; var version = "0.5.2"; /* combinatory arithmetics */ var P = function(m, n) { var p = 1; while (n--) p *= m--; return p; }; var C = function(m, n) { if (n > m) { return 0; } return P(m, n) / P(n, n); }; var factorial = function(n) { return P(n, n); }; var factoradic = function(n, d) { var f = 1; if (!d) { for (d = 1; f < n; f *= ++d); if (f > n) f /= d--; } else { f = factorial(d); } var result = [0]; for (; d; f /= d--) { result[d] = Math.floor(n / f); n %= f; } return result; }; /* common methods */ var addProperties = function(dst, src) { Object.keys(src).forEach(function(p) { Object.defineProperty(dst, p, { value: src[p], configurable: p == 'next' }); }); }; var hideProperty = function(o, p) { Object.defineProperty(o, p, { writable: true }); }; var toArray = function(f) { var e, result = []; this.init(); while (e = this.next()) result.push(f ? f(e) : e); this.init(); return result; }; var common = { toArray: toArray, map: toArray, forEach: function(f) { var e; this.init(); while (e = this.next()) f(e); this.init(); }, filter: function(f) { var e, result = []; this.init(); while (e = this.next()) if (f(e)) result.push(e); this.init(); return result; }, lazyMap: function(f) { this._lazyMap = f; return this; }, lazyFilter: function(f) { Object.defineProperty(this, 'next', { writable: true }); if (typeof f !== 'function') { this.next = this._next; } else { if (typeof (this._next) !== 'function') { this._next = this.next; } var _next = this._next.bind(this); this.next = (function() { var e; while (e = _next()) { if (f(e)) return e; } return e; }).bind(this); } Object.defineProperty(this, 'next', { writable: false }); return this; } }; /* power set */ var power = function(ary, fun) { var size = 1 << ary.length, sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'index'); addProperties(that, { valueOf: sizeOf, init: function() { that.index = 0; }, nth: function(n) { if (n >= size) return; var i = 0, result = []; for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]); return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; }, next: function() { return this.nth(this.index++); } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* combination */ var nextIndex = function(n) { var smallest = n & -n, ripple = n + smallest, new_smallest = ripple & -ripple, ones = ((new_smallest / smallest) >> 1) - 1; return ripple | ones; }; var combination = function(ary, nelem, fun) { if (!nelem) nelem = ary.length; if (nelem < 1) throw new RangeError; if (nelem > ary.length) throw new RangeError; var first = (1 << nelem) - 1, size = C(ary.length, nelem), maxIndex = 1 << ary.length, sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'index'); addProperties(that, { valueOf: sizeOf, init: function() { this.index = first; }, next: function() { if (this.index >= maxIndex) return; var i = 0, n = this.index, result = []; for (; n; n >>>= 1, i++) { if (n & 1) result[result.length] = this[i]; } this.index = nextIndex(this.index); return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* permutation */ var _permutation = function(ary) { var that = ary.slice(), size = factorial(that.length); that.index = 0; that.next = function() { if (this.index >= size) return; var copy = this.slice(), digits = factoradic(this.index, this.length), result = [], i = this.length - 1; for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]); this.index++; return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; }; return that; }; // which is really a permutation of combination var permutation = function(ary, nelem, fun) { if (!nelem) nelem = ary.length; if (nelem < 1) throw new RangeError; if (nelem > ary.length) throw new RangeError; var size = P(ary.length, nelem), sizeOf = function() { return size; }, that = Object.create(ary.slice(), { length: { get: sizeOf } }); hideProperty(that, 'cmb'); hideProperty(that, 'per'); addProperties(that, { valueOf: function() { return size; }, init: function() { this.cmb = combination(ary, nelem); this.per = _permutation(this.cmb.next()); }, next: function() { var result = this.per.next(); if (!result) { var cmb = this.cmb.next(); if (!cmb) return; this.per = _permutation(cmb); return this.next(); } return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result; } }); addProperties(that, common); that.init(); return (typeof (fun) === 'function') ? that.map(fun) : that; }; /* export */ var Combinatorics = Object.create(null); addProperties(Combinatorics, { C: C, P: P, factorial: factorial, factoradic: factoradic, permutation: permutation, }); return Combinatorics; })(); function permute_Technicalbloke(inputArray) { if (inputArray.length === 1) return inputArray; return inputArray.reduce( function(accumulator,_,index){ permute_Technicalbloke([...inputArray.slice(0,index),...inputArray.slice(index+1)]) .map(value=>accumulator.push([inputArray[index],value])); return accumulator; },[]); } var suite = new Benchmark.Suite; var input = [0, 1, 2, 3, 4]; suite.add('permute_SiGanteng', function() { permute_SiGanteng(input); }) .add('permute_delimited', function() { permute_delimited(input); }) .add('permute_monkey', function() { permute_monkey(input); }) .add('permute_Oriol', function() { permute_Oriol(input); }) .add('permute_MarkusT', function() { permute_MarkusT(input); }) .add('permute_le_m', function() { permute_le_m(input); }) .add('permute_Urielzen', function() { permute_Urielzen(input); }) .add('permute_Taylor_Hakes', function() { permute_Taylor_Hakes(input); }) .add('permute_Combinatorics', function() { Combinatorics.permutation(input).toArray(); }) .add('permute_Technicalbloke', function() { permute_Technicalbloke(input); }) .on('cycle', function(event) { console.log(String(event.target)); }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run({async: true}); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.4/platform.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script> ``` Run-time results for Chrome 48: * 99.152ms **This algorithm** * 153.115ms [MarkusT](https://stackoverflow.com/a/11629015/1647737) * 401.255ms [js-combinatorics](https://stackoverflow.com/a/30013816/1647737) * 497.037ms [Urielzen](https://stackoverflow.com/a/24622772/1647737) * 925.669ms [Oriol](https://stackoverflow.com/a/11509565/1647737) * 1026.571ms [SiGanteng](https://stackoverflow.com/a/9960925/1647737) * 2529.841ms [delimited](https://stackoverflow.com/a/20871714/1647737) * 3992.622ms [monkey](https://stackoverflow.com/a/22063440/1647737) * 4514.665ms [Oriol](https://stackoverflow.com/a/32551801/1647737)
Here's one I made... ``` const permute = (ar) => ar.length === 1 ? ar : ar.reduce( (ac,_,i) => {permute([...ar.slice(0,i),...ar.slice(i+1)]).map(v=>ac.push([].concat(ar[i],v))); return ac;},[]); ``` And here it is again but written less tersely!... ``` function permute(inputArray) { if (inputArray.length === 1) return inputArray; return inputArray.reduce( function(accumulator,_,index){ permute([...inputArray.slice(0,index),...inputArray.slice(index+1)]) .map(value=>accumulator.push([].concat(inputArray[index],value))); return accumulator; },[]); } ``` How it works: If the array is longer than one element it steps through each element and concatenates it with a recursive call to itself with the remaining elements as it's argument. It doesn't mutate the original array.
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
Here's one I made... ``` const permute = (ar) => ar.length === 1 ? ar : ar.reduce( (ac,_,i) => {permute([...ar.slice(0,i),...ar.slice(i+1)]).map(v=>ac.push([].concat(ar[i],v))); return ac;},[]); ``` And here it is again but written less tersely!... ``` function permute(inputArray) { if (inputArray.length === 1) return inputArray; return inputArray.reduce( function(accumulator,_,index){ permute([...inputArray.slice(0,index),...inputArray.slice(index+1)]) .map(value=>accumulator.push([].concat(inputArray[index],value))); return accumulator; },[]); } ``` How it works: If the array is longer than one element it steps through each element and concatenates it with a recursive call to itself with the remaining elements as it's argument. It doesn't mutate the original array.
I think you'll may like this one: ``` const permute1 = (arr: any[]): any[][] => arr.reduce( (acc, curr) => acc.length > 0 ? acc .map((p) => Array.from({ length: p.length + 1 }, (_, i) => p.slice(0, i).concat(curr, p.slice(i)) ) ) .flat() : [[curr]], [] ); ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
``` var inputArray = [1, 2, 3]; var result = inputArray.reduce(function permute(res, item, key, arr) { return res.concat(arr.length > 1 && arr.slice(0, key) .concat(arr.slice(key + 1)) .reduce(permute, []) .map(function (perm) { return [item].concat(perm); }) || item); }, []); alert(JSON.stringify(result)); ```
here is a visualization for the recursive function => <https://recursion.vercel.app/> ``` var permute = function (nums) { let answer = []; var permuter = function (arr, permutation = []) { if (arr.length === 0) { return answer.push(permutation); } else { for (let i = 0; i < arr.length; i++) { let currentArr = arr.slice(); let next = currentArr.splice(i, 1); permuter(currentArr, permutation.concat(next)); ///we use concat because splice returns an array. } } }; permuter(nums); return answer; }; ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
``` function perm(xs) { return xs.length === 0 ? [[]] : perm(xs.slice(1)).reduce(function (acc, ys) { for (var i = 0; i < xs.length; i++) { acc.push([].concat(ys.slice(0, i), xs[0], ys.slice(i))); } return acc; }, []); } ``` Test it with: ``` console.log(JSON.stringify(perm([1, 2, 3,4]))); ```
here is a visualization for the recursive function => <https://recursion.vercel.app/> ``` var permute = function (nums) { let answer = []; var permuter = function (arr, permutation = []) { if (arr.length === 0) { return answer.push(permutation); } else { for (let i = 0; i < arr.length; i++) { let currentArr = arr.slice(); let next = currentArr.splice(i, 1); permuter(currentArr, permutation.concat(next)); ///we use concat because splice returns an array. } } }; permuter(nums); return answer; }; ```
11,794,136
I'm facing the problem when i am creating database in SQL server management studio 2008. it is showing error that xpstar90.dll DLL find could not load (response 126).
2012/08/03
[ "https://Stackoverflow.com/questions/11794136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556859/" ]
The error `undefined local variable or method 'params'` clearly indicates that `params` are not available in your model. Also, it's not a good idea to use params in your models. See this question [Rails How to pass params from controller to after\_save inside model](https://stackoverflow.com/questions/4725185/rails-how-to-pass-params-from-controller-to-after-save-inside-model). Further, even if you got `params` in your model, `params[:wallet]` will not be available because that wasn't submitted from the web form. ``` # No 'wallet' key here. Parameters: {"utf8"=>"✓", "authenticity_token"=>"7rgoJQwWFFbo4Wv6gHF2AzwQpCQwB+Pp/kaNRw/YW/k=", "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"} ``` **UPDATE** Creating wallet without `params` ``` has_one :wallet, :dependent => :destroy after_create do |user| user.create_wallet end ```
Undefined local variable or method `params' for your user model
3,277,745
I have a layout that looks like this: ``` .-------------------.u |#content |u '-------------------'u .-------------------.u |#menu |u '-------------------'u .-------------------.u |#morecontent vu | vu | vu '-------------------'u ``` `u`'s represent the body scrollbar and `v`'s the one created from `#morecontent`'s `overflow: auto` property. I have `#menu` contain dynamic data so sometimes it takes more than one line but right now `#morecontent` is sized to fit only one. How can I make the height of `#morecontent` adjust itself so it doesn't cause the `u` scrollbar to be scrollable or "enabled". I guess when I have more than one line? I know I should be using `%`'s and I tried using `max-height` but it didn't really work the way I wanted...
2010/07/19
[ "https://Stackoverflow.com/questions/3277745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Make sure that your div uses only max-height and min-height. Do not use height. If you want its height to go forever, don't set anything.
Use `position: fixed` to make the layout more concrete and Javascript to resize the #morecontent div. There is no way to make it resize when the other div does with XHTML/CSS.
3,277,745
I have a layout that looks like this: ``` .-------------------.u |#content |u '-------------------'u .-------------------.u |#menu |u '-------------------'u .-------------------.u |#morecontent vu | vu | vu '-------------------'u ``` `u`'s represent the body scrollbar and `v`'s the one created from `#morecontent`'s `overflow: auto` property. I have `#menu` contain dynamic data so sometimes it takes more than one line but right now `#morecontent` is sized to fit only one. How can I make the height of `#morecontent` adjust itself so it doesn't cause the `u` scrollbar to be scrollable or "enabled". I guess when I have more than one line? I know I should be using `%`'s and I tried using `max-height` but it didn't really work the way I wanted...
2010/07/19
[ "https://Stackoverflow.com/questions/3277745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Take a look at this: <http://jsfiddle.net/9QNUG/> note: you did not say if the content above was dynamic, but i am assuming not from your description, you will need to play with the heights in the example to get them to match yours.
Use `position: fixed` to make the layout more concrete and Javascript to resize the #morecontent div. There is no way to make it resize when the other div does with XHTML/CSS.
40,181,608
I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work. My PHP page: ``` <?php $servername = "10.10.10.10"; $username = "username"; $password = "password"; $dbname = "GENERIC_TABLES"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<br> WO Number ". $row["WO_NUM"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?> ``` So, WO\_NUM column has numbers like 1, 2, 3 etc. I want to get the last one + 1 So if I do like: ``` $sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1"; ``` Then it works fine, but if I want to make it WO\_NUM + 1 then it returns nothing. Why it happens like that and is there any way to get what I want using MySQL? I don't want to get WO\_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
2016/10/21
[ "https://Stackoverflow.com/questions/40181608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6743748/" ]
As you realized, `WO_NUM+1` changes the column name in the resulting array, so use an alias `WO_NUM+1 as NEW_NUM`. However I would not bother with the sorting and limit. Consider `MAX()`: ``` SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS ```
As it has been pointed by AbraCadaver, I missed that if I am using WO\_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.
11,340,696
How can I remove multiple "[" in HTML Tag ID attribute with Regex? For example ``` <div id="test[12][45][67]">test inline [for example]</div> ``` Change to ``` <div id="test12]45]67]">test inline [for example]</div> ```
2012/07/05
[ "https://Stackoverflow.com/questions/11340696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409400/" ]
What you could (most likely should) do is to use a PHP HTML parser, such as [PHP Simple DOM Parser](http://simplehtmldom.sourceforge.net/) to go over the HTML, extract the ID value and then replace it using something like so: ``` <?php $string = <yourID> $pattern = '/\[/g'; $replacement = ''; echo preg_replace($pattern, $replacement, $string); ?> ``` This would allow you to *safely* modify only your `id` section in a relatively simple manner.
using javascript: ``` function rem_open_square_brackets(_id) { if(_id) { return _id.replace(/[\[]*/g, ''); } return _id; } var _id = rem_open_square_brackets('test[12][45][67]'); document.write(_id); ``` you could find all your ids and past them to the function and replace them with the return value.
15,865,797
I want to add elements to my array through a user input. I know this can be done very easy using a list but i have to use an array. The problem with the code is that the array.lenght will always be 1. I want the array to have the same size as the total amount of elements in it, so size of the array shouldnt be set when declaring the array. I thought that if you add an element to an array it will copy the previous values + the added value and create a new array. UPDATED WITH ANSWER ``` public static void Add(int x){ if (Item == null) // First time need to initialize your variable { Item = new int[1]; } else { Array.Resize<int>(ref Item, Item.Length + 1); } Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1 } ```
2013/04/07
[ "https://Stackoverflow.com/questions/15865797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197276/" ]
Use `List<int>` instead of an explicit array, which will dynamically size for you, and use the Add() method to add elements at the end.
Lists grow as you add elements to it. Arrays have a constant size. If you must use arrays, the easiest way to do it, is to create an array that is big enough to hold the entered elements. ``` private int[] _items = new int[100]; private int _count; public void Add(int x) { _items[_count++] = x; } ``` You also need to keep track of the number of elements already inserted (I used the field `_count` here); --- As an example, you can then enumerate all the items like this: ``` for (int i = 0; i < _count; i++) { Console.WriteLine(_items[i]); } ``` --- You can make the items accessible publicly like this: ``` public int[] Items { get { return _items; } } public int Count { get { return _count; } } ``` --- **UPDATE** If you want to grow the array size automatically, this is best done by doubling the actual size, when the array becomes too small. It's a good compromise between speed and memory efficiency (this is how lists work internally). ``` private int[] _items = new int[8]; private int _count; public void Add(int x) { if (_count == _items.Lengh) { Array.Resize(ref _items, 2 * _items.Length); } _items[_count++] = x; } ``` However, keep in mind that this changes the array reference. So no permanent copy of this array reference should be stored anywhere else.
15,865,797
I want to add elements to my array through a user input. I know this can be done very easy using a list but i have to use an array. The problem with the code is that the array.lenght will always be 1. I want the array to have the same size as the total amount of elements in it, so size of the array shouldnt be set when declaring the array. I thought that if you add an element to an array it will copy the previous values + the added value and create a new array. UPDATED WITH ANSWER ``` public static void Add(int x){ if (Item == null) // First time need to initialize your variable { Item = new int[1]; } else { Array.Resize<int>(ref Item, Item.Length + 1); } Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1 } ```
2013/04/07
[ "https://Stackoverflow.com/questions/15865797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197276/" ]
I didn't test in VS. Here you go: ``` namespace ConsoleApplication1 { class Program { static int[] Item; //Fixed int Item[] to int[] Item static void Main(string[] args) { Add(3); Add(4); Add(6); } public static void Add(int x){ if (Item == null) // First time need to initialize your variable { Item = new int[1]; } else { Array.Resize<int>(ref Item, Item.Length + 1); } Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1 } } } ``` This should resize your array by one each time and then set the last item to what you are trying to add. Note that this is VERY inefficient.
Lists grow as you add elements to it. Arrays have a constant size. If you must use arrays, the easiest way to do it, is to create an array that is big enough to hold the entered elements. ``` private int[] _items = new int[100]; private int _count; public void Add(int x) { _items[_count++] = x; } ``` You also need to keep track of the number of elements already inserted (I used the field `_count` here); --- As an example, you can then enumerate all the items like this: ``` for (int i = 0; i < _count; i++) { Console.WriteLine(_items[i]); } ``` --- You can make the items accessible publicly like this: ``` public int[] Items { get { return _items; } } public int Count { get { return _count; } } ``` --- **UPDATE** If you want to grow the array size automatically, this is best done by doubling the actual size, when the array becomes too small. It's a good compromise between speed and memory efficiency (this is how lists work internally). ``` private int[] _items = new int[8]; private int _count; public void Add(int x) { if (_count == _items.Lengh) { Array.Resize(ref _items, 2 * _items.Length); } _items[_count++] = x; } ``` However, keep in mind that this changes the array reference. So no permanent copy of this array reference should be stored anywhere else.
58,178,675
My goal is to make a small program/macro in VBA Excel that fixes column names automatically. The way I would like to do this is having `Subs` for each individual column name `cell`. Each of these `Subs` has an `Array` of Strings, which contain the keywords that will be searched. If the cells value is exactly one of the Strings, the value will be fixed. How they will be fixed, however, depends on the column name and that is why each of these subs will need to be created separately. Now, I've created the `Sub` which calls all the individual `cell` fixing `Subs`. I've also made the `Function` that tests if the corresponding `cell` contains one of the keywords. However, I can't figure out how to properly pass information about the `Array` of searchable Strings and the corresponding `cell` to the `Sub`. I'm getting a "Run-time error '13': Type mismatch" when I try to call the FindMatch() Function. ``` Function FindMatch(textArr() As String, cell As Range) As Boolean FindMatch = False Dim testCell As Range Dim i As Integer ' Range.Find() each string in the Array. If one of the Strings is found, FindMatch is true For i = 0 To UBound(textArr) Set testCell = cell.Find(What:=textArr(i), LookIn:=xlValues, LookAt:=xlWhole) If Not testCell Is Nothing Then FindMatch = True End If Next i End Function ``` It is called from here: ``` Sub FindCr(cell As Range) Dim match As Boolean match = False Dim textArr() As String ' I get the type mismatch error here. textArr = Array("Cr", "Bag ", " Dog") match = FindMatch(textArr, cell) If match Then ' Do stuff depending on the column, for example: HighlightRange cell End If End Sub ``` And here is the main Sub that calls the individual find-and-fix Subs. It is also called from a big main loop that goes through the whole range of column name cells. ``` Public Sub fixColumnNames(cell As Range) 'Do find-and-fix functions for all possible column names FindCr cell End Sub ``` Note, I didn't want to use a ParamArray because I also need to pass the `cell` in the FindMatch() Function. I believe ParamArray is used only for when there is an undefined amount of arguments in the call. I don't want the `cell` to go in the ParamArray. I tried changing the declarations of FindMatch and Dim textArr() to `As Variant`, but it really messes up the Range.Find() function. It started matching all kinds of wrong keywords when it was given a `Variant`. Like this: ``` Function FindMatch(textArr() As Variant, cell As Range) As Boolean ``` And ``` Dim textArr() As Variant textArr = Array("Cr", "Bag ", " Dog") match = FindMatch(textArr, cell) ``` So if you have an alternative approach for passing list of Strings to a Function with other additional arguments, please teach me. Or if you know what is causing the problems, help would be appreciated.
2019/10/01
[ "https://Stackoverflow.com/questions/58178675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12130762/" ]
I'm not exactly sure why you are having issues, but this is working just fine for me. Since you were having issues with `ParamArray`, I went ahead and incorporated that into the code for demonstration purposes. ``` Sub FindCr(cell As Range) If FindMatch(cell, "Cr", "Bag ", " Dog") Then MsgBox "There was a match!" End If End Sub Function FindMatch(ByVal cell As Range, ParamArray textArr() As Variant) As Boolean Dim i As Long For i = 0 To UBound(textArr) If Not cell.Find(What:=textArr(i), LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then FindMatch = True Exit Function End If Next End Function ``` I have shortened it a bit for you for readability. You never demonstrated what you were passing for your `Cell` argument, but make sure that you are fully qualifying the range. ``` Dim Cell As Range Set Cell = Thisworkbook.Worksheets(1).Range("A1") ``` would be an example of a fully qualified range.
You cannot affect an array of string in this way : ``` textArr = Array("Cr", "Bag ", " Dog") ``` To use that form of affectation, textArr must be a variant. If you still want to use string, use redim and single affectation. For example : ``` dim textArr() as String ... Redim Preserve textArr(1) textArr(0) = "Cr" ... Redim Preserve textArr(2) textArr(1) = "Bag" ``` And so on, or you can do it in a loop or if you know the length of the final array, just Dim it with correct length
64,531,838
I have this string where I need to extract only one word to put into a new columns. ``` HELLO WORLD TEST SHOES1 PROJECT ``` The required string is SHOES, but it has '1' beside it. How can I extract the SHOES only? Thank you
2020/10/26
[ "https://Stackoverflow.com/questions/64531838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14122835/" ]
``` $("#franchise").change(function() { //alert( $( "#franchise" ).val() ); var f = $( "#franchise" ).val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: 'POST', url : 'ajax/series', data : ({franchise : f}), dataType: 'JSON', success: function(response) { $("#series").html(''); $("#series").append(response); } }); }); ```
just move your below code in document ready function ``` $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); ``` add `{{ csrf_field() }}` in your common layout file make sure your js code is in the same file not external js then use below js code ``` $("#franchise").change(function() { //alert( $( "#franchise" ).val() ); var f = $( "#franchise" ).val(); $.ajax({ type: 'POST', url : "{{ route('ajax.series') }}", data : ({franchise : f}), dataType: 'JSON', success: function(response) { $("#series").html(''); $("#series").append(response); } }); }); ```
64,531,838
I have this string where I need to extract only one word to put into a new columns. ``` HELLO WORLD TEST SHOES1 PROJECT ``` The required string is SHOES, but it has '1' beside it. How can I extract the SHOES only? Thank you
2020/10/26
[ "https://Stackoverflow.com/questions/64531838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14122835/" ]
``` $("#franchise").change(function() { //alert( $( "#franchise" ).val() ); var f = $( "#franchise" ).val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: 'POST', url : 'ajax/series', data : ({franchise : f}), dataType: 'JSON', success: function(response) { $("#series").html(''); $("#series").append(response); } }); }); ```
Your controller and route code are perfectly fine but your javaScript code has a little problem here, in laravel there is no need to add an ajax header field for CSRF token you can add CSRF token as the body of ajax like you have added franchise and the code will work absolutely fine. I have written the code for you to give it a try. ``` $('#franchise').change(function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "{{ route('ajax.series') }}", data: { franchise: $(this).val(), _token: $('meta[name="csrf-token"]').attr('content'), }, success: function(response) { $("#series").html('').append(response); } }); }); ```
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
Why have an exchange rate? Just deal in the local currency on whichever end of the trip I am at, and carry my wealth in the form of goods that will sell well at my next stop. Freight carriers don't like to run with empty holds, it is a waste of resources to sit still longer than necessary to unload and reload, and an even bigger waste to move while empty. I leave A with a hold full of cargo bound for B. When I get there I sell my cargo for B coin. I then turn around and buy new cargo using said B coin for my trip back to A. On the A side I do the same thing but with A dollars. If I am doing this regularly, I keep accounts on both ends of the trip in that planets currency. When I am ready to retire, or otherwise have a need to consolidate my wealth, I deliberately skew the relative value of my cargos so that A>B just covers the costs, while B>A lets me extract my savings and bring my profits home. Money is just a convenient means of representing the time and energy that goes into producing something. It only has value as long as all parties agree on what a unit represents. People on A will never see value in B coins, and B will never value A dollars, because they have a different reference base. The only ones who will see value in both are the people who move between places, and they will naturally define their own formula for relative worth base on what they can do with each currency in it's own place.
During the barter phase, when you were trading a ship full of grain for some crates of microprocessors, you established the relative values of the commodities. Now that you have this information you can start trading with tokens, like the federal reserve notes. The parties will have to establish a clearing house for transactions, the parities between the tokens will have to be agreed upon, either by state decrees or by letting the tokens' value float in the markets or by having a common currency. Until you a have an agreed-upon clearing house you will still need to resort to barter.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
Comparing commodities. Money, after all, is just an abstract representation of goods and services. The only reason any form of fiat currency has power is its ability to be swapped for either a good or a service. A way to get an idea at what the exchange rate would be is to just compare a common and frequently used commodity between the two and use it to set a benchmark. The trick is finding the commodity. Any metal that's used in equal measure would be useful, but suppose one planet is iron-rich and the other is iron-poor? Or perhaps one culture values gold whereas the other values silver? If both planets have the same amount of metals and use similar ways to process it, that would be the best, but that's not always the case. Services would actually be another good place to start. Figure out the 'living wage', as in how much money would be the bare minimum for living expenses i.e. food, clothing, shelter at a minimal level. Or plot a graph with the respective salaries for necessary jobs - like doctor, farmer, lawyer, etc. (Cue lawyer joke.) Take all that information together and you should get a pretty good idea of what the exchange rate should look like.
**I think the short answer is: you're missing a step.** **The next step in that picture *isn't* a currency exchange. If you've got a trader who's currently taking barter in exchange for their goods, the next step is to *take the local currency instead.*** Instead of taking on 500 kilos of sodium chloride in payment, you get 500 cilrish - which you know you can use to purchase X, Y, and Z at the local alien freemarket. There isn't an exchange rate - you're not directly exchanging dollars for cilrish. In fact, the trader in that situation doesn't even really care about an exchange rate. Instead, they care about the goods X, Y, and Z versus the amount of dollars they spent on the venture. The trader may even keep spare cilrish - but mostly from the standpoint that it'll let them buy goods on the alien planet. So for small-time trading, there isn't an exchange rate. But what happens when trading gets more prevalent - or, more directly, entities start springing up that do *one directional trading* - they focus on importing A and B from the alien planet and selling them on earth. In that case, the business needs to find a way to convert dollars into cilrish. But there are likely business entities on the alien planet with the same problem. They're importing Miniature Corgis (a delicacy on their planet) and receiving payment in cilrish... which those businesses have to convert to dollars in order to purchase more inventory. At that point, there's still not really an 'exchange rate', so much as a "Here's a rate we happen to agree to a transaction to at this point in time." It's just two companies agreeing to swap X dollars for Y cilrish. Now, once there's a *market demand* for exchanges, that's when an actual exchange rate pops up. Because there's enough trading of cilrish to/from dollars that an actual proper rate can be established.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
Comparing commodities. Money, after all, is just an abstract representation of goods and services. The only reason any form of fiat currency has power is its ability to be swapped for either a good or a service. A way to get an idea at what the exchange rate would be is to just compare a common and frequently used commodity between the two and use it to set a benchmark. The trick is finding the commodity. Any metal that's used in equal measure would be useful, but suppose one planet is iron-rich and the other is iron-poor? Or perhaps one culture values gold whereas the other values silver? If both planets have the same amount of metals and use similar ways to process it, that would be the best, but that's not always the case. Services would actually be another good place to start. Figure out the 'living wage', as in how much money would be the bare minimum for living expenses i.e. food, clothing, shelter at a minimal level. Or plot a graph with the respective salaries for necessary jobs - like doctor, farmer, lawyer, etc. (Cue lawyer joke.) Take all that information together and you should get a pretty good idea of what the exchange rate should look like.
OK, let's think about it: * we have roughly market economies on both sides * we have not united planets with already non uniform jurisdiction => they must already have some rules governing [conflict of laws](https://en.wikipedia.org/wiki/Conflict_of_laws) or [law of the sea](https://en.wikipedia.org/wiki/Law_of_the_sea) * we have modern states, which detest any power vacuum and just in case would impose (or even usurp) their authority on everything closing by. (not mentioning that modern states would quite quickly at least start to establish some kind of relationship and working on treaties) So for practical purposes a space alien is a foreigner like any other, who while in your space is subject to local laws, but for many purposes concerning example technical certification of his ship is considered to be subject to his local laws, unless they are considered as outrageous. (In this case he is politely asked to comply with local laws or refused docking rights). I don't think that any high tech tech civilisation would barter much. It would be too cumbersome. Rather an alien would check what he can buy, whether there are any nasty restrictions, and if everything is fine would accept local currency with tendency to err on side of caution. Moreover, someone presumably would even demand from him some cash payment for tariffs or docking fees. If he didn't trust it, then he would just try to spend it all before leaving those barbarians. **Exchange rate would be determined by the market and it would happen very fast. However, at first it would jump a lot, before stabilising. In a while all major currencies of the other world would be honoured.**
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
You just pass laws on each world allowing the purchase and sale of the other world’s currency, with some sensible regulation to make sure people can’t get ripped off. Then the markets will establish the exchange rate and arrange the physical transport of any currency that actually needs to be moved, just like between two countries on Earth at present.
I was thinking, if they are different life beings and have different life standards and materials use, what they have in common? Because one of the civilizations could valerate gold, whereas the others simply don't care. But what they have in common? Both have difficulties and cost to travel between their two planets. The exchange rate could be a trip from one planet to the other. **They can calculate the equivalent in 1kg per trip.** I assume that the cost of travel is more or less the same in each civilization while being a little cheaper for the most advanced one. But they are more advanced, is logical they have a more valuable exchange. For example: A car cost 50,000€, and the European Union can put 1 kg in orbit for 9047€ (according to Wikipedia, Ariane 6 cargo capacity and approx launch cost are 10500 kg and € 95 million). The car cost (50000/9047 = 5.52) 5.52kg per trip. Meanwhile, in Russia, they are selling a laptop, about 40000 Russian Rubles. The Soyuz have a charge capacity of 7200kg and a cost of 3200 million Rubles. 1 kg per trip cost 444444 Rubles. The laptop cost 0.09 kg per trip. Those calculations are approximate and the capacity and the cost of the launches and capacity of the rockets are also approximate, the source is Wikipedia. If we convert the currency (the laptop cost approximately 600€, 40000 Rubles), the car is 83 times more valuable than the laptop. So, 0.09 kg per trip 83 times more, are 7,5 kg per trip. The Europeans have they car for 5,2 kg per trip. **The exchange rate is 1.44 Russian kg per trip for 1 European kg per trip.** I think it's a good ratio.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
As bitcoin history shows, currency exchanges will emerge very quickly as soon as the currency is considered to have some nonzero value, despite exchange rate fluctuations. The rates on all these exchanges tend to quickly converge, and are used as a basis even for other people who trade directly. Even after failures of large exchanges like MtGox, the trade went on. Unlike Bitcoin, you have equivalent goods on both planets (gold, drinking water, rocket fuel, ...), so trader can use them to calculate the estimated value of foreign currency. When the interplanetary trade gets non-negligible and it gets regulated, these exchanges gradually enter the regulated regime and precautions to stabilize the exchange rate are made. I assume here both governemnts view the interplanetary trade as something good or neutral, not try to stop it.
I was thinking, if they are different life beings and have different life standards and materials use, what they have in common? Because one of the civilizations could valerate gold, whereas the others simply don't care. But what they have in common? Both have difficulties and cost to travel between their two planets. The exchange rate could be a trip from one planet to the other. **They can calculate the equivalent in 1kg per trip.** I assume that the cost of travel is more or less the same in each civilization while being a little cheaper for the most advanced one. But they are more advanced, is logical they have a more valuable exchange. For example: A car cost 50,000€, and the European Union can put 1 kg in orbit for 9047€ (according to Wikipedia, Ariane 6 cargo capacity and approx launch cost are 10500 kg and € 95 million). The car cost (50000/9047 = 5.52) 5.52kg per trip. Meanwhile, in Russia, they are selling a laptop, about 40000 Russian Rubles. The Soyuz have a charge capacity of 7200kg and a cost of 3200 million Rubles. 1 kg per trip cost 444444 Rubles. The laptop cost 0.09 kg per trip. Those calculations are approximate and the capacity and the cost of the launches and capacity of the rockets are also approximate, the source is Wikipedia. If we convert the currency (the laptop cost approximately 600€, 40000 Rubles), the car is 83 times more valuable than the laptop. So, 0.09 kg per trip 83 times more, are 7,5 kg per trip. The Europeans have they car for 5,2 kg per trip. **The exchange rate is 1.44 Russian kg per trip for 1 European kg per trip.** I think it's a good ratio.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
I was thinking, if they are different life beings and have different life standards and materials use, what they have in common? Because one of the civilizations could valerate gold, whereas the others simply don't care. But what they have in common? Both have difficulties and cost to travel between their two planets. The exchange rate could be a trip from one planet to the other. **They can calculate the equivalent in 1kg per trip.** I assume that the cost of travel is more or less the same in each civilization while being a little cheaper for the most advanced one. But they are more advanced, is logical they have a more valuable exchange. For example: A car cost 50,000€, and the European Union can put 1 kg in orbit for 9047€ (according to Wikipedia, Ariane 6 cargo capacity and approx launch cost are 10500 kg and € 95 million). The car cost (50000/9047 = 5.52) 5.52kg per trip. Meanwhile, in Russia, they are selling a laptop, about 40000 Russian Rubles. The Soyuz have a charge capacity of 7200kg and a cost of 3200 million Rubles. 1 kg per trip cost 444444 Rubles. The laptop cost 0.09 kg per trip. Those calculations are approximate and the capacity and the cost of the launches and capacity of the rockets are also approximate, the source is Wikipedia. If we convert the currency (the laptop cost approximately 600€, 40000 Rubles), the car is 83 times more valuable than the laptop. So, 0.09 kg per trip 83 times more, are 7,5 kg per trip. The Europeans have they car for 5,2 kg per trip. **The exchange rate is 1.44 Russian kg per trip for 1 European kg per trip.** I think it's a good ratio.
During the barter phase, when you were trading a ship full of grain for some crates of microprocessors, you established the relative values of the commodities. Now that you have this information you can start trading with tokens, like the federal reserve notes. The parties will have to establish a clearing house for transactions, the parities between the tokens will have to be agreed upon, either by state decrees or by letting the tokens' value float in the markets or by having a common currency. Until you a have an agreed-upon clearing house you will still need to resort to barter.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
Why have an exchange rate? Just deal in the local currency on whichever end of the trip I am at, and carry my wealth in the form of goods that will sell well at my next stop. Freight carriers don't like to run with empty holds, it is a waste of resources to sit still longer than necessary to unload and reload, and an even bigger waste to move while empty. I leave A with a hold full of cargo bound for B. When I get there I sell my cargo for B coin. I then turn around and buy new cargo using said B coin for my trip back to A. On the A side I do the same thing but with A dollars. If I am doing this regularly, I keep accounts on both ends of the trip in that planets currency. When I am ready to retire, or otherwise have a need to consolidate my wealth, I deliberately skew the relative value of my cargos so that A>B just covers the costs, while B>A lets me extract my savings and bring my profits home. Money is just a convenient means of representing the time and energy that goes into producing something. It only has value as long as all parties agree on what a unit represents. People on A will never see value in B coins, and B will never value A dollars, because they have a different reference base. The only ones who will see value in both are the people who move between places, and they will naturally define their own formula for relative worth base on what they can do with each currency in it's own place.
Comparing commodities. Money, after all, is just an abstract representation of goods and services. The only reason any form of fiat currency has power is its ability to be swapped for either a good or a service. A way to get an idea at what the exchange rate would be is to just compare a common and frequently used commodity between the two and use it to set a benchmark. The trick is finding the commodity. Any metal that's used in equal measure would be useful, but suppose one planet is iron-rich and the other is iron-poor? Or perhaps one culture values gold whereas the other values silver? If both planets have the same amount of metals and use similar ways to process it, that would be the best, but that's not always the case. Services would actually be another good place to start. Figure out the 'living wage', as in how much money would be the bare minimum for living expenses i.e. food, clothing, shelter at a minimal level. Or plot a graph with the respective salaries for necessary jobs - like doctor, farmer, lawyer, etc. (Cue lawyer joke.) Take all that information together and you should get a pretty good idea of what the exchange rate should look like.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
As bitcoin history shows, currency exchanges will emerge very quickly as soon as the currency is considered to have some nonzero value, despite exchange rate fluctuations. The rates on all these exchanges tend to quickly converge, and are used as a basis even for other people who trade directly. Even after failures of large exchanges like MtGox, the trade went on. Unlike Bitcoin, you have equivalent goods on both planets (gold, drinking water, rocket fuel, ...), so trader can use them to calculate the estimated value of foreign currency. When the interplanetary trade gets non-negligible and it gets regulated, these exchanges gradually enter the regulated regime and precautions to stabilize the exchange rate are made. I assume here both governemnts view the interplanetary trade as something good or neutral, not try to stop it.
During the barter phase, when you were trading a ship full of grain for some crates of microprocessors, you established the relative values of the commodities. Now that you have this information you can start trading with tokens, like the federal reserve notes. The parties will have to establish a clearing house for transactions, the parities between the tokens will have to be agreed upon, either by state decrees or by letting the tokens' value float in the markets or by having a common currency. Until you a have an agreed-upon clearing house you will still need to resort to barter.
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
You just pass laws on each world allowing the purchase and sale of the other world’s currency, with some sensible regulation to make sure people can’t get ripped off. Then the markets will establish the exchange rate and arrange the physical transport of any currency that actually needs to be moved, just like between two countries on Earth at present.
During the barter phase, when you were trading a ship full of grain for some crates of microprocessors, you established the relative values of the commodities. Now that you have this information you can start trading with tokens, like the federal reserve notes. The parties will have to establish a clearing house for transactions, the parities between the tokens will have to be agreed upon, either by state decrees or by letting the tokens' value float in the markets or by having a common currency. Until you a have an agreed-upon clearing house you will still need to resort to barter.