text
stringlengths
15
59.8k
meta
dict
Q: $.Post() cross-domain request works in chrome console but not in html page request I'm trying to send a $.post() cross-domain request. This is what I'm doing: $.post( "http://mysite.com/call.aspx/record", { Enroll : enroll, Item : item, usu : user, version : version, video : flv64String }, function(data){ console.log(data); return data; }, "json" ) This is what I have in the calling Webservice button function. I'have configured my web.config with <add name="Access-Control-Allow-Origin" value="*" /> So, when I click in the webservice caller button, the post is called and nothing happens. But when I paste the same $.post() method in Chrome console and properly change the variables with working values and execute, it works fine! Now I'm wondering, why the $.post works in Google Chrome console and in my site doesn't ? I hope some one could answer me.
{ "language": "en", "url": "https://stackoverflow.com/questions/18900711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Smarty loop count I am new to smarty concepts. I have used section loop in my tpl page to show the user data, in this page i need the section count. For example: {section name=i loop=$getFriends start=0 step=1} {/section} I need to check the section count for the array values($getFriends) to display some messages for the users. so please guide me on how to make the section count. A: To get the total count use {$smarty.section.customer.total} A: By 'count' do you mean the current index of the loop? If so you can use this {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]}<br /> {/section} http://www.smarty.net/docsv2/en/language.function.section.tpl#section.property.index A: Try {counter} http://www.smarty.net/docsv2/en/language.function.counter.tpl Exapmle: {counter start=0 print=false name=bla} {section name=i loop=$getFriends start=0 step=1} {counter} {/section} A: {assign var=val value=0} {section name=i loop=$data} {assign var=val value=$val+1} {/section}
{ "language": "en", "url": "https://stackoverflow.com/questions/5509769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract json api through go to extract stargazers_count of a repo? stargazers_count of https://api.github.com/repos/openebs/openebs using go language by extracting it through json A: Here is an example (completely neglecting error handling): request, _ := http.Get("https://api.github.com/repos/openebs/openebs") defer request.Body.Close() bytes, _ := ioutil.ReadAll(request.Body) var apiResponse struct { StargazersCount int `json:"stargazers_count"` } json.Unmarshal(bytes, &apiResponse) fmt.Println(apiResponse.StargazersCount) Playground
{ "language": "en", "url": "https://stackoverflow.com/questions/49468309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: EMR spark job from aws-cli I am trying to run an spark job on EMR using the aws cli. What I want is to have the server startup, run the job, and terminate. I am able to do it as a two step process (first fire up the server, then run the job), but when I send one command I get an error. error: Error: Cannot load main class from JAR file:/home/hadoop/spark/bin/spark-submit Run with --help for usage help or --verbose for debug output Command exiting with ret '1' So it looks like it can't find the jar (or the main class). I have set the master to yarn-cluster so that it should lookup the jars on s3, and I am 100% sure that the classpath of main class is correct. Command aws emr create-cluster --name "Test auto run" --release-label emr-5.4.0 \ --applications Name=Spark --ec2-attributes KeyName=key-emr --instance-type m3.xlarge --instance-count 2 \ --log-uri s3://test/emr --steps Type=Spark,Name="Spark Program",ActionOnFailure=CONTINUE,,\ Args=[/home/hadoop/spark/bin/spark-submit,--verbose,--master,yarn-cluster,--class,co.path.test.TestJob,s3://test/test-0.0.1-SNAPSHOT-jar-with-dependencies.jar,\ 's3://test/test-messages/1998*','d','s3://test/loaded'] \ --use-default-roles --auto-terminate The controller says this is being executed: /usr/lib/hadoop/bin/hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit /home/hadoop/spark/bin/spark-submit --verbose --master yarn-cluster --class,co.path.test.TestJob s3://test/test-0.0.1-SNAPSHOT-jar-with-dependencies.jar s3://test/test-messages/1998* d s3://test/loaded Any ideas what am I messing up? A: If the EMR step type is Spark which you mentioned on the step API --steps Type=Spark , as you identified on Step's controller logs, EMR will add the spark-submit command and you do not need to pass the /home/hadoop/spark/bin/spark-submit as arguments of the STEP API. The error was because of two spark-submit's , where it was taking the second one /home/hadoop/spark/bin/spark-submit as argument. Please see : http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-submit-step.html
{ "language": "en", "url": "https://stackoverflow.com/questions/43745431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django Filter timestamp data GROUP BY day, week, month, year I have an django(DRF) app in which I storing periodic timeseries data based on API response. Here is my model.py # Model to store the Alexa API Data class Alexa(models.Model): created_at = models.DateTimeField(auto_now_add=True) extra = jsonfield.JSONField(null=True) rank = models.PositiveIntegerField(default=0, null=True) I am using django-filters to query data based on a range (__lte, __gte). Like /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z return all the data created before 2020-02-14T09:15:52.329641Z [ { "id": 1, "created_at": "2020-02-03T19:30:57.868588Z", "extra": "{'load_time': 00, 'backlink': 0}", "rank": 0 }, ... ] Is there a way to build an endpoint to return aggregated data grouped by day, week, month and year based on the query params I pass. For example, /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z&group_by=month would return [ { "created_at": "2020-01-01T00:00:00.000000Z", "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data "rank": 0 <- Aggregated Data }, { "created_at": "2020-02-01T00:00:00.000000Z", "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data "rank": 0 <- Aggregated Data }, ] Here's my current views.py class AlexaViewSet(viewsets.ModelViewSet): queryset = Alexa.objects.all() filter_fields = {'created_at' : ['iexact', 'lte', 'gte']} http_method_names = ['get', 'post', 'head'] I have seen several snippets doing aggregation but none completely fulfilling my requirements nor giving me a complete idea about the topic. I am new to Django and building analytics dashboards in general, if there are any other way of representing such timeseries data for consumption in front-end graphs, I would appreciate your suggestions to that as well. EDIT : Here is my serializer.py class AlexaSerializer(serializers.ModelSerializer): class Meta: model = Alexa fields = '__all__' A: First of all, the class AlexaViewSet is not a serializer but a ViewSet. You didn't specify the serializer class on that ViewSet so I you need to specify that. On the other side, if you want to pass a custom query param on the URL then you should override the list method of this ViewSet and parse the query string passed in the request object to retrieve the value of group_by, validate it, and then perfom the aggregation youself. Another problem that I see is that you also need to define what is to aggregate a JSON field, which is not supported in SQL and it's very relative, so you may want to consider redesigning how you store the information of this JSON field if you want to perfom aggregations on fields inside it. I would suggest extracting the fields you want to aggregate from the JSON (when storing them in the database) and put them in a SQL column separately so you could perform aggregations later. The client could also pass the agregation operation as a query parameter, for example aggregation=sum or aggregation=avg. In a simple case, where you just need the average of the ranks this should be useful as an example (you could add TruncQuarter, etc.): class AlexaViewSet(viewsets.ModelViewSet): serializer_class = AlexaSerializer queryset = Alexa.objects.all() filter_fields = {'created_at': ['iexact', 'lte', 'gte']} http_method_names = ['get', 'post', 'head'] GROUP_CASTING_MAP = { # Used for outputing the reset datetime when grouping 'day': Cast(TruncDate('created_at'), output_field=DateTimeField()), 'month': Cast(TruncMonth('created_at'), output_field=DateTimeField()), 'week': Cast(TruncWeek('created_at'), output_field=DateTimeField()), 'year': Cast(TruncYear('created_at'), output_field=DateTimeField()), } GROUP_ANNOTATIONS_MAP = { # Defines the fields used for grouping 'day': { 'day': TruncDay('created_at'), 'month': TruncMonth('created_at'), 'year': TruncYear('created_at'), }, 'week': { 'week': TruncWeek('created_at') }, 'month': { 'month': TruncMonth('created_at'), 'year': TruncYear('created_at'), }, 'year': { 'year': TruncYear('created_at'), }, } def list(self, request, *args, **kwargs): group_by_field = request.GET.get('group_by', None) if group_by_field and group_by_field not in self.GROUP_CASTING_MAP.keys(): # validate possible values return Response(status=status.HTTP_400_BAD_REQUEST) queryset = self.filter_queryset(self.get_queryset()) if group_by_field: queryset = queryset.annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .annotate(rank=Avg('rank'), created_at=self.GROUP_CASTING_MAP[group_by_field]) \ .values('rank', 'created_at') page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) For these values: GET /alexa [ { "id": 1, "created_at": "2020-03-16T12:04:59.096098Z", "extra": "{}", "rank": 2 }, { "id": 2, "created_at": "2020-02-15T12:05:01.907920Z", "extra": "{}", "rank": 64 }, { "id": 3, "created_at": "2020-02-15T12:05:03.890150Z", "extra": "{}", "rank": 232 }, { "id": 4, "created_at": "2020-02-15T12:05:06.357748Z", "extra": "{}", "rank": 12 } ] GET /alexa/?group_by=day [ { "created_at": "2020-02-15T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-16T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=week [ { "created_at": "2020-02-10T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-16T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=month [ { "created_at": "2020-02-01T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-01T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=year [ { "created_at": "2020-01-01T00:00:00Z", "extra": null, "rank": 77 } ]
{ "language": "en", "url": "https://stackoverflow.com/questions/60236869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the fastest way to compare two strings in C? For clarity I'm only talking about null terminated strings. I'm familiar with the standard way of doing string comparisons in C with the usage of strcmp. But I feel like it's slow and inefficient. I'm not necessarily looking for the easiest method but the most efficient. Can the current comparison method (strcmp) be optimized further while the underlying code remains cross platform? If strcmp can't be optimized further, what is the fastest way which I could perform the string comparison without strcmp? Current use case: * *Determine if two arbitrary strings match *Strings will not exceed 4096 bytes, nor be less than 1 byte in size *Strings are allocated/deallocated and compared within the same code/library *Once comparison is complete I do pass the string to another C library which needs the format to be in a standard null terminated format *System memory limits are not a huge concern, but I will have tens of thousands of such strings queued up for comparison *Strings may contain high-ascii character set or UTF-8 characters but for my purposes I only need to know if they match, content is not a concern *Application runs on x86 but should also run on x64 Reference to current strcmp() implementation: * *How does strcmp work? *What does strcmp actually do? *GLIBC strcmp() source code Edit: Clarified the solution does not need to be a modification of strcmp. Edit 2: Added specific examples for this use case. A: I'm afraid your reference imlementation for strcmp() is both inaccurate and irrelevant: * *it is inaccurate because it compares characters using the char type instead of the unsigned char type as specified in the C11 Standard: 7.24.4 Comparison functions The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared. *It is irrelevant because the actual implementation used by modern compilers is much more sophisticated, expanded inline using hand-coded assembly language. Any generic implementation is likely to be less optimal, especially if coded to remain portable across platforms. Here are a few directions to explore if your program's bottleneck is comparing strings. * *Analyze your algorithms, try and find ways to reduce the number of comparisons: for example if you search for a string in an array, sorting that array and using a binary search with drastically reduce the number of comparisons. *If your strings are tokens used in many different places, allocate unique copies of these tokens and use those as scalar values. The strings will be equal if and only if the pointers are equal. I use this trick in compilers and interpreters all the time with a hash table. *If your strings have the same known length, you can use memcmp() instead of strcmp(). memcmp() is simpler than strcmp() and can be implemented even more efficiently in places where the strings are known to be properly aligned. EDIT: with the extra information provided, you could use a structure like this for your strings: typedef struct string_t { size_t len; size_t hash; // optional char str[]; // flexible array, use [1] for pre-c99 compilers } string_t; You allocate this structure this way: string_t *create_str(const char *s) { size_t len = strlen(s); string_t *str = malloc(sizeof(*str) + len + 1; str->len = len; str->hash = hash_str(s, len); memcpy(str->str, s, len + 1); return str; } If you can use these str things for all your strings, you can greatly improve the efficiency of the matching by first comparing the lengths or the hashes. You can still pass the str member to your library function, it is properly null terminated.
{ "language": "en", "url": "https://stackoverflow.com/questions/41420339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unlocking the condition variable mutex twice? I'm looking at the following snippets: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cvar; char buf[25]; void*thread_f(void *); int main(){ pthread_t thr; pthread_cond_init(&cvar,NULL); pthread_mutex_lock(&mtx); pthread_create(&thr,NULL,thread_f,NULL); pthread_cond_wait(&cvar,&mtx); pthread_mutex_unlock(&mtx); ...join and destroy thread... } and thread_f: void* thread_f(void* argp){ pthread_mutex_lock(&mtx); strcpy(buf,"test"); pthread_cond_signal(&cvar); pthread_mutex_unlock(&mtx); //why? pthread_exit(NULL); } My understanding of the above code is, that main grabs the lock, creates the thread and runs thread_f which blocks. Then, main signals the wait on the condition variable cvar and unlocks the mutex. Then, thread_f unblocks, strcpys and signals cvar to wake up. Then, both main and thread_f unlock the mutex. Is this the actual behaviour, or am I missing something somewhere? If it's the actual behaviour, isn't unlocking the already unlocked mutex UB, therefore should one of he mutex unlocks in the end be removed? Thanks. A: The pthread_cond_wait() in the main thread unlocks the mutex and waits for the condition to be signalled — and relocks the mutex before returning. The child thread is able to lock the mutex, manipulate the buffer, signal the condition and then unlock the mutex, letting the main thread reacquire the lock. Consequently, the code is well-behaved — give or take the need to worry about 'spurious wakeups' in more general situations with multiple child threads. I don't think you can get a spurious wakeup here. A: What this code is doing is valid. When the thread calls pthread_cond_signal it doesn't immediately cause the main thread to grab the mutex, but wakes up the main thread so it can attempt to lock it. Then once the thread releases the mutex, the main thread is able to lock it and return from pthread_cond_wait.
{ "language": "en", "url": "https://stackoverflow.com/questions/72450466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bash if variable set by function I have limited experience with BASH and I am looking for some guidance about how to proceed so please bear with me. I am trying to change the command prompt when I am inside a git repo, which I can do using this post I found on google, but I also would like to add color depending on the current state of the repo (clean, untracked files, modified files). Currently I have this at the end of my .bashrc file: parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } modified () { git status 2> /dev/null | grep -q modified } untracked () { git status 2> /dev/null | grep -q Untracked } clean () { git status 2> /dev/null | grep -q clean } NO_COLOR="\[\033[0m\]" GREEN="\[\033[0;32m\]" YELLOW="\[\033[0;33m\]" RED="\[\033[0;31m\]" set_color () { if untracked ; then echo $RED elif modified ; then echo $YELLOW elif clean ; then echo $GREEN else echo $NO_COLOR fi } PS1="\u:\w\$(set_color)\$(parse_git_branch)$NO_COLOR> " The command prompt changes but does not change the color like I think it should. Here is what I get instead: outside git repo arod:~\[\033[0m\]> inside a git repo arod:~/tos\[\033[0;32m\][dev]> I am unsure how to get the color to evaluate I think, just looking for some guidance from someone with more BASH experience than I have. A: If anyone is looking for an answer; or at least the solution that I used: parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } modified () { git status 2> /dev/null | grep -q modified } untracked () { git status 2> /dev/null | grep -q Untracked } clean () { git status 2> /dev/null | grep -q clean } NO_COLOR="\033[0m" GREEN="\033[0;32m" YELLOW="\033[0;33m" RED="\033[0;31m" set_color () { if untracked ; then echo -e $RED elif modified ; then echo -e $YELLOW elif clean ; then echo -e $GREEN else echo -e $NO_COLOR fi } PS1="\u:\w\$(set_color)\$(parse_git_branch)$NO_COLOR> " The main difference between the code in the question and this one is that I did add the -e flag to echo, and removed the \'s from the color variables. Hope this helps someone EDIT After receiving a bit more feedback, here is what this looks like now: parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } no_color="\033[0m" green="\033[0;32m" yellow="\033[0;33m" red="\033[0;31m" set_color () { case "$(git status 2> /dev/null)" in *Untracked*) printf '%b' "$red";; *modified*) printf '%b' "$yellow";; *clean*) printf '%b' "$green";; *) printf '%b' "$no_color";; esac } PS1="\u:\w\$(set_color)\$(parse_git_branch)$no_color> " All of this came from @Charles Duffy. The only thing I did not incorporate was using tput to get the color escape sequences.
{ "language": "en", "url": "https://stackoverflow.com/questions/33514629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle: how to check either two polygon are overlapping or not I have measured a land area (plot) and captured its 4 corner's GPS co-ordinates using a GPS device. Now I have two Questions * *How to save this is Oracle Database. (it seems answer of first point. is it?) *After saving it I wanna check whether any plot is overlapping (partially or full) to another existing plot in database or not? A: I got very helpful comments by Rene and Ben. and based on i have solved my issues.. --------------------------- CREATING TABLE -------------------------- create table tbl_location( id int constraint id_pk primary key, unit_code char(2) not null, plot_id number(15) not null, season_cntrl number(2), Ryot_code varchar2(9), share_or_perc_val number(2) not null, plot_no varchar2(18) not null, total_area decimal(5,5), a1 varchar2(15), b1 varchar2(15), a2 varchar2(15), b2 varchar2(15), a3 varchar2(15), b3 varchar2(15), a4 varchar2(15), b4 varchar2(15), location sdo_geometry ); --------------------------- CREATING SEQUENCE FOR ID --------------------------- create sequence location_sequence start with 1 increment by 1 nocache nocycle; / --- createing a trigger for auto-incrementation of ID ------------------------------ Create or replace trigger id_increment before insert on tbl_location for each row begin select location_sequence.nextval into :new.id from dual; end; for column location data update tbl_location set location = SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.16181','27.8682866666666','80.1616516666666','27.8681266666666','80.161215','27.867975','80.1613933333333','27.8685933333333','80.16181','27.8682866666666' )) where id =2; update tbl_location set location = SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.1538483333333','27.88376','80.15354','27.8841166666666','80.1529499999999','27.8834933333333','80.1532','27.8832566666666','80.1538483333333','27.88376' )) where id =3; To get plots (polygon) which are intersecting each other select a.id as id1, b.id as id2,a.unit_code, a.ryot_code,a.share_or_perc_val, sdo_geom.sdo_intersection(a.location, b.location, 0.005) location, a.plot_no, a.total_area from tbl_location a Inner Join tbl_location b on a.id < b.id and sdo_geom.sdo_intersection(a.location, b.location,0.005) is not null ; A: Well, you can just call the SDO_GEOM.SDO_AREA() on the result of the SDO_GEOM.SDO_INTERSECTION() function. However that will not give you meaningful results: your geometries are (so it seems) in geodetic WGS84 coordinates (i.e. in decimal degrees), but you load them without specifying any coordinate system. As a result, any area calculation will return a result in square degrees, a meaningless and unusable result. You should load your two geometries like this: update tbl_location set location = SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.16181,27.8682866666666,80.1616516666666,27.8681266666666,80.161215,27.867975,80.1613933333333,27.8685933333333,80.16181,27.8682866666666 )) where id =2; update tbl_location set location = SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.1538483333333,27.88376,80.15354,27.8841166666666,80.1529499999999,27.8834933333333,80.1532,27.8832566666666,80.1538483333333,27.88376 )) where id =3; Finally your approach only works because you only play with two geometries. As soon as you start dealing with real data, the query will perform very badly: it requires computing the intersection between each shape and all the others. For a set of 10,000 shapes, that means 100,000,000 computations (well actually 99,990,000 since you avoid intersecting a geometry with itself). The proper approach is to detect the shapes that intersect by taking advantage of spatial indexing. The appropriate approach is to use the SDO_JOIN() procedure for that. A: There is a much more simple way to do that. Your Problem seems to use the SDO_GEOM.RELATE function. This function Returns the relationship between two or more Polygons. In the following example all relations to the other polygons in your table are shown to the polygon with the 1 SELECT c.id, SDO_GEOM.RELATE(c.polygon, 'determine', c_b.polygon, 0.005) relationship FROM my_polygon_table c, my_polygon_talbe c_b WHERE c_b.id = 1; The result is one of the opsibile relationships: ANYINTERACT; CONTAINS; COVEREDBY; COVERS; DISJOINT; EQUAL; INSIDE; ON; OVERLAPBDYDISJOINT; OVERLAPBDYINTERSECT; TOUCH; Care also about the Right Keyword: If you pass the DETERMINE keyword in mask, the function returns the one relationship keyword that best matches the geometries. If you pass the ANYINTERACT keyword in mask, the function returns TRUE if the two geometries are not disjoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/23564595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript find matching variables between two nested arrays I have two nested arrays. arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]] arr2 = [["image1","blue"],["image2","red"]] The desired output is : If the image names (image) match, I want to return the color from the second array to a variable. I have tried using two for loops: var color = for (var i = 0; i < arr1.length; i++ ) { for (var j = 0; j < arr2.length; j++ ) { if (arr1[i][0] === arr2[j][0]) { return arr2[j][1] } } Since this is a larger part of a program, The first loop gets executed much before the second loop...however both are nested into each other in the order that I have specified.....I am trying to using the variable to color some html elements, but my entire program gets halted. I am not sure if my approach is right. A: Feels like you're trying to use the second array as a lookup into the first. Here's a way to do this by transforming it into an object: function toLookupTable(shirtColors) { //keys will be image names, values will be colors const lookupTable = {}; shirtColors.forEach(shirtColor => { //use array destructuring const [ image, color ] = shirtColor; lookupTable[image] = color; }); return lookupTable; } const colorLookup = toLookupTable( [["image1","blue"],["image2","red"]] ); console.log(colorLookup["image2"]); //outputs "red" A: Use Array#reduce and Array#findIndex I want to return the color from the second array to a variable. const arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]] const arr2 = [["image1", "blue"],["image2","red"]] const res = arr2.reduce((a,[image,color])=>{ if(arr1.findIndex(([n])=>n===image) > -1) a.push(color); return a; }, []); console.log(res); A: You can use reduce let arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]; let arr2 = [["image1","blue"],["image2","red"]]; let op = arr1.reduce((out,inp,index)=>{ if(arr2[index].includes(inp[0])){ out.push(arr2[index][1]) } return out },[] ) console.log(op)
{ "language": "en", "url": "https://stackoverflow.com/questions/54559457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows screensaver from HTML/JS I've an html page without any external includes with some inline CSS3 animations and JS timers. Is it possible to convert a simple html file to a screensaver file, which can be further used as a screensaver on my windows and mac desktops? I mean a real screensaver, which boots once desktop goes to a sleep mode, not the one that works in the browser. I know there're some tools available to export swf as a screensaver file, are there any tools available for exporting the HTML? At least, for Windows 8. Any ideas are respected.
{ "language": "en", "url": "https://stackoverflow.com/questions/21431800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Checkboxes not working in WiX generated windows installer I've used WiXEdit in conjunction with Wix to reverse engineer an MSI installation in order to move my main solution up to VS2013 from VS2010. The error Im getting is that when the MSI is run, the checkboxes and text box I've placed in a dialog act as if they're disabled. I need the checkboxes as in my main application they allow the user to select a feature set. I've generated a simple solution that demonstrates the same error. The solution has 2(3) projects, windowsformsapplication12 will always be installed, windowsformsapplication1 will only be installed if conditional CHECKBOX1A=1 (SetupProject2 is the wix project and the wix script is found here as setup1.wxs) (Wix toolkit is necessary to be installed into visual studio to compile the Wix setup project if necessary, but if somebody with installer expertise checks the script setup1.wxs they may see what's wrong with it.) NB On attempting to compile the reverse engineered file, I received error message "Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes." on lines 491,492,493,494. So I added Property="CHECKBOXA1" (or as appropriate) to the end of the control descriptor xml as can be seen if you unrar the source. I assume I'm missing adding extra code elsewhere or I assume it would work. This is the first time I've ever encountered a Wix script and the source code doesn't really resemble Wix tutorial code I've seen so I've not been able to debug it. A: Converting VS2010 setup project to a Wix script Please find instructions for anybody else who'd find it useful 1) Install WixToolkit and WixEdit 2) Build VS2010 setup project 3) Create new Wix project within the solution. 4) Remove the default product.wxs file from the Wix project 5) Copy the setup MSI file to the root directory of the Wix project 6) Run WixEdit application 7) Open the setup MSI file in WixEdit (This should generate files and directories) 7) Add directories and files generated by WixEdit to the Wix project 8) Compile Wix Setup Project and fix errors 9) Delete the original msi file from the wix project Re Check boxes not working "Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes" Go to the error line in the script <Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no"/> Change it so it reads (or appropriate changes) <Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no" Property="CHECKBOXA1" CheckBoxValue="1" /> CheckBoxValue="1" was the missing attribute that caused my checkboxes to be disabled
{ "language": "en", "url": "https://stackoverflow.com/questions/28716084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Annotations @AfterViews called 3 times I'm using Android Annotations and my method annotated with @AfterViews is called 3 times. I debugged the generated class and i figure that these 3 methods are invoked but i dont know why. @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); afterSetContentView_(); } @Override public void setContentView(View view, LayoutParams params) { super.setContentView(view, params); afterSetContentView_(); } @Override public void setContentView(View view) { super.setContentView(view); afterSetContentView_(); } -- edit 1 -- My activity declaration is the only place where I set a layout: @EActivity(R.layout.real_estate_customer_leads_list) public class RealEstateCustomerLeadsListActivity extends SlidingFragmentActivity implements FilterResponseHandler { } A: that's probably because one super is calling the other. Something like this: // super.setContentView(layoutResID); code is: View v = LayoutInflater.from(getContext()).inflate(layoutResId); setContentView(v); // then super.setContentView(view); code is: setContentView(view, null); // then super.setContentView(view, params); this one now actually do real work. Hence, 3 calls!
{ "language": "en", "url": "https://stackoverflow.com/questions/15115877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sort values a data frame with duplicates values I have a dataframe with a format like this: d = {'col1': ['PC', 'PO', 'PC', 'XY', 'XY', 'AB', 'AB', 'PC', 'PO'], 'col2': [1,2,3,4,5,6,7,8,9]} df = pd.DataFrame(data=d) df.sort_values(by = 'col1') This gives me the result like this: I want to sort the values based on col1 values with desired order, keep the duplicates. The result I expect would be like this: Any idea? Thanks in advance! A: You can create an order beforehand and then sort values as below. order = ['PO','XY','AB','PC'] df['col1'] = pd.CategoricalIndex(df['col1'], ordered=True, categories=order) df = df.sort_values(by = 'col1') df col1 col2 1 PO 2 8 PO 9 3 XY 4 4 XY 5 5 AB 6 6 AB 7 0 PC 1 2 PC 3 7 PC 8
{ "language": "en", "url": "https://stackoverflow.com/questions/66853210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: arduino yun to parse.com starter project not working I'm trying to run the arduino starter project from parse.com and like other people i have found the object id blank Parse.com Arduino Yun SDK Quickstart tutorial not working in the serial monitor i get this response Parse Starter Project Response for saving a TestObject: Test object id: However i've tried everything i can think of, updated the bridge library, tried various different versions of the IDE and of the bridge library. I'm running windows. I've tried 1.6.1, 1.6.3, 1.6.5 and i've tried several versions of the bridge library. I'm at a loss. Anyone else encountered this issue and have an ideas? A: So i managed to fix it! The issue was with the embedded SDK. If anyone struggles with the same probelm here are the steps i took: * *Download WinSCP. *Connect to the arduino using SSH in WinSCP (username root) *copy across the two embedded parse.com arduino files (make sure they are in the correct root folder *Download PuTTY and use this to open the arduino command line *call opkg install *.ipk to install the SDK files That seems to have sorted the problem, they weren't installed properly before
{ "language": "en", "url": "https://stackoverflow.com/questions/32006551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invoking a controller method without having a route defined for it I have several routes, and do not want to add another due to the difficulty in setting permissions, etc. I have a controller method, which isn't invoked on any route. Is there any way I can do this in my blade template? My controller method is as follows: public static function editROA(){ //do stuff } and in my blade template, I would like to refer this: <a type='button' class='btn-warning' href="{{action('HomeController::editROA')}}">Edit</a> However, this throws an error, and says that there is no method named editROA. Is there any solution to this problem? A: Since you cannot have more than five routes, I would suggest you use only one wild-carded route. So you run an if else on the wild card to call the appropriate method. Route::get('{uri?}',function($uri){ if($uri == "/edit") { return app()->call('App\Http\Controllers\HomeController@editROA'); }else if($uri == "something else"){ return app()->call('App\Http\Controllers\SomeController@someMethod'); } // add statements for other routes }); view <a type='button' class='btn-warning' href="{{url('edit')}}">Edit</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/46079245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent a page from resubmitting? in grails 2.2.0 When once form is submitted successfully.... but When I click on "BACK" button and trying submit same form its gives me an error Source: <g:form action="addData" name="addValues" controller="emp" method="Post"> </g:form> Controller Source:- def editProfile (Long id,Long version){ withForm { // code }.invalidToken { response.status = 405 } } A: Its hard to infer the cause of the error with what you have posted. However, you asked about how to prevent a page from resubmitting in Grails. Take a look at documentation. Grails has a build in support for that. Basically you define a form with a token and using withForm you will check if the token still is valid or not. <g:form useToken="true" ...> / withForm { // good request }.invalidToken { // bad request }
{ "language": "en", "url": "https://stackoverflow.com/questions/18373361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Backbone Undefined is not a function error I'm learning backbone and I'm trying to execute this sample code to get the feel. http://backbonetutorials.com/what-is-a-view/ My code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>hello-backbonejs</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script> <script src="http://backbonejs.org/backbone.js"></script> <script type="text/javascript"> Rocky = Backbone.Model.extend({ initialize: function(){ console.log('hello world'); } }); </script> </body> </html> I get this error. Uncaught type error: Undefined is not a function! What did I do wrong? I was just trying to print and see if it's printed on my console! Thanks, R A: Your underscore.js version is too old. Try to use the new version (1.7): <script src="http://underscorejs.org/underscore.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/25829955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is infinite loop needed when using threading and a queue in Python I'm trying to understand how to use threading and I came across this nice example at http://www.ibm.com/developerworks/aix/library/au-threadingpython/ #!/usr/bin/env python import Queue import threading import urllib2 import time hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", "http://ibm.com", "http://apple.com"] queue = Queue.Queue() class ThreadUrl(threading.Thread): """Threaded Url Grab""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue host = self.queue.get() #grabs urls of hosts and prints first 1024 bytes of page url = urllib2.urlopen(host) print url.read(1024) #signals to queue job is done self.queue.task_done() start = time.time() def main(): #spawn a pool of threads, and pass them queue instance for i in range(5): t = ThreadUrl(queue) t.setDaemon(True) t.start() #populate queue with data for host in hosts: queue.put(host) #wait on the queue until everything has been processed queue.join() main() print "Elapsed Time: %s" % (time.time() - start) The part I don't understand is why the run method has an infinite loop: def run(self): while True: ... etc ... Just for laughs I ran the program without the loop and it looks like it runs fine! So can someone explain why this loop is needed? Also how is the loop exited as there is no break statement? A: Do you want the thread to perform more than one job? If not, you don't need the loop. If so, you need something that's going to make it do that. A loop is a common solution. Your sample data contains five job, and the program starts five threads. So you don't need any thread to do more than one job here. Try adding one more URL to your workload, though, and see what changes. A: The loop is required as without it each worker thread terminates as soon as it completes its first task. What you want is to have the worker take another task when it finishes. In the code above, you create 5 worker threads, which just happens to be sufficient to cover the 5 URL's you are working with. If you had >5 URL's you would find only the first 5 were processed.
{ "language": "en", "url": "https://stackoverflow.com/questions/14493915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Azure Function ignoring https.request I have an azure function with this line of code. var myReq = https.request(options, function(res) { context.log('STATUS: ' + res.statusCode); context.log('HEADERS: ' + JSON.stringify(res.headers)); body += res.statusCode res.on('data', function (chunk) { context.log('BODY: ' + chunk); }); }); myReq.on('error', function(e) { context.log('problem with request: ' + e.message); }); myReq.write(postData); myReq.end(); But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up. Any ideas? Edit: Here is my full code const https = require('https'); const querystring = require('querystring'); module.exports = async function (context, req) { if (req.query.accessCode || (req.body && req.body.accessCode)) { context.log('JavaScript HTTP trigger function processed a request.'); var options = { host: 'httpbin.org', port: 80, path: '/post', method: 'POST' }; var postData = querystring.stringify({ client_id : '1234', client_secret: 'xyz', code: req.query.accessCode }); var body = ""; var myReq = https.request(options, function(res) { context.log('STATUS: ' + res.statusCode); context.log('HEADERS: ' + JSON.stringify(res.headers)); body += res.statusCode res.on('data', function (chunk) { context.log('BODY: ' + chunk); }); }); myReq.on('error', function(e) { context.log('problem with request: ' + e.message); }); myReq.write(postData); myReq.end(); context.log("help"); context.res = { status: 200, body: "Hello " + (body) }; } else { context.res = { status: 400, body: "Please pass a name on the query string or in the request body" }; } }; A: Ideally it should work. You can also try using request module like below const request = require('request'); request('http://www.google.com', function (error, response, body) { console.error('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); Try and see if it helps. A: Solved by doing await properly. Used this as guide. var https = require('https'); var util = require('util'); const querystring = require('querystring'); var request = require('request') module.exports = async function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); /*if (req.query.name || (req.body && req.body.name)) {*/ var getOptions = { contentType: 'application/json', headers: { 'Authorization': <bearer_token> }, }; var postData = { "key": "value" }; var postOptions = { method: 'post', body: postData, json: true, url: <post_url>, headers: { 'Authorization': <bearer_token> }, }; try{ var httpPost = await HttpPostFunction(context, postOptions); var httpGet = await HttpGetFunction(context, <get_url>, getOptions); return { res: httpPost }; }catch(err){ //handle errr console.log(err); }; }; async function HttpPostFunction(context, options) { context.log("Starting HTTP Post Call"); return new Promise((resolve, reject) => { var data = ''; request(options, function (err, res, body) { if (err) { console.error('error posting json: ', err) reject(err) } var headers = res.headers; var statusCode = res.statusCode; //context.log('headers: ', headers); //context.log('statusCode: ', statusCode); //context.log('body: ', body); resolve(body); }) }); }; async function HttpGetFunction(context, url, options) { context.log("Starting HTTP Get Call"); return new Promise((resolve, reject) => { var data = ''; https.get(url, options, (resp) => { // A chunk of data has been recieved. resp.on('data', (chunk) => { data += chunk; }) // The whole response has been received. Print out the result. resp.on('end', () => { resolve(JSON.parse(data)); }); }).on("error", (err) => { console.log("Error: " + err.message); reject(err.message); }); }); };
{ "language": "en", "url": "https://stackoverflow.com/questions/56022566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run regasm.exe from a C++ program (.NET 4) I need to register a .NET COM dll from a C++ program that is using it. For .NET versions older then .NET 4 this is explained in How to run regasm.exe from a C++ program?. Following is the minimal code (no checks) that provides the path to an older version of the CLR. CComBSTR mscoreeName("mscoree.dll"); HINSTANCE hMscoree = CoLoadLibrary(mscoreeName, FALSE); typedef HRESULT (WINAPI *LPFNGETCORSYSDIR)(LPWSTR, DWORD, DWORD*); LPFNGETCORSYSDIR lpfunc = (LPFNGETCORSYSDIR)GetProcAddress(hMscoree,_T("GetCORSystemDirectory")); DWORD bufferSize = 256; DWORD bufferUsed; LPWSTR pwzBuffer = new WCHAR[bufferSize]; (*lpfunc)(pwzBuffer, bufferSize, &bufferUsed); However since I use .NET 4 the method GetCORSystemDirectory is superseded by the ICLRRuntimeInfo::GetRuntimeDirectory which is not an entry point in mscoree.dll (checked with depends). According the documentation on MSDN the method is included as a resource in MSCorEE.dll. Question is how to get access to this method from C++? Besides that I'm wondering if there is no easier way... A: The problem with the way of working in the question is in finding the correct location of RegAsm. Thanks to the comment of Hans Passant to use RegistrationService.RegisterAssembly I changed the ClassLibrary into a self-registering executable. static void Main(string[] args) { if (args.Length != 1) { ShowHelpMessage(); return; } if (args[0].CompareTo("/register") == 0) { Assembly currAssembly = Assembly.GetExecutingAssembly(); var rs = new RegistrationServices(); if (rs.RegisterAssembly(currAssembly, AssemblyRegistrationFlags.SetCodeBase)) { Console.WriteLine("Succesfully registered " + currAssembly.GetName()); } else { Console.WriteLine("Failed to register " + currAssembly.GetName()); } return; } if (args[0].CompareTo("/remove") == 0) { Assembly currAssembly = Assembly.GetExecutingAssembly(); var rs = new RegistrationServices(); if (rs.UnregisterAssembly(currAssembly)) { Console.WriteLine("Succesfully removed " + currAssembly.GetName()); } else { Console.WriteLine("Failed to remove " + currAssembly.GetName()); } return; } ShowHelpMessage(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/23155041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to understand where argv[1] and arg [2] command are pointing in this program Here is someone's program, which i need for my project to collect data. I'm unable to understand where is the command #define IMAGE argv[1] #define IFS argv[2] pointing to and what are the values being defined in the IMAGE and IFS. These two command are necessary as they are later on required to for reading a file name. #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include <alloc.h> #define IMAGE argv[1] #define IFS argv[2] get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int *assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image, char *argv[]); unsigned int *image; main(int argc, char *argv[]) { unsigned char dom[4][4], d1[4][4], ran[8][8], lowest_error, sym, bestsym, domain_whites,range_whites; unsigned int assumed_width_of_image, assumed_height_of_image, width_of_image, height_of_image; unsigned long int count, domx, domy, ranx, rany, bestranx; time_t start_time; FILE *ifs_file; start_time = time(NULL); if (argc != 3) { printf("\nUse the following format:\n\ncompress [image_file] [ifs_file]\n\n"); exit } if ((ifs_file = fopen(IFS, "wb")) == NULL) { fprintf(stderr, "\nError opening file %s\n", IFS); exit(1); } get_image(ifs_file, &assumed_width_of_image, &assumed_height_of_image, &width_of_image, &height_of_image, argv); get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int *assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image, char *argv[]) { FILE *image_file; unsigned int buf[24], *header, size_of_header, extra_height; unsigned long size_of_file, size_of_image; if ((image_file = fopen(IMAGE, "rb")) == NULL) { fprintf(stderr, "\nCannot open file %s\n", IMAGE); exit(1); } if (fread(buf, sizeof(unsigned int), 24, image_file) != 24) { fprintf(stderr, "\nError reading file %s\n", IMAGE); exit(1); } if (buf[0] != 19778) { printf("%s is not a .BMP file", IMAGE); exit(0); } if (buf[23] != 2) { printf("%s is not a black and white image", IMAGE); exit(0); } A: argc and argv refer to command line inputs. When the program is run they are specified by the user. myprogram.exe --input1 fred See this: What does int argc, char *argv[] mean?
{ "language": "en", "url": "https://stackoverflow.com/questions/20172294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How get list of days in a week that exist in some date range (Javascript) Hello I need to define existing days in some date range. I don't wont to make loop from start to end dates and use like here http://www.w3schools.com/jsref/jsref_getday.asp Is it possible to calculate it some how ? A: function getDays(earlierDate, laterDate) { var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; var elapsedDays = (laterDate - earlierDate) / 1000 / 60 / 60 / 24; if (elapsedDays < 7) { var dayArray = []; for (i = 0; i <= elapsedDays; i++) { dayArray.push(dayNames[(earlierDate.getDay()+i) % 7]); } return dayArray; } return dayNames; } And testing in the js console: > getDays(new Date("03-01-2012"), new Date("03-01-2012")); ["Thursday"] > getDays(new Date("03-01-2012"), new Date("03-05-2012")); ["Thursday", "Friday", "Saturday", "Sunday", "Monday"] > getDays(new Date("03-01-2012"), new Date("03-05-2013")); ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] A: var sevenDaysInMS = 604800000; if (new Date(dTo - dFrom).getTime() >= sevenDaysInMS) { $('.day_hid').attr(attrUnaviableDay, "true"); } else { var dt = dFrom; do { var day = dt.getDay(); ActivateDaySelector(day); dt.setDate(dt.getDate() + 1); } while (dt <= dTo); } I think it is ok. What do you think ?
{ "language": "en", "url": "https://stackoverflow.com/questions/14496310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mgwt / gwtphonegap advices, feedback, tips I have to develop an application on Android, iOS and Windows Phone by using Phonegap. I would like to know if someone has already used mgwt / gwtphonegap and have your feedback / advices on these technologies, if you have encountered some blocking issues for example. I have already developed a Phonegap application in javascript (jquery / jquery mobile) html / css, but now I would know if I could start another one by using only GWT. However I would like to avoid to begin the development and realize 3 weeks later that I'm blocked because of mgwt / gwtphonegap. Note that I have never developed with GWT but often in Java Thanks A: I've been using mgwt/phonegap only a few months, so I'm definitely not an expert, but so far no major stumbling blocks. I like GWT, as it is well documented, robust and supported, although mgwt is a bit less so. There's an active google forum at https://groups.google.com/forum/?fromgroups#!forum/mgwt. Maybe if you have some more specific question, I or someone on that forum could answer it.
{ "language": "en", "url": "https://stackoverflow.com/questions/16303070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If two random numbers generated at exactly same time using Math.random(), would they be same or different? I want to predict the random number generated with Math.random() function. I studied an article that the algorithm behind random number generator function takes the time in mili seconds an input, and generate a random number. So, is this possible to predict the next random number? I am playing a game named as dragon/tiger. Each dragon and tiger has 13 numbers. The numbers for both are both randomly generated after every 15 seconds. The side having higher number wins. Is there any way to predict which side will win(what number would be generated next)?
{ "language": "en", "url": "https://stackoverflow.com/questions/75356403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush I'm getting an error when imagemin is run on png : Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush i'm on a macbook pro 10.6.8 I installed grunt today along with the plugin's Any help would be wonderful as google is pointing me to IOS development issues. A: The binary is compiled for a newer version of the OS (you're now 4 major releases behind — upgrade if you can!)
{ "language": "en", "url": "https://stackoverflow.com/questions/26642685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use org.apache.logging.log4j.jul.LogManager in an eclipse-rcp application? I am trying to use the log4j2 LogManager in an eclipse rcp application. I have -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager set as start parameter. Starting the rcp application from within my eclipse IDE everything works as expected. But as soon as I start it as a standalone application logging won't work. A possible hint may be the following stacktrace from the client console: Could not load Logmanager "org.apache.logging.log4j.jul.LogManager" java.lang.ClassNotFoundException: org.apache.logging.log4j.jul.LogManager at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at org.eclipse.core.runtime.internal.adaptor.ContextFinder.loadClass(ContextFinder.java:131) at java.lang.ClassLoader.loadClass(Unknown Source) at java.util.logging.LogManager$1.run(Unknown Source) at java.util.logging.LogManager$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.util.logging.LogManager.<clinit>(Unknown Source) at java.util.logging.Logger.demandLogger(Unknown Source) at java.util.logging.Logger.getLogger(Unknown Source) at org.apache.felix.gogo.runtime.threadio.ThreadIOImpl.<clinit>(ThreadIOImpl.java:30) at org.apache.felix.gogo.runtime.activator.Activator.start(Activator.java:75) at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702) at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683) at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381) at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300) at org.eclipse.equinox.console.command.adapter.Activator.startBundle(Activator.java:248) at org.eclipse.equinox.console.command.adapter.Activator.start(Activator.java:237) at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702) at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683) at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381) at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300) at org.eclipse.osgi.framework.internal.core.ConsoleManager.checkForConsoleBundle(ConsoleManager.java:215) at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:297) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:176) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584) at org.eclipse.equinox.launcher.Main.run(Main.java:1438) What do I need to do to get logging running in the RCP application without starting it from within my IDE? A: It sounds like eclipse is aware of your dependency on this class and is able to add it to the classpath for you. What you need is a way to add the dependency to the classpath when you run it outside of eclipse. To fix this, ensure the class org.apache.logging.log4j.jul.LogManager is on the classpath. This can be done with -cp and the path to the jar file. For example if you have a class com.org.Main you are trying to run. java -cp your.jar:log4j-jul-2.3.jar com.org.Main your.jar is the jar containing your application and log4j-jul-2.3.jar is the jar containing the missing class.
{ "language": "en", "url": "https://stackoverflow.com/questions/43759123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating HK2 modules I'm trying to leverage the Hundred Kilobyte Kernel (HK2) framework, however I can't find any tutorials or working examples of it. I have installed Maven, as it is required, but I can't find the archetypes to work with. I'm working with Eclipse, and I have only found this Netbeans guide but even the example source files are non existent. Under Eclipse, I managed to install the m2e maven plugin and I have tried to start a new project, however when I try to search for the hk2 archetype to create my customization of it I can't find the required resources. I try to create a new project, and then add an archetype, I specify com.sun.enterprise as the group id, the artifact id as hk2 (and hk2-maven-plugin as per some instructions), the latest version I could find (1.6.9) and the remote location as http://download.java.net/maven/glassfish/, but even when the jar files are there, there is no archetype catalog file that I can find. I have also tried adding this location as a Remote Catalog, but since there is no xml file to point to, it says the catalog is empty. My question is, does anyone have any updated resources or startup steps to create an hk2 module? or can tell me how to use what I have? Inside the jars there are pom.xml files, however if I import those to Eclipse, it has errors that I don't know how to fix. Development on the project seems almost completely halted (last updates are from jul 2011) but maybe someone already familiar with Glassfish plugin development can point me in the right direction? or maybe could someone recommend an alternative to HK2? If anyone has any good OSGi tutorials that would be nice too, or any other similar framework. Thanks! A: Sounds like you're better off with OSGi ... The HK2 (which would surprise me if it was still 100k) was an attempt to not depend on OSGi directly for Glassfish. I do not think it has a well maintained API. Since OSGi is a well defined and maintained API, that it runs on Glassfish, and that you also get portability to other environments seems to indicate that the choice for OSGi is smarter. The easiest way to get started is http://bndtools.org/ A: If you want to do Glassfish module development I can recommend you following tutorials and one example taken from the Glassfish trunk. Just have a look there how they do it. I tried it once, but since HK2 is not really OSGi as Peter already mentioned, I let it be after some time :) But maybe you can take advantages of these information now ;) * *http://kalali.me/glassfish-modularity-system-how-extend-glassfish-cli-and-web-administration-console-part-2-developing-sample-modules/ *http://java.net/projects/glassfish-samples/sources/svn/show/trunk/v3/plugin/adminconsole/console-sample-ip/
{ "language": "en", "url": "https://stackoverflow.com/questions/14680734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android loadLabel giving very laggy/slow performance, any solutions? I'm trying to create a launcher app in which I fetch all app names with loadLabel, but it's taking almost 3 second to load the names, and is very slow!!! I tried removing that text and now it works very fast! But I want app labels, Can we use any alternative method? Here's the code: TextView label = (TextView) grid.findViewById(R.id.label); Typeface tf_label = Typeface.createFromAsset(getAssets(), "fonts/RobotoC-Regular.ttf"); label.setTypeface(tf_label); label.setText(info.activityInfo.loadLabel(getPackageManager()) .toString()); A: similiar problem here. I load the list of all apps and add them to a recyclerview, i had to wait some seconds before it was loaded so i timed the loading time. What i noticed is that loading icons and labels with 70 apps i needed around 2.6 seconds to load the apps, without loading icons and label ... an astonishing 61ms! YEAH milliseconds! For now i am using a temporary solution, i will probably improve it in the future. What i did is create a model object that loads labels and icons in a background thread. public class AppModel { ComponentName componentName; Drawable icon = null; String appName = ""; public AppModel(ComponentName componentName) { this.componentName = componentName; } public void init(ActivityInfo ai, PackageManager pm) { new Thread(new Runnable() { @Override public void run() { appName = (String) ai.loadLabel(pm); icon = ai.loadIcon(pm); } }).start(); } ... ... } when i load the apps i do the following: AppModel appModel = new AppModel(componentName); appModel.init(ai, pm); // other stuff I needed a fast and working hotfix, in this way while the app is added to the recyclerview the labels and icons get loaded in background, cutting down the loading time by a lot! A future solution i am considering is to load those icons and labels in multithreading. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/30633396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capturing IR Data using VB.NET Just found an old IR reciever (Microsoft eHome Infared Transceiver) and i'm trying to write an application that can use data it captures... Any examples or jumping off points for this are appreciated. A: Looks like it's a USB HID device. As such, you should be able to use Win32 API to talk to it - similar to other USB HID devices. A: I think the Microsoft eHome Infared Transceiver is a Human Interface Device (HID), so I'd start with The HID Page. This has a VB.NET sample on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/719804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP displaying arrays having duplicate with color=red I have a array that i want to check if has duplicates using PHP $i=array('One','Two','Two','Three','Four','Five','Five','Six'); I was able to achieve it by using below function function array_not_unique($input) { $duplicates=array(); $processed=array(); foreach($input as $i) { if(in_array($i,$processed)) { $duplicates[]=$i; } else { $processed[]=$i; } } return $duplicates; } I got below output Array ( [0] => Two [1] => Five ) Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table. My goal is to display the duplicated values with red font color. A: Try this piece of code... simplest and shortest :) $i=array('One','Two','Two','Three','Four','Five','Five','Six'); $arrayValueCounts = array_count_values($i); foreach($i as $value){ if($arrayValueCounts[$value]>1){ echo '<span style="color:red">'.$value.'</span>'; } else{ echo '<span>'.$value.'</span>'; } } A: Here is optimized way that will print exact expected output. <?php $i=array('One','Two','Two','Three','Four','Five','Five','Six'); $dups = array_count_values($i); print_r($dups); foreach($i as $v) { $colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : ''; echo "<span $colorStyle>$v</span>"; } ?> A: Try this, function array_not_unique($input) { $duplicates=array(); $processed=array(); foreach($input as $key => $i) { if(in_array($i,$processed)) { $duplicates[$key]=$i; // fetching only duplicates here and its key and value } } return $duplicates; } foreach($processed as $k => $V){ if(!empty($duplicates[$k])){ // if duplicate found then red echo '<span style="color:red">'.$duplicates[$k].'</span>'; }else{ echo '<span>'.$duplicates[$k].'</span>'; // normal string } } A: Like this : PHP function array_duplicate_css($input) { $output = $processed = array(); foreach($input as $key => $i) { $output[$key]['value'] = $i; if(in_array($i, $processed)) { $output[$key]['class'] = 'duplicate'; } else { $output[$key]['class'] = ''; $processed[] = $i; } } return $output; } foreach(array_duplicate_css($input) as $row) { echo '<tr><td class="' . $row['class'] . '">' . $row['value'] . '</td></tr>'; } CSS .duplicate { color: #ff0000; } A: Simple use array_count_values. $array=array('One','Two','Two','Three','Four','Five','Five','Six'); $new_array= array_count_values($array); foreach($new_array as $key=>$val){ if($val>1){ for($j=0;$j<$val;$j++){ echo "<span style='color:red'>".$key."</span>"; } }else{ echo "<span>".$key."</span>"; } } A: It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.
{ "language": "en", "url": "https://stackoverflow.com/questions/45812736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Abbreviating numbers in Android, locale sensitive In my Android project, I am hoping to find a way to abbreviate numbers that is sensitive to various locales. If the number is less than 1000, it is to remain as is; otherwise, I would like the number divided by the largest possible power of 1000 and rounded to two decimal places. So far, I have the below code, which correctly produces the desired results as stated under Output. public void formatNumbers() { //Output: //842 => 842 //24,567 => 24.57k //356,915 => 356.92k //7,841,234 => 7.84M //1,982,452,873 => 1.98B int[] i = new int[] {842, 24567, 356915, 7841234, 1982452873}; String[] abbr = new String[] {"", "k", "M", "B"}; DecimalFormat df = new DecimalFormat("0.00"); df.setRoundingMode(RoundingMode.HALF_UP); for (long i1 : i) { int thousands = thousands(i1); String result; if(thousands == 0) { result = String.valueOf(i1); } else { double d = (double) i1 / Math.pow(1000.0, thousands); result = df.format(d)+abbr[thousands]; } System.out.println(i1 + " => " + result); } } public int thousands(double num) { //returns the number of times the number can be divided by 1000 int n=0; double comp=1000.0; while(num>comp) { n++; comp*=1000.0; } return n; } My concern is that I want a way to ensure that the output is sensitive to locale. If I understand correctly, DecimalFormat should take care of conventions such as commas instead of decimals where applicable; this leaves my concern with the suffix. While my output would be generally be understood in the United States for casual purposes (despite the fact that "M" is used to mean "thousands" in some industries, such as finance) and, from my understanding, many areas in Europe which have languages based on Latin, there are many locales that this would not be understood well. Perhaps there is a built-in function that handles this that I have not been able to find. Thank you in advance for your attention to and input on this task.
{ "language": "en", "url": "https://stackoverflow.com/questions/32361142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Play audio when app is not in foreground or app is inactive I do not want any code but want to get reference that how can we play audio in background in multitasking devices when application is running in background not in foreground... Please help me to solve this question. Thanks in advance.. A: There is developer documentation available here: * *Executing Code in the Background *Playing Background Audio *Audio Session Programming Guide A: I had solved this question by referring iOS Application Background tasks and make some changes in .plist file of our application.. Happy coding...
{ "language": "en", "url": "https://stackoverflow.com/questions/7358079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex: Match string from set of characters, but need to have exactly X count of a specific character I have a very specific regex match and I can't seem to figure it out. I need to find full strings matches for /^[aple]+$/i but MUST match exactly two "p's" and exactly one of the other characters. Any other characters are not allowed. Case insensitive. So, for example, these will successfully match: Apple ppleA APPLE apple ppale These would not match: foo appple aple bar test I've tried to set the explicit count of p using {brackets} but I think I have the syntax completely wrong. Such as: /^([p]{2})([ale]{1}+$)/i -- not working at all. This one ^(([a]{1})([p]{2})([l]{1})([e]{1}))+$ matches "apple" but it doesn't match "pplea" Assume I can do this in two sets of matches, run it first to get the set of matches that may have any # of p's and then do a second run to test for exactly two, but there has got to be a one-liner? Thanks for any help. A: Something like this would work: /^(?=.*a)(?=.*p.*p)(?=.*l)(?=.*e)[aple]{5}$/i * */^ - start the regex and use a start string anchor *(?=.*a) - ensure that an a exists anywhere in the string *(?=.*p.*p) - ensure that two ps exist anywhere in the string *(?=.*l) - ensure that an l exists anywhere in the string *(?=.*e) - ensure that an e exists anywhere in the string *[aple]{5} - get 5 chars of a, p, l, or e *$ - end string anchor */i - case-insensitive modifier https://regex101.com/r/DJlWAL/1/ You can ignore the /gm in the demo as they are used just for show with all the words at one time. A: You can assert a single instance of a l and e by using a character class and optionally matching all allowed chars except the one that you want to assert, preventing unnecessary backtracking. Then match 2 times a p char between optionally matching the other chars (as they are already asserted for). ^(?=[ple]*a[ple]*$)(?=[ape]*l[ape]*$)(?=[apl]*e[apl]*$)[ale]*p[ale]*p[ale]*$ Explanation * *^ Start of string *(?=[ple]*a[ple]*$) Assert an a *(?=[ape]*l[ape]*$) Assert an l *(?=[apl]*e[apl]*$) Assert an e *[ale]*p[ale]*p[ale]* Match 2 times a p *$ End of string Regex demo Or a shorter version using a quantifier based of the answer of @MonkeyZeus. ^(?=[ple]*a)(?=[ape]*l)(?=[apl]*e)(?=[ale]*p[ale]*p)[aple]{5}$ Regex demo A: ^(?=^[^a]*a[^a]*$)(?=^[^l]*l[^l]*$)(?=^[^e]*e[^e]*$)[aple]{5}$ This works by restricting the number of a, l, and e characters to exactly 1 of each, and then restricting the overall string to exactly 5 characters to enforce 2 p characters. You asked about regex, but in case it helps, an algorithmic version would be to sort the characters of APPLE and compare to the upper-cased version of your string sorted as above.
{ "language": "en", "url": "https://stackoverflow.com/questions/65415066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to disable addressbar without using windows.open in javascript or jquery or other way Hi I want to disable address bar as I don't want that user can edit anything in to the URL or modify the url. So basically I'm emailing link to them and by clicking they can complete require task and that'why I want to stop them to make any changes. thanks A: The scenario you are describing (give someone a link to do something, and only that thing) is typically solved with server-side validation rather than just hiding the URL. Often, you want to make use of a "nonce", that is a one-time secret value for each allowed action that users could not guess. So for example http://www.example.com/validate-email/?nonce=d389mxfh47c A user could not simply change the nonce to get a desired effect. The server can look up what the correct, authorized action is for that nonce when the user accesses/submits the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/34388720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: smooth scrolling of imageview I have added the images to scrollview dynamically. Following is the code: -(void)displayimages { for (int i=0; i<[featuredarray count]; i++) { NSString *image=[[featuredarray objectAtIndex:i]objectForKey:@"img"]; if (i==0) { webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)]; } else { webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)]; } webview.backgroundColor=[UIColor clearColor]; webview.layer.borderWidth=4; webview.layer.cornerRadius=4; webview.layer.borderColor=[[UIColor whiteColor]CGColor]; [webview setTag:i]; webview.userInteractionEnabled=YES; NSURL *url = [NSURL URLWithString:image]; [webview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; [scroll addSubview:webview]; UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlefirstTap:)]; tap1.delegate=self; tap1.numberOfTapsRequired=1; [webview addGestureRecognizer:tap1]; [tap1 release]; [webview release]; } pages.defersCurrentPageDisplay=YES; scroll.delegate =self; scroll.contentSize = CGSizeMake(290*[featuredarray count],300); scroll.pagingEnabled = YES; pages.numberOfPages = [featuredarray count]-1; pages.currentPage =0; } -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{ int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width; CGRect frame = scroll.frame; frame.origin.x = frame.size.width-15*gallerypage; NSLog(@"frame.origin.x..%f",frame.origin.x); frame.origin.y =0; [scroll scrollRectToVisible:frame animated:YES]; } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width; CGRect frame = scroll.frame; frame.origin.x=gallerypage*290; frame.origin.y =0; [scroll scrollRectToVisible:frame animated:YES]; } It is showing the images well when I use pagecontroller action -(IBAction)pagecontrolaction:(id)sender { int page = pages.currentPage; CGRect frame = scroll.frame; frame.origin.x=page*290; frame.origin.y =0; [scroll scrollRectToVisible:frame animated:YES]; } but when I used touch event to imageview then it is not displaying the images smoothly. It gets stuck during scrolling. These are the preview which shows the current image with the start of second image. A: The two methods: scrollViewWillBeginDecelerating and scrollViewDidEndDecelerating contains two animation with different x position it is animated to: frame.origin.x = frame.size.width-15*gallerypage; and frame.origin.x=gallerypage*290; It is better if you could turn off either function: scrollViewWillBeginDecelerating or scrollViewDidEndDecelerating. Otherwise probably you should adjust the x position (must be in sync for both functions) it will be animated to. A: if (i==0) { webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 440)]; } else { webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 380)]; } A: You need to change your implementation for loading the images from a remote resource, thats where the biggest bottle neck lies. I don't want to go into details but try to replace this line of code [webview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; With something more c.p.u friendly. Use a caching mechanism that employs multi-threading, what you want to do is move the heavy lifting (Downloading remote images) to another thread. SDWebImage does a perfect job at this https://github.com/rs/SDWebImage If you are a bit hard core, you can roll your own multi-threaded image downloader using [NSURLConnection sendAsynchronousRequest:queue: completionHandler:] And do the image loading in the block, Or even better dispatch_async(queu, block) A: You should checkout SYPaginator (SYPaginator is a horizontal TableView with lazy loading and view recycling.) Simple paging scroll view to make complicated tasks easier. We use this in several of the Synthetic apps including Hipstamatic, D-Series, and IncrediBooth. If you need more perfomance you should give MSCachedAsyncViewDrawing a try: Helper class that allows you to draw views (a)synchronously to a UIImage with caching for great performance. A: I think that happens because your images are larger in size (MB) , and you fit them into that CGRect without resizing them that specific size, also it matters how many pictures you have loaded inside the scrollview , if you load many pictures it will take a lot of memory and it will slide slowly. A: It happens when you are trying to show an image of larger size in that case you have to use cache to get the image there and try to load image from there.For better know how to use it..use SDwebimage thats the nice way to do it and it is fast. You can read * *Lazy Loading 2.paging enabled. https://github.com/rs/SDWebImage Need any further help.Happy to help you. A: I am not sure why are you setting the frame when you start scrolling, but if I were in your place I would do the logic as per below: -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{ // do nothing } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width; CGFloat xoffset = 290 * gallerypage; [UIView animateWithDuration:0.5 animations:^{ scrollView.contentOffset = CGPointMake(xoffset, 0); } completion:^(BOOL finished){ NSLog(@"Done!"); }]; } Hope it helps. A: You should definitely resize your image in background prior to loading it into UIImageView. Also you should set UIImageView content mode to the none-resizing one. It gave me significantly scrolling improvement after other ways were already implemented (async cache and others).
{ "language": "en", "url": "https://stackoverflow.com/questions/17336450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Runtime Error 1004 / Error 438 when getting the Text property of a copied button, setting the property works though I've inserted a large number of form controll buttons (with the text "") into an excel worksheet by copy'n'pasting (from another workbook). These buttons are connected to this macro (which is located in PERSONAL.XLSB): Option Explicit Sub ChangeSomething() ' The button which called the macro. Dim b As Button Set b = ActiveSheet.Buttons(Application.Caller) ' Do run the code if the button was not already active. If b.Text <> "x" Then ' SEEMS TO BE THE PROBLEM ' Do something ' Mark the button as activated. b.Text = "x" b.Font.Bold = True ' If the button was already activated, deactivate it. Else 'Mark the button as deactivated. b.Text = " " End If End Sub This set up worked properly before. But since copying, I get Runtime Error 1004 "Unable to set the Text property of the Button class". When handled, the exception seems to be Error 438 "Object Doesn't Support This Property or Method". The Debugging marks the line: If b.Text <> "x" Then What puzzles me is that getting the text property seems to throw the runtime error, but setting the value runs just fine: b.Text = "x" The correct Button in the correct Worksheet of the correct Workbook is changed. As soon as I change the text of the button manually to something other than "", the macro also seems to work. Unfortunately, the inserted buttons do not appear to be included in the list returned by ActiveSheet.Buttons, so I can not loop over them to change their values. I'm not sure if that's appropriate, but I've uploaded here a sample file. A: I'm not sure your question has the right details. If these buttons are indeed Form Controls - and I think they must be because I believe ActiveX controls don't return a Caller - then their parent object is Shapes, and you would call the Text property from the Shape.TextFrame.Characters object. I wonder if your original worksheet had aCollection object called Buttons which contained, perhaps, a list of the buttons in the form of a class object, called Button (hence your error message) and which exposes the properties that are called in your code. Without that collection and class, the code would be more like this: Public Sub ChangeSomething() Dim btn As Shape With Application 'Check for correct data types. If Not TypeOf .ActiveSheet Is Worksheet Then Exit Sub If IsObject(.Caller) Then Exit Sub 'Acquire button On Error Resume Next Set btn = .ActiveSheet.Shapes(.Caller) On Error GoTo 0 'Check for a found button If btn Is Nothing Then Exit Sub End With 'Check for non-actionable button. With btn.TextFrame.Characters If .Count = 0 Then .Text = "x" Exit Sub End If End With 'If we've reached here, it's an actionable button. Debug.Print "Do something." 'Clear the button text. btn.TextFrame.Characters.Text = "" End Sub I rather suspect some half-copied code here, and the rest of the project remains elsewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/58695841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS swift pointer CGPoint startPoint1; CGPoint startPoint2; CGPoint startPoint3; CGPoint startPoint4; - (void)Method { CGPoint* startPoint = NULL; if (panGesture.view == ...) { startPoint = &startPoint1; } else if (panGesture.view == ...) { startPoint = &startPoint2; } if (panGesture.state == UIGestureRecognizerStateBegan) { *startPoint = [panGesture locationInView:...] } else if (panGesture.state == UIGestureRecognizerStateChanged) { CGPoint endPoint = [panGesture locationInView:...]; *startPoint = endPoint; } } CGPoint* startPoint = NULL; startPoint = &startPoint1; *startPoint = endPoint; This three lines of code in Swift 3.0 is how to express Or how do I write the above code into swift A: The problem is that Swift doesn't have pointers in the C sense. Well, it does, sort of, but it's not worth invoking them just to do what you're trying to do. The simplest approach is to rewrite the core of your method to call a function that takes an inout parameter. So let's take the reduction you ask about in your last three lines: CGPoint* startPoint = NULL; startPoint = &startPoint1; *startPoint = endPoint; To do that, we need a general way to set one CGPoint to another by indirection, expressed as a func (because that is the only way to work with an inout parameter). To make it truly general, we may as well make this a generic, so we're not confined to CGPoint alone: func setByIndirection<T>(_ thing1 : inout T, to thing2: T) { thing1 = thing2 } And now we can test it, doing exactly what you asked to do: var startPoint = CGPoint.zero let endPoint = CGPoint(x:5, y:5) setByIndirection(&startPoint, to: endPoint) print(startPoint) // 5,5 So you see, the use of the inout parameter has allowed us to pass into the function a "pointer" to the CGPoint whose value is to be set, which is what your code is trying to accomplish at its heart. If you're willing to "damage" your original endPoint, you don't even need to write setByIndirection; you can use the built-in swap: var startPoint = CGPoint.zero var endPoint = CGPoint(x:5, y:5) swap(&startPoint, &endPoint) A: In swift, I would use enums and an array. I simplified the code a litte, but I guess you'll get it: var points = [CGPoint(), CGPoint()] enum indexEnum:Int { case startPoint = 0 case endPoint = 1 } func method() { var inx:indexEnum if (1==1) { inx = .startPoint } else { inx = .endPoint } if (2==2) { points[inx.rawValue] = CGPoint(x:10,y:10) } else { points[inx.rawValue] = CGPoint(x:20,y:20) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43336203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel 4 NotFoundHttpException [2014-04-28 12:34:46] production.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' in C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php:140 Stack trace: #0 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(1021): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request)) #1 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(989): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request)) #2 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(968): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request)) #3 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(738): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request)) #4 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(708): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request)) #5 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Http\FrameGuard.php(38): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true) #6 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Session\Middleware.php(72): Illuminate\Http\FrameGuard->handle(Object(Illuminate\Http\Request), 1, true) #7 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true) #8 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true) #9 C:\wamp\www\ppdb\vendor\stack\builder\src\Stack\StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true) #10 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(606): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request)) #11 C:\wamp\www\ppdb\public\index.php(49): Illuminate\Foundation\Application->run() #12 C:\wamp\www\ppdb\index.php(19): require_once('C:\wamp\www\ppd...') #13 {main} [] [] Tried to create a form with laravel , and seems fine when i load the page , the problem is when i try to submit the form this error is getting in log file. Can anyone please check to solve this issue? Thanks in advance A: I missed to add post routing in routes.php Route::post('search', 'SearchController@index'); Post routing did the job for me. Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/23341756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Change file system of Eclipse for procedure/support of "New Web dynamic project" I want to change file system of Eclipse for change "support" or "User interface" (UI) of New Dynamic WEB Project. I have Windows 7 but I am interested also on Linux. Should be easy change file system in Linux and not in Windows. * *What do I would to change? In Eclipse, I press NEW-> Dynamic Web Project, put the name and press Next. We have, in default, this window: Now I have to remove src folder and put new folders src\main\java and src\main\resource. So I will have a folder "Source Folders" of Maven project because I will convert in it. So the result is: - Why not do New Maven Project so I will have these directory java resource. Why I not like the pom.xml of new Maven Project that is in default: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bla</groupId> <artifactId>bla</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>asd Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>bla</finalName> </build> </project> Miss the plugin of maven: <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> If I do, from project Dynamic WEB project and will convert to Maven Project. I will have this pom.xml that is generated from Eclipse: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>HibernateExample</groupId> <artifactId>HibernateExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>HibernateExample</name> <url>http://maven.apache.org</url> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> For me like too the second pom.xml and not get error of miss plugin maven. So today I've got an idea: * *Why not change the program files (say inside folder Eclipse) and change line of folder " Source Resource"? So I will have the new default windows (see second image) in every time when I create Dynamic WEB Project. I hope the title is correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/30888201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Django REST Framework with sessions-based CSRF I am using Django + Django REST Framework in an environment where I cannot use cookie-based CSRF tokens; therefore I must run with CSRF_USE_SESSIONS = True. The DRF web UI, however, depends on this cookie for all interactions. It appears this is set by reading the csrftoken cookie and settings the X-CSRFToken header on the subsequent request, which is then consumed by django.middleware.csrf.CsrfViewMiddleware.process_view() if the hidden field is not included in the request body. This is set in this code from rest_framework.templates.rest_framework.base.html: <script> window.drf = { csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}", csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}" }; </script> DRF forms that do not use POST do contain the CSRF token in the form body, so not having the cookie means the web interface does not have access to the CSRF token at all, causing all PUT, PATCH, and DELETE requests to fail with a 403 response. I believe this is a bug in DRF, but it is possible this is intended behavior. Can someone explain how DRF is intended to be used with CSRF_USE_SESSIONS = True? A: This was fixed in https://github.com/encode/django-rest-framework/pull/6207 and released as part of DRF 3.9.2. More complete context can be read at https://github.com/encode/django-rest-framework/issues/6206.
{ "language": "en", "url": "https://stackoverflow.com/questions/52461537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Print vowels from the vector I need to execute the vowels from the LETTERS R build-in vector "A", "E", etc. > LETTERS [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" [25] "Y" "Z" Maybe, someone knows how to do it with if() or other functions. Thank you in advance. A: Looks like you need extract vowels, does this work: > vowels <- c('A','E','I','O','U') > LETTERS[sapply(vowels, function(ch) grep(ch, LETTERS))] [1] "A" "E" "I" "O" "U" >
{ "language": "en", "url": "https://stackoverflow.com/questions/64456929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert number into amount of space I have a number and want it to generate to a string with corresponding space For Example: var NumberOfSpace = 3; // This will result in a string with 3 empty space // the result will be " " var space = convertToSpace(NumberOfSpace); A: You can simply use the String.prototype.repeat method: " ".repeat(3); A polyfill for older browsers. A: Here is a convertToSpace function var convertToSpace = function (spaces) { var string = ""; for (var i = 0; i < spaces; i++) { string += " "; } return string; } A: A concise option: function convertToSpace(n) { return new Array(n + 1).join(' ') } A: Using Array#fill and Array#reduce The fill() method fills all the elements of an array from a start index to an end index with a static value. The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. var NumberOfSpace = 3; function convertToSpace(param) { return new Array(param).fill(' ').reduce(function(a, b) { return a + b; }); } var space = convertToSpace(NumberOfSpace); console.log(space);
{ "language": "en", "url": "https://stackoverflow.com/questions/38939105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: webkit framework iphone i am not able to add webkit framework in my application. Getting error which says no such framework is available. A: The WebKit framework is not available on iPhone - it's only for Macs. The nearest you can get is adding a UIWebView to your app, which gives you a WebKit-based HTML window.
{ "language": "en", "url": "https://stackoverflow.com/questions/4537914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQLite Trigger issue - "No such column" I have a sqlite database with a table named Achievements, it stores whether certain achievements have been met in a simple quiz I am building (iphone project to learn objective-c). The table structure is: ID Name Completed ============================= 1 FiveInARow 0 2 TenInARow 0 3 AllCorrect 0 4 UnderASecond 0 5 AllCompleted 0 The ID is the primary key, Name is a VARCHAR and Completed is BOOL (0 for false and 1 for true). I am trying to add a trigger onto the update statements of this table, such that when a Completed column is set to 1 (i.e. achievement completed - this is the only update that will happen on the table) there will be a calculation to see whether all of the other achievements have been completed and if so also update the AllCompleted achievement (ID 5) to 1. The trigger I created is: CREATE TRIGGER "checkAllAchievements" AFTER UPDATE ON "Achievements" WHEN (Select SUM(Completed) from Achievements) = (Select COUNT(Completed) -1 from Achievements) BEGIN UPDATE Achievements SET Completed = 1 WHERE Name= 'AllCompleted'; So what I am trying to do is take the sum of the completed row and compare it to the total count minus 1, if they match then it means that all achievements apart from the AllCompleted achievement are achieved so we can also set that to true. The trigger gets created fine. Now on to the problem - When I attempt to update the table with the following statement UPDATE Achievements SET Completed = 1 WHERE ID = 1 I receive the error message "No such Column Completed". Am I trying to do something that is fundamentally wrong? Is it not possible for me to achieve this using a trigger? Any advice? Thanks. A: Double check that you spelled everything exactly as it is in the database. In your example, you state the table name is "Achievements" however reference "Achievement" in two places. Fixing that should solve your issue. Final SQL is as follows: CREATE TRIGGER "checkAllAchievements" AFTER UPDATE ON Achievements WHEN (SELECT SUM(Completed) FROM Achievements) = (SELECT COUNT(Completed)-1 FROM Achievements) BEGIN UPDATE Achievements SET Completed=1 WHERE Name='AllCompleted'; END; A: typically this would be a mutation in the table you are updating... the trigger should just set the value something like new_rec.completed := 1; not try to do another update. (excuse my Oracle syntax) A: I think you should not update a table from a trigger on updating of that table, could be a infinite recursion. Maybe SQLite doesn't like that, but give a bad diagnositic
{ "language": "en", "url": "https://stackoverflow.com/questions/7616161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Amp Contact form error when submitting Anyone can help me work out in using the AMP Contact form? I am doing a subscribe form using Mailchimp and SendEngine and I embedded the form to my HTML page. Here is the screenshot of the error: A: This happens when you try to submit to a domain different than your AMP site. You need to whitelist your AMP domain on your server to enable CORS or contact Administrator if it's a shared hosting for your AMP domain to be whitelisted for CORS. Read further about CORS on AMP. Also check out specs on CORS Whitelisting.
{ "language": "en", "url": "https://stackoverflow.com/questions/47167885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return the id of a mui datagrid row from an onClick event I'm trying to use a material-ui datagrid that's being populated by a sql database to be able to edit what's inside of the database, I want that to be done via a form instead of simply editing the rows and cells individually. I want to pass the id of the specific row as an argument into a function that will patch that row, using the id I can actually select the row inside of the database and then use a dialog form to update the individual data columns. I've looked into the docs and anything that it seems to say would work just doesn't. I can't import the GridApi from @mui/x-data-grid-pro or @mui/x-data-grid-premium despite those being installed to make it work, getRowId seems to be a means of setting the row id rather than getting it, and the code snippets I've been able to find don't work either <DataGrid onComponentMount={getComponents()} {/*Calls on the database to get the rows and places the resulting array into the rows variable using sqlalchemy and fastapi */} rows={rows} columns={columns} {/* contains columns id, description, stock */} pageSize={6} rowsPerPageOptions={[6]} onRowClick={()=>{selectComponents(((index) => {index.api.getRowIndex(index.rows.id)}))}} /> A: onRowClick={(rows)=>{selectComponents(rows.id)}} This is the answer. Now when I click a row, it will return the row id as an argument in my function. Now I can simply click a row and use that info to open a dataform modal that comes pre-filled out with info that can change and then either be pushed to the database or canceled without saving
{ "language": "en", "url": "https://stackoverflow.com/questions/74210704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: make table out of several files and combine into one matrix table I have these files (https://github.com/learnseq/RNAseqcollection.git) that I want to merge(combine) the second column of each into one table with reference name. I have two issues: how to enforce column conversion from factor to another type (because I'm getting error when I try) and how to join them with shorter code. I want this out put (for example one row of the output): Geneid MCL1.DG MCL1.DI MCL1.DK MCL1.LA MCL1.LC MCL1.LE MCL1.DH MCL1.DJ MCL1.DL MCL1.LB MCL1.LD MCL1.LF 1 100008567 0 0 0 0 0 0 0 0 0 0 0 0 I tried this: files = list.files(path=".", pattern="MCL") file1 = read.table("MCL1-DG.txt", col.names=c("Geneid","MCL1-DG" )) file2 = read.table("MCL1-DI.txt", col.names=c("Geneid","MCL1-DI" )) file3 = read.table("MCL1-DK.txt", col.names=c("Geneid","MCL1-DK" )) file4 = read.table("MCL1-LA.txt", col.names=c("Geneid","MCL1-LA")) file5 = read.table("MCL1-LC.txt", col.names=c("Geneid","MCL1-LC")) file6 = read.table("MCL1-LE.txt", col.names=c("Geneid","MCL1-LE")) file7 = read.table("MCL1-DH.txt", col.names=c("Geneid","MCL1-DH")) file8 = read.table("MCL1-DJ.txt", col.names=c("Geneid","MCL1-DJ")) file9 = read.table("MCL1-DL.txt", col.names=c("Geneid","MCL1-DL")) file10 = read.table("MCL1-LB.txt", col.names=c("Geneid","MCL1-LB")) file11 = read.table("MCL1-LD.txt", col.names=c("Geneid","MCL1-LD")) file12 = read.table("MCL1-LF.txt", col.names=c("Geneid","MCL1-LF")) out.file = merge (file1, file2, by=c("Geneid")) out.file2 <- merge(out.file, file3, by=c("Geneid")) out.file3 <- merge(out.file2, file4, by=c("Geneid")) out.file4 <- merge(out.file3, file5, by=c("Geneid")) out.file5 <- merge(out.file4, file6, by=c("Geneid")) out.file6 <- merge(out.file5, file7, by=c("Geneid")) out.file7 <- merge(out.file6, file8, by=c("Geneid")) out.file8 <- merge(out.file7, file9, by=c("Geneid")) out.file9 <- merge(out.file8, file10, by=c("Geneid")) out.file10 <- merge(out.file9, file11, by=c("Geneid")) out.file11 <- merge(out.file10, file12, by=c("Geneid")) A: This seems to work quite well: files = list.files(path=".", pattern="MCL") table_list <- lapply(X = files, FUN = read.table, header=TRUE) combined <- Reduce(f = merge, x = table_list) We first loop over the table names with lapply and read each one in, returning a list. By using header=TRUE we can avoid having to rename each one and instead deduce the column names from the first row of each file. Then we can use Reduce to repeatedly merge each table with the next one. merge is smart enough to assume that the shared column name is the thing we want to merge on, so we don't need to specify arguments there either. I didn't download all the files but here's the output from running this code on the first 3:
{ "language": "en", "url": "https://stackoverflow.com/questions/64547554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect if a fs writable stream is full I'm opening a writable stream to a device (e.g: /dev/disk2) with fs.createWriteStream(). Assuming I don't know the device size in advance, how could I correctly detect if the device can't receive more data (e.g: the device doesn't have any more space)? If I simulate such scenario, I eventually get an EIO error emitted from the stream: Error: EIO: i/o error, write at Error (native) errno: -5, code: 'EIO', syscall: 'write', type: 'write' But then an EIO is too generic, and can be thrown in other situations as well. I'm inspecting the properties of the stream object once the error is thrown but there doesn't seem to exist a flag I could use to determine this.
{ "language": "en", "url": "https://stackoverflow.com/questions/38510821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does passing a value type in an "out" parameter cause the variable to be boxed? I'm aware that boxing and unboxing are relatively expensive in terms of performance. What I'm wondering is: Does passing a value type to a method's out parameter cause boxing/unboxing of the variable (and thus a performance hit)? Can the compiler optimize this away? int number; bool result = Int32.TryParse(value, out number); A: No boxing, compiler uses the ldloca.s instruction which pushes a reference to the local variable onto the stack (http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldloca_s(VS.71).aspx) .method private hidebysig static void Func() cil managed { .maxstack 2 .locals init ( [0] int32 num, [1] bool flag) L_0000: nop L_0001: ldstr "5" L_0006: ldloca.s num L_0008: call bool [mscorlib]System.Int32::TryParse(string, int32&) L_000d: stloc.1 L_000e: ret } A: No, there is no Boxing (required/involved). When you do Box a variable, changes to the boxed instance do not affect the original. But that is exactly what out is supposed to do. The compiler 'somehow' constructs a reference to the original variable. A: As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable. You are not doing anything to the value of the variable. You're making two variables represent the same storage location. Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.) A: There is no boxing; what the out parameter does is specifies that number must be assigned to within the TryParse method. Irrespective of this, it is still treated as an int, not an object.
{ "language": "en", "url": "https://stackoverflow.com/questions/4807086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Test Custom Gradle plugin after Evaluate I'm developing a Gradle custom plugin and I'm having issues on how to test it. The plugin creates an extension to receive configuration and after evaluation (project.afterEvaluate {) creates a tasks with the received configuration, those values are @Input on tasks. Following the documentation https://docs.gradle.org/current/userguide/custom_plugins.html to create a test for the plugin, I use the following to create the project and apply the plugin @Before fun setup() { project = ProjectBuilder.builder().build() project.pluginManager.apply("my.plugin.name") and then test that extension got created: assertTrue(project.extensions.findByName("name") is MyConfigType) and the task got created: assertTrue(project.tasks.findByName("mytask") is MyTaskType) The issue I'm having is that the task is only created afterEvaluate, so this test is failing. As far as I understood, it has to be afterEvaluate so that it can receive the configuration values. So the only way I could see if I could on the test force this project to be evaluated, but how? Is there maybe a different way to receive values? A: I posted my similar question in the gradle forums and was able to solve the issue: https://discuss.gradle.org/t/unit-test-plugins-afterevaulate/37437/3 Apparently afterEvaluate is not the best/right place to perform the task creation. If you have a DomainObjectCollection in your extension and want to create a task for each element in the collection, task creation should be done in the all-Callback of the collection: final MyExtension extension = project.getExtensions().create("extension", MyExtension.class); extension.configurations.all((c) -> { // register task here }); If you have simple properties in the extension that are feed to the task as input, you should use lazy configuration: public class MyExtension { public final Property<String> property; public final NamedDomainObjectContainer<Configuration> configurations; @Inject public MyExtension(final ObjectFactory objectFactory) { property = objectFactory.property(String.class).convention("value"); configurations = objectFactory.domainObjectContainer(Configuration.class); } } public abstract class MyTask extends DefaultTask { @Input private final Property<String> property = getProject().getObjects().property(String.class); public Property<String> getProperty() { return property; } } And the apply method: public class MyPlugin implements Plugin<Project> { @Override public void apply(final Project aProject) { final MyExtension extension = aProject.getExtensions().create("extension", MyExtension.class); aProject.getTasks().register("myTask", MyTask.class).configure((t) -> { t.getProperty().set(extension.property); }); } } A: You should call project.evaluationDependsOn(":"): @Before fun setup() { project = ProjectBuilder.builder().build() project.pluginManager.apply("my.plugin.name") project.evaluationDependsOn(":") // <<-- ... } It executes your afterEvaluate callback.
{ "language": "en", "url": "https://stackoverflow.com/questions/60989927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Socket programming: Struct sockaddr VS struct sockaddr_in I have seen the question similar question below: struct sockaddr_un v/s sockaddr - C(Linux) But I am still very unclear about what the difference is between sockaddr_in and sockaddr, every socket method/function I.e bind, connect, seems to use sockaddr and not sockaddr_in, are these structures interchangeable? if only sockaddr is used then why is there the _in one? I prefer the _in seems more detailed and sorted. Delete the post or so if I have broken any rules ;( most of the time the 3rd parameter is the addr_len is this used to quickly differentiate between ipv4 and ipv6? A: The sockaddr is a generic socket address. If you remember, you can create TCP/IPv4, UDP/IPv4, UNIX, TCP/IPv6, UDP/IPv6 sockets (and more!) through the same operating system API - socket(). All of these different socket types have different actual addresses - composed of different fields. sockaddr_in is the actual IPv4 address layout (it has .sin_port and .sin_addr). A UNIX domain socket will have type sockaddr_un and will have different fields defined, specific to the UNIX socket family. Basically sockaddr is a collection of bytes, it's size being the maximum of sizes of all supported (by the O/S) socket/address families such that it can hold all of the supported addresses. A: Taking a look at sockaddr_in struct sockaddr_in { __SOCKADDR_COMMON (sin_); in_port_t sin_port; /* Port number. */ struct in_addr sin_addr; /* Internet address. */ /* Pad to size of `struct sockaddr'. */ unsigned char sin_zero[sizeof (struct sockaddr) - __SOCKADDR_COMMON_SIZE - sizeof (in_port_t) - sizeof (struct in_addr)]; }; And if we see sockaddr * Structure describing a generic socket address. */ struct sockaddr { __SOCKADDR_COMMON (sa_); /* Common data: address family and length. */ char sa_data[14]; /* Address data. */ }; So actually, they are not exchangeable, but but they have the same size so you can use it with no problem and cast between those structures. But remember you must know what you are doing or probably will get segfaults or unexpected behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/29649348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Call function on Main Module I have a VB.NET script that creates mail accounts using smartermail webservice, i know nothing of VB.Net but i have a little knowledge of programming. I created a new project on Visual Studio 2012 and know i need to call the function that creates the accounts on the main module to run it, that's a console app project. Main Module (Module1.vb) is as follows: Module Module1 Sub Main() End Sub End Module* My function is: Sub fnc_CriaContas_Email_Lote() It's on the file cria_contas_lote.vb in the same directory. Content of cria_contas_lote.vb: Sub fnc_CriaContas_Email_Lote() Dim oPainelWS As PainelControle.svcSmarterMail Dim sRetorno As String = "" Try 'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx") Catch ex As Exception Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message) Exit Sub End Try Dim sNomeArquivo As String = "C:\dir\emails.xlsx" Dim sSQL As String = "" Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0" Dim oExcel As New OleDbConnection(stringExcel) Try oExcel.Open() Catch ex As Exception Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo) Console.Write(vbCrLf & "================================================") Console.Write(vbCrLf & ex.Message) Console.Write(vbCrLf & "================================================") Exit Sub End Try Dim oDataSet As New DataSet Try Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel) oExcelAdapter.Fill(oDataSet, "conteudo") Catch ex As Exception Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP") oExcel.Close() Exit Sub End Try oExcel.Close() Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView Dim lTotal As Long = 0 Dim lErro As Long = 0 Dim oLinha As DataRow Dim iTamanhoCaixa As Integer = 1024 Dim sComCopia As String For Each oLinha In oDataSet.Tables("conteudo").Rows If Not (Trim(oLinha("conta").ToString) = "") Then Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...") sRetorno = "" sComCopia = Trim(oLinha("enviar_copia").ToString) iTamanhoCaixa = oLinha("tamanho_mb") sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password") 'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "") Console.WriteLine("Retorno: " & sRetorno) 'If Not (sRetorno = "OK") Then 'Exit Sub 'End If Threading.Thread.Sleep(100) End If Next End Sub Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String If Not (iTamanhoCaixaKB > 1) Then Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB" End If Dim aContaNome As String() = Split(sConta, "@") Dim sContaNome As String = "" Dim sDominio As String = "" sContaNome = aContaNome(0) sDominio = aContaNome(1) Dim oUsuarios As New svcUserAdmin Dim oUsuarioInfo As New SettingsRequestResult Dim oResultado As New GenericResult oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB) If (oResultado.Result = False) Then Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message End If If Not (sForwardTo.ToString = "") Then Dim arrInfo(0) As String arrInfo(0) = "forwardaddress=" & sForwardTo.ToString oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo) If (oResultado.Result = False) Then Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message End If End If Return "OK" End Function A: What have you tried? Because as it stands it sounds like all you need to do is Module Module1 Sub Main() fnc_CriaContas_Email_Lote() End Sub Sub fnc_CriaContas_Email_Lote() ' Do something. End Sub End Module If "fnc_CriaContas_Email_Lote" is a class then you might have to do something like: Module Module1 Sub Main() dim email as new cria_contas_lote() email.fnc_CriaContas_Email_Lote() End Sub End Module Without seeing the cria_contas_lote file its hard to know. Edit: Below is how you can call it all from just the module Imports System.Data.OleDb Module Module1 Sub Main() fnc_CriaContas_Email_Lote() End Sub Sub fnc_CriaContas_Email_Lote() Dim oPainelWS As PainelControle.svcSmarterMail Dim sRetorno As String = "" Try 'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx") Catch ex As Exception Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message) Exit Sub End Try Dim sNomeArquivo As String = "C:\dir\emails.xlsx" Dim sSQL As String = "" Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0" Dim oExcel As New OleDbConnection(stringExcel) Try oExcel.Open() Catch ex As Exception Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo) Console.Write(vbCrLf & "================================================") Console.Write(vbCrLf & ex.Message) Console.Write(vbCrLf & "================================================") Exit Sub End Try Dim oDataSet As New DataSet Try Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel) oExcelAdapter.Fill(oDataSet, "conteudo") Catch ex As Exception Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP") oExcel.Close() Exit Sub End Try oExcel.Close() Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView Dim lTotal As Long = 0 Dim lErro As Long = 0 Dim oLinha As DataRow Dim iTamanhoCaixa As Integer = 1024 Dim sComCopia As String For Each oLinha In oDataSet.Tables("conteudo").Rows If Not (Trim(oLinha("conta").ToString) = "") Then Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...") sRetorno = "" sComCopia = Trim(oLinha("enviar_copia").ToString) iTamanhoCaixa = oLinha("tamanho_mb") sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password") 'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "") Console.WriteLine("Retorno: " & sRetorno) 'If Not (sRetorno = "OK") Then 'Exit Sub 'End If Threading.Thread.Sleep(100) End If Next End Sub Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String If Not (iTamanhoCaixaKB > 1) Then Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB" End If Dim aContaNome As String() = Split(sConta, "@") Dim sContaNome As String = "" Dim sDominio As String = "" sContaNome = aContaNome(0) sDominio = aContaNome(1) Dim oUsuarios As New svcUserAdmin Dim oUsuarioInfo As New SettingsRequestResult Dim oResultado As New GenericResult oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB) If (oResultado.Result = False) Then Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message End If If Not (sForwardTo.ToString = "") Then Dim arrInfo(0) As String arrInfo(0) = "forwardaddress=" & sForwardTo.ToString oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo) If (oResultado.Result = False) Then Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message End If End If Return "OK" End Function End Module Your issue is your missing the following types: * *PainelControle.svcSmarterMail *svcUserAdmin *SettingsRequestResult *GenericResult These are not built in .Net types and must be defined in either another file. Once you've found the missing classes just add them into the project and you should be good to go. A: I think you want to make Sub Main run ENTIRE function, and DON'T EXIT as sub main is executed. I have written answer of your question here : VB.net program with no UI Sub Main() 'Write whatever you want, and add this code at the END: Application.Run End Sub
{ "language": "pt", "url": "https://stackoverflow.com/questions/17884097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery mobile theme on dynamic pages My theme is not being carried out on the dynamic pages that are created in the code I have below. on the first menu page it works then all other pages have the default theme not the one I have set in siteData.theme. How can I set this? var siteData = build; $(this).find('[data-role="header"] h3').html(siteData.name); $.mobile.activePage.find('[data-role=header] h3').html(siteData.name); $('div[data-theme]', '#index').data('theme', siteData.theme); //reset all the buttons widgets $.mobile.activePage.find('.ui-btn') .removeClass('ui-btn-up-a ui-btn-up-b ui-btn-up-c ui-btn-up-d ui-btn-up-e ui-btn-hover-a ui-btn-hover-b ui-btn-hover-c ui-btn-hover-d ui-btn-hover-e') .addClass('ui-btn-up-' + $('div[data-theme]', '#index').data('theme')) .attr('data-theme', $('div[data-theme]', '#index').data('theme')); //reset the header/footer widgets $.mobile.activePage.find('.ui-header, .ui-footer') .removeClass('ui-bar-a ui-bar-b ui-bar-c ui-bar-d ui-bar-e') .addClass('ui-bar-' + $('div[data-theme]', '#index').data('theme')) .attr('data-theme', $('div[data-theme]', '#index').data('theme')); //reset the page widget $.mobile.activePage.removeClass('ui-body-a ui-body-b ui-body-c ui-body-d ui-body-e') .addClass('ui-body-' + $('div[data-theme]', '#index').data('theme')) .attr('data-theme', $('div[data-theme]', '#index').data('theme')); $.each(siteData["pages"], function (i, v) { if (!$('#' + v["id"]).length) { // Build nav. $.mobile.activePage.find('[data-role=content]').append('' + '<a href="#' + v["id"] + '" data-role="button">' + v["name"] + '</a>').trigger('create'); var components = {}; var newPage = $("<div data-role='page' id='" + v["id"] + "'><div data-role=header><a data-iconpos='left' data-icon='back' href='#' data-role='button' " + "data-rel='back'>Back</a>" + "<h1>" + v["name"] + "</h1>" + "</div>" + "<div data-role=content>" + pagecontent + "</div>" + "<div data-role='footer'>" + "<h4>" + v["name"] + "</h4>" + " </div>" + "</div>"); newPage.appendTo($.mobile.pageContainer); } }); }); A: From your code it looks like siteData.theme holds the theme name i.e. 'b' so you can just add: $('[data-role=page]').page({ theme: siteData.theme }); To your script. This will not however change the header and footer from the default theme. You could just in the newPage creation add data-theme=siteData.theme depending on whats in siteData.theme of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/16304225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert array object property value into HTML? I wanted to make a simple carousel using DOM manipulation, I don't know if I can do this or not in Angular, but the idea is I created an array of objects with properties that I want to pass to the HTML using interpolation, and I don't know how to do it yet. Here's my code: <div class="container"> <div class="row"> <div class="col-12 text-center"> <h1 class="mt-5 mb-1"><strong>carousel</strong></h1> <div class="container"> <div class="row"> <div class="col-12"> <div class="carousel-container"> <div class="carousel-cell"> <div class="row text-center"> <div class="col-12"> <div class="row carousel-control"> <div class="col-2 carousel-prev fa-2x" (click)="carouselPrev()"> <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon> </div> <div class="col-7 col-md-2"> <div class="carousel-image"> <img [src]="carousel.image" alt="carousel image"> </div> </div> <div class="col-2 carousel-next fa-2x" (click)="carouselNext()"> <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon> </div> </div> </div> <div class="col-12"> <div class="carousel-text mt-4"> <h3>{{carousel.description}}</h3> <p><em> {{carousel.name}}, <span>{{carousel.affiliation}}</span></em></p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> import { Component } from '@angular/core'; import { Router } from '@angular/router'; import {faChevronLeft, faChevronRight, IconDefinition} from '@fortawesome/free-solid-svg-icons'; @Component({ selector: 'app-carousel', templateUrl: './carousel.component.html', styleUrls: ['./carousel.component.scss'] }) export class CarouselComponent implements OnInit { faChevronLeft: IconDefinition = faChevronLeft; faChevronRight: IconDefinition = faChevronRight; carousel = [ { id: 1, name: 'captain america', affiliation: 'camp lehigh', description: 'language!', image: 'http://picsum.photos/200' }, { id: 2, name: 'thor', affiliation: 'asgard', description: 'i am god of thunder!', image: 'http://picsum.photos/200' }, { id: 3, name: 'tony stark', affiliation: 'stark industries', description: 'and i....am..iron man!', image: 'http://picsum.photos/200' } ]; constructor( ) {} ngOnInit() { } carouselPrev() { // i want to make this a control by making the id/index +1 } carouselNext() { // i want to make this a control by making the id/index -1 } } A: You can achieve it using ngFor with index. Live example: https://stackblitz.com/edit/angular-b5qvwy Some code: Basic HTML <h1>{{list[i].name}}</h1> <div (click)="prev()"><</div> <div (click)="next()">></div> Basic TS code export class AppComponent { list = [ { name: "Jhon" }, { name: "Joe" }, { name: "Marth" } ]; i = 0; prev(){ if(this.i > 0){ this.i--; } } next(){ if(this.i < this.list.length -1){ this.i++; } } } For your example, simply do that in the html: <div class="container"> <div class="row"> <div class="col-12 text-center"> <h1 class="mt-5 mb-1"><strong>carousel</strong></h1> <div class="container"> <div class="row"> <div class="col-12"> <div class="carousel-container"> <div class="carousel-cell" *ngIf="carousel[i].id"> <div class="row text-center"> <div class="col-12"> <div class="row carousel-control"> <div class="col-2 carousel-prev fa-2x" (click)="carouselPrev()"> <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon> </div> <div class="col-7 col-md-2"> <div class="carousel-image"> <img [src]="carousel[i].image" alt="carousel image"> </div> </div> <div class="col-2 carousel-next fa-2x" (click)="carouselNext()"> <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon> </div> </div> </div> <div class="col-12"> <div class="carousel-text mt-4"> <h3>{{carousel[i].description}}</h3> <p><em> {{carousel[i].name}}, <span>{{carousel[i].affiliation}}</span></em></p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/56001760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object in Redhat I am using Redhat 6. I am in strange problem. I was working with java 1.6. I updated my system with yum updated automatically openjdk 1.8 got install. I removed the package fro UI. Now when I typed java -version. I get this error Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object. I thought my java is corrupted and I remove java using yum remove java*. Again I installed java. I downloaded the bin file of java 1.6 and extracted it in my home folder. edited .bash_profile and gave the path. run .bash_profile Using . .bash_profile Now when I type java -version I get java version "1.6.0_45" Java(TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode) but when i restart my system and again I type java -version I get the same error saying Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object How do i resolve it?
{ "language": "en", "url": "https://stackoverflow.com/questions/32580306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Count how many arguments passed as positional If I have a function def foo(x, y): pass how can I tell, from inside the function, whether y was passed positionally or with its keyword? I'd like to have something like def foo(x, y): if passed_positionally(y): print('y was passed positionally!') else: print('y was passed with its keyword') so that I get >>> foo(3, 4) y was passed positionally >>> foo(3, y=4) y was passed with its keyword I realise I didn't originally specify this, but is it possible to do this whilst preserving type annotations? The top answer so far suggests using a decorator - however, that does not preserve the return type A: You can create a decorator, like this: def checkargs(func): def inner(*args, **kwargs): if 'y' in kwargs: print('y passed with its keyword!') else: print('y passed positionally.') result = func(*args, **kwargs) return result return inner >>> @checkargs ...: def foo(x, y): ...: return x + y >>> foo(2, 3) y passed positionally. 5 >>> foo(2, y=3) y passed with its keyword! 5 Of course you can improve this by allowing the decorator to accept arguments. Thus you can pass the parameter you want to check for. Which would be something like this: def checkargs(param_to_check): def inner(func): def wrapper(*args, **kwargs): if param_to_check in kwargs: print('y passed with its keyword!') else: print('y passed positionally.') result = func(*args, **kwargs) return result return wrapper return inner >>> @checkargs(param_to_check='y') ...: def foo(x, y): ...: return x + y >>> foo(2, y=3) y passed with its keyword! 5 I think adding functools.wraps would preserve the annotations, following version also allows to perform the check over all arguments (using inspect): from functools import wraps from inspect import signature def checkargs(func): @wraps(func) def inner(*args, **kwargs): for param in signature(func).parameters: if param in kwargs: print(param, 'passed with its keyword!') else: print(param, 'passed positionally.') result = func(*args, **kwargs) return result return inner >>> @checkargs ...: def foo(x, y, z) -> int: ...: return x + y >>> foo(2, 3, z=4) x passed positionally. y passed positionally. z passed with its keyword! 9 >>> inspect.getfullargspec(foo) FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'return': <class 'int'>}) _____________HERE____________ Update Python 3.10 In Python 3.10+ new ParamSpec type annotation was introduced (PEP 612), for better specifying parameter types in higher-order functions. As of now, the correct way to annotate this decorator would be like this: from functools import wraps from inspect import signature from typing import Callable, ParamSpec, TypeVar, TYPE_CHECKING T = TypeVar("T") P = ParamSpec("P") def check_args(func: Callable[P, T]) -> Callable[P, T]: """ Decorator to monitor whether an argument is passed positionally or with its keyword, during function call. """ @wraps(func) def inner(*args: P.args, **kwargs: P.kwargs) -> T: for param in signature(func).parameters: if param in kwargs: print(param, 'passed with its keyword!') else: print(param, 'passed positionally.') return func(*args, **kwargs) return inner Which correctly preserves type annotation: if TYPE_CHECKING: reveal_type(foo(2, 3)) # ─❯ mypy check_kwd.py # check_kwd.py:34: note: Revealed type is "builtins.int" # Success: no issues found in 1 source file A: Adapted from @Cyttorak 's answer, here's a way to do it which maintains the types: from typing import TypeVar, Callable, Any, TYPE_CHECKING T = TypeVar("T", bound=Callable[..., Any]) from functools import wraps import inspect def checkargs() -> Callable[[T], T]: def decorate(func): @wraps(func) def inner(*args, **kwargs): for param in inspect.signature(func).parameters: if param in kwargs: print(param, 'passed with its keyword!') else: print(param, 'passed positionally.') result = func(*args, **kwargs) return result return inner return decorate @checkargs() def foo(x, y) -> int: return x+y if TYPE_CHECKING: reveal_type(foo(2, 3)) foo(2, 3) foo(2, y=3) Output is: $ mypy t.py t.py:27: note: Revealed type is 'builtins.int' $ python t.py x passed positionally. y passed positionally. x passed positionally. y passed with its keyword! A: It is not ordinarily possible. In a sense: the language is not designed to allow you to distinguish both ways. You can design your function to take different parameters - positional, and named, and check which one was passed, in a thing like: def foo(x, y=None, /, **kwargs): if y is None: y = kwargs.pop(y) received_as_positional = False else: received_as_positional = True The problem is that, although by using positional only parameters as abov, you could get y both ways, it would be shown not once for a user (or IDE) inspecting the function signature. I hav a feeling you just want to know this for the sake of knowing - if you really intend this for design of an API, I'd suggest you'd rethink your API - there should be no difference in the behavior, unless both are un-ambiguously different parameters from the user point of view. That said, the way to go would be to inspect the caller frame, and check the bytecode around the place the function is called: In [24]: import sys, dis In [25]: def foo(x, y=None): ...: f = sys._getframe().f_back ...: print(dis.dis(f.f_code)) ...: In [26]: foo(1, 2) 1 0 LOAD_NAME 0 (foo) 2 LOAD_CONST 0 (1) 4 LOAD_CONST 1 (2) 6 CALL_FUNCTION 2 8 PRINT_EXPR 10 LOAD_CONST 2 (None) 12 RETURN_VALUE None In [27]: foo(1, y=2) 1 0 LOAD_NAME 0 (foo) 2 LOAD_CONST 0 (1) 4 LOAD_CONST 1 (2) 6 LOAD_CONST 2 (('y',)) 8 CALL_FUNCTION_KW 2 10 PRINT_EXPR 12 LOAD_CONST 3 (None) 14 RETURN_VALUE So, as you can see, when y is called as named parameter, the opcode for the call is CALL_FUNCTION_KW , and the name of the parameter is loaded into the stack imediately before it. A: You can trick the user and add another argument to the function like this: def foo(x,y1=None,y=None): if y1 is not None: print('y was passed positionally!') else: print('y was passed with its keyword') I don't recommend doing it but it does work A: In foo, you can pass the call stack from traceback to positionally, which will then parse the lines, find the line where foo itself is called, and then parse the line with ast to locate positional parameter specifications (if any): import traceback, ast, re def get_fun(name, ast_obj): if isinstance(ast_obj, ast.Call) and ast_obj.func.id == name: yield from [i.arg for i in getattr(ast_obj, 'keywords', [])] for a, b in getattr(ast_obj, '__dict__', {}).items(): yield from (get_fun(name, b) if not isinstance(b, list) else \ [i for k in b for i in get_fun(name, k)]) def passed_positionally(stack): *_, [_, co], [trace, _] = [re.split('\n\s+', i.strip()) for i in stack] f_name = re.findall('(?:line \d+, in )(\w+)', trace)[0] return list(get_fun(f_name, ast.parse(co))) def foo(x, y): if 'y' in passed_positionally(traceback.format_stack()): print('y was passed with its keyword') else: print('y was passed positionally') foo(1, y=2) Output: y was passed with its keyword Notes: * *This solution does not require any wrapping of foo. Only the traceback needs to be captured. *To get the full foo call as a string in the traceback, this solution must be run in a file, not the shell. A: At the end, if you are going to do something like this: def foo(x, y): if passed_positionally(y): raise Exception("You need to pass 'y' as a keyword argument") else: process(x, y) You can do this: def foo(x, *, y): pass >>> foo(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes 1 positional argument but 2 were given >>> foo(1, y=2) # works Or only allow them to be passed positionally: def foo(x, y, /): pass >>> foo(x=1, y=2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() got some positional-only arguments passed as keyword arguments: 'x, y' >>> foo(1, 2) # works See PEP 570 and PEP 3102 for more.
{ "language": "en", "url": "https://stackoverflow.com/questions/67639234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: iOS app localization I want to localize my app. Should I create a new app in itunesconnect for each country or there is a way to automatically detect the country where user is? Actually my app is game based on Unity3d - is it possible to do it on Unity3d? A: Before Unity starts write these lines to pass the current language into unity NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; NSArray* languages = [defs objectForKey:@"AppleLanguages"]; NSString* preferredLang = [languages objectAtIndex:0]; [[NSUserDefaults standardUserDefaults] setObject: preferredLang forKey: @"language"]; [[NSUserDefaults standardUserDefaults] synchronize]; A: Definitely don't create a new app for each locale. iOS apps are localizable and iTunes Connect allows you to enter different metadata for each language. A: You dont need to make a new app for each language. Try following a guide like SmoothLocalize's tutorial or This one. Then you'll have a Localizable.strings file you need to translate. I usually use SmoothLocalize.com as my translation services, because its cheap and super easy, but you can look around for others or even try to find individual translators yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/12279361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: EF 4 - Lazy Loading Without Proxies I´ve read that proxies are used when wee need to use Lazy Loading and Change Tracking. In other words, to use Lazy Loading I must enable proxies. So far so good. the point is that I can use the code bellow to setup the context to not use a proxy and even yet use lazy loading. ctx = new SchoolEntities(); ctx.ContextOptions.ProxyCreationEnabled = false; ctx.ContextOptions.LazyLoadingEnabled = true; Is the ProxyCreationEnabled property related only to change tracking proxy or am I missing something? Could someone please explain this with some details? Thanks! EDIT1 I´m not using POCO/DbContext. I´m using a regular edmx EF model with ObjectContext. I know the importance of proxies for POCO entities regards to change tracking and lazy loading. By why to use Proxies in a regular EDMX model? A: When using POCO entities with the built-in features of Entity Framework, proxy creation must be enabled in order to use lazy loading. So, with POCO entities, if ProxyCreationEnabled is false, then lazy loading won't happen even if LazyLoadingEnabled is set to true. With certain types of legacy entities (notably those the derive from EntityObject) this was not the case and lazy loading would work even if ProxyCreationEnabled is set to false. But don't take that to mean you should use EntityObject entities--that will cause you more pain. The ProxyCreationEnabled flag is normally set to false when you want to ensure that EF will never create a proxy, possibly because this will cause problems for the type of serialization you are doing. The LazyLoadingEnabled flag is normally used to control whether or not lazy loading happens on a context-wide basis once you have decided that proxies are okay. So, for example, you might want to use proxies for change tracking, but switch off lazy loading.
{ "language": "en", "url": "https://stackoverflow.com/questions/9688966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Custombox and modal using JS I have a modal using custombox that works using a button : <html> <head> <link href="assets/plugins/custombox/dist/custombox.min.css" rel="stylesheet"> <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="assets/css/core.css" rel="stylesheet" type="text/css" /> <link href="assets/css/components.css" rel="stylesheet" type="text/css" /> <link href="assets/css/icons.css" rel="stylesheet" type="text/css" /> <link href="assets/css/pages.css" rel="stylesheet" type="text/css" /> <link href="assets/css/menu.css" rel="stylesheet" type="text/css" /> <link href="assets/css/responsive.css" rel="stylesheet" type="text/css" /> <script src="assets/js/modernizr.min.js"></script> </head> <body> <div id="accordion-modal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content p-0"> <div class="panel-group panel-group-joined" id="accordion-test"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion-test" href="#collapseOne" class="collapsed"> Collapsible Group Item #1 </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse"> <div class="panel-body"> test </div> </div> </div> </div> </div> </div> </div> <button data-toggle="modal" data-target="#accordion-modal">Accordion in Modal</button> <!-- jQuery --> <script src="assets/js/jquery.min.js"></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/detect.js"></script> <script src="assets/js/fastclick.js"></script> <script src="assets/js/jquery.slimscroll.js"></script> <script src="assets/js/jquery.blockUI.js"></script> <script src="assets/js/waves.js"></script> <script src="assets/js/wow.min.js"></script> <script src="assets/js/jquery.nicescroll.js"></script> <script src="assets/js/jquery.scrollTo.min.js"></script> <!-- Modal-Effect --> <script src="assets/plugins/custombox/dist/custombox.min.js"></script> <script src="assets/plugins/custombox/dist/legacy.min.js"></script> <!-- App js --> <script src="assets/js/jquery.core.js"></script> <script src="assets/js/jquery.app.js"></script> </body> </html> I am trying to initiate this modal inside jquery, inside a datatables button with no luck. This is the part of the code in my function : buttons: [ { text: 'My accordion Button', className: "btn-sm", action: function ( e, dt, node, config ) { Custombox.open({ target: '#accordion-modal', effect: 'fadein' }); e.preventDefault(); } } ] The code above works to open other simple modals but not this one. This has to do I guess with the data-toggle="modal" data-target="#accordion-modal" that is contained in the button. From what I understand the data-target is replaced by "target" in js, but the data-toggle is not triggered anywhere. How do I trigger it properly? I attempted to initiate it with $('#accordion-modal').modal('show') but I am not sure where exactly I should put this. If I put it in the beginning it just flashes for a second A: Looks like I only needed : { text: 'My accordion Button', className: "btn-sm", action: function ( e, dt, node, config ) { $('#accordion-modal').modal('show'); e.preventDefault(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/38317649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detecting when right mouse button was clicked only My table has 4 columns, and I only want column 1 to be allowed to be clicked. Also, this code also allows the LEFT mouse button to be used, I only want the RIGHT button. private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: int iCol = jTable1.getSelectedColumn(); if(iCol == 1 && evt.getModifiers() == InputEvent.BUTTON3_MASK) { if(evt.getClickCount() == 2) { int iRow = jTable1.getSelectedRow(); File iFile = new File(jTable1.getValueAt(iRow, iCol).toString()); String iPath = iFile.getAbsolutePath(); File iDir = new File(iPath.substring(0, iPath.lastIndexOf(File.separator))); if(Desktop.isDesktopSupported()) { try { Desktop.getDesktop().open(iDir); } catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } } } } } I'm sorry if this question turned out as 2. A: Lets start with, left button is normally represented by MouseEvent.BUTTON1, then move onto MouseEvent#getModifiers is usually used to provide information about what keys are currently pressed and we begin to see the major problems. The method you really want is MouseEvent#getButton Try run the following example for some ideas ;) public class TestMouseClicked { public static void main(String[] args) { new TestMouseClicked(); } public TestMouseClicked() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new MousePane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class MousePane extends JPanel { private JToggleButton leftButton; private JToggleButton middleButton; private JToggleButton rightButton; public MousePane() { setLayout(new GridBagLayout()); leftButton = new JToggleButton("Left"); middleButton = new JToggleButton("Middle"); rightButton = new JToggleButton("Right"); add(leftButton); add(middleButton); add(rightButton); ButtonGroup bg = new ButtonGroup(); bg.add(leftButton); bg.add(middleButton); bg.add(rightButton); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println(e.getButton()); if (e.getButton() == MouseEvent.BUTTON1) { leftButton.setSelected(true); } else if (e.getButton() == MouseEvent.BUTTON2) { middleButton.setSelected(true); } else if (e.getButton() == MouseEvent.BUTTON3) { rightButton.setSelected(true); } } }); } } } A: Concerning the clicking only of a specific column: 1. create the table using you own model. final JTable table = new JTable( new MyTableModel(data, columnNames)); 2. create the new model overriding the function you need (i.e. isCellEditable) public class MyTableModel extends DefaultTableModel { private static final long serialVersionUID = -8422360723278074044L; MyTableModel(Object[][] data, Object[] columnNames ) { super(data,columnNames); } public boolean isCellEditable(int row,int cols) { if(cols==1 ){return true;} return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/13148315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Laravel 5.1 AJAX Response always causes a connection reset I have a problem with a Laravel AJAX response. The request is GET not POST This is the API URL: http://example.com/app/public/index.php/api/userdata and I never receive an AJAX response. In my Chrome browser I get the following error net::ERR_CONNECTION_RESET, but when I go to the API URL directly from Chrome I get the JSON response and it's correct. This only happens for AJAX requests and I also have "Provisional headers are shown" in my AJAX request. I'm using Ember for AJAX requests, but I also tried using jQuery $.getJSON and I got the same result. I read some discussion about "Laravel Connection Reset" and I tried to disable opcache but this is still happening. This is my enviroment * *PHP Version 7.0 *Laravel 5.1.39(LTS) *Ubuntu 14.04.4 LTS *jQuery 1.11.3 *Ember 2.0.2 This is my controller code : public function index() { $inputs = Input::all(); $userData = UserData::inMyCompany(); if(isset($inputs['filters'])) { foreach($inputs['filters'] as $field => $value) { $userData->where($field, '=', $value); } } $userData->with([ 'userDataRelation1', 'userDataRelation2', ]); $userData = $userData->get(); return Response::json($userData); } This is my JavaScript code : <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script> <script> $(document).ready(function(){ var url = 'http://example.com/app/public/index.php/api/userdata?filters[id]=633'; $.getJSON(url, function(response){ console.log(response); }); }); </script> Why does the AJAX request always return a "Connection Reset" ? What is the possible cause for this ? How to fix the problem ? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/37872474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 2D fused Lasso with Matlab CVX I wrote a 2D fused lasso code here. [m n] = size(circle); cvx_begin variable theta(m, n); minimize( norm(circle-theta, 'fro')); subject to sum(sum(abs(theta(:,1:n-1)-theta(:,2:n)))) == 0; sum(sum(abs(theta(1:m-1,:)-theta(2:m,:)))) == 0; cvx_end Weirdly, the program report, In cvxprob (line 28) In cvx_begin (line 41) Error using cvxprob/newcnstr (line 192) Disciplined convex programming error: Invalid constraint: {convex} == {constant} Error in == (line 12) b = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '==' ); After I remove abs() in the constraint, the program could run, but that's not what constraints I expect to be. A: I think you can try stacking the matrices into vectors, then use L1 norm. In CVX, it's just norm(variable, 1). It will do the same as you wrote here: sum of absolute elementary-wise differences.
{ "language": "en", "url": "https://stackoverflow.com/questions/39409116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ActionController::UnknownFormat in HelpController#about as a Ruby newbie I am still getting to grips with the language. I have created a broadcast controller for a simple database that is already being used in production. However, I am getting the above mentioned error. Below is the code I have used: show.html.erb <p id="notice"><%= notice %></p> <%= link_to 'Edit', edit_broadcast_path(@broadcast) %> | <%= link_to 'Back', broadcasts_path %> Index.html.erb index.html.erb broadcasts_controller.rb boradcast controller help controller class HelpController < ApplicationController skip_before_action :authenticate_user! def about #render text: "Hello" end end I am not sure if I am missing any files or configs, I will add them in the comments if need be. Thanks A: Incoming requests may use headers or parameters to indicate to Rails what format, called "MIME type", the response should have. For instance, a typical GET request from entering a URL into your browser will ask for an HTML (or default) response. Other types of common responses return JSON or XML. In your case your "about" action does not have any explicit responders, and because of that Rails can't match the requested format (which is what the error message is trying to convey). You will probably just want to add an HTML template app/views/help/about.html.erb with your content. Rails should identify the HTML template and handle things from there. More info In Rails you need to respond with a specific format, and it is easy to setup your controller actions to handle a variety of formats. Here is a snippet you might find in a controller which can respond in 3 different ways. respond_to do |format| format.html { render "foo" } # renders foo.html.erb format.json { render json: @foo } format.xml { render xml: @foo } end You can see more examples and deeper explanations in the documentation here. ActiveRecord helps because it comes with serializers out of the box which can create JSON and XML representations of your objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/45635251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if the same letter is used more than once in a word (hangman project, javascript) I have almost finished the javascript logic for my personal hangman project i am creating. One of the final issues i am having is getting the program to recognize if the same letter is used in the "chosen word". For example, when "ninja" is selected as the "chosen word", and the user selects "n", i would like my counter variable to recognize that there are two "n's", and add 2 to the score instead of one. My code thus far: var secretWords = ["batman", "Donkey kong", "ninja", "programming"]; var chosenWord = secretWords[Math.floor(Math.random()*secretWords.length)]; var guesses = 8; console.log(chosenWord); var letters = chosenWord.length; var counter = 0; var gameOver = guesses === 0; console.log(guesses); console.log(counter); while(guesses !== 0){ const guess = prompt("GUESS A LETTER") var guessLowerCase = guess.toLowerCase(); var isGuessedLetterInWord = chosenWord.includes(guessLowerCase); if (isGuessedLetterInWord) { alert('nice'); counter ++; } else { alert('wrong'); guesses --; } } if(counter === chosenWord.length){ alert("You Win!!"); } if (guesses === 0){ alert("LOSER!"); } A: A simple hack would be to split the string by letter and count. let occurances = chosenWord.split(guessLowerCase).length - 1 Or you could use regular expression to search for all occurances: let occurances = [...chosenWord.matchAll(new RegExp(guessLowerCase, 'g'))].length
{ "language": "en", "url": "https://stackoverflow.com/questions/60623828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing data from a List using jsp I have a bean that has the follwing: public DeptLibraryEntry(int id, String type, String name, String info, Boolean avail){ this.id = id; this.type = type; this.name = name; this.info = info; this.avail = avail; this.log = new ArrayList<Log>(); } and another bean called Log.It is the following: public Log(String num, String name, String dateBorrowed, String dateReturned){ this.num = num; this.name = name; this.dateBorrowed = dateBorrowed; this.dateReturned = dateReturned; } I want to list the "num","name","dateBorrowed" and "dateReturned" in a JSP. I am trying the following code in my JSP: <c:forEach items="${entries}" var="entry"> <tr><td>${entry.Log.num}</td></tr> </c:forEach> I've tried some variations of this but can't seem to get it. Any help would be appreciated! A: Thiss assumes that entries is a list/collection of DeptLibraryEntry. Note that log (and not Log, capitalization is important!) is itself a list of items, so to get the value of each item you have to iterate over it again <c:forEach items="${entries}" var="entry"> <c:forEach items="${entry.log}" var="logItem"> <tr><td>${logItem.num}</td></tr> .... </c:forEach> </c:forEach> Of course, your classes will need to have the appropiate getters to access the properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/26876828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change row names based off input from different dataframe Say I have df1 that contains names in column 1 and numerical values in the other columns, and I have df2 that contains the same set of names in column 2 and a unique corresponding identifier in column 1. The order of the names in the dfs don't match so I need a way to replace df1 names with df2 identifiers. I know I can do something similar with the dplyr rename function but my dataframes are HUGE so that's a lot to manually write out. I thought this could be done in base R with a simple for/if loop using logical arguments but I feel like there has to be an easier way? Any help, tips or tricks would be appreciated. For example: View(df1) Name Value etc. Heart 2 ... Brain 5 ... Blood 10 ... Lung 3 ... ... ... ... View(df2) ID Type H Heart L Lung Br Brain Bl Blood ... ... After code: View(df1) Name Value etc. H 2 ... Br 5 ... Bl 10 ... L 3 ... ... ... ...
{ "language": "en", "url": "https://stackoverflow.com/questions/73708740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: need help in mvvmcross windows phone 8 fluent binding with conversion I'm Little stuck in getting the fluent binding/conversion to Work. I have the following to work set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay() but when I try to add a WithConversion, I need some help in how to get the converter called set.Bind(TextBackStartColor).For(v => v.Text).To(vm => vm.TextBackStartColor).TwoWay().WithConversion("Test") In xaml the converter works fine, in Android and Touch the above converter works fine. I've tried in CORE: public sealed class TestValueConverter : MvxValueConverter<string, string> { protected override string Convert(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string test = (string)value + "test"; return test; } public string ConvertBack(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value; } } and the corresponding Phone/NativeConverters: namespace DCS.Phone.NativeConverters { public class NativeTestValueConverter : MvxNativeValueConverter<TestValueConverter> { } } I've also tried in Phone/Converters public sealed class TestConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string test = (string)value+"test"; return test; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } But my converters are never getting called. As I said my bindings works very well, so what am I missing in Phone project to get the converters called? A: Android and iOS both automatically pick up the ValueConverter names - the mechanism they do this by is described in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid Windows platforms don't do this by default - because Windows uses Xaml binding by default. If you want to add this use of named value converters, then you can do this using code in your Windows Setup.cs like: // call this in InitializeLastChance Mvx.CallbackWhenRegistered<IMvxValueConverterRegistry>(FillValueConverters); // add this method private FillValueConverters(IMvxValueConverterRegistry registry) { registry.Fill(ValueConverterAssemblies); } // add this property protected virtual List<Assembly> ValueConverterAssemblies { get { var toReturn = new List<Assembly>(); toReturn.AddRange(GetViewModelAssemblies()); toReturn.AddRange(GetViewAssemblies()); return toReturn; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/22402797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to to solve the responsiveness of mouseover and mouseout I am sliding a div whenever there is a mouse over event and sliding it back(hiding) when there is mouse out event. If I do too fast mouse out and mouse over, the div keeps oscillating. How do I fix this problem? $(document).ready(function() { $("#in").ready(function(){ $("#out").mouseover(function () { $("#in").animate({"height":"toggle",},200); }); }); $("#in").ready(function(){ $("#out").mouseout(function () { $("#in").animate({"height":"toggle",},200); }); }); }); <div id="out"><img src="pics/1.gif" ><div id="in"><h1>Google</h1></div></div> A: you can use stop() method: Stop the currently-running animation on the matched elements. $("#out").mouseover(function () { $("#in").stop(true, true).animate({"height":"toggle"},200); }); A: First of all, you should take the advice given by me and by Raminson. The stop() function will halt all currently running animations on the given element and prevent the behavior you were seeing. Another 2 things can be said about the code you posted. * *You have a trailing comma in the parameters you gave to the .animate() function. {"height":"toggle",}. Now that might work on Chrome and Firefox, but in IE that will probably not work and more over it probably won't tell you where or why it's not working. You should never have trailing commas in an array or object in JavaScript.... *You wrapped your jQuery call in the document ready handler (as you should) but then you wrapped your code within another ready handler for each element.$("#in").ready()... $("#out").ready(). This is unnecessary. You only need one ready function to make sure the DOM and jQuery are loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/11487396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Empty Object ID for first DrEdit Doc in PHP Google API Drive SDK Example Ive worked through several errors to get this far with the Google API Drive PHP DREdit example, and attempted the setup on this. The OAuth2 appears to connect ok, and loading the DrEdit demo page. However on first save the doc has no ID, and the DrEdit frontends /public/js/controller.js handles this with: ... if ($routeParams.id ) { editor.load($routeParams.id); } else { // New doc, but defer to next event cycle to ensure init $timeout(function () { editor.create(); }, 1); } To me, this means get the ID the second time the doc is saved because it won't be present at the first time. Chrome console output (not expanded) shows on first menu File > Save: Object {id: ""} controllers.js:14 Creating new doc angular-1.0.0.js:5525 Updating editor Object {content: "", labels: Object, editable: true, title: "Untitled document", description: ""…}content: nulldescription: ""editable: truelabels: ObjectmimeType: "text/plain"resource_id: nulltitle: "Untitled document"proto: Object angular-1.0.0.js:5525` Then second save in the File menu: Saving file true angular-1.0.0.js:5525 Saving Object {content: "", labels: Object, editable: true, title: "Untitled document", description: ""…} angular-1.0.0.js:5525 Saved file Object {data: Object, status: 200, headers: function, config: Object} angular-1.0.0.js:5525 Object {id: "[object Object]"} controllers.js:14 Loading resource [object Object] Object {} angular-1.0.0.js:5525 Saving file false angular-1.0.0.js:5525 Saving Object {content: "abc", labels: Object, editable: true, title: "Untitled document", description: ""…} angular-1.0.0.js:5525 PUT http://company.com/svc?newRevision=true 500 (Internal Server Error) I'm concerned with the Object {id: "[object Object]"} but a little stuck. $routeParams.id on first go does not appear to have a valid file ID but not sure if its supposed to until the second save. PHP SLIM framework consequently complains with ErrorException Undefined property: stdClass::$id How do I diagnose further? A: It appears that there maybe a bug in the sample leading to this error. Please file an issue in the GitHub project's issue tracker so we can follow up.
{ "language": "en", "url": "https://stackoverflow.com/questions/26084958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: COUNT DISTINCT / nunique within groups I want to count the number of distinct tuples within each group: df = pd.DataFrame({'a': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'b': [1, 2, 1, 2, 1, 2, 1, 2], 'c': [1, 1, 2, 2, 2, 1, 2, 1]}) counts = count_distinct(df, by='a', columns=['b', 'c']) assert counts == pd.Series([4, 2], index=['A', 'B']) In other words, counts should report that for group 'A', there are four distinct tuples and for group 'B', there are two. I tried using df.groupby('a')['b', 'c'].nunique(), but nunique works only with a single column. I know I could count distinct tuples by df.groupby(['b', 'c']), but that means I have use a slow apply with a pure python function (the number of groups of column 'a' is large). I could convert the 'b' and 'c' columns into a single column of tuples, but that would be super slow since it will no longer use vectorized operations. A: I think your logic is equivalent to count the size of data frames grouped by column a after dropping the duplicated values of combined columns a, b and c, since duplicated tuples within each group must also be duplicated records in the data frame assuming your data frame contains only columns a, b and c and vice versa: df.drop_duplicates().groupby('a').size() # a # A 4 # B 2 # dtype: int64
{ "language": "en", "url": "https://stackoverflow.com/questions/39323071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I defined an templated class. Can I see the (source) code that occurs after it is instantiated? C++ I defined an templated class. I'd like to see source code that results when the class is instantiated. For example, imagine I have a class like std::vector from the standard library: template <typename T> class Vector { ... } // this is in the .h and .inl Then I instantiate it vector<int> v = new vector<int>(); Can I see the inlined code that the compiler will create? A: There's no source code, template instantiation isn't a text-replace step. To inspect the generated code you should use a disassembler/debugger or dump (if the compiler supports it) the generated code. Template instantiation is a compilation step and although it can get pretty complex, it generates code and not text. Macros undergo a process similar to what you described: they're processed in the pre-processing stage and they're just plain text substitutions
{ "language": "en", "url": "https://stackoverflow.com/questions/25703952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it safe to have various Perl installations on one machine share a cpan_home? I have a dated system perl 5.8.8 on a Linux machine and installed a 5.12.4 from ActiveState. Both perl's cpan_home is ~root/.cpan. I was about to change the new perl's cpan_home, but then I realized I didn't know whether I really have to do this or whether it would just result in multiple copies of modules being downloaded to different directories when in fact they could be shared. So can they? Is it safe? With regard to compiling? Or do I have to go for separate cpan_home directories? Note that I tried perlbrew first but it failed with Can't load '../lib/auto/IO/IO.so' for module IO: ../lib/auto/IO/IO.so: wrong ELF class: ELFCLASS64 at ../lib/XSLoader.pm line 70. So instead of pursueing the issue I went for ActivePerl, which installs easily. A: I have a dozen builds of Perl on my system, and they all use ~/.cpan. I have never had a problems, but I cannot say that it is safe. It depends on the settings therein. Specifically, * *build_dir_reuse should (probably) be zero. *makepl_arg shouldn't contain INSTALL_BASE. *mbuildpl_arg shouldn't contain --install_base. "Install base" overrides where the modules are installed. If you start installing the modules for all your builds in one location, you will have problems due to incompatibilities between versions, releases and builds of Perl. If you want to share .cpan and have a local install directory, you can probably get away with using PREFIX=/home/username/perl5 LIB=/home/username/perl5/lib instead of INSTALL_BASE=/home/username/perl5. It uses a smarter directory structure. By the way, local::lib causes "install base" to be used, so you'll run into problems if you use local::lib with multiple installs of Perl.
{ "language": "en", "url": "https://stackoverflow.com/questions/9281536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get object property stored in listview from another page wpf This is my class : class Discussion { public String name {get; set;} public String discussionId { get; set; } public List<Message> liste {get; set;} public Discussion(String name, String discussionId) { this.name = name; this.discussionId = discussionId; } I create some instance of this class and I store them in a listview. When I double click on a listViewItem (it only show the name property), I navigate to another page that need to know the discussionId. How can I get this property ? This is how I navigate to the new page : public partial class DiscussionPage : Page { public DiscussionPage() { InitializeComponent(); try { SqlDataReader read = Broker.sqlcommand("SELECT DISCUSSION.TITRE, USER1.NOM FROM dbo.DISCUSSION, dbo.USER1 WHERE USER1.ID = DISCUSSION.ID_CREER;").ExecuteReader(); while (read.Read()) { Discussion d = new Discussion(read["TITRE"].ToString(), read["NOM"].ToString()); listDiscussion.Items.Add(d); } } catch (Exception) { throw; } } private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DependencyObject clickedObj = (DependencyObject)e.OriginalSource; while (clickedObj != null && clickedObj != listDiscussion) { if (clickedObj.GetType() == typeof(ListViewItem)) { Discussion selectedDiscussion = (Discussion)listDiscussion.SelectedItem; this.NavigationService.Navigate(new MessagePage(selectedDiscussion)); break; } clickedObj = VisualTreeHelper.GetParent(clickedObj); } } private void openAddDiscussion(object sender, RoutedEventArgs e) { addDiscussion add = new addDiscussion(); add.Show(); } } I need to know discussionId to load the content of this page : public partial class MessagePage : Page { public MessagePage(Discussion SelectedDiscussion) { InitializeComponent(); try { SqlDataReader read = Broker.sqlcommand("SELECT MESSAGE.TEXT FROM dbo.MESSAGE WHERE MESSAGE.ID_POSSEDER = \'" + SelectedDiscussion.discussionId + "\'").ExecuteReader(); while (read.Read()) { Message m = new Message(read["TEXT"].ToString()); showMessage.Items.Add(m); } } catch (Exception) { throw; } } } Full code added, still don't work with SelectedValue: incoherent Accessibility: parameter type 'commApp.Classes.Discussion' is less accessible than method 'commApp.MessagePage.MessagePage (commApp.Classes.Discussion)' A: Without a good, minimal, complete code example, it's impossible to know for sure what the best approach is. However, if you have set your ListView up correctly and the ItemsSource is a collection of Discussion objects, then by default the SelectedValue property will return the Discussion object instance reference that corresponds to the selected item in the list. In that case, you would just change your code to look like this: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DependencyObject clickedObj = (DependencyObject)e.OriginalSource; while (clickedObj != null && clickedObj != listDiscussion) { if (clickedObj.GetType() == typeof(ListViewItem)) { Discussion selectedDiscussion = (Discussion)listDiscussion.SelectedValue; this.NavigationService.Navigate(new MessagePage(selectedDiscussion)); break; } clickedObj = VisualTreeHelper.GetParent(clickedObj); } } I.e. just use the SelectedValue property instead of SelectedItem. If you have deviated from the default by setting the SelectedValuePath property, then you will want to use the ItemContainerGenerator object to get the correct reference: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DependencyObject clickedObj = (DependencyObject)e.OriginalSource; while (clickedObj != null && clickedObj != listDiscussion) { if (clickedObj.GetType() == typeof(ListViewItem)) { Discussion selectedDiscussion = (Discussion)listDiscussion.ItemContainerGenerator .ItemFromContainer((ListViewItem)listDiscussion.SelectedItem); this.NavigationService.Navigate(new MessagePage(selectedDiscussion)); break; } clickedObj = VisualTreeHelper.GetParent(clickedObj); } } If neither of those seem to apply in your case, please edit your question so that it includes a good code example, with which a better answer can be provided.
{ "language": "en", "url": "https://stackoverflow.com/questions/29929955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle SQL - Return rows with a value based on multiple values in a second field I need to return the rows that contain the employee names (in one field) who are only classified as Managers (not as Workers, or as Managers and Workers). Managers and Workers values are in a second field. So it might look like this: +----------+------------+ | 'Miller' | 'Manager' | | 'Jones' | 'Manager' | | 'Jones' | 'Worker' | +----------+------------+ In this instance I just want it to return 'Miller'. I can get one or both, but not the ones where an employee is only classified as a Manager. Any thoughts? A: One method uses aggregation: select name from t group by name having min(classification) = max(classification) and min(classification) = 'manager'; A: Method with a subquery which should work well when there are not only 'Managers' and 'Workers' in the table: SELECT t1.name FROM t t1 WHERE t1.classification='Manager' AND NOT EXISTS ( SELECT 1 FROM t t2 WHERE t1.name=t2.name AND t2.classification='Worker' ) A: Count the number of titles. If they have a title of 'Manager' and there's only one title, select the individual: SELECT * FROM PEOPLE p INNER JOIN (SELECT NAME, COUNT(TITLE) AS TITLE_COUNT FROM PEOPLE GROUP BY NAME) c ON c.NAME = p.NAME WHERE p.TITLE = 'Manager' AND c.TITLE_COUNT = 1; dbfiddle here
{ "language": "en", "url": "https://stackoverflow.com/questions/53033361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The improper use of a GetX has been detected when using RxList I have created an observable list and then storing data in the list from the api as below class FeedsController extends GetxController { final Rx<List<Stories>> _stories = Rx<List<Stories>>([]); @override void onInit() { super.onInit(); getActiveStories(); } List<Stories> get getStories { return _stories.value; } Future<List<Stories>> getActiveStories() async { var url = Uri.parse(storiesURL); Map<String, Object> params = {'apikey': apiKey, 'userid': "8"}; await http.post(url, body: params).then((value) { StoriesResponse storiesResponse = storiesResponseFromJson(value.body); _stories.value = storiesResponse.stories; }).onError((error, stackTrace) { debugPrint('Error occurred while fetching stories response: ${error.toString()}'); }); return _stories.value; } } Here is the code for displaying the Stories List class _ActiveStoriesListState extends State<ActiveStoriesList> { List<Story> _currentUserStories = []; final FeedsController _feedsController = Get.find(); @override void initState() { Future.delayed(Duration.zero, fetchUserStories); super.initState(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Active Stories', style: titleLargeTextStyle.copyWith(fontSize: 22, fontWeight: FontWeight.w600),), const SizedBox(height: 10), SizedBox( height: 100, child: Obx( () => ListView.builder( shrinkWrap: true, scrollDirection: Axis.horizontal, itemBuilder: (ctx, index) => ActiveStoriesWidget(story: _currentUserStories[index]), itemCount: _currentUserStories.length, ), )), ], ); } void fetchUserStories() async { List<Stories> stories = _feedsController.getStories; stories = stories.where((story) => story.userId == '8').toList(); _currentUserStories = stories[0].story; debugPrint('Active Stories Page: ${_currentUserStories.length}'); } } Solutions I have tried is that make only ListView observable (that didn't work), making ListView parent child Observable that also didn't work. I'm unable to understand where I'm missing. Below is the exception Exception Screenshot sample json data { "status": 200, "success": [ { "user_id": "4", "first_name": "Abu", "profileImage": "jayspur.com/RallyApp/public/uploads/userImages/…", "story": [ { "story": "jayspur.com/RallyApp/public/uploads/userStories/…", "addeddate": "2023-02-08 09:58:11" } ] } ] } A: You are getting this error because you are not using any observable list inside your ListView.builder. But before that you should convert your StatefullWidget to a StatelessWidget because in GetX, we don't need any StatefullWidget. You can try the following code. Controller class FeedsController extends GetxController { final Rx<List<Stories>> _stories = Rx<List<Stories>>([]); List<Stories> currUserstories = []; RxBool isLoading = false.obs; @override void onInit() { super.onInit(); getActiveStories(); } List<Stories> get getStories { return _stories.value; } Future<List<Stories>> getActiveStories() async { isLoading.value = true; var url = Uri.parse("storiesURL"); Map<String, Object> params = {'apikey': apiKey, 'userid': "8"}; await http.post(url, body: params).then((value) { StoriesResponse storiesResponse = storiesResponseFromJson(value.body); _stories.value = storiesResponse.stories; _stories.value = _stories.value.where((story) => story.userId == '8').toList(); currUserstories = _stories.value[0]; }).onError((error, stackTrace) { debugPrint( 'Error occurred while fetching stories response: ${error.toString()}'); }); isLoading.value = false; return _stories.value; } } View file: class ActiveStoriesList extends StatelessWidget { ActiveStoriesList({super.key}); final FeedsController _feedsController = Get.find(); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Active Stories', style: titleLargeTextStyle.copyWith( fontSize: 22, fontWeight: FontWeight.w600), ), const SizedBox(height: 10), SizedBox( height: 100, child: Obx( () => _feedsController.isLoading.value ? const Center( child: CircularProgressIndicator(), ) : ListView.builder( shrinkWrap: true, scrollDirection: Axis.horizontal, itemBuilder: (ctx, index) => ActiveStoriesWidget( story: _feedsController.currUserstories[index]), itemCount: _feedsController.currUserstories.length, ), )), ], ); } } You might have to tweak the code a bit but the core concept it you should do all your work inside the controller and only fetch the data in view file. Also, you should only use the lifecycle which controller provides. Eg. onInit instead of initState. If this dosen't work, try to modify your controller file such that you get the value in the list as you want in the controller file itself and you the list which was preseneted in controller in your view file. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/75420580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define out of class functions for a class specialized using std::enable_if I have a specialization of a class called graph which is enabled only if the input is a particular type. I am not able to define out of class definitions for the functions inside that class. This question os different from some other questions on stack overflow where sfinae happens on member function. Here I want enable if on the class and just define a normal member function for this class outside the class. Note- There are multiple graph classes with different container types. This is an example of just one. I want to be able to define graph_func outside this class template<typename ContainerType, std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type = 0> class graph { . . . void graph_func() const; } I tried this and I get the error that it doesn't refer into any class template <typename ContainerType> void graph<ContainerType, std::enable_if<std::is_same<Graph, Eigen::MatrixXd>::value, int>::type>::graph_func() const { // definition } A: Notice that std::enable_if<..., int>::type in your parameter list is an non-type template argument: template<typename ContainerType, typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type = 0> class graph { void graph_func() const; }; You need to pass the value of that type (In here we just named it _) to the parameter list: template <typename ContainerType, typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type _> void graph<ContainerType, _>::graph_func() const { // definition } See live demo.
{ "language": "en", "url": "https://stackoverflow.com/questions/57735235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Async compression c# i have this code string dirName = "C:\\temp"; if (Directory.Exists(dirName)) { Console.WriteLine(); Console.WriteLine("Файлы:"); string[] files = Directory.GetFiles(dirName); foreach (string s in files) { Console.WriteLine(s); string sourceFile = $"{s}"; string compressedFile = $"{s}z"; Compress(sourceFile, compressedFile); } } it shows me all files in directory and compress it. method compress: public static void Compress(string sourceFile, string compressedFile) { using (FileStream sourceStream = new FileStream(sourceFile, FileMode.OpenOrCreate)) { using (FileStream targetStream = File.Create(compressedFile)) { using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress)) { sourceStream.CopyTo(compressionStream); Console.WriteLine("Compressing file {0} is end. : {1} compressede size is: {2}.", sourceFile, sourceStream.Length.ToString(), targetStream.Length.ToString()); } } } } How can i do async compression of this files? should i use array of tasks? thank you A: * *Make Compress async method public static async Task Compress() { await Task.Run(() => { //your compress logic } } *Call it as awaitable: await Compress(...); You can also use Parallel.ForEach instead of your foreach loop. But be aware that this code won't really execute in parallel. This is because that you are using IO functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/55181238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: String comparison after transfer through TCP socket in C I am sending a file through TCP, and have the server sending a message containing "END_OF_MESSAGE" to alert the client that they have received the whole file and can close the socket. The file is being sent, and the client receives the "END_OF_MESSAGE" string, however, when I use strcmp to compare the received information to "END_OF_MESSAGE", it never says that they match. I have tried strncmp and memcmp but am confused as to why strcmp does not tell me the strings match. Code snippets: Server: char endMessage[MESSAGESIZE] = "END_OF_MESSAGE"; if ((send(clntSocket, endMessage, sizeof endMessage, 0))!= sizeof endMessage) DieWithError("Sending failed"); The above code snippet does get sent. Client: if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ if (!(strcmp(echoBuffer, "END_OF_MESSAGE")==0)){ printf(echoBuffer); /* Print the echo buffer */ printf("\n"); }else{ break; //break out of while loop } the strcmp of the echoBuffer and "END_OF_MESSAGE" never returns 0, even though "END_OF_MESSAGE" is what I am sending from the server..I have tried strncmp to compare the first 3 characters ("END") to no avail. Note: when I print out the echoBuffer, the very last one does print out END_OF_MESSAGE which is just adding to my confusion. Does anyone have any insights into what I am doing wrong? Thank you. A: am sending a file through TCP, and have the server sending a message containing "END_OF_MESSAGE" to alert the client that they have received the whole file and can close the socket. Why? Just close the socket. That will tell the client exactly the same thing.. What you're attempting is fraught with difficulty. What happens if the file contains END_OF_MESSAGE? You're going to need an escape convention, and an escape for the escape, and inspect all the data when both sending and receiving. The actual problem that you're seeing is that END_OF_MESSAGE can arrive along with the last bit of the file, so it isn't at the start of the buffer. But it's all pointless. Just close the socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/43308285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: check ienumerable for any elements I need to check if list has any elements, and the way I'm doing it is with Any(): public static string ToQuotedString(this IEnumerable list) { if (!list.Any()) { return string.Empty; } var output = string.Empty; foreach (var item in list) { output += "'" + item + "',"; } return output.TrimEnd(','); } I am getting the following exception: 'IEnumerable' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) I am referencing System.Linq: using System.Linq; What am I doing wrong? A: If you have a non-generic enumerator, the cheapest way to check for any elements is to check if there's a first element. In this case, hasAny is false: var collection= new List<string>( ) as IEnumerable; bool hasAny = collection.GetEnumerator().MoveNext(); while in this case, it's true: var collection= new List<string>{"dummy"} as IEnumerable; bool hasAny = collection.GetEnumerator().MoveNext(); A: Your parameter is IEnumerable not IEnumerable<T> but the LINQ extension methods are for the latter. So either change the type of the parameter to IEnumerable<string> or use Cast: if (!list.Cast<string>().Any()) { return string.Empty; } If you don't know the type (string in this case) and you just want to know if there's at least one, you can still use Cast and Any because Object works always: bool containsAny = list.Cast<Object>().Any();
{ "language": "en", "url": "https://stackoverflow.com/questions/52894880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: weird problem with select count from multiple tables (with joins) I'm having an odd problem with the following query, it works all correct, the count part in it gets me the number of comments on a given 'hintout' I'm trying to add a similar count that gets the number of 'votes' for each hintout, the below is the query: SELECT h.* , h.permalink AS hintout_permalink , hi.hinter_name , hi.permalink , hf.user_id AS followed_hid , ci.city_id, ci.city_name, co.country_id, co.country_name, ht.thank_id , COUNT(hc.comment_id) AS commentsCount FROM hintouts AS h INNER JOIN hinter_follows AS hf ON h.hinter_id = hf.hinter_id INNER JOIN hinters AS hi ON h.hinter_id = hi.hinter_id LEFT JOIN cities AS ci ON h.city_id = ci.city_id LEFT JOIN countries as co ON h.country_id = co.country_id LEFT JOIN hintout_thanks AS ht ON (h.hintout_id = ht.hintout_id AND ht.thanker_user_id = 1) LEFT JOIN hintout_comments AS hc ON hc.hintout_id = h.hintout_id WHERE hf.user_id = 1 GROUP BY h.hintout_id I tried to add the following to the select part: COUNT(ht2.thanks_id) AS thanksCount and the following on the join: LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id but the weird thing happening, to which I could not find any answers or solutions, is that the moment I add this addtiional part, the count for comments get ruined (I get wrong and weird numbers), and I get the same number for the thanks - I couldn't understand why or how to fix it...and I'm avoiding using nested queries so any help or pointers would be greatly appreciated! ps: this might have been posted twice, but I can't find the previous post A: When you add LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id The number of rows increases, you get duplicate rows for table hc, which get counted double in COUNT(hc.comment_id). You can replace COUNT(hc.comment_id) <<-- counts duplicated /*with*/ COUNT(DISTINCT(hc.comment_id)) <<-- only counts unique ids To only count unique appearances on an id. On values that are not unique, like co.county_name the count(distinct will not work because it will only list the distinct countries (if all your results are in the USA, the count will be 1). Quassnoi Has solved the whole count problem by putting the counts in a sub-select so that the extra rows caused by all those joins do not influence those counts. A: SELECT h.*, h.permalink AS hintout_permalink, hi.hinter_name, hi.permalink, hf.user_id AS followed_hid, ci.city_id, ci.city_name, co.country_id, co.country_name, ht.thank_id, COALESCE( ( SELECT COUNT(*) FROM hintout_comments hci WHERE hc.hintout_id = h.hintout_id ), 0) AS commentsCount, COALESCE( ( SELECT COUNT(*) FROM hintout_comments hti WHERE hti.hintout_id = h.hintout_id ), 0) AS thanksCount FROM hintouts AS h JOIN hinter_follows AS hf ON hf.hinter_id = h.hinter_id JOIN hinters AS hi ON hi.hinter_id = h.hinter_id LEFT JOIN cities AS ci ON ci.city_id = h.city_id LEFT JOIN countries as co ON co.country_id = h.country_id LEFT JOIN hintout_thanks AS ht ON ht.hintout_id = h.hintout_id AND ht.thanker_user_id=1 WHERE hf.user_id = 1
{ "language": "en", "url": "https://stackoverflow.com/questions/5883311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Azure Search: Frequency of calling indexer For an Azure Search service, I am looking to get updates reflected closest to real-time. I can execute it via REST API using a logic app with recurrence. If I invoke the logic app very frequently(ever 3 seconds). Is there a catch to this approach? * *can the indexer get blocked because of too frequent calls? *is there any cost-implication of this constant invocation (either on logic app or on azure search) I am trying to see if I can avoid building logic to determine various scenarios when the indexer needs to be called. (can get complex) A: If you're OK with indexer running every 5 minutes, you don't need to invoke it at all - it can run on a schedule. If you need to invoke indexer more frequently, you can run it once every 3 minutes on a free tier service, and as often as you want on any paid tier service. If an indexer is already running when you run it, the call will fail with a 409 status. However, if you need to run indexer very frequently, usually it's in response to new data arriving and you have that data in hand. In that case, it may be more efficient to directly index that data using the push-style indexing API. See Add, update, or delete documents for REST API reference, or you can use Azure Search .NET SDK
{ "language": "en", "url": "https://stackoverflow.com/questions/45638153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to test/mock API with JUnit Mockito in Kotlin I am trying to wrote a Unit test in my Android application using kotlin. getPosts() get list of POSTS from https://jsonplaceholder.typicode.com/posts I want to test this function comparing the count or any other way you suggest. I am pretty new to this so any suggestions corrections will be very much helpful Here is what I have tried so far. your help will be much appreciated. R @Singleton class PostsRemoteDataSource @Inject constructor( private val postsService: PostsService ): PostsDataSource { override fun getAllPosts(): Flowable<List<PostEntity>> { return postsService.getPosts() .flatMap { posts -> Flowable.fromIterable(posts) .take(10) .toList().toFlowable() } } } PostService interface PostsService { @GET("/posts") fun getPosts(): Flowable<List<PostEntity>> } Testcase class PostsRemoteDataSourceTest { @Before fun init() { MockitoAnnotations.initMocks(this) } @Test fun getAllPosts() { val postService = mock(PostsService::class.java) val postsRemoteDataSource = PostsRemoteDataSource(postService) var mList = listOf<PostEntity>() Mockito.`when`(postService.getPosts()).thenReturn(Flowable.fromArray(mList)) val allPosts = postsRemoteDataSource.getAllPosts() //PRETTY SURE THE LINE BELLOW IS WRONG I AM TRYING TO COMPARE THE //COUNT BUT CANNOT GET appPosts.size as it is Flowable type assertEquals(allPosts , CoreMatchers.`is`(10)) } } UPDATE @Test fun getAllPosts() { val postService = mock(PostsService::class.java) val postsRemoteDataSource = PostsRemoteDataSource(postService) var mList = listOf<PostEntity>( PostEntity(1,1,"Title 1", "Body 1"), PostEntity(1,1,"Title 1", "Body 1") ) Mockito.`when`(postService.getPosts()).thenReturn(Flowable.fromArray(mList)) val subsciber = postsRemoteDataSource.getAllPosts().test() assertEquals(subsciber.assertValueCount(10) , 10) } } Error message when I run the test at io.reactivex.observers.BaseTestConsumer.fail(BaseTestConsumer.java:189) at io.reactivex.observers.BaseTestConsumer.assertValueCount(BaseTestConsumer.java:515) at com.rao.com.idealarchitecture.data.remote.PostsRemoteDataSourceTest.getAllPosts(PostsRemoteDataSourceTest.kt:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) A: Option 1 Use blockingFirst() to get data via a blocking call: val allPosts = postsRemoteDataSource.getAllPosts().blockingFirst() assertEquals(10, allPosts.size) Note that making blocking calls on a Flowable is usually considered bad practice in production code, but it's safe to do in tests since your object under test is backed by a mock. Option 2 Obtain a TestSubscriber by calling test() and assert on it: val subscriber = postsRemoteDataSource.getAllPosts().test() subscriber.assertValueCount(10)
{ "language": "en", "url": "https://stackoverflow.com/questions/57454299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect subdomain to main domain except specific URLs - Nginx I have a main domain as follows and am using Nginix server Main domain : https://website.com/ Sub domain : https://admin.website.com/ If anyone accesses https://admin.website.com/ It needs to redirect to https://website.com/ - I have found the following code which uses a combination of multiple servers (including the one with wildcard subdomain): server { listen 80; server_name admin.website.com; add_header Content-Type text/plain; return 200 "admin"; } server { listen 80; server_name *.website.com; return 301 $scheme://example.com$request_uri; } server { listen 80; server_name website.com; add_header Content-Type text/plain; return 200 "main"; } But from the subdomain, if anyone accesses the following url https://admin.website.com/login and any subsequent pages, for example: * *https://admin.website.com/login/useraccount *https://admin.website.com/login/useraccount/password *https://admin.website.com/login/password/reset/ *https://admin.website.com/login/password/reset/&hdJ7dHsSJKDJ etc... Then it should not redirect to the main domain. It should stay on that sub domain page. Does anyone have any ideas? A: What about server { listen 80; server_name admin.website.com; ... location / { return 301 $scheme://website.com$request_uri; } location /login { # processing URL here root </path/to/root>; ... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/69070933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: openshift jersey not working I am trying to execute a simple example of Jersey using openshift however i am running into a snag. I get error below: 2014/06/12 13:06:44,060 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/]] (ServerService Thread Pool -- 65) JBWEB000289: Servlet jersey-serlvet threw load() exception: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes. at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99) [jersey-server-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1298) [jersey-server-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:169) [jersey-server-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:775) [jersey-server-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:771) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193) [jersey-core-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:771) [jersey-server-1.8.jar:1.8] at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:766) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:488) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373) [jersey-server-1.8.jar:1.8] at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556) [jersey-server-1.8.jar:1.8] at javax.servlet.GenericServlet.init(GenericServlet.java:242) [jboss-servlet-api_3.0_spec.jar:1.0.2.Final-redhat-1] at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1194) [jbossweb.jar:7.3.1.Final-redhat-1] at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1100) [jbossweb.jar:7.3.1.Final-redhat-1] at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3591) [jbossweb.jar:7.3.1.Final-redhat-1] at org.apache.catalina.core.StandardContext.start(StandardContext.java:3798) [jbossweb.jar:7.3.1.Final-redhat-1] at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:156) [jboss-as-web.jar:7.3.3.Final-redhat-3] at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:60) [jboss-as-web.jar:7.3.3.Final-redhat-3] at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:93) [jboss-as-web.jar:7.3.3.Final-redhat-3] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_55] at java.util.concurrent.FutureTask.run(FutureTask.java:262) [rt.jar:1.7.0_55] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_55] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_55] at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_55] at org.jboss.threads.JBossThread.run(JBossThread.java:122) 2014/06/12 13:06:44,356 INFO [org.jboss.as.server] (ServerService Thread Pool -- 35) JBAS018559: Deployed "ROOT.war" (runtime-name : "ROOT.war") 2014/06/12 13:06:44,496 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.12.197.129:9990/management 2014/06/12 13:06:44,497 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.12.197.129:9990 2014/06/12 13:06:44,498 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: JBoss EAP 6.2.3.GA (AS 7.3.3.Final-redhat-3) started in 26318ms - Started 211 of 355 services (141 services are passive or on-demand) Any idea what I can do to fix this? I also have the repository posted here: https://github.com/bibhor/jerseyopenshift
{ "language": "en", "url": "https://stackoverflow.com/questions/24190273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails render form + jQuery problem I have a little mistake about jQuery with a render form. I have link_to_add_fields to add nested render. The problem is when i add field, my jQuery stop working. I have no error, nothing just my jquery stop working. Here is my code from helper and jquery def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, ("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).parent().before(content.replace(regexp, new_id)); } The jquery i try to use is the datepicker from jQuery UI. my render : <div class="field"> <div> <%= f.label :work_start_date %><br/> <%= f.text_field :work_start_date, :class => 'calpicker' %> </div> <div> <%= f.label :work_end_date %><br/> <%= f.text_field :work_end_date, :class => 'calpicker' %> </div> <div> <%= f.label :value_renovation %><br/> <%= f.text_field :value_renovation %> </div> <div> <%= f.label :note %><br/> <%= f.text_area :note, :rows => '3' %> </div> </div> and my script for the class calpicker jQuery(function() { // for PikaChoose $(".calpicker").datepicker(); }); i see a difference between my nested render after a link_to_add_field and if i set defaut view from my controller (mymodel.nestedmodel.build) with mymodel.nestedmodel.build my class have 'hasDatepicker' with my calpicker, with my render i dont have this element in my class. What can i do? with my firebug i see no error. Thanks for your help. A: You are having this problem because you are adding fields after the DOM has loaded and after $(".calpicker").datepicker(); has run so the new fields are not included to have a datepicker. You will need to use the .live function to achieve this functionality so have a look at this article it might help: http://www.vancelucas.com/blog/jquery-ui-datepicker-with-ajax-and-livequery/ Extracted and modified source: jQuery(function() { $('input.calpicker').live('click', function() { $(this).datepicker({showOn:'focus'}).focus(); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7251525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting Python Output into .xlxs File The following code runs and does what it's supposed to do but I'm having trouble using the XlxsWriter module in Python in order to get some of the results into a .xlxs file. The goal is for the output to contain information from the function block_trial where it tracks each block and gives me the all_powers variable the corresponds with that trial. Installing the module into my user directory goes smoothly but it won't give me a file that gives me both sets of information. At the moment, I'm using: import xlsxwriter workbook = xlsxwriter.Workbook('SRT_data.xlsx') worksheet = workbook.add_worksheet() Widen the first column to make the text clearer. worksheet.set_column('A:A', 20) Add a bold format to use to highlight cells. bold = workbook.add_format({'bold': True}) Write some simple text. worksheet.write('A1', 'RT') workbook.close() But can't get any of my data to show up. import random, math num_features = 20 stim_to_vect = {} all_stim = [1,2,3,4,5] all_features = range(num_features) zeros=[0 for i in all_stim] memory=[] def snoc(xs,x): new_xs=xs.copy() new_xs.append(x) return new_xs def concat(xss): new_xs = [] for xs in xss: new_xs.extend(xs) return new_xs def point_wise_mul(xs,ys): return [x*y for x,y in zip(xs,ys)] for s in snoc(all_stim, 0): stim_to_vect[s]= [] for i in all_features: stim_to_vect[s].append(random.choice([-1, 1])) def similarity(x,y): return(math.fsum(point_wise_mul(x,y))/math.sqrt(math.fsum(point_wise_mul(x,x))*math.fsum(point_wise_mul(y,y)))) def echo(probe,power): echo_vect=[] for j in all_features: total=0 for i in range(len(memory)): total+=math.pow(similarity(probe, memory[i]),power)*memory[i][j] echo_vect.append(total) return echo_vect fixed_seq=[1,5,3,4,2,1,3,5,4,2,5,1] prev_states={} prev_states[0]=[] prev=0 for curr in fixed_seq: if curr not in prev_states.keys(): prev_states[curr]=[] prev_states[curr].append(prev) prev=curr def update_memory(learning_parameter,event): memory.append([i if random.random() <= learning_parameter else 0 for i in event]) for i in snoc(all_stim,0): for j in prev_states[i]: curr_stim = stim_to_vect[i] prev_resp = stim_to_vect[j] curr_resp = stim_to_vect[i] update_memory(1.0, concat([curr_stim, prev_resp, curr_resp])) def first_part(x): return x[:2*num_features-1] def second_part(x): return x[2*num_features:] def compare(curr_stim, prev_resp): for power in range(1,10): probe=concat([curr_stim,prev_resp,zeros]) theEcho=echo(probe,power) if similarity(first_part(probe),first_part(theEcho))>0.97: curr_resp=second_part(theEcho) return power,curr_resp return 10,zeros def block_trial(sequence): all_powers=[] prev_resp = stim_to_vect[0] for i in sequence: curr_stim = stim_to_vect[i] power,curr_resp=compare(curr_stim,prev_resp) update_memory(0.7,concat([curr_stim,prev_resp,curr_resp])) all_powers.append(power) prev_resp=curr_resp return all_powers
{ "language": "en", "url": "https://stackoverflow.com/questions/30388693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stop file download dialog from showing in Firefox/Chrome I have an MVC3 app and users can upload files and then view or download them whenever they want. The following code works as expected in IE (my popup window appears and the file in rendered inside of it) but in Firefox i get the open with/save file dialog box and my file doesnt render in the popup window. In chrome, the file just automatically downloads. Heres my code: //for brevity i'm not showing how i get the file stream to display, //but that code works fine, also the ContentType is set properly as well public class BinaryContentResult : ActionResult { private readonly string ContentType; private readonly string FileName; private readonly int Length; private readonly byte[] ContentBytes; public BinaryContentResult(byte[] contentBytes, string contentType, string fileName, int nLength) { ContentBytes = contentBytes; ContentType = contentType; FileName = fileName; Length = nLength; } public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; //current context being passed in response.Clear(); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType; if (ext.ToLower().IndexOf(".pdf") == -1) { //if i comment out this line, jpg files open fine but not png response.AddHeader("Content-Disposition", "application; filename=" + FileName); response.AddHeader("Content-Length", Length.ToString()); response.ContentEncoding = System.Text.Encoding.UTF8; } var stream = new MemoryStream(ContentBytes); //byte[] ContentBytes; stream.WriteTo(response.OutputStream); stream.Dispose(); } } Heres my view: public ActionResult _ShowDocument(string id) { int nLength = fileStream.Length;//fileStream is a Stream object containing the file to display return new BinaryContentResult(byteInfo, contentType, FileName,nLength); } For PDf and plain text files, this works across the board, but for jpg and png files, i get the download dialog. How do I make Firefox/Chrome open files in my popup like they do the PDF files in Firefox/Chrome? Thanks A: You need to send some headers so the browser knows how to handle the thing you are streaming. In particular: Response.ContentType = "image/png" Response.ContentType = "image/jpg" etc. Also note that for anything different than PDF, you are setting the content-disposition to "Content-Disposition", "application; filename=" + FileName) which will force a download.
{ "language": "en", "url": "https://stackoverflow.com/questions/10933747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: std::cin and std;:getline not working together in cpp I'm new to cpp, it's been 2 weeks since i stared learning. Today this weird bug or what it is called, causing my code to run weird way and not working as expected, thing is if I use only std::cin code runs perfectly fine but things got shaky when I add std::getline and then the program stops. Here's my simple code. #include <iostream> int main(){ int age; std::cout << "Age: "; std::cin >> age; std::cout << age << "\n"; std::string Name; std::cout << "Name\n"; std::getline(std::cin, Name); std::cout << Name << "\n"; return 0; } output chitti@Thor /m/4/F/Langs> cd "/mnt/404EA75214A150D1/Files/Langs/Cpp/" && g++ main.cpp -o main && "/mnt/404EA75214A150D1/Files/Langs/Cpp/"main Age: 55 55 Name chitti@Thor /m/4/F/L/Cpp>
{ "language": "en", "url": "https://stackoverflow.com/questions/70679364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to deploy django under a suburl behind nginx I have a django application running on http://localhost:12345 . I'd like user to access it via url http://my.server.com/myapp . I use nginx to reverse proxy to it like the following: ... ... server_name my.server.com; location /myapp { rewrite /myapp(.*) $1 break; ... ... # proxy param proxy_pass http://localhost:12345; } ... ... The question is, when configured like the above, how to make the urls in my response pages to have a prefix of "/myapp" so that the nginx can direct them correctly to myapp. E.g., the urls in a page like "/foo/far" ought to be changed to "/myapp/foo/bar" to allow nginx proxy to myapp. what is the right nginx configure to use to achieve this ? I can use settings variables of django to specify the root url prefix, but it's not flexiable to my mind, since the variable have to be modified according to different nginx configuration(say one day nginx may change the suburl from "/myapp" to "/anotherapp"). A: As the prefix is set in Nginx, the web server that hosts the Django app has no way of knowing the URL prefix. As orzel said, if you used apache+mod_wsgi of even nginx+gunicorn/uwsgi (with some additional configuration), you could use the WSGIScriptAlias value, that is automatically read by Django. When I need to use a URL prefix, I generally put it myself in my root urls.py, where I have only one line, prefixed by the prefix and including an other urls.py (r'^/myapp/', include('myapp.urls')), But I guess this has the same bottleneck than setting a prefix in settings.py, you have redundant configuration in nginx and Django. You need to do something in the server that hosts your Django app at :12345. You could set the prefix there, and pass it to Django using the WSGIScriptAlias or its equivalent outside mod_wsgi. I cannot give more information as I don't know how your Django application is run. Also, maybe you should consider running your Django app directly from Django, using uWSGI or gunicorn. To pass the prefix to Django from the webserver, you can use this : proxy_set_header SCRIPT_NAME /myapp; More information here A: Here is part of my config for nginx which admittedly doesn't set FORCE_SCRIPT_NAME, but then, I'm not using a subdirectory. Maybe it will be useful for setting options related to USE_X_FORWARDED_HOST in nginx rather than Django. upstream app_server_djangoapp { server localhost:8001 fail_timeout=0; } server { listen xxx.xxx.xx.xx:80; server_name mydomain.com www.mydomain.com; if ($host = mydomain.com) { rewrite ^/(.*)$ http://www.mydomain.com/$1 permanent; } ... location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://app_server_djangoapp; break; } } ... } A: You'll need to update your setting: USE_X_FORWARDED_HOST = True FORCE_SCRIPT_NAME = "/myapp" And update your MEDIA_URL and STATIC_URL accordingly. I haven't had the experience of deploying under nginx, but under apache, it works fine. refer to: https://docs.djangoproject.com/en/dev/ref/settings/#use-x-forwarded-host
{ "language": "en", "url": "https://stackoverflow.com/questions/8133063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Does Anyone Know a Fix for MongoDB Timeout Exceptions? I've been getting MongoDB Timeout Exceptions a lot more frequently lately. I code a discord bot that relies on it for most guild-based functions, and yesterday it hasn't been able to log into MongoDB at all using the Java driver. Just for a general overview of it, I'm using all up-to-date drivers and dependencies, and don't make use of any deprecated methods at all. Since it isn't a problem inside my own code I have tried to tinker with the connection timeouts and different network settings. Here are the error logs in the console (Disregard the logger messages): 2020-05-22 18:25 [main] CavenBot [INFO ] - Logging into databases... 2020-05-22 18:25 [main] CavenBot [INFO ] - Logging into MongoDB Exception in thread "main" com.mongodb.MongoConfigurationException: Unable to look up TXT record for host discord-y3bzo.mongodb.net at com.mongodb.internal.dns.DefaultDnsResolver.resolveAdditionalQueryParametersFromTxtRecords(DefaultDnsResolver.java:131) at com.mongodb.ConnectionString.<init>(ConnectionString.java:378) at com.mongodb.client.MongoClients.create(MongoClients.java:61) at com.dragons0u1.CavenBot.main(CavenBot.java:37) Caused by: javax.naming.CommunicationException: DNS error [Root exception is java.net.SocketTimeoutException: Receive timed out]; remaining name 'discord-y3bzo.mongodb.net' at jdk.naming.dns/com.sun.jndi.dns.DnsClient.query(DnsClient.java:313) at jdk.naming.dns/com.sun.jndi.dns.Resolver.query(Resolver.java:81) at jdk.naming.dns/com.sun.jndi.dns.DnsContext.c_getAttributes(DnsContext.java:434) at java.naming/com.sun.jndi.toolkit.ctx.ComponentDirContext.p_getAttributes(ComponentDirContext.java:235) at java.naming/com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.getAttributes(PartialCompositeDirContext.java:141) at java.naming/com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.getAttributes(PartialCompositeDirContext.java:129) at java.naming/javax.naming.directory.InitialDirContext.getAttributes(InitialDirContext.java:171) at com.mongodb.internal.dns.DefaultDnsResolver.resolveAdditionalQueryParametersFromTxtRecords(DefaultDnsResolver.java:114) ... 3 more Caused by: java.net.SocketTimeoutException: Receive timed out at java.base/java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData(Native Method) at java.base/java.net.DualStackPlainDatagramSocketImpl.receive0(DualStackPlainDatagramSocketImpl.java:124) at java.base/java.net.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:182) at java.base/java.net.DatagramSocket.receive(DatagramSocket.java:815) at jdk.naming.dns/com.sun.jndi.dns.DnsClient.doUdpQuery(DnsClient.java:423) at jdk.naming.dns/com.sun.jndi.dns.DnsClient.query(DnsClient.java:212) ... 10 more A: The relevant errors here are: Unable to look up TXT record for host discord-y3bzo.mongodb.net DNS error java.net.SocketTimeoutException: Receive timed out This suggests that you are using a mongodb+srv style connection string, and the DnsClient library is timing out trying to query the DNS server for the TXT record in needs in order to connect. That is to say, this looks a lot like an issue with DNS resolver confguration, the DNS server, or the network connection to the DNS server.
{ "language": "en", "url": "https://stackoverflow.com/questions/61965043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to export Kotlin functions to Javascript with correct name I'm trying to export Kotlin functions to Javascript. The problem is, functions which require arguments are renamed after Kotlin2JS operation, here's an example: Kotlin source: fun withParam(args: String) { println("JavaScript generated through Kotlin") } fun withoutParams() { println("Without params") } After Kotlin2JS, trying to require in Node REPL: > const kotlinBundle = require('./build/index.js'); undefined > kotlinBundle { 'withParam_61zpoe$': [Function: withParam], withoutParams: [Function: withoutParams] } > As you can see, function with argument got exported with _61zpoe$ suffix. Is it possible to get rid of that part? I'm using kotlin2js plugin and kotlin-stdlib-js:1.1.1 library, my kotlinOptions are: compileKotlin2Js.kotlinOptions { moduleKind = "commonjs" outputFile = "build/index.js" } Thanks A: You can use @JsName annotation to provide exact name for the function (or other symbol) in compiled javascript. I.e. @JsName("withParam") fun withParam(args: String) { println("JavaScript generated through Kotlin") }
{ "language": "en", "url": "https://stackoverflow.com/questions/46190782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server side script in C# return different time from what server clock is displaying I am facing typical issue.My dedicated server clock showing 11 Am and datetime function in asp.net script returns 4pm time. Please help how to resolve the issue.I need the function to return the server clock time.I dont know if its common issue i am facing it for first time. Automatically syncronize with an internet time server :: CHECKED TICK ntp2.ja.net GMT-05 eastern time (US & Canada) PIECE OF CODE:: if (DateTime.Now.Hour >= 12 && Convert.ToDateTime(txtShipDate.Text.Trim()) < DateTime.Today.AddDays(2)) { flag = false; } if (DateTime.Now.Hour < 12 && Convert.ToDateTime(txtShipDate.Text.Trim()) < DateTime.Today.AddDays(1)) { flag = false; } regards A: I guess you are using two different properties of DateTime (or simply Date) class: Now and UtcNow. Try to use UtcNow, if you use Now, or vice versa.
{ "language": "en", "url": "https://stackoverflow.com/questions/10454213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make WndProc inline? Is it possible, and if so, how to make WndProc inline? That is, I would like to process Windows messages WM_... within WinMain, so as to avoid seemingly needless function calls. Thank you. A: You cannot inline a window procedure. This is by design. You can easily see the architectural limitation when registering a window class. This is done by calling RegisterClassExW, passing along a WNDCLASSEXW structure. That structure requires a valid lpfnWndProc. You cannot take the address of an inlined function. There are other aspects that require the window procedure to be an actual function. For example, the stored window procedure address serves as a customization point and allows subclassing controls, e.g. to tweak the behavior of a standard control. There's nothing you can do to avoid the function call. If you want to limit the scope of variables, you can assign the result of a lambda expression to the lpfnWndProc member. Visual Studio makes sure to synthesize the correct function signature.
{ "language": "en", "url": "https://stackoverflow.com/questions/59934042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Web Scraping CSS Selectors With Beautiful Soup 4 I am trying to print only the high impact news from the given currency. When I include the worsedata == True conditional in the if statement the code prints nothing. When I only include the currency conditional in the if statement it prints all USD news regardless of impact strength. import requests from bs4 import BeautifulSoup r = requests.get("https://www.forexfactory.com/#closed") soup = BeautifulSoup(r.text, 'lxml') table = soup.find("table", class_="calendar__table") worsedata = False for row in table.find_all('tr', class_='calendar__row--grey'): #finds all rows on forexfactory.com currency = row.find("td", class_="currency") currency = currency.get_text(strip=True) for impact in row.select("tr.calendar__row calendar_row calendar__row--grey span.high:not(.revised)"): worsedata = True if currency == "USD" and worsedata == True: actual = row.find("td", class_="actual") actual = actual.get_text(strip=True) forecast = row.find("td", class_="forecast") forecast = forecast.get_text(strip=True) print(actual, forecast)
{ "language": "en", "url": "https://stackoverflow.com/questions/59745017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dropping a table created by df.to_sql() I have a flask application with a background process I have spawned away from the GUI. I have a db session created in association with the Flask app. Because I want to have the freedom to write tables to the db that are not necessarily to be referenced by GUI code, I am not creating the overhead of a class. The code that creates a table is as follows: admin_df.to_sql(df_name, con=db.engine, if_exists="replace") How would I now delete this table? A: The answer I needed is based upon Levon's reply at: How to delete a table in SQLAlchemy? Basically, this did the trick: from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base from [code location] import db Base = declarative_base() metadata = MetaData(db.engine, reflect=True) table = metadata.tables.get(table_name) table_to_delete = metadata.tables.get('table_name_for_table_to_delete') Base.metadata.drop_all(db.engine, [table_to_delete])
{ "language": "en", "url": "https://stackoverflow.com/questions/64598060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory reduction I am not a programmer but am facing a programming problem. I need to reduce the memory consumption of a Python code. One option is to reduce the variable precision. In this regard: * *Identify Floating points (as I think the data types are assigned on the fly)? *Python uses 64-bit or 32-bit floating points? *Any function to reduce floating precision or convert to int? Kindly help me. These questions may be stupid, but I have very less knowledge of Programming. Thanks... A: If you are already using numpy you can set the dtype field to the type that you want (documentation). You'll get a little more flexibility there for typing, but in general you aren't going to get a lot of control over variable precision in Python. You might also have some luck if you want to go through the structural overhead of using the static types from Cython, though if you are new to programming that may not be the best route. Beyond that, you haven't given us a lot to work with regarding your actual problem and why you feel that the variable precision is the best spot for optimization. A: Pure CPython (sans numpy, etc.) floats are implemented as C doubles. http://www.ibm.com/developerworks/opensource/library/os-python1/ Yes, the types are associated with values, not variables. You can check for something being a Python float with isinstance(something, float). You could perhaps try objgraph to see what's using your memory. http://mg.pov.lt/objgraph/ There's also a possibility that you are leaking memory, or merely need a garbage collection. And it could be that your machine just doesn't have much memory - sometimes it's cheaper to throw a little extra RAM, or even a little more swap space, at a constrained memory problem. It's possible that using a low precision, alternative numeric representation would help - perhaps http://pypi.python.org/pypi/Simple%20Python%20Fixed-Point%20Module/0.6 ?.
{ "language": "en", "url": "https://stackoverflow.com/questions/8511166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement ASN1 decoding in Java Spring? I need to decode ASN1 strings from a complex sequence but I just cannot figure out how this whole thing works. I'd like to do something like decoder = ASN1Library.initWithSequence(sequenceString); ParseObject obj = decoder.decodeString(asn1String); I have tried a few libraries but none allowed me to do what I want, or I was not able to understand how they work. I guess I need to implement a parser myself. Can anybody explain how to do so? Thank you very much! A: Ok here's what I found. I am using com.objsys.asn1j.runtime library; I need to implement the whole sequence in Java classes, and make each class extend Asn1Seq, Asn1Integer or other super classes from the library. In each class which extends Asn1Seq (ie. all Sequence-like classes) I need to override the decode method and in the body I have to call decode again on every attribute of the class. Quick sample (both Type1 and Type2 extend Asn1Integer): class SeqData extends Asn1Seq { private static final long serialVersionUID = 55L; Type1 attribute1; Type2 attribute2; @Override public int getElementCount() { return 2; } @Override public String getElementName(int arg0) { switch (arg0) { case 0: return "attribute1"; case 1: return "attribute2"; } return ""; } @Override public Object getElementValue(int arg0) { switch (arg0) { case 0: return attribute1; case 1: return attribute2; } return null; } @Override public void decode(Asn1PerDecodeBuffer arg0) throws Asn1Exception, IOException { attribute1 = new Type1(); attribute1.decode(arg0, 1L, 62L); attribute2 = new Type2(); attribute2.decode(arg0, 1L, 62L); }
{ "language": "en", "url": "https://stackoverflow.com/questions/51944660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Kill app completely from service class I have an audio streaming app playing in backgroundand also a foreground service which should control media player from the background. There is aCLOSE` button in the foreground which is expected to kill the app completely when clicked. However, the methods i have used to accomplish that has not yet worked as expected. public void showNotification() { Intent playPauseIntent = new Intent(this, AudioService.class); playPauseIntent.setAction(Constants.ACTION_STREAM_PLAY_PAUSE); PendingIntent playPausePendingIntent = PendingIntent.getService( this, 0, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT ); Intent deleteIntent = new Intent(this, AudioService.class); deleteIntent.setAction(Constants.ACTION_STOP_RADIO_SERVICE); PendingIntent pendingDelete = PendingIntent.getService(this, 0, deleteIntent, PendingIntent.FLAG_ONE_SHOT ); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getAction() != null) { switch (intent.getAction()) { case Constants.ACTION_STOP_RADIO_SERVICE: hideNotification(); stopSelf(); android.os.Process.killProcess(android.os.Process.myPid()); this.onDestroy(); // not working as expected. i want app killed from here break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49205025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get my flutter firebase user to also create their stripe account I am creating a mobile marketplace however, I don't know how to allow my user who has created an account with firebase also create a stripe account and having that connect to my app so that when they create a listing for a product, they can receive money in their stripe accounts after someone buys their specific product. My question is, does anyone know how I can do that? I tried following the stripe instructions but realized that they are only making an account and after they sell an item, they arn't getting payed. How would I program that? How would they get payed? For firebase functions, I am using Js. My mobile app is made using flutter and my backend is firebase. A: You can make a payout system "add to each user a field which holds the total gained money and when this user collect a specific amount you can send money from stripe to his bank account" because it's not right to connect each user with Stripe as it or any other payment gateways allow to connect the app with one account and it requires some information to be able to receive money .. etc , you see that you put private key and other key to connect with stripe and those keys and you should hide'em with env properties so no one can see'em I hope you got what i want to say A: Stripe Connect has a 3 different charge types to select from : https://stripe.com/docs/connect/charges In general, you would either create the charge on your platform then transfer the funds to the connected account, or create a charge on the connected account. You would want to follow one of the two guides below depending on which charge type [0] you choose : * *https://stripe.com/docs/connect/collect-then-transfer-guide *https://stripe.com/docs/connect/enable-payment-acceptance-guide Following the flows mentioned above, funds will accumulate in the connected account's balance and will be available to be paid out. You can read about connected account payouts in more detail here : https://stripe.com/docs/connect/bank-debit-card-payouts You would probably want to write in to Stripe support if you need further guidance on how Stripe Connect works as a product. A: * *This documentation provides detailed steps on how you can process payments with Firebase using a stripe account. *It walks you through customizing and deploying your own version of the open-source cloud-functions-stripe-sample.web.app example app using stripe payments whose source code is available at this GitHub link. *Also have a look at this stackoverflow thread where a stackoverflow user has shown how he has integrated Firebase with his stripe account using Firebase functions. *For a detailed description on how you can create a stripe account for Firebase Flutter, go through this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/69421476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }