qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
13,707
Using Twig, is it possible to strip out or replace a non-breaking space (` `)? I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this: ``` Nkr 100,00 ``` What I'd like, is to strip the `Nkr ` part, so the string looks like this: ``` 100,00 ``` However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space. `{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it. Here's what I tried already (after stripping the `Nkr` part): ``` {{ price|replace({' ' : ''}) }} {{ price|raw|replace({' ' : ''}) }} {{ price|striptags }} {{ price|raw|striptags }} {{ price|trim }} {{ price|raw|trim }} {{ price|replace({ '\u00a0' : '' }) }} {{- price -}} {% spaceless %}{{ price }}{% endspaceless %} ```
2016/02/16
[ "https://craftcms.stackexchange.com/questions/13707", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/1098/" ]
Here's a different spin... Try removing everything that's **not numeric or comma**. ``` {{ price|replace('/[^0-9,]/', '') }} ```
To add space between two words use below code: ``` {{ price|replace({" ": " "})|raw |nl2br }} ``` This will work.
13,707
Using Twig, is it possible to strip out or replace a non-breaking space (` `)? I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this: ``` Nkr 100,00 ``` What I'd like, is to strip the `Nkr ` part, so the string looks like this: ``` 100,00 ``` However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space. `{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it. Here's what I tried already (after stripping the `Nkr` part): ``` {{ price|replace({' ' : ''}) }} {{ price|raw|replace({' ' : ''}) }} {{ price|striptags }} {{ price|raw|striptags }} {{ price|trim }} {{ price|raw|trim }} {{ price|replace({ '\u00a0' : '' }) }} {{- price -}} {% spaceless %}{{ price }}{% endspaceless %} ```
2016/02/16
[ "https://craftcms.stackexchange.com/questions/13707", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/1098/" ]
You just think it is ` ` that get's returned from the filter, because that's how your developer tools display it, but in fact it is a *UTF-8 encoded* non-breaking space character. Have a look at the source code that is output and you won't see the ` `. The filter gets the formatting pattern from the [app/framework/i18n/data/no.php](https://github.com/pixelandtonic/Craft-Release/blob/master/app/framework/i18n/data/no.php#L32) file. Everything in this file is UTF-8 encoded and the non-breaking space is no exception. So how can we remove it? Copy-and-pasting doesn't always work, because it depends on the apps used. On Mac OS X 10.11 I was able to simply copy the string from the source code view in the Safari dev tools to Atom editor and it worked. I can also generate the character with `Alt`+`Space`. Copying the snippet into this answer doesn't work though, it somehow converts it to a normal space: ``` {{ price|replace('Nkr ') }} ``` **Important sidenote:** Mac OS X users who are like me and sometimes accidentially enter a non-breaking space character into their source code and then go mad trying to fix the error, have a look at this Apple Stack Exchange post: [What's alt+spacebar character and how to disable it?](https://apple.stackexchange.com/questions/34672/whats-altspacebar-character-and-how-to-disable-it) Atom editor users can install the [highlight-nbsp](https://atom.io/packages/highlight-nbsp) package.
If you need to trim a non-breaking space which is the UTF-8 encoded non-breaking space character: ``` {{ value|trim(" \t\n\r\0\x0B\xC2\xA0") }} ``` This works because internally Twig uses the PHP `trim`, `ltrim`, and `rtrim functions`.
13,707
Using Twig, is it possible to strip out or replace a non-breaking space (` `)? I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this: ``` Nkr 100,00 ``` What I'd like, is to strip the `Nkr ` part, so the string looks like this: ``` 100,00 ``` However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space. `{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it. Here's what I tried already (after stripping the `Nkr` part): ``` {{ price|replace({' ' : ''}) }} {{ price|raw|replace({' ' : ''}) }} {{ price|striptags }} {{ price|raw|striptags }} {{ price|trim }} {{ price|raw|trim }} {{ price|replace({ '\u00a0' : '' }) }} {{- price -}} {% spaceless %}{{ price }}{% endspaceless %} ```
2016/02/16
[ "https://craftcms.stackexchange.com/questions/13707", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/1098/" ]
You just think it is ` ` that get's returned from the filter, because that's how your developer tools display it, but in fact it is a *UTF-8 encoded* non-breaking space character. Have a look at the source code that is output and you won't see the ` `. The filter gets the formatting pattern from the [app/framework/i18n/data/no.php](https://github.com/pixelandtonic/Craft-Release/blob/master/app/framework/i18n/data/no.php#L32) file. Everything in this file is UTF-8 encoded and the non-breaking space is no exception. So how can we remove it? Copy-and-pasting doesn't always work, because it depends on the apps used. On Mac OS X 10.11 I was able to simply copy the string from the source code view in the Safari dev tools to Atom editor and it worked. I can also generate the character with `Alt`+`Space`. Copying the snippet into this answer doesn't work though, it somehow converts it to a normal space: ``` {{ price|replace('Nkr ') }} ``` **Important sidenote:** Mac OS X users who are like me and sometimes accidentially enter a non-breaking space character into their source code and then go mad trying to fix the error, have a look at this Apple Stack Exchange post: [What's alt+spacebar character and how to disable it?](https://apple.stackexchange.com/questions/34672/whats-altspacebar-character-and-how-to-disable-it) Atom editor users can install the [highlight-nbsp](https://atom.io/packages/highlight-nbsp) package.
To add space between two words use below code: ``` {{ price|replace({" ": " "})|raw |nl2br }} ``` This will work.
13,707
Using Twig, is it possible to strip out or replace a non-breaking space (` `)? I've got a string variable `price` (returned from the [`currency`](https://craftcms.com/docs/templating/filters#currency) filter) that prints like this: ``` Nkr 100,00 ``` What I'd like, is to strip the `Nkr ` part, so the string looks like this: ``` 100,00 ``` However, `{{ price|replace('Nkr ', '') }}` does nothing, as the `replace` filter doesn't appear to actually match the non-breaking space. `{{ price|replace({'Nkr' : ''}) }}` strips out the `Nkr` part, but leaves the ` `; and I'm unable to remove it. Here's what I tried already (after stripping the `Nkr` part): ``` {{ price|replace({' ' : ''}) }} {{ price|raw|replace({' ' : ''}) }} {{ price|striptags }} {{ price|raw|striptags }} {{ price|trim }} {{ price|raw|trim }} {{ price|replace({ '\u00a0' : '' }) }} {{- price -}} {% spaceless %}{{ price }}{% endspaceless %} ```
2016/02/16
[ "https://craftcms.stackexchange.com/questions/13707", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/1098/" ]
To add space between two words use below code: ``` {{ price|replace({" ": " "})|raw |nl2br }} ``` This will work.
If you need to trim a non-breaking space which is the UTF-8 encoded non-breaking space character: ``` {{ value|trim(" \t\n\r\0\x0B\xC2\xA0") }} ``` This works because internally Twig uses the PHP `trim`, `ltrim`, and `rtrim functions`.
72,469,393
I am trying to make the weather app in Vite , but when I run the program I get the error "TypeError: Cannot read properties of undefined (reading 'main')". Below is part of the code: ``` <div id="app" :class="{warm: weather.main && weather.main.temp > 17}"> <main> <div class="search-box"> <input type="text" class="search-bar" placeholder="Search..." v-model="query" @keypress="fetchWeather" /> </div> <div class="weather-wrap" v-if="typeof weather.main != 'undefined'"> <div class="location-box"> <div class="location"> {{ weather.name }}, {{ weather.sys.country }} </div> <div class="date"> {{ dateBuilder() }} </div> </div> <div class="weather-box"> <div class="temp"> {{ Math.round(weather.main.temp) }}°c </div> <div class="weather">{{ weather.weather[0].main }}</div> </div> </div> </main> </div> ``` This my js ``` export default { name: "app", date() { return { api_key: '803a7cd7089cd54e3ecc37bf1b6a3340', url_base: 'https://api.openweathermap.org/data/2.5/', query: 'Taiwan', weather: { main: { temp: 17 } }, } ``` my Error [enter image description here](https://i.stack.imgur.com/QmsTQ.png)
2022/06/02
[ "https://Stackoverflow.com/questions/72469393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18137571/" ]
I think the problem is this line: ``` <div id="app" :class="{warm: weather.main && weather.main.temp > 17}"> ``` If you want to use js within the `class=""`, You just have to prepend it by `:`, and not wrap it in `{}`. Try changing that to: ``` <div id="app" :class="weather.main && weather.main.temp > 17 ? 'warm' : ''"> ``` This will result in: either ``` <div id="app" class="warm"> ``` or ``` <div id="app" class=""> ``` depending on the condition. Also, a better way to check for optional properties is to use optional chaining as such: ``` <div id="app" :class="weather.main?.temp > 17 ? 'warm' : ''"> ``` Below is a snippet of working code. ```html <script src="https://unpkg.com/vue@3"></script> <div id="app"> <h1 :class="weather?.main?.temp > 17 ? 'warm' : 'cold'">{{query}}</h1> </div> <script> const { createApp } = Vue createApp({ data() { return { api_key: '803a7cd7089cd54e3ecc37bf1b6a3340', url_base: 'https://api.openweathermap.org/data/2.5/', query: 'Taiwan', weather: { main: { temp: 18 } }, } } }).mount('#app') </script> <style> .warm { color: red; } .cold { color: blue; } </style> ```
``` <div id="app" :class="weather?.main?.temp > 17 ? 'warm' : ''"> <main> <div class="search-box"> <input type="text" class="search-bar" placeholder="Search..." v-model="query" @keypress="fetchWeather" /> </div> <div class="weather-wrap" v-if="weather.main != 'undefined'"> <div class="location-box"> <div class="location"> {{ weather.name }} </div> <div class="date"> {{ dateBuilder() }} </div> </div> <div class="weather-box"> <div class="temp"> {{ Math.round(weather.main.temp) }}°c </div> </div> </div> </main> </div> ``` ``` export default { name: "app", data() { return { api_key: '803a7cd7089cd54e3ecc37bf1b6a3340', url_base: 'https://api.openweathermap.org/data/2.5/', query: '', weather: { main: { temp: 0 }, }, } }, ```
2,825,110
So I've got a Users controller, and it has (amongst others) a function called details. The idea is that a user can go to localhost:3000/user/:user\_id/details and be able to view the details of :user\_id. For example, I have a user called "tester". When I go to the uri: `http://localhost:3000/users/tester/details` I'd want the details function to be called up, to render the details view, and to display the information for the user tester. But instead I get an error saying that ``` No action responded to tester. Actions: change_password, create, current_user, details, forgot_password, index, login_required, new, redirect_to_stored, show, and update_attributes ``` And I understand that to basically mean that if I wanted to access details, I should really be using ``` http://localhost:3000/users/details ``` Except that that isn't really working either... >.< That is instead bringing me to `http://localhost:3000/users/details/registries` (which is the default path that I'd stipulated for anybody trying to view `users/:user_id`, so again, that's working the way I wanted it to) Point is: Can anybody help and tell me how I can go about getting `users/:user_id/details` to work the way I want it to and display the details of :user\_id? Thanks!
2010/05/13
[ "https://Stackoverflow.com/questions/2825110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336025/" ]
Are you using resources? If your routes look like: ``` map.resources :users ``` You could make it: ``` map.resources :users, :member => { :details => :get } ``` That would allow GET requests for the URL /users/:id/details More info here: <http://guides.rubyonrails.com/routing.html#customizing-resources>
In order to get routes like "users/:user\_id/details" change following in routes.rb ``` map.users 'users/:user_id/details', :controller => 'users', :action=>'details' ```
2,825,110
So I've got a Users controller, and it has (amongst others) a function called details. The idea is that a user can go to localhost:3000/user/:user\_id/details and be able to view the details of :user\_id. For example, I have a user called "tester". When I go to the uri: `http://localhost:3000/users/tester/details` I'd want the details function to be called up, to render the details view, and to display the information for the user tester. But instead I get an error saying that ``` No action responded to tester. Actions: change_password, create, current_user, details, forgot_password, index, login_required, new, redirect_to_stored, show, and update_attributes ``` And I understand that to basically mean that if I wanted to access details, I should really be using ``` http://localhost:3000/users/details ``` Except that that isn't really working either... >.< That is instead bringing me to `http://localhost:3000/users/details/registries` (which is the default path that I'd stipulated for anybody trying to view `users/:user_id`, so again, that's working the way I wanted it to) Point is: Can anybody help and tell me how I can go about getting `users/:user_id/details` to work the way I want it to and display the details of :user\_id? Thanks!
2010/05/13
[ "https://Stackoverflow.com/questions/2825110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336025/" ]
Are you using resources? If your routes look like: ``` map.resources :users ``` You could make it: ``` map.resources :users, :member => { :details => :get } ``` That would allow GET requests for the URL /users/:id/details More info here: <http://guides.rubyonrails.com/routing.html#customizing-resources>
I think that your problem is with setting routes in such way, that instead of `:user_id` you have `:login` (or whatever) in url `/users/tester` instead of `/users/34`. Probably you should take a look at `to_param` ([1st example](https://stackoverflow.com/questions/2269885/username-in-url-with-rails-routes), [2nd example](https://stackoverflow.com/questions/1382174/ruby-on-rails-url-from-ids-to-names-titles-ect), [3rd example](https://stackoverflow.com/questions/2632732/id-slug-name-in-url-in-rails-like-in-stackoverflow)). If you want to have another option in routes (besides default REST routes), you can add `:member => {:details => :get}` if you are using `map.resources` (@dylanfm answer) or just map it like in @Salil answer.
2,825,110
So I've got a Users controller, and it has (amongst others) a function called details. The idea is that a user can go to localhost:3000/user/:user\_id/details and be able to view the details of :user\_id. For example, I have a user called "tester". When I go to the uri: `http://localhost:3000/users/tester/details` I'd want the details function to be called up, to render the details view, and to display the information for the user tester. But instead I get an error saying that ``` No action responded to tester. Actions: change_password, create, current_user, details, forgot_password, index, login_required, new, redirect_to_stored, show, and update_attributes ``` And I understand that to basically mean that if I wanted to access details, I should really be using ``` http://localhost:3000/users/details ``` Except that that isn't really working either... >.< That is instead bringing me to `http://localhost:3000/users/details/registries` (which is the default path that I'd stipulated for anybody trying to view `users/:user_id`, so again, that's working the way I wanted it to) Point is: Can anybody help and tell me how I can go about getting `users/:user_id/details` to work the way I want it to and display the details of :user\_id? Thanks!
2010/05/13
[ "https://Stackoverflow.com/questions/2825110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336025/" ]
I think that your problem is with setting routes in such way, that instead of `:user_id` you have `:login` (or whatever) in url `/users/tester` instead of `/users/34`. Probably you should take a look at `to_param` ([1st example](https://stackoverflow.com/questions/2269885/username-in-url-with-rails-routes), [2nd example](https://stackoverflow.com/questions/1382174/ruby-on-rails-url-from-ids-to-names-titles-ect), [3rd example](https://stackoverflow.com/questions/2632732/id-slug-name-in-url-in-rails-like-in-stackoverflow)). If you want to have another option in routes (besides default REST routes), you can add `:member => {:details => :get}` if you are using `map.resources` (@dylanfm answer) or just map it like in @Salil answer.
In order to get routes like "users/:user\_id/details" change following in routes.rb ``` map.users 'users/:user_id/details', :controller => 'users', :action=>'details' ```
37,978,619
I have 2 tables `battles` & `battle_user` structure: `battles` table: ``` id create_date 1 2015/... ``` `battle_user` table: ``` id battle_id user_id 1 1 1 2 1 2 ``` Only 2 users accepted in each battle, the question is: Is there a way using `primary/foreign keys` (or indexing) to prevent insert another battle for same 2 users? prevent this: `battles` table: ``` id create_date 1 2015/... 2 2015/... ``` `battle_user` table: ``` id battle_id user_id 1 1 1 2 1 2 3 2 1 4 2 2 ``` > > prevent create 2 battles between same 2 users > > >
2016/06/22
[ "https://Stackoverflow.com/questions/37978619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407412/" ]
As I said in the comments, I reluctantly will show how a unique key can be used in a de-normalized fashion, and the OP wanted to see it. The concept is that you know the users, so have them wedged in the battles table. How you then proceed on to a `battle_users` table is up to you and I would recommend no change there. ``` create table battlesA1 ( id int auto_increment primary key, createDt datetime not null, user1 int not null, user2 int not null, -- FK Constraints go here (not shown, FK to users table) -- Then unique constraint goes here unique key(user1,user2) -- user1 is less than user2 on insert -- so on insert, utilize the least() and greatest() functions (mysql) -- or your front-end programming language ); insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00',1,2); -- success insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00',1,2); -- Error 1062, Duplicate Entry ``` **`least()` and `greatest()` examples:** ``` set @user1:=14; set @user2:=7; insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) ); -- success insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) ); -- Error 1062, Duplicate Entry set @user1:=6; set @user2:=700; insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) ); -- success insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) ); -- Error 1062, Duplicate Entry drop table battlesA1; -- perhaps the best command you see here. ``` Manual pages for [least(), greatest()](http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html) and [LAST\_INSERT\_ID()](http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id). The latter was not used but is used often in cases like this. So there you have it. You wanted to see it, and I am not terribly proud to show it.
The condition is not simple, at the moment the only way to create a complex check before insert a row in MySQL table is a trigger. I created a trigger that checks if there is another record with these users, but there is a problem (maybe): you will need to delete the not created battle id. ``` delimiter $$ drop trigger if exists `battle_user_bi`$$ create trigger `battle_user_bi` before insert on `battle_user` for each row begin declare msg varchar(100); declare usersInBattle int default 0; declare battleUsers int default 0; declare otherUser int default 0; set usersInBattle= (select count(*) from `battle_user` bu where bu.battle_id = new.battle_id); if usersInBattle = 1 then -- getting the other user set otherUser = (select user_id from `battle_user` bu where bu.battle_id = new.battle_id); -- getting the same users in other battles set battleUsers = (select count(*) from (select bu.battle_id from `battle_user` bu where bu.battle_id <> new.battle_id and bu.user_id = otherUser) b1 inner join (select bu.battle_id from `battle_user` bu where bu.battle_id <> new.battle_id and bu.user_id = new.user_id) b2 on b1.battle_id = b2.battle_id); if battleUsers > 0 then set msg = "There is already one battle for this users... "; SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; end if; end if; end$$ delimiter ; ``` Excuting in a empty table I get: ``` insert into battle_user values (1,1,1); insert into battle_user values (2,1,2); insert into battle_user values (3,2,1); -- the next sentence will no execute -- Error Code: 1644. There is already one battle for this users... insert into battle_user values (4,2,2); ```
45,983,124
I know this question has been asked before on SO, and I understood the explanation given in some of them and the solution. In fact the solutions I found was what I was doing prior to searching SO. But I am still getting an error. I have a dictionary that I set up like so: ``` var dictBarData = [String: Any]() ``` and then I populate it like so: ``` let vThisBar = UIView() //set initial coordinates for view var barX = 0.0 let barY = Double(vBarChart.frame.size.height - 40.0) let barW = 60.0 var barH = 10.0 barX = getBarX(barIndex) vThisBar.frame = CGRect(x:barX, y:barY, width:barW, height:barH) vThisBar.backgroundColor = UIColor.blue vBarChart.addSubview(vThisBar); var dictThisBar = [String: Any]() dictThisBar["category"] = category dictThisBar["value"] = value dictThisBar["view"] = vThisBar dictBarData[String(barIndex)] = dictThisBar ``` then I try to access these dictionaries like so: ``` for dictThisBar in dictBarData as Dictionary { print(dictThisBar["view"] as! UIView) } ``` it's at this point I am getting the error (on the print). I'm making the transition from Objective-c to Swift (and am probably in the minority of liking Objective-C more :D), so I assume I have missed a step.
2017/08/31
[ "https://Stackoverflow.com/questions/45983124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468455/" ]
You can retrieve URL parameter(s) using multiple services such: * request\_stack * path.current * current\_route\_match Here I show you how to get your `value2` from the `param2` using the `request_stack`: ``` // Initialize the service. $requestStack = \Drupal::service('request_stack'); // Get your Master Request. $masterRequest = $requestStack->getMasterRequest(); // Get the value from a GET parameter. $value = $masterRequest->query->get('param2'); ``` --- To go further: * Don't use static call such `\Drupal::service('request_stack');` but you inject the service into you Block. See [this greate article about Dependency Injection in Drupal 8 Plugins](https://chromatichq.com/blog/dependency-injection-drupal-8-plugins). * Understand the difference [between MasterRequest & SubRequest](https://stackoverflow.com/questions/12456949/what-is-the-difference-between-master-sub-request-in-symfony2). --- Hope it will help you !
``` $value = \Drupal::request()->query->get('param2'); ``` Should do the trick.
37,749,771
I'm writing a code and I am selecting a dropdown and when I click the button I want to print the value in console, but it is printing `null`. Below is my code. ``` <form name="formSec" id="formSec"> <div class="bodytag1"> <table> <tr> <td colspan="2" align="center">Breaks</td> </tr> <tr> <td>Break Task</td> <td><select id="task" name="task" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);"> <option value="" disabled selected>Select</option> <option value="break" id="break">Break</option> <option value="ORD" id="ORD">ORD Meetings</option> <option value="Training" id="Training">Training</option> <option value="project" id="project">Adhoc Project</option> </select></td> </tr> <tr> <td>SubTask</td> <td><select id="subtask" name="subtask"> <option value="Subtask">Subtask</option> </select></td> </tr> <tr> <td><input type="button" value="Start" name="Start" id="Start" /></td> <td><input type="button" value="Stop" name="Stop" id="Stop" /></td> </tr> </table> </div> </form> ``` And here is my js ``` <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <link rel="stylesheet" type="text/css" href="CSSFiles/myCssFile.css"> <script type="text/javascript"> function dynamicdropdown(listindex) { document.getElementById("subtask").length = 0; switch (listindex) { case "break": document.getElementById("subtask").options[0] = new Option( "Please select Break type"); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Casual Break ", "Casual Break"); document.getElementById("subtask").options[2] = new Option( "Lunch Break", "Lunch Break"); break; case "ORD": document.getElementById("subtask").options[0] = new Option( "Please select type of Meeting", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option("Calls", "Calls"); document.getElementById("subtask").options[2] = new Option( "Team Meeting", "Team Meeting"); document.getElementById("subtask").options[3] = new Option( "Thomson Activity (Fire Drill, RnR)", "Thomson Activity (Fire Drill, RnR)"); document.getElementById("subtask").options[4] = new Option( "System Downtime", "System Downtime"); break; case "Training": document.getElementById("subtask").options[0] = new Option( "Please select Type of Training", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "EDP Training", "EDP Training"); document.getElementById("subtask").options[2] = new Option( "Process Training", "Process Training"); break; case "project": document.getElementById("subtask").options[0] = new Option( "Please select type of Project", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Others", "Others"); break; } return true; } </script> <script type="text/javascript"> var form = $('#formSec'); var task = $('#task'); var subtask = $('#subtask'); $(document).ready(function() { $('#Start').on("click", function() { console.log(task); $.ajax({ type : "post", url : "UpdateTime", data : form.serialize(), success : function(data) { if (data) { alert("worked"); } //$('#result').attr("value", result); } }); return false; }); }); </script> ``` please let me know where am I going wrong and how can I fix this. Thanks
2016/06/10
[ "https://Stackoverflow.com/questions/37749771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514543/" ]
Move the references to the elements inside the document ready ``` $(document).ready(function() { var form = $('#formSec'); var task = $('#task'); var subtask = $('#subtask'); $('#Start').on("click", function() { console.log(task); }); }); ``` Now when you click on the button, it will have a reference to the task input. Other option, if you want to have them as globals is to move the script so it appears after the elements you are referencing.
You should get the selected option first, and then you can get the value of that option. You can use this code, for example: ``` var selectedOption = task.find("option:selected"); console.log(selectedOption.text()); ```
37,749,771
I'm writing a code and I am selecting a dropdown and when I click the button I want to print the value in console, but it is printing `null`. Below is my code. ``` <form name="formSec" id="formSec"> <div class="bodytag1"> <table> <tr> <td colspan="2" align="center">Breaks</td> </tr> <tr> <td>Break Task</td> <td><select id="task" name="task" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);"> <option value="" disabled selected>Select</option> <option value="break" id="break">Break</option> <option value="ORD" id="ORD">ORD Meetings</option> <option value="Training" id="Training">Training</option> <option value="project" id="project">Adhoc Project</option> </select></td> </tr> <tr> <td>SubTask</td> <td><select id="subtask" name="subtask"> <option value="Subtask">Subtask</option> </select></td> </tr> <tr> <td><input type="button" value="Start" name="Start" id="Start" /></td> <td><input type="button" value="Stop" name="Stop" id="Stop" /></td> </tr> </table> </div> </form> ``` And here is my js ``` <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <link rel="stylesheet" type="text/css" href="CSSFiles/myCssFile.css"> <script type="text/javascript"> function dynamicdropdown(listindex) { document.getElementById("subtask").length = 0; switch (listindex) { case "break": document.getElementById("subtask").options[0] = new Option( "Please select Break type"); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Casual Break ", "Casual Break"); document.getElementById("subtask").options[2] = new Option( "Lunch Break", "Lunch Break"); break; case "ORD": document.getElementById("subtask").options[0] = new Option( "Please select type of Meeting", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option("Calls", "Calls"); document.getElementById("subtask").options[2] = new Option( "Team Meeting", "Team Meeting"); document.getElementById("subtask").options[3] = new Option( "Thomson Activity (Fire Drill, RnR)", "Thomson Activity (Fire Drill, RnR)"); document.getElementById("subtask").options[4] = new Option( "System Downtime", "System Downtime"); break; case "Training": document.getElementById("subtask").options[0] = new Option( "Please select Type of Training", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "EDP Training", "EDP Training"); document.getElementById("subtask").options[2] = new Option( "Process Training", "Process Training"); break; case "project": document.getElementById("subtask").options[0] = new Option( "Please select type of Project", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Others", "Others"); break; } return true; } </script> <script type="text/javascript"> var form = $('#formSec'); var task = $('#task'); var subtask = $('#subtask'); $(document).ready(function() { $('#Start').on("click", function() { console.log(task); $.ajax({ type : "post", url : "UpdateTime", data : form.serialize(), success : function(data) { if (data) { alert("worked"); } //$('#result').attr("value", result); } }); return false; }); }); </script> ``` please let me know where am I going wrong and how can I fix this. Thanks
2016/06/10
[ "https://Stackoverflow.com/questions/37749771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514543/" ]
Move the references to the elements inside the document ready ``` $(document).ready(function() { var form = $('#formSec'); var task = $('#task'); var subtask = $('#subtask'); $('#Start').on("click", function() { console.log(task); }); }); ``` Now when you click on the button, it will have a reference to the task input. Other option, if you want to have them as globals is to move the script so it appears after the elements you are referencing.
Use `console.log(task.val())` instead of `console.log(task)` ```js function dynamicdropdown(listindex) { document.getElementById("subtask").length = 0; switch (listindex) { case "break": document.getElementById("subtask").options[0] = new Option( "Please select Break type"); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Casual Break ", "Casual Break"); document.getElementById("subtask").options[2] = new Option( "Lunch Break", "Lunch Break"); break; case "ORD": document.getElementById("subtask").options[0] = new Option( "Please select type of Meeting", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option("Calls", "Calls"); document.getElementById("subtask").options[2] = new Option( "Team Meeting", "Team Meeting"); document.getElementById("subtask").options[3] = new Option( "Thomson Activity (Fire Drill, RnR)", "Thomson Activity (Fire Drill, RnR)"); document.getElementById("subtask").options[4] = new Option( "System Downtime", "System Downtime"); break; case "Training": document.getElementById("subtask").options[0] = new Option( "Please select Type of Training", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "EDP Training", "EDP Training"); document.getElementById("subtask").options[2] = new Option( "Process Training", "Process Training"); break; case "project": document.getElementById("subtask").options[0] = new Option( "Please select type of Project", ""); document.getElementById("subtask").options[0].disabled = true; document.getElementById("subtask").options[1] = new Option( "Others", "Others"); break; } return true; } var form = $('#formSec'); var task = $('#task'); var subtask = $('#subtask'); $(document).ready(function() { $('#Start').on("click", function() { console.log(task.val()); $.ajax({ type: "post", url: "UpdateTime", data: form.serialize(), success: function(data) { if (data) { alert("worked"); } //$('#result').attr("value", result); } }); return false; }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <form name="formSec" id="formSec"> <div class="bodytag1"> <table> <tr> <td colspan="2" align="center">Breaks</td> </tr> <tr> <td>Break Task</td> <td> <select id="task" name="task" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);"> <option value="" disabled selected>Select</option> <option value="break" id="break">Break</option> <option value="ORD" id="ORD">ORD Meetings</option> <option value="Training" id="Training">Training</option> <option value="project" id="project">Adhoc Project</option> </select> </td> </tr> <tr> <td>SubTask</td> <td> <select id="subtask" name="subtask"> <option value="Subtask">Subtask</option> </select> </td> </tr> <tr> <td> <input type="button" value="Start" name="Start" id="Start" /> </td> <td> <input type="button" value="Stop" name="Stop" id="Stop" /> </td> </tr> </table> </div> </form> ```
9,038,337
How do a I turn off AppCode generating a closing brace `}` whenever I type the opening brace `{` character? ### What I've Tried: I looked through: Settings --> Code Style --> Objective-C and then selected "Wrapping and Braces" and in that list, nothing jumps out as disabling the automatic right brace. With such a sophisticated set of customizations, I know it has to be there! ### Update: Here's a visual on the answer provided by @pjumble ![enter image description here](https://i.stack.imgur.com/ApRMU.png)
2012/01/27
[ "https://Stackoverflow.com/questions/9038337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535054/" ]
Turn off `"AppCode" -> "Preferences" -> "Editor" -> "Smart Keys" -> "Insert Pair Bracket"` and `"Insert Pair '}'"`
Choose Xcode > Preferences, click Text Editing, and deselect `Automatically insert closing ‘}’`.
158,761
so I have two sprites, a box and an X animation (I'm making Tic-Tac-Toe). So, in the code, when I click on the box, it instantiates the X animation at the right place. The X animation does not have a background, but the box does. However, when it instantiates, it puts it *behind* the box. This doesn't make sense to me, but even when I move it around in the editor, moving it across the box puts it behind it. Which is interesting, since neither have layers. And even when I do put layers on (a higher layer on the X animation), it still goes behind. Take a look: [![Disappearing GameObject](https://i.stack.imgur.com/ZLqt8.gif)](https://i.stack.imgur.com/ZLqt8.gif) Any ideas on why this is happening, and how I can fix it? **EDIT:** Here's my hierarchy and inspector: [![Hierarchy and Inspector](https://i.stack.imgur.com/62CcI.png)](https://i.stack.imgur.com/62CcI.png)
2018/05/17
[ "https://gamedev.stackexchange.com/questions/158761", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/112380/" ]
Though I'm not sure why, I tried messing around, and putting the Z-radius of the X Animation *behind* the box, it actually showed up in front of it (with the Z-radius of the X animation being -2 and the box being 0).
From your edit, it looks like you’ve selected the X animation GameObject. I see that it’s on the Default sorting layer. See SpriteRenderer component’s layer. If you have multiple layers, put the X animation on the a foreground layer. You can create new layers if you don’t have any. If you are not able to create/use a different layer due to some reason, you can change the Order in Layer property of the SpriteRenderer component. It is currently set to 0. You can try changing it to 1 or more. Putting the X animation slightly closer towards the camera, meaning a slight negative offset than the box, will also work. But remember, if you move the X animation in z axis, and you’re using a perspective camera, the result might not be what you are looking for. I would prefer doing it in either of the 2 above mentioned ways
64,689,797
I have read multiple answers given to my problem but none made any change. My problem is that when I press the "Reset" button it resets it doesn't show me all the info it should. For some reason, it can't find the id of the line I want to change. So in short: It gives errors after I press the "Reset button". ```html <!DOCTYPE html> <head> <link rel="stylesheet" href="Style.css"> <title></title> </head> <body> <button onclick="SetName(this.id)" id=" Name1">Name1</button> <button onclick="SetName(this.id)" id=" Name2">Name2</button> <button onclick="SetName(this.id)" id=" Name3">Name3</button> <button onclick="SetName(this.id)" id=" Name4">Name4</button> <button onclick="SetName(this.id)" id=" Name5">Name5</button> <button onclick="SetName(this.id)" id=" Name6">Name6</button> <button onclick="SetName(this.id)" id=" Name7">Name7</button> <button onclick="SetName(this.id)" id=" Name8">Name8</button> <button onclick="Randomize()">Randomize</button> <button onclick="Reset()">Reset</button> <p id="Spelers">Players: <span id="RandomNames"></span></p> <p id="TotalPlayers">Total Players: <span id="TotalMembers">0</span></p> <p>Team 1: <span id="TeamOne"></span></p> <p>Team 2: <span id="TeamTwo"></span></p> <script> var Names = []; var Team1 = []; var Team2 = []; function SetName(NameClicked) { if(!(Names.includes(NameClicked))) { Names.push(NameClicked); } else { var DeleteNamePos = Names.indexOf(NameClicked); Names.splice(DeleteNamePos, 1); } document.getElementById("RandomNames").innerHTML = Names; document.getElementById("TotalMembers").innerHTML = Names.length; } function Randomize() { var i = 1; while(i <= Names.length) { var RandomNameSelect = Math.floor(Math.random() * Names.length); Team1.push(Names[RandomNameSelect]); Names.splice(RandomNameSelect, 1); var RandomNameSelect2 = Math.floor(Math.random() * Names.length); Team2.push(Names[RandomNameSelect2]); Names.splice(RandomNameSelect2, 1); } document.getElementById("Spelers").innerHTML = "Teams are: "; document.getElementById("TotalPlayers").innerHTML = ""; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } function Reset() { Names = []; Team1 = []; Team2 = []; document.getElementById("TotalPlayers").innerHTML = "Total players: "; document.getElementById("Spelers").innerHTML = "Players: "; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } </script> </body> ``` Also a link for a code snippet: <http://jsfiddle.net/u2wt9qpe/>
2020/11/05
[ "https://Stackoverflow.com/questions/64689797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11632275/" ]
On `Reset()` function, you have set html data to `TotalPlayers` and `Spelers` selectors using `innerHTML`. So the inner span tags, `TotalMembers`, and `RandomNames` selectors are removed. To reset the data, it is needed to make `TotalMembers` and `RandomNames` selectors empty as follows. ```js var Names = []; var Team1 = []; var Team2 = []; function SetName(NameClicked) { if (!(Names.includes(NameClicked))) { Names.push(NameClicked); } else { var DeleteNamePos = Names.indexOf(NameClicked); Names.splice(DeleteNamePos, 1); } document.getElementById("RandomNames").innerHTML = Names; document.getElementById("TotalMembers").innerHTML = Names.length; } function Randomize() { var i = 1; while (i <= Names.length) { var RandomNameSelect = Math.floor(Math.random() * Names.length); Team1.push(Names[RandomNameSelect]); Names.splice(RandomNameSelect, 1); var RandomNameSelect2 = Math.floor(Math.random() * Names.length); Team2.push(Names[RandomNameSelect2]); Names.splice(RandomNameSelect2, 1); } document.getElementById("Spelers").innerHTML = "Teams are: "; document.getElementById("TotalMembers").innerHTML = ""; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } function Reset() { Names = []; Team1 = []; Team2 = []; document.getElementById("TotalMembers").innerHTML = ""; document.getElementById("RandomNames").innerText = ""; document.getElementById("TeamOne").innerText = Team1; document.getElementById("TeamTwo").innerText = Team2; } ``` ```html <button onclick="SetName(this.id)" id=" Name1">Name1</button> <button onclick="SetName(this.id)" id=" Name2">Name2</button> <button onclick="SetName(this.id)" id=" Name3">Name3</button> <button onclick="SetName(this.id)" id=" Name4">Name4</button> <button onclick="SetName(this.id)" id=" Name5">Name5</button> <button onclick="SetName(this.id)" id=" Name6">Name6</button> <button onclick="SetName(this.id)" id=" Name7">Name7</button> <button onclick="SetName(this.id)" id=" Name8">Name8</button> <button onclick="Randomize()">Randomize</button> <button onclick="Reset()">Reset</button> <p id="Spelers">Players: <span id="RandomNames"></span></p> <p id="TotalPlayers">Total Players: <span id="TotalMembers">0</span></p> <p>Team 1: <span id="TeamOne"></span></p> <p>Team 2: <span id="TeamTwo"></span></p> ```
When you initially set up the DOM, you have Players: . Notice that Element with ID=RandomNames is a child of the element with ID="Spelers". When you execute either the reset() or the randomize(), this line document.getElementById("Spelers").innerHTML = "Teams are: "; <--- will remove the child element with ID="RandomNames" as it replaces everything. This will no longer be available on the DOM the next time you call SetName(). You could add code to replace this element after resetting.
64,689,797
I have read multiple answers given to my problem but none made any change. My problem is that when I press the "Reset" button it resets it doesn't show me all the info it should. For some reason, it can't find the id of the line I want to change. So in short: It gives errors after I press the "Reset button". ```html <!DOCTYPE html> <head> <link rel="stylesheet" href="Style.css"> <title></title> </head> <body> <button onclick="SetName(this.id)" id=" Name1">Name1</button> <button onclick="SetName(this.id)" id=" Name2">Name2</button> <button onclick="SetName(this.id)" id=" Name3">Name3</button> <button onclick="SetName(this.id)" id=" Name4">Name4</button> <button onclick="SetName(this.id)" id=" Name5">Name5</button> <button onclick="SetName(this.id)" id=" Name6">Name6</button> <button onclick="SetName(this.id)" id=" Name7">Name7</button> <button onclick="SetName(this.id)" id=" Name8">Name8</button> <button onclick="Randomize()">Randomize</button> <button onclick="Reset()">Reset</button> <p id="Spelers">Players: <span id="RandomNames"></span></p> <p id="TotalPlayers">Total Players: <span id="TotalMembers">0</span></p> <p>Team 1: <span id="TeamOne"></span></p> <p>Team 2: <span id="TeamTwo"></span></p> <script> var Names = []; var Team1 = []; var Team2 = []; function SetName(NameClicked) { if(!(Names.includes(NameClicked))) { Names.push(NameClicked); } else { var DeleteNamePos = Names.indexOf(NameClicked); Names.splice(DeleteNamePos, 1); } document.getElementById("RandomNames").innerHTML = Names; document.getElementById("TotalMembers").innerHTML = Names.length; } function Randomize() { var i = 1; while(i <= Names.length) { var RandomNameSelect = Math.floor(Math.random() * Names.length); Team1.push(Names[RandomNameSelect]); Names.splice(RandomNameSelect, 1); var RandomNameSelect2 = Math.floor(Math.random() * Names.length); Team2.push(Names[RandomNameSelect2]); Names.splice(RandomNameSelect2, 1); } document.getElementById("Spelers").innerHTML = "Teams are: "; document.getElementById("TotalPlayers").innerHTML = ""; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } function Reset() { Names = []; Team1 = []; Team2 = []; document.getElementById("TotalPlayers").innerHTML = "Total players: "; document.getElementById("Spelers").innerHTML = "Players: "; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } </script> </body> ``` Also a link for a code snippet: <http://jsfiddle.net/u2wt9qpe/>
2020/11/05
[ "https://Stackoverflow.com/questions/64689797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11632275/" ]
When resetting the values through `Reset()` function, you have removed the inner elements like `RandomNames` and `TotalMembers`. As a workaround, you can add those two elements again when resetting. ```js var Names = []; var Team1 = []; var Team2 = []; function SetName(NameClicked) { if(!(Names.includes(NameClicked))) { Names.push(NameClicked); } else { var DeleteNamePos = Names.indexOf(NameClicked); Names.splice(DeleteNamePos, 1); } document.getElementById("RandomNames").innerHTML = Names; document.getElementById("TotalMembers").innerHTML = Names.length; } function Randomize() { var i = 1; while(i <= Names.length) { var RandomNameSelect = Math.floor(Math.random() * Names.length); Team1.push(Names[RandomNameSelect]); Names.splice(RandomNameSelect, 1); var RandomNameSelect2 = Math.floor(Math.random() * Names.length); Team2.push(Names[RandomNameSelect2]); Names.splice(RandomNameSelect2, 1); } document.getElementById("Spelers").innerHTML = "Teams are: "; document.getElementById("TotalPlayers").innerHTML = ""; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } function Reset() { Names = []; Team1 = []; Team2 = []; document.getElementById("TotalPlayers").innerHTML = 'Total Players: <span id="TotalMembers">0</span>'; document.getElementById("Spelers").innerHTML = 'Players: <span id="RandomNames"></span>'; document.getElementById("TeamOne").innerHTML = Team1; document.getElementById("TeamTwo").innerHTML = Team2; } ``` ```html <!DOCTYPE html> <head> <link rel="stylesheet" href="Style.css"> <title></title> </head> <body> <button onclick="SetName(this.id)" id=" Name1">Name1</button> <button onclick="SetName(this.id)" id=" Name2">Name2</button> <button onclick="SetName(this.id)" id=" Name3">Name3</button> <button onclick="SetName(this.id)" id=" Name4">Name4</button> <button onclick="SetName(this.id)" id=" Name5">Name5</button> <button onclick="SetName(this.id)" id=" Name6">Name6</button> <button onclick="SetName(this.id)" id=" Name7">Name7</button> <button onclick="SetName(this.id)" id=" Name8">Name8</button> <button onclick="Randomize()">Randomize</button> <button onclick="Reset()">Reset</button> <p id="Spelers">Players: <span id="RandomNames"></span></p> <p id="TotalPlayers">Total Players: <span id="TotalMembers">0</span></p> <p>Team 1: <span id="TeamOne"></span></p> <p>Team 2: <span id="TeamTwo"></span></p> ```
When you initially set up the DOM, you have Players: . Notice that Element with ID=RandomNames is a child of the element with ID="Spelers". When you execute either the reset() or the randomize(), this line document.getElementById("Spelers").innerHTML = "Teams are: "; <--- will remove the child element with ID="RandomNames" as it replaces everything. This will no longer be available on the DOM the next time you call SetName(). You could add code to replace this element after resetting.
63,738,830
I'm using the [Python standard library modules](https://docs.python.org/3/py-modindex.html) and the `pythoncom` and `win32com.client` modules from the `PyWin32` package to interact with Microsoft Excel. I get a list of the running Excel instances as COM object references and then when I want to close the Excel instances I first iterate through the workbooks and close them. Then I execute the [Quit method](https://learn.microsoft.com/en-us/office/vba/api/excel.application.quit) and after I attempt to terminate the Excel process if it's not terminated. I do the check (`_is_process_running`) because the Excel instance might not close successfully if for example the Excel process is a zombie process ([information on how one can be created](https://github.com/xlwings/xlwings/issues/55)) or if the VBA listens to the [before close event](https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.beforeclose) and cancels it. My current quirky solution to know when to check if it closed is to use the [sleep function](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep). It does seem to work but it can fail in certain circumstances, such as if it takes longer than the sleep function waits for. I thought that clearing all the COM references and collecting the garbage would be enough for the Excel process to terminate if the `Quit` method does succeed but it still takes some time asynchronously. The check is in the `close` method of the `_excel_application_wrapper` class in the `excel.pyw` file. --- Simple code to generate an Excel zombie process (you can see the process in the task manager): ``` from os import getpid, kill from win32com.client import DispatchEx _ = DispatchEx('Excel.Application') kill(getpid(), 9) ``` This is only for testing purposes to help reproduce an Excel instance that won't be closed when calling `Quit`. Another way to make `Quit` fail to close is to add this VBA code to the workbook in Excel: ``` Private Sub Workbook_BeforeClose(Cancel As Boolean) Cancel = True End Sub ``` --- Code on the `excel_test.py` file: ``` import excel from traceback import print_exc as print_exception try: excel_application_instances = excel.get_application_instances() for excel_application_instance in excel_application_instances: # use excel_application_instance here before closing it # ... excel_application_instance.close() except Exception: print('An exception has occurred. Details of the exception:') print_exception() finally: input('Execution finished.') ``` Code on the `excel.pyw` file: ``` from ctypes import byref as by_reference, c_ulong as unsigned_long, windll as windows_dll from gc import collect as collect_garbage from pythoncom import CreateBindCtx as create_bind_context, GetRunningObjectTable as get_running_object_table, \ IID_IDispatch as dispatch_interface_iid, _GetInterfaceCount as get_interface_count from win32com.client import Dispatch as dispatch class _object_wrapper_base_class(): def __init__(self, object_to_be_wrapped): # self.__dict__['_wrapped_object'] instead of # self._wrapped_object to prevent recursive calling of __setattr__ # https://stackoverflow.com/a/12999019 self.__dict__['_wrapped_object'] = object_to_be_wrapped def __getattr__(self, name): return getattr(self._wrapped_object, name) def __setattr__(self, name, value): setattr(self._wrapped_object, name, value) class _excel_workbook_wrapper(_object_wrapper_base_class): # __setattr__ takes precedence over properties with setters # https://stackoverflow.com/a/15751159 def __setattr__(self, name, value): # raises AttributeError if the attribute doesn't exist getattr(self, name) if name in vars(_excel_workbook_wrapper): attribute = vars(_excel_workbook_wrapper)[name] # checks if the attribute is a property with a setter if isinstance(attribute, property) and attribute.fset is not None: attribute.fset(self, value) return setattr(self._wrapped_object, name, value) @property def saved(self): return self.Saved @saved.setter def saved(self, value): self.Saved = value def close(self): self.Close() class _excel_workbooks_wrapper(_object_wrapper_base_class): def __getitem__(self, key): return _excel_workbook_wrapper(self._wrapped_object[key]) class _excel_application_wrapper(_object_wrapper_base_class): @property def workbooks(self): return _excel_workbooks_wrapper(self.Workbooks) def _get_process(self): window_handle = self.hWnd process_identifier = unsigned_long() windows_dll.user32.GetWindowThreadProcessId(window_handle, by_reference(process_identifier)) return process_identifier.value def _is_process_running(self, process_identifier): SYNCHRONIZE = 0x00100000 process_handle = windows_dll.kernel32.OpenProcess(SYNCHRONIZE, False, process_identifier) returned_value = windows_dll.kernel32.WaitForSingleObject(process_handle, 0) windows_dll.kernel32.CloseHandle(process_handle) WAIT_TIMEOUT = 0x00000102 return returned_value == WAIT_TIMEOUT def _terminate_process(self, process_identifier): PROCESS_TERMINATE = 0x0001 process_handle = windows_dll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process_identifier) process_terminated = windows_dll.kernel32.TerminateProcess(process_handle, 0) windows_dll.kernel32.CloseHandle(process_handle) return process_terminated != 0 def close(self): for workbook in self.workbooks: workbook.saved = True workbook.close() del workbook process_identifier = self._get_process() self.Quit() del self._wrapped_object # 0 COM references print(f'{get_interface_count()} COM references.') collect_garbage() # quirky solution to wait for the Excel process to # terminate if it did closed successfully from self.Quit() windows_dll.kernel32.Sleep(1000) # check if the Excel instance closed successfully # it may not close for example if the Excel process is a zombie process # or if the VBA listens to the before close event and cancels it if self._is_process_running(process_identifier=process_identifier): print('Excel instance failed to close.') # if the process is still running then attempt to terminate it if self._terminate_process(process_identifier=process_identifier): print('The process of the Excel instance was successfully terminated.') else: print('The process of the Excel instance failed to be terminated.') else: print('Excel instance closed successfully.') def get_application_instances(): running_object_table = get_running_object_table() bind_context = create_bind_context() excel_application_class_clsid = '{00024500-0000-0000-C000-000000000046}' excel_application_clsid = '{000208D5-0000-0000-C000-000000000046}' excel_application_instances = [] for moniker in running_object_table: display_name = moniker.GetDisplayName(bind_context, None) if excel_application_class_clsid not in display_name: continue unknown_com_interface = running_object_table.GetObject(moniker) dispatch_interface = unknown_com_interface.QueryInterface(dispatch_interface_iid) dispatch_clsid = str(dispatch_interface.GetTypeInfo().GetTypeAttr().iid) if dispatch_clsid != excel_application_clsid: continue excel_application_instance_com_object = dispatch(dispatch=dispatch_interface) excel_application_instance = _excel_application_wrapper(excel_application_instance_com_object) excel_application_instances.append(excel_application_instance) return excel_application_instances ``` --- [This answer](https://stackoverflow.com/a/32717130) suggests checking if the remote procedural call (RPC) server is unavailable by calling something from the COM object. I have tried trial and error in different ways without success. Such as adding the code below after `self.Quit()`. ``` from pythoncom import com_error, CoUninitialize as co_uninitialize from traceback import print_exc as print_exception co_uninitialize() try: print(self._wrapped_object) except com_error as exception: if exception.hresult == -2147023174: # "The RPC server is unavailable." print_exception() else: raise ```
2020/09/04
[ "https://Stackoverflow.com/questions/63738830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7393973/" ]
You shouldn't be using your Demo/Developer account for production data - envelope will be sent with the red "demonstration" watermark. When you have a paid production account, I would recommend setting up your webhooks to run on different urls: Something like `example.com/webhook/test` vs `example.com/webhook/production`. Query String Parameters could be used instead if your application can parse them. When an integration key is promoted to production, it is copied over, so it can still be used in the Demo environment. It is recommended that you keep your application running in the Demo environment so you can be aware of upcoming changes in the DocuSign platform.
Connect webhook is set on per account, your DEMO and Production accounts are separate entities. When you promote your ikey to production even the value is the same they are completely different. In production you still have to set your Secret Key and RSA Keypairs for the promoted ikey read here <https://www.docusign.com/blog/dsdev-from-the-trenches-your-apps-approved-for-go-live-now-configure-your-production-account> You can generate another ikey in sandbox, this is solution as well.
31,632,806
I have a table that stretches across the entire page. I'm zebra striping using `nth-child` on the `tr`'s to set the `background` of the row. The problem is that it is only coloring the cells and not the entire row. You can see white space in between each cell of the colored rows. You can see an example [here](http://jsfiddle.net/6q3r8bj9/.) ```css table { width: 100%; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ``` How do you change the `background` color of the entire row and not each individual cell?
2015/07/26
[ "https://Stackoverflow.com/questions/31632806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5156529/" ]
add [`border-collapse:collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) to `table` > > The border-collapse CSS property determines whether a table's borders > are separated or collapsed. In the separated model, adjacent cells > each have their own distinct borders. In the collapsed model, adjacent > table cells share borders. > > > The separated model is the traditional HTML table border model. > Adjacent cells each have their own distinct borders. The distance > between them given by the border-spacing property. > > > In the collapsed border model, adjacent table cells share borders. In > that model, the border-style value of inset behaves like groove, and > outset behaves like ridge. > > > ```css table { width: 100%; border-collapse:collapse; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ```
Add this to your HTML: ``` <table cellspacing="0"> ``` Or via CSS ``` table {border-spacing: 0;} ```
31,632,806
I have a table that stretches across the entire page. I'm zebra striping using `nth-child` on the `tr`'s to set the `background` of the row. The problem is that it is only coloring the cells and not the entire row. You can see white space in between each cell of the colored rows. You can see an example [here](http://jsfiddle.net/6q3r8bj9/.) ```css table { width: 100%; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ``` How do you change the `background` color of the entire row and not each individual cell?
2015/07/26
[ "https://Stackoverflow.com/questions/31632806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5156529/" ]
The CSS solution to this uses the `border-spacing` and `border-collapse` properties. Here's your `table` rule, updated: ``` table { width: 100%; border-spacing: 0; border-collapse: collapse; } ``` It used to be that margin and padding in tables were primarily controlled in the HTML with the `cellspacing` and `cellpadding` attributes. `<table border="1" cellpadding="5" cellspacing="10"> ... </table>` But these attributes are now on a path to obsolescence. Use CSS. Examples ``` table { border-collapse: separate; border-spacing: 5px; } td { padding: 5px; } ``` To learn more about `border-collapse` see this article. <https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse>
Add this to your HTML: ``` <table cellspacing="0"> ``` Or via CSS ``` table {border-spacing: 0;} ```
31,632,806
I have a table that stretches across the entire page. I'm zebra striping using `nth-child` on the `tr`'s to set the `background` of the row. The problem is that it is only coloring the cells and not the entire row. You can see white space in between each cell of the colored rows. You can see an example [here](http://jsfiddle.net/6q3r8bj9/.) ```css table { width: 100%; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ``` How do you change the `background` color of the entire row and not each individual cell?
2015/07/26
[ "https://Stackoverflow.com/questions/31632806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5156529/" ]
add [`border-collapse:collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) to `table` > > The border-collapse CSS property determines whether a table's borders > are separated or collapsed. In the separated model, adjacent cells > each have their own distinct borders. In the collapsed model, adjacent > table cells share borders. > > > The separated model is the traditional HTML table border model. > Adjacent cells each have their own distinct borders. The distance > between them given by the border-spacing property. > > > In the collapsed border model, adjacent table cells share borders. In > that model, the border-style value of inset behaves like groove, and > outset behaves like ridge. > > > ```css table { width: 100%; border-collapse:collapse; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ```
The CSS solution to this uses the `border-spacing` and `border-collapse` properties. Here's your `table` rule, updated: ``` table { width: 100%; border-spacing: 0; border-collapse: collapse; } ``` It used to be that margin and padding in tables were primarily controlled in the HTML with the `cellspacing` and `cellpadding` attributes. `<table border="1" cellpadding="5" cellspacing="10"> ... </table>` But these attributes are now on a path to obsolescence. Use CSS. Examples ``` table { border-collapse: separate; border-spacing: 5px; } td { padding: 5px; } ``` To learn more about `border-collapse` see this article. <https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse>
31,632,806
I have a table that stretches across the entire page. I'm zebra striping using `nth-child` on the `tr`'s to set the `background` of the row. The problem is that it is only coloring the cells and not the entire row. You can see white space in between each cell of the colored rows. You can see an example [here](http://jsfiddle.net/6q3r8bj9/.) ```css table { width: 100%; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ``` How do you change the `background` color of the entire row and not each individual cell?
2015/07/26
[ "https://Stackoverflow.com/questions/31632806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5156529/" ]
add [`border-collapse:collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) to `table` > > The border-collapse CSS property determines whether a table's borders > are separated or collapsed. In the separated model, adjacent cells > each have their own distinct borders. In the collapsed model, adjacent > table cells share borders. > > > The separated model is the traditional HTML table border model. > Adjacent cells each have their own distinct borders. The distance > between them given by the border-spacing property. > > > In the collapsed border model, adjacent table cells share borders. In > that model, the border-style value of inset behaves like groove, and > outset behaves like ridge. > > > ```css table { width: 100%; border-collapse:collapse; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ```
By default there is some spacing between the borders, to remove the spacing use ``` table { border-collapse: collapse; } ``` or ``` table { border-spacing: 0; } ``` the `border-collapse: collapse` will merge the borders of cells in to one border while `border-spacing: 0` will decrease the space between the cells to show it as single border. I will prefer to use `border-collapse` because its purpose is to merge the borders into single border.
31,632,806
I have a table that stretches across the entire page. I'm zebra striping using `nth-child` on the `tr`'s to set the `background` of the row. The problem is that it is only coloring the cells and not the entire row. You can see white space in between each cell of the colored rows. You can see an example [here](http://jsfiddle.net/6q3r8bj9/.) ```css table { width: 100%; } tr:nth-child(even) { background: peachpuff; } ``` ```html <table> <tbody> <tr> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>0</td> </tr> <tr> <td>3</td> <td>0</td> </tr> <tr> <td>4</td> <td>0</td> </tr> <tr> <td>5</td> <td>0</td> </tr> <tr> <td>6</td> <td>0</td> </tr> <tr> <td>7</td> <td>0</td> </tr> <tr> <td>8</td> <td>0</td> </tr> <tr> <td>9</td> <td>0</td> </tr> </tbody> </table> ``` How do you change the `background` color of the entire row and not each individual cell?
2015/07/26
[ "https://Stackoverflow.com/questions/31632806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5156529/" ]
The CSS solution to this uses the `border-spacing` and `border-collapse` properties. Here's your `table` rule, updated: ``` table { width: 100%; border-spacing: 0; border-collapse: collapse; } ``` It used to be that margin and padding in tables were primarily controlled in the HTML with the `cellspacing` and `cellpadding` attributes. `<table border="1" cellpadding="5" cellspacing="10"> ... </table>` But these attributes are now on a path to obsolescence. Use CSS. Examples ``` table { border-collapse: separate; border-spacing: 5px; } td { padding: 5px; } ``` To learn more about `border-collapse` see this article. <https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse>
By default there is some spacing between the borders, to remove the spacing use ``` table { border-collapse: collapse; } ``` or ``` table { border-spacing: 0; } ``` the `border-collapse: collapse` will merge the borders of cells in to one border while `border-spacing: 0` will decrease the space between the cells to show it as single border. I will prefer to use `border-collapse` because its purpose is to merge the borders into single border.
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
I had the same problem with my app. How the rotation in iOS 6 work is that. => when ever you are using UINavigationCOntroller the method in AppDelegate ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return } ``` decides whether to rotate or not. => when the view is presented in the Modal presentation style the method ``` - (BOOL)shouldAutorotate ``` which is inside the viewController for that view triggers the method in the appDelegate. And as 1st case appDelegate decides to rotate or not. **My Solution::** What I did for Modal presentation was that. Created a flag in app delegate. when ever the flag is YES it rotates to Landscape and else its only Portrait. ``` - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window { if(self.shouldRotate ) //shouldRotate is my flag { self.shouldRotate = NO; return (UIInterfaceOrientationMaskAll); } return (UIInterfaceOrientationMaskPortrait); } ``` And to toggle between rotations ``` - (BOOL)shouldAutorotate { YourAppDelegate *mainDelegate = (YourAppDelegate*)[[UIApplication sharedApplication]delegate]; mainDelegate.shouldRotate = YES; return YES; } ``` **Note**: This works is only for view that are Modely Presented. Using Flag, not a good coding practice.
Try this, If TabBarController is RootViewController for window, Then Create Custom Class which inherits TabBarController say CustomTabBarController.h Add Below method in CustomTabBarController.h ``` -(NSUInteger)supportedInterfaceOrientations // Must return Orientation Mask ``` Finally Call Below in AppDelegate.m ``` - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if( [self.window.rootViewController supportedInterfaceOrientations]!=0) { return [self.window.rootViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; } ```
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
From Apple's iOS 6 SDK Release Notes: > > Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow: and shouldAutorotate methods. > > > More responsibility is moving to the app and the app delegate. Now, iOS containers (such as UINavigationController) do not consult their children to determine whether they should autorotate. **By default, an app and a view controller’s supported interface orientations are set to UIInterfaceOrientationMaskAll for the iPad idiom and UIInterfaceOrientationMaskAllButUpsideDown for the iPhone idiom.** > > > A view controller’s supported interface orientations can change over time—even an app’s supported interface orientations can change over time. **The system asks the top-most full-screen view controller (typically the root view controller) for its supported interface orientations whenever the device rotates or whenever a view controller is presented with the full-screen modal presentation style.** Moreover, the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method. **The system intersects the view controller’s supported orientations with the app’s supported orientations (as determined by the Info.plist file or the app delegate’s application:supportedInterfaceOrientationsForWindow: method) to determine whether to rotate.** > > > The system determines whether an orientation is supported by intersecting the value returned by the app’s supportedInterfaceOrientationsForWindow: method with the value returned by the supportedInterfaceOrientations method of the top-most full-screen controller. > The setStatusBarOrientation:animated: method is not deprecated outright. It now works only if the supportedInterfaceOrientations method of the top-most full-screen view controller returns 0. This makes the caller responsible for ensuring that the status bar orientation is consistent. > > > For compatibility, view controllers that still implement the shouldAutorotateToInterfaceOrientation: method do not get the new autorotation behaviors. (In other words, they do not fall back to using the app, app delegate, or Info.plist file to determine the supported orientations.) Instead, the shouldAutorotateToInterfaceOrientation: method is used to synthesize the information that would be returned by the supportedInterfaceOrientations method. > > > If you want your whole app to rotate then you should set your Info.plist to support all orientations. Now if you want a specific view to be portrait only you will have to do some sort of subclass and override the autorotation methods to return portrait only. I have an example here: <https://stackoverflow.com/a/12522119/1575017>
Ough! A half of a day spent, and the problem solved! He he. As the documentation above says, this is really it! The core points are: > > More **responsibility is moving to the app and the app delegate**. > Now, iOS containers (such as UINavigationController) do not consult > their children to determine whether they should autorotate. By > default, an app and a view controller’s supported interface > orientations are set to UIInterfaceOrientationMaskAll for the iPad > idiom and UIInterfaceOrientationMaskAllButUpsideDown for the iPhone > idiom. > > > So, any time something with root controller changes, the system asks app delegate "So, what are we? Rotating or not?" If "rotating": > > the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method > > > then system asks our app delegate for ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return ...; } ``` That's really pretty simple. How to determine when should we allow Portrait or Landscape etc - is up to you. Testing for root controller didn't work for me because of some points, but this works: ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return self.fullScreenVideoIsPlaying ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait; } ``` The property "fullScreenVideoIsPlaying" is set up by me manually whenever I need that. The only other important thing to be careful is the enum. As it says in docs ... (read carefully above iPad/iPhone thing). So, you can play with those as you need. Another tiny thing was some buggy behaviour after closing the player controller. There was one time when it did not change the orientation, but that happened once and in some strange way, and only in simulator (iOS 6 only, of course). So I even could not react, as it happened unexpectedly and after clicking fast on some other elements of my app, it rotated to normal orientation. So, not sure - might be some delay in simulator work or something (or, really a bug :) ). Good luck!
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
Unfortunately you'll need to turn on all orientations in your plist and use supportedInterfaceOrientations on all the view controllers you don't want to rotate. (In your case everything but the video player.)
Try this, If TabBarController is RootViewController for window, Then Create Custom Class which inherits TabBarController say CustomTabBarController.h Add Below method in CustomTabBarController.h ``` -(NSUInteger)supportedInterfaceOrientations // Must return Orientation Mask ``` Finally Call Below in AppDelegate.m ``` - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if( [self.window.rootViewController supportedInterfaceOrientations]!=0) { return [self.window.rootViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; } ```
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
You can also subclass UITabBarController to make it ask its children about the shouldAutorotate and supportedInterfaceOrientation like this: ``` @implementation MyTabBarController -(BOOL)shouldAutorotate { return [self.selectedViewController shouldAutorotate]; } -(NSUInteger)supportedInterfaceOrientations { return [self.selectedViewController supportedInterfaceOrientations]; } @end ``` Then you just use your custom container in place of the standard one and it works! just tested.
I found the easiest way to set this up is to use the "supported interface orientations" buttons which you can see if you look at Targets....Summary Tab (under iPhone/iPad Deployment info). Its basically a GUI to set the plist file
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
I had the same problem with my app. How the rotation in iOS 6 work is that. => when ever you are using UINavigationCOntroller the method in AppDelegate ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return } ``` decides whether to rotate or not. => when the view is presented in the Modal presentation style the method ``` - (BOOL)shouldAutorotate ``` which is inside the viewController for that view triggers the method in the appDelegate. And as 1st case appDelegate decides to rotate or not. **My Solution::** What I did for Modal presentation was that. Created a flag in app delegate. when ever the flag is YES it rotates to Landscape and else its only Portrait. ``` - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window { if(self.shouldRotate ) //shouldRotate is my flag { self.shouldRotate = NO; return (UIInterfaceOrientationMaskAll); } return (UIInterfaceOrientationMaskPortrait); } ``` And to toggle between rotations ``` - (BOOL)shouldAutorotate { YourAppDelegate *mainDelegate = (YourAppDelegate*)[[UIApplication sharedApplication]delegate]; mainDelegate.shouldRotate = YES; return YES; } ``` **Note**: This works is only for view that are Modely Presented. Using Flag, not a good coding practice.
Unfortunately you'll need to turn on all orientations in your plist and use supportedInterfaceOrientations on all the view controllers you don't want to rotate. (In your case everything but the video player.)
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
Ough! A half of a day spent, and the problem solved! He he. As the documentation above says, this is really it! The core points are: > > More **responsibility is moving to the app and the app delegate**. > Now, iOS containers (such as UINavigationController) do not consult > their children to determine whether they should autorotate. By > default, an app and a view controller’s supported interface > orientations are set to UIInterfaceOrientationMaskAll for the iPad > idiom and UIInterfaceOrientationMaskAllButUpsideDown for the iPhone > idiom. > > > So, any time something with root controller changes, the system asks app delegate "So, what are we? Rotating or not?" If "rotating": > > the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method > > > then system asks our app delegate for ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return ...; } ``` That's really pretty simple. How to determine when should we allow Portrait or Landscape etc - is up to you. Testing for root controller didn't work for me because of some points, but this works: ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return self.fullScreenVideoIsPlaying ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait; } ``` The property "fullScreenVideoIsPlaying" is set up by me manually whenever I need that. The only other important thing to be careful is the enum. As it says in docs ... (read carefully above iPad/iPhone thing). So, you can play with those as you need. Another tiny thing was some buggy behaviour after closing the player controller. There was one time when it did not change the orientation, but that happened once and in some strange way, and only in simulator (iOS 6 only, of course). So I even could not react, as it happened unexpectedly and after clicking fast on some other elements of my app, it rotated to normal orientation. So, not sure - might be some delay in simulator work or something (or, really a bug :) ). Good luck!
Unfortunately you'll need to turn on all orientations in your plist and use supportedInterfaceOrientations on all the view controllers you don't want to rotate. (In your case everything but the video player.)
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
I had the same problem with my app. How the rotation in iOS 6 work is that. => when ever you are using UINavigationCOntroller the method in AppDelegate ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return } ``` decides whether to rotate or not. => when the view is presented in the Modal presentation style the method ``` - (BOOL)shouldAutorotate ``` which is inside the viewController for that view triggers the method in the appDelegate. And as 1st case appDelegate decides to rotate or not. **My Solution::** What I did for Modal presentation was that. Created a flag in app delegate. when ever the flag is YES it rotates to Landscape and else its only Portrait. ``` - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window { if(self.shouldRotate ) //shouldRotate is my flag { self.shouldRotate = NO; return (UIInterfaceOrientationMaskAll); } return (UIInterfaceOrientationMaskPortrait); } ``` And to toggle between rotations ``` - (BOOL)shouldAutorotate { YourAppDelegate *mainDelegate = (YourAppDelegate*)[[UIApplication sharedApplication]delegate]; mainDelegate.shouldRotate = YES; return YES; } ``` **Note**: This works is only for view that are Modely Presented. Using Flag, not a good coding practice.
I found the easiest way to set this up is to use the "supported interface orientations" buttons which you can see if you look at Targets....Summary Tab (under iPhone/iPad Deployment info). Its basically a GUI to set the plist file
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
Try this, If TabBarController is RootViewController for window, Then Create Custom Class which inherits TabBarController say CustomTabBarController.h Add Below method in CustomTabBarController.h ``` -(NSUInteger)supportedInterfaceOrientations // Must return Orientation Mask ``` Finally Call Below in AppDelegate.m ``` - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if( [self.window.rootViewController supportedInterfaceOrientations]!=0) { return [self.window.rootViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; } ```
I found the easiest way to set this up is to use the "supported interface orientations" buttons which you can see if you look at Targets....Summary Tab (under iPhone/iPad Deployment info). Its basically a GUI to set the plist file
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
From Apple's iOS 6 SDK Release Notes: > > Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow: and shouldAutorotate methods. > > > More responsibility is moving to the app and the app delegate. Now, iOS containers (such as UINavigationController) do not consult their children to determine whether they should autorotate. **By default, an app and a view controller’s supported interface orientations are set to UIInterfaceOrientationMaskAll for the iPad idiom and UIInterfaceOrientationMaskAllButUpsideDown for the iPhone idiom.** > > > A view controller’s supported interface orientations can change over time—even an app’s supported interface orientations can change over time. **The system asks the top-most full-screen view controller (typically the root view controller) for its supported interface orientations whenever the device rotates or whenever a view controller is presented with the full-screen modal presentation style.** Moreover, the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method. **The system intersects the view controller’s supported orientations with the app’s supported orientations (as determined by the Info.plist file or the app delegate’s application:supportedInterfaceOrientationsForWindow: method) to determine whether to rotate.** > > > The system determines whether an orientation is supported by intersecting the value returned by the app’s supportedInterfaceOrientationsForWindow: method with the value returned by the supportedInterfaceOrientations method of the top-most full-screen controller. > The setStatusBarOrientation:animated: method is not deprecated outright. It now works only if the supportedInterfaceOrientations method of the top-most full-screen view controller returns 0. This makes the caller responsible for ensuring that the status bar orientation is consistent. > > > For compatibility, view controllers that still implement the shouldAutorotateToInterfaceOrientation: method do not get the new autorotation behaviors. (In other words, they do not fall back to using the app, app delegate, or Info.plist file to determine the supported orientations.) Instead, the shouldAutorotateToInterfaceOrientation: method is used to synthesize the information that would be returned by the supportedInterfaceOrientations method. > > > If you want your whole app to rotate then you should set your Info.plist to support all orientations. Now if you want a specific view to be portrait only you will have to do some sort of subclass and override the autorotation methods to return portrait only. I have an example here: <https://stackoverflow.com/a/12522119/1575017>
Try this, If TabBarController is RootViewController for window, Then Create Custom Class which inherits TabBarController say CustomTabBarController.h Add Below method in CustomTabBarController.h ``` -(NSUInteger)supportedInterfaceOrientations // Must return Orientation Mask ``` Finally Call Below in AppDelegate.m ``` - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if( [self.window.rootViewController supportedInterfaceOrientations]!=0) { return [self.window.rootViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; } ```
12,526,054
I have `UITabBarController` app which plays video and shows other information in other `UITabBar` tabs. In iOS 6 `UIView` rotation methods have been deprecated, and now I need to use `shouldAutoRotate` and `supportedInterfaceOrientations` methods. For video playing I use `MPMoviePlayerViewController`. How to rotate only this player view? I can only rotate whole app, but don't want to do this. I present `MPMoviePlayerViewController` but it doesn't rotate as in iOS 5 and earlier. In `plist` setting I've set only 1 Portrait interface orientation. If I set other - whole app will be rotated.
2012/09/21
[ "https://Stackoverflow.com/questions/12526054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902424/" ]
Ough! A half of a day spent, and the problem solved! He he. As the documentation above says, this is really it! The core points are: > > More **responsibility is moving to the app and the app delegate**. > Now, iOS containers (such as UINavigationController) do not consult > their children to determine whether they should autorotate. By > default, an app and a view controller’s supported interface > orientations are set to UIInterfaceOrientationMaskAll for the iPad > idiom and UIInterfaceOrientationMaskAllButUpsideDown for the iPhone > idiom. > > > So, any time something with root controller changes, the system asks app delegate "So, what are we? Rotating or not?" If "rotating": > > the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method > > > then system asks our app delegate for ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return ...; } ``` That's really pretty simple. How to determine when should we allow Portrait or Landscape etc - is up to you. Testing for root controller didn't work for me because of some points, but this works: ``` - (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return self.fullScreenVideoIsPlaying ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait; } ``` The property "fullScreenVideoIsPlaying" is set up by me manually whenever I need that. The only other important thing to be careful is the enum. As it says in docs ... (read carefully above iPad/iPhone thing). So, you can play with those as you need. Another tiny thing was some buggy behaviour after closing the player controller. There was one time when it did not change the orientation, but that happened once and in some strange way, and only in simulator (iOS 6 only, of course). So I even could not react, as it happened unexpectedly and after clicking fast on some other elements of my app, it rotated to normal orientation. So, not sure - might be some delay in simulator work or something (or, really a bug :) ). Good luck!
Try this, If TabBarController is RootViewController for window, Then Create Custom Class which inherits TabBarController say CustomTabBarController.h Add Below method in CustomTabBarController.h ``` -(NSUInteger)supportedInterfaceOrientations // Must return Orientation Mask ``` Finally Call Below in AppDelegate.m ``` - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if( [self.window.rootViewController supportedInterfaceOrientations]!=0) { return [self.window.rootViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; } ```
70,507,192
I've a problem with ajax success redirect.This is the code. '/sendmsg' is the API url. on success I need the ajax function to redirect to a page say "sample.html" ``` const token = 'token'; const chatId = 'id'; $(document).ready(function () { $("#add_button").on('click', function (event) { execute(); }); function execute() { const fname = document.querySelector('#fname').value; const country = document.querySelector('#country').value; const message = `Fullname: ${fname}\nCountry: ${country}`; $.ajax({ type: 'POST', url: `https://api.telegram.org/bot${token}/sendMessage`, data: { chat_id: chatId, text: message, parse_mode: 'html', }, success: function (res) { var url=base_url+"sample.html"; $(location).attr('href',url); }, error: function (error) { console.error(error); alert("error failed"); } }); } }); ```
2021/12/28
[ "https://Stackoverflow.com/questions/70507192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17780935/" ]
With below changes, now I am able to return the user to the post after login. Login URL at each post remained same as below with `redirect_to`: ``` http://www......com/login/?redirect_to=http://www......com/post-name ``` In my custom login page template `login` I am capturing the `redirect_to` value as a variable: ``` $redirect_back_to = $_GET['redirect_to']; ``` And then in the same custom login page I have this hidden input field that take the `redirect_to` as input value: ``` <input type="hidden" value="<?php echo $redirect_back_to; ?>" name="redirect_to_post_url"> ``` In the below function I am capturing the post referrer URL from the above input and checks if there is a referrer (`redirect_to`) it will redirect to the post else to `wp-admin`: ``` function redirect_to_posts_after_login($redirect_to) { $redirect_to_post = filter_input(INPUT_POST, 'redirect_to_post_url'); if (!$redirect_to_post === "") { wp_redirect(esc_url($redirect_to_post)); } else { return $redirect_to; } } add_filter('login_redirect', 'redirect_to_posts_after_login', 10, 1); ```
Since you are trying to redirect the user, to your desired custom URL after login. Then you should insert your custom URL here:- ``` if ( isset( $user->roles ) && is_array( $user->roles ) ) { //check for admins if ( in_array( 'administrator', $user->roles ) ) { // redirect them to the default place return $redirect_to; } else { //you shud concatinate your custom url here return home_url(); } } else { return $redirect_to; } ``` $redirect\_to variable contains the URL to the wp-admin. But as a user apart from admin. You can insert the custom URL beside the home\_url() function.(Concatinate your custom url in the form hard coded string)
70,507,192
I've a problem with ajax success redirect.This is the code. '/sendmsg' is the API url. on success I need the ajax function to redirect to a page say "sample.html" ``` const token = 'token'; const chatId = 'id'; $(document).ready(function () { $("#add_button").on('click', function (event) { execute(); }); function execute() { const fname = document.querySelector('#fname').value; const country = document.querySelector('#country').value; const message = `Fullname: ${fname}\nCountry: ${country}`; $.ajax({ type: 'POST', url: `https://api.telegram.org/bot${token}/sendMessage`, data: { chat_id: chatId, text: message, parse_mode: 'html', }, success: function (res) { var url=base_url+"sample.html"; $(location).attr('href',url); }, error: function (error) { console.error(error); alert("error failed"); } }); } }); ```
2021/12/28
[ "https://Stackoverflow.com/questions/70507192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17780935/" ]
`!$redirect_to_post === ""` will always return false ! can you try with this code? ``` function redirect_to_posts_after_login($redirect_to, $requested_redirect_to) { $redirect_to_post = $_GET['redirect_to']; if ($redirect_to_post !== "") { return $redirect_to_post; } else { return $requested_redirect_to; } } add_filter('login_redirect', 'redirect_to_posts_after_login', 10, 3); ```
Since you are trying to redirect the user, to your desired custom URL after login. Then you should insert your custom URL here:- ``` if ( isset( $user->roles ) && is_array( $user->roles ) ) { //check for admins if ( in_array( 'administrator', $user->roles ) ) { // redirect them to the default place return $redirect_to; } else { //you shud concatinate your custom url here return home_url(); } } else { return $redirect_to; } ``` $redirect\_to variable contains the URL to the wp-admin. But as a user apart from admin. You can insert the custom URL beside the home\_url() function.(Concatinate your custom url in the form hard coded string)
53,718,725
I have a Lighsail LAMP stack. I’ve uploaded my PHP file which is a simple contact us page. I’ve created a database in phpmyadmin. I’d like to know: What will be the database username? What will be the database password? Looking forward for your support.
2018/12/11
[ "https://Stackoverflow.com/questions/53718725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9883913/" ]
Try to add async to beforeEach: ``` beforeEach(async(() => { // <-- use async TestBed.configureTestingModule({ declarations: [AppComponent], }); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); })); ```
You can try following things. ``` it('TEST', async(() => { fixture.whenStable().then(() => { fixture.detectChanges(); // you can write this const nextBtn = fixture.debugElement.nativeElement.querySelector('#create-btn'); expect(nextBtn.getAttribute('ng-reflect-disabled')).toBe('true'); }); })); ```
53,718,725
I have a Lighsail LAMP stack. I’ve uploaded my PHP file which is a simple contact us page. I’ve created a database in phpmyadmin. I’d like to know: What will be the database username? What will be the database password? Looking forward for your support.
2018/12/11
[ "https://Stackoverflow.com/questions/53718725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9883913/" ]
for angular 11 you can wrap beforeEach's callback into [waitForAsync](https://angular.io/api/core/testing/waitForAsync) if you want to test somesing like `async ngOnInit` ``` beforeEach( waitForAsync(() => { fixture = TestBed.createComponent(SomeFeatureComponent); component = fixture.componentInstance; fixture.detectChanges(); }) ); ```
You can try following things. ``` it('TEST', async(() => { fixture.whenStable().then(() => { fixture.detectChanges(); // you can write this const nextBtn = fixture.debugElement.nativeElement.querySelector('#create-btn'); expect(nextBtn.getAttribute('ng-reflect-disabled')).toBe('true'); }); })); ```
53,718,725
I have a Lighsail LAMP stack. I’ve uploaded my PHP file which is a simple contact us page. I’ve created a database in phpmyadmin. I’d like to know: What will be the database username? What will be the database password? Looking forward for your support.
2018/12/11
[ "https://Stackoverflow.com/questions/53718725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9883913/" ]
Try to add async to beforeEach: ``` beforeEach(async(() => { // <-- use async TestBed.configureTestingModule({ declarations: [AppComponent], }); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); })); ```
for angular 11 you can wrap beforeEach's callback into [waitForAsync](https://angular.io/api/core/testing/waitForAsync) if you want to test somesing like `async ngOnInit` ``` beforeEach( waitForAsync(() => { fixture = TestBed.createComponent(SomeFeatureComponent); component = fixture.componentInstance; fixture.detectChanges(); }) ); ```
2,020,839
> > Show that $f$ is in $\mathscr R[0,1]$ (Riemann integrable) and find$\int\_{0}^{2} f$ > > > $f(x)=$ \begin{cases} 1 & 0 \leq x<1 \\ 3 & x=1 \\ -1 & 1<x \leq2 \end{cases} Here I let $P\_n = \{0,1- \frac{1}{n}, 1+ \frac{1}{n}, 2\}$ (the Partition in [0,2].) Im haveing trouble fiding $U(P,f)$ and $L(P,f)$. would $U(P,f)= \sum 3 \Delta x\_i$ But then Im having trouble with what $\Delta x\_i$ is. is it $\frac{2}{n}$
2016/11/19
[ "https://math.stackexchange.com/questions/2020839", "https://math.stackexchange.com", "https://math.stackexchange.com/users/366048/" ]
A function $f$ is Riemann-Integrable $\iff$ the set of points of discontinuity of $f$ has measure zero. Points of discontinuity of $f=\{1\}$ which being finite has measure zero. **Alter:** Consider the partition $P=\{0< \frac{1}{n}< \frac{2}{n}\dots<\frac{n-2}{n}<\frac{n-1}{n}< 1+\frac{1}{n},< 1+\frac{2}{n}\dots <2 \}$ where $||P||\to 0 \text{as}n\to \infty$ We only consider the subintervals $[\frac{n-1}{n},1]\text{and}[1,1+\frac{1}{n}]$ since $U(P,f)\text{and}L(P,f)$ remain same in other sub-intervals. $U(P,f)=3\times \frac{1}{n}+3\times \frac{1}{n}=\frac{6}{n}$ since $f(1)=3$ And $L(P,f)=\frac{1}{n}\times 1+\frac{1}{n}\times (-1)=0\text{since} f(1-\frac{1}{n})=1\text{and}f(1+\frac{1}{n})=-1$ and Hence $U(P,f)-L(P,f)=\frac{6}{n}\to 0$ as $n\to \infty$ Since $U(P,f)-L(P,f)\to 0$ forall partitions $P\text {with} ||P||\to 0$ so $f$ is $\mathscr R-\text{integrable}$
Recall the definition of a lower and upper sum: $$ L(P,f) = \sum\_{i=0}^{n-1} (x\_{i+1}-x\_i) \displaystyle\inf\_{[x\_{i},x\_{i+1}]} f(x) $$ $$ U(P,f) = \sum\_{i=0}^{n-1} (x\_{i+1}-x\_i) \displaystyle\sup\_{[x\_{i},x\_{i+1}]} f(x) $$ So that $\Delta x\_i$ probably means $x\_{i+1}-x\_{i}$. Your partition is $\{0,1- \frac 1n,1+\frac 1n,2\}$. In these intervals, the infimums are $1,-1,-1$ respectively (draw the intervals,and check the values). The supremums are $1,3,-1$. Meanwhile, the $\Delta x\_i$ are $1 - \frac 1n, \frac 2n,1-\frac 1n$ respectively (just do $x\_{i+1}-x\_i$ and check for yourself). So the upper and lower sums are: $$ L(P,f) = 1(1 - \frac 1n) + (-1)(\frac 2n) + (-1)(1-\frac 1n) = \frac {-2}n $$ $$ U(P,f) = 1(1-\frac 1n) + 3(\frac 2n) + (-1)(1-\frac 1n) = \frac 6n $$
13,119,102
If I try to delete a char I get an access violation error. Heres my code: ``` int main() { char *myString = new char[32]; myString = "Hello"; cout << myString; cin.get(); delete [] myString; return 0; } ``` Ive also tried ``` delete myString ``` but im still get access violation errors
2012/10/29
[ "https://Stackoverflow.com/questions/13119102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352609/" ]
After the line ``` myString = "Hello"; ``` the pointer `myString` no longer points to the array you've allocated, but to a string literal. The line ``` delete [] myString; ``` then attempts to delete the literal (which results in a crash). You can copy a string with `strcpy`, or better yet, use `std::string`. ``` std::string myString = "Hello"; cout << myString; ```
You trying to delete memeory where "Hello" is allocated. You need to use strcpy to copy content instead of pointers.
13,119,102
If I try to delete a char I get an access violation error. Heres my code: ``` int main() { char *myString = new char[32]; myString = "Hello"; cout << myString; cin.get(); delete [] myString; return 0; } ``` Ive also tried ``` delete myString ``` but im still get access violation errors
2012/10/29
[ "https://Stackoverflow.com/questions/13119102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352609/" ]
After the line ``` myString = "Hello"; ``` the pointer `myString` no longer points to the array you've allocated, but to a string literal. The line ``` delete [] myString; ``` then attempts to delete the literal (which results in a crash). You can copy a string with `strcpy`, or better yet, use `std::string`. ``` std::string myString = "Hello"; cout << myString; ```
``` char *myString = new char[32]; myString = "Hello"; ``` This re-assigns the `myString` variable to something else (specifically, to the constant "Hello" string). Don't do that. If you really need a char pointer, use ``` strcpy(myString, "Hello"); ``` or even better ``` char *myString = strdup("Hello"); ``` and then free the allocated memory using ``` free(myString); ``` instead of ``` delete [] myString; ``` which would be an error. but **do not do that.** Use `std::string` instead.
13,119,102
If I try to delete a char I get an access violation error. Heres my code: ``` int main() { char *myString = new char[32]; myString = "Hello"; cout << myString; cin.get(); delete [] myString; return 0; } ``` Ive also tried ``` delete myString ``` but im still get access violation errors
2012/10/29
[ "https://Stackoverflow.com/questions/13119102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352609/" ]
After the line ``` myString = "Hello"; ``` the pointer `myString` no longer points to the array you've allocated, but to a string literal. The line ``` delete [] myString; ``` then attempts to delete the literal (which results in a crash). You can copy a string with `strcpy`, or better yet, use `std::string`. ``` std::string myString = "Hello"; cout << myString; ```
You get the access violation because of the following line, your pointer no longer looks at the dynamic memory you allocated and is pointing to a literal "hello" instead which you can't delete.... ``` myString = "Hello"; ``` That Line also isn't going to do what you want, you need to use (Note that you don't need to new/delete in this change) ``` char myString[32]; strcpy(myString,"Hello") ``` or better `strncpy`... look it up on Google or in a book. Or even better if you are trying to use c++ ``` std::string myString; myString = "Hello"; ```
13,119,102
If I try to delete a char I get an access violation error. Heres my code: ``` int main() { char *myString = new char[32]; myString = "Hello"; cout << myString; cin.get(); delete [] myString; return 0; } ``` Ive also tried ``` delete myString ``` but im still get access violation errors
2012/10/29
[ "https://Stackoverflow.com/questions/13119102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352609/" ]
``` char *myString = new char[32]; myString = "Hello"; ``` This re-assigns the `myString` variable to something else (specifically, to the constant "Hello" string). Don't do that. If you really need a char pointer, use ``` strcpy(myString, "Hello"); ``` or even better ``` char *myString = strdup("Hello"); ``` and then free the allocated memory using ``` free(myString); ``` instead of ``` delete [] myString; ``` which would be an error. but **do not do that.** Use `std::string` instead.
You trying to delete memeory where "Hello" is allocated. You need to use strcpy to copy content instead of pointers.
13,119,102
If I try to delete a char I get an access violation error. Heres my code: ``` int main() { char *myString = new char[32]; myString = "Hello"; cout << myString; cin.get(); delete [] myString; return 0; } ``` Ive also tried ``` delete myString ``` but im still get access violation errors
2012/10/29
[ "https://Stackoverflow.com/questions/13119102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352609/" ]
``` char *myString = new char[32]; myString = "Hello"; ``` This re-assigns the `myString` variable to something else (specifically, to the constant "Hello" string). Don't do that. If you really need a char pointer, use ``` strcpy(myString, "Hello"); ``` or even better ``` char *myString = strdup("Hello"); ``` and then free the allocated memory using ``` free(myString); ``` instead of ``` delete [] myString; ``` which would be an error. but **do not do that.** Use `std::string` instead.
You get the access violation because of the following line, your pointer no longer looks at the dynamic memory you allocated and is pointing to a literal "hello" instead which you can't delete.... ``` myString = "Hello"; ``` That Line also isn't going to do what you want, you need to use (Note that you don't need to new/delete in this change) ``` char myString[32]; strcpy(myString,"Hello") ``` or better `strncpy`... look it up on Google or in a book. Or even better if you are trying to use c++ ``` std::string myString; myString = "Hello"; ```
39,619,111
In my Edit view I have a textbox that accepts `Date`'s. Using MVC, when I go to the Edit View, the fields are already filled in with that record's information which is fine. But, I want to set an event listener on one of the fields, specifically the field that accepts dates as stated above. When i go to the page, I check the source and it looks like this for that field: ``` <div class="form-group"> <label class="control-label col-md-2" for="DateEntered">Date Entered:</label> <div style="width:26.5%" class="col-md-10"> <div id="datetimepicker" class="input-group date"> <input class="form-control text-box single-line" id="DateEnteredPhase" name="DateEntered" type="datetime" value="09/21/2016" /> <span class="field-validation-valid text-danger" data-valmsg-for="DateEntered" data-valmsg-replace="true"></span> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> ``` Notice how the value is `"09/21/2016"` which is correct at first. Here is my jQuery: ``` $(document).ready(function () { $(function () { $('#DateEnteredPhase').change(function () { var dateString = $('#DateEnteredPhase').val(); alert(dateString); }); }); }); ``` Now, I have changed the date value in that textbox to `"09/22/2016"`, and the change event is not firing. Also when I check the source **after** I change the date, the value still says `"09/21/2016"` and not `"09/22/2016"`. When I plug this into a [JSFiddle](https://jsfiddle.net/4ot8jznb/), the change event is firing appropriately. How do I fix this? Any help is appreciated. **UPDATE** Where the [DateTimePicker (by eonasdan)](https://eonasdan.github.io/bootstrap-datetimepicker/) is initialized in jQuery: ``` $(function () { $('#datetimepicker').datetimepicker({ format: 'MM/DD/YYYY' }); }); ```
2016/09/21
[ "https://Stackoverflow.com/questions/39619111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5525311/" ]
**Problem** : Is after you apply the plugin the user has to just change the date via the calendar displayed on the UI, And **the plugin will programatically change the date, This will not trigger your change event**. **Solution** : **use the plugin built in event handler to catch the change event** and then execute your code. So the below code must work. Here is the change event details from **[Plugin Documentation](http://eonasdan.github.io/bootstrap-datetimepicker/Events/#dpchange)** ``` $(function () { $('#datetimepicker').datetimepicker({ format: 'MM/DD/YYYY' }); //add change event listner that plugin supports $('#datetimepicker').on('dp.change',function(e){ alert(e.date); }) }); ```
If the source is generated dynamically - events will not bind to elements on document ready. Try this. ``` $(document).on("change", "#DateEnteredPhase", function () { var dateString = $('#DateEnteredPhase').val(); alert(dateString); }); ```
36,815,219
I put together a small script that is supposed to search through files of a certain type in a directory accumulating unique word counts > 4 characters, but it's not working as expected. 1. It doesn't eliminate the same word regardless of case. 2. I'm not sure how to tally up the totals of each word obviously. 3. Lastly, is this an efficient way to do this (if it actually worked?). Script: ``` #!/bin/bash file_list=() while IFS= read file ; do file_list=("${file_list[@]}" "$file") tr -sc 'A-Za-z' '\012' < "$file" | sort | uniq -c | egrep "\w{4,}" >> words.txt done < <(find . -maxdepth 1 -type f -name "*.c") # echo "${file_list[@]}" cat words.txt | sort -u | sort -nr echo "" > words.txt ``` example output: ``` 38 char 35 return 25 static 18 year 18 char 10 COLS 10 CHAR ``` How would I remove the duped word `char` in the example above, but getting it's count in all files?
2016/04/23
[ "https://Stackoverflow.com/questions/36815219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1125006/" ]
First, convert to all-lowercase as the first step in your pipeline. ``` tr A-Z a-z <"$file" | tr -sc a-z '\012' | ... ``` Second, do the sorting and counting at the end of the whole thing instead of inside the loop: ``` ... tr A-Z a-z <"$file" | tr -sc a-z '\012' done < <(find ...) | sort | uniq -c | egrep "\w{4,}" >words.txt ```
The following uses [Associative Arrays](http://mywiki.wooledge.org/BashGuide/Arrays#Associative_Arrays) ( Bash 4 ) to store the word as the key, and its occurrences as the value: ``` declare -A arr while read -r word; do arr[$word]=$(( ${arr[$word]} + 1 )) done < <(find . -maxdepth 1 -type f -name '*.c' -exec grep -E '\w{4,}' {} \; | tr -s '[:space:]' \\n) ``` Yes, it can perform faster, but notice: If you'll change `find`'s `\;` command termination to `+`, `grep` will yield also the file name as a part of the output ( which is the key, in our case ). We do not want this kind of behavior. Thus, if you have GNU `grep` - add the `-h` option alongside `find`'s `+` command termination. Quoted from `man grep`: > > > ``` > -h, --no-filename > Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. > > ``` > > i.e. : ``` find . -maxdepth 1 -type f -name '*.c' -exec grep -hE '\w{4,}' {} + | tr -s '[:space:]' \\n ``` --- For testing, I created the following content: ``` $ cat 1.c 2.c char return char char int char char switch return int CHAR switch COLS year static char CHAR INT int main return case long double ``` I created a script named ***sof***, which contains the relevant code above plus a `declare -p arr` to validate the associative array contents after execution: ``` $ ./sof declare -A arr='([return]="3" [static]="1" [switch]="2" [int]="1" [CHAR]="2" [char]="6" [COLS]="1" [double]="1" [main]="1" [case]="1" [long]="1" [year]="1" )' ``` It looks good, so now we can simply print it according to your requested output: ``` $ for k in "${!arr[@]}";do v="${arr[$k]}"; printf '%s %s\n' "$v" "$k";done 1 static 3 return 2 switch 1 int 6 char 2 CHAR 1 COLS 1 main 1 double 1 case 1 long 1 year ```
36,815,219
I put together a small script that is supposed to search through files of a certain type in a directory accumulating unique word counts > 4 characters, but it's not working as expected. 1. It doesn't eliminate the same word regardless of case. 2. I'm not sure how to tally up the totals of each word obviously. 3. Lastly, is this an efficient way to do this (if it actually worked?). Script: ``` #!/bin/bash file_list=() while IFS= read file ; do file_list=("${file_list[@]}" "$file") tr -sc 'A-Za-z' '\012' < "$file" | sort | uniq -c | egrep "\w{4,}" >> words.txt done < <(find . -maxdepth 1 -type f -name "*.c") # echo "${file_list[@]}" cat words.txt | sort -u | sort -nr echo "" > words.txt ``` example output: ``` 38 char 35 return 25 static 18 year 18 char 10 COLS 10 CHAR ``` How would I remove the duped word `char` in the example above, but getting it's count in all files?
2016/04/23
[ "https://Stackoverflow.com/questions/36815219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1125006/" ]
First, convert to all-lowercase as the first step in your pipeline. ``` tr A-Z a-z <"$file" | tr -sc a-z '\012' | ... ``` Second, do the sorting and counting at the end of the whole thing instead of inside the loop: ``` ... tr A-Z a-z <"$file" | tr -sc a-z '\012' done < <(find ...) | sort | uniq -c | egrep "\w{4,}" >words.txt ```
All you need is: ``` awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' *.c ``` The above uses GNU awk for multi-char RS and `\s`, it's a simple tweak with other awks: ``` awk '{for (i=1;i<=NF;i++) if (length($i)>3) cnt[tolower($i)]++} END{for (word in cnt) print cnt[word], word}' *.c ``` wrt your question asking is your current approach efficient - no, it's very inefficient and will run at least an order of magnitude slower than the script I posted above. Read [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice). If you need to do this on all files found recursively then, this might be all you need: ``` awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' $(find -type f -name '*.c' -print) ``` otherwise this will do it: ``` find -type f -name '*.c' -print0 | xargs -0 cat | awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' ```
36,815,219
I put together a small script that is supposed to search through files of a certain type in a directory accumulating unique word counts > 4 characters, but it's not working as expected. 1. It doesn't eliminate the same word regardless of case. 2. I'm not sure how to tally up the totals of each word obviously. 3. Lastly, is this an efficient way to do this (if it actually worked?). Script: ``` #!/bin/bash file_list=() while IFS= read file ; do file_list=("${file_list[@]}" "$file") tr -sc 'A-Za-z' '\012' < "$file" | sort | uniq -c | egrep "\w{4,}" >> words.txt done < <(find . -maxdepth 1 -type f -name "*.c") # echo "${file_list[@]}" cat words.txt | sort -u | sort -nr echo "" > words.txt ``` example output: ``` 38 char 35 return 25 static 18 year 18 char 10 COLS 10 CHAR ``` How would I remove the duped word `char` in the example above, but getting it's count in all files?
2016/04/23
[ "https://Stackoverflow.com/questions/36815219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1125006/" ]
All you need is: ``` awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' *.c ``` The above uses GNU awk for multi-char RS and `\s`, it's a simple tweak with other awks: ``` awk '{for (i=1;i<=NF;i++) if (length($i)>3) cnt[tolower($i)]++} END{for (word in cnt) print cnt[word], word}' *.c ``` wrt your question asking is your current approach efficient - no, it's very inefficient and will run at least an order of magnitude slower than the script I posted above. Read [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice). If you need to do this on all files found recursively then, this might be all you need: ``` awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' $(find -type f -name '*.c' -print) ``` otherwise this will do it: ``` find -type f -name '*.c' -print0 | xargs -0 cat | awk -v RS='\\s' 'length()>3{cnt[tolower($0)]++} END{for (word in cnt) print cnt[word], word}' ```
The following uses [Associative Arrays](http://mywiki.wooledge.org/BashGuide/Arrays#Associative_Arrays) ( Bash 4 ) to store the word as the key, and its occurrences as the value: ``` declare -A arr while read -r word; do arr[$word]=$(( ${arr[$word]} + 1 )) done < <(find . -maxdepth 1 -type f -name '*.c' -exec grep -E '\w{4,}' {} \; | tr -s '[:space:]' \\n) ``` Yes, it can perform faster, but notice: If you'll change `find`'s `\;` command termination to `+`, `grep` will yield also the file name as a part of the output ( which is the key, in our case ). We do not want this kind of behavior. Thus, if you have GNU `grep` - add the `-h` option alongside `find`'s `+` command termination. Quoted from `man grep`: > > > ``` > -h, --no-filename > Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. > > ``` > > i.e. : ``` find . -maxdepth 1 -type f -name '*.c' -exec grep -hE '\w{4,}' {} + | tr -s '[:space:]' \\n ``` --- For testing, I created the following content: ``` $ cat 1.c 2.c char return char char int char char switch return int CHAR switch COLS year static char CHAR INT int main return case long double ``` I created a script named ***sof***, which contains the relevant code above plus a `declare -p arr` to validate the associative array contents after execution: ``` $ ./sof declare -A arr='([return]="3" [static]="1" [switch]="2" [int]="1" [CHAR]="2" [char]="6" [COLS]="1" [double]="1" [main]="1" [case]="1" [long]="1" [year]="1" )' ``` It looks good, so now we can simply print it according to your requested output: ``` $ for k in "${!arr[@]}";do v="${arr[$k]}"; printf '%s %s\n' "$v" "$k";done 1 static 3 return 2 switch 1 int 6 char 2 CHAR 1 COLS 1 main 1 double 1 case 1 long 1 year ```
1,414,645
Let $f,g:\mathbb{R}\rightarrow \mathbb{R}$ and $f(I)\cap g(J)\not=\phi$ for all nonempty open interval $I,J$. Consider $f\_1=\chi\_\mathbb{Q}$ and $g\_1=\chi\_\mathbb{Q^c}$, we know that $f\_1$ and $g\_1$ satisfy above condition. (some examples can be constructed from this.) Can we find other examples ? Can we find $g$ when $f$ is given ? ps. My question is motivated by this work [enter link description here](http://www.austms.org.au/Publ/Gazette/2010/Mar10/TechPaperTeodorescu.pdf)
2015/08/30
[ "https://math.stackexchange.com/questions/1414645", "https://math.stackexchange.com", "https://math.stackexchange.com/users/240011/" ]
We can find one $f$ that works for all $g.$ The idea is to construct $f:\mathbb {R}\to \mathbb {R}$ such that $f(I)=\mathbb {R}$ for every nonempty open interval $I.$ Such an $f$ then has the desired property. The construction makes use of Cantor sets. By a Cantor set I mean here a set of the form $a +bK,$ where $a \in \mathbb R , b > 0,$ and $K$ is "the" Cantor set. We don't need to use any fancy properties of the Cantor set, just that it is compact, is nowhere dense, and has cardinality of $\mathbb {R}.$ All Cantor sets then have this property. Let $I\_n$ be the open intervals with rational end points. We can inductively find Cantor sets $K\_n\subset I\_n, n=1,2,\dots ,$ that are pairwise disjoint. For each $n$ there exists a bijection $f\_n:K\_n \to \mathbb {R}.$ Define $f:\mathbb {R}\to \mathbb {R}$ by setting $f = f\_n$ on each $K\_n,$ and setting $f=0$ on the complement of $\cup K\_n.$ If $I$ is any nonempty open interval, then $I$ contains some $I\_n,$ hence some $K\_n,$ hence $f(I) \supset f(K\_n) = \mathbb {R}.$
I know of examples that are very similar to your example. I'm not sure how helpful these examples will be. Basically, two indicator functions on any dense subset of the reals will work. For example $f(x) = 1$ and $g(x)$ is the indicator function of the algebraic numbers. Also, you can do something like $h(x) = 3$ and $k(x) = 3g(x)$. When $f$ is given, you won't necessarily be able to uniquely find a corresponding $g$. In your example, your $f(x)$ is the indicator function on the rationals. $g(x) = 1$ works just as well as your other $g(x)$. Also, $g(x)=0$ is another possible pair for your $f(x)$. Thus, in the generic case, it seems that you can't uniquely determine a function from that condition. <https://math.stackexchange.com/a/978359/234911> With the above construction, you should be able to come up with examples where you have functions $f\_1,...,f\_n$ such that $f\_i(I) \cap f\_j(J) \neq \emptyset %$ for all nonempty open intervals $I$, $J$ and integers $i$, $j$, such that $1 \leq i \leq j \leq n$.
4,829,774
Javadoc is great for scanning all of source files and creating HTML pages to view it. I was wondering if there is a similar tool that would go through all of your Spring controllers and collect all of the methods that have been annotated with @RequestMapping and produce a single HTML page listing them. Sort of like a pseudo site map for developers to ensure uniqueness and standardization across controllers. I apologize if this question has been asked elsewhere already. I could not come up with an appropriate set of search terms that would provide a useful result.
2011/01/28
[ "https://Stackoverflow.com/questions/4829774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158613/" ]
This is a very good question, I often miss (and implement) functionality like this. Use a Build Tool ---------------- What I'd do is run Maven (or ant) and execute a task after compilation that * reads all classes (perhaps with a configurable list of packages) * iterates over all methods of these classes * reads the annotations * and writes the output to HTML Use Annotation Processing ------------------------- But I guess this is a scenario, where [annotation processing](http://download.oracle.com/javase/6/docs/technotes/guides/apt/index.html) might also be a way to do it. Usually, you have to use some internal APIs to get stuff done in API, but using [`Filer.createResource(...)`](http://download.oracle.com/javase/6/docs/api/javax/annotation/processing/Filer.html#createResource%28javax.tools.JavaFileManager.Location%2C%20java.lang.CharSequence%2C%20java.lang.CharSequence%2C%20javax.lang.model.element.Element...%29) it should actually possible to do it out of the box. Here's a rudimentary implementation: ``` public class RequestMappingProcessor extends AbstractProcessor{ private final Map<String, String> map = new TreeMap<String, String>(); private Filer filer; @Override public Set<String> getSupportedAnnotationTypes(){ return Collections.singleton(RequestMapping.class.getName()); } @Override public synchronized void init( final ProcessingEnvironment processingEnv){ super.init(processingEnv); filer = processingEnv.getFiler(); } @Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv){ for(final TypeElement annotatedElement : annotations){ final RequestMapping mapping = annotatedElement.getAnnotation( RequestMapping.class ); if(mapping != null){ addMapping(mapping, annotatedElement, roundEnv); } } assembleSiteMap(); return false; } private void assembleSiteMap(){ Writer writer = null; boolean threw = false; try{ final FileObject fileObject = filer.createResource( StandardLocation.CLASS_OUTPUT, "html", "siteMap.html" ); writer = fileObject.openWriter(); writer.append("<body>\n"); for(final Entry<String, String> entry : map.entrySet()){ writer .append("<a href=\"") .append(entry.getKey()) .append("\">") .append("Path: ") .append(entry.getKey()) .append(", method: ") .append(entry.getValue()) .append("</a>\n"); } writer.append("</body>\n"); } catch(final IOException e){ threw = true; throw new IllegalStateException(e); } finally{ // with commons/io: IOUtils.closeQuietly(writer) // with Guava: Closeables.close(writer, rethrow) // with plain Java this monstrosity: try{ if(writer != null){ writer.close(); } } catch(final IOException e){ if(!threw){ throw new IllegalStateException(e); } } finally{ } } } private void addMapping(final RequestMapping mapping, final TypeElement annotatedElement, final RoundEnvironment roundEnv){ final String[] values = mapping.value(); for(final String value : values){ map.put( value, annotatedElement.getQualifiedName().toString() ); } } } ```
There's nothing that I know of that would do that. I've retrieved controllers and mappings via the app context before to create navigation, but it was a lot of work for little gain IMO: ``` @Component public class SiteMap implements ApplicationContextAware, InitializingBean { private ApplicationContext context; private List<Page> pages = new ArrayList<Page>(); public List<Page> getPages() { return pages; } public void setApplicationContext(ApplicationContext applicationContext) { this.context = applicationContext; } public void afterPropertiesSet() throws Exception { Assert.notNull(context, "applicationContext not set"); Map<String, Object> controllers = ctx.getBeansWithAnnotation(Controller.class); for(Map.Entry<String, Object> entry : controllers.entrySet()) { Page page = new Page(); Class<?> controllerClass = entry.getValue(); String controllerRoot = null; RequestMapping classMapping = controllerClass.getAnnotation(RequestMapping.class); if(classMapping != null) controllerRoot = classMapping.value(); if(controllerRoot = null) controllerRoot = // get and parse controller name page.setPath(controllerRoot); for(Method m : controllerClass.getDeclaredMethods()) { RequestMapping rm = m.getAnnotation(RequestMapping.class); if(rm == null) continue; Page child = new Page(); child.setPath(rm.value()); page.getChildren().add(child); } pages.add(page); } } public static class Page { private String path; private List<Page> children = new ArrayList<Page>(); // other junk } } ``` Then access `${pages}` in your site map page JSP. Might need to play with that code some if you do something similar, I freehanded it in this editor.
71,477,143
I'm using Visual Studio 2019, and tried this in two different computers. Can someone explain what is going on?
2022/03/15
[ "https://Stackoverflow.com/questions/71477143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8933996/" ]
The distance for the center is proportional to the scaling (in each axis). We may compute `newx` and `newy` as follows: * Subtract `x_original_center` and `y_original_center` from `oldx` and `oldy`. After subtraction, (0, 0) is the "new center" (applies "centered coordinate system"). * Scale the "zero centered" coordinates by `scale_x` and `scale_y`. * Convert the "scaled zero centered" coordinates to "top left (0, 0)" by adding `x_scaled_center` and `y_scaled_center`. --- Illustration: ```none Origin: (0,0) New coordinate system: (0,0) center ----------------- ----------------- | | x -= (cols-1)/2 | (0,0) | | | ===============> | + | | | y -= (rows-1)/2 | | ----------------- ----------------- After scaling: The distance to the center is proportional to the scale. In x axis the distance is proportional to x_scale In y axis the distance is proportional to y_scale ------------- | | | ^ o | | y*sy | | --------^-------- | | | | y | o | Scale | V | | +<---> | ===========> | +<--> | | x | | x*sx | ----------------- | | | | | | | | ------------- Convert the scaled result to origin (0, 0): newx += (new_cols-1)/2 newy += (new_rows-1)/2 ``` --- Computing the center accurately: The C++ conversion is: (0, 0) is the top left, and (cols-1, rows-1) is the bottom right coordinate. The accurate center coordinate is: `x_original_center = (original_rows-1.0)/2.0` `y_original_center = (original_cols-1.0)/2.0` --- C++ code sample: ``` #include <cmath> #include <iostream> #include "opencv2/opencv.hpp" #include <opencv2/highgui/highgui.hpp> int main() { double scale_x = 2.0; double scale_y = 0.5; int oldx = 385; int oldy = 400; cv::Mat org = cv::Mat::zeros(cv::Size(969, 348), CV_8UC1); //Fill with zeros (for example). cv::Mat resizeimage; //Height and width before resize: int rows = org.rows; //384 int cols = org.cols; //969 //cv::resize(org, resizeimage, Size(org.rows / 0.5, org.cols / 2.0), 0, 0, INTER_AREA); //Instead of dividing by 0.5, sacle by 2.0 (and Instead of dividing by 2.0, scale by 0.5) cv::resize(org, resizeimage, cv::Size((int)std::round(rows * scale_x), (int)std::round(cols * scale_y)), 0, 0, cv::INTER_AREA); //Height and width after resize: int resized_rows = resizeimage.rows; //485 int resized_cols = resizeimage.cols; //696 //Center before resize: double x_original_center = ((double)cols - 1.0) / 2.0; //484.0 double y_original_center = ((double)rows - 1.0) / 2.0; //173.5 //Center after resize: double x_scaled_center = ((double)resized_cols - 1.0) / 2.0; //347.5 double y_scaled_center = ((double)resized_rows - 1.0) / 2.0; //242 //Subtract the center, scale, and add the "scaled center". int newx = (int)std::round((oldx - x_original_center) * scale_x + x_scaled_center); //150 int newy = (int)std::round((oldy - y_original_center) * scale_y + y_scaled_center); //355 std::cout << "newx = " << newx << std::endl << "newy = " << newy << std::endl; return 0; } ```
I prefer map coordinates in the following way: ``` float x_ratio = resizeimage.cols / static_cast<float>(org.cols); float y_ratio = resizeimage.rows / static_cast<float>(org.rows); cv::Point newPoint(static_cast<int>(oldx * x_ratio), static_cast<int>(oldy * y_ratio)); ```
12,028,250
If I have a C++ function/method, for example: ``` getSound(Animal a){ a.printSound(); } ``` and then pass it a `Dog` object that extends the class `Animal` but overrides Animal's `printSound()` method, is there a way of using Dog's `printSound()` within `getSound()`? I have tried making `printSound()` in the `Animal` class definition virtual, but I am still getting the output of the original `printSound()`. Thanks in advance.
2012/08/19
[ "https://Stackoverflow.com/questions/12028250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610242/" ]
Making `printSound` virtual was correct. Change the signature of `getSound` to take a `Animal&` or `const Animal&`. By taking an `Animal` by value you are constructing a new `Animal` from your `Dog`, and that's just an `Animal`, not a `Dog`.
It is because of [object-slicing](http://en.wikipedia.org/wiki/Object_slicing), as you accept the argument by value. Accept it by reference as: ``` void getSound(Animal & a); //now reference ``` If `Animal::printSound()` doesn't change the state of the object, then make it `const` member function (if it isn't const already), and then accept the argument by `const` reference as: ``` void getSound(Animal const & a); //now const reference ```
12,028,250
If I have a C++ function/method, for example: ``` getSound(Animal a){ a.printSound(); } ``` and then pass it a `Dog` object that extends the class `Animal` but overrides Animal's `printSound()` method, is there a way of using Dog's `printSound()` within `getSound()`? I have tried making `printSound()` in the `Animal` class definition virtual, but I am still getting the output of the original `printSound()`. Thanks in advance.
2012/08/19
[ "https://Stackoverflow.com/questions/12028250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610242/" ]
Making `printSound` virtual was correct. Change the signature of `getSound` to take a `Animal&` or `const Animal&`. By taking an `Animal` by value you are constructing a new `Animal` from your `Dog`, and that's just an `Animal`, not a `Dog`.
When you call `getSound`, you are passing the `Animal` by value. This means that a copy of the `Dog` is made by calling the `Animal`'s copy constructor. The `Animal`'s copy constructor constructs an `Animal`, not a `Dog`. You probably want pass by reference: ``` getSound(Animal& a){ a.printSound(); } ```
12,028,250
If I have a C++ function/method, for example: ``` getSound(Animal a){ a.printSound(); } ``` and then pass it a `Dog` object that extends the class `Animal` but overrides Animal's `printSound()` method, is there a way of using Dog's `printSound()` within `getSound()`? I have tried making `printSound()` in the `Animal` class definition virtual, but I am still getting the output of the original `printSound()`. Thanks in advance.
2012/08/19
[ "https://Stackoverflow.com/questions/12028250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610242/" ]
Making `printSound` virtual was correct. Change the signature of `getSound` to take a `Animal&` or `const Animal&`. By taking an `Animal` by value you are constructing a new `Animal` from your `Dog`, and that's just an `Animal`, not a `Dog`.
You've basically done everything right, except for one thing. Either pass the Animal object by reference ``` getSound(Animal &a); ``` Or provide a pointer to the object in question. ``` getSound(Animal *a) { a->printSound(); //Mind the -> in this case. } ``` To call this function, you'd go about like this: ``` Dog D; getSound(&D); //Passes a pointer to the function. ``` Otherwise, you'll construct a new object of type 'Animal', instead of really 'passing' a Dog. Actually, you're best off with the pointer solution, otherwise you'll run into problems when passing a derived object, since it will expect an object of type `Animal` and will not settle for anything else.
60,155,678
I would like to create a simple code snippet that fetches all messages from the DLQ and re-sends them to the original destination (AKA resend/retry) It can be done easily by the ActiveMQ UI (but for a single message at a time).
2020/02/10
[ "https://Stackoverflow.com/questions/60155678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103894/" ]
There is no direct JMS API for re-sending a message from a DLQ to its original queue. In fact, the JMS API doesn't even discuss dead-letter queues. It's merely a convention used by most brokers to deal with messages that can't be consumed. You'd need to create an actual JMS consumer to receive the message from the DLQ and then create a JMS producer to send the message back to its original queue. It's important that you use `Session.TRANSACTED` mode to avoid potential message loss or duplication. If you use `Session.AUTO_ACKNOWLEDGE` and there is a problem between the time the message is consumed and sent (e.g the application crashes, hardware failure, etc.) then the message could be lost due to the fact that it was already acknowledged before it was sent successfully. If you use `Session.CLIENT_ACKNOWLEDGE` and there is a problem between the time the message is sent and acknowledged then the message could ultimately be duplicated due to the fact that it was already sent before it was acknowledged successfully. *Both* operations should be part of the JMS transaction so that the work is atomic. Lastly, I recommend you either invoke `commit()` on the transacted session for each message sent or after a small batch of messages (e.g. 10). Given that you have no idea how many messages are in the DLQ it would be unwise to process *every* message in a single transaction. Generally you want the transaction to be as small as possible in order to minimize the window during which an error might occur and the transaction's work will need to be performed again. Also, the larger the transaction is the more heap memory will be required on the broker to keep track of the work in the transaction. Keep in mind that you can invoke `commit()` on the same session as many times as you want. You don't need to create a new session for each transaction.
After Justin's reply I've manually implemented the retry mechanism like so: ```java public void retryAllDlqMessages() throws JMSException { logger.warn("retryAllDlqMessages starting"); logger.warn("Creating a connection to {}", activemqUrl); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("test", "test", activemqUrl); HashMap<String, MessageProducer> messageProducersMap = new HashMap<>(); MessageConsumer consumer = null; try (ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); ActiveMQSession session = (ActiveMQSession) connection.createSession(true, Session.SESSION_TRANSACTED)) { String dlqName = getDlqName(); logger.warn("Creating a session to {}", dlqName); ActiveMQQueue queue = (ActiveMQQueue) session.createQueue(dlqName); logger.warn("Starting JMS Connection"); connection.start(); logger.warn("Creating a DLQ consumer"); consumer = session.createConsumer(queue); logger.warn("Consumer start receiving"); Message message = consumer.receive(CONSUMER_RECEIVE_TIME_IN_MS); int retriedMessages = 0; while (message != null) { try { retryMessage(messageProducersMap, session, message); retriedMessages++; } catch (Exception e) { logger.error("Error calling retryMessage for message = {}", message); logger.error("Rolling back the JMS transaction..."); session.rollback(); return; } message = consumer.receive(CONSUMER_RECEIVE_TIME_IN_MS); } logger.warn("Consumer finished retrying {} messages", retriedMessages); logger.warn("Commiting JMS Transactions of retry"); session.commit(); } finally { if (!messageProducersMap.isEmpty()) { logger.warn("Closing {} messageProducers in messageProducersMap", messageProducersMap.size()); for (MessageProducer producer : messageProducersMap.values()) { producer.close(); } } if (consumer != null) { logger.warn("Closing DLQ Consumer"); consumer.close(); } } } private void retryMessage(HashMap<String, MessageProducer> messageProducersMap, ActiveMQSession session, Message message) { ActiveMQObjectMessage qm = (ActiveMQObjectMessage) message; String originalDestinationName = qm.getOriginalDestination().getQualifiedName(); logger.warn("Retry message with JmsID={} to original destination {}", qm.getJMSMessageID(), originalDestinationName); try { if (!messageProducersMap.containsKey(originalDestinationName)) { logger.warn("Creating a new producer for original destination: {}", originalDestinationName); messageProducersMap.put(originalDestinationName, session.createProducer(qm.getOriginalDestination())); } logger.info("Producing message to original destination"); messageProducersMap.get(originalDestinationName).send(qm); logger.info("Message sent"); } catch (Exception e) { logger.error("Message retry failed with exception", e); } } ```
60,155,678
I would like to create a simple code snippet that fetches all messages from the DLQ and re-sends them to the original destination (AKA resend/retry) It can be done easily by the ActiveMQ UI (but for a single message at a time).
2020/02/10
[ "https://Stackoverflow.com/questions/60155678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103894/" ]
Retrying all messages on the DLQ is already implemented in activemq as an mbean. You can trigger the retry method with jmxterm/jolokia e.g Replaying all messages on queue ActiveMQ.DLQ with jolokia ``` curl -XGET --user admin:admin --header "Origin: http://localhost" http://localhost:8161/api/jolokia/exec/org.apache.activemq:brokerName=localhost,destinationName=ActiveMQ.DLQ,destinationType=Queue,type=Broker/retryMessages ``` NOTE: You can only use this method on a queue that is marked as a DLQ. It will not work for regular queues. Also the DLQ queue can have its 'DLQ' flag set to false if the server is restarted. It is automatically set to true when a new message is sent to the DLQ
After Justin's reply I've manually implemented the retry mechanism like so: ```java public void retryAllDlqMessages() throws JMSException { logger.warn("retryAllDlqMessages starting"); logger.warn("Creating a connection to {}", activemqUrl); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("test", "test", activemqUrl); HashMap<String, MessageProducer> messageProducersMap = new HashMap<>(); MessageConsumer consumer = null; try (ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); ActiveMQSession session = (ActiveMQSession) connection.createSession(true, Session.SESSION_TRANSACTED)) { String dlqName = getDlqName(); logger.warn("Creating a session to {}", dlqName); ActiveMQQueue queue = (ActiveMQQueue) session.createQueue(dlqName); logger.warn("Starting JMS Connection"); connection.start(); logger.warn("Creating a DLQ consumer"); consumer = session.createConsumer(queue); logger.warn("Consumer start receiving"); Message message = consumer.receive(CONSUMER_RECEIVE_TIME_IN_MS); int retriedMessages = 0; while (message != null) { try { retryMessage(messageProducersMap, session, message); retriedMessages++; } catch (Exception e) { logger.error("Error calling retryMessage for message = {}", message); logger.error("Rolling back the JMS transaction..."); session.rollback(); return; } message = consumer.receive(CONSUMER_RECEIVE_TIME_IN_MS); } logger.warn("Consumer finished retrying {} messages", retriedMessages); logger.warn("Commiting JMS Transactions of retry"); session.commit(); } finally { if (!messageProducersMap.isEmpty()) { logger.warn("Closing {} messageProducers in messageProducersMap", messageProducersMap.size()); for (MessageProducer producer : messageProducersMap.values()) { producer.close(); } } if (consumer != null) { logger.warn("Closing DLQ Consumer"); consumer.close(); } } } private void retryMessage(HashMap<String, MessageProducer> messageProducersMap, ActiveMQSession session, Message message) { ActiveMQObjectMessage qm = (ActiveMQObjectMessage) message; String originalDestinationName = qm.getOriginalDestination().getQualifiedName(); logger.warn("Retry message with JmsID={} to original destination {}", qm.getJMSMessageID(), originalDestinationName); try { if (!messageProducersMap.containsKey(originalDestinationName)) { logger.warn("Creating a new producer for original destination: {}", originalDestinationName); messageProducersMap.put(originalDestinationName, session.createProducer(qm.getOriginalDestination())); } logger.info("Producing message to original destination"); messageProducersMap.get(originalDestinationName).send(qm); logger.info("Message sent"); } catch (Exception e) { logger.error("Message retry failed with exception", e); } } ```
40,840,624
How can I create folder on the server-pc on a button click ``` protected void BtnCreateFolder_Click(object sender, EventArgs e) { Directory.CreateDirectory("C:\\NewFolder1"); } ``` This code create folder on my local-pc, how can i create folder on server-pc with server-pc ip
2016/11/28
[ "https://Stackoverflow.com/questions/40840624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730399/" ]
As explained in [MSDN: Directory.CreateDirectory](https://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx): > > You can create a directory on a remote computer, on a share that you have write access to. UNC paths are supported; > > > Keyword here being "UNC paths", which take the following form: ``` \\server-name\share-name\[subdirectory-names\] ``` So: ``` Directory.CreateDirectory(@"\\server-name\share-name\NewFolder1"); ```
``` string directoryPath = Server.MapPath(string.Format("~/{0}/", "NewFolder1")); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); ``` this will create your newfolder1 and also check whether there is an another folder with same name.
9,672,868
Here's a demo of what I have so far: <http://www.betafreshmedia.com/nathan/coffee.html> I know there are a lot of other questions like this, however, I cannot adapt their syntax to mine as everyone's is pretty different. Here's my jQuery: ``` $(".trigger").click(function() { $(this).find('ul.coffeetype').slideToggle(); }); ``` I want a minimal, straight-forward way to continue using the same class for each div and only allow one to be opened at a time. When you click on a div that's closed, I want the open one to slide out of sight and the new one to drop down in its respective position. HTML: ``` <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> ``` It's just the same thing three times in a row right now for demo purposes.
2012/03/12
[ "https://Stackoverflow.com/questions/9672868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130589/" ]
``` $(document).ready(function() { $(".trigger").click(function() { var $el = $(this).find('ul.coffeetype'); var $opened = $('.toggledDown').not($el); $opened.toggleClass('toggledDown'); $opened.slideToggle(); $el.toggleClass('toggledDown'); $el.slideToggle(); }); }); ``` Track the ones that are open and close them before you open the active one. *EDIT* Added the ".not($el)" so you can still toggle the same menu up and down.
If my understanding is correct:- JS -- ``` $(".trigger").hover(function() { $(this).find('.coffeetype').slideToggle(); });​ ``` CSS --- ``` .coffeetype { display: none; }​ ``` Refer **[LIVE DEMO](http://jsfiddle.net/dVVwB/)**
9,672,868
Here's a demo of what I have so far: <http://www.betafreshmedia.com/nathan/coffee.html> I know there are a lot of other questions like this, however, I cannot adapt their syntax to mine as everyone's is pretty different. Here's my jQuery: ``` $(".trigger").click(function() { $(this).find('ul.coffeetype').slideToggle(); }); ``` I want a minimal, straight-forward way to continue using the same class for each div and only allow one to be opened at a time. When you click on a div that's closed, I want the open one to slide out of sight and the new one to drop down in its respective position. HTML: ``` <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> <div class="trigger"> <img src="images/coffeetype1.png" /> <ul class="coffeetype"> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> <li>International</li> <li>Regional</li> </ul> </div> ``` It's just the same thing three times in a row right now for demo purposes.
2012/03/12
[ "https://Stackoverflow.com/questions/9672868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130589/" ]
``` $(document).ready(function() { $(".trigger").click(function() { var $el = $(this).find('ul.coffeetype'); var $opened = $('.toggledDown').not($el); $opened.toggleClass('toggledDown'); $opened.slideToggle(); $el.toggleClass('toggledDown'); $el.slideToggle(); }); }); ``` Track the ones that are open and close them before you open the active one. *EDIT* Added the ".not($el)" so you can still toggle the same menu up and down.
Change your code to the following: ``` $(".trigger").click(function() { $('ul.coffeetype').slideUp(); $(this).find('ul.coffeetype').slideToggle(); });​ ``` This slides all open lists closed first.
47,195,118
My Jenkins version is 2.7.8, I have job like Email\_AAA Email\_BBB Email\_CCC etc i created a view and set the filter with following Regular Expression: ^Email.\*$ But nothing is returned I didn't find anything related to this in log. Any possible clues? Thanks. -Neo
2017/11/09
[ "https://Stackoverflow.com/questions/47195118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8426528/" ]
The -p according to documentation is for (Use a custom password prompt with optional escape sequences) zentyal used the /usr/bin/sudo -p sudo: just for purpose of testing ``` Readonly::Scalar our $SUDO_PATH => '/usr/bin/sudo -p sudo:'; # our declaration eases testing ``` Because if you change to ``` /usr/bin/sudo -p anything: ``` The functionality of sudo zentyal is normal. In you comments you wanted know why zentyal can run any shell system command without prompting the password, is because when you installed zentyal you have to set a user to sudo group or admin (this is similar to sudo group) Members of the admin group may gain root privileges %admin ALL=(ALL) ALL The last ALL allowed **to run any command** Case related: <https://forum.zentyal.org/index.php/topic,34663.0.html>
This answer gives you an answer to both the `sudo` and `-p sudo:` in your command. `sudo` itself is a privilege command allowing users to execute commands, if allowed in the `sudoers` file, which generally is not allowed by normal users. The sudoers file can determine exactly which commands a user is allowed to run. Typically these commands can be run by either setting up the sudoers file by either prompting for the user password each time a command is being run, or by adding the NOPASSWD option which allows a user to run sudo commands without having to retype their password. Example: a normal user cannot run dmidecode as you will get a access denied. ``` [user@host ~]$ dmidecode # dmidecode 3.0 Scanning /dev/mem for entry point. /dev/mem: Permission denied ``` but if allowed in the sudoers file, you can allow the user to run the command as a super user. ``` [user@host ~]$ sudo dmidecode ``` Here is an example of a sudoers file entry allowing user to only run some `dmidecode` and `sar` using sudo, without prompting for password. ``` user123 ALL=(ALL) NOPASSWD: /usr/sbin/dmidecode, /usr/bin/sar ``` for the `-p sudo:` part. The `-p` (prompt) option allows you to override the default password prompt and use a custom one. The following percent (‘%’) escapes are supported by the sudoers. In other words in this case it will replace the default prompt for sudo password with the `sudo:` text. So as an example, running a command like `df -h` ``` [user@phost ~]$ sudo df -h [sudo] password for host: ``` but when running with `-p` ``` [user@phost ~]$ sudo -p sudo: df -h sudo: ``` **TIP!** whenever you need to edit a sudoers file, you need to ensure you never do `vi sudoers` as it will change file ownership. Always edit a sudoers file by running the `visudo` command as `root`.
8,469,732
I'd like to know this for the first boot and for subsequent boots. I'm compiling my own kernel and want it to be as lean as possible. I want to build the .config file by hand (mainly as a learning experience), so I need to know everything that can be excluded. I know a possible solution is to look at my current distros list of loaded drivers. However, I'm curious about how my distro discovered what drivers to load initially. TIA.
2011/12/12
[ "https://Stackoverflow.com/questions/8469732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/977656/" ]
> > How does the Linux kernel know which drivers to load at boot? > > > The kernel generates events for devices on e.g. the PCI bus when they are plugged (either hot or cold; events are queued until userspace runs AFAIR). udev will receive these events and do modprobe calls which include the PID/VID (product/vendor IDs) of the device(s); this is usually a string with some \* in it. modprobe will then calculate the intersection of the set expressed by udev's load request wildcard and the set of aliases of kernel modules (themselves being possibly wildcards). Since USB/Firewire/etc. controllers are usually attached to the PCI bus, that's how your HCI driver gets loaded. That is how things recurse down; loading is then done with USB/Firewire PID/VIDs of course. Network protocol modules (e.g. ipv6) are however not dealt with through udev; instead, when a program calls `socket(AF_INET6, ...)` the kernel directly calls modprobe (more precisely: whatever is in `/proc/sys/kernel/modprobe`) with a non-wildcarded alias, `net-pf-10` in case of IPv6, because `AF_INET6` happens to have value 10. modprobe then loads `ipv6.ko`, because that is what has the `net-pf-10` alias. Similarly for filesystems, attempting to `mount -t foo` will cause the kernel to also call modprobe (again, via `____call_usermodehelper`), this time with `foo` as argument. Accessing device nodes (e.g. `/dev/loop0`, provided it already exists) has the same strategy if `loop.ko` is not already loaded. The kernel here requests `block-major-7-0` (because loop0 usually has (7,0), cf. `ls -l`), and `loop.ko` has the fitting `block-major-7-*` alias.
Greg Kroah give an excellent example on how to find exactly which drivers you need for you kernel. Kindly Greg gives his book away for free online <http://files.kroah.com/lkn/> A quote from Greg's books ``` I'm especially proud of the chapter on how to figure out how to configure a custom kernel based on the hardware running on your machine. This is an essential task for anyone wanting to wring out the best possible speed and control of your hardware. ```
6,658,128
I am learning Objective-C and have completed a simple program and got an unexpected result. This program is just a multiplication table test... User inputs the number of iterations(test questions), then inputs answers. That after program displays the number of right and wrong answers, percentage and accepted/failed result. ``` #import <Foundation/Foundation.h> ``` int main (int argc, const char \* argv[]) { ``` NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Welcome to multiplication table test"); int rightAnswers; //the sum of the right answers int wrongAnswers; //the sum of wrong answers int combinations; //the number of combinations@ NSLog(@"Please, input the number of test combinations"); scanf("%d",&combinations); for(int i=0; i<combinations; ++i) { int firstInt=rand()%8+1; int secondInt=rand()%8+1; int result=firstInt*secondInt; int answer; NSLog(@"%d*%d=",firstInt,secondInt); scanf("%d",&answer); if(answer==result) { NSLog(@"Ok"); rightAnswers++; } else { NSLog(@"Error"); wrongAnswers++; } } int percent=(100/combinations)*rightAnswers; NSLog(@"Combinations passed: %d",combinations); NSLog(@"Answered right: %d times",rightAnswers); NSLog(@"Answered wrong: %d times",wrongAnswers); NSLog(@"Completed %d percent",percent); if(percent>=70)NSLog(@"accepted"); else NSLog(@"failed"); [pool drain]; return 0; ``` } Problem (strange result) When I input 3 iterations and answer 'em right, i am not getting of 100% right. Getting only 99%. The same count I tried on my iPhone calculator. 100 / 3 = 33.3333333... percentage for one right answer (program displays 33%. The digits after mantissa getting cut off) 33.3333333... \* 3=100% Can someone explain me where I went wrong? Thanx.
2011/07/12
[ "https://Stackoverflow.com/questions/6658128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715999/" ]
You might want to implement some sort of rounding because 33.333....\*3 = 99.99999%. 3/10 is an infinite decimal therefore you need some sort of rounding to occur (maybe at the 3rd decimal place) so that the answer comes out correct. I would say `if (num*1000 % 10 >= 5) num += .01` or something along those lines multiply by 100 moves decimal 3 times and then mod returns the 3rd digit (could be zero). You also might only want to round at the end once you sum everything up to avoid errors. EDIT: Didn't realize you were using integers numbers at the end threw me off, you might want to use double or float (floats are slightly inaccurate past 2 or 3 digits which is OK with what you want).
100/3 is 33. Integer mathematics here.
6,658,128
I am learning Objective-C and have completed a simple program and got an unexpected result. This program is just a multiplication table test... User inputs the number of iterations(test questions), then inputs answers. That after program displays the number of right and wrong answers, percentage and accepted/failed result. ``` #import <Foundation/Foundation.h> ``` int main (int argc, const char \* argv[]) { ``` NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Welcome to multiplication table test"); int rightAnswers; //the sum of the right answers int wrongAnswers; //the sum of wrong answers int combinations; //the number of combinations@ NSLog(@"Please, input the number of test combinations"); scanf("%d",&combinations); for(int i=0; i<combinations; ++i) { int firstInt=rand()%8+1; int secondInt=rand()%8+1; int result=firstInt*secondInt; int answer; NSLog(@"%d*%d=",firstInt,secondInt); scanf("%d",&answer); if(answer==result) { NSLog(@"Ok"); rightAnswers++; } else { NSLog(@"Error"); wrongAnswers++; } } int percent=(100/combinations)*rightAnswers; NSLog(@"Combinations passed: %d",combinations); NSLog(@"Answered right: %d times",rightAnswers); NSLog(@"Answered wrong: %d times",wrongAnswers); NSLog(@"Completed %d percent",percent); if(percent>=70)NSLog(@"accepted"); else NSLog(@"failed"); [pool drain]; return 0; ``` } Problem (strange result) When I input 3 iterations and answer 'em right, i am not getting of 100% right. Getting only 99%. The same count I tried on my iPhone calculator. 100 / 3 = 33.3333333... percentage for one right answer (program displays 33%. The digits after mantissa getting cut off) 33.3333333... \* 3=100% Can someone explain me where I went wrong? Thanx.
2011/07/12
[ "https://Stackoverflow.com/questions/6658128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715999/" ]
This is a result of integer division. When you perform division between two integer types, the result is automatically rounded towards 0 to form an integer. So, integer division of `(100 / 3)` gives a result of 33, not 33.33.... When you multiply that by 3, you get 99. To fix this, you can force floating point division by changing `100` to `100.0`. The `.0` tells the compiler that it should use a floating point type instead of an integer, forcing floating point division. As a result, rounding will not occur after the division. However, 33.33... cannot be represented exactly by binary numbers. Because of this, you may still see incorrect results at times. Since you store the result as an integer, rounding down will still occur after the multiplication, which will make it more obvious. If you want to use an integer type, you should use the `round` function on the result: ``` int percent = round((100.0 / combinations) * rightAnswers); ``` This will cause the number to be rounded to the closest integer before converting it to an integer type. Alternately, you could use a floating point storage type and specify a certain number of decimal places to display: ``` float percent = (100.0 / combinations) * rightAnswers; NSLog(@"Completed %.1f percent",percent); // Display result with 1 decimal place ``` Finally, since floating point math will still cause rounding for numbers that can't be represented in binary, I would suggest multiplying by `rightAnswers` before dividing by `combinations`. This will increase the chances that the result is representable. For example, `100/3=33.33`... is not representable and will be rounded. If you multiply by 3 first, you get `300/3=100`, which is representable and will not be rounded.
You might want to implement some sort of rounding because 33.333....\*3 = 99.99999%. 3/10 is an infinite decimal therefore you need some sort of rounding to occur (maybe at the 3rd decimal place) so that the answer comes out correct. I would say `if (num*1000 % 10 >= 5) num += .01` or something along those lines multiply by 100 moves decimal 3 times and then mod returns the 3rd digit (could be zero). You also might only want to round at the end once you sum everything up to avoid errors. EDIT: Didn't realize you were using integers numbers at the end threw me off, you might want to use double or float (floats are slightly inaccurate past 2 or 3 digits which is OK with what you want).
6,658,128
I am learning Objective-C and have completed a simple program and got an unexpected result. This program is just a multiplication table test... User inputs the number of iterations(test questions), then inputs answers. That after program displays the number of right and wrong answers, percentage and accepted/failed result. ``` #import <Foundation/Foundation.h> ``` int main (int argc, const char \* argv[]) { ``` NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Welcome to multiplication table test"); int rightAnswers; //the sum of the right answers int wrongAnswers; //the sum of wrong answers int combinations; //the number of combinations@ NSLog(@"Please, input the number of test combinations"); scanf("%d",&combinations); for(int i=0; i<combinations; ++i) { int firstInt=rand()%8+1; int secondInt=rand()%8+1; int result=firstInt*secondInt; int answer; NSLog(@"%d*%d=",firstInt,secondInt); scanf("%d",&answer); if(answer==result) { NSLog(@"Ok"); rightAnswers++; } else { NSLog(@"Error"); wrongAnswers++; } } int percent=(100/combinations)*rightAnswers; NSLog(@"Combinations passed: %d",combinations); NSLog(@"Answered right: %d times",rightAnswers); NSLog(@"Answered wrong: %d times",wrongAnswers); NSLog(@"Completed %d percent",percent); if(percent>=70)NSLog(@"accepted"); else NSLog(@"failed"); [pool drain]; return 0; ``` } Problem (strange result) When I input 3 iterations and answer 'em right, i am not getting of 100% right. Getting only 99%. The same count I tried on my iPhone calculator. 100 / 3 = 33.3333333... percentage for one right answer (program displays 33%. The digits after mantissa getting cut off) 33.3333333... \* 3=100% Can someone explain me where I went wrong? Thanx.
2011/07/12
[ "https://Stackoverflow.com/questions/6658128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715999/" ]
Ints are integers. They can't represent an arbitrary real number like 1/3. Even floating-point numbers, which can represent reals, won't have enough precision to represent an infinitely repeating decimal like 100/3. You'll either need to use an arbitrary-precision library, use a library that includes rationals as a data type, or just store as much precision as you need and round from there (e.g. make your integer unit hundredths-of-a-percent instead of a single percentage point).
100/3 is 33. Integer mathematics here.
6,658,128
I am learning Objective-C and have completed a simple program and got an unexpected result. This program is just a multiplication table test... User inputs the number of iterations(test questions), then inputs answers. That after program displays the number of right and wrong answers, percentage and accepted/failed result. ``` #import <Foundation/Foundation.h> ``` int main (int argc, const char \* argv[]) { ``` NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Welcome to multiplication table test"); int rightAnswers; //the sum of the right answers int wrongAnswers; //the sum of wrong answers int combinations; //the number of combinations@ NSLog(@"Please, input the number of test combinations"); scanf("%d",&combinations); for(int i=0; i<combinations; ++i) { int firstInt=rand()%8+1; int secondInt=rand()%8+1; int result=firstInt*secondInt; int answer; NSLog(@"%d*%d=",firstInt,secondInt); scanf("%d",&answer); if(answer==result) { NSLog(@"Ok"); rightAnswers++; } else { NSLog(@"Error"); wrongAnswers++; } } int percent=(100/combinations)*rightAnswers; NSLog(@"Combinations passed: %d",combinations); NSLog(@"Answered right: %d times",rightAnswers); NSLog(@"Answered wrong: %d times",wrongAnswers); NSLog(@"Completed %d percent",percent); if(percent>=70)NSLog(@"accepted"); else NSLog(@"failed"); [pool drain]; return 0; ``` } Problem (strange result) When I input 3 iterations and answer 'em right, i am not getting of 100% right. Getting only 99%. The same count I tried on my iPhone calculator. 100 / 3 = 33.3333333... percentage for one right answer (program displays 33%. The digits after mantissa getting cut off) 33.3333333... \* 3=100% Can someone explain me where I went wrong? Thanx.
2011/07/12
[ "https://Stackoverflow.com/questions/6658128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715999/" ]
This is a result of integer division. When you perform division between two integer types, the result is automatically rounded towards 0 to form an integer. So, integer division of `(100 / 3)` gives a result of 33, not 33.33.... When you multiply that by 3, you get 99. To fix this, you can force floating point division by changing `100` to `100.0`. The `.0` tells the compiler that it should use a floating point type instead of an integer, forcing floating point division. As a result, rounding will not occur after the division. However, 33.33... cannot be represented exactly by binary numbers. Because of this, you may still see incorrect results at times. Since you store the result as an integer, rounding down will still occur after the multiplication, which will make it more obvious. If you want to use an integer type, you should use the `round` function on the result: ``` int percent = round((100.0 / combinations) * rightAnswers); ``` This will cause the number to be rounded to the closest integer before converting it to an integer type. Alternately, you could use a floating point storage type and specify a certain number of decimal places to display: ``` float percent = (100.0 / combinations) * rightAnswers; NSLog(@"Completed %.1f percent",percent); // Display result with 1 decimal place ``` Finally, since floating point math will still cause rounding for numbers that can't be represented in binary, I would suggest multiplying by `rightAnswers` before dividing by `combinations`. This will increase the chances that the result is representable. For example, `100/3=33.33`... is not representable and will be rounded. If you multiply by 3 first, you get `300/3=100`, which is representable and will not be rounded.
Ints are integers. They can't represent an arbitrary real number like 1/3. Even floating-point numbers, which can represent reals, won't have enough precision to represent an infinitely repeating decimal like 100/3. You'll either need to use an arbitrary-precision library, use a library that includes rationals as a data type, or just store as much precision as you need and round from there (e.g. make your integer unit hundredths-of-a-percent instead of a single percentage point).
6,658,128
I am learning Objective-C and have completed a simple program and got an unexpected result. This program is just a multiplication table test... User inputs the number of iterations(test questions), then inputs answers. That after program displays the number of right and wrong answers, percentage and accepted/failed result. ``` #import <Foundation/Foundation.h> ``` int main (int argc, const char \* argv[]) { ``` NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Welcome to multiplication table test"); int rightAnswers; //the sum of the right answers int wrongAnswers; //the sum of wrong answers int combinations; //the number of combinations@ NSLog(@"Please, input the number of test combinations"); scanf("%d",&combinations); for(int i=0; i<combinations; ++i) { int firstInt=rand()%8+1; int secondInt=rand()%8+1; int result=firstInt*secondInt; int answer; NSLog(@"%d*%d=",firstInt,secondInt); scanf("%d",&answer); if(answer==result) { NSLog(@"Ok"); rightAnswers++; } else { NSLog(@"Error"); wrongAnswers++; } } int percent=(100/combinations)*rightAnswers; NSLog(@"Combinations passed: %d",combinations); NSLog(@"Answered right: %d times",rightAnswers); NSLog(@"Answered wrong: %d times",wrongAnswers); NSLog(@"Completed %d percent",percent); if(percent>=70)NSLog(@"accepted"); else NSLog(@"failed"); [pool drain]; return 0; ``` } Problem (strange result) When I input 3 iterations and answer 'em right, i am not getting of 100% right. Getting only 99%. The same count I tried on my iPhone calculator. 100 / 3 = 33.3333333... percentage for one right answer (program displays 33%. The digits after mantissa getting cut off) 33.3333333... \* 3=100% Can someone explain me where I went wrong? Thanx.
2011/07/12
[ "https://Stackoverflow.com/questions/6658128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715999/" ]
This is a result of integer division. When you perform division between two integer types, the result is automatically rounded towards 0 to form an integer. So, integer division of `(100 / 3)` gives a result of 33, not 33.33.... When you multiply that by 3, you get 99. To fix this, you can force floating point division by changing `100` to `100.0`. The `.0` tells the compiler that it should use a floating point type instead of an integer, forcing floating point division. As a result, rounding will not occur after the division. However, 33.33... cannot be represented exactly by binary numbers. Because of this, you may still see incorrect results at times. Since you store the result as an integer, rounding down will still occur after the multiplication, which will make it more obvious. If you want to use an integer type, you should use the `round` function on the result: ``` int percent = round((100.0 / combinations) * rightAnswers); ``` This will cause the number to be rounded to the closest integer before converting it to an integer type. Alternately, you could use a floating point storage type and specify a certain number of decimal places to display: ``` float percent = (100.0 / combinations) * rightAnswers; NSLog(@"Completed %.1f percent",percent); // Display result with 1 decimal place ``` Finally, since floating point math will still cause rounding for numbers that can't be represented in binary, I would suggest multiplying by `rightAnswers` before dividing by `combinations`. This will increase the chances that the result is representable. For example, `100/3=33.33`... is not representable and will be rounded. If you multiply by 3 first, you get `300/3=100`, which is representable and will not be rounded.
100/3 is 33. Integer mathematics here.
12,395,337
My website has a small menu in the upper right hand corner that says the user's First Name and Last Name. I put this piece into a partial view. Since this displays on every page, I obviously think to cache it so I don't have to get the user's information everytime a page loads. Should I store this in cache or session data and also where should i create my code to cache this data if its in every page?
2012/09/12
[ "https://Stackoverflow.com/questions/12395337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372519/" ]
As per scenarion, you should definitely use cache. and as you said, you already have menu as partial view ``` [OutputCache(Duration = 3600)] public ActionResult mymenu() { return PartialView(); } ```
It is preferred to store user information in session , not in cache. Cache is mostly application level and Session is per user/session. You can store per user info in the cache, providing you provide a key (either by session or cookie) . This article might be useful :- [cache-session-viewstate-c#](http://www.codeproject.com/Articles/26621/Cache-Session-and-ViewState)
12,395,337
My website has a small menu in the upper right hand corner that says the user's First Name and Last Name. I put this piece into a partial view. Since this displays on every page, I obviously think to cache it so I don't have to get the user's information everytime a page loads. Should I store this in cache or session data and also where should i create my code to cache this data if its in every page?
2012/09/12
[ "https://Stackoverflow.com/questions/12395337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372519/" ]
As per scenarion, you should definitely use cache. and as you said, you already have menu as partial view ``` [OutputCache(Duration = 3600)] public ActionResult mymenu() { return PartialView(); } ```
If you are refering to the ASP.Net Cache, information stored in it is available to any .Net page running on the machine. I would think in your case the Session would be more appropriate.
12,395,337
My website has a small menu in the upper right hand corner that says the user's First Name and Last Name. I put this piece into a partial view. Since this displays on every page, I obviously think to cache it so I don't have to get the user's information everytime a page loads. Should I store this in cache or session data and also where should i create my code to cache this data if its in every page?
2012/09/12
[ "https://Stackoverflow.com/questions/12395337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372519/" ]
As per scenarion, you should definitely use cache. and as you said, you already have menu as partial view ``` [OutputCache(Duration = 3600)] public ActionResult mymenu() { return PartialView(); } ```
I am not sure what authentication mechanism you are using but it may already be stored in: HttpContext.Current.User or System.Threading.Thread.CurrentPrincipal
12,395,337
My website has a small menu in the upper right hand corner that says the user's First Name and Last Name. I put this piece into a partial view. Since this displays on every page, I obviously think to cache it so I don't have to get the user's information everytime a page loads. Should I store this in cache or session data and also where should i create my code to cache this data if its in every page?
2012/09/12
[ "https://Stackoverflow.com/questions/12395337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372519/" ]
As per scenarion, you should definitely use cache. and as you said, you already have menu as partial view ``` [OutputCache(Duration = 3600)] public ActionResult mymenu() { return PartialView(); } ```
I prefer to create a User object which I set all the handy parameters I need across my site. This object is stored in the session or database depending on the site
388,672
What is the difference between GNOME, KDE, Xfce and LXDE desktop environments?
2013/12/10
[ "https://askubuntu.com/questions/388672", "https://askubuntu.com", "https://askubuntu.com/users/125078/" ]
* Unity is a nice 3D desktop environment designed for good performance on recent hardware. Unity is a graphical shell for the GNOME desktop environment. In 17.10 and later the Ubuntu Desktop uses GNOME as the default desktop environment instead of Unity. * KDE is an alternative lighter weight desktop environment to Ubuntu's default interface. Plasma is the default desktop interface for KDE. It includes an application launcher (start menu), the desktop and the desktop panel (often referred to simply as the task bar). * Xfce is a lightweight 2D desktop environment designed for better performance on older hardware. * LXDE is a minimalistic desktop environment, somewhat like Windows XP in look and feel. It is designed to run on legacy hardware which requires a desktop environment that has minimal system requirements. For screenshots and information about the comparative system requirements of different desktop environments refer to [How do I find out which version and derivative of Ubuntu is right for my hardware in terms of minimal system requirements?](https://askubuntu.com/questions/206407/).
these are all desktop environments, you can still launch the same applications but how you get there and what they look like is a bit different. With some desktop environments you can change the appereance a lot (like KDE) while others will hardly allow you to change anything. an other big difference is how much resources they will take from your system. If you have problems running Unity (default for Ubuntu) or KDE, XFCE or LXDE might run just fine. As far as I know there is no connection between Gnome and the Mac OS.
388,672
What is the difference between GNOME, KDE, Xfce and LXDE desktop environments?
2013/12/10
[ "https://askubuntu.com/questions/388672", "https://askubuntu.com", "https://askubuntu.com/users/125078/" ]
[Wikipedia](http://en.wikipedia.org/wiki/Comparison_of_X_Window_System_desktop_environments) has a comparison so you can look it up there. And [the arch wiki](https://wiki.archlinux.org/index.php/Desktop_Environment) has another too. Just read them through.
these are all desktop environments, you can still launch the same applications but how you get there and what they look like is a bit different. With some desktop environments you can change the appereance a lot (like KDE) while others will hardly allow you to change anything. an other big difference is how much resources they will take from your system. If you have problems running Unity (default for Ubuntu) or KDE, XFCE or LXDE might run just fine. As far as I know there is no connection between Gnome and the Mac OS.
28,861,194
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json\_encode for append it. Jquery sent two type data to php file: **1st:** page id **2nd:** post ids (a jquery array sent them to php file) If I used `print_r($_REQUEST['CID']); exit;` on php file for test what he get from jquery, Its return and display all post ids well. But if I make any reply on particular post, Its only return recent post reply. That means, if I have 3 post like: *post-1st*, *post-2nd*, *post-3rd* ; my php return only *post-3rd* activities. I want my script update any post reply when it submitted at sql. my wall.php ``` // id is dynamic <div class="case" data-post-id="111"></div> <div class="case" data-post-id="222"></div> <div class="case" data-post-id="333"></div> //Check for any update after 15 second interval by post id. <script type="text/javascript" charset="utf-8"> var CID = []; $('div[data-post-id]').each(function(i){ CID[i] = $(this).data('post-id'); }); function addrep(type, msg){ CID.forEach(function(id){ $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>"); }); } var tutid = '<?php echo $tutid; ?>'; function waitForRep(){ $.ajax({ type: "GET", url: "/server.php", cache: false, data: { tutid : tutid, CID : CID }, timeout:15000, success: function(data){ addrep("postreply", data); setTimeout( waitForRep, 15000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ setTimeout( waitForRep, 15000); } }); } $(document).ready(function(){ waitForRep(); }); </script> ``` server.php (may be problem in my array or something else) ``` while (true) { if($_REQUEST['tutid'] && $_REQUEST['CID']){ foreach($_REQUEST['CID'] as $key => $value){ date_default_timezone_set('Asia/Dhaka'); $datetime = date('Y-m-d H:i:s', strtotime('-15 second')); $res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh)); } // array close $rows = mysqli_fetch_assoc($res); $row[] = array_map('utf8_encode', $rows); $data = array(); $data['id'] = $rows['id']; $data['qazi_id'] = $rows['qazi_id']; //ect all // do something and echo $data['detail'] = $detail; if (!empty($data)) { echo json_encode($data); flush(); exit(0); } } // request close sleep(5); } // while close ```
2015/03/04
[ "https://Stackoverflow.com/questions/28861194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453049/" ]
I can think of one way without a slash: ``` double c = a * Math.pow(b, -1); ``` You can also substitute a Unicode escape for the `/` character. ``` double c2 = a \u002f b; ``` You can also convert to `BigDecimal`s, use the `divide` method, and then convert the quotient back to a `double`. ``` double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue(); ```
`System.out.println("The result is : " + (a * Math.pow(b, -1)));`
28,861,194
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json\_encode for append it. Jquery sent two type data to php file: **1st:** page id **2nd:** post ids (a jquery array sent them to php file) If I used `print_r($_REQUEST['CID']); exit;` on php file for test what he get from jquery, Its return and display all post ids well. But if I make any reply on particular post, Its only return recent post reply. That means, if I have 3 post like: *post-1st*, *post-2nd*, *post-3rd* ; my php return only *post-3rd* activities. I want my script update any post reply when it submitted at sql. my wall.php ``` // id is dynamic <div class="case" data-post-id="111"></div> <div class="case" data-post-id="222"></div> <div class="case" data-post-id="333"></div> //Check for any update after 15 second interval by post id. <script type="text/javascript" charset="utf-8"> var CID = []; $('div[data-post-id]').each(function(i){ CID[i] = $(this).data('post-id'); }); function addrep(type, msg){ CID.forEach(function(id){ $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>"); }); } var tutid = '<?php echo $tutid; ?>'; function waitForRep(){ $.ajax({ type: "GET", url: "/server.php", cache: false, data: { tutid : tutid, CID : CID }, timeout:15000, success: function(data){ addrep("postreply", data); setTimeout( waitForRep, 15000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ setTimeout( waitForRep, 15000); } }); } $(document).ready(function(){ waitForRep(); }); </script> ``` server.php (may be problem in my array or something else) ``` while (true) { if($_REQUEST['tutid'] && $_REQUEST['CID']){ foreach($_REQUEST['CID'] as $key => $value){ date_default_timezone_set('Asia/Dhaka'); $datetime = date('Y-m-d H:i:s', strtotime('-15 second')); $res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh)); } // array close $rows = mysqli_fetch_assoc($res); $row[] = array_map('utf8_encode', $rows); $data = array(); $data['id'] = $rows['id']; $data['qazi_id'] = $rows['qazi_id']; //ect all // do something and echo $data['detail'] = $detail; if (!empty($data)) { echo json_encode($data); flush(); exit(0); } } // request close sleep(5); } // while close ```
2015/03/04
[ "https://Stackoverflow.com/questions/28861194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453049/" ]
I can think of one way without a slash: ``` double c = a * Math.pow(b, -1); ``` You can also substitute a Unicode escape for the `/` character. ``` double c2 = a \u002f b; ``` You can also convert to `BigDecimal`s, use the `divide` method, and then convert the quotient back to a `double`. ``` double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue(); ```
You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b public class HelloWorld{ ``` public static void main(String []args){ System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b))); } ``` } You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself. For example if b = 0 Throw error if a<0 and b>0 ``` System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b))); ``` etc.
28,861,194
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json\_encode for append it. Jquery sent two type data to php file: **1st:** page id **2nd:** post ids (a jquery array sent them to php file) If I used `print_r($_REQUEST['CID']); exit;` on php file for test what he get from jquery, Its return and display all post ids well. But if I make any reply on particular post, Its only return recent post reply. That means, if I have 3 post like: *post-1st*, *post-2nd*, *post-3rd* ; my php return only *post-3rd* activities. I want my script update any post reply when it submitted at sql. my wall.php ``` // id is dynamic <div class="case" data-post-id="111"></div> <div class="case" data-post-id="222"></div> <div class="case" data-post-id="333"></div> //Check for any update after 15 second interval by post id. <script type="text/javascript" charset="utf-8"> var CID = []; $('div[data-post-id]').each(function(i){ CID[i] = $(this).data('post-id'); }); function addrep(type, msg){ CID.forEach(function(id){ $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>"); }); } var tutid = '<?php echo $tutid; ?>'; function waitForRep(){ $.ajax({ type: "GET", url: "/server.php", cache: false, data: { tutid : tutid, CID : CID }, timeout:15000, success: function(data){ addrep("postreply", data); setTimeout( waitForRep, 15000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ setTimeout( waitForRep, 15000); } }); } $(document).ready(function(){ waitForRep(); }); </script> ``` server.php (may be problem in my array or something else) ``` while (true) { if($_REQUEST['tutid'] && $_REQUEST['CID']){ foreach($_REQUEST['CID'] as $key => $value){ date_default_timezone_set('Asia/Dhaka'); $datetime = date('Y-m-d H:i:s', strtotime('-15 second')); $res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh)); } // array close $rows = mysqli_fetch_assoc($res); $row[] = array_map('utf8_encode', $rows); $data = array(); $data['id'] = $rows['id']; $data['qazi_id'] = $rows['qazi_id']; //ect all // do something and echo $data['detail'] = $detail; if (!empty($data)) { echo json_encode($data); flush(); exit(0); } } // request close sleep(5); } // while close ```
2015/03/04
[ "https://Stackoverflow.com/questions/28861194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453049/" ]
I can think of one way without a slash: ``` double c = a * Math.pow(b, -1); ``` You can also substitute a Unicode escape for the `/` character. ``` double c2 = a \u002f b; ``` You can also convert to `BigDecimal`s, use the `divide` method, and then convert the quotient back to a `double`. ``` double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue(); ```
``` public class Num { public static void main(String[] args) { double num, den, res; num = 10; den = 2; res = Math.pow(Math.E, (Math.log(num)-Math.log(den))); System.out.println(res); } } ```
28,861,194
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json\_encode for append it. Jquery sent two type data to php file: **1st:** page id **2nd:** post ids (a jquery array sent them to php file) If I used `print_r($_REQUEST['CID']); exit;` on php file for test what he get from jquery, Its return and display all post ids well. But if I make any reply on particular post, Its only return recent post reply. That means, if I have 3 post like: *post-1st*, *post-2nd*, *post-3rd* ; my php return only *post-3rd* activities. I want my script update any post reply when it submitted at sql. my wall.php ``` // id is dynamic <div class="case" data-post-id="111"></div> <div class="case" data-post-id="222"></div> <div class="case" data-post-id="333"></div> //Check for any update after 15 second interval by post id. <script type="text/javascript" charset="utf-8"> var CID = []; $('div[data-post-id]').each(function(i){ CID[i] = $(this).data('post-id'); }); function addrep(type, msg){ CID.forEach(function(id){ $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>"); }); } var tutid = '<?php echo $tutid; ?>'; function waitForRep(){ $.ajax({ type: "GET", url: "/server.php", cache: false, data: { tutid : tutid, CID : CID }, timeout:15000, success: function(data){ addrep("postreply", data); setTimeout( waitForRep, 15000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ setTimeout( waitForRep, 15000); } }); } $(document).ready(function(){ waitForRep(); }); </script> ``` server.php (may be problem in my array or something else) ``` while (true) { if($_REQUEST['tutid'] && $_REQUEST['CID']){ foreach($_REQUEST['CID'] as $key => $value){ date_default_timezone_set('Asia/Dhaka'); $datetime = date('Y-m-d H:i:s', strtotime('-15 second')); $res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh)); } // array close $rows = mysqli_fetch_assoc($res); $row[] = array_map('utf8_encode', $rows); $data = array(); $data['id'] = $rows['id']; $data['qazi_id'] = $rows['qazi_id']; //ect all // do something and echo $data['detail'] = $detail; if (!empty($data)) { echo json_encode($data); flush(); exit(0); } } // request close sleep(5); } // while close ```
2015/03/04
[ "https://Stackoverflow.com/questions/28861194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453049/" ]
You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b public class HelloWorld{ ``` public static void main(String []args){ System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b))); } ``` } You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself. For example if b = 0 Throw error if a<0 and b>0 ``` System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b))); ``` etc.
`System.out.println("The result is : " + (a * Math.pow(b, -1)));`
28,861,194
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json\_encode for append it. Jquery sent two type data to php file: **1st:** page id **2nd:** post ids (a jquery array sent them to php file) If I used `print_r($_REQUEST['CID']); exit;` on php file for test what he get from jquery, Its return and display all post ids well. But if I make any reply on particular post, Its only return recent post reply. That means, if I have 3 post like: *post-1st*, *post-2nd*, *post-3rd* ; my php return only *post-3rd* activities. I want my script update any post reply when it submitted at sql. my wall.php ``` // id is dynamic <div class="case" data-post-id="111"></div> <div class="case" data-post-id="222"></div> <div class="case" data-post-id="333"></div> //Check for any update after 15 second interval by post id. <script type="text/javascript" charset="utf-8"> var CID = []; $('div[data-post-id]').each(function(i){ CID[i] = $(this).data('post-id'); }); function addrep(type, msg){ CID.forEach(function(id){ $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>"); }); } var tutid = '<?php echo $tutid; ?>'; function waitForRep(){ $.ajax({ type: "GET", url: "/server.php", cache: false, data: { tutid : tutid, CID : CID }, timeout:15000, success: function(data){ addrep("postreply", data); setTimeout( waitForRep, 15000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ setTimeout( waitForRep, 15000); } }); } $(document).ready(function(){ waitForRep(); }); </script> ``` server.php (may be problem in my array or something else) ``` while (true) { if($_REQUEST['tutid'] && $_REQUEST['CID']){ foreach($_REQUEST['CID'] as $key => $value){ date_default_timezone_set('Asia/Dhaka'); $datetime = date('Y-m-d H:i:s', strtotime('-15 second')); $res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh)); } // array close $rows = mysqli_fetch_assoc($res); $row[] = array_map('utf8_encode', $rows); $data = array(); $data['id'] = $rows['id']; $data['qazi_id'] = $rows['qazi_id']; //ect all // do something and echo $data['detail'] = $detail; if (!empty($data)) { echo json_encode($data); flush(); exit(0); } } // request close sleep(5); } // while close ```
2015/03/04
[ "https://Stackoverflow.com/questions/28861194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453049/" ]
You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b public class HelloWorld{ ``` public static void main(String []args){ System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b))); } ``` } You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself. For example if b = 0 Throw error if a<0 and b>0 ``` System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b))); ``` etc.
``` public class Num { public static void main(String[] args) { double num, den, res; num = 10; den = 2; res = Math.pow(Math.E, (Math.log(num)-Math.log(den))); System.out.println(res); } } ```
55,598,155
I am quite new to Swift programming, but I am having trouble setting UILabel text in my UITableView class for individual UITableViewCell instances. I have created a custom subclass of UITableViewCell called `PizzaTableViewCell` and a custom UITableView class called `PizzaListTableViewController`. I am trying to populate the UITableView instance with data from an array, which is being populated from an API call to my node.js server. I have included my UITableView subclass, custom UITablveViewCell class, the struct for the data, and a link to a screenshot of the Simulator loading what I have done. Any help is greatly appreciated! ![](https://i.stack.imgur.com/0hu4R.png) I have verified that the data is being put in the array with no issues, as I can print the contents after the call to `fetchInventory` method. I have been able to set a single textLabel with `cell.textLabel?.text = pizzas[indexPath.row].name` along with an image in the array with: `cell.imageView?.image = pizzas[indexPath.row].image` but I have 2 more labels that I need in each cell which I cannot set. I have checked my `IBOutlets` and Storyboard identifiers, and they match the code. ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift struct Pizza { let id: String let name: String let description: String let amount: Float //let amount: String let image: UIImage init(data: [String: Any]) { //print("CHECK:: pizza.swift") self.id = data["id"] as! String self.name = data["name"] as! String // self.amount = data["amount"] as! Float self.amount = ((data["amount"] as? NSNumber)?.floatValue)! self.description = data["description"] as! String self.image = data["image"] as! UIImage } } ``` As noted above, I have been able to print the contents of the data array with beer names, pictures, descriptions and etc. I have tried to print to console `print(cell.name?.text)` after setting `cell.name?.text = pizzas[indexPath.row].name` but it prints `nil` and this is a problem. I have been stuck with this for about 2 weeks! IBOutlets screenshot: ![](https://i.imgur.com/tiUR0Tf.png)
2019/04/09
[ "https://Stackoverflow.com/questions/55598155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11314191/" ]
I think i found your Problem, let me explain What you are doing here is you have a custom `UITableViewCell` defined in the `Storyboard` in a Controller named "Root View Controller" which is not your `PizzaListTableViewController` to put it simply And as you said you have absolutely no issue regarding the `IBOutlets` Now when you say ``` tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") ``` In Your `PizzaListTableViewController` you are not linking it with the UI of the cell rather just the Code (This is only used when there is no xib of the cell) *Now what you can do to solve this* **Solution # 1** * Move/Copy your UI of the `PizzaTableViewCell` to `PizzaListTableViewController` in the storyboard from your "Root View Controller" * Make sure you add a `Reuse Identifier` in the Attribute Inspector of the cell in the storyboard * remove `tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")` this wont give you an error this time as it will automatically get register * Make sure all the `IBOutlets` are connected **Solution # 2** create a separate `Nib` (`xib`) of the cell and now you have to register the cell here like ``` tableView.register(UINib(nibName: "PizzaTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "PizzaCell") ``` Hope this helps.
Try this ``` cell.name?.text = ... cell.amount?.text = ... cell.miscellaneousText?.text = ... cell.pizzaImageView?.image = ... ``` If it still does not work then make sure your cell and your outlets are not null when setting its value. Hope it helps !
55,598,155
I am quite new to Swift programming, but I am having trouble setting UILabel text in my UITableView class for individual UITableViewCell instances. I have created a custom subclass of UITableViewCell called `PizzaTableViewCell` and a custom UITableView class called `PizzaListTableViewController`. I am trying to populate the UITableView instance with data from an array, which is being populated from an API call to my node.js server. I have included my UITableView subclass, custom UITablveViewCell class, the struct for the data, and a link to a screenshot of the Simulator loading what I have done. Any help is greatly appreciated! ![](https://i.stack.imgur.com/0hu4R.png) I have verified that the data is being put in the array with no issues, as I can print the contents after the call to `fetchInventory` method. I have been able to set a single textLabel with `cell.textLabel?.text = pizzas[indexPath.row].name` along with an image in the array with: `cell.imageView?.image = pizzas[indexPath.row].image` but I have 2 more labels that I need in each cell which I cannot set. I have checked my `IBOutlets` and Storyboard identifiers, and they match the code. ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift struct Pizza { let id: String let name: String let description: String let amount: Float //let amount: String let image: UIImage init(data: [String: Any]) { //print("CHECK:: pizza.swift") self.id = data["id"] as! String self.name = data["name"] as! String // self.amount = data["amount"] as! Float self.amount = ((data["amount"] as? NSNumber)?.floatValue)! self.description = data["description"] as! String self.image = data["image"] as! UIImage } } ``` As noted above, I have been able to print the contents of the data array with beer names, pictures, descriptions and etc. I have tried to print to console `print(cell.name?.text)` after setting `cell.name?.text = pizzas[indexPath.row].name` but it prints `nil` and this is a problem. I have been stuck with this for about 2 weeks! IBOutlets screenshot: ![](https://i.imgur.com/tiUR0Tf.png)
2019/04/09
[ "https://Stackoverflow.com/questions/55598155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11314191/" ]
I think i found your Problem, let me explain What you are doing here is you have a custom `UITableViewCell` defined in the `Storyboard` in a Controller named "Root View Controller" which is not your `PizzaListTableViewController` to put it simply And as you said you have absolutely no issue regarding the `IBOutlets` Now when you say ``` tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") ``` In Your `PizzaListTableViewController` you are not linking it with the UI of the cell rather just the Code (This is only used when there is no xib of the cell) *Now what you can do to solve this* **Solution # 1** * Move/Copy your UI of the `PizzaTableViewCell` to `PizzaListTableViewController` in the storyboard from your "Root View Controller" * Make sure you add a `Reuse Identifier` in the Attribute Inspector of the cell in the storyboard * remove `tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")` this wont give you an error this time as it will automatically get register * Make sure all the `IBOutlets` are connected **Solution # 2** create a separate `Nib` (`xib`) of the cell and now you have to register the cell here like ``` tableView.register(UINib(nibName: "PizzaTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "PizzaCell") ``` Hope this helps.
[![enter image description here](https://i.stack.imgur.com/YydJt.png)](https://i.stack.imgur.com/YydJt.png) There is something definitely strange going on with your setup. If you try to name the IBOutlets with the same name as the UITableViewCell default property it'll throw an error. The fact that you were able to set those names and build successfully is strange. From the screenshot above you can see what happens when I attempted to do this.
55,598,155
I am quite new to Swift programming, but I am having trouble setting UILabel text in my UITableView class for individual UITableViewCell instances. I have created a custom subclass of UITableViewCell called `PizzaTableViewCell` and a custom UITableView class called `PizzaListTableViewController`. I am trying to populate the UITableView instance with data from an array, which is being populated from an API call to my node.js server. I have included my UITableView subclass, custom UITablveViewCell class, the struct for the data, and a link to a screenshot of the Simulator loading what I have done. Any help is greatly appreciated! ![](https://i.stack.imgur.com/0hu4R.png) I have verified that the data is being put in the array with no issues, as I can print the contents after the call to `fetchInventory` method. I have been able to set a single textLabel with `cell.textLabel?.text = pizzas[indexPath.row].name` along with an image in the array with: `cell.imageView?.image = pizzas[indexPath.row].image` but I have 2 more labels that I need in each cell which I cannot set. I have checked my `IBOutlets` and Storyboard identifiers, and they match the code. ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift class PizzaListTableViewController: UITableViewController { var pizzas: [Pizza] = [] override func viewDidLoad() { super.viewDidLoad() //title you will see on the app screen at the top of the table view navigationItem.title = "Drink Selection" tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") //tableView.estimatedRowHeight = 134 //tableView.rowHeight = UITableViewAutomaticDimension fetchInventory { pizzas in guard pizzas != nil else { return } self.pizzas = pizzas! print(self.pizzas) //self.tableView.reloadData() //print(self.pizzas) DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } } //end of viewDidLoad private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) { Alamofire.request("http://127.0.0.1:4000/inventory", method: .get) .validate() .responseJSON { response in guard response.result.isSuccess else { return completion(nil) } guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) } let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in var data = pizzaDict! data["image"] = UIImage(named: pizzaDict!["image"] as! String) //print(data) //print("CHECK") print("Printing each item: ", Pizza(data: data)) //printing all inventory successful return Pizza(data: data) } completion(inventory) } } @IBAction func ordersButtonPressed(_ sender: Any) { performSegue(withIdentifier: "orders", sender: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //PRINTING ROWS 0 TWICE in console override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("ROWS", pizzas.count) return self.pizzas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Pizza", for: indexPath) as! PizzaTableViewCell //cell.backgroundColor = Services.baseColor //cell.pizzaImageView?.image = pizzas[indexPath.row].image //THESE WORK BUT ARE A STATIC WAY OF SETTING THE CELLS //CAN ONLY SET THE SELL WITH A SINGLE TEXT LABEL FROM THE DATA ARRAY cell.imageView?.image = pizzas[indexPath.row].image cell.textLabel?.text = pizzas[indexPath.row].name //cell.textLabel?.text = pizzas[indexPath.row].description //cell.textLabel?.text = "$\(pizzas[indexPath.row].amount)" // cell.name?.text = pizzas[indexPath.row].name // cell.imageView?.image = pizzas[indexPath.row].image // cell.amount?.text = "$\(pizzas[indexPath.row].amount)" // cell.miscellaneousText?.text = pizzas[indexPath.row].description //print(cell.name?.text! as Any) print(cell.imageView as Any) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } //END OF override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "pizzaSegue", sender: self.pizzas[indexPath.row] as Pizza) } //END OF override func tableView override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pizzaSegue" { guard let vc = segue.destination as? PizzaViewController else { return } vc.pizza = sender as? Pizza } } //END OF override preppare func } ``` ```swift struct Pizza { let id: String let name: String let description: String let amount: Float //let amount: String let image: UIImage init(data: [String: Any]) { //print("CHECK:: pizza.swift") self.id = data["id"] as! String self.name = data["name"] as! String // self.amount = data["amount"] as! Float self.amount = ((data["amount"] as? NSNumber)?.floatValue)! self.description = data["description"] as! String self.image = data["image"] as! UIImage } } ``` As noted above, I have been able to print the contents of the data array with beer names, pictures, descriptions and etc. I have tried to print to console `print(cell.name?.text)` after setting `cell.name?.text = pizzas[indexPath.row].name` but it prints `nil` and this is a problem. I have been stuck with this for about 2 weeks! IBOutlets screenshot: ![](https://i.imgur.com/tiUR0Tf.png)
2019/04/09
[ "https://Stackoverflow.com/questions/55598155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11314191/" ]
I think i found your Problem, let me explain What you are doing here is you have a custom `UITableViewCell` defined in the `Storyboard` in a Controller named "Root View Controller" which is not your `PizzaListTableViewController` to put it simply And as you said you have absolutely no issue regarding the `IBOutlets` Now when you say ``` tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza") ``` In Your `PizzaListTableViewController` you are not linking it with the UI of the cell rather just the Code (This is only used when there is no xib of the cell) *Now what you can do to solve this* **Solution # 1** * Move/Copy your UI of the `PizzaTableViewCell` to `PizzaListTableViewController` in the storyboard from your "Root View Controller" * Make sure you add a `Reuse Identifier` in the Attribute Inspector of the cell in the storyboard * remove `tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")` this wont give you an error this time as it will automatically get register * Make sure all the `IBOutlets` are connected **Solution # 2** create a separate `Nib` (`xib`) of the cell and now you have to register the cell here like ``` tableView.register(UINib(nibName: "PizzaTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "PizzaCell") ``` Hope this helps.
[![](https://i.stack.imgur.com/RGppb.png)](https://i.stack.imgur.com/RGppb.png) Make sure your Table View Controller class is set in the storyboard. [![](https://i.stack.imgur.com/qTIZs.png)](https://i.stack.imgur.com/qTIZs.png) Make sure your Table View Cell class is set in the storyboard. [![enter image description here](https://i.stack.imgur.com/x8Iei.png)](https://i.stack.imgur.com/x8Iei.png) Make sure that all your outlets are properly connected. [![enter image description here](https://i.stack.imgur.com/2zsok.png)](https://i.stack.imgur.com/2zsok.png) Make sure your Table View Cell Identifier is provided in the storyboard. [![enter image description here](https://i.stack.imgur.com/AhnV0.png)](https://i.stack.imgur.com/AhnV0.png) My Table View Controller Subclass [![enter image description here](https://i.stack.imgur.com/LVzlm.png)](https://i.stack.imgur.com/LVzlm.png) My Table View Cell Subclass **cell.imageView?.image** and **cell.textLabel?.text** are optional properties of the table view itself. They are not the properties of the custom cell that you designed. You use **tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "Pizza")** when you have designed a table view cell in XIB. But as you have designed the cell in the storyboard itself you should set the cell reuse identifier and cell class in the storyboard. I hope this will help you out.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Helpers are the classes that help something already there for example there can be a helper for: **array string url etc** A library is something that can be any solution; it could be created for the first time by you and no one else has created. Because you are dealing with a string (something already there), you should put it in a helper class, or modify the string helper class of the framework (if there is one). However, this is a convention or standard but you can create a library for it too if you are creating something really cool for string handling with quite some functions.
I assume you are using CodeIgniter. Since you already write that you don't need to instantiate an object and will use it in it's static methods, then making it into helper will be make sense than making it into library. In CI, helpers is also managed, once loaded, second attempt to load it will be omitted. You can open the CI's build in helper to learn what it does, then compare it with libraries. By knowing the purpose, you can then decide yourself, helpers or libraries.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Helpers are the classes that help something already there for example there can be a helper for: **array string url etc** A library is something that can be any solution; it could be created for the first time by you and no one else has created. Because you are dealing with a string (something already there), you should put it in a helper class, or modify the string helper class of the framework (if there is one). However, this is a convention or standard but you can create a library for it too if you are creating something really cool for string handling with quite some functions.
> > if i've got string functions i use a lot, should i put them in a helper class or a library class? > > > If they are functions, why do you want to stick them in a class? PHP allows for free floating functions.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Helpers are the classes that help something already there for example there can be a helper for: **array string url etc** A library is something that can be any solution; it could be created for the first time by you and no one else has created. Because you are dealing with a string (something already there), you should put it in a helper class, or modify the string helper class of the framework (if there is one). However, this is a convention or standard but you can create a library for it too if you are creating something really cool for string handling with quite some functions.
Helper is collection of user-defined or pre-defined functions, no need to instantiate as well as libraries are classes needs to instantiate to use them. Library might contain user-defined and pre-defined functions/methods too. Function defined in library (class) is known as method!
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Helpers are the classes that help something already there for example there can be a helper for: **array string url etc** A library is something that can be any solution; it could be created for the first time by you and no one else has created. Because you are dealing with a string (something already there), you should put it in a helper class, or modify the string helper class of the framework (if there is one). However, this is a convention or standard but you can create a library for it too if you are creating something really cool for string handling with quite some functions.
Besides the [manual](http://ellislab.com/codeigniter/user-guide/index.html) that explains these all quite well… libraries: Utility classes where object state is important (payment gateways, authentication, etc.) helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.) plugins: A simple way to drop in third party classes. Typically, the whole process is called with a single wrapper function. (deprecated in the upcoming version 2.0 of CodeIgniter.)
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
I assume you are using CodeIgniter. Since you already write that you don't need to instantiate an object and will use it in it's static methods, then making it into helper will be make sense than making it into library. In CI, helpers is also managed, once loaded, second attempt to load it will be omitted. You can open the CI's build in helper to learn what it does, then compare it with libraries. By knowing the purpose, you can then decide yourself, helpers or libraries.
> > if i've got string functions i use a lot, should i put them in a helper class or a library class? > > > If they are functions, why do you want to stick them in a class? PHP allows for free floating functions.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Besides the [manual](http://ellislab.com/codeigniter/user-guide/index.html) that explains these all quite well… libraries: Utility classes where object state is important (payment gateways, authentication, etc.) helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.) plugins: A simple way to drop in third party classes. Typically, the whole process is called with a single wrapper function. (deprecated in the upcoming version 2.0 of CodeIgniter.)
I assume you are using CodeIgniter. Since you already write that you don't need to instantiate an object and will use it in it's static methods, then making it into helper will be make sense than making it into library. In CI, helpers is also managed, once loaded, second attempt to load it will be omitted. You can open the CI's build in helper to learn what it does, then compare it with libraries. By knowing the purpose, you can then decide yourself, helpers or libraries.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Helper is collection of user-defined or pre-defined functions, no need to instantiate as well as libraries are classes needs to instantiate to use them. Library might contain user-defined and pre-defined functions/methods too. Function defined in library (class) is known as method!
> > if i've got string functions i use a lot, should i put them in a helper class or a library class? > > > If they are functions, why do you want to stick them in a class? PHP allows for free floating functions.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Besides the [manual](http://ellislab.com/codeigniter/user-guide/index.html) that explains these all quite well… libraries: Utility classes where object state is important (payment gateways, authentication, etc.) helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.) plugins: A simple way to drop in third party classes. Typically, the whole process is called with a single wrapper function. (deprecated in the upcoming version 2.0 of CodeIgniter.)
> > if i've got string functions i use a lot, should i put them in a helper class or a library class? > > > If they are functions, why do you want to stick them in a class? PHP allows for free floating functions.
2,174,866
if i've got string functions i use a lot, should i put them in a helper class or a library class? functions like: truncate string if longer than 30 characters, return a random string, make all lower cases and so on. these are functions that i probably don't need to create an object for. it's better to use them as static methods. should i put them in a library class or a helper class? when do i know when to put where?
2010/02/01
[ "https://Stackoverflow.com/questions/2174866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206446/" ]
Besides the [manual](http://ellislab.com/codeigniter/user-guide/index.html) that explains these all quite well… libraries: Utility classes where object state is important (payment gateways, authentication, etc.) helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.) plugins: A simple way to drop in third party classes. Typically, the whole process is called with a single wrapper function. (deprecated in the upcoming version 2.0 of CodeIgniter.)
Helper is collection of user-defined or pre-defined functions, no need to instantiate as well as libraries are classes needs to instantiate to use them. Library might contain user-defined and pre-defined functions/methods too. Function defined in library (class) is known as method!
29,940,663
I'm looking for the following regex: * The match can be empty. * If it is not empty, it must contain at least 2 characters which are English letters or digits. * The regex must allow spaces between words. This is what I come up with: ``` ^[a-zA-Z0-9]{2,}$ ``` It works fine, but it does not except spaces between words.
2015/04/29
[ "https://Stackoverflow.com/questions/29940663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3707896/" ]
Here, you can use this regex to make sure we match all kind of spaces (even a hard space), and make sure we allow an empty string match: ``` (?i)^(?:[a-z0-9]{2}[a-z0-9\p{Zs}]*|)$ ``` C#: ``` var rg11x = new Regex(@"(?i)^(?:[a-z0-9]{2}[a-z0-9\p{Zs}]*|)$"); var tst = rg11x.IsMatch(""); // true var tst1 = rg11x.Match("Mc Donalds").Value; // Mc Donalds ```
You can use `^[a-zA-Z\d]{2}[a-zA-Z\d\s]*?$` Here is also an useful site for learning and testing regex patterns. <http://regex101.com/>
30,576,966
First i insert a date into a textbox, from a SQL Server. The user can edit the date when needed. When the 'Save' button is pressed, i need to check if the date in the textbox is valid for SQL. When i check the date format as 'yyyy-mm-dd' and the date is valid everything is okay. But when i install my application on an other computer the date can't inserted in the SQL Server Database. How can i check the date for the needed format...?
2015/06/01
[ "https://Stackoverflow.com/questions/30576966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452125/" ]
It seems that you are confusing SQL Management Studio with underlying Database. Based on this qualified guess, the answer is simple: C# implements `DateTime` object compatible with all version of SQL Databases. If data is stored as string in DB, then you should use `DateTime.TryParse()` method to find out if it's a valid `DataTime` value. Furthermore, having the valid `DateTime` object you can convert it to a `String` in any desirable format (e.g. `ToShortDateString()`, etc.). Hope this may help.
Your approch seems to be wrong. If, in c#, you read a Date from the database in a correct way, you get a DateTime object, not a formatted string. For sql use for example sqldatareader.getDateTime()
57,931,379
I have a Rails project with a "Product Variant" form. The Product variant model is called `Variant`, and on the `Variant` form users should be able to select one choice for each option available. For instance a T-Shirt might have an "Option" called "Size" with the "Choices" small, medium, or large, and another "Option" called one "Color" with the "Choices" red, green, blue. Thus, the `Variant` created is a unique SKU such as a "T-shirt — Size: Small, Color: Green." Or if it were a product that had 3 options instead of 2, the variant would require 3 choices per option, such as "Guitar Strap - Size: Long, Fabric Color: Red, Leather Color: Brown". I can't figure out how to write a custom validation that only allows the user to save one choice per option. Each option should only have one choice selected for each variant. Here's an illustration. [![need a validation that prevents this](https://i.stack.imgur.com/Vq7Ae.png)](https://i.stack.imgur.com/Vq7Ae.png) [![correct outcome](https://i.stack.imgur.com/O7Nzn.png)](https://i.stack.imgur.com/O7Nzn.png) Here are my models with the relevant associations... `models/variant.rb` ``` class Variant < ApplicationRecord has_many :selections has_many :choices, through: :selections validate :one_choice_per_option private def one_choice_per_option # can't figure out how to do this custom validation here end end ``` `models/choice.rb` ``` class Choice < ApplicationRecord has_many :variants, through: :selections belongs_to :option end ``` `models/selection.rb` ``` class Selection < ApplicationRecord belongs_to :choice belongs_to :variant end ``` `models/option.rb` ``` class Option < ApplicationRecord has_many :choices, dependent: :destroy accepts_nested_attributes_for :choices, allow_destroy: true end ``` The best I've managed to do is get this custom validation working on in `models/variant.rb` ``` def one_choice_per_option self.product.options.each do |option| if option.choices.count > 1 errors.add(:choice, 'Error: select one choice for each option') end end end ``` But that only allows one `Choice` total through the variant form. What I want to do is allow one choice for each set of options. I know that this could be done with Javascript in the UI, but this is essential to keeping the database clean and preventing a user error, so I believe it should be a Rails validation at the model level. What is a "Railsy" way to do this type of custom validation? Should I be trying to do a custom validation on the `Selection` model? If so, how? --- UPDATE ====== Based on the discussion in the comments. It seems that I need to do some combination of [Active Record querying](https://guides.rubyonrails.org/active_record_querying.html) to make this work. @sevensidedmarble's "EDIT 2" below is closer but that is giving me this error: `Type Error compared with non class/module` If I save the wrong behavior to the database and then call `Variant.last.choices` in the console it feels like I'm getting closer: [![illustrating the form behavior I need to prevent with a validation](https://i.stack.imgur.com/rGRxU.png)](https://i.stack.imgur.com/rGRxU.png) [![showing the console response](https://i.stack.imgur.com/TBDrq.png)](https://i.stack.imgur.com/TBDrq.png) So essentially, what I need to do is not allow the `Variant` form to save if there is more than one `Selection` with the same `option_id`. A selection shouldn't save unless the `option_id` is unique to the associated `Variant`. Something like this is what I'm trying to do: ``` validate :selections_must_have_unique_option private def selections_must_have_unique_option unless self.choices.distinct(:option_id) errors.add(:options, 'can only have one choice per option') end end ``` But that code doesn't work. It just saves the form as if the validation weren't there.
2019/09/13
[ "https://Stackoverflow.com/questions/57931379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168286/" ]
It's analogous to a uniqueness constraint, but Rails's built-in [`validates_uniqueness_of`](https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of) can't handle this: the validation required is on each Selection object, but it's by option, and the `selections` table doesn't *have* an `option_id` column to constrain. You can't easily do it in the database, either, because unique indexes don't cross table boundaries. I suggest you have each `Selection` object look for a conflicting sibling, and use an [absence validation](https://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_absence_of) on the result. Something like this: ``` class Variant < ApplicationRecord has_many :selections has_many :choices, through: :selections end class Selection < ApplicationRecord belongs_to :choice belongs_to :variant validates_absence_of :conflicting_selection protected def option choice.option end def conflicting_selection variant.selections.excluding(self).detect { |other| option == other.option } end end ``` Eagle eyes will notice that I've used array methods rather than ActiveRecord queries. This isn't a cheesy gimmick to avoid a database round-trip; it ensures that the validation works correctly on unsaved selections as well as those persisted, which might be essential for form processing. That `Selection#option` method, which I'd normally want to write as `has_one :option, through: :choice`, is in a similar vein. Sample gist with unit tests [here](https://gist.github.com/inopinatus/ee6dcc3e0c5cc1ab4d8a6cdeb395175d) if you need it.
Something like this should work: ```rb def one_choice_per_option errors.add(:choice, "can't be more then one per selection") if selections.any { |selection| selection.choices.count > 1 } end ``` Alternatively, I suspect you could also just have selections `has_one :choice` and then your life might be simpler. --- EDIT: as requested in comments, here's an update I think will do exactly as requested: ```rb def one_choice_per_option errors.add(:choice, "can't be more then one per selection") if selections.joins(:choice).where(selections: :choice).count > 3 end ``` I think this will get what you want. If not we just need to mess with the `joins` and `where` part slightly, let me know. EDIT 2: --- Ok, after discussion again I'm a little more clear on what's requested. Sorry for it taking a while, it's hard to understand the schema without seeing it in front of you in your own app. Here's what I *think* would work for what specified. I wrote it here from the context of `Product` but it would work with a little change on `Option` too. ```rb def one_choice_per_option errors.add(:options, "can't be more then one per selection") if (options.joins(:choices).group("options.id").having("COUNT(1) > 1") > 1) end ``` I think that should work, if not it's really close to what you need. This SQL is the basic idea. Sometimes it can help to call `.to_sql` on these queries to see exactly what activerecords pumping out. --- EDIT 3: I was thinking about your original code on `Variant`, and came up with this as well: ```rb class Variant < ApplicationRecord has_many :selections has_many :choices, through: :selections validate :one_choice_per_option private def one_choice_per_option if (choices.joins(:option).group("options.id").having("COUNT(1) > 1") > 1) errors.add(:choices, "can't be more then one per selection") end end end ```
12,403,990
i have a small problem. I have register two events, but only the last was alwas called, can someone help me ``` <!-- Events --> <events> <checkout_type_onepage_save_order_after> <observers> <save_after> <type>singleton</type> <class>XXX_testr_Model_Observer_OrderObserver</class> <method>orderSubmitEvent</method> </save_after> </observers> </checkout_type_onepage_save_order_after> <customer_save_after> <observers> <XXX_testr_observer_observer> <type>singleton</type> <class>XXX_testr_Model_Observer_Observer</class> <method>customerSaveEvent</method> </XXX_testr_observer_observer> </observers> </customer_save_after> </events> ```
2012/09/13
[ "https://Stackoverflow.com/questions/12403990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1668234/" ]
If you want to replace jQuery's fadeIn and fadeOut functions with jQuery Transit, you could do something like this: ``` $.fn.fadeOut = function(speed, callback) { var transitionSpeed = typeof (speed) == "undefined" ? 1000 : speed; $(this).transition({opacity: 0 }, transitionSpeed, callback); }; $.fn.fadeIn = function(speed, callback) { var transitionSpeed = typeof (speed) == "undefined" ? 1000 : speed; $(this).transition({opacity: 1 }, transitionSpeed, callback); }; $("div").on("click", function () { //Fade out for 4 seconds, then fade in for 6 seconds $(this).fadeOut(4000, myCallBackFunction); }); function myCallBackFunction () { $(this).fadeIn(6000); } ``` [JS Fiddle Demo](http://jsfiddle.net/aydbk/) -------------------------------------------- It's not perfect, but you can tweak it to your liking.
Take a look at [this](https://github.com/louisremi/jquery.transition.js/) plugin. It might help you.
7,113,950
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have: ``` <?php function evolve_nav($vals) { echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>'; } ?> ``` Does anyone know why this doesn't return anything and results in an error?
2011/08/18
[ "https://Stackoverflow.com/questions/7113950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633424/" ]
You just forgot some brackets: ``` function evolve_nav($vals) { echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>'; } evolve_nav(array('type' => 'foobar')); evolve_nav(array('not' => 'showing')); ```
``` echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>'; ```
7,113,950
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have: ``` <?php function evolve_nav($vals) { echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>'; } ?> ``` Does anyone know why this doesn't return anything and results in an error?
2011/08/18
[ "https://Stackoverflow.com/questions/7113950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633424/" ]
You just forgot some brackets: ``` function evolve_nav($vals) { echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>'; } evolve_nav(array('type' => 'foobar')); evolve_nav(array('not' => 'showing')); ```
* `''.$vals['type'].''` is superfluous, make it `$vals['type']` * `'darn''>'` those are two string literals without any operator (or anything) between them -> syntax error. In this case I'd rather not use string concatenation (i.e. using the dot-operator like `'xyz' . $a` ) but "pass" multiple parameters to echo. ``` echo '<', ''!==$vals['type'] ? $vals['type'] : 'darn', '>'; ``` or using printf ``` printf('<%s>', ''!==$vals['type'] ? $vals['type'] : 'darn'); ```
7,113,950
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have: ``` <?php function evolve_nav($vals) { echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>'; } ?> ``` Does anyone know why this doesn't return anything and results in an error?
2011/08/18
[ "https://Stackoverflow.com/questions/7113950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633424/" ]
You just forgot some brackets: ``` function evolve_nav($vals) { echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>'; } evolve_nav(array('type' => 'foobar')); evolve_nav(array('not' => 'showing')); ```
``` $descriptiveVariableName = $vals['type']!=='' ? $vals['type'] : 'darn'; // View code echo "<$descriptiveVariableName>"; ```
7,113,950
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have: ``` <?php function evolve_nav($vals) { echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>'; } ?> ``` Does anyone know why this doesn't return anything and results in an error?
2011/08/18
[ "https://Stackoverflow.com/questions/7113950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633424/" ]
``` echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>'; ```
* `''.$vals['type'].''` is superfluous, make it `$vals['type']` * `'darn''>'` those are two string literals without any operator (or anything) between them -> syntax error. In this case I'd rather not use string concatenation (i.e. using the dot-operator like `'xyz' . $a` ) but "pass" multiple parameters to echo. ``` echo '<', ''!==$vals['type'] ? $vals['type'] : 'darn', '>'; ``` or using printf ``` printf('<%s>', ''!==$vals['type'] ? $vals['type'] : 'darn'); ```
7,113,950
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have: ``` <?php function evolve_nav($vals) { echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>'; } ?> ``` Does anyone know why this doesn't return anything and results in an error?
2011/08/18
[ "https://Stackoverflow.com/questions/7113950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633424/" ]
``` echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>'; ```
``` $descriptiveVariableName = $vals['type']!=='' ? $vals['type'] : 'darn'; // View code echo "<$descriptiveVariableName>"; ```
5,905,024
I have a view called 'sub\_nav' and it currently holds a multidimentional array of the links for each section. This view looks at the controller name to get the current section and then loops through the appropriate array set and outputs the links. that works works but it feels like maybe I should create a controller just for the nav? and make sub\_nav simpler but only outputing.... ? can anyone advice? ``` $controllerName = $this->router->class; $methodName = $this->router->method; $subLinks['about'] = array( 'introduction' => 'Introduction', 'people' => 'Our People' ); $subLinks['contact'] = array( 'singapore' => 'Singapore', 'japan' => 'Japan' ); ?> <ul> <?php foreach($subLinks[$controllerName] as $link=>$linkName){ ?> <li <?php if($methodName == $link){ ?>class="on"<? } ?>><a href="<?php echo base_url(); ?><?php echo $controllerName ?>/<?php echo $link ?>/"><?php echo $linkName ?></a></li> <? } ?> </ul> ``` `
2011/05/05
[ "https://Stackoverflow.com/questions/5905024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739215/" ]
If the content is a **static** array, I would put it in either: * **A view file.** Controllers aren't the only place views can be loaded, there's nothing wrong with calling `$this->load->view()` from within another view file (your template). Just store the array *and* the view logic there. * **A config file.** May sound strange, but it's a perfect place for static data like this. This way you won't have to constantly load the data in every load->view() call. Just load the config file in `MY_Controller` or something, and you have access to it anywhere. Then you can write a navigation view or library that will output whatever navigation array you send to it (in other words, don't do any html here - just data, then use for the config item in your view). I say to use a base controller because there's probably no need to autoload this data, for an AJAX request for instance. You won't always need it. It definitely doesn't belong in a Controller, which is more for processing requests and data. A library is a more likely candidate. If the content was dynamic (from the database for example) then you'd definitely want to use a Model or Library, but in this case I would prefer a view file. It's not likely you'll be using the navigation array data anywhere else except your views. In any case, HTML belongs in views whenever possible. If you only use the navigation array in views, only in one view, and it's not dynamic, just store it right there in the view file. Models and libraries should be reusable, storing static data there (that you'll probably need to update frequently) makes no sense to me, but I'd be willing to listen to opponents.
Depending where the data for the navigation comes from, I might give it a model of its own (if it comes from a database for example). As for the logic for choosing navigation to display, I would put that logic in a common base controller, either running it on all page loads or placing code for it in a method on the base controller, so those pages that need it can use it. If your controllers use something like $this->data to hold the data to send to the view, then the base controller logic could pass the navigation data to the view too.
70,992,183
I currently have a dataframe of customers, contracts, and contract dates like this ex ``` Cust Contract Start End A 123 10/1/2021 11/3/2021 B 987 7/4/2022 8/12/2022 ``` For each row, I want to generate a variable that tells me if it was active during a set range ex: 10/1/2021-12/31/2021. When I import from the excel file, the 'Start' and 'End' Columns come in as datetime64[ns] Code I have tried so far is this: ``` df.loc[df['Start'].dt.strftime('%Y-%m-%d')<='2021-10-31' & df['End'].dt.strftime('%Y-%m-%d')<='2021-10-1', 'Active Flag'] = 'Yes' ``` When I run this I get the following error ``` Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool] ``` I'm not really sure if I am even on the correct track for solving this, or if there is an easier way. Any help would be appreciated as Python's date time operations are very odd to me.
2022/02/04
[ "https://Stackoverflow.com/questions/70992183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17996183/" ]
You are not allocating any character memory for `s` to refer to, so `s.size()` is 0 and thus `[0]` is out of bounds, and writing anything to it is [**undefined behavior**](https://en.cppreference.com/w/cpp/language/ub) 1. 1: in C++11 and later, you can safely write `'\0'` to `s[s.size()]`, but you are not doing that here. Try this instead: ``` #include <string> #include <iostream> using namespace std; int main() { string a = "1 23"; string s = ""; if (a[1] == ' ') { s += a[1]; // alternatively: s = a[1]; // alternatively: s.resize(1); s[0] = a[1]; cout << s; } return 0; } ``` Just note that `a[1]` is the whitespace character `' '`, so while you can assign that character to `s`, and it will print to the console, you just won't (easily) see it visually in your console. Any of the other characters from `a` would be more visible.
This assignment ``` if(a[1]==' '){s[0]=a[1]; ``` invokes undefined behavior because the string `s` is empty and you may not use the subscript operator for an empty string to assign a value. Instead you could write for example ``` if(a[1]==' '){s += a[1]; ``` Pay attention to that in this case the string s will contain the space character. To make it visible you could write for example ``` #include <iostream> #include <iomanip> #include <string> //... std::cout<< std::quoted( s ) << '\n'; ``` or ``` std::cout << '\'' << s << "\'\n"; ```
70,992,183
I currently have a dataframe of customers, contracts, and contract dates like this ex ``` Cust Contract Start End A 123 10/1/2021 11/3/2021 B 987 7/4/2022 8/12/2022 ``` For each row, I want to generate a variable that tells me if it was active during a set range ex: 10/1/2021-12/31/2021. When I import from the excel file, the 'Start' and 'End' Columns come in as datetime64[ns] Code I have tried so far is this: ``` df.loc[df['Start'].dt.strftime('%Y-%m-%d')<='2021-10-31' & df['End'].dt.strftime('%Y-%m-%d')<='2021-10-1', 'Active Flag'] = 'Yes' ``` When I run this I get the following error ``` Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool] ``` I'm not really sure if I am even on the correct track for solving this, or if there is an easier way. Any help would be appreciated as Python's date time operations are very odd to me.
2022/02/04
[ "https://Stackoverflow.com/questions/70992183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17996183/" ]
This assignment ``` if(a[1]==' '){s[0]=a[1]; ``` invokes undefined behavior because the string `s` is empty and you may not use the subscript operator for an empty string to assign a value. Instead you could write for example ``` if(a[1]==' '){s += a[1]; ``` Pay attention to that in this case the string s will contain the space character. To make it visible you could write for example ``` #include <iostream> #include <iomanip> #include <string> //... std::cout<< std::quoted( s ) << '\n'; ``` or ``` std::cout << '\'' << s << "\'\n"; ```
My guess is that this is a naive attempt to parse the string. Is this what you are looking for? ``` #include <string> #include <iostream> using namespace std; int main() { string a = "1 23"; string s; if (a[1] == ' ') { s = a.substr(2); cout << s; } return 0; } ```