qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
56,217,829
Ionic Showing error on device console Error: advanced-http: invalid params object, needs to be an object with strings Error: advanced-http: invalid params object, needs to be an object with strings. ``` private http: HTTP verify(){ this.http.get('http://outreach.pk/api/sendsms.php/sendsms/url?id=rchiginsurance&pass=igi123456&mask=IGInsurance&lang=English&type=xml', { params: { to: this.mobile.value, msg: this.number1 } }, {}); } ```
2019/05/20
[ "https://Stackoverflow.com/questions/56217829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8825698/" ]
you need to set the headers for the request by using `set` as shown: ``` this.http.setHeader('*', String("Content-Type"), String("application/json")); this.http.setHeader('*', String("Accept"), String("application/json")); ``` and you need to set the serializer ``` this.http.setDataSerializer('json'); ```
Since your header is empty, just put "null" for headers object and set serializer. For example: ``` this.http.setDataSerializer("json"); this.http.post(url, body, null).then(res => {....}); ``` or ``` this.http.setDataSerializer("json"); this.http.post(url, body, {headers: {'Content-Type: application/json'}}).then(res => {....}); ``` im writing this on ionic capacitor 2.4 and ionic-native/http 5.29
1,061,016
still a bit of a n00b on SharpSVN, I'm looking to get some simple code to open up an SVN repository, and read (at least) the full path of all files in a specific folder. Lets say that this folder is \trunk\source I'm not looking to checkout or commit, just read into a list I'm also looking to read ALL files, not just the changed ones.
2009/06/29
[ "https://Stackoverflow.com/questions/1061016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129565/" ]
ok it looks like I found a method.. ``` bool gotList; List<string> files = new List<string>(); using (SvnClient client = new SvnClient()) { Collection<SvnListEventArgs> list; gotList = client.GetList(projectPath, out list); if (gotList) { foreach (SvnListEventArgs item in list) { files.Add(item.Path); } } } ```
Wrote this in a hurry in notepad; Sorry. ``` SvnClient client = new SvnClient(); client.Authentication.DefaultCredentials = new NetworkCredential("svnuser", "svnpass"); SvnUriTarget folderTarget = new SvnUriTarget("https://mysvnserver.com/mysvnpath"); List<String> filesFound = getFolderFiles(client, folderTarget); // GetFolderFiles // Function that, given a SvnClient and Target to a folder, returns a list of files private List<String> getFolderFiles(SvnClient client, SvnTarget folderTarget) { List<String> filesFound = new List<String>(); List<SvnListEventArgs> listResults; if (client.GetList(folderTarget, out listResults)) { foreach (SvnListEventArgs item in listResults) if (item.Entry.NodeKind == SvnNodeKind.File) filesFound.Add(item.Path); return filesFound; } else throw new Exception("Failed to retrieve files via SharpSvn"); } ```
60,084,727
There is a table in which the managers column and the status column. How to calculate the total status of Fully, the divided total of records with all statuses except N / A for each manager? I tried to portray in this way, but nothing came of it First Query ``` SELECT "Manager Name", count("Performance Score") as Perfomance FROM public.hr_dataset WHERE ("Performance Score" = 'Fully Meets') GROUP BY "Manager Name" ORDER BY Perfomance DESC; ``` Second Query ``` SELECT "Manager Name", count("Performance Score") FROM public.hr_dataset WHERE ("Performance Score" != 'N/A- too early to review') GROUP BY "Manager Name"; ``` Need to recieve two columns with name and values (1 query/2 query)
2020/02/05
[ "https://Stackoverflow.com/questions/60084727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989201/" ]
The JavaScript approach to detect closing still works. The syntax just has changed a little ``` UI.getCurrent().getPage().executeJs("function closeListener() { $0.$server.windowClosed(); } " + "window.addEventListener('beforeunload', closeListener); " + "window.addEventListener('unload', closeListener);",getElement()); @ClientCallable public void windowClosed() { System.out.println("Window closed"); } ``` Although this is not 100% bullet proof way, since I think not the all browsers work the same way. For example the above code triggers twice with Chrome, where listening just `beforeunload` is enough. This allows to simplify the JavaScript to ``` UI.getCurrent().getPage().executeJs( "window.addEventListener('beforeunload', () => $0.$server.windowClosed()); ",getElement()); ``` **BeforeLeaveObserver** works with navigation. So if you use **RouterLink** or call `ui.navigate("route")` then **BeforeLeaveEvent** is dispatched, but not when you call `page.setLocation()`. Browser can close due crash, or lost due other reasons, then `beforeunload` naturally does not happen. The last resort is the heart beat based detection mechanism. I.e. after three lost heart beats Vaadin server will conclude that Browser was lost. There is naturally a delay in this, which simply cannot be avoided.
Depending on which browsers you need to support, you might also want to take a look at the [Beacon API](https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API), which is supported by all modern browsers, but not IE11. The Beacon API has the benefit of being non-blocking. With the unload listener, the client waits for a response before closing the tab, which might be bad user experience. Still, as Tatu mentioned, if the browser crashes or the user loses internet connection, all you can do is wait for the session to time out.
8,327
I'm looking to make some custom gui elements. Has anyone had success using pyside to use Qt to communicate with Blender?
2014/04/04
[ "https://blender.stackexchange.com/questions/8327", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/2452/" ]
There is at least a video showing someone compiled PyQt into Blender: <http://vimeo.com/86398593> And a facebook post: <https://www.facebook.com/cgtutorials/posts/521688517904188?stream_ref=10> So it seems possible, at least with a modified Blender binary.
I have tried to get PySide working inside Blender, but i have had trouble getting PySide working correctly in python 3.4 standalone, so i gave up on PySide and moved to PyQt4. First of all, i have it working on mac OSX 10.8 with blender 2.71. but i would say the process below would be almost the same on linux, but for windows may be easier, as you can download QT4 and PyQT4 binaries i would suggest setting up a Virtual environment, as i previously had issues with different versions of python running on my machine, and it mucked up the install path, and version of python used to compile PyQt. <https://pypi.python.org/pypi/virtualenv> You need to make sure you install PyQT with the exact version of python that blender is using (2.71 uses 3.4, 2.70 uses 3.3) I used the following versions. * Python 3.4.1 * Qt 4.8.6 * pyQT 4.11.1 Once you have the correct python version, and virtualenv set up and working this is the code i use inside blender to open a PyQT window. ``` import sys sys.path.append('*venv directory* /py3.4/lib/python3.4/site-packages') import bpy from PyQt4 import QtGui, QtCore class ExampleQtWindow(QtGui.QDialog): def __init__(self): super(ExampleQtWindow, self).__init__() self.mainLayout = QtGui.QVBoxLayout(self) self.buttonLayout = QtGui.QHBoxLayout() self.CreateButton = QtGui.QPushButton("print info") QtCore.QObject.connect(self.CreateButton, QtCore.SIGNAL('clicked()'), self.testCommand) self.mainLayout.addWidget(self.CreateButton) self.setLayout(self.mainLayout) def testCommand(self): print(bpy.data.objects) # register class stuff class PyQtEvent(): _timer = None _window = None def execute(self): self._application = QtGui.QApplication.instance() if self._application is None: self._application = QtGui.QApplication(['']) self._eventLoop = QtCore.QEventLoop() self.window = ExampleQtWindow() self.window.show() print("running in background") new_window = PyQtEvent() new_window.execute() ```
5,828,971
i have made one site in which i have given functionality called 'connect with facebook'. it works fine for login.. but now i want to implement functionality when i click on logout, it should be logged out from facebook as well... can any one tell me from where i should start..?
2011/04/29
[ "https://Stackoverflow.com/questions/5828971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730607/" ]
Make sure that the **class-name** stated in the *Inhertis*-part of your page-directive **matches** the name of the class in your **code-behind file**. Master1.master: ``` <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="master1.master.cs" Inherits="FlexStock.Forms.master1" %> ``` Master1.Master.cs: ``` namespace FlexStock.Forms { public class master1 { /* ... */ ```
Have you built your project w/o any errors/warning? Error says that its unable to find code-behind class `FlexStock.Forms.master1` so issue will be likely in `master1.Master.cs` or `designer.cs` - where you may have changed the namespace or class name w/o making the same change in markup. Or there is some compilation error and VS is unable to generate the assembly (or unable to put it in bin folder)
5,828,971
i have made one site in which i have given functionality called 'connect with facebook'. it works fine for login.. but now i want to implement functionality when i click on logout, it should be logged out from facebook as well... can any one tell me from where i should start..?
2011/04/29
[ "https://Stackoverflow.com/questions/5828971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730607/" ]
Make sure that the **class-name** stated in the *Inhertis*-part of your page-directive **matches** the name of the class in your **code-behind file**. Master1.master: ``` <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="master1.master.cs" Inherits="FlexStock.Forms.master1" %> ``` Master1.Master.cs: ``` namespace FlexStock.Forms { public class master1 { /* ... */ ```
If you can see the bin folder in Explorer, but not in VS, try "Including" it in your project. Maybe drag the folder into Solution Explorer, and then right-click it and Include it.
38,839,796
Here's some test in my Chrome dev console: ``` > tags returns ["test_tag", "test_tag2"] > tags.forEach returns undefined > ["test_tag", "test_tag2"].forEach returns forEach() { [native code] } ``` I have no idea why my `tags` object is not responding to `forEach`. Checking the type is not very instructive, which is to be expected: ``` > typeof(tags) // returns 'object' > typeof(["test_tag", "test_tag2"]) // returns 'object' ``` How am I constructing this `tags` object? ``` var $nodes = $(".metadata") var tags = $nodes.map(function(idx, node){ nodeJson = $(node).text() return JSON.parse(nodeJson)['tags'] }) ```
2016/08/08
[ "https://Stackoverflow.com/questions/38839796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2981429/" ]
jQuery's `map()` function returns the collection of elements, or in this case the returned text wrapped in a jQuery object, which is of course an object, not an array. If you wanted the text in an array, you'd use `get()` as well ``` var $nodes = $(".metadata") var tags = $nodes.map(function(idx, node){ var nodeJson = $(node).text(); return JSON.parse(nodeJson)['tags']; }).get(); ``` or the more appropriate `$.map` ``` var $nodes = $(".metadata") var tags = $.map( $nodes, function(node){ var nodeJson = $(node).text(); return JSON.parse(nodeJson)['tags']; }); ```
Try it like this: ``` Array.prototype.forEach.call(tags, function(el){ console.log(el); }); ```
39,464,748
I have a Flask API, it connects to a Redis cluster for caching purposes. Should I be creating and tearing down a Redis connection on each flask api call? Or, should I try and maintain a connection across requests? My argument against the second option is that I should really try and keep the api as stateless as possible, and I also don't know if keeping some persistent across request might causes threads race conditions or other side effects. However, if I want to persist a connection, should it be saved on the session or on the application context?
2016/09/13
[ "https://Stackoverflow.com/questions/39464748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1658296/" ]
This is about performance and scale. To get those 2 buzzwords buzzing you'll in fact need persistent connections. Eventual race conditions will be no different than with a reconnect on every request so that shouldn't be a problem. Any RCs will depend on how you're using redis, but if it's just caching there's not much room for error. I understand the desired stateless-ness of an API from a client sides POV, but not so sure what you mean about the server side. I'd suggest you put them in the application context, not the sessions (those could become too numerous) whereas the app context gives you the optimal 1 connection per process (and created immediately at startup). Scaling this way becomes easy-peasy: you'll never have to worry about hitting the max connection counts on the redis box (and the less multiplexing the better).
It's good idea from the performance standpoint to keep connections to a database opened between requests. The reason for that is that opening and closing connections is not free and takes some time which may become problem when you have too many requests. Another issue that a database can only handle up to a certain number of connections and if you open more, database performance will degrade, so you need to control how many connections are opened at the same time. To solve both of these issues you may use a connection pool. A connection pool contains a number of opened database connections and provides access to them. When a database operation should be performed from a connection shoul be taken from a pool. When operation is completed a connection should be returned to the pool. If a connection is requested when all connections are taken a caller will have to wait until some connections are returned to the pool. Since no new connections are opened in this processed (they all opened in advance) this will ensure that a database will not be overloaded with too many parallel connections. If connection pool is used correctly a single connection will be used by only one thread will use it at any moment. Despite of the fact that connection pool has a state (it should track what connections are currently in use) your API will be stateless. This is because from the API perspective "stateless" means: does not have a state/side-effects visible to an API user. Your server can perform a number of operations that change its internal state like writing to log files or writing to a cache, but since this does not influence what data is being returned as a reply to API calls this does not make this API "stateful". You can see some examples of using Redis connection pool [here](http://www.programcreek.com/python/example/22730/redis.ConnectionPool). Regarding where it should be stored I would use application context since it fits better to its [purpose](http://flask.pocoo.org/docs/0.11/appcontext/#context-usage).
17,078,981
Normalization not in a general relational database sense, in this context. I have received reports from a User. The data in these reports was generated roughly at the same time, making the timestamp the same for all reports gathered in one request. I'm still pretty new to datastore, and I know you can query on properties, you have to grab the ancestors' entity's key to traverse down... so I'm wondering which one is better performance and "write/read/etc" wise. Should I do: Option 1: * **User** (Entity, ancestor of ReportBundle): general user information properties * **ReportBundle** (Entity, ancestor of Report): timestamp * **Report** (Entity): general data properties Option 2: * **User** (Entity, ancestor of Report): insert general user information properties * **Report** (Entity): timestamp property AND general data properties
2013/06/13
[ "https://Stackoverflow.com/questions/17078981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458482/" ]
``` SetZero::setZero((int **)a, 4, 5) ``` `a` is not an array of pointers, it is simply a 2 dimensional array. notice how the access violation is reading address 0x0000004B? that's 75, a number between 0 and 99 :) because you are treating a 2 dimensional array (which is just a one dimensional array with a neat way of accessing it) as an array of arrays, it is taking one of the values in your array (75) to be the address of a sub array, then trying to read the non existent array at address 75 (or 0x0000004B) I suggest that you 'flatten' your arrays and work with them as one dimensional arrays, which I find simpler: ``` void SetZero::setZero(int * a, int m, int n){ int i, j, k; int * b = new int [m*n]; //flags to identify whether set to zero or not. for(i = 0; i < m; i++){ b[i] = new int[n]; for(j = 0; j < n; j++) b[i*n+j] = 1; } for(i = 0; i < m; i++) for(j = 0; j < n; j++) if(a[i*n+j] == 0 && b[i*n+j]){//DUMP here. If I change it to (a+i)[j], then works. for (k = 0; k < n; k++){ a[i*n+k] = 0;//but there is NO dump here. Weird! b[i*n+k] = 0; } for(k = 0; k < m; k++){ a[k*n+j] = 0; b[k*n+j] = 0; } j = n;//break. next row loop. } delete[] b; } int main(){ int a[4*5]; srand(time(NULL)); for(int i = 0; i < 4; i++){//create an 2D array for(int j = 0; j < 5; j++){ a[i*5+j] = rand() % 100; cout << a[i*5+j] << " "; } cout << endl; } SetZero::setZero(a, 4, 5);//type cast. cout << endl; for(int i = 0; i < 4; i++){//print result for(int j = 0; j < 5; j++) cout << a[i*5+j] << " "; cout << endl; } return 0; } ```
One suggestion about the SetZero(). There is a function called [memset()](http://www.cplusplus.com/reference/cstring/memset/) which allows you to set all bytes to a specific value given a starting pointer and the range. This function could make your SetZero() function more cleaner: --- ``` void * memset ( void * ptr, int value, size_t num ); ``` Fill block of memory. Sets the first `num` bytes of the block of memory pointed by `ptr` to the specified `value` (interpreted as an unsigned char). ***Parameters*** * ptr: Pointer to the block of memory to fill. * value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value. * num: Number of bytes to be set to the value, size\_t is an unsigned integral type. --- For example, the following code block from your program: ``` for (k = 0; k < n; k++){ a[i][k] = 0;//but there is NO dump here. Weird! b[i][k] = 0; } ``` can be achieved by `memset` in a cleaner way: ``` memset(a[i], 0, n * sizeof(int)); memset(b[i], 0, n * sizeof(int)); ```
49,674,913
I run a statistical test in R (running in RStudio). I save the result using a variable name. I want to extract one part of the result. How do I do this? Here is an example with the R code at the end. I set up an experiment with four treatments, and gather data. I next run ANOVA and perform a Tukey HSD test. The result is stored in a variable called "posthoc." I look and note that posthoc is a list of 1. In RStudio I see a little blue arrow to the left of the name, and clicking on that gives more information. I am not sure how to interpret it in a way that I can use to answer my own question. I can print(posthoc) and I get the following. ``` # Tukey multiple comparisons of means # 95% family-wise confidence level # #Fit: aov(formula = Expt1$Treat1 ~ Expt1$Trt) # #$`Expt1$Trt` # diff lwr upr p adj #B-A 6.523841 2.664755 10.38292569 0.0001372 #C-A 18.584160 14.725075 22.44324507 0.0000000 #D-A 2.643719 -1.215367 6.50280370 0.2854076 #C-B 12.060319 8.201234 15.91940456 0.0000000 #D-B -3.880122 -7.739207 -0.02103681 0.0482260 #D-C -15.940441 -19.799527 -12.08135619 0.0000000 ``` I can also type class(posthoc) and I get this: [1] "TukeyHSD" "multicomp" In this case, what I need are all the p-values in a new variable. The general problem is that R gives me output and I need to be able to figure out how to extract specific elements of that output. I might be using aov, lm, nlme, or something else. ``` Mean1=3.2 Sd1=3.2 Mean2=9.4 Sd2=2.4 Mean3=21.4 Sd3=6.4 Mean4=3.9 Sd4=10.7 Size1=30 Treat1=rnorm(Size1,mean=Mean1, sd=Sd1) Trt="A" Treat1M <- data.frame(Treat1, Trt) Treat1=rnorm(Size1,mean=Mean2, sd=Sd2) Trt="B" Treat2M <- data.frame(Treat1, Trt) Treat1=rnorm(Size1,mean=Mean3, sd=Sd3) Trt="C" Treat3M <- data.frame(Treat1, Trt) Treat1=rnorm(Size1,mean=Mean4, sd=Sd4) Trt="D" Treat4M <- data.frame(Treat1, Trt) Expt1=rbind(Treat1M, Treat2M, Treat3M, Treat4M) Expt1R<-aov(Expt1$Treat1 ~ Expt1$Trt) posthoc <-TukeyHSD(x=Expt1R, 'Expt1$Trt', conf.level=.95) ```
2018/04/05
[ "https://Stackoverflow.com/questions/49674913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4547897/" ]
simply use subsetting of your `posthoc` variable. ``` posthoc$`Expt1$Trt`[,4] ``` or you can try the `broom` package. ``` library(broom) res <- tidy(posthoc) res term comparison estimate conf.low conf.high adj.p.value 1 Expt1$Trt B-A 5.904138 1.3639293 10.444346 5.223255e-03 2 Expt1$Trt C-A 16.886340 12.3461316 21.426548 3.919087e-14 3 Expt1$Trt D-A 4.283597 -0.2566111 8.823805 7.189220e-02 4 Expt1$Trt C-B 10.982202 6.4419940 15.522410 3.226398e-08 5 Expt1$Trt D-B -1.620540 -6.1607487 2.919668 7.886097e-01 6 Expt1$Trt D-C -12.602743 -17.1429509 -8.062534 3.235351e-10 ``` The output of the `tidy` function is a data.frame. Thus, you can access the p-values using `res$adj.p.value`. ``` class(res) [1] "data.frame" ```
Jimbou has already provided an excellent solution. I would also go for `broom` especially when doing plots with `ggplot2`. I would just like to expound on the comment by John Coleman. You can inspect the object by using `str`. In case of `posthoc`, ``` str(posthoc) ``` gives ``` List of 1 $ Expt1$Trt: num [1:6, 1:4] 6.46 18.19 -0.76 11.74 -7.22 ... ``` Typing ``` posthoc$`Expt1$Trt` ``` gives ``` diff lwr upr p adj B-A 6.4562 2.130 10.782 9.530e-04 C-A 18.1922 13.866 22.519 2.454e-14 D-A -0.7598 -5.086 3.566 9.680e-01 C-B 11.7360 7.410 16.062 7.427e-10 D-B -7.2160 -11.542 -2.890 1.725e-04 D-C -18.9521 -23.278 -14.626 1.588e-14 ``` So you can access the fourth column by typing ``` posthoc$`Expt1$Trt`[,4] ``` or ``` posthoc$`Expt1$Trt`[,'p adj'] ``` For some objects like `Expt1R`, the output of `str()` can sometimes be overwhelming. Using `names()` to look at the different objects inside it is also helpful. ``` names(Expt1R) [1] "coefficients" "residuals" "effects" "rank" "fitted.values" "assign" [7] "qr" "df.residual" "contrasts" "xlevels" "call" "terms" [13] "model" ``` So ``` Expt1R$df.residual ``` will give you the degrees of freedom of the residual.
41,297,615
With regard to the built-in Excel function: VLOOKUP(lookup\_value,table\_array,col\_index\_num,range\_lookup). This function is described at <https://support.microsoft.com/en-gb/kb/181213> As we know this function starts to give the wrong results if you insert a column in the middle of the lookup table. This is because the col\_index\_num parameter does not change to accommodate the new offset between the columns you are interested in. The problem becomes worse when using a vlookup function from within VBA where the table\_array range also lacks the ability to respond to movements in the lookup table. The question: Is there an alternate function that can respond to structural changes in the lookup table without giving unexpected results (exact matches are required). I am going to answer my own question in the event that my solution may be useful to others.
2016/12/23
[ "https://Stackoverflow.com/questions/41297615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1170311/" ]
SPSS has a [`FILE HANDLE`](http://www.ibm.com/support/knowledgecenter/en/SSLVMB_21.0.0/com.ibm.spss.statistics.help/syn_file_handle.htm) and [`CD`](http://www.ibm.com/support/knowledgecenter/en/SSLVMB_21.0.0/com.ibm.spss.statistics.help/syn_cd.htm) command (as you point out also) that aid to try make these type of thing easier. However I opt for a different approach that I have all my job setup to use, which if you use Python can implement also. You can get the dynamic location of a (saved) syntax file using python like so: ``` os.path.dirname(SpssClient.GetDesignatedSyntaxDoc().GetDocumentPath()) ``` I have posted a detailed solution to this in the past which you can find [here](https://stackoverflow.com/questions/28010865/spss-syntax-use-path-of-the-file) and may find helpful in your scenario also.
Another possibility is to use the STATS OPEN PROJECT extension command. This opens a project and carries out the actions it defines. It can open data files, run any syntax, etc. You can have a master project that does things you always want and subprojects for specific work. It can be set to do this on Statistics startup if you want. STATS OPEN PROJECT can be installed from the Extensions menu in V24 or Utilities > Extension Commands in V22 or 23.
70,881,196
How can i transform this sql query to an EF linq command ``` "update dbo.table set col1= col1 + 1 where Id = 27" ``` i want to execute this query using one command to avoid concurrency problems in case of another client modify the record in the same time i'm looking for doing that using EF but in one command i tried this but i'm looking for a better solution : ``` context.table1.FromSqlInterpolated($"update dbo.table set col1= col1+ 1 where Id=27").FirstOrDefaultAsync(); ```
2022/01/27
[ "https://Stackoverflow.com/questions/70881196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15190100/" ]
There are ways to [update a column without first querying](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework/5567616#5567616), but the problem you have is that the update is based on the existing value. Entity Framework can't help you there. You can only do what you want with a direct SQL statement.
Even the original SQL statement should be executed within a transaction if you want to be sure no other changes can occur between reading and updating the value. It's one SQL statement, but the db still has to read the value, increment and store.
70,881,196
How can i transform this sql query to an EF linq command ``` "update dbo.table set col1= col1 + 1 where Id = 27" ``` i want to execute this query using one command to avoid concurrency problems in case of another client modify the record in the same time i'm looking for doing that using EF but in one command i tried this but i'm looking for a better solution : ``` context.table1.FromSqlInterpolated($"update dbo.table set col1= col1+ 1 where Id=27").FirstOrDefaultAsync(); ```
2022/01/27
[ "https://Stackoverflow.com/questions/70881196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15190100/" ]
I would propose to use [linq2db.EntityFrameworkCore](https://github.com/linq2db/linq2db.EntityFrameworkCore) (note that I'm one of the creators) Then you can do that with ease: ```cs await context.table1.Where(x => x.Id == 27) .Set(x => x.Col1, prev => prev.Col1 + 1) .UpdateAsync(); ```
Even the original SQL statement should be executed within a transaction if you want to be sure no other changes can occur between reading and updating the value. It's one SQL statement, but the db still has to read the value, increment and store.
1,495,139
I have 3 sets of tabular data I want to display with a JavaScript framework in ASP.NET MVC. I know I can embed a separate grid in a tab, but this seems inefficient especially when large datasets are involved since I imagine 3 separate grids would be created. I haven't found a JavaScript datagrid which emulates what a spreadsheet does with multiple tabs. This example from YUI might come close though: <http://developer.yahoo.com/yui/examples/datatable/dt_dynamicfilter_source.html> I'm a little familiar with jQuery, but would be willing to switch to any framework which makes this easy. I don't really need to edit the data. Any suggestions? ***EDIT***: I didn't mean this to be about jQuery. Maybe some details about my scenario would help, as suggested in one of the comments. I want to display tabular data from an ordering system containing thousands of records. I'd like 3 tabs: 1. All orders entered in the system which haven't been paid for yet. 2. All orders from a specific vendor. 3. All orders which have been paid for. Since each category has thousands of rows, I only want to load data if the user starts paging. I thought having 3 tabs with 3 separate grids (one within each tab) wouldn't be performant. I haven't actually tried though, so I'm probably guilty of prematurely optimizing. I'm looking for a grid with tab support built-in. I don't think there's one for jQuery. Perhaps ExtJS?
2009/09/29
[ "https://Stackoverflow.com/questions/1495139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58634/" ]
Since you tagged this with Ext JS, I'll mention that it's quite simple to render grids into tabs using Ext JS. It also supports deferred load/render, so that only the first tab/grid would load initially, then the others would be loaded on first access. Without knowing your specific requirements it's hard to comment further. **EDIT** (based on edited question): Ext grids don't directly support tabbing, but they can be embedded within a TabPanel as I mentioned for the same effect. However, based on your description, it sounds more like a filtering scenario to me. I don't see the point in having the overhead of multiple grids when only one will ever be visible, and each one's purpose is to show a specific view (i.e. filter) of the same data. I would just have a single grid with a toolbar or some other method of providing your toggle between filters, and use Ext's built-in store filtering/querying to create your views on demand. The Ext grid supports paging out of the box (client or server, in your case it would be server for thousands of records). There is also a very popular plugin called [LiveGrid](http://www.extjs.com/forum/showthread.php?t=17791) that provides for virtual scroll-paging of large data sets. I'm not necessarily advocating Ext over any other framework -- I just happen to be most familiar with it and I think it could solve your problem quite nicely. I would suggest trying it out for yourself to be sure.
jQuery Grid is kinda what people use a lot. I use it and it's pretty good. [jqGrid Link](http://www.jqgrid.com/) I wouldn't draw a grid with three tabs. I'd use a single grid with a tab control and then load data via jQuery as required. Or maybe have three PartialViews that you can load dynamically when you hit a tab.
1,495,139
I have 3 sets of tabular data I want to display with a JavaScript framework in ASP.NET MVC. I know I can embed a separate grid in a tab, but this seems inefficient especially when large datasets are involved since I imagine 3 separate grids would be created. I haven't found a JavaScript datagrid which emulates what a spreadsheet does with multiple tabs. This example from YUI might come close though: <http://developer.yahoo.com/yui/examples/datatable/dt_dynamicfilter_source.html> I'm a little familiar with jQuery, but would be willing to switch to any framework which makes this easy. I don't really need to edit the data. Any suggestions? ***EDIT***: I didn't mean this to be about jQuery. Maybe some details about my scenario would help, as suggested in one of the comments. I want to display tabular data from an ordering system containing thousands of records. I'd like 3 tabs: 1. All orders entered in the system which haven't been paid for yet. 2. All orders from a specific vendor. 3. All orders which have been paid for. Since each category has thousands of rows, I only want to load data if the user starts paging. I thought having 3 tabs with 3 separate grids (one within each tab) wouldn't be performant. I haven't actually tried though, so I'm probably guilty of prematurely optimizing. I'm looking for a grid with tab support built-in. I don't think there's one for jQuery. Perhaps ExtJS?
2009/09/29
[ "https://Stackoverflow.com/questions/1495139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58634/" ]
jQuery Grid is kinda what people use a lot. I use it and it's pretty good. [jqGrid Link](http://www.jqgrid.com/) I wouldn't draw a grid with three tabs. I'd use a single grid with a tab control and then load data via jQuery as required. Or maybe have three PartialViews that you can load dynamically when you hit a tab.
You could use [JS tab object](http://www.pagecolumn.com/webparts/tabs_object_top_bottom.htm) to create tabs. And use [javascript grid framework](http://www.pagecolumn.com/javascript/js_grid_framework.htm) to create grids and populate data into grids.
1,495,139
I have 3 sets of tabular data I want to display with a JavaScript framework in ASP.NET MVC. I know I can embed a separate grid in a tab, but this seems inefficient especially when large datasets are involved since I imagine 3 separate grids would be created. I haven't found a JavaScript datagrid which emulates what a spreadsheet does with multiple tabs. This example from YUI might come close though: <http://developer.yahoo.com/yui/examples/datatable/dt_dynamicfilter_source.html> I'm a little familiar with jQuery, but would be willing to switch to any framework which makes this easy. I don't really need to edit the data. Any suggestions? ***EDIT***: I didn't mean this to be about jQuery. Maybe some details about my scenario would help, as suggested in one of the comments. I want to display tabular data from an ordering system containing thousands of records. I'd like 3 tabs: 1. All orders entered in the system which haven't been paid for yet. 2. All orders from a specific vendor. 3. All orders which have been paid for. Since each category has thousands of rows, I only want to load data if the user starts paging. I thought having 3 tabs with 3 separate grids (one within each tab) wouldn't be performant. I haven't actually tried though, so I'm probably guilty of prematurely optimizing. I'm looking for a grid with tab support built-in. I don't think there's one for jQuery. Perhaps ExtJS?
2009/09/29
[ "https://Stackoverflow.com/questions/1495139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58634/" ]
Since you tagged this with Ext JS, I'll mention that it's quite simple to render grids into tabs using Ext JS. It also supports deferred load/render, so that only the first tab/grid would load initially, then the others would be loaded on first access. Without knowing your specific requirements it's hard to comment further. **EDIT** (based on edited question): Ext grids don't directly support tabbing, but they can be embedded within a TabPanel as I mentioned for the same effect. However, based on your description, it sounds more like a filtering scenario to me. I don't see the point in having the overhead of multiple grids when only one will ever be visible, and each one's purpose is to show a specific view (i.e. filter) of the same data. I would just have a single grid with a toolbar or some other method of providing your toggle between filters, and use Ext's built-in store filtering/querying to create your views on demand. The Ext grid supports paging out of the box (client or server, in your case it would be server for thousands of records). There is also a very popular plugin called [LiveGrid](http://www.extjs.com/forum/showthread.php?t=17791) that provides for virtual scroll-paging of large data sets. I'm not necessarily advocating Ext over any other framework -- I just happen to be most familiar with it and I think it could solve your problem quite nicely. I would suggest trying it out for yourself to be sure.
You could also use [dhtmlx grid.](http://dhtmlx.com/docs/products/dhtmlxGrid/)
1,495,139
I have 3 sets of tabular data I want to display with a JavaScript framework in ASP.NET MVC. I know I can embed a separate grid in a tab, but this seems inefficient especially when large datasets are involved since I imagine 3 separate grids would be created. I haven't found a JavaScript datagrid which emulates what a spreadsheet does with multiple tabs. This example from YUI might come close though: <http://developer.yahoo.com/yui/examples/datatable/dt_dynamicfilter_source.html> I'm a little familiar with jQuery, but would be willing to switch to any framework which makes this easy. I don't really need to edit the data. Any suggestions? ***EDIT***: I didn't mean this to be about jQuery. Maybe some details about my scenario would help, as suggested in one of the comments. I want to display tabular data from an ordering system containing thousands of records. I'd like 3 tabs: 1. All orders entered in the system which haven't been paid for yet. 2. All orders from a specific vendor. 3. All orders which have been paid for. Since each category has thousands of rows, I only want to load data if the user starts paging. I thought having 3 tabs with 3 separate grids (one within each tab) wouldn't be performant. I haven't actually tried though, so I'm probably guilty of prematurely optimizing. I'm looking for a grid with tab support built-in. I don't think there's one for jQuery. Perhaps ExtJS?
2009/09/29
[ "https://Stackoverflow.com/questions/1495139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58634/" ]
Since you tagged this with Ext JS, I'll mention that it's quite simple to render grids into tabs using Ext JS. It also supports deferred load/render, so that only the first tab/grid would load initially, then the others would be loaded on first access. Without knowing your specific requirements it's hard to comment further. **EDIT** (based on edited question): Ext grids don't directly support tabbing, but they can be embedded within a TabPanel as I mentioned for the same effect. However, based on your description, it sounds more like a filtering scenario to me. I don't see the point in having the overhead of multiple grids when only one will ever be visible, and each one's purpose is to show a specific view (i.e. filter) of the same data. I would just have a single grid with a toolbar or some other method of providing your toggle between filters, and use Ext's built-in store filtering/querying to create your views on demand. The Ext grid supports paging out of the box (client or server, in your case it would be server for thousands of records). There is also a very popular plugin called [LiveGrid](http://www.extjs.com/forum/showthread.php?t=17791) that provides for virtual scroll-paging of large data sets. I'm not necessarily advocating Ext over any other framework -- I just happen to be most familiar with it and I think it could solve your problem quite nicely. I would suggest trying it out for yourself to be sure.
You could use [JS tab object](http://www.pagecolumn.com/webparts/tabs_object_top_bottom.htm) to create tabs. And use [javascript grid framework](http://www.pagecolumn.com/javascript/js_grid_framework.htm) to create grids and populate data into grids.
1,495,139
I have 3 sets of tabular data I want to display with a JavaScript framework in ASP.NET MVC. I know I can embed a separate grid in a tab, but this seems inefficient especially when large datasets are involved since I imagine 3 separate grids would be created. I haven't found a JavaScript datagrid which emulates what a spreadsheet does with multiple tabs. This example from YUI might come close though: <http://developer.yahoo.com/yui/examples/datatable/dt_dynamicfilter_source.html> I'm a little familiar with jQuery, but would be willing to switch to any framework which makes this easy. I don't really need to edit the data. Any suggestions? ***EDIT***: I didn't mean this to be about jQuery. Maybe some details about my scenario would help, as suggested in one of the comments. I want to display tabular data from an ordering system containing thousands of records. I'd like 3 tabs: 1. All orders entered in the system which haven't been paid for yet. 2. All orders from a specific vendor. 3. All orders which have been paid for. Since each category has thousands of rows, I only want to load data if the user starts paging. I thought having 3 tabs with 3 separate grids (one within each tab) wouldn't be performant. I haven't actually tried though, so I'm probably guilty of prematurely optimizing. I'm looking for a grid with tab support built-in. I don't think there's one for jQuery. Perhaps ExtJS?
2009/09/29
[ "https://Stackoverflow.com/questions/1495139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58634/" ]
You could also use [dhtmlx grid.](http://dhtmlx.com/docs/products/dhtmlxGrid/)
You could use [JS tab object](http://www.pagecolumn.com/webparts/tabs_object_top_bottom.htm) to create tabs. And use [javascript grid framework](http://www.pagecolumn.com/javascript/js_grid_framework.htm) to create grids and populate data into grids.
14,667,010
I'm playing with the Gamepad API - in particular the axes using the joysticks on a controller. The position of these updates a lot and often - as such, the event that I'm listening for (movement on the sticks) also happens a lot. Is there any way to limit it happening to, say, 25 times a second in order to reduce lag?
2013/02/02
[ "https://Stackoverflow.com/questions/14667010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2036108/" ]
You can't limit the rate at which JavaScript events are triggered, but your event handler could opt to do nothing on some calls. Here is an example using `mousemove` (I don't know which Gamepad API you're talking about): ``` var lastMove = 0; document.addEventListener('mousemove', function() { // do nothing if last move was less than 40 ms ago if(Date.now() - lastMove > 40) { // Do stuff lastMove = Date.now(); } }); ``` <http://jsfiddle.net/jk3Qh/>
Initialize a variable that increments every time the event listener activates. Make it so that the function the event listener outputs only occurs when the variable is below 25.
14,667,010
I'm playing with the Gamepad API - in particular the axes using the joysticks on a controller. The position of these updates a lot and often - as such, the event that I'm listening for (movement on the sticks) also happens a lot. Is there any way to limit it happening to, say, 25 times a second in order to reduce lag?
2013/02/02
[ "https://Stackoverflow.com/questions/14667010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2036108/" ]
You could do something like this, where you check how often your event is called in a 1 second interval and whether or not you process it. Code sample, rough outline of what I was thinking (no gaurantee (like that spelling)). ``` function process_event() { var curr = new Date().getTime(); if ((curr - timeObj.last) < 1000) { //One Second if (timeObj.counter > 25) { for (var x=0;x<timeObj.times;x++) { if ((curr - timeObj.times[x]) >= 1000) { timeObj.times.splice(x, 1); timeObj.counter -= 1; } } } else { timeObj.counter += 1; timeObj.times[timeObj.times.length()-1] = curr; } } else { timeObj.counter = 0; timeObj.times = []; } if (timeObj.counter > 25) { return False } else { return True } } ```
Initialize a variable that increments every time the event listener activates. Make it so that the function the event listener outputs only occurs when the variable is below 25.
14,667,010
I'm playing with the Gamepad API - in particular the axes using the joysticks on a controller. The position of these updates a lot and often - as such, the event that I'm listening for (movement on the sticks) also happens a lot. Is there any way to limit it happening to, say, 25 times a second in order to reduce lag?
2013/02/02
[ "https://Stackoverflow.com/questions/14667010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2036108/" ]
You can't limit the rate at which JavaScript events are triggered, but your event handler could opt to do nothing on some calls. Here is an example using `mousemove` (I don't know which Gamepad API you're talking about): ``` var lastMove = 0; document.addEventListener('mousemove', function() { // do nothing if last move was less than 40 ms ago if(Date.now() - lastMove > 40) { // Do stuff lastMove = Date.now(); } }); ``` <http://jsfiddle.net/jk3Qh/>
You could do something like this, where you check how often your event is called in a 1 second interval and whether or not you process it. Code sample, rough outline of what I was thinking (no gaurantee (like that spelling)). ``` function process_event() { var curr = new Date().getTime(); if ((curr - timeObj.last) < 1000) { //One Second if (timeObj.counter > 25) { for (var x=0;x<timeObj.times;x++) { if ((curr - timeObj.times[x]) >= 1000) { timeObj.times.splice(x, 1); timeObj.counter -= 1; } } } else { timeObj.counter += 1; timeObj.times[timeObj.times.length()-1] = curr; } } else { timeObj.counter = 0; timeObj.times = []; } if (timeObj.counter > 25) { return False } else { return True } } ```
56,443,979
Is there a way to make a class that holds several other classes? In the Bootstrap menu, there are many anchor tags with the same multiple classes such as: ``` <a class="nav-item nav-link" asp-controller="Account" asp-action="Login">Login</a> ``` To something like: ``` <a class="consolidate-name" asp-controller="Account" asp-action="Login">Login</a> ```
2019/06/04
[ "https://Stackoverflow.com/questions/56443979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1261114/" ]
Regular Expressions will work nicely here. `.contains()` [allows for regex](https://docs.cypress.io/api/commands/contains.html#Regular-Expression) So you can do a regex that matches the whole string only (use `^` and `$`). That way anything with extra characters won't match (like New Navigation Label). So for example, you could do: ```js cy.get(`[data-test="dropdown"]`) .find('.item') .contains(/^Navigation Label$/) .click(); ``` Regex is a little tricky when you are building an expression with a variable (ex. your `option` variable). In this case, you'll [build a regular expression](https://stackoverflow.com/a/494046/9040602) like so: ```js cy.get(`[data-test="dropdown"]`) .find('.item') .contains(new RegExp("^" + option + "$", "g")) .click(); ``` So to get an exact match with `.contains()`: ```js cy.contains(new RegExp(yourString, "g")) ```
You can use below code snippet to click on an element which has exact text. This will work like charm, let me know if you face any issue. You have to handle like below in cypress which is equivalent getText() in selenium webdriver. ``` clickElementWithEaxctTextMatch(eleText) { cy.get(".className").each(ele => { if (ele.text() === eleText) { ele.click(); } }); } ```
1,419,718
I've been playing with C++ for a few years now, and want to become adept at using and factories. Are there some good web tutorials and/or textbooks that cover this well? I started programming prior to the wide use of the term "patterns" ('80's)... but when I first saw the term I recognized the "pattern" of it's usage. A good reference/resource for various useful patterns would also be useful to me as well. Thanks!
2009/09/14
[ "https://Stackoverflow.com/questions/1419718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The links in this forum post will help you a ton: [Forum Post](http://www.codeguru.com/forum/showthread.php?t=327982)
Do you mean book for C++ Templates and Design patterns ? Then, my choice: * C++ Templates : [C++ Templates The Complete Guide](http://books.google.co.in/books?id=EotSAwuBkJoC&dq=C%2B%2B+Templates+The+Complete+Guide+%2B+josuttis&printsec=frontcover&source=bl&ots=iwLZM21oeg&sig=0v97fIH9aFLXQfQH6MjyY64iuRk&hl=en&ei=79OtSpXNKeKRjAeZ9-zhBw&sa=X&oi=book_result&ct=result&resnum=1#v=onepage&q=&f=false) by Josuttis * design Patterns: [Head First design patterns](http://books.google.co.in/books?id=LjJcCnNf92kC&printsec=frontcover&dq=HeadFirst+design+patterns&ei=H9StStz7IomGzATKntXuBA#v=onepage&q=HeadFirst%20design%20patterns&f=false)
1,419,718
I've been playing with C++ for a few years now, and want to become adept at using and factories. Are there some good web tutorials and/or textbooks that cover this well? I started programming prior to the wide use of the term "patterns" ('80's)... but when I first saw the term I recognized the "pattern" of it's usage. A good reference/resource for various useful patterns would also be useful to me as well. Thanks!
2009/09/14
[ "https://Stackoverflow.com/questions/1419718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Read books of Herb Sutter like **Exceptional C++** or **C++ Coding Standards**, books from Scott Meyers, like **Effective C++**. For different patterns read **Design Patterns** by the Gang of four (Gamma, Helm, Johnson, Vlissides), the **Advanced C++ Programming Styles and Idioms** by James O. Coplien is also good. If you want to go deeper - like metaprogramming, take the **Modern C++ Design** by Andrei Alexandrescu.
Do you mean book for C++ Templates and Design patterns ? Then, my choice: * C++ Templates : [C++ Templates The Complete Guide](http://books.google.co.in/books?id=EotSAwuBkJoC&dq=C%2B%2B+Templates+The+Complete+Guide+%2B+josuttis&printsec=frontcover&source=bl&ots=iwLZM21oeg&sig=0v97fIH9aFLXQfQH6MjyY64iuRk&hl=en&ei=79OtSpXNKeKRjAeZ9-zhBw&sa=X&oi=book_result&ct=result&resnum=1#v=onepage&q=&f=false) by Josuttis * design Patterns: [Head First design patterns](http://books.google.co.in/books?id=LjJcCnNf92kC&printsec=frontcover&dq=HeadFirst+design+patterns&ei=H9StStz7IomGzATKntXuBA#v=onepage&q=HeadFirst%20design%20patterns&f=false)
46,750,808
How can I tell my function to respond to an endpoint specified on the received message with a HTTP Post response in Google Cloud function? In the code, or the trigger configuration, or in the package json? I think I'm looking for something [like this](https://cloud.google.com/functions/docs/writing/http) but in python:
2017/10/15
[ "https://Stackoverflow.com/questions/46750808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8612164/" ]
All you need is just this - **return Response('No file uploaded', status=500**) Check this out - <https://www.programcreek.com/python/example/51515/flask.Response> FYI, A Google Cloud Function uses a Flask Response object - <http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>
This is the link to google's answer: <https://cloud.google.com/functions/docs/writing/http> I used this link to write this solution: ``` headers= { 'Access-Control-Allow-Origin': '*', 'Content-Type':'application/json' } id1= "1234567" var1= "variable 1" text = '{"id1":"'+id1+'","var1":"'+var1+'"}' print(text) return (text, 200, headers) ```
3,310,857
I'm about to design a client application and the server part is not designed either. I need to decide on the communication protocol. The requirements are: * fast, compact * supports binary file transfer both ways * server is probably PHP, client .NET So far I have considered these: * custom XML over HTTP - I've done this in the past, but it's not very suitable for file transfer, otherwise OK * SOAP - no experience, I read it's very verbose and complicated * Google protobuf - read a lot of good things about this * pure HTTP - using get and post - this may be badly extensible. I'm open to suggestions. So far i'm leaning towards protobuf. **Edit: More info** * The server will be data heavy, thin application layer, possibly only database itself. Milions to a billion records, search intensive (fultext and custom searches). * Expected client application count is in hundeds, but may grow * 2 types of messages from server to client, small (under 100KB), but very common, large (file downloads, under 10MB cca) * client sends back only the smaller messages but with more information. * i'd like to have information structured, to provide meta information both ways. * i'd like it extensible for future changes * Encryption mandatory (considering https as transport layer) * Lantency is crutial, I'd like to achieve "standard" web latencies (under 200ms would be good), for the small messages. This really depends on many things.
2010/07/22
[ "https://Stackoverflow.com/questions/3310857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177591/" ]
Answering my own question, the tool is available here: [MSDN subscribers download](http://msdn.microsoft.com/en-us/vstudio/ff655021.aspx)
This online service <http://modeling-languages.com/content/xmi2-tool-exchanging-uml-models-among-case-tools> helps to exchange UML class diagrams between different tools. Not sure if the XMI format imported/exported by your specific tool combination is similar to one of the currently supported tools
3,555,474
We use WordPress for development, but often make a lot of modifications. We're looking for a way to always keep our development version up to date with our modified version. It possible to import all of the [WordPress SVN](http://core.svn.wordpress.org/) commits, branches and tags, but merge these with any we've made in our repo. For example if we had removed the readme.txt file in our local repo, when we did another import from the WordPress SVN it would display the changes between this files and allow us to decide to to merge, update etc. If not SVN is this possible with Git? Thanks,
2010/08/24
[ "https://Stackoverflow.com/questions/3555474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45350/" ]
What you want is a vendor branch. We used it with wordpress and it works well. [Subversion svn:externals file override?](https://stackoverflow.com/questions/3754459/subversion-svnexternals-file-override/3785904#3785904)
I think you can merge from the WordPress SVN repo into your local repo, but you need to keep track of what revisions you have merged, and you need to remind yourself to do the merge. There is no concept of live forking in SVN. The closest you can get is [SVN Externals](http://svnbook.red-bean.com/en/1.0/ch07s03.html), but that does not allow you to check in local modifications.
26,555
Is it possible to create thrusters for station keeping that require no fuel? Are there ideas similar to solar sails which can help in station- keeping and make use of a natural phenomenon? Except the EM drive.
2018/04/09
[ "https://space.stackexchange.com/questions/26555", "https://space.stackexchange.com", "https://space.stackexchange.com/users/23950/" ]
In theory an Electro Dynamic Tether (<https://en.wikipedia.org/wiki/Electrodynamic_tether>) could be used to impart momentum to a satellite or station for station-keeping maneuvers, converting electricity to momentum. See this paper: <http://issfd.org/2015/files/downloads/papers/111_Oliveira.pdf>
The EM drive is currently the only concept under testing that I'm aware. If by fuel you mean some consumable that is loaded before lunch, and if by "Is it possible" you are proposing a more theoretical rather than readily practical question, I would argue that it should be possible to create some kind of particle acceleration technique such that regular atoms and electrons found in the space environment could be accelerated or decelerated thus exchanging momentum with the spacecraft. This would require electrical power, but no consumable fuel. Also, in theory light carries momentum, so emitting a laser is also a way of exchanging momentum. Solar Sails are an interesting concept but they also would cause drag, in this sense if the station-keeping over long term is meant to compensate drag effects, I strongly doubt they could be effective. They could be used for deep-space missions, such as voyager, where the goal is to get away from the sun instead of remaining in a controlled neighborhood of a planet. Note however that station keeping requires some specific minimum amount of delta-V provided over a finite windows of time, so any futuristic method needs to comply with real-world restrictions in order to be actually useful. Think about the Carnot Engine, that while it's theoretically the most efficient would take infinite time to run a single cycle.
872,230
I've been reading its man page but haven't yet been successful in figuring out how it works. On calling system(), is a new child process forked and the shell binary exec()-ed in it? That may be a stupid guess though.
2009/05/16
[ "https://Stackoverflow.com/questions/872230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/108127/" ]
Yes, system() is essentially a fork() and exec() "sh -c" for the passed command string. An example implementation (from eglibc, recently forked from glibc) can be found [here](http://www.eglibc.org/cgi-bin/viewcvs.cgi/branches/eglibc-2_9/libc/sysdeps/posix/system.c?rev=7350&view=markup).
Yes, system("foo bar") is equivalent to execv("/bin/sh", ["sh", "-c", "foo bar"]).
36,240,991
I'm working with CSV but all the tutorials I've read use 2D Lists. ``` private void cargaCSV() { List<string[]> values = new List<string[]>(); var reader = new StreamReader(File.OpenRead(*my file*)); while (!reader.EndOfStream) { string line = reader.ReadLine(); values.Add(line.Split(';')); } } ``` My problem is my project works with 2D String Array. I tried the following: ``` string [,] Data = values.ToArray(); ``` I want to convert the 2d list into 2d array
2016/03/26
[ "https://Stackoverflow.com/questions/36240991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4608648/" ]
If all the arrays have the same length, then you can do what you are doing and, after that, create and fill the array manually: ``` string[,] stringArray = new string[values.Count, values.First().Length] for (int i = 0; i < values.Count; i++) row = values[i]; for (int j = 0; j < row.Length; j++) string[i,j] = row[j]; } } ```
You don't have to typecast hard and old way. Simply replace ``` string [,] Data = values.ToArray(); ``` With ``` var Data = values.ToArray(); ``` Now Data is two dimensional array of strings.
66,886
I'm trying to translate [a video on TED](http://www.ted.com/talks/susan_cain_the_power_of_introverts.html) into my native language (Latvian). At the very start there is an expression I'm unfamiliar with - "animal warmth". I think I kind of understand the idea intuitively, but I can't think of any similar expressions in my native tongue (short of direct translation). It would be nice if someone could explain the concept to me, or give some more examples of usage. Here's the context: > > ... Because in my family, reading was the primary group activity. And this might sound antisocial to you, but for us it was really just a different way of being social. You have the **animal warmth** of your family sitting right next to you, but you are also free to go roaming around the adventureland inside your own mind. > > >
2012/05/06
[ "https://english.stackexchange.com/questions/66886", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5587/" ]
It simply describes, rather graphically, the comfort to be derived from the presence of other people, particularly people you are close to.
Animal warmth is literally a warmth generated from within an animal or person, as opposed to external sources of heat. It is used figuratively to mean a coziness and closeness with another being. Here are a few examples of its use. The first excerpt is from an old medical journal, just showing that it's an old term and that animal warmth is different than artificial heat. [*Baltimore monthly journal of medicine & surgery*, Volume 1, 1830](http://books.google.com/books?id=JHWbGLG05iAC&pg=PA100&dq=%22animal+warmth%22&hl=en&sa=X&ei=P5OmT-C8GKmN6QHwhrC4BA&ved=0CDUQ6AEwADgU#v=onepage&q=%22animal%20warmth%22&f=false) > > Besides there is something we know not what in animal warmth which cherishes far more than artificial heat. The knowledge of the fact seems to be as old as the days of King David but the rationale we cannot explain until we shall have learnt something more of the constitution of heat. > > > This excerpt from a textbook shows the connotation of closeness and nurturing. [Anglo-Irish Autobiography: Class, Gender, and the Forms of Narrative By Elizabeth Grubgeld, 2004](http://books.google.com/books?id=CX2XmwyER7QC&pg=PA87&dq=%22animal+warmth%22+Elizabeth+Grubgeld&hl=en&sa=X&ei=rpGmT_CJKYTb6gGj08XUDQ&ved=0CDoQ6AEwAA#v=onepage&q&f=false) > > As a small child I often longed for the animal warmth of simple maternal love. I longed for some one to take me in her arms, to kiss me and to hug me, to rock me to sleep in her lap. > > > As does this example from the journal of poet Sylvia Plath. [The Unabridged Journals of Sylvia Plath, 1950-1962](http://books.google.com/books?id=ITPOjgipsBgC&pg=PA30&dq=%22animal+warmth%22&hl=en&sa=X&ei=FZCmT6OaEsu26QHwhamvBA&ved=0CG0Q6AEwCThG#v=onepage&q=%22animal%20warmth%22&f=false) > > So there it was, two hours of driving through the dark, the warmth of the people on either side of me -- animal warmth penetrates regardless of sensibilities and arbitrary barricades. > > >
66,886
I'm trying to translate [a video on TED](http://www.ted.com/talks/susan_cain_the_power_of_introverts.html) into my native language (Latvian). At the very start there is an expression I'm unfamiliar with - "animal warmth". I think I kind of understand the idea intuitively, but I can't think of any similar expressions in my native tongue (short of direct translation). It would be nice if someone could explain the concept to me, or give some more examples of usage. Here's the context: > > ... Because in my family, reading was the primary group activity. And this might sound antisocial to you, but for us it was really just a different way of being social. You have the **animal warmth** of your family sitting right next to you, but you are also free to go roaming around the adventureland inside your own mind. > > >
2012/05/06
[ "https://english.stackexchange.com/questions/66886", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5587/" ]
It simply describes, rather graphically, the comfort to be derived from the presence of other people, particularly people you are close to.
I belong to a local Toastmasters group and my next 5-7 minute speech is coming up. I've chosen the title 'Animal Warmth' and here is the very first draft of my speech (sorry it is not as yet more polished): > > Animal warmth > > > I wonder how many of you have experienced the warmth and comfort you > can get from an animal? > > > The first time I really felt this was way back when I was thirteen > going on fourteen. It was my worst ever Christmas. We were on my aunt > and uncle's dairy farm in the Manawatu when my father died of a sudden > heart attack. Very early Christmas morning. You can imagine the next > few days. Mum's health hadn't been good the past year and now she'd > suddenly lost her husband. My step-grandmother was there, and lots of > other people, all milling around her. No one seemed to take any notice > of me. So I spent the next few days just wandering over the farm. > Feeling lost. And I found my way to the cows. I'd been helping with > milking for some time already. I knew there are some cows that are > tamer than others. They'll stand still in the paddock and let you go > up to them. There's a way of approaching a cow so she isn't scared. > [demonstrate] You don't just barge up to them front on. You approach > at the back, and you gently rub along her back, gradually getting > closer to her head as she relaxes a bit. Then you can rub her between > the ears, like a dog. You can put your arm around her neck. You can > snuggle in to her. She's so warm, so comforting. That's what I did, > day after day. I let the cows give me comfort. Who knows what they > were thinking … but they stayed still for me, they let me cuddle them. > I felt their warmth, their soft heat. They were like a mother. They > mothered me when I most needed it, when my own mother was consumed by > her own pain, her own loss. I've loved cows ever since. > > > These days I don't come across cows very often. There are beef cattle > up in the Wellington hills. I've taken a dog walking behind Wellington > Prison and we came across some surprisingly docile Herefords. Even > though I had Seal with me, they let me get up really close and pat > them. It was a good feeling. There are often beef cattle in the hills > around Mt Kaukau too. I love to take photos of them but these ones > don't let me get close enough to pat them, with dog or without. Seal > wasn't 'my' dog but I took her walking in the hills a lot. I never > thought I'd get attached to a dog but Seal became my friend … and she > gave me comfort too. Seal was part of the wider family … and > > Earlier this year, Seal developed cancer of the jaw. She had to be > put down. I guess quite a few of you have gone through that … you'll > know how hard it is. Anyway, I was walking in the hills south of > Kaukau one day, taking the 'scenic route' to Ngaio. I was by myself – > and feeling cold, lonely and lost, thinking about the last time I was > there … with the dog running ahead, looking back eagerly, doing what > happy dogs do. Thinking about other losses in my life, thinking about > times that just don't come again. Finally I walked down to the Ngaio > railway station to catch a train home again. And I learned that > animal warmth and comfort can sometimes come along when they're most > needed. > > > I'd just missed a train. Nearly half an hour to wait. No one else on > the platform. Nothing to read. I sat down, miserable. And then … a > small furry creature dashed across from the other side of the tracks. > Leapt on my lap. Settled down, purring madly. The Ngaio > stationmaster. I wonder how many of you know the Ngaio stationmaster. > I'd often see this cat from the train as I passed through Ngaio. Just > about always at the Ngaio station, meeting the trains. It took me a > while to learn that the stationmaster is female, lives quite close by, > does have another name – Belle. A local fixture. She was so warm! I > moved, I didn't want her to jump off my lap. But there was no risk of > that, she was there to stay. And somehow I felt comforted. She was > still on my lap when I saw my train appearing round the corner from > Crofton Downs. I lifted her off. 'I'm sorry, I have to go now.' I > felt like thanking her. > > > When the train moved off, I looked back at her through the window. I > felt so warm towards her. 'That's the Ngaio stationmaster,' I told a > man sitting nearby. He just laughed. 'Yes, she'll jump up on anyone > who's waiting for the train,' he said. > > > Well, I knew that, didn't I. She wasn't there specially for me … but > she certainly came along at a time I needed a bit of animal warmth. > > > You might imagine that I'm now going to tell you you should go out > and get a pet of your own … a cat or dog if not a cow … Well, I'm > not doing that … I don't have a pet of any sort so I can't tell YOU to > get one! But what I AM here to say is simply this … When you need > some warmth and comfort, there's often an obliging animal nearby. If > you can't find a suitable cow …. you could head down to the Ngaio > railway station … the stationmaster might well leap onto your lap. > > >
66,886
I'm trying to translate [a video on TED](http://www.ted.com/talks/susan_cain_the_power_of_introverts.html) into my native language (Latvian). At the very start there is an expression I'm unfamiliar with - "animal warmth". I think I kind of understand the idea intuitively, but I can't think of any similar expressions in my native tongue (short of direct translation). It would be nice if someone could explain the concept to me, or give some more examples of usage. Here's the context: > > ... Because in my family, reading was the primary group activity. And this might sound antisocial to you, but for us it was really just a different way of being social. You have the **animal warmth** of your family sitting right next to you, but you are also free to go roaming around the adventureland inside your own mind. > > >
2012/05/06
[ "https://english.stackexchange.com/questions/66886", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5587/" ]
Animal warmth is literally a warmth generated from within an animal or person, as opposed to external sources of heat. It is used figuratively to mean a coziness and closeness with another being. Here are a few examples of its use. The first excerpt is from an old medical journal, just showing that it's an old term and that animal warmth is different than artificial heat. [*Baltimore monthly journal of medicine & surgery*, Volume 1, 1830](http://books.google.com/books?id=JHWbGLG05iAC&pg=PA100&dq=%22animal+warmth%22&hl=en&sa=X&ei=P5OmT-C8GKmN6QHwhrC4BA&ved=0CDUQ6AEwADgU#v=onepage&q=%22animal%20warmth%22&f=false) > > Besides there is something we know not what in animal warmth which cherishes far more than artificial heat. The knowledge of the fact seems to be as old as the days of King David but the rationale we cannot explain until we shall have learnt something more of the constitution of heat. > > > This excerpt from a textbook shows the connotation of closeness and nurturing. [Anglo-Irish Autobiography: Class, Gender, and the Forms of Narrative By Elizabeth Grubgeld, 2004](http://books.google.com/books?id=CX2XmwyER7QC&pg=PA87&dq=%22animal+warmth%22+Elizabeth+Grubgeld&hl=en&sa=X&ei=rpGmT_CJKYTb6gGj08XUDQ&ved=0CDoQ6AEwAA#v=onepage&q&f=false) > > As a small child I often longed for the animal warmth of simple maternal love. I longed for some one to take me in her arms, to kiss me and to hug me, to rock me to sleep in her lap. > > > As does this example from the journal of poet Sylvia Plath. [The Unabridged Journals of Sylvia Plath, 1950-1962](http://books.google.com/books?id=ITPOjgipsBgC&pg=PA30&dq=%22animal+warmth%22&hl=en&sa=X&ei=FZCmT6OaEsu26QHwhamvBA&ved=0CG0Q6AEwCThG#v=onepage&q=%22animal%20warmth%22&f=false) > > So there it was, two hours of driving through the dark, the warmth of the people on either side of me -- animal warmth penetrates regardless of sensibilities and arbitrary barricades. > > >
I belong to a local Toastmasters group and my next 5-7 minute speech is coming up. I've chosen the title 'Animal Warmth' and here is the very first draft of my speech (sorry it is not as yet more polished): > > Animal warmth > > > I wonder how many of you have experienced the warmth and comfort you > can get from an animal? > > > The first time I really felt this was way back when I was thirteen > going on fourteen. It was my worst ever Christmas. We were on my aunt > and uncle's dairy farm in the Manawatu when my father died of a sudden > heart attack. Very early Christmas morning. You can imagine the next > few days. Mum's health hadn't been good the past year and now she'd > suddenly lost her husband. My step-grandmother was there, and lots of > other people, all milling around her. No one seemed to take any notice > of me. So I spent the next few days just wandering over the farm. > Feeling lost. And I found my way to the cows. I'd been helping with > milking for some time already. I knew there are some cows that are > tamer than others. They'll stand still in the paddock and let you go > up to them. There's a way of approaching a cow so she isn't scared. > [demonstrate] You don't just barge up to them front on. You approach > at the back, and you gently rub along her back, gradually getting > closer to her head as she relaxes a bit. Then you can rub her between > the ears, like a dog. You can put your arm around her neck. You can > snuggle in to her. She's so warm, so comforting. That's what I did, > day after day. I let the cows give me comfort. Who knows what they > were thinking … but they stayed still for me, they let me cuddle them. > I felt their warmth, their soft heat. They were like a mother. They > mothered me when I most needed it, when my own mother was consumed by > her own pain, her own loss. I've loved cows ever since. > > > These days I don't come across cows very often. There are beef cattle > up in the Wellington hills. I've taken a dog walking behind Wellington > Prison and we came across some surprisingly docile Herefords. Even > though I had Seal with me, they let me get up really close and pat > them. It was a good feeling. There are often beef cattle in the hills > around Mt Kaukau too. I love to take photos of them but these ones > don't let me get close enough to pat them, with dog or without. Seal > wasn't 'my' dog but I took her walking in the hills a lot. I never > thought I'd get attached to a dog but Seal became my friend … and she > gave me comfort too. Seal was part of the wider family … and > > Earlier this year, Seal developed cancer of the jaw. She had to be > put down. I guess quite a few of you have gone through that … you'll > know how hard it is. Anyway, I was walking in the hills south of > Kaukau one day, taking the 'scenic route' to Ngaio. I was by myself – > and feeling cold, lonely and lost, thinking about the last time I was > there … with the dog running ahead, looking back eagerly, doing what > happy dogs do. Thinking about other losses in my life, thinking about > times that just don't come again. Finally I walked down to the Ngaio > railway station to catch a train home again. And I learned that > animal warmth and comfort can sometimes come along when they're most > needed. > > > I'd just missed a train. Nearly half an hour to wait. No one else on > the platform. Nothing to read. I sat down, miserable. And then … a > small furry creature dashed across from the other side of the tracks. > Leapt on my lap. Settled down, purring madly. The Ngaio > stationmaster. I wonder how many of you know the Ngaio stationmaster. > I'd often see this cat from the train as I passed through Ngaio. Just > about always at the Ngaio station, meeting the trains. It took me a > while to learn that the stationmaster is female, lives quite close by, > does have another name – Belle. A local fixture. She was so warm! I > moved, I didn't want her to jump off my lap. But there was no risk of > that, she was there to stay. And somehow I felt comforted. She was > still on my lap when I saw my train appearing round the corner from > Crofton Downs. I lifted her off. 'I'm sorry, I have to go now.' I > felt like thanking her. > > > When the train moved off, I looked back at her through the window. I > felt so warm towards her. 'That's the Ngaio stationmaster,' I told a > man sitting nearby. He just laughed. 'Yes, she'll jump up on anyone > who's waiting for the train,' he said. > > > Well, I knew that, didn't I. She wasn't there specially for me … but > she certainly came along at a time I needed a bit of animal warmth. > > > You might imagine that I'm now going to tell you you should go out > and get a pet of your own … a cat or dog if not a cow … Well, I'm > not doing that … I don't have a pet of any sort so I can't tell YOU to > get one! But what I AM here to say is simply this … When you need > some warmth and comfort, there's often an obliging animal nearby. If > you can't find a suitable cow …. you could head down to the Ngaio > railway station … the stationmaster might well leap onto your lap. > > >
804,761
While I'm browsing the Internet, Opera always pop out a lots of these Server certificate chain incomplete boxes. Several times it pops out tons of them . Even if I click to remember my choice or aproove, it still pop out hundreds of them... What should I do? I tried different Opera versions - 12.14 , 12. 15 , 12.16 , 12.17 and 15. The last version doesn't have any bookmarks options to put them on the left well organised. so I wanted to keep using opera 12.16 , but this problem won't let me usit it. The box is like this : " Security Issue : Warning The server's certificate chain is incomplete, ans the signer(s) are not registered. Accept? Server name: [for example] www.google.ro " So it's unbelievable... I tried to search for a solution but I can't find anything. Does somebody else has this problem too? I have it on every computer where Opera is installed. It's very annoying. Is there a way to turn this off or make it to automatically approve these windows?
2014/08/29
[ "https://superuser.com/questions/804761", "https://superuser.com", "https://superuser.com/users/362978/" ]
I just had this problem myself. Make sure your virus scanner (AVG, AVAST, Norton, etc.) is not scanning your email. You have google so turning it off is good because it's simply redundant to scan them again. Google scans all email for you. I'm not sure the root cause, but that will fix your problem. I know I'm a few years too late, but here's hoping that this answer can help others whom are in the same boat!
It's possible your router, or computers have been exploited; for example alterations to your DNS entries. A good place to start would be checking (and if needed changing) your computer's and router's DNS entries to use your IP's DNS servers. **Changing Your Router's DNS Entries:** You router will likely have a local IP address you can use to access it's settings. The exact IP will vary depending on the router, but a common example is 192.168.2.1. ![router page](https://i.stack.imgur.com/lueUQ.png) [Full size image](https://i.stack.imgur.com/lueUQ.png) 1. Open your web browser, and type `http://yourroutersipaddress`. You should be presented with a settings page. 2. Hopefully you have this page password protected; if so you will need to login using your router password. Find the login button, and login. ![dns settings](https://i.stack.imgur.com/OBvMa.png) 3. There should be a DNS section, find it. The options available with vary, but if possible set it automatically to use your internet provider's DNS servers. If manual entry is required, and you don't know your ISP's dns servers you can always use [Google's freely available DNS servers](https://developers.google.com/speed/public-dns/) instead. **Changing Your Computer's DNS Entries:** It will vary depending on what operating system you are running. These instructions are for Windows 8. 1. Open the Control Panel, and navigate to `Control Panel\Network and Internet\Network Connections`. 2. Right click on the adapter you use for your internet access, and choose `properties`. ![windows dns entries for adapter](https://i.stack.imgur.com/JkUsq.png) 3. Click `Internet Protocol Version 4`, and then click `properties`. Your DNS entries should all be blank so that Windows will request from your router. If after checking both your computer's, and router the issue still persists you might try temporarily changing your router's DNS entries to use servers that aren't from your ISP like the previously mentioned [Google](https://developers.google.com/speed/public-dns/) ones.
804,761
While I'm browsing the Internet, Opera always pop out a lots of these Server certificate chain incomplete boxes. Several times it pops out tons of them . Even if I click to remember my choice or aproove, it still pop out hundreds of them... What should I do? I tried different Opera versions - 12.14 , 12. 15 , 12.16 , 12.17 and 15. The last version doesn't have any bookmarks options to put them on the left well organised. so I wanted to keep using opera 12.16 , but this problem won't let me usit it. The box is like this : " Security Issue : Warning The server's certificate chain is incomplete, ans the signer(s) are not registered. Accept? Server name: [for example] www.google.ro " So it's unbelievable... I tried to search for a solution but I can't find anything. Does somebody else has this problem too? I have it on every computer where Opera is installed. It's very annoying. Is there a way to turn this off or make it to automatically approve these windows?
2014/08/29
[ "https://superuser.com/questions/804761", "https://superuser.com", "https://superuser.com/users/362978/" ]
I know that this should be a comment but I don't have enough privilege. I had myself a problem like that in the past and I recognized that the problem is that my date is not updated.
It's possible your router, or computers have been exploited; for example alterations to your DNS entries. A good place to start would be checking (and if needed changing) your computer's and router's DNS entries to use your IP's DNS servers. **Changing Your Router's DNS Entries:** You router will likely have a local IP address you can use to access it's settings. The exact IP will vary depending on the router, but a common example is 192.168.2.1. ![router page](https://i.stack.imgur.com/lueUQ.png) [Full size image](https://i.stack.imgur.com/lueUQ.png) 1. Open your web browser, and type `http://yourroutersipaddress`. You should be presented with a settings page. 2. Hopefully you have this page password protected; if so you will need to login using your router password. Find the login button, and login. ![dns settings](https://i.stack.imgur.com/OBvMa.png) 3. There should be a DNS section, find it. The options available with vary, but if possible set it automatically to use your internet provider's DNS servers. If manual entry is required, and you don't know your ISP's dns servers you can always use [Google's freely available DNS servers](https://developers.google.com/speed/public-dns/) instead. **Changing Your Computer's DNS Entries:** It will vary depending on what operating system you are running. These instructions are for Windows 8. 1. Open the Control Panel, and navigate to `Control Panel\Network and Internet\Network Connections`. 2. Right click on the adapter you use for your internet access, and choose `properties`. ![windows dns entries for adapter](https://i.stack.imgur.com/JkUsq.png) 3. Click `Internet Protocol Version 4`, and then click `properties`. Your DNS entries should all be blank so that Windows will request from your router. If after checking both your computer's, and router the issue still persists you might try temporarily changing your router's DNS entries to use servers that aren't from your ISP like the previously mentioned [Google](https://developers.google.com/speed/public-dns/) ones.
804,761
While I'm browsing the Internet, Opera always pop out a lots of these Server certificate chain incomplete boxes. Several times it pops out tons of them . Even if I click to remember my choice or aproove, it still pop out hundreds of them... What should I do? I tried different Opera versions - 12.14 , 12. 15 , 12.16 , 12.17 and 15. The last version doesn't have any bookmarks options to put them on the left well organised. so I wanted to keep using opera 12.16 , but this problem won't let me usit it. The box is like this : " Security Issue : Warning The server's certificate chain is incomplete, ans the signer(s) are not registered. Accept? Server name: [for example] www.google.ro " So it's unbelievable... I tried to search for a solution but I can't find anything. Does somebody else has this problem too? I have it on every computer where Opera is installed. It's very annoying. Is there a way to turn this off or make it to automatically approve these windows?
2014/08/29
[ "https://superuser.com/questions/804761", "https://superuser.com", "https://superuser.com/users/362978/" ]
I know that this should be a comment but I don't have enough privilege. I had myself a problem like that in the past and I recognized that the problem is that my date is not updated.
I just had this problem myself. Make sure your virus scanner (AVG, AVAST, Norton, etc.) is not scanning your email. You have google so turning it off is good because it's simply redundant to scan them again. Google scans all email for you. I'm not sure the root cause, but that will fix your problem. I know I'm a few years too late, but here's hoping that this answer can help others whom are in the same boat!
68,011,222
I need to make an algorithm in which the person types a login and password and he has three attempts, I did a "while x <= 3" (ox has a value of 0) and then an if inside the while with the login and password condition . But how do I stop while asking for login and password 3 times even hitting the login and password on the first or second attempt?
2021/06/16
[ "https://Stackoverflow.com/questions/68011222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You mentioned that you want to load your data without clicking the button and you are putting all the code responsible for retrieving and displaying data inside the OnClickListener of the button. If you want to display data when the app loads, take all the code out of OnClickListener. You are not seeing data until a double click is because, as soon as you click, the data retrieval starts asynchronously and codes keeps running and reaches to setup the recyclerview. But the data is not yet retrieved. That's why the recyclerview is displaying nothing. In your subsequent click on the button, data retrieval is completed and recyclerview is able to display the data. To fix it, we need to wait until the data is retrieved.. This can be achieved by many ways. A quick fix can be calling your `buildRecyclerView()` function at the last line of try block inside `my_func()`.
To fetch data without click take the method call outside the click Listener. ``` my_func(exampleList); ``` Before my\_fun() method run your buildRecyclerView(); method in oncreate. Then in last line of try block notify the adapter of recyclerView to update the data in it.
68,011,222
I need to make an algorithm in which the person types a login and password and he has three attempts, I did a "while x <= 3" (ox has a value of 0) and then an if inside the while with the login and password condition . But how do I stop while asking for login and password 3 times even hitting the login and password on the first or second attempt?
2021/06/16
[ "https://Stackoverflow.com/questions/68011222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You mentioned that you want to load your data without clicking the button and you are putting all the code responsible for retrieving and displaying data inside the OnClickListener of the button. If you want to display data when the app loads, take all the code out of OnClickListener. You are not seeing data until a double click is because, as soon as you click, the data retrieval starts asynchronously and codes keeps running and reaches to setup the recyclerview. But the data is not yet retrieved. That's why the recyclerview is displaying nothing. In your subsequent click on the button, data retrieval is completed and recyclerview is able to display the data. To fix it, we need to wait until the data is retrieved.. This can be achieved by many ways. A quick fix can be calling your `buildRecyclerView()` function at the last line of try block inside `my_func()`.
Simply call your method in `onCreate`. For example : ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mQueue = MySingleton.getInstance(this).getRequestQueue(); exampleList = new ArrayList<>(); thisIsMyFunction(); } public void thisIsMyFunction() { try { my_func(exampleList); buildRecyclerView(); } catch (Exception e) { e.printStackTrace(); } //you can add all the code you want to execute here } ```
53,048,916
I am analyzing the student test data, but before that I want to tidy it. I tried to build a tidy data frame but it seems like the rows are duplicating. Below is my code. ``` library(tidyverse) (Test <- tibble( Student = c("A", "B", "C", "D", "E"), Test1 = c("SAT", "SAT", "SAT", "SAT", "SAT"), Test2 = c("NA", "ACT", "ACT", "ACT", "ACT"), testdate1 = c("7/1/2017", "6/1/2017", "3/1/2017", "2/17/2018", "NA"), testdate2 = c("NA", "NA", "1/1/2016", "12/1/2016", "10/1/2016") )) (Testa <- tibble( Student = c("A", "B", "C", "D", "E"), Test1 = c("SAT", "SAT", "SAT", "SAT", "SAT"), Test2 = c("NA", "ACT", "ACT", "ACT", "ACT") )) (Testb <- tibble( Student = c("A", "B", "C", "D", "E"), testdate1 = c("7/1/2017", "6/1/2017", "3/1/2017", "2/17/2018", "NA"), testdate2 = c("NA", "NA", "1/1/2016", "12/1/2016", "10/1/2016") )) (td1 <- Testa %>% gather(Test1, Test2, key = "Test", value = "Score")) (td2 <- Testb %>% gather(testdate1, testdate2, key = "Dated", value = "Datev")) (tidy <- left_join(td1, td2)) ``` Can anyone please help me solve this issue. Below is the image of how I want to see the data. [![enter image description here](https://i.stack.imgur.com/rug27.png)](https://i.stack.imgur.com/rug27.png)
2018/10/29
[ "https://Stackoverflow.com/questions/53048916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9613842/" ]
It is simple , as you emit event to make footer flag to true. In same way you have to again make one emit and subscribe to make it false. **In your main service... E.x common.service.ts** ``` footerReset = new EventEmitter<any>(); ``` Now when ever you change component or call any API you just have to emit event... ``` this.common.footerReset.emit(); ``` **In footer.component.ts** In constructor... ``` this.common.footerReset().subscribe(() => { this.flag = false; }) ``` This will hide **footer** part. And you also call again emit when you got data from API. So it will automatically enable footer when you got data...
It's because your **ngOnInit** is not firing on your route change , So your code won't execute. I think it's known issue. There are some alternative to execute ngOnInit explicitly.It's explain in the below thread <https://github.com/angular/angular/issues/20112> I would suggest move your code to the constructor , So constructor will call every time when the route change ``` constructor(private service: SharedService) { this.service.footer.emit(); } ``` Also call the change detection explicitly on your app component after subscribe to get the new changes in the model in to the view. It's because subscribe is from RXJS , So angular don't know the model is updated or not , So it won't call change detection. You can do the below tweak to say explicitly to angular something is changes in my model and call the change detection for me ``` constructor(private service: SharedService,private changeDetector: ChangeDetectorRef) { this.service.footer.subscribe(() => { this.flag = true; this.changeDetector.detectChanges(); console.log("Flag is ::: ", this.flag); }) } ``` Here is the working sample <https://stackblitz.com/edit/angular-nd1euj-stackoverflow?file=src/app/app.component.ts>
11,871,962
Hi all Our Maven scripts are currently written to compile/package & deploy in tomcat6 (development) server. This helped us in automating the build-deploy process. Moving forward, we want to do **automated deployments into WAS7 (Websphere 7) server using MAVEN** scripts. Few articles which i read talks about invoking ANT Tasks that could perform deployment to websphere. Could anybody share maven scripts/tags for the same ?
2012/08/08
[ "https://Stackoverflow.com/questions/11871962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538815/" ]
I don't know if that works for WAS 7, but IBM provide support for WAS 6 and Maven integration : * <http://sdudzin.blogspot.fr/2007/09/maven-2-and-websphere-automated-build.html> * <https://www.ibm.com/developerworks/wikis/download/attachments/113607155/RAD_755_MAVEN_0601.pdf?version=1> * [Maven Integration for RAD7.5 along with automatic Websphere compatible EAR creation](https://stackoverflow.com/questions/4972880/maven-integration-for-rad7-5-along-with-automatic-websphere-compatible-ear-creat) * <http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14486753> A (famous) French IT consulting company list compatibilities with the well known **Cargo plugin**, that allow remote control on servers : <http://blog.xebia.fr/2008/11/05/lintegration-continue-avec-cargo/>. But as you can see (even you don't understand french ;D), Websphere is not yes well supported. It won't probably help you, but the main idea is Maven and WAS 7 integration will probably more painful for you that other servers ;)
You can use this plugin <http://code.google.com/p/websphere-maven-plugin/> ``` <plugin> <groupId>Websphere7AM.plugin</groupId> <artifactId>websphere7am-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <defaultCommand> <host>localhost</host> <port>8880</port> </defaultCommand> <commands>  <command> <command>INSTALL</command> <appName>My Application</appName> <earFile>myapp.ear</earFile> <target>WebSphere:cell=myhostNode01Cell,node=myhostNode01,server=server1</target> <description>Install my app</description> </command> </commands> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>was</goal> </goals> </execution> </executions> </plugin> ```
267,375
I've started using Dropbox but I'm finding that my upload speeds are dropping down to the withering pace of 6Kb per second. I have checked my upload speed with [speedtest.net](http://speedtest.net) and I get just under 1Mbs. Is this due to preferences or settings on my install or would this be something out of my control and related to location or ISP?
2011/04/06
[ "https://superuser.com/questions/267375", "https://superuser.com", "https://superuser.com/users/30182/" ]
Check your Preferences. By default, Dropbox doesn't limit download speed, but limits upload speed to whatever they think is sufficient. ![Dropbox preferences: Bandwidth](https://i.stack.imgur.com/Fm25G.png)
The up/down speeds depend on many different variables. Please see [Why is my internet so slow?](https://superuser.com/questions/8392/why-is-my-internet-so-slow) for detailed explanations. As for your question, it's not a common experience. I just tested a 5 mb file and it uploaded just fine, i.e. using the full upload bandwidth. You can also check [status of Dropbox](http://status.dropbox.com/) to see if there's any current problems with servers, locations, app etc.
267,375
I've started using Dropbox but I'm finding that my upload speeds are dropping down to the withering pace of 6Kb per second. I have checked my upload speed with [speedtest.net](http://speedtest.net) and I get just under 1Mbs. Is this due to preferences or settings on my install or would this be something out of my control and related to location or ISP?
2011/04/06
[ "https://superuser.com/questions/267375", "https://superuser.com", "https://superuser.com/users/30182/" ]
Check your Preferences. By default, Dropbox doesn't limit download speed, but limits upload speed to whatever they think is sufficient. ![Dropbox preferences: Bandwidth](https://i.stack.imgur.com/Fm25G.png)
I don't think it's a problem with Dropbox but your Internet connection. Usually the upload speed of your connection is slower than your download speed, using a site like [SpeedTest.net](http://www.speedtest.net) will show you both values and if you can publish them we can have a better idea of what's happening. It would make sense also to take speed tests at different times for comparison and to know if your ISP is overselling the channel and is not delivering the same speed all the time. But if your upload speed is slow there is not much that Dropbox can do about it.
267,375
I've started using Dropbox but I'm finding that my upload speeds are dropping down to the withering pace of 6Kb per second. I have checked my upload speed with [speedtest.net](http://speedtest.net) and I get just under 1Mbs. Is this due to preferences or settings on my install or would this be something out of my control and related to location or ISP?
2011/04/06
[ "https://superuser.com/questions/267375", "https://superuser.com", "https://superuser.com/users/30182/" ]
Check your Preferences. By default, Dropbox doesn't limit download speed, but limits upload speed to whatever they think is sufficient. ![Dropbox preferences: Bandwidth](https://i.stack.imgur.com/Fm25G.png)
It's my experience also, so I moved to Wuala. From my experience Dropbox seems to slow down the speed when you have a lot of files to download (f.e. when you have a new PC that has to download the complete storage once). F.e. when I have to sync only 2-3 files then I get "normal" speeds of 700-800Kb/s. If the number of files to download are f.e. 30.000 then it's slows down to 10-60Kb/s. So it seems like Dropbox is saying "oh you have to download a lot, let's bring down your speed otherwise our server will be tired ..."
4,139,164
How can show arabic numbers in label? better is i say how can i convert en numbers to arabic numbers. like ۱و۲و۳و... iphone
2010/11/09
[ "https://Stackoverflow.com/questions/4139164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498137/" ]
Since Lollipop (API 21) there is [PowerManager#ACTION\_POWER\_SAVE\_MODE\_CHANGED](http://developer.android.com/reference/android/os/PowerManager.html#ACTION_POWER_SAVE_MODE_CHANGED) broadcast intent. So you need just to receive it: --- AndroidManifest.xml: ``` <receiver android:name=".observers.PowerSaveModeReceiver"> <intent-filter> <action android:name="android.os.action.POWER_SAVE_MODE_CHANGED"/> </intent-filter> </receiver> ``` --- PowerSaveModeReceiver.java: ``` public class PowerSaveModeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if (BuildConfig.DEV_LOGS) Log.d(this.getClass().getName(), String.format("onReceive(context = [%s], intent = [%s])", context, intent)); final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm.isPowerSaveMode()) { // do something } else { // do some else } } } ```
> > How can an Android listener be created to perform a task just before entering power save mode? > > > There is no broadcast `Intent` for this. The closest is `ACTION_SCREEN_OFF`. The device will likely fall asleep in the near future after you receive this broadcast. And, you can only listen for this broadcast using a `BroadcastReceiver` registered via `registerReceiver()` in an activity or service or other `Context`. > > Also: what are some of the low power options that can be controlled by this task? > > > I have no idea what this means, sorry.
4,139,164
How can show arabic numbers in label? better is i say how can i convert en numbers to arabic numbers. like ۱و۲و۳و... iphone
2010/11/09
[ "https://Stackoverflow.com/questions/4139164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498137/" ]
The answer above(for API 21 and above) is not exactly right. You should register a receiver in your activity or service like this: ``` BroadcastReceiver powerSaverChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkPowerSaverMode(); } }; IntentFilter filter = new IntentFilter(); filter.addAction("android.os.action.POWER_SAVE_MODE_CHANGED"); registerReceiver(powerSaverChangeReceiver, filter); ``` The reason for this is that receivers in manifest are not triggered by this broadcast. > > ACTION\_POWER\_SAVE\_MODE\_CHANGED > > > Intent that is broadcast when the state of isPowerSaveMode() changes. This broadcast is only sent to registered receivers. > > > I have tested this and it works.
> > How can an Android listener be created to perform a task just before entering power save mode? > > > There is no broadcast `Intent` for this. The closest is `ACTION_SCREEN_OFF`. The device will likely fall asleep in the near future after you receive this broadcast. And, you can only listen for this broadcast using a `BroadcastReceiver` registered via `registerReceiver()` in an activity or service or other `Context`. > > Also: what are some of the low power options that can be controlled by this task? > > > I have no idea what this means, sorry.
4,139,164
How can show arabic numbers in label? better is i say how can i convert en numbers to arabic numbers. like ۱و۲و۳و... iphone
2010/11/09
[ "https://Stackoverflow.com/questions/4139164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498137/" ]
The answer above(for API 21 and above) is not exactly right. You should register a receiver in your activity or service like this: ``` BroadcastReceiver powerSaverChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkPowerSaverMode(); } }; IntentFilter filter = new IntentFilter(); filter.addAction("android.os.action.POWER_SAVE_MODE_CHANGED"); registerReceiver(powerSaverChangeReceiver, filter); ``` The reason for this is that receivers in manifest are not triggered by this broadcast. > > ACTION\_POWER\_SAVE\_MODE\_CHANGED > > > Intent that is broadcast when the state of isPowerSaveMode() changes. This broadcast is only sent to registered receivers. > > > I have tested this and it works.
Since Lollipop (API 21) there is [PowerManager#ACTION\_POWER\_SAVE\_MODE\_CHANGED](http://developer.android.com/reference/android/os/PowerManager.html#ACTION_POWER_SAVE_MODE_CHANGED) broadcast intent. So you need just to receive it: --- AndroidManifest.xml: ``` <receiver android:name=".observers.PowerSaveModeReceiver"> <intent-filter> <action android:name="android.os.action.POWER_SAVE_MODE_CHANGED"/> </intent-filter> </receiver> ``` --- PowerSaveModeReceiver.java: ``` public class PowerSaveModeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if (BuildConfig.DEV_LOGS) Log.d(this.getClass().getName(), String.format("onReceive(context = [%s], intent = [%s])", context, intent)); final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm.isPowerSaveMode()) { // do something } else { // do some else } } } ```
759,105
I have a computer (HP Pavilion g6-2342dx) which came with Windows 8, and thus the new UEFI boot system. I would like to install a few OS's which are not EFI compatible, and Arch GNU/Linux with BIOS mode. However, I would not like to completely wipe all my files to set to legacy. My preferred options would be to: 1. Multiboot legacy OS alongside my EFI os 2. Convert Windows 8 and Ubuntu to legacy without reformatting or switching to MSDOS part table. If anyone could suggest a solution or a method, your help would be appreciated! Thanks!
2014/05/27
[ "https://superuser.com/questions/759105", "https://superuser.com", "https://superuser.com/users/293521/" ]
AFAIK, the easiest way to do this is to use my [rEFInd boot manager,](http://www.rodsbooks.com/refind/) which enables switching between EFI-mode and BIOS-mode booting. You'll need to uncomment the `scanfor` option in `refind.conf` and ensure that `hdbios` is among the options. Also, be sure to use the latest version; pre-0.8.0 versions had weak BIOS-mode support on PCs, and I made some improvements in 0.8.1 (the latest as I write) that are worth having. That said, many BIOS-only OSes won't boot from a GPT disk, which means you'll need at least two physical hard disks to do the job. You should be able to do it with one disk if your BIOS-mode OSes all support GPT, though. (Linux and FreeBSD both do, for instance.) Also, I don't see much point to booting Linux in BIOS mode if you're dual-booting with an EFI-mode OS *unless* you have specific problems with EFI-mode booting. (Proprietary video drivers sometimes have problems in EFI mode, for instance.) You'll boot more quickly in EFI mode, and you'll have more choices in boot loaders and boot managers. If you use rEFInd to select the boot mode, booting in EFI mode means you can eliminate GRUB and all its flakiness. (I'm not a fan of GRUB.) Converting Windows from EFI-mode to BIOS-mode booting is another possibility, but I know of no site that documents the process. It would be the opposite of the procedure described [on this page,](https://gitorious.org/tianocore_uefi_duet_builds/pages/Windows_x64_BIOS_to_UEFI) though -- that page describes how to convert from MBR/BIOS-mode booting to GPT/EFI-mode booting.
There are many solutions to this when you Google "Disable Secure Boot UEFI". I usually direct people to the HowToGeek article which gives a lot of details about the Why behind Secure Boot mechanics as well as How. [How to Boot and Install Linux on a UEFI PC With Secure Boot](http://www.howtogeek.com/175641/how-to-boot-and-install-linux-on-a-uefi-pc-with-secure-boot/) One option that it lists that you may not have thought about is booting from a removable USB hard disk or thumb drive.
759,105
I have a computer (HP Pavilion g6-2342dx) which came with Windows 8, and thus the new UEFI boot system. I would like to install a few OS's which are not EFI compatible, and Arch GNU/Linux with BIOS mode. However, I would not like to completely wipe all my files to set to legacy. My preferred options would be to: 1. Multiboot legacy OS alongside my EFI os 2. Convert Windows 8 and Ubuntu to legacy without reformatting or switching to MSDOS part table. If anyone could suggest a solution or a method, your help would be appreciated! Thanks!
2014/05/27
[ "https://superuser.com/questions/759105", "https://superuser.com", "https://superuser.com/users/293521/" ]
It is possible. I have an option in my BIOS to either boot UEFI first or Legacy first. I have installed Ubuntu in UEFI mode from a USB live disk (first) and Windows 7 not in UEFI (MBR) from a DVD. This has resulted in 2 x 100mb partitions and I can switch OS's via the BIOS. I found this accidentally but it works. As neither OS realises it is in a dual boot system it might even possible to add more OS's, I won't be testing this, just happy to finally have dual boot working.
There are many solutions to this when you Google "Disable Secure Boot UEFI". I usually direct people to the HowToGeek article which gives a lot of details about the Why behind Secure Boot mechanics as well as How. [How to Boot and Install Linux on a UEFI PC With Secure Boot](http://www.howtogeek.com/175641/how-to-boot-and-install-linux-on-a-uefi-pc-with-secure-boot/) One option that it lists that you may not have thought about is booting from a removable USB hard disk or thumb drive.
33,543,003
I want to calculate total number of working days in between two date. Here we include second and fourth Saturday as working day(i.e all Even Saturdays are considered as Holiday) I can get the day of the particular date by using below code ``` $day = ‘2015-11-07’; $dayName = date("l",strtotime($day)); if ($dayName =='saturday') { ... } ``` then I have to find whether that particular date falls under first Saturday of November or second Saturday. Is there any option in doing that? I have the code to calculate total number of days excluding all Saturdays,Sunday and holidays. I got that code from [another question](https://stackoverflow.com/questions/336127/calculate-business-days) But I want to identify even saturdays and I will detect that saturdays in total days.
2015/11/05
[ "https://Stackoverflow.com/questions/33543003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259939/" ]
Use list comprehension: ``` [x for x in list1 if x in list2] ``` This returns me this list for your data: ``` [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] ```
If order is not important and you don't need to worry about duplicates then you can use set intersection: ``` a = [1,2,3,4,5] b = [1,3,5,6] list(set(a) & set(b)) [1, 3, 5] ```
33,543,003
I want to calculate total number of working days in between two date. Here we include second and fourth Saturday as working day(i.e all Even Saturdays are considered as Holiday) I can get the day of the particular date by using below code ``` $day = ‘2015-11-07’; $dayName = date("l",strtotime($day)); if ($dayName =='saturday') { ... } ``` then I have to find whether that particular date falls under first Saturday of November or second Saturday. Is there any option in doing that? I have the code to calculate total number of days excluding all Saturdays,Sunday and holidays. I got that code from [another question](https://stackoverflow.com/questions/336127/calculate-business-days) But I want to identify even saturdays and I will detect that saturdays in total days.
2015/11/05
[ "https://Stackoverflow.com/questions/33543003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259939/" ]
The solution below might perform better for large lists but might also need more memory due to the sorting step. The intersection can either be done over a defined sortKey e.g. 'count' or the the hash of the dictionary will be used as suggested by <https://stackoverflow.com/a/60765557/1497139>. The algorithm sorts the two lists and iterates in parallel checking for the three possible states of the two iterators: * first iterator behind second -> progress first iterator * second iterator behind first -> progress second iterator * both at same position -> found an intersection element In the given example using the "count" field as a sortKey gives the same reuslt as using the dict hashes as keys. ``` [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] ``` **python unit test** ``` def testIntersection(self): ''' test creating the intersection of a list of dictionaries ''' list1 = [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 332, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 336, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 309, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] list2 = [{'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 381, 'evt_datetime': datetime.datetime(2015, 10, 22, 8, 45), 'att_value': 'red'}] listi=ListOfDict.intersect(list1, list2,'count') print(listi) self.assertEquals(2,len(listi)) listi=ListOfDict.intersect(list1, list2) print(listi) self.assertEquals(2,len(listi)) ``` **ListOfDict** ``` ''' Created on 2020-08-11 @author: wf ''' class ListOfDict(object): ''' https://stackoverflow.com/questions/33542997/python-intersection-of-2-lists-of-dictionaries/33543164 ''' @staticmethod def sortKey(d,key=None): ''' get the sort key for the given dict d with the given key ''' if key is None: # https://stackoverflow.com/a/60765557/1497139 return hash(tuple(d.items())) else: return d[key] @staticmethod def intersect(listOfDict1,listOfDict2,key=None): ''' get the intersection lf the two lists of Dicts by the given key ''' i1=iter(sorted(listOfDict1, key=lambda k: ListOfDict.sortKey(k, key))) i2=iter(sorted(listOfDict2, key=lambda k: ListOfDict.sortKey(k, key))) c1=next(i1) c2=next(i2) lr=[] while True: try: val1=ListOfDict.sortKey(c1,key) val2=ListOfDict.sortKey(c2,key) if val1<val2: c1=next(i1) elif val1>val2: c2=next(i2) else: lr.append(c1) c1=next(i1) c2=next(i2) except StopIteration: break return lr ```
If order is not important and you don't need to worry about duplicates then you can use set intersection: ``` a = [1,2,3,4,5] b = [1,3,5,6] list(set(a) & set(b)) [1, 3, 5] ```
33,543,003
I want to calculate total number of working days in between two date. Here we include second and fourth Saturday as working day(i.e all Even Saturdays are considered as Holiday) I can get the day of the particular date by using below code ``` $day = ‘2015-11-07’; $dayName = date("l",strtotime($day)); if ($dayName =='saturday') { ... } ``` then I have to find whether that particular date falls under first Saturday of November or second Saturday. Is there any option in doing that? I have the code to calculate total number of days excluding all Saturdays,Sunday and holidays. I got that code from [another question](https://stackoverflow.com/questions/336127/calculate-business-days) But I want to identify even saturdays and I will detect that saturdays in total days.
2015/11/05
[ "https://Stackoverflow.com/questions/33543003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259939/" ]
Use list comprehension: ``` [x for x in list1 if x in list2] ``` This returns me this list for your data: ``` [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] ```
The solution below might perform better for large lists but might also need more memory due to the sorting step. The intersection can either be done over a defined sortKey e.g. 'count' or the the hash of the dictionary will be used as suggested by <https://stackoverflow.com/a/60765557/1497139>. The algorithm sorts the two lists and iterates in parallel checking for the three possible states of the two iterators: * first iterator behind second -> progress first iterator * second iterator behind first -> progress second iterator * both at same position -> found an intersection element In the given example using the "count" field as a sortKey gives the same reuslt as using the dict hashes as keys. ``` [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] ``` **python unit test** ``` def testIntersection(self): ''' test creating the intersection of a list of dictionaries ''' list1 = [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 332, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 336, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 309, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}] list2 = [{'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 381, 'evt_datetime': datetime.datetime(2015, 10, 22, 8, 45), 'att_value': 'red'}] listi=ListOfDict.intersect(list1, list2,'count') print(listi) self.assertEquals(2,len(listi)) listi=ListOfDict.intersect(list1, list2) print(listi) self.assertEquals(2,len(listi)) ``` **ListOfDict** ``` ''' Created on 2020-08-11 @author: wf ''' class ListOfDict(object): ''' https://stackoverflow.com/questions/33542997/python-intersection-of-2-lists-of-dictionaries/33543164 ''' @staticmethod def sortKey(d,key=None): ''' get the sort key for the given dict d with the given key ''' if key is None: # https://stackoverflow.com/a/60765557/1497139 return hash(tuple(d.items())) else: return d[key] @staticmethod def intersect(listOfDict1,listOfDict2,key=None): ''' get the intersection lf the two lists of Dicts by the given key ''' i1=iter(sorted(listOfDict1, key=lambda k: ListOfDict.sortKey(k, key))) i2=iter(sorted(listOfDict2, key=lambda k: ListOfDict.sortKey(k, key))) c1=next(i1) c2=next(i2) lr=[] while True: try: val1=ListOfDict.sortKey(c1,key) val2=ListOfDict.sortKey(c2,key) if val1<val2: c1=next(i1) elif val1>val2: c2=next(i2) else: lr.append(c1) c1=next(i1) c2=next(i2) except StopIteration: break return lr ```
27,158,252
i'm not to bad at javascript myself but i am wondering for a few days at this moment wheter it's possible or not. And if it is, who can help me ? *i need to build a single page application , and i am at the early phase. now one part where i am stuck at the moment is.* **i wish to load different kind of questions into a canvas.** => java of the canvas ``` var Question = 'questions'; //<= **this is the part that needs to be corrected** var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = 'italic 18px Arial'; ctx.textAlign = 'center'; ctx. textBaseline = 'middle'; ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values ctx.fillText(Question,100,50)// text and position ``` to be more clear. i have let's say 10 questions. i want to load them one by one into the canvas by clicking a button. **but i can't figure out how to load .txt files into the canvas can anyone PLEASE help me ?** thanx in advance , any help would be much appriciated
2014/11/26
[ "https://Stackoverflow.com/questions/27158252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3436769/" ]
You need to issue AJAX GET request, load text file data, and use response text as a question. Something like this: ``` var request = new XMLHttpRequest(); request.open('GET', 'question.txt', true); request.onload = function() { if (request.status >= 200 && request.status < 400){ var Question = request.responseText; ctx.fillText(Question, 100, 50) } }; request.send(); ``` This is a basic idea. I guess, depending on file contents you might want to process response text somehow before rendering on the canvas. ### Demo: <http://plnkr.co/edit/3OX8xI7h43CSlcuWowQ5?p=preview>
You just need 1) a list of questions and 2) to reset the canvas when setting a new question: ``` var questionIndex = 0; var questions = [ "question 1", "question 2", "question 3" ]; function nextQuestion() { var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.font = 'italic 18px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values ctx.fillText(questions[questionIndex++], 100, 50)// text and position if (questionIndex > questions.length - 1) { questionIndex = 0; } } ``` .. ``` <canvas id="myCanvas"></canvas> <input type="button" id="btnNext" onclick="nextQuestion()" value="Next Question" /> ``` <http://jsfiddle.net/oehq2c0p/>
38,240,502
Good day, I have a model class like below ``` public class EmployeeModel { [Key] public int employeeId{get;set;} public string Fullname {get;set;} public string Address{get;set;} public ICollection<PaymentModel> Payments {get;set;} } public class PaymentModel { [Key] public int PaymentId{get; set;} public int employeeId{get; set;} public decimal PaymentAmount{get; set;} public int IsPosted {get; set;} public virtual EmployeeModel Employee {get; set;} } ``` i just want to query the list of employee together with their list of payments using linq. so i code like this: ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include("Payments") select d; ``` this listing show the all of the employee and all its payments. but i need to filter each employee Payments that IsPosted = 1 so as initial answer, ill do this code; ``` dbcontext db = new dbcontext(); List<EmployeeModel> FinalList = new List<EmployeeModel>(); var listingofEmp = db.employee.ToList(); foreach(EmployeeModel emp in listingofEmp){ emp.Payments= db.payments.where(x => x.IsPosted == 1).ToList(); FinalList.Add(emp); } ``` my Question is, is ther any other way to code it much easier? something like this. ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include(d => x.Payments.IsPosted == 1) select d; ``` im curently using entityframework 5 ive research regarding it not work for me [Link](https://www.google.com.ph/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=how%20to%20filter%20child%20collections%20in%20linq&oq=how%20to%20filter%20child%20collec&aqs=chrome.1.69i57j0j69i60l2.8926j0j7) Hope someone will help me Thanks In Advance Guys
2016/07/07
[ "https://Stackoverflow.com/questions/38240502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5545309/" ]
it colud be a good alternative ``` var listing = from d in db.Payments .include("Employees") .where d.IsPosted == 1 select d.Employees; ``` (not tested, then please fix mistakes) start from pyaments, filter for is posted=1 , then select related emplyees
Try something like this: It will give you a list of anonymous type that will hold the employee and it's payments. ``` using (dbcontext ctx = new dbcontext()) { ctx.Connection.Open(); var result = (from e in ctx.Employees join p in ctx.Payments on e.employeeId equals p.employeeId where p.IsPosted == 1 select new { Employee = e, Payments = p }).ToList(); ctx.Connection.Close(); } ```
38,240,502
Good day, I have a model class like below ``` public class EmployeeModel { [Key] public int employeeId{get;set;} public string Fullname {get;set;} public string Address{get;set;} public ICollection<PaymentModel> Payments {get;set;} } public class PaymentModel { [Key] public int PaymentId{get; set;} public int employeeId{get; set;} public decimal PaymentAmount{get; set;} public int IsPosted {get; set;} public virtual EmployeeModel Employee {get; set;} } ``` i just want to query the list of employee together with their list of payments using linq. so i code like this: ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include("Payments") select d; ``` this listing show the all of the employee and all its payments. but i need to filter each employee Payments that IsPosted = 1 so as initial answer, ill do this code; ``` dbcontext db = new dbcontext(); List<EmployeeModel> FinalList = new List<EmployeeModel>(); var listingofEmp = db.employee.ToList(); foreach(EmployeeModel emp in listingofEmp){ emp.Payments= db.payments.where(x => x.IsPosted == 1).ToList(); FinalList.Add(emp); } ``` my Question is, is ther any other way to code it much easier? something like this. ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include(d => x.Payments.IsPosted == 1) select d; ``` im curently using entityframework 5 ive research regarding it not work for me [Link](https://www.google.com.ph/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=how%20to%20filter%20child%20collections%20in%20linq&oq=how%20to%20filter%20child%20collec&aqs=chrome.1.69i57j0j69i60l2.8926j0j7) Hope someone will help me Thanks In Advance Guys
2016/07/07
[ "https://Stackoverflow.com/questions/38240502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5545309/" ]
What are you asking for is not natively supported, so there is no easier way, but for sure there is more efficient way because your current code is performing N + 1 database queries. A better way could be to retrieve employees and related filtered payments with one database query using anonymous type projection, and then do something similar to your approach to create the final result in memory. For instance: ``` var listing = db.Employees.Select(employee => new { employee, payments = employee.Payments.Where(p => p.IsPosted == 1) }) .AsEnumerable() // Switch to LINQ to Objects .Select(r => { r.employee.Payments = r.payments.ToList(); return r.employee; }) .ToList(); ```
it colud be a good alternative ``` var listing = from d in db.Payments .include("Employees") .where d.IsPosted == 1 select d.Employees; ``` (not tested, then please fix mistakes) start from pyaments, filter for is posted=1 , then select related emplyees
38,240,502
Good day, I have a model class like below ``` public class EmployeeModel { [Key] public int employeeId{get;set;} public string Fullname {get;set;} public string Address{get;set;} public ICollection<PaymentModel> Payments {get;set;} } public class PaymentModel { [Key] public int PaymentId{get; set;} public int employeeId{get; set;} public decimal PaymentAmount{get; set;} public int IsPosted {get; set;} public virtual EmployeeModel Employee {get; set;} } ``` i just want to query the list of employee together with their list of payments using linq. so i code like this: ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include("Payments") select d; ``` this listing show the all of the employee and all its payments. but i need to filter each employee Payments that IsPosted = 1 so as initial answer, ill do this code; ``` dbcontext db = new dbcontext(); List<EmployeeModel> FinalList = new List<EmployeeModel>(); var listingofEmp = db.employee.ToList(); foreach(EmployeeModel emp in listingofEmp){ emp.Payments= db.payments.where(x => x.IsPosted == 1).ToList(); FinalList.Add(emp); } ``` my Question is, is ther any other way to code it much easier? something like this. ``` dbcontext db = new dbcontext(); var listing = from d in db.Employees .include(d => x.Payments.IsPosted == 1) select d; ``` im curently using entityframework 5 ive research regarding it not work for me [Link](https://www.google.com.ph/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=how%20to%20filter%20child%20collections%20in%20linq&oq=how%20to%20filter%20child%20collec&aqs=chrome.1.69i57j0j69i60l2.8926j0j7) Hope someone will help me Thanks In Advance Guys
2016/07/07
[ "https://Stackoverflow.com/questions/38240502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5545309/" ]
What are you asking for is not natively supported, so there is no easier way, but for sure there is more efficient way because your current code is performing N + 1 database queries. A better way could be to retrieve employees and related filtered payments with one database query using anonymous type projection, and then do something similar to your approach to create the final result in memory. For instance: ``` var listing = db.Employees.Select(employee => new { employee, payments = employee.Payments.Where(p => p.IsPosted == 1) }) .AsEnumerable() // Switch to LINQ to Objects .Select(r => { r.employee.Payments = r.payments.ToList(); return r.employee; }) .ToList(); ```
Try something like this: It will give you a list of anonymous type that will hold the employee and it's payments. ``` using (dbcontext ctx = new dbcontext()) { ctx.Connection.Open(); var result = (from e in ctx.Employees join p in ctx.Payments on e.employeeId equals p.employeeId where p.IsPosted == 1 select new { Employee = e, Payments = p }).ToList(); ctx.Connection.Close(); } ```
40,473,360
This is a conceptual question, so I am not providing the "working code" for this reason. Imagine one has two std::vector of different types and different number of entities, just for example: ``` vector <int> A; vector <string> B; ``` One has a set of rules following which one can associate any members of A with some(or none) of the members of B. Is there a way to "store" this connection? I was thinking that one of the ways to do so is having a `vector <map <int, vector <string> > >` or `vector <map <int, vector <string*> > >`, but this solutions seems to me unreliable (if A contains two same numbers for example) and I assume there are much more elegant solutions somewhere there.
2016/11/07
[ "https://Stackoverflow.com/questions/40473360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152072/" ]
A `std::multiset` of `std::pair`s would be able to map multiple `int*`s to zero or more `std::string*`s: ``` std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B; ``` Example: ``` #include <set> #include <vector> #include <string> #include <utility> #include <iostream> int main() { std::vector<int> A{3,3,1,5}; std::vector<std::string> B{"three a", "three b", "one", "five", "unknown"}; std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B{ {&A[0],{&B[0],&B[1]}}, {&A[1],{&B[0],&B[1],&B[4]}}, {&A[2],{&B[2]}}, {&A[3],{&B[3]}}, }; for(auto e : map_A_to_B) { for(auto s : e.second) { std::cout << *e.first << " linked to " << *s << '\n'; } std::cout << "------------------------------\n"; } } ``` produces: ``` 3 linked to three a 3 linked to three b ------------------------------ 3 linked to three a 3 linked to three b 3 linked to unknown ------------------------------ 1 linked to one ------------------------------ 5 linked to five ------------------------------ ```
Based on your comment, it seems like you want an actual mapping (as in math, from a set A to a set B) that is general (not one-to-one or onto). First you have to conceptually understand what you want. First, you want a mapping between a class A (say int in your example) to B (string). Let's template this: ``` template <class From, class To> bool isMapped(From A,To B) { return (//Code representing mapping,say check if A=int->char is in B=string) } ``` Now the mapping of a `From` value to a `To` vector is (in math terms) the range in "To" which is reachable (`isMapped`) form this value: ``` template<class From, class To> List<To>& getRange(From value, To range) { List<To> result(); for (const auto& toValue : range) { if(isMapped(value,toValue) result.push_back(toValue); return result; ``` This will return the range the `From` value is mapped to in the `To` vector, with duplicates if they appear more than once in the range. Another option (maybe better) would be to iterate over indices instead of values in the range, and return a Boolean vector of the length of `range` with `true` in the indices where From is mapped to. Similarly you would need to define the opposite mapping. Probably you couldn't make this completely general, and maybe even templates won't fit this simply - you would need to give more specifics. So concluding, the mapping from A to B would be a vector of length of vector A (the domain) of vectors of length B (domain) with True/False in the relevant indices. There are of course, more possibilities.
40,473,360
This is a conceptual question, so I am not providing the "working code" for this reason. Imagine one has two std::vector of different types and different number of entities, just for example: ``` vector <int> A; vector <string> B; ``` One has a set of rules following which one can associate any members of A with some(or none) of the members of B. Is there a way to "store" this connection? I was thinking that one of the ways to do so is having a `vector <map <int, vector <string> > >` or `vector <map <int, vector <string*> > >`, but this solutions seems to me unreliable (if A contains two same numbers for example) and I assume there are much more elegant solutions somewhere there.
2016/11/07
[ "https://Stackoverflow.com/questions/40473360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152072/" ]
A `std::multiset` of `std::pair`s would be able to map multiple `int*`s to zero or more `std::string*`s: ``` std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B; ``` Example: ``` #include <set> #include <vector> #include <string> #include <utility> #include <iostream> int main() { std::vector<int> A{3,3,1,5}; std::vector<std::string> B{"three a", "three b", "one", "five", "unknown"}; std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B{ {&A[0],{&B[0],&B[1]}}, {&A[1],{&B[0],&B[1],&B[4]}}, {&A[2],{&B[2]}}, {&A[3],{&B[3]}}, }; for(auto e : map_A_to_B) { for(auto s : e.second) { std::cout << *e.first << " linked to " << *s << '\n'; } std::cout << "------------------------------\n"; } } ``` produces: ``` 3 linked to three a 3 linked to three b ------------------------------ 3 linked to three a 3 linked to three b 3 linked to unknown ------------------------------ 1 linked to one ------------------------------ 5 linked to five ------------------------------ ```
You could use Boost to implement a [bidirectional map](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/examples.html) - that would allow you to use either of the values as a key. [Here is an example of how to use it](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/example/bimap.cpp). But, in short: (usage only, without definitions) ``` struct from {}; // tag for boost typedef bidirectional_map<int, std::string>::type bi_map; bi_map values; values.insert(bi_map::value_type(123, "{")); // ... // ... bi_map::iterator it = values.get<from>().find(123); if (it != values.end()) { cout << "Char #123 is " << it->second << endl; // and in the opposite case, where "it" is the result of: // values.get<to>().find("{") // it->second would be 123, so you have access to both items } ```
40,473,360
This is a conceptual question, so I am not providing the "working code" for this reason. Imagine one has two std::vector of different types and different number of entities, just for example: ``` vector <int> A; vector <string> B; ``` One has a set of rules following which one can associate any members of A with some(or none) of the members of B. Is there a way to "store" this connection? I was thinking that one of the ways to do so is having a `vector <map <int, vector <string> > >` or `vector <map <int, vector <string*> > >`, but this solutions seems to me unreliable (if A contains two same numbers for example) and I assume there are much more elegant solutions somewhere there.
2016/11/07
[ "https://Stackoverflow.com/questions/40473360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152072/" ]
You could implement some *database* techniques: indices. Place your data into a single `vector` then create `std::map` for each way you want to index your data or relate the data. Rather than 2 vectors, make one vector of structures: ``` struct Datum { int value; string text; }; // The database std::vector<Datum> database; // An index table by integer std::map<int, // Key unsigned int vector_index> index_by_value; // An index table, by text std::map<std::string, // Key unsigned int index_into_vector> index_by text; ``` The index tables give you a quick method to find things in the database, without having to sort the database.
A `std::multiset` of `std::pair`s would be able to map multiple `int*`s to zero or more `std::string*`s: ``` std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B; ``` Example: ``` #include <set> #include <vector> #include <string> #include <utility> #include <iostream> int main() { std::vector<int> A{3,3,1,5}; std::vector<std::string> B{"three a", "three b", "one", "five", "unknown"}; std::multiset < std::pair<int*, std::vector<std::string*>>> map_A_to_B{ {&A[0],{&B[0],&B[1]}}, {&A[1],{&B[0],&B[1],&B[4]}}, {&A[2],{&B[2]}}, {&A[3],{&B[3]}}, }; for(auto e : map_A_to_B) { for(auto s : e.second) { std::cout << *e.first << " linked to " << *s << '\n'; } std::cout << "------------------------------\n"; } } ``` produces: ``` 3 linked to three a 3 linked to three b ------------------------------ 3 linked to three a 3 linked to three b 3 linked to unknown ------------------------------ 1 linked to one ------------------------------ 5 linked to five ------------------------------ ```
40,473,360
This is a conceptual question, so I am not providing the "working code" for this reason. Imagine one has two std::vector of different types and different number of entities, just for example: ``` vector <int> A; vector <string> B; ``` One has a set of rules following which one can associate any members of A with some(or none) of the members of B. Is there a way to "store" this connection? I was thinking that one of the ways to do so is having a `vector <map <int, vector <string> > >` or `vector <map <int, vector <string*> > >`, but this solutions seems to me unreliable (if A contains two same numbers for example) and I assume there are much more elegant solutions somewhere there.
2016/11/07
[ "https://Stackoverflow.com/questions/40473360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152072/" ]
You could implement some *database* techniques: indices. Place your data into a single `vector` then create `std::map` for each way you want to index your data or relate the data. Rather than 2 vectors, make one vector of structures: ``` struct Datum { int value; string text; }; // The database std::vector<Datum> database; // An index table by integer std::map<int, // Key unsigned int vector_index> index_by_value; // An index table, by text std::map<std::string, // Key unsigned int index_into_vector> index_by text; ``` The index tables give you a quick method to find things in the database, without having to sort the database.
Based on your comment, it seems like you want an actual mapping (as in math, from a set A to a set B) that is general (not one-to-one or onto). First you have to conceptually understand what you want. First, you want a mapping between a class A (say int in your example) to B (string). Let's template this: ``` template <class From, class To> bool isMapped(From A,To B) { return (//Code representing mapping,say check if A=int->char is in B=string) } ``` Now the mapping of a `From` value to a `To` vector is (in math terms) the range in "To" which is reachable (`isMapped`) form this value: ``` template<class From, class To> List<To>& getRange(From value, To range) { List<To> result(); for (const auto& toValue : range) { if(isMapped(value,toValue) result.push_back(toValue); return result; ``` This will return the range the `From` value is mapped to in the `To` vector, with duplicates if they appear more than once in the range. Another option (maybe better) would be to iterate over indices instead of values in the range, and return a Boolean vector of the length of `range` with `true` in the indices where From is mapped to. Similarly you would need to define the opposite mapping. Probably you couldn't make this completely general, and maybe even templates won't fit this simply - you would need to give more specifics. So concluding, the mapping from A to B would be a vector of length of vector A (the domain) of vectors of length B (domain) with True/False in the relevant indices. There are of course, more possibilities.
40,473,360
This is a conceptual question, so I am not providing the "working code" for this reason. Imagine one has two std::vector of different types and different number of entities, just for example: ``` vector <int> A; vector <string> B; ``` One has a set of rules following which one can associate any members of A with some(or none) of the members of B. Is there a way to "store" this connection? I was thinking that one of the ways to do so is having a `vector <map <int, vector <string> > >` or `vector <map <int, vector <string*> > >`, but this solutions seems to me unreliable (if A contains two same numbers for example) and I assume there are much more elegant solutions somewhere there.
2016/11/07
[ "https://Stackoverflow.com/questions/40473360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152072/" ]
You could implement some *database* techniques: indices. Place your data into a single `vector` then create `std::map` for each way you want to index your data or relate the data. Rather than 2 vectors, make one vector of structures: ``` struct Datum { int value; string text; }; // The database std::vector<Datum> database; // An index table by integer std::map<int, // Key unsigned int vector_index> index_by_value; // An index table, by text std::map<std::string, // Key unsigned int index_into_vector> index_by text; ``` The index tables give you a quick method to find things in the database, without having to sort the database.
You could use Boost to implement a [bidirectional map](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/examples.html) - that would allow you to use either of the values as a key. [Here is an example of how to use it](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/example/bimap.cpp). But, in short: (usage only, without definitions) ``` struct from {}; // tag for boost typedef bidirectional_map<int, std::string>::type bi_map; bi_map values; values.insert(bi_map::value_type(123, "{")); // ... // ... bi_map::iterator it = values.get<from>().find(123); if (it != values.end()) { cout << "Char #123 is " << it->second << endl; // and in the opposite case, where "it" is the result of: // values.get<to>().find("{") // it->second would be 123, so you have access to both items } ```
16,188,971
I have a array in java script ``` var aaa = ["school1,100"],["school2,101"],["school3,103"] ``` I want to bind this array to Multiselect Listbox of razor page. Any one can help me ?
2013/04/24
[ "https://Stackoverflow.com/questions/16188971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1498159/" ]
You have to use jQuery for binding Javascript array to the listbox. Below code will help you to bind JS Array to listbox. **JAVASCRIPT** ``` $(document).ready(function () { var aaa = ["school1,100", "school2,101", "school3,103"] for (var i = 0; i < aaa.length; i++) { $('#listbox').append('<option>' + aaa[i] + '</option>'); } }); ``` **HTML** ``` <select id="listbox" size="5"></select> ```
``` <select id="listbox" size="5"></select> ``` JS: ``` var select = document.getElementById('listbox'); addOptions(select, aaa); function addOptions(el, ar){ for(var i = 0; i < ar.length; i++){ var option = document.createElement('option'); option.innerHTML = ar[i]; el.appendChild(option); } } ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
A concise solution: ``` location.search .slice(1) .split('&') .map(p => p.split('=')) .reduce((obj, pair) => { const [key, value] = pair.map(decodeURIComponent); obj[key] = value; return obj; }, {}); ```
Using phpjs ``` function parse_str(str, array) { // discuss at: http://phpjs.org/functions/parse_str/ // original by: Cagri Ekin // improved by: Michael White (http://getsprink.com) // improved by: Jack // improved by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Onno Marsman // bugfixed by: Brett Zamir (http://brett-zamir.me) // bugfixed by: stag019 // bugfixed by: Brett Zamir (http://brett-zamir.me) // bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/) // reimplemented by: stag019 // input by: Dreamer // input by: Zaide (http://zaidesthings.com/) // input by: David Pesta (http://davidpesta.com/) // input by: jeicquest // note: When no argument is specified, will put variables in global scope. // note: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c // test: skip // example 1: var arr = {}; // example 1: parse_str('first=foo&second=bar', arr); // example 1: $result = arr // returns 1: { first: 'foo', second: 'bar' } // example 2: var arr = {}; // example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr); // example 2: $result = arr // returns 2: { str_a: "Jack and Jill didn't see the well." } // example 3: var abc = {3:'a'}; // example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5'); // returns 3: {"3":"a","a":{"b":{"c":"def"}},"q":"t 5"} var strArr = String(str) .replace(/^&/, '') .replace(/&$/, '') .split('&'), sal = strArr.length, i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value, postLeftBracketPos, keys, keysLen, fixStr = function(str) { return decodeURIComponent(str.replace(/\+/g, '%20')); }; if (!array) { array = this.window; } for (i = 0; i < sal; i++) { tmp = strArr[i].split('='); key = fixStr(tmp[0]); value = (tmp.length < 2) ? '' : fixStr(tmp[1]); while (key.charAt(0) === ' ') { key = key.slice(1); } if (key.indexOf('\x00') > -1) { key = key.slice(0, key.indexOf('\x00')); } if (key && key.charAt(0) !== '[') { keys = []; postLeftBracketPos = 0; for (j = 0; j < key.length; j++) { if (key.charAt(j) === '[' && !postLeftBracketPos) { postLeftBracketPos = j + 1; } else if (key.charAt(j) === ']') { if (postLeftBracketPos) { if (!keys.length) { keys.push(key.slice(0, postLeftBracketPos - 1)); } keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos)); postLeftBracketPos = 0; if (key.charAt(j + 1) !== '[') { break; } } } } if (!keys.length) { keys = [key]; } for (j = 0; j < keys[0].length; j++) { chr = keys[0].charAt(j); if (chr === ' ' || chr === '.' || chr === '[') { keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1); } if (chr === '[') { break; } } obj = array; for (j = 0, keysLen = keys.length; j < keysLen; j++) { key = keys[j].replace(/^['"]/, '') .replace(/['"]$/, ''); lastIter = j !== keys.length - 1; lastObj = obj; if ((key !== '' && key !== ' ') || j === 0) { if (obj[key] === undef) { obj[key] = {}; } obj = obj[key]; } else { // To insert new dimension ct = -1; for (p in obj) { if (obj.hasOwnProperty(p)) { if (+p > ct && p.match(/^\d+$/g)) { ct = +p; } } } key = ct + 1; } } lastObj[key] = value; } } } ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
Using ES6, URL API and URLSearchParams API. ``` function objectifyQueryString(url) { let _url = new URL(url); let _params = new URLSearchParams(_url.search); let query = Array.from(_params.keys()).reduce((sum, value)=>{ return Object.assign({[value]: _params.get(value)}, sum); }, {}); return query; } ```
Pretty easy using the `URLSearchParams` JavaScript Web API, ```js var paramsString = "abc=foo&def=%5Basf%5D&xyz=5"; //returns an iterator object var searchParams = new URLSearchParams(paramsString); //Usage for (let p of searchParams) { console.log(p); } //Get the query strings console.log(searchParams.toString()); //You can also pass in objects var paramsObject = {abc:"forum",def:"%5Basf%5D",xyz:"5"} //returns an iterator object var searchParams = new URLSearchParams(paramsObject); //Usage for (let p of searchParams) { console.log(p); } //Get the query strings console.log(searchParams.toString()); ``` ##Useful Links * [URLSearchParams - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) * [Easy URL Manipulation with URLSearchParams | Web | Google Developers](https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en) > > **NOTE**: *Not Supported in IE* > > >
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
The proposed solutions I found so far do not cover more complex scenarios. I needed to convert a query string like `https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name` into an object like: ``` { "Target": "Offer", "Method": "findAll", "fields": [ "id", "name", "default_goal_name" ], "filters": { "has_goals_enabled": { "TRUE": "1" }, "status": "active" } } ``` OR: `https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999` INTO: ``` { "Target": "Report", "Method": "getStats", "fields": [ "Offer.name", "Advertiser.company", "Stat.clicks", "Stat.conversions", "Stat.cpa", "Stat.payout", "Stat.date", "Stat.offer_id", "Affiliate.company" ], "groups": [ "Stat.offer_id", "Stat.date" ], "limit": "9999", "filters": { "Stat.affiliate_id": { "conditional": "EQUAL_TO", "values": "1831" } } } ``` I compiled and adapted multiple solutions into one that actually works: ----------------------------------------------------------------------- CODE: ``` var getParamsAsObject = function (query) { query = query.substring(query.indexOf('?') + 1); var re = /([^&=]+)=?([^&]*)/g; var decodeRE = /\+/g; var decode = function (str) { return decodeURIComponent(str.replace(decodeRE, " ")); }; var params = {}, e; while (e = re.exec(query)) { var k = decode(e[1]), v = decode(e[2]); if (k.substring(k.length - 2) === '[]') { k = k.substring(0, k.length - 2); (params[k] || (params[k] = [])).push(v); } else params[k] = v; } var assign = function (obj, keyPath, value) { var lastKeyIndex = keyPath.length - 1; for (var i = 0; i < lastKeyIndex; ++i) { var key = keyPath[i]; if (!(key in obj)) obj[key] = {} obj = obj[key]; } obj[keyPath[lastKeyIndex]] = value; } for (var prop in params) { var structure = prop.split('['); if (structure.length > 1) { var levels = []; structure.forEach(function (item, i) { var key = item.replace(/[?[\]\\ ]/g, ''); levels.push(key); }); assign(params, levels, params[prop]); delete(params[prop]); } } return params; }; ```
I needed to also deal with `+` in the query part of the URL ([decodeURIComponent doesn't](https://stackoverflow.com/questions/4535288/why-doesnt-decodeuriab-a-b)), so I adapted Wolfgang's code to become: ``` var search = location.search.substring(1); search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value)}):{}; ``` In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.: ``` var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value)}); objForm.anyParam += stringToAddToTheParam; var serializedForm = $.param(objForm); ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
I had the same problem, tried the solutions here, but none of them really worked, since I had arrays in the URL parameters, like this: ``` ?param[]=5&param[]=8&othr_param=abc&param[]=string ``` So I ended up writing my own JS function, which makes an array out of the param in URI: ``` /** * Creates an object from URL encoded data */ var createObjFromURI = function() { var uri = decodeURI(location.search.substr(1)); var chunks = uri.split('&'); var params = Object(); for (var i=0; i < chunks.length ; i++) { var chunk = chunks[i].split('='); if(chunk[0].search("\\[\\]") !== -1) { if( typeof params[chunk[0]] === 'undefined' ) { params[chunk[0]] = [chunk[1]]; } else { params[chunk[0]].push(chunk[1]); } } else { params[chunk[0]] = chunk[1]; } } return params; } ```
Many other solutions don't account for edge cases. This one handles * null keys `a=1&b=2&` * null values `a=1&b` * empty values `a=1&b=` * unencoded equals signs `a=1&b=2=3=4` ```js decodeQueryString: qs => { // expects qs to not have a ? // return if empty qs if (qs === '') return {}; return qs.split('&').reduce((acc, pair) => { // skip no param at all a=1&b=2& if (pair.length === 0) return acc; const parts = pair.split('='); // fix params without value if (parts.length === 1) parts[1] = ''; // for value handle multiple unencoded = signs const key = decodeURIComponent(parts[0]); const value = decodeURIComponent(parts.slice(1).join('=')); acc[key] = value; return acc; }, {}); }, ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
There's a lightweight library called [YouAreI.js](https://github.com/purge/youarei.js) that's tested and makes this really easy. ``` YouAreI = require('YouAreI') uri = new YouAreI('http://user:pass@www.example.com:3000/a/b/c?d=dad&e=1&f=12.3#fragment'); uri.query_get() => { d: 'dad', e: '1', f: '12.3' } ```
``` //under ES6 const getUrlParamAsObject = (url = window.location.href) => { let searchParams = url.split('?')[1]; const result = {}; //in case the queryString is empty if (searchParams!==undefined) { const paramParts = searchParams.split('&'); for(let part of paramParts) { let paramValuePair = part.split('='); //exclude the case when the param has no value if(paramValuePair.length===2) { result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]); } } } return result; } ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
I found [$.String.deparam](https://github.com/jupiterjs/jquerymx/blob/master/lang/string/deparam/deparam.js) the most complete pre built solution (can do nested objects etc.). Check out the [documentation](http://javascriptmvc.com/docs.html#!jQuery.String.deparam).
Here's one I use: ``` var params = {}; window.location.search.substring(1).split('&').forEach(function(pair) { pair = pair.split('='); if (pair[1] !== undefined) { var key = decodeURIComponent(pair[0]), val = decodeURIComponent(pair[1]), val = val ? val.replace(/\++/g,' ').trim() : ''; if (key.length === 0) { return; } if (params[key] === undefined) { params[key] = val; } else { if ("function" !== typeof params[key].push) { params[key] = [params[key]]; } params[key].push(val); } } }); console.log(params); ``` Basic usage, eg. `?a=aa&b=bb` `Object {a: "aa", b: "bb"}` Duplicate params, eg. `?a=aa&b=bb&c=cc&c=potato` `Object {a: "aa", b: "bb", c: ["cc","potato"]}` Missing keys, eg. `?a=aa&b=bb&=cc` `Object {a: "aa", b: "bb"}` Missing values, eg. `?a=aa&b=bb&c` `Object {a: "aa", b: "bb"}` The above JSON/regex solutions throw a syntax error on this wacky url: `?a=aa&b=bb&c=&=dd&e` `Object {a: "aa", b: "bb", c: ""}`
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
A concise solution: ``` location.search .slice(1) .split('&') .map(p => p.split('=')) .reduce((obj, pair) => { const [key, value] = pair.map(decodeURIComponent); obj[key] = value; return obj; }, {}); ```
If you are using URI.js, you can use: <https://medialize.github.io/URI.js/docs.html#static-parseQuery> ``` var result = URI.parseQuery("?foo=bar&hello=world&hello=mars&bam=&yup"); result === { foo: "bar", hello: ["world", "mars"], bam: "", yup: null }; ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc): ``` function deparam(paramStr) { let paramArr = paramStr.split('&'); let paramObj = {}; paramArr.forEach(e=>{ let param = e.split('='); paramObj[param[0]] = decodeURIComponent(param[1]); }); return paramObj; } ``` example: ``` deparam('abc=foo&def=%5Basf%5D&xyz=5') ``` returns ``` { abc: "foo" def:"[asf]" xyz :"5" } ``` The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.
Many other solutions don't account for edge cases. This one handles * null keys `a=1&b=2&` * null values `a=1&b` * empty values `a=1&b=` * unencoded equals signs `a=1&b=2=3=4` ```js decodeQueryString: qs => { // expects qs to not have a ? // return if empty qs if (qs === '') return {}; return qs.split('&').reduce((acc, pair) => { // skip no param at all a=1&b=2& if (pair.length === 0) return acc; const parts = pair.split('='); // fix params without value if (parts.length === 1) parts[1] = ''; // for value handle multiple unencoded = signs const key = decodeURIComponent(parts[0]); const value = decodeURIComponent(parts.slice(1).join('=')); acc[key] = value; return acc; }, {}); }, ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
One simple answer with build in native Node module.(No third party npm modules) The querystring module provides utilities for parsing and formatting URL query strings. It can be accessed using: ``` const querystring = require('querystring'); const body = "abc=foo&def=%5Basf%5D&xyz=5" const parseJSON = querystring.parse(body); console.log(parseJSON); ```
Here is a more-streamlined version of [silicakes' approach](https://stackoverflow.com/a/52539264/1762224). The following function(s) can parse a querystring from either a [`USVString`](https://developer.mozilla.org/en-US/docs/Web/API/USVString) or [`Location`](https://developer.mozilla.org/en-US/docs/Web/API/Location). ```js /** * Returns a plain object representation of a URLSearchParams object. * @param {USVString} search - A URL querystring * @return {Object} a key-value pair object from a URL querystring */ const parseSearch = (search) => [...new URLSearchParams(search).entries()] .reduce((acc, [key, val]) => ({ ...acc, // eslint-disable-next-line no-nested-ternary [key]: Object.prototype.hasOwnProperty.call(acc, key) ? Array.isArray(acc[key]) ? [...acc[key], val] : [acc[key], val] : val }), {}); /** * Returns a plain object representation of a URLSearchParams object. * @param {Location} location - Either a document or window location, or React useLocation() * @return {Object} a key-value pair object from a URL querystring */ const parseLocationSearch = (location) => parseSearch(location.search); console.log(parseSearch('?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D')); ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ``` Here is a one-liner of the code above (125 bytes): > > *Where `f` is `parseSearch`* > > > ```js f=s=>[...new URLSearchParams(s).entries()].reduce((a,[k,v])=>({...a,[k]:a[k]?Array.isArray(a[k])?[...a[k],v]:[a[k],v]:v}),{}) ``` --- Edit ---- Here is a method of serializing and updating: ```js const parseSearch = (search) => [...new URLSearchParams(search).entries()] .reduce((acc, [key, val]) => ({ ...acc, // eslint-disable-next-line no-nested-ternary [key]: Object.prototype.hasOwnProperty.call(acc, key) ? Array.isArray(acc[key]) ? [...acc[key], val] : [acc[key], val] : val }), {}); const toQueryString = (params) => `?${Object.entries(params) .flatMap(([key, values]) => Array.isArray(values) ? values.map(value => [key, value]) : [[key, values]]) .map(pair => pair.map(val => encodeURIComponent(val)).join('=')) .join('&')}`; const updateQueryString = (search, update) => (parsed => toQueryString(update instanceof Function ? update(parsed) : { ...parsed, ...update })) (parseSearch(search)); const queryString = '?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D'; const parsedQuery = parseSearch(queryString); console.log(parsedQuery); console.log(toQueryString(parsedQuery) === queryString); const updatedQuerySimple = updateQueryString(queryString, { foo: 'baz', x: 'z', }); console.log(updatedQuerySimple); console.log(parseSearch(updatedQuerySimple)); const updatedQuery = updateQueryString(updatedQuerySimple, parsed => ({ ...parsed, ids: [ ...parsed.ids, JSON.stringify([7,8,9]) ] })); console.log(updatedQuery); console.log(parseSearch(updatedQuery)); ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ```
8,648,892
I have a string like this: ``` abc=foo&def=%5Basf%5D&xyz=5 ``` How can I convert it into a JavaScript object like this? ``` { abc: 'foo', def: '[asf]', xyz: 5 } ```
2011/12/27
[ "https://Stackoverflow.com/questions/8648892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
```js console.log(decodeURI('abc=foo&def=%5Basf%5D&xyz=5') .split('&') .reduce((result, current) => { const [key, value] = current.split('='); result[key] = value; return result }, {})) ```
I needed to also deal with `+` in the query part of the URL ([decodeURIComponent doesn't](https://stackoverflow.com/questions/4535288/why-doesnt-decodeuriab-a-b)), so I adapted Wolfgang's code to become: ``` var search = location.search.substring(1); search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value)}):{}; ``` In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.: ``` var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value)}); objForm.anyParam += stringToAddToTheParam; var serializedForm = $.param(objForm); ```
13,418,173
I want to use jQuery UI on my site. I downloaded custom build, but it didn't work. So I used "full" version from their site. It doesn't work either. My only code is: ``` $('#gameRelease').datepicker(); ``` And what I get is an error in console: ``` Uncaught TypeError: Cannot read property 'fadeIn' of undefined ``` What can I do? -- edit -- Okay, this is getting quite weird. * I **have included** jQuery before jQuery UI. * I have other things using jQuery before my code and they are working well. * I tried disabling other plugins and commenting my previous code - nothing works. Here's my full code (I cutted what's not important): **JS** ``` (function($){})(window.jQuery); $(document).ready(function() { /* jQuery UI */ $('#gameRelease').datepicker(); }) ``` **HTML** ``` <script src="/js/modernizr-1.7.min.js"></script> <script src="//code.jquery.com/jquery-latest.min.js"></script> <script src="/js/jquery-ui-1.9.1.custom.min.js"></script> <script src="/js/script.js"></script> ```
2012/11/16
[ "https://Stackoverflow.com/questions/13418173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409674/" ]
Silly problem. It turns out, that you have to load jQueryUI right after jQuery. And I loaded it later.
The plugin *Nivo Slider for WordPress* (0.2) loads it's own `jquery.effects.core.js` file, which also makes the datepicker throw the same error. If disabling the plugin makes the datepickers work, then you have to edit the `nivoslider4wp-show.php` file. Find the line with `<script ... src=".../js/jquery.effects.core.js" ...`, and comment it out using HTML comments (`<!-- ... -->`).
184,727
I'm trying to get a list output, but I get integer results. Is there a way to convert integers to a list? Here is my code: ``` list = {12, 37, 44, 96}; list2 = IntegerDigits[list]; Do[ list3 = Total[list2[[i]]]; Print[list3]; , {i, 1, Length[list]}] ```
2018/10/26
[ "https://mathematica.stackexchange.com/questions/184727", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/60960/" ]
``` Total /@ IntegerDigits[list] ``` > > {3, 10, 8, 15} > > > Also ``` Total[IntegerDigits[list], {2}] (* thanks: HenrikSchumacher *) Total[Transpose@IntegerDigits[list]] FromDigits[#, 1] & /@ IntegerDigits[list] ``` > > {3, 10, 8, 15} > > >
It does not improve on the previous solutions, but for such manipulations Table is normally enough. For the above lists, ``` Table[Total[list2[[i]]], {i, 1, Length[list]}] ```
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
The HTTP request is sent from Client to port 8080 of the Proxy Server. The Proxy Server then originates a new HTTP request to the destination site. The proxy, depending on the configuration, will often add a "X-Forwarded-For" header to the HTTP request. The log files on the destination web site will show the proxy's IP address, but may or may not be configured to log the "X-Forwarded-For" address. That's the typical configuration, but proxy software will allow you all kinds of customization. EDIT: I should note that when I originally read your question, I got the idea you were asking about an HTTP Proxy specifically, such as squid or nginx. There are many different types of proxies available. In Internet Explorer, you'll most likely be using an HTTP proxy, but there are many other types as well.
There's no such thing as "tcp packet". TCP operates with data streams. There are IP packets. You seem to be lacking some basic knowledge about networking, I suggest you to get a good book about TCP/IP. Everyone's favorite seems to be "TCP/IP illustrated" by W. Richard Stevens. Back to your question. A proxy is a middleman: [you] - [proxy] - [server you want to connect] Now there are two different connections: [you] - (your connection to proxy) - [proxy] - (proxy's connection to server) - [server you want to connect] When you think you're connecting to a server through a proxy, you're actually connecting to the proxy and tell it you want to reach a certain server. Then the proxy opens a second connection from itself to that server and acts as middleman passing data in both directions.
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
The HTTP request is sent from Client to port 8080 of the Proxy Server. The Proxy Server then originates a new HTTP request to the destination site. The proxy, depending on the configuration, will often add a "X-Forwarded-For" header to the HTTP request. The log files on the destination web site will show the proxy's IP address, but may or may not be configured to log the "X-Forwarded-For" address. That's the typical configuration, but proxy software will allow you all kinds of customization. EDIT: I should note that when I originally read your question, I got the idea you were asking about an HTTP Proxy specifically, such as squid or nginx. There are many different types of proxies available. In Internet Explorer, you'll most likely be using an HTTP proxy, but there are many other types as well.
HTTP is a Layer 7 protocol so dont get confuse. when you use a HTTP proxy and you type say google.com , the HTTP header still same google.com, but the destination IP address will be IP address of the Proxy, source will be Hosts IP to the customized port number 8080.
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
The HTTP request is sent from Client to port 8080 of the Proxy Server. The Proxy Server then originates a new HTTP request to the destination site. The proxy, depending on the configuration, will often add a "X-Forwarded-For" header to the HTTP request. The log files on the destination web site will show the proxy's IP address, but may or may not be configured to log the "X-Forwarded-For" address. That's the typical configuration, but proxy software will allow you all kinds of customization. EDIT: I should note that when I originally read your question, I got the idea you were asking about an HTTP Proxy specifically, such as squid or nginx. There are many different types of proxies available. In Internet Explorer, you'll most likely be using an HTTP proxy, but there are many other types as well.
To use an HTTP proxy, the request is sent from the client to the proxy server's IP address rather than to the destination server. **The proxy must then read the HTTP header** to extract the *request-URI*. The request-URI includes the name or IP of the destination server, and the proxy server uses that information to forward the request. The [HTTP specification](https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html) allows the request line to exclude the server name and port when a proxy is not used (since these would be unnecessary if the request was sent directly to that server). But, as per the spec... > > The absoluteURI form is REQUIRED when the request is being made to a proxy. > > > So when not using a proxy, the request line might look like: ``` GET /robots.txt HTTP/1.1 ``` but to use a proxy, the line must include the server name (and port if not 80): ``` GET http://httpbin.org:80/robots.txt HTTP/1.1 ``` --- The response side if the operation can be simpler since the proxy server may simply relay the verbatim response via the pre-established request socket.
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
HTTP is a Layer 7 protocol so dont get confuse. when you use a HTTP proxy and you type say google.com , the HTTP header still same google.com, but the destination IP address will be IP address of the Proxy, source will be Hosts IP to the customized port number 8080.
There's no such thing as "tcp packet". TCP operates with data streams. There are IP packets. You seem to be lacking some basic knowledge about networking, I suggest you to get a good book about TCP/IP. Everyone's favorite seems to be "TCP/IP illustrated" by W. Richard Stevens. Back to your question. A proxy is a middleman: [you] - [proxy] - [server you want to connect] Now there are two different connections: [you] - (your connection to proxy) - [proxy] - (proxy's connection to server) - [server you want to connect] When you think you're connecting to a server through a proxy, you're actually connecting to the proxy and tell it you want to reach a certain server. Then the proxy opens a second connection from itself to that server and acts as middleman passing data in both directions.
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
To use an HTTP proxy, the request is sent from the client to the proxy server's IP address rather than to the destination server. **The proxy must then read the HTTP header** to extract the *request-URI*. The request-URI includes the name or IP of the destination server, and the proxy server uses that information to forward the request. The [HTTP specification](https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html) allows the request line to exclude the server name and port when a proxy is not used (since these would be unnecessary if the request was sent directly to that server). But, as per the spec... > > The absoluteURI form is REQUIRED when the request is being made to a proxy. > > > So when not using a proxy, the request line might look like: ``` GET /robots.txt HTTP/1.1 ``` but to use a proxy, the line must include the server name (and port if not 80): ``` GET http://httpbin.org:80/robots.txt HTTP/1.1 ``` --- The response side if the operation can be simpler since the proxy server may simply relay the verbatim response via the pre-established request socket.
There's no such thing as "tcp packet". TCP operates with data streams. There are IP packets. You seem to be lacking some basic knowledge about networking, I suggest you to get a good book about TCP/IP. Everyone's favorite seems to be "TCP/IP illustrated" by W. Richard Stevens. Back to your question. A proxy is a middleman: [you] - [proxy] - [server you want to connect] Now there are two different connections: [you] - (your connection to proxy) - [proxy] - (proxy's connection to server) - [server you want to connect] When you think you're connecting to a server through a proxy, you're actually connecting to the proxy and tell it you want to reach a certain server. Then the proxy opens a second connection from itself to that server and acts as middleman passing data in both directions.
265,513
When I clicked on terminal. It shows this: ``` Last login: Fri Apr 1 17:04:59 on ttys000 -bash: export: /opt/local/bin': not a valid identifier -bash: export: :/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/usr/X11/bin': ``` not a valid identifier Josh@Macbook-Pro~$ export I installed something yesterday and modified bash\_profile. Now I cannot do anything in terminal. Even `ls`. It returns - Need help. How can I fix it? ``` bash: ls: No such file or directory ```
2011/04/01
[ "https://superuser.com/questions/265513", "https://superuser.com", "https://superuser.com/users/65071/" ]
HTTP is a Layer 7 protocol so dont get confuse. when you use a HTTP proxy and you type say google.com , the HTTP header still same google.com, but the destination IP address will be IP address of the Proxy, source will be Hosts IP to the customized port number 8080.
To use an HTTP proxy, the request is sent from the client to the proxy server's IP address rather than to the destination server. **The proxy must then read the HTTP header** to extract the *request-URI*. The request-URI includes the name or IP of the destination server, and the proxy server uses that information to forward the request. The [HTTP specification](https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html) allows the request line to exclude the server name and port when a proxy is not used (since these would be unnecessary if the request was sent directly to that server). But, as per the spec... > > The absoluteURI form is REQUIRED when the request is being made to a proxy. > > > So when not using a proxy, the request line might look like: ``` GET /robots.txt HTTP/1.1 ``` but to use a proxy, the line must include the server name (and port if not 80): ``` GET http://httpbin.org:80/robots.txt HTTP/1.1 ``` --- The response side if the operation can be simpler since the proxy server may simply relay the verbatim response via the pre-established request socket.
42,761,862
I use asp.net MVC model binding to accept the parameters for ajax. I have an object, it's data structure like this: ``` { "conditions": [ { "field": "", "opreator": "", "value": "" },[{ "field": "", "opreator": "", "value": "" }, { "field": "", "opreator": "", "value": "" }] ], "name": "query", } ``` C# array can't has different types. (the property conditions is an arrray that has object and array). So I defined an object array. ``` public class QueryVM { public class condition { public string field { get; set; } public string opreator { get; set; } public string value { get; set; } } public object[] conditions { get; set; } public string name { get; set; } } ``` But what I received the property conditions is just an object array. I can't access it's actual property, I even don't know it's actual type is(`QueryVM.condition` or `array`). I thinks the model binding even not set value of the properties. So this is a bad way. I want know whether there is other way to do this? **UPDATE** The `conditions` property of `QueryVM` is an object array because it's contain object and array.
2017/03/13
[ "https://Stackoverflow.com/questions/42761862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5954068/" ]
This can be achieved with a simple linear step combined with a for-loop. ```js var stop = 5, step = 20; for (var i = 0, min = 0, max = step; i < stop; i++, min+=step, max+=step) { console.log(i, min, max); } ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ``` If you do not want to create two additional variables, you can simply multiply. ```js var stop = 5, step = 20; for (var i = 0; i < stop; i++) { console.log(i, i * step, (i + 1) * step); } ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ``` If you do not want a loop, you can try this: ```js function minMaxMap(count, step) { return Array.from(new Array(count), (_, i) => [i * step, (i + 1) * step]); } var items = minMaxMap(5, 20); items.forEach((item, index) => console.log([index].concat(item).join(', '))); ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ```
```js var res = [0, 1, 2, 3, 4].map(function (e) { return [e * 20, e * 20 + 20]; }); console.log(res); ``` **Edit:** let **N** be a arbitrary number which defines desired array size. ```js var N = 10; var res = new Array(N).fill(0).map(function (e, i) { return [i * 20, i * 20 + 20]; }); console.log(res); ```
42,761,862
I use asp.net MVC model binding to accept the parameters for ajax. I have an object, it's data structure like this: ``` { "conditions": [ { "field": "", "opreator": "", "value": "" },[{ "field": "", "opreator": "", "value": "" }, { "field": "", "opreator": "", "value": "" }] ], "name": "query", } ``` C# array can't has different types. (the property conditions is an arrray that has object and array). So I defined an object array. ``` public class QueryVM { public class condition { public string field { get; set; } public string opreator { get; set; } public string value { get; set; } } public object[] conditions { get; set; } public string name { get; set; } } ``` But what I received the property conditions is just an object array. I can't access it's actual property, I even don't know it's actual type is(`QueryVM.condition` or `array`). I thinks the model binding even not set value of the properties. So this is a bad way. I want know whether there is other way to do this? **UPDATE** The `conditions` property of `QueryVM` is an object array because it's contain object and array.
2017/03/13
[ "https://Stackoverflow.com/questions/42761862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5954068/" ]
This can be achieved with a simple linear step combined with a for-loop. ```js var stop = 5, step = 20; for (var i = 0, min = 0, max = step; i < stop; i++, min+=step, max+=step) { console.log(i, min, max); } ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ``` If you do not want to create two additional variables, you can simply multiply. ```js var stop = 5, step = 20; for (var i = 0; i < stop; i++) { console.log(i, i * step, (i + 1) * step); } ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ``` If you do not want a loop, you can try this: ```js function minMaxMap(count, step) { return Array.from(new Array(count), (_, i) => [i * step, (i + 1) * step]); } var items = minMaxMap(5, 20); items.forEach((item, index) => console.log([index].concat(item).join(', '))); ``` ```css .as-console-wrapper { top: 0; max-height: 100% !important; } ```
You can use `map` to achieve this one, returning an array for min max. ```js const data = [0,1,2,3,4,5] function minMax(index) { return [index * 20, (index * 20) + 20] } const out = data.map(minMax) console.log(out) ```
14,010,665
What I'd like to achieve is a pulsate effect on an action (button click for example). So what I made is this (simplified [removed browser specifics]): ``` @keyframes pulse { 0% {transform: scale(1);} 50% {transform: scale(1.02);} 100% {transform: scale(1);} } .pulsate{ animation-name: pulse 0.2s linear 2; } ``` And in jQuery I did this: ``` $('#btn').click(function(e)){ e.preventDefault(); $('#some_element').addClass('pulse'); } ``` It works OK, but just the first time... Once the "pulse" class is added it doesn't trigger anymore... So what I tried to do is: ``` $('#btn').click(function(e)){ e.preventDefault(); $('#some_element').removeClass('pulsate').addClass('pulsate'); } ``` And it still is not working... Contrary to this: ``` $('#btn').click(function(e){ e.preventDefault(); $('#some_element').toggleClass('pulsate'); } ``` That works the first time, not the second, but works again the third; so basically every other time. I am baffled. Why would it work this way and not removing and adding it again? I even tried to make a reset class (once again simplified): ``` .reset_transform(){ transform: none; } ``` And in jQuery I'm doing something like: ``` $('#btn').click(function(e)){ e.preventDefault(); $('#some_element').removeClass('pulsate').addClass('reset_transform').addClass('pulsate'); } ``` But as you can imagine, it doesn't work... Any ideas? I would like the element to pulsate every time I click the button.
2012/12/23
[ "https://Stackoverflow.com/questions/14010665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484025/" ]
This is the solution to my problem. As @Aspiring Aqib pointed out I needed a delay between adding and removing the Class. He used a delay() jquery but it was not working. Here is my solution using setTimeout(); ``` $('#some_element').addClass('pulsate'); setTimeout(function(){ $('#some_element').removeClass('pulsate'); }, 800); ```
`ToggleClass()` did not worked because when you clicked it first time then it added the class and the animation played . When you clicked the second time it removed that class and this time, class is removed thats why it does not plays animation. On third time, it works like first time and this process will continue :/ ``` $('#btn').click(function(e)){ e.preventDefault(); $('#some_element').addClass('pulse').delay(200).removeClass('pulse'); } ``` well i don't think so the above code will work! :)
2,778,270
If $X$ is a set, $\{X\_i\}$ a family of topological spaces and for each $i\in I$ there is a map $f\_i:X\_i\rightarrow X$, then one can define a topology on $X$ which is the finest topology for which the maps $f\_i$ are all continuous. Sucha topology is the final topology. According to Bourbaki (and also to [Wiki](https://en.wikipedia.org/wiki/Disjoint_union_(topology))) the open sets in $X$ are such that their preimage under each $f\_i$ are open sets in $X\_i$. It works fine for the subsets $V\subset Y$ such that $$\bigcap\_{i\in I} f\_i(X\_i). $$ But I can't understand what happens with the sets $U$ which are not contained in the above intersection. Clearly $f^{-1}\_i(U)$ cannot be open in $X\_i$, since the operation $f^{-1}\_i(U)$ is not defined for at least one index in $I$. A solution would be that $U$ were not open. But then, it may happen that $X$ is not open, which is completely forbidden. What condition I'm misunderstanding in my above reasoning? Maybe the subsets $U$ of $X$ such that $$ U\subseteq \bigcap\_{i\in I} f\_i(X\_i) $$ and $f\_i^{-1}(U)$ are open in every space $X\_i$ form a basis for the toplogy of $X$ but they **are not** the whole set of open sets (as for example Bourbaki says)?
2018/05/12
[ "https://math.stackexchange.com/questions/2778270", "https://math.stackexchange.com", "https://math.stackexchange.com/users/415701/" ]
There is a problem with the sentence “Clearly $f^{-1}\_i(U)$ cannot be open in $X\_i$, since the operation $f^{-1}\_i(U)$ is not defined for at least one index in $I$.” For *each* $U\subset Y$ and *each* $i\in I$, it makes sense to talk about $f\_i^{-1}(U)$, since it is defined as $\left\{x\in X\,\middle|\,f(x)\in U\right\}$.
$f^{-1}[U\_i]$ is **always** defined, namely as $\{x\in X\_i: f\_i(x) \in U\_i\}$. This might be empty (or even $X\_i$) depending on $U\_i$. Example: suppose $f: X \to Y$ is a constant map with value $p \in Y$. Then $f^{-1}[O]=\emptyset$ when $p\notin O$ and $f^{-1}[O] = X$ when $p\in O$. So open in $X$ always, regardless of the precise topology on $X$. So the final topology for $f$, is the discrete topology on $Y$: all sets are open.
7,871,368
I want to know why `id` is a weak reference pointer,how it is able to handle any `class` type pointer and at run time how can we detect that which type of class pointer is assigned to `id`.
2011/10/24
[ "https://Stackoverflow.com/questions/7871368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299797/" ]
> > Why is id a weak reference pointer? > > > `id` is not a weak reference pointer, at least not in the ARC ownership sense. Whether an `id`-typed reference to an object is weak or not depends on the reference having been declared `__weak` (and variations) and the object’s class actually supporting weak references. However, you could say that `id` provides *weak typing*, although I think that dynamic/duck typing is a more accurate description. Since an `id`- typed reference contains no compile-time class-type information, the compiler isn’t able to, for example, determine if the underlying object can respond to a given selector, which could lead to runtime errors. > > How is it able to handle any class type pointer? > > > That’s part of the definition of [the Objective-C language](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html). The compiler recognises `id` as being the supertype of every Objective-C class, and it treats `id` differently. See the answer below as well. > > At runtime, how can we detect that which type of class pointer is assigned to id? > > > In Apple’s Objective-C runtime, the first bytes in the memory allocated to an object must point to that object’s class. You might see this referenced elsewhere as the `isa` pointer, and that’s how Apple’s runtime finds out the class of every1 object. The `id` type is defined to have this information as well. In fact, its only attribute is the `isa` pointer, which means that all1 Objective-C objects conform to this definition. If you have an `id` reference and want to discover the class of the referenced object, you can send it `-class`: ``` id someObject; // Assign something to someObject // Log the corresponding class Class c = [someObject class]; NSLog(@"class = %@", c); // Test whether the object is of type NSString (or a subclass of NSString) if ([someObject isKindOfClass:[NSString class]]) { NSLog(@"it's a string"); } ``` 1[Tagged pointers](http://objectivistc.tumblr.com/post/7872364181/tagged-pointers-and-fast-pathed-cfnumber-integers-in) are a notable deviation of this structure, and (partly) because of them one shouldn’t access the `isa` pointer directly.
It's nice to have a generic object type, so you can define collection types that can hold any kind of object, and other generic services that work with any object without knowing what kind of object it is. There is no trick to make id work. At a binary level all pointers are interchangeable. They just represent a memory address as a numerical value. To make id accept any type of pointer, it's only necessary to *disable* the rules of the compiler that normally require pointer types to match. You can find out information about the class of an id type variable in these kinds of ways: ``` id theObject = // ... something Class theClass = [theObject class]; NSString *className = NSStringFromClass(theClass); NSClassDescription *classDescription = [NSClassDescription classDescriptionForClass:theClass]; ``` But it's rarely necessary to do those kinds of things in code. More often, you want to test if your id variable is an instance of a particular class, and if so cast it to that class and start treating it as that type. ``` if ([theObject isKindOfClass:[MySpecializedClass class]]) { MySpecializedClass *specialObject = (MySpecializedClass *)theObject; [specialObject doSomethingSpecial]; } ``` If you were to use `-class` to find out the class, but it returned a class you know nothing about, then there's nothing special you can do with the object based on its class anyway. So there is no reason to do anything but check if it matches classes you know about, and only if you intend to do special handling for those classes anyway. You can sometimes use `isMemberOfClass` instead of `isKindOfClass`. It depends whether you want an exact match or to include subclasses.
7,871,368
I want to know why `id` is a weak reference pointer,how it is able to handle any `class` type pointer and at run time how can we detect that which type of class pointer is assigned to `id`.
2011/10/24
[ "https://Stackoverflow.com/questions/7871368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299797/" ]
> > Why is id a weak reference pointer? > > > `id` is not a weak reference pointer, at least not in the ARC ownership sense. Whether an `id`-typed reference to an object is weak or not depends on the reference having been declared `__weak` (and variations) and the object’s class actually supporting weak references. However, you could say that `id` provides *weak typing*, although I think that dynamic/duck typing is a more accurate description. Since an `id`- typed reference contains no compile-time class-type information, the compiler isn’t able to, for example, determine if the underlying object can respond to a given selector, which could lead to runtime errors. > > How is it able to handle any class type pointer? > > > That’s part of the definition of [the Objective-C language](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html). The compiler recognises `id` as being the supertype of every Objective-C class, and it treats `id` differently. See the answer below as well. > > At runtime, how can we detect that which type of class pointer is assigned to id? > > > In Apple’s Objective-C runtime, the first bytes in the memory allocated to an object must point to that object’s class. You might see this referenced elsewhere as the `isa` pointer, and that’s how Apple’s runtime finds out the class of every1 object. The `id` type is defined to have this information as well. In fact, its only attribute is the `isa` pointer, which means that all1 Objective-C objects conform to this definition. If you have an `id` reference and want to discover the class of the referenced object, you can send it `-class`: ``` id someObject; // Assign something to someObject // Log the corresponding class Class c = [someObject class]; NSLog(@"class = %@", c); // Test whether the object is of type NSString (or a subclass of NSString) if ([someObject isKindOfClass:[NSString class]]) { NSLog(@"it's a string"); } ``` 1[Tagged pointers](http://objectivistc.tumblr.com/post/7872364181/tagged-pointers-and-fast-pathed-cfnumber-integers-in) are a notable deviation of this structure, and (partly) because of them one shouldn’t access the `isa` pointer directly.
It may be worth to take a look on header file objc/objc.h to find internals of `id`. ``` typedef struct objc_class *Class; typedef struct objc_object { Class isa; } *id; typedef struct objc_selector *SEL; typedef id (*IMP)(id, SEL, ...); ```
7,871,368
I want to know why `id` is a weak reference pointer,how it is able to handle any `class` type pointer and at run time how can we detect that which type of class pointer is assigned to `id`.
2011/10/24
[ "https://Stackoverflow.com/questions/7871368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299797/" ]
It's nice to have a generic object type, so you can define collection types that can hold any kind of object, and other generic services that work with any object without knowing what kind of object it is. There is no trick to make id work. At a binary level all pointers are interchangeable. They just represent a memory address as a numerical value. To make id accept any type of pointer, it's only necessary to *disable* the rules of the compiler that normally require pointer types to match. You can find out information about the class of an id type variable in these kinds of ways: ``` id theObject = // ... something Class theClass = [theObject class]; NSString *className = NSStringFromClass(theClass); NSClassDescription *classDescription = [NSClassDescription classDescriptionForClass:theClass]; ``` But it's rarely necessary to do those kinds of things in code. More often, you want to test if your id variable is an instance of a particular class, and if so cast it to that class and start treating it as that type. ``` if ([theObject isKindOfClass:[MySpecializedClass class]]) { MySpecializedClass *specialObject = (MySpecializedClass *)theObject; [specialObject doSomethingSpecial]; } ``` If you were to use `-class` to find out the class, but it returned a class you know nothing about, then there's nothing special you can do with the object based on its class anyway. So there is no reason to do anything but check if it matches classes you know about, and only if you intend to do special handling for those classes anyway. You can sometimes use `isMemberOfClass` instead of `isKindOfClass`. It depends whether you want an exact match or to include subclasses.
It may be worth to take a look on header file objc/objc.h to find internals of `id`. ``` typedef struct objc_class *Class; typedef struct objc_object { Class isa; } *id; typedef struct objc_selector *SEL; typedef id (*IMP)(id, SEL, ...); ```
1,518,379
I'm getting this error (Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.) when trying to run a stored procedure from C# on a SQL Server 2005 database. I'm not actively/purposefully using transactions or anything, which is what makes this error weird. I can run the stored procedure from management studio and it works fine. Other stored procedures also work from C#, it just seems to be this one with issues. The error returns instantly, so it can't be a timeout issue. The code is along the lines of: ``` SqlCommand cmd = null; try { // Make sure we are connected to the database if (_DBManager.CheckConnection()) { cmd = new SqlCommand(); lock (_DBManager.SqlConnection) { cmd.CommandText = "storedproc"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Connection = _DBManager.SqlConnection; cmd.Parameters.AddWithValue("@param", value); int affRows = cmd.ExecuteNonQuery(); ... } } else { ... } } catch (Exception ex) { ... } ``` It's really got me stumped. Thanks for any help
2009/10/05
[ "https://Stackoverflow.com/questions/1518379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184155/" ]
It sounds like there is a `TransactionScope` somewhere that is unhappy. The `_DBManager.CheckConnection` and `_DBManager.SqlConnection` sounds like you are keeping a `SqlConnection` hanging around, which I expect will contribute to this. To be honest, in *most* common cases you are better off just using the inbuilt connection pooling, and `using` your connections locally - i.e. ``` using(var conn = new SqlConnection(...)) { // or a factory method // use it here only } ``` Here you get a clean `SqlConnection`, which will be mapped to an unmanaged connection via the pool, i.e. it doesn't create an *actual* connection each time (but will do a logical reset to clean it up). This also allows much more flexible use from multiple threads. Using a `static` connection in a web app, for example, would be horrendous for blocking.
From the code it seems that you are utilizing an already opened connection. May be there's a transaction pending previously on the same connection.
51,394,716
i don't know why this program is not working on my computer while other PC does so when i want to running this program it gives one error is given below, so try to hep for fix it... **index.js** ``` import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter, Route} from 'react-router-dom'; import PropTypes from 'prop-types'; import Posts from './components/posts'; import Profile from './components/profile'; class App extends Component { render() { return <div>Home</div> } } ReactDOM.render( <BrowserRouter> <div> <Route path="/posts" component={Posts}></Route> <Route path="/profile" component={Profile}></Route> </div> </BrowserRouter> , document.querySelector('.container')); ``` **posts.js** ``` import React, {Component} from 'react'; class Posts extends Component { render() { return <div>Posts</div> } } export default Posts; ``` **profile.js** ``` import React, {Component} from 'react'; class Profile extends Component { render() { return <div>Profile</div> } } export default Profile; ``` but it shows the error something like this in the microsogt edge... [![error](https://i.stack.imgur.com/4nBgG.png)](https://i.stack.imgur.com/4nBgG.png) it shows error in mozilla firefox like this... [![enter image description here](https://i.stack.imgur.com/34nFB.png)](https://i.stack.imgur.com/34nFB.png) error is in bundle.js file...so here one is the full error message from the bundle.js file which is given below **bundle.js** [![enter image description here](https://i.stack.imgur.com/tyje6.png)](https://i.stack.imgur.com/tyje6.png)
2018/07/18
[ "https://Stackoverflow.com/questions/51394716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10097453/" ]
It is there, just needs a bit of digging :-) [This page](https://datatables.net/manual/server-side) details the sent parameters and the returned data. The DataTable sends some data when using server-side processing and expects the returned data to be in a specific format - both of which are detailed in that page far better than I can here. Hope that helps?
DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. <https://datatables.net/examples/data_sources/ajax>
35,729,053
I'm going through a SQL tutorial, and came across this question. I've been stuck for sometime. **Customers** ``` id INTEGER PRIMARY KEY lastname VARCHAR firstname VARCHAR ``` **Purchases** ``` id INTEGER PRIMARY KEY customers_id INTEGER FOREIGN KEY customers(id) purchasedate DATETIME purchaseamount REAL ``` `Write a statement that gives a list of all customers who purchases something this month.` I know I want to inner-join the tables on customer\_id and then get the customer names where the month is February, does this look right? ``` SELECT * from Purchases inner join Customers on Purchases.customers_id=Customers.id WHERE MONTH(purchasedate) = 2 ```
2016/03/01
[ "https://Stackoverflow.com/questions/35729053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2891803/" ]
Yeah, or to avoid the whole `distinct` business you could write ``` SELECT id, LastName, firstname FROM Customers WHERE EXISTS ( SELECT 1 FROM Purchases WHERE customers_id=Customers.id AND MONTH(purchasedate)=2 AND YEAR(purchasedate)=2016 ) ```
Your query will return a list with duplicates name. Just add `DISTINCT` Dont use `*`, just include the fields your require. Also include the `id`, just in case two ppl has same first and last name ``` SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname from Purchases inner join Customers on Purchases.customers_id = Customers.id WHERE MONTH(purchasedate) = 2 ``` In case you want only the current month sales. you need specify your RDBMS because date function are different. For example in postgres sql you can use [Get first date of month in postgres](https://stackoverflow.com/questions/18069275/get-first-date-of-month-in-postgres) ``` SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname from Purchases inner join Customers on Purchases.customers_id = Customers.id WHERE date_trunc('month', current_date) = date_trunc('month', purchasedate) ```
35,729,053
I'm going through a SQL tutorial, and came across this question. I've been stuck for sometime. **Customers** ``` id INTEGER PRIMARY KEY lastname VARCHAR firstname VARCHAR ``` **Purchases** ``` id INTEGER PRIMARY KEY customers_id INTEGER FOREIGN KEY customers(id) purchasedate DATETIME purchaseamount REAL ``` `Write a statement that gives a list of all customers who purchases something this month.` I know I want to inner-join the tables on customer\_id and then get the customer names where the month is February, does this look right? ``` SELECT * from Purchases inner join Customers on Purchases.customers_id=Customers.id WHERE MONTH(purchasedate) = 2 ```
2016/03/01
[ "https://Stackoverflow.com/questions/35729053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2891803/" ]
I will go with `EXISTS` which will avoid duplicate ``` SELECT Customers.id, Customers.LastName, Customers.firstname FROM Customers WHERE EXISTS (SELECT 1 FROM Purchases WHERE Purchases.customers_id = Customers.id AND Month(purchasedate) = 2) ``` Considering you want to pull customer information who purchased in `2` month of any year
Your query will return a list with duplicates name. Just add `DISTINCT` Dont use `*`, just include the fields your require. Also include the `id`, just in case two ppl has same first and last name ``` SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname from Purchases inner join Customers on Purchases.customers_id = Customers.id WHERE MONTH(purchasedate) = 2 ``` In case you want only the current month sales. you need specify your RDBMS because date function are different. For example in postgres sql you can use [Get first date of month in postgres](https://stackoverflow.com/questions/18069275/get-first-date-of-month-in-postgres) ``` SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname from Purchases inner join Customers on Purchases.customers_id = Customers.id WHERE date_trunc('month', current_date) = date_trunc('month', purchasedate) ```
35,729,053
I'm going through a SQL tutorial, and came across this question. I've been stuck for sometime. **Customers** ``` id INTEGER PRIMARY KEY lastname VARCHAR firstname VARCHAR ``` **Purchases** ``` id INTEGER PRIMARY KEY customers_id INTEGER FOREIGN KEY customers(id) purchasedate DATETIME purchaseamount REAL ``` `Write a statement that gives a list of all customers who purchases something this month.` I know I want to inner-join the tables on customer\_id and then get the customer names where the month is February, does this look right? ``` SELECT * from Purchases inner join Customers on Purchases.customers_id=Customers.id WHERE MONTH(purchasedate) = 2 ```
2016/03/01
[ "https://Stackoverflow.com/questions/35729053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2891803/" ]
Yeah, or to avoid the whole `distinct` business you could write ``` SELECT id, LastName, firstname FROM Customers WHERE EXISTS ( SELECT 1 FROM Purchases WHERE customers_id=Customers.id AND MONTH(purchasedate)=2 AND YEAR(purchasedate)=2016 ) ```
I will go with `EXISTS` which will avoid duplicate ``` SELECT Customers.id, Customers.LastName, Customers.firstname FROM Customers WHERE EXISTS (SELECT 1 FROM Purchases WHERE Purchases.customers_id = Customers.id AND Month(purchasedate) = 2) ``` Considering you want to pull customer information who purchased in `2` month of any year
40,751,826
I've always known to import my `Observable` operators separately to limit the load times. However I've noticed something today that I hope someone could please explain to me. I am using IntelliJ/WebStorm with Webpack. Let's say on a page in my `ngOnInit` I have an http call: ``` ngOnInit() { this.http.get('https//:google.com').map(e => e); } ``` If I don't import the map operator the compiler will complain, so I import it like this: ``` import 'rxjs/add/operator/map'; ``` All is good in the world. Until I need to use an Observable. So, I'll add one. ``` ngOnInit() { let test = Observable.create(subscriber => { return null; }); this.http.get('https//:google.com').map(e => e); } ``` Now the compiler understandably complains that it cannot find Observable, so I get IntelliJ/WebStorm to import it for me and adds this at the top of my file: ``` import {Observable} from 'rxjs'; ``` All is good again. But, this new import seems to make the map import irrelevant. What I mean is that, if I remove the map import and just leave the Observable one in, all compiles fine... However, if I specify to import Observable like this: ``` import {Observable} from 'rxjs/Observable'; ``` Then I must re-add the import for the map operator... Am I importing all of RxJS when I import my Observable like this? ``` import {Observable} from 'rxjs'; ``` If so, how can I tell IntelliJ to not do that and import class only?
2016/11/22
[ "https://Stackoverflow.com/questions/40751826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2275792/" ]
Why not have a file(ex: rxjs-extensions.ts) with your required rxjs observable class extensions and operators? ``` // Observable class extensions import 'rxjs/add/observable/throw'; // Observable operators import 'rxjs/add/operator/do'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; ``` And then in your main module (ex app.module.ts) import from this file: ``` import './rxjs-extensions'; ``` And in your main component (ex: app.component.ts) just import Observavle: ``` import { Observable } from 'rxjs/Rx'; ``` This is how it is covered on the main angular tutorial.
You can use all operators by using this: ``` import * as Rx from "rxjs/Rx"; Rx.Observable.of(1,2,3,4,5); ```
40,751,826
I've always known to import my `Observable` operators separately to limit the load times. However I've noticed something today that I hope someone could please explain to me. I am using IntelliJ/WebStorm with Webpack. Let's say on a page in my `ngOnInit` I have an http call: ``` ngOnInit() { this.http.get('https//:google.com').map(e => e); } ``` If I don't import the map operator the compiler will complain, so I import it like this: ``` import 'rxjs/add/operator/map'; ``` All is good in the world. Until I need to use an Observable. So, I'll add one. ``` ngOnInit() { let test = Observable.create(subscriber => { return null; }); this.http.get('https//:google.com').map(e => e); } ``` Now the compiler understandably complains that it cannot find Observable, so I get IntelliJ/WebStorm to import it for me and adds this at the top of my file: ``` import {Observable} from 'rxjs'; ``` All is good again. But, this new import seems to make the map import irrelevant. What I mean is that, if I remove the map import and just leave the Observable one in, all compiles fine... However, if I specify to import Observable like this: ``` import {Observable} from 'rxjs/Observable'; ``` Then I must re-add the import for the map operator... Am I importing all of RxJS when I import my Observable like this? ``` import {Observable} from 'rxjs'; ``` If so, how can I tell IntelliJ to not do that and import class only?
2016/11/22
[ "https://Stackoverflow.com/questions/40751826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2275792/" ]
Why not have a file(ex: rxjs-extensions.ts) with your required rxjs observable class extensions and operators? ``` // Observable class extensions import 'rxjs/add/observable/throw'; // Observable operators import 'rxjs/add/operator/do'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; ``` And then in your main module (ex app.module.ts) import from this file: ``` import './rxjs-extensions'; ``` And in your main component (ex: app.component.ts) just import Observavle: ``` import { Observable } from 'rxjs/Rx'; ``` This is how it is covered on the main angular tutorial.
Starting from WebStorm 2016.3 (I believe), you have an option to blacklist certain imports. `Editor > Code Style > StypeScript` ``` Do not import exactly from: [rxjs] ``` Additionally, there is a flag available in tslint to prohibit global imports: ``` { "rules": { "import-blacklist": [true, "rxjs"] } } ```
40,751,826
I've always known to import my `Observable` operators separately to limit the load times. However I've noticed something today that I hope someone could please explain to me. I am using IntelliJ/WebStorm with Webpack. Let's say on a page in my `ngOnInit` I have an http call: ``` ngOnInit() { this.http.get('https//:google.com').map(e => e); } ``` If I don't import the map operator the compiler will complain, so I import it like this: ``` import 'rxjs/add/operator/map'; ``` All is good in the world. Until I need to use an Observable. So, I'll add one. ``` ngOnInit() { let test = Observable.create(subscriber => { return null; }); this.http.get('https//:google.com').map(e => e); } ``` Now the compiler understandably complains that it cannot find Observable, so I get IntelliJ/WebStorm to import it for me and adds this at the top of my file: ``` import {Observable} from 'rxjs'; ``` All is good again. But, this new import seems to make the map import irrelevant. What I mean is that, if I remove the map import and just leave the Observable one in, all compiles fine... However, if I specify to import Observable like this: ``` import {Observable} from 'rxjs/Observable'; ``` Then I must re-add the import for the map operator... Am I importing all of RxJS when I import my Observable like this? ``` import {Observable} from 'rxjs'; ``` If so, how can I tell IntelliJ to not do that and import class only?
2016/11/22
[ "https://Stackoverflow.com/questions/40751826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2275792/" ]
Starting from WebStorm 2016.3 (I believe), you have an option to blacklist certain imports. `Editor > Code Style > StypeScript` ``` Do not import exactly from: [rxjs] ``` Additionally, there is a flag available in tslint to prohibit global imports: ``` { "rules": { "import-blacklist": [true, "rxjs"] } } ```
You can use all operators by using this: ``` import * as Rx from "rxjs/Rx"; Rx.Observable.of(1,2,3,4,5); ```
19,640,681
In this case `hours_start` will be 08:00:00 and `hours_end` will be 14:00:00 here's the code i'm using to generate a list of 30 minute time slots between start and end ``` while($row = $q->fetch()){ $hours = $row['hours_end'] - $row['hours_start']; //amount of hours working in day for($i = 0; $i < $hours * 2; $i++){ // double hours for 30 minute increments $minutes_to_add = 1800 * $i; // add 30 - 60 - 90 etc. $timeslot = date('h:i:s', strtotime($row['hours_start'])+$minutes_to_add); echo " <tr> <td>" . date('h:i A', strtotime($timeslot)) . "</td> </tr>"; } } ``` this is producing: ``` 08:00 AM 08:30 AM 09:00 AM 09:30 AM 10:00 AM 10:30 AM 11:00 AM 11:30 AM 12:00 PM 12:30 PM 01:00 AM 01:30 AM ``` as you can see, it is functioning as (i) expected until it gets to (what should be) 1 PM then it switches back to AM. not sure whats going on here.
2013/10/28
[ "https://Stackoverflow.com/questions/19640681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391454/" ]
Its because you are setting `$timeslot` using `h` which is only a 12 hour format without appending `am` or `pm`. Then taking that 12 hour format and running it through `strtotime` which expects 24 hour format if am or pm is not present. Hence anything after 12 becomes am again. You need to use: ``` $timeslot = date('H:i:s', strtotime($row['hours_start'])+$minutes_to_add); ``` OR ``` $timeslot = date('h:i:s a', strtotime($row['hours_start'])+$minutes_to_add); ```
Your date format is using `h` instead of `H`. The lowercase `h` is [12 hour format](http://php.net/manual/en/function.date.php) Use a capital `H` instead for 24 hours. ``` date('H:i A', strtotime($timeslot)) ```
25,216,786
I want to implement a screen layout as shown below, with a Scrollview at the top of the screen, and a block of 2 buttons which are fixed at the bottom of the screen. I also want the buttons to occupy a fixed proportion of the screen width, and have used weights in a horizontal layout to achieve this. ![Desired layout](https://i.stack.imgur.com/9necJ.jpg) The ScrollView rows are populated from a database table, and may contain too many rows to be displayed on a single screen. For this reason I only want the ScrollView to occupy a fixed proportion of the top of the screen, so that the buttons always appear at the bottom of the screen. I tried adapting the solution here: [Android ScrollView and buttons at bottom of the screen](https://stackoverflow.com/questions/9326299/android-scrollview-and-buttons-at-bottom-of-the-screen) - substituting my own interface elements, but this resulted in the ScrollView occupying the whole screen, and the buttons not being visible at all. I suspect this is because the weights in my "layoutContainer" LinearLayout were conflicting with the design of the suggested solution. My current code is below. This renders the ScrollView and Buttons fine until the Scrollview gets too large - when that happens the buttons disappear from the bottom of the screen. ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:orientation="vertical" tools:context="com.itm.timer.ItemActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:gravity="top" android:text="@string/activity_meal_item_textview1" android:textSize="16sp" android:textStyle="bold" /> <ScrollView android:id="@+id/scrollViewRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="75" > <LinearLayout android:id="@+id/linearLayoutRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/layoutContainer" android:layout_width="fill_parent" android:layout_height="0dip" android:orientation="horizontal" > <RelativeLayout android:layout_width="0dip" android:layout_height="0dip" android:layout_weight="2" > </RelativeLayout> <RelativeLayout android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="20" > <Button android:id="@+id/btnMealPlan" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/clipboard" android:onClick="onClickMealPlan" android:text="Show Meal Plan" /> <Button android:id="@+id/btnStartTimer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/btnMealPlan" android:drawableLeft="@drawable/starttimer" android:onClick="onClickStartTimer" android:text="Set Reminders" /> </RelativeLayout> <RelativeLayout android:layout_width="0dip" android:layout_height="0dip" android:layout_weight="2" > </RelativeLayout> </LinearLayout> </LinearLayout> ``` Any ideas for how to achieve what I want, or how to simplify my design to achieve the aim of accommodating the ScrollView and Buttons in fixed positions on the screen?
2014/08/09
[ "https://Stackoverflow.com/questions/25216786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3647395/" ]
try like this it may help you, ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="top" android:padding="5dp" android:text="MeatItem" android:textSize="16sp" android:textStyle="bold" /> <ScrollView android:id="@+id/scrollViewRecords" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_weight="1" android:background="@android:color/holo_blue_light" > <LinearLayout android:id="@+id/linearLayoutRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="ScoollView" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/layoutContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="10dp" android:orientation="vertical" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:color/holo_blue_dark" android:text="Button1" android:textColor="@android:color/white" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@android:color/holo_blue_dark" android:text="Button2" android:textColor="@android:color/white" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@android:color/holo_blue_dark" android:text="Button3" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> ```
**Try this way,hope this will help you to solve your problem.** ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:orientation="vertical" tools:context="com.itm.timer.ItemActivity" tools:ignore="MergeRootFrame" android:padding="10dp" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="top" android:text="@string/activity_meal_item_textview1" android:textSize="16sp" android:textStyle="bold" /> <ScrollView android:id="@+id/scrollViewRecords" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <LinearLayout android:id="@+id/linearLayoutRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/layoutContainer" android:layout_width="match_parent" android:layout_height="wrap_content"> <View android:layout_width="0dp" android:layout_height="1" android:layout_weight="0.10"/> <LinearLayout android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="0.80" android:orientation="vertical"> <Button android:id="@+id/btnMealPlan" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/clipboard" android:onClick="onClickMealPlan" android:text="Show Meal Plan" /> <Button android:id="@+id/btnStartTimer" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/starttimer" android:onClick="onClickStartTimer" android:text="Set Reminders" /> <Button android:id="@+id/btnStartTimer" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/starttimer" android:onClick="onClickStartTimer" android:text="Set Reminders" /> </LinearLayout> <View android:layout_width="0dp" android:layout_height="1" android:layout_weight="0.10"/> </LinearLayout> </LinearLayout> ```
25,216,786
I want to implement a screen layout as shown below, with a Scrollview at the top of the screen, and a block of 2 buttons which are fixed at the bottom of the screen. I also want the buttons to occupy a fixed proportion of the screen width, and have used weights in a horizontal layout to achieve this. ![Desired layout](https://i.stack.imgur.com/9necJ.jpg) The ScrollView rows are populated from a database table, and may contain too many rows to be displayed on a single screen. For this reason I only want the ScrollView to occupy a fixed proportion of the top of the screen, so that the buttons always appear at the bottom of the screen. I tried adapting the solution here: [Android ScrollView and buttons at bottom of the screen](https://stackoverflow.com/questions/9326299/android-scrollview-and-buttons-at-bottom-of-the-screen) - substituting my own interface elements, but this resulted in the ScrollView occupying the whole screen, and the buttons not being visible at all. I suspect this is because the weights in my "layoutContainer" LinearLayout were conflicting with the design of the suggested solution. My current code is below. This renders the ScrollView and Buttons fine until the Scrollview gets too large - when that happens the buttons disappear from the bottom of the screen. ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:orientation="vertical" tools:context="com.itm.timer.ItemActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:gravity="top" android:text="@string/activity_meal_item_textview1" android:textSize="16sp" android:textStyle="bold" /> <ScrollView android:id="@+id/scrollViewRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="75" > <LinearLayout android:id="@+id/linearLayoutRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/layoutContainer" android:layout_width="fill_parent" android:layout_height="0dip" android:orientation="horizontal" > <RelativeLayout android:layout_width="0dip" android:layout_height="0dip" android:layout_weight="2" > </RelativeLayout> <RelativeLayout android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="20" > <Button android:id="@+id/btnMealPlan" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/clipboard" android:onClick="onClickMealPlan" android:text="Show Meal Plan" /> <Button android:id="@+id/btnStartTimer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/btnMealPlan" android:drawableLeft="@drawable/starttimer" android:onClick="onClickStartTimer" android:text="Set Reminders" /> </RelativeLayout> <RelativeLayout android:layout_width="0dip" android:layout_height="0dip" android:layout_weight="2" > </RelativeLayout> </LinearLayout> </LinearLayout> ``` Any ideas for how to achieve what I want, or how to simplify my design to achieve the aim of accommodating the ScrollView and Buttons in fixed positions on the screen?
2014/08/09
[ "https://Stackoverflow.com/questions/25216786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3647395/" ]
try like this it may help you, ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="top" android:padding="5dp" android:text="MeatItem" android:textSize="16sp" android:textStyle="bold" /> <ScrollView android:id="@+id/scrollViewRecords" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_weight="1" android:background="@android:color/holo_blue_light" > <LinearLayout android:id="@+id/linearLayoutRecords" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="ScoollView" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/layoutContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="10dp" android:orientation="vertical" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:color/holo_blue_dark" android:text="Button1" android:textColor="@android:color/white" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@android:color/holo_blue_dark" android:text="Button2" android:textColor="@android:color/white" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@android:color/holo_blue_dark" android:text="Button3" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> ```
Just use layout\_height="0dp" and layout\_weight="1" in your scrollview.
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
Create an Interface and extend `Easel`, `Cat`, `Dog` class to that interface. ``` public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } ``` [Ref:](http://docs.oracle.com/javase/tutorial/java/generics/bounded.html) > > There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what *bounded type parameters* are for. > > > To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). > > > ``` public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } ```
Although it's not elegant you could use construction as below. You can try using instanceof and casting. ``` public static <T> workWithRealTypeAttr(T objectClass) { if (objectClass instanceof Easel) { ((Easel) objectClass).toSomehtingEaselsDo()); } elseif (objectClass instanceof Cat) { ((Cat) objectClass).toSomehtingCatsDo()); } elseif (objectClass instanceof Dog) { ((Dog) objectClass).toSomehtingDogsDo()); } else { //do something to inform about not supported class. } } ``` The other way may be using a common interface (as suggested in other answers) `<T extends yourInterface>` or a Decorator pattern.
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
> > I want to have access to certain method/fields of the real class > > > If you want to access method/fields of the real class then use different **overloaded methods** ``` class GenericClassUtil { public static void workWithRealTypeAttr(Bird objectClass) { // call a method specific to Bird (Easel) } public static void workWithRealTypeAttr(Mammal objectClass) { // call a method specific to Mammal (Cat, Dog etc) } } ``` You can groups classes as Mammal, Bird and make the method more generic. ![enter image description here](https://i.stack.imgur.com/QE4kE.png) --- You can group classes based on behavior as per design pattern. ``` class GenericClassUtil { public static void workWithRealTypeAttr(Flyable objectClass) { // call a method specific to Flyable } public static void workWithRealTypeAttr(Swimmable objectClass) { // call a method specific to Swimmable } } interface Swimmable { public void swim() } interface Flyable { public void fly() } ``` ![enter image description here](https://i.stack.imgur.com/fRjYx.png) It's better explained in [Head First Design Pattern](http://uet.vnu.edu.vn/%7Echauttm/e-books/java/Head-First-Java-2nd-edition.pdf)
Although it's not elegant you could use construction as below. You can try using instanceof and casting. ``` public static <T> workWithRealTypeAttr(T objectClass) { if (objectClass instanceof Easel) { ((Easel) objectClass).toSomehtingEaselsDo()); } elseif (objectClass instanceof Cat) { ((Cat) objectClass).toSomehtingCatsDo()); } elseif (objectClass instanceof Dog) { ((Dog) objectClass).toSomehtingDogsDo()); } else { //do something to inform about not supported class. } } ``` The other way may be using a common interface (as suggested in other answers) `<T extends yourInterface>` or a Decorator pattern.
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
Create an Interface and extend `Easel`, `Cat`, `Dog` class to that interface. ``` public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } ``` [Ref:](http://docs.oracle.com/javase/tutorial/java/generics/bounded.html) > > There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what *bounded type parameters* are for. > > > To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). > > > ``` public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } ```
> > I want to have access to certain method/fields of the real class > > > If you want to access method/fields of the real class then use different **overloaded methods** ``` class GenericClassUtil { public static void workWithRealTypeAttr(Bird objectClass) { // call a method specific to Bird (Easel) } public static void workWithRealTypeAttr(Mammal objectClass) { // call a method specific to Mammal (Cat, Dog etc) } } ``` You can groups classes as Mammal, Bird and make the method more generic. ![enter image description here](https://i.stack.imgur.com/QE4kE.png) --- You can group classes based on behavior as per design pattern. ``` class GenericClassUtil { public static void workWithRealTypeAttr(Flyable objectClass) { // call a method specific to Flyable } public static void workWithRealTypeAttr(Swimmable objectClass) { // call a method specific to Swimmable } } interface Swimmable { public void swim() } interface Flyable { public void fly() } ``` ![enter image description here](https://i.stack.imgur.com/fRjYx.png) It's better explained in [Head First Design Pattern](http://uet.vnu.edu.vn/%7Echauttm/e-books/java/Head-First-Java-2nd-edition.pdf)