id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23536100
I want to write the following, keeping both namespace A and B on a single line, to receive a single indent for the namespace block. namespace A { namespace B { class { .... } }// end B }// end A The problem is that as soon as I auto format (CTRL K-D), Visual Studio reformat this to namespace A { namespace B { class { .... } } //end B } //end A Question How can I make sure Visual Studio's auto format according to the first example above? (I have tried to find the correct settings but not been successful) I need to be C++11/14 compliant so namespace A::B is not a solution for me.
doc_23536101
EDIT From the docs: The Firebase Admin SDKs automatically connect to the Cloud Firestore emulator when the FIRESTORE_EMULATOR_HOST environment variable is set I do have that environment variable set but I'm trying to connect to production. How can I instruct the SDK to do this? index.js const admin = require("firebase-admin"); const serviceAccount = require("./serviceAccount.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "" }); const snapshot = admin.firestore().collection('users').get().then((snapshot)=>{ snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); }); }).catch(e=>{ console.error(e); }); The full error log: PS C:\Users\simeon.ramjit\Documents\projects\controllino-server> node index Error: 14 UNAVAILABLE: No connection established at Object.callErrorFromStatus (C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@grpc\grpc-js\build\src\call.js:31:26) at Object.onReceiveStatus (C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@grpc\grpc-js\build\src\client.js:330:49) at Object.onReceiveStatus (C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:299:181) at C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@grpc\grpc-js\build\src\call-stream.js:145:78 at processTicksAndRejections (internal/process/task_queues.js:77:11) Caused by: Error at CollectionReference._get (C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@google-cloud\firestore\build\src\reference.js:1450:23) at CollectionReference.get (C:\Users\simeon.ramjit\Documents\projects\controllino-server\node_modules\@google-cloud\firestore\build\src\reference.js:1439:21) at Object.<anonymous> (C:\Users\simeon.ramjit\Documents\projects\controllino-server\index.js:41:57) at Module._compile (internal/modules/cjs/loader.js:1085:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10) at Module.load (internal/modules/cjs/loader.js:950:32) at Function.Module._load (internal/modules/cjs/loader.js:790:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) at internal/main/run_main_module.js:17:47 { code: 14, details: 'No connection established', metadata: Metadata { internalRepr: Map(0) {}, options: {} } } A: As mentioned above if the FIRESTORE_EMULATOR_HOST environment variable is set the admin SDK will try to connect to your emulator. Following this comment I deleted the env variable and restarted my terminal and it connected to production successfully
doc_23536102
On adding ADT plugin to in software update I got following some dependency error. Cannot complete the install because one or more required items could not be found. Software being installed: Android Development Tools 16.0.1.v201112150204-238534 (com.android.ide.eclipse.adt.feature.group 16.0.1.v201112150204-238534) I consulted some blogs and found that I have to update my Eclipse. Following two sources are there in Eclipse. * *http://download.eclipse.org/eclipse/updates/3.7 *http://download.eclipse.org/releases/indigo But their download is also broken. They try to dowload content.jar file which is not there. Any hand how to solve this problem? Or I should use some other version of Eclipse? Thanks A: I was running a proxy program (UltraSurf). I closed the application and re-tried and that solves my installation problem.
doc_23536103
can anyone help me to find where I am wrong. for help the code is given below. <mx:DataGrid id="userlist" horizontalGridLines="true" horizontalGridLineColor="0xeeeeee" dataChange="dataChanged();" editable="true" change="changegrid(event);" width="100%" height="250" borderColor="#FF0000" borderStyle="solid" borderThickness="1"> <mx:columns > <mx:DataGridColumn dataField="User" editable="false" headerText="User" /> <mx:DataGridColumn dataField="cam" editable="true" width="24" itemEditor="mx.controls.CheckBox" editorDataField="cam" textAlign="center" headerText="M"> <mx:itemRenderer> <mx:Component > <mx:Box horizontalAlign="center" verticalAlign="middle" height="100%" width="100%"> <mx:CheckBox id="chb" click="data.cam=!data.cam" selected="{data.cam}"/> </mx:Box> </mx:Component> </mx:itemRenderer> <mx:headerRenderer> <mx:Component> <mx:Image width="16" height="16" toolTip="Change Cam Status" source="@Embed(source='icons/webcam_start.png')" verticalAlign="middle" horizontalAlign="center"/> </mx:Component> </mx:headerRenderer> </mx:DataGridColumn> <mx:DataGridColumn dataField="mic" editable="false" itemEditor="mx.controls.CheckBox" editorDataField="mic" width="24" textAlign="center" headerText="C"> <mx:itemRenderer> <mx:Component > <mx:Box horizontalAlign="center" verticalAlign="middle" height="100%" width="100%"> <mx:CheckBox id="chb1" click="data.mic=!data.mic" selected="{data.mic}" /> </mx:Box> </mx:Component> </mx:itemRenderer> <mx:headerRenderer> <mx:Component> <mx:Image width="16" height="16" toolTip="Change Microphone Status " source="@Embed(source='icons/microphone_plus.png')" verticalAlign="middle" horizontalAlign="center"/> </mx:Component> </mx:headerRenderer> </mx:DataGridColumn> <mx:DataGridColumn dataField="sound" editable="false" itemEditor="mx.controls.CheckBox" editorDataField="sound" width="24" textAlign="center" headerText="R1"> <mx:itemRenderer> <mx:Component > <mx:Box horizontalAlign="center" verticalAlign="middle" height="100%" width="100%"> <mx:CheckBox id="chb2" click="data.sound=!data.sound" selected="{data.sound}"/> </mx:Box> </mx:Component> </mx:itemRenderer> <mx:headerRenderer> <mx:Component> <mx:Image width="16" height="16" toolTip="Turn Sound on/off " source="@Embed(source='icons/audio_volume_high.png')" verticalAlign="middle" horizontalAlign="center"/> </mx:Component> </mx:headerRenderer> </mx:DataGridColumn> </mx:columns> </mx:DataGrid> I am using the following data private var plist:ArrayList = new ArrayList( [{User:'Ravi Kanchan Sharma', cam:true, mic:true, sound:true}, {User:'Vijay Anand Sharma', cam:true, mic:false, sound:true}, {User:'Yogender Kumar Sharma', cam:false, mic:true, sound:true}]);` A: For the dataChange event to fire from a component, the 'data' value needs to change. It is not clear from your code why the DataGrid's data value will change. the dataChange event is usually used inside an itemRenderer to modify its display contents whenever the itemRenderer's data property is changed. The data property in an itemRenderer would represent a single element of the DataGrid's dataProvider. Unless you are using the DataGrid as an itemRenderer--which is possible but unusual--I would not expect the DataGrid's data property to change; and therefore the dataChange event will never fire from the DataGrid.
doc_23536104
Here is the command : bash <(curl -s https://raw.githubusercontent.com/TitouanVanBelle/XCTestHTMLReport/master/install.sh) '1.0.0' I am able to execute the command in shell without the version like this: /bin/bash -c "$(curl -s https://raw.githubusercontent.com/TitouanVanBelle/XCTestHTMLReport/master/install.sh)" but if I try to pass the version like this: /bin/bash -c "$(curl -s https://raw.githubusercontent.com/TitouanVanBelle/XCTestHTMLReport/master/install.sh) '1.0.0'" or /bin/bash -c "$(curl -s https://raw.githubusercontent.com/TitouanVanBelle/XCTestHTMLReport/master/install.sh '1.0.0')" it won't execute the command. Can someone help me with this A: This command will do the same thing though, try this out- curl -s https://raw.githubusercontent.com/TitouanVanBelle/XCTestHTMLReport/master/install.sh | bash -s '1.0.0' curl downloads this script from online, and as the download finishes the file will be run by bash and bash will pass the argument '1.0.0' to it to download this specific version of XCTestHTMLReport (it is default to version 1.6.1). Or you could simply create a script file on your computer with this, and run it to do the same thing. #!/bin/bash set -e VERSION=$1 if [ -z $VERSION ] ; then VERSION="1.0.0" fi OUT_ZIP="xchtmlreport.zip" printf "Downloading xchtmlreport $VERSION\n" CURL=$(curl -L -s -w "%{http_code}" -o $OUT_ZIP https://github.com/TitouanVanBelle/XCTestHTMLReport/releases/download/$VERSION/xchtmlreport-$VERSION.zip) if [ ! -f $OUT_PATH ]; then printf '\e[1;31m%-6s\e[m' "Failed to download XCTestHTMLReport. Make sure the version you're trying to download exists." printf '\n' exit 1 fi unzip $OUT_ZIP chmod 755 xchtmlreport mv xchtmlreport /usr/local/bin/ rm $OUT_ZIP printf '\e[1;32m%-6s\e[m' "Successully installed XCTestHTMLReport. Execute xchtmlreport -h for help." printf '\n' exit 0 I did a slight modification as I changed the default version to 1.0.0.
doc_23536105
Category: Foresatt Among them: Name: 'foresatt epost', type:email, number: multiple values I would like to list these values using Google Script. I used this: https://developers.google.com/admin-sdk/directory/v1/quickstart/apps-script To write this code: function listUsers() { var optionalArgs = { customer: 'my_customer', maxResults: 10, orderBy: 'email', projection: 'custom', customFieldMask:'Foresatt' }; var response = AdminDirectory.Users.list(optionalArgs); var users = response.users; if (users && users.length > 0) { Logger.log('Users:'); for (i = 0; i < users.length; i++) { var user = users[i]; var foresatt = user.customSchemas; Logger.log('%s (%s)', user.primaryEmail, user.name.fullName, foresatt); } } else { Logger.log('No users found.'); } } That works, but I would like to get only the values. What I get now: {Foresatt={ foresatt_mob=[{value=X#X#X#X#, type=work}, {type=work, value=X#X#X#X#}, {type=work, value=X#X#X#X#}], foresatt_epost=[{value=xx@xx.no, type=work}, {type=work, value=xy@xx.no}, {value=yy@xx.no, type=work}], foresatt_navn=[{type=work, value=Xx}, {value=Xy, type=work}, {type=work, value=Yy}] } } What I would like to get: xx@xx.no, xy@xx.no, yy@xx.no I have tried several things, but I'm afraid I'm not experienced enough. var epost = foresatt.foresatt_epost; Results in: TypeError: Cannot read property 'foresatt_epost' var epost = foresatt('foresatt_epost'); Results in: TypeError: foresatt is not a function Please advise me, how do I get only the values fram the field 'foresatt epost'? A: I believe your goal as follows. * *You want to retrieve the values of xx@xx.no, xy@xx.no, yy@xx.no from the following object: const object = { Foresatt: { foresatt_mob: [ { value: "X#X#X#X#",type: "work"}, { value: "X#X#X#X#",type: "work"}, { value: "X#X#X#X#",type: "work"}, ], foresatt_epost: [ { value: "xx@xx.no", type: "work"}, { value: "xy@xx.no", type: "work"}, { value: "yy@xx.no", type: "work"}, ], foresatt_navn: [ { type: "work", value: "Xx"}, { type: "work", value: "Xy"}, { type: "work", value: "Yy"}, ] } } In this case, the values can be retrieved from the object.Foresatt.foresatt_epost array. Sample script: const object = {}; //Your object const res = object.Foresatt.foresatt_epost.map(e => e.value); console.log(res) // Outputs: [ 'xx@xx.no', 'xy@xx.no', 'yy@xx.no' ] * *If user.customSchemas is the above object, the script is as follows. var foresatt = user.customSchemas; const res = foresatt.Foresatt.foresatt_epost.map(e => e.value); console.log(res) * *If you want to retrieve the value as a comma separated string, you can use res.join(","). References: * *map() Note: If there is no guarantee your property will exist in your object, you can do (object.property||[]).map(...) instead of object.property.map(...) to avoid the error Uncaught TypeError: Cannot read property 'forEach' of undefined.
doc_23536106
Upon building the image with docker-compose up --build with the following Dockerfile FROM php:7.3-apache-stretch RUN apt-get update -y && apt-get install -y libpng-dev RUN docker-php-ext-install pdo pdo_mysql gd FROM composer:1.9.0 as build WORKDIR /app COPY . /app RUN composer global require hirak/prestissimo && composer install I am getting the error message: phpoffice/phpspreadsheet 1.13.0 requires ext-gd * -> the requested PHP extension gd is missing from your system. This happens when the composer install command runs. As you can see up, I am actually installing gd from php, so it should not give me this error message. Do you have any idea how I can solve it? Thanks! A: It's happen, because you are using multistage building and your composer second stage have nothing to do with previous build using PHP container. Primary use case with multistaging is to produce some useful artefacts which can be used later. So what I suggest is to copy composer file from composer image, then place it somewhere in your php container. I will give you my solution which is working perfectly for me with laravel/symfony etc. FROM php:7.4.4-fpm # We copy composer from it's original image to our php container to use it later. COPY --from=composer:1.9 /usr/bin/composer /usr/bin/composer WORKDIR /var/www ARG USER_ID RUN useradd -s /bin/bash -d /home/user/ -m -G sudo,www-data user -u $USER_ID RUN apt update && apt install -y zip unzip wget zlib1g-dev libicu-dev RUN docker-php-ext-install pdo_mysql intl opcache gd USER user RUN wget https://get.symfony.com/cli/installer -O - | bash ENV PATH="/home/user/.symfony/bin:${PATH}" COPY php.ini /usr/local/etc/php # You can also run here composer install, depends on your use case A: You can change your docker image. For example try this: FROM richarvey/nginx-php-fpm WORKDIR /app RUN php ./artisan config:cache && composer install
doc_23536107
public partial class Service1 : ServiceBase { It seems to be an application, on properties we see: Output type: Windows Application Target framework: .NET Framework 4 This somehow translates to a SearchUpdater.exe file we have on the web server which is run every day. The code deletes a search index text file and then rebuilds it. Simple, except I need to update the code logic and replace the .exe. When I do this I can't seem to generate the .exe file any way I try. If I 'publish' the SearchUpdater project I get a local 'setup.exe' file, which, when I run it generates a kind of SearchUpdater 'shortcut' in my start menu which is a Type of file: Application Reference (.appref-ms) Location: C:\Users\Me\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\HP Inc There's no 'target'... Basically, I can't find a .exe file anywhere to replace the one on our webserver! Any ideas? I'm a bit lost with this one, how can I generate a .exe, and will I need to do this somehow on the webserver? Am I doing something wrong? A: Thanks to suggestions by @codecaster and @hans-passant. If you build the project in release mode, then go to the solution folder and check in the correct bin folder there is indeed a 'release' folder that will contain the .exe file (or did for me!).
doc_23536108
"value1:value2::value3".split(":"); Problem is that I want it to include the blank results. It returns: [value1, value2, value3] It should be: [value1, value2, , value3] Does anyone know the regexp to fix this? Ok I found cause of problem. I'm actually reading a text file and it contains this line: 123:;~\&:ST02:M:test:M:4540145::type;12:51253:D:2.2:567766::AL:::::::2.2b When I process this line reading the text file it produces the erroneous result mentioned above, which is it doesn't include any empty results in cases like this: :::::. But when I use the above line in a test program it doesn't compile and I get a "invalid escape sequence". I think its because of the "\&". Is there a workaround to this problem by using a regular expression? A: Works for me. class t { public static void main(String[] _) { String t1 = "value1:value2::value3"; String[] t2 = t1.split(":"); System.out.println("t2 has "+t2.length+" elements"); for (String tt : t2) System.out.println("\""+tt+"\""); } } gives the output $ java t t2 has 4 elements "value1" "value2" "" "value3" A: split does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1). A: I think that a StringTokenizer might work better for you, YMMV. A: I don't honestly see the big draw of split. StringTokenizer works just as well for most things like this and will easily send back the tokens (so you can tell there was nothing in between :: ). I just wish it worked a little better with the enhanced for loop, but that aside, it wouldn't hurt to give it a try. I think there is a regexp trick to get your matched tokens to return as well but I've gone 20 years without learning regexp and it's still never been the best answer to any problem I've tackled (Not that I would actually know since I don't ever use it, but the non-regexp solutions are generally too easy to beat.) A: Use a negative limit in your split statement: String str = "val1:val2::val3"; String[] st = str.split(":", -1); for (int i = 0; i< st.length; i++) System.out.println(st[i]); Results: val1 val2 val3 A: public static void main(String[] args){ String[] arr = "value1:value2::value3".split(":"); for(String elm:arr){ System.out.println("'"+elm+"',"); } System.out.println(arr.length); } prints 'value1', 'value2', '', 'value3', 4 Which is exactly what you want. Your mistake is somewhere else... A: Using Guava's Splitter class: Iterable<String> split = Splitter.on(':').split("value1:value2::value3"); Splitter does not omit empty results by default, though you can make one that does. Though it seems from what others are saying that what you're doing should work as well. A: That should work but give StringTokenizer a go if you're still having issues. A: This works, import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.IOException; public class split { public static void main(String[] args) { String data = null; try { BufferedReader br = new BufferedReader(new FileReader(new File("split.csv"))); while( (data=br.readLine())!=null) { System.out.println("line:"+data); String[] cols = data.split(":",-1); System.out.println("count:"+cols.length); for(int x=0;x<cols.length;++x) { System.out.println("["+x+"] =("+cols[x]+")"); } } } catch (IOException e) { e.printStackTrace(); } } } Here is a test file, a:b:c:d:e a:b:c:d: a:b:c:: a:b::: a:::: :::: ::::e :::d:e ::c:d:e :b:c:d:e a:b:c:d:e
doc_23536109
CSS #element{ margin-left: 10%; } Javascript $('#element').css('margin-left'); // returns 29px in Firefox, but 10% in Chrome getComputedStyle(document.getElementById('element')).getPropertyValue('margin-left'); // returns 29px in Firefox, but 10% in Chrome A: This example is using css width, but the principle can be applied to any attribute that may be specified in % CSS .oneThirds { width: 25%; background-color: red; } .half { width: 50%; background-color: green; } .twoThirds { width: 75%; background-color: yellow; } HTML <div class="oneThirds">One third</div> <div class="half">Half</div> <div class="twoThirds">two thirds</div> Javascript var elements = document.getElementsByTagName("div"); Array.prototype.forEach.call(elements, function (element) { var parentStyle = window.getComputedStyle(element.parentNode); var elementStyle = window.getComputedStyle(element); var widthPercent = (parseFloat(elementStyle.width) / parseFloat(parentStyle.width)) * 100; console.log(widthPercent); }); Output 25 50 75 On jsfiddle On some browsers you may need to do a little rounding of the floating point.
doc_23536110
var dataModel = {name1:"value1", name2:"value2"}; $.ajax({ url: "/testURL", type: "POST", async: false, contentType: "application/json", data: dataModel, success: function(response) { } }) Here is my relevant snippet from spring xml <annotation-driven> <!-- Message converters are added to use custom object mapper in MappingJackson2HttpMessageConverter. StringHttpMessageConverter is required to avoid MappingJackson2HttpMessageConverter from converting a string into json. --> <message-converters> <beans:bean class="org.springframework.http.converter.StringHttpMessageConverter"> </beans:bean> <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <beans:property name="objectMapper" ref="jacksonObjectMapper"/> </beans:bean> </message-converters> </annotation-driven> Here is my controller mapping @RequestMapping(value = "/testURL", method = { RequestMethod.POST }) public String add(HttpServletRequest request, @RequestBody CustomObject customObject) throws Exception {} But My request does not even reach to controller. As soon as I remove @RequestBody CustomObject customObject it works. But I want to map the json request to CustomObject with @RequestBody which is not happening . Not sure what i am missing here ? In fact when I inspect request.getParameterMap() it displays empty but as soon as I remove contentType: "application/json" I see parameter map gets populated but still then get below error `The server refused this request because the request entity is in a format not supported by the requested resource for the requested method` Here is my CustomObject definition public class CustomObject implements Serializable { private static final long serialVersionUID = 1L; private String name1; private String name2; //getters and setters } Already gone through JQuery, Spring MVC @RequestBody and JSON - making it work together but did not help A: In fact when I inspect request.getParameterMap() it displays empty but as soon as I remove contentType: "application/json" That is right. Reason is with contentType: "application/json" jquery internally convert the data into string. so there is no request parameter. Without contentType: "application/json" , default contentType' is form data . So data sent is converted to request parameters based on delimiters&and=` Also try data: JSON.stringify(dataModel), it should work
doc_23536111
A number can also be prepended to the format of the examine command to examine multiple units at the target address. source: hacking the art of exploration (gdb) x/2x $eip 0x8048384 <main+16>: 0x00fc45c7 0x83000000 (gdb) x/x $eip 0x8048384 <main+16>: 0x00fc45c7 I know that the second examine command returns the memory address that eip is currently locating. What about the first one which returns two memory address? A: The examine command of gdb has the following syntax: x/[n][f][u] where n, f and u are optional and n is the length, f the format and u the unit size. Possible formats are: * *s (null terminated string) *i (machine code instruction) *x (hexadecimal value) If no unit size can be one of the following values: * *b (bytes) *h (2 bytes) *w (4 bytes) *g (8 bytes) where w is the default. Therefore x/2x prints 2 hexadecimal values with a size of 4 bytes from your code segment.
doc_23536112
From TokenInterface $token, i can print with $token->getUser(), it works correctly. I'm stuck really do not know where the problem is. I will give u some suspecious codes that maybe has error. security.yaml firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: anonymous: ~ pattern: ^/ provider: steam_user_provider steam: true logout: path: /logout target: / user.php public function __construct() { $this->roles = []; } /** * @return array */ public function getRoles(): array { $roles = []; foreach ($this->roles as $role) { $roles[] = new Role($role); } return $roles; } SteamProvider class SteamProvider implements AuthenticationProviderInterface { /** * @var UserProviderInterface */ private $userProvider; /** * @param UserProviderInterface $userProvider */ public function __construct(UserProviderInterface $userProvider) { $this->userProvider = $userProvider; } /** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByUsername($token->getUsername()); $authenticatedToken = new SteamUserToken(); $authenticatedToken->setUser($user); $authenticatedToken->setUsername($user->getUsername()); $authenticatedToken->setAuthenticated(true); return $authenticatedToken; } /** * {@inheritdoc} */ public function supports(TokenInterface $token) { return $token instanceof SteamUserToken; } } ContextListener. (Error shows up here) $token->setUser($refreshedUser); if (null !== $this->logger) { $context = ['provider' => \get_class($provider), 'username' => $refreshedUser->getUsername()]; foreach ($token->getRoles() as $role) { if ($role instanceof SwitchUserRole) { $context['impersonator_username'] = $role- >getSource()->getUsername(); break; } } I'm really sorry about this retarded question. But i do not have idea about why this error happening. Really $token->getUser() works perfectly, but in provider->refreshUser($token->getUser()) is giving NULL value.Maybe there is a error with roles but really do not know. If you need more examples about my code, just ask me. Thx for your helping Adding SteamUserProvider for more info /** * @var EntityManagerInterface */ private $entityManager; /** * @var SteamApiClient */ private $api; /** * @var string */ private $userClass; /** * @var UserFactory */ private $userFactory; /** * @param EntityManagerInterface $entityManager * @param SteamApiClient $steamApiClient * @param string $userClass * @param UserFactory $userFactory */ public function __construct( EntityManagerInterface $entityManager, SteamApiClient $steamApiClient, string $userClass, UserFactory $userFactory ) { $this->entityManager = $entityManager; $this->api = $steamApiClient; $this->userClass = $userClass; $this->userFactory = $userFactory; } /** * {@inheritdoc} */ public function loadUserByUsername($username) { $user = $this->entityManager->getRepository($this->userClass)- >findOneBy(['steamId' => $username]); $userData = $this->api->loadProfile($username); if (null === $user) { $user = $this->userFactory->getFromSteamApiResponse($userData); $this->entityManager->persist($user); } else { $user->update($userData); } $this->entityManager->flush(); return $user; } /** * {@inheritdoc} */ public function refreshUser(UserInterface $user) { if (!$user instanceof SteamUserInterface) { throw new UnsupportedUserException(); } return $this->entityManager->getRepository($this->userClass)- >findOneBy(['steamId' => $user->getSteamId()]); } /** * {@inheritdoc} */ public function supportsClass($class) { return $class === $this->userClass; }
doc_23536113
Kind regards
doc_23536114
I want a 100% width div, with 1 row of elements. I need to scroll through this div, just like: http://jqueryfordesigners.com/demo/scrollable-timelines.html So with a hidden overflow and such. But now I want some sort of smooth ease when I let go of the mouseclick, so it'll be like a sort sweep. So when I drag the screen from left to right, and let go of the mouse, it'll move on for 1 sec and linearly slowing down. Hm, am I making sense? Does anyone know of any scripts or some tips to put me back on track? Don A: Utterscroll is a drag and scroll library I've written: (EDIT: demo temporarily broken, seems a CDN link no longer works,) GitHub: https://github.com/debiki/utterscroll GitHub hosted demo: http://rawgit.com/debiki/utterscroll/master/utterscroll-example.html It differs from other libraries in that it 1) understands if you intend to select text, rather than scrolling (note that in the example linked to by the question, it's not possible to select text), and 2) it needs no, or almost no, configuration. Utterscroll stops when you release the mouse though (just like Dragscrollable, in the answer above, does.)
doc_23536115
IServiceCollection services = ... services.AddScoped<IEmailService, EmailService>(); Then I know that for each HTTP request a new scope will be created and a new instance of Email service will be reused. Moreover, the same scope will persist for the lifetime of a request. Now, imagine I add a Hangfire Background Job like this: RecurringJob.AddOrUpdate<IServiceA>("DoA", s => s.DoA(), Cron.Daily()); where public class ServiceA: IServiceA { public ServiceA(IEmailService emailService) { ... } public void DoA() { ... } } I would like to understand what does scoped mean in hangfire job terms, by default, does hangfire * *use a single scope for all the jobs and runs *create separate scopes for each job, but different runs of the same job share the scope *create separate scopes for each run of any job Bonus points for an explanation on how to configure it. A: As Panagiotis Kanavos put in a comment above (but to make more visible as an accepted answer): Looks like this is provided out of the box if you simply call AddHangFire in your DI configuration. Each execution is wrapped in a scope, no matter what DI container is used. This isn't documented anywhere though
doc_23536116
Image a box, or a cube, all sides right. If we were to put the box on a flat surface, the face touching the bottom, would be the floor or base. if the base had an inside, which most boxes do, from the outside you would not be able to see it right. Unfortunately, in my code you can. instead of a box, you have a room, in which i go outside the room and see the floor, but i should not. ill post an image of the problem and a video, as well as some code and any code that you might ask for. http://www.youtube.com/watch?v=ml3-OBGNXXA&feature=youtu.be http://www.flickr.com/photos/pkerkm/8607171993/ http://www.flickr.com/photos/pkerkm/8608276014/ //here is how i manage the textures void /*GraphicsEngine::*/drawWall(double a[3],double b[3], double c[3], double d[3], bool floor){ if(floor){ glBindTexture(GL_TEXTURE_2D, texture[1]); }else{ glBindTexture(GL_TEXTURE_2D, texture[0]); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data); // build our texture mipmaps glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_DECAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_DECAL); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2d(0.0,0.0); glVertex3dv(a); glTexCoord2d(-1.0,0.0); glVertex3dv(d); glTexCoord2d(-1.0,-1.0); glVertex3dv(c); glTexCoord2d(0.0,-1.0); glVertex3dv(b); glEnd(); } //here is the reshape function void reshape(int w, int h){ //glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); //glLoadIdentity(); gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 200.0); glMatrixMode(GL_MODELVIEW); //glTranslatef(0.0, 0.0, -3.6); //glLoadIdentity(); } //here is the display function void /*GraphicsEngine::*/display(){ //glClearColor (0.0, 0.0, 0.0, 1.0); //glLoadIdentity (); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glShadeModel(GL_FLAT); //glClearDepth(1.0); //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); setPos(); gluLookAt(currentXPos,currentYPos,currentZPos,currentXFace,currentYFace,currentZFace,0,1,0); generateMap(); graphicsFloor(); int i = 0; if(projectiles.size()>0){ for(i= 0; i< projectiles.size(); i++){ arrow(projectiles.operator[](i).getXPos(),projectiles.operator[](i).getYPos(),projectiles.operator[](i).getZPos(),0.5,BLOCKWIDTH); } projectileMotion(); player.advance(); //glutPostRedisplay(); /*}else if(player.advance()){ glutPostRedisplay(); }*/ } //glFlush(); glutSwapBuffers(); } //here is what tells where to draw the floor and the walls void graphicsFloor(){ int x,z; //up for(x=0;x<7;x+=7){ for(z=0;z<105;z+=7){ double a[3] = {x,0,z}; double b[3] = {x+7,0,z}; double c[3] = {x+7,0,z+7}; double d[3] = {x,0,z+7}; drawWall(d,a,b,c,true); } } } // the walls void generateMap(){ int z; int x; for(z =0;z<105;z+=7){ double a[3] = {0,0,z}; double b[3] = {0,0,z+7}; double c[3] = {0,MAPHEIGHT,z+7}; double d[3] = {0,MAPHEIGHT,z}; drawWall(d,a,b,c,false); } for(z =0;z<42;z+=7){ double a[3] = {7,0,z}; double b[3] = {7,0,z+7}; double c[3] = {7,MAPHEIGHT,z+7}; double d[3] = {7,MAPHEIGHT,z}; drawWall(d,a,b,c,false); } } //and here is how i load up the textures void genTex(){ texture[0]=SOIL_load_OGL_texture // load an image file directly as a new OpenGL texture ( //"C:\\Users\\Eddy\\Desktop\\Senior Project\\Senior Project\\bloodwall2.png", "C:\\Users\\Pkerkm\\Documents\\Visual Studio 2010\\Projects\\files\\gameprojecgraphics\\bloodwall2.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT //SOIL_FLAG_POWER_OF_TWO| SOIL_FLAG_MIPMAPS| SOIL_FLAG_MULTIPLY_ALPHA| SOIL_FLAG_COMPRESS_TO_DXT| SOIL_FLAG_DDS_LOAD_DIRECT| SOIL_FLAG_INVERT_Y ); glBindTexture(GL_TEXTURE_2D, texture[0]); } A: It looks like depth testing is disabled. Enable it: glEnable(GL_DEPTH_TEST); If that doesn't work, make sure you have a depth buffer and try again.
doc_23536117
Too few arguments to function FOS\UserBundle\Controller\ResettingController::__construct(), 0 passed in /var/www/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php on line 200 and exactly 6 expected that happens when i open the link in the automatic Mail of FosUserBundle FOSMailer::sendResettingEmailMessage // routing.yml app: resource: "@AppBundle/Controller" type: annotation prefix: /{_locale}/ requirements: _locale: fr|en|es app_api: resource: "@AppBundle/Controller/Api" type: annotation fos_js_routing: resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml" fos_user_security_login: path: /connexion methods: [ GET, POST ] defaults: { _controller: FOSUserBundle:Security:login } fos_user_security_check: path: /login_check methods: [ POST ] defaults: { _controller: FOSUserBundle:Security:check } fos_user_security_logout: path: /logout methods: [ GET, POST ] defaults: { _controller: FOSUserBundle:Security:logout } fos_user_resetting_reset: path: /resetting/reset/{token} methods: ['GET', 'POST'] defaults: { _controller: FOSUserBundle:Resetting:reset } I cleared the cache, and i added the 6 parameters with dependency injection: //services.yml services: fos_user.resetting.reset: class: FOS\UserBundle\Controller\ResettingController arguments: - "@event_dispatcher" - "@fos_user.resetting.form.factory" - "@fos_user.user_manager" - "@fos_user.util.token_generator" - "@fos_user.mailer" - "%fos_user.resetting.retry_ttl%" That worked well in dev environnement (in local and on a server), but i still got the same error "too few arguments..." in production. So cleared the cache again : bin/console c:c --env=prod removed the cache folder: rm -Rf var/cache/prod But i still got the error :/ Does anyone have an idea ? A: Thank you @Cerad for your help. I finally found the solution to my problem : i just realized that the version of fosUserBundle wasn't the same on the 2 servers ... so i just changed my composer.json with that: "friendsofsymfony/user-bundle": "2.0.*" And this works fine!
doc_23536118
I've created an IAM user, and have the access key and secret access key ID associated with the user, but I'm struggling to figure out how to grant that user permissions to an S3 bucket. I'd like to grant them write access (but not read) to the bucket, but am starting with all access to see if I can get permissions working. I tried creating a policy through the policy creation tool and then attaching the policy to the user, but when I try to access the bucket through the policy simulator I get an error 'Implicitly denied no matching statements' Here is the policy the policy generator created: { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1451195578000", "Effect": "Allow", "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::techp.websitebackup/*" ] } ] } I think tried to attach this policy to the bucket in S3, but I get an error: Statement is missing required element - Statement "Stmt1451195578000" is missing "Principal" element I think I'm probably misunderstanding how permissions on AWS work, can you provide some guidance? thx v A: Associating your policy with the user is the correct way of doing so. Your policy document is also correct. In the simulator, don't provide * as the ARN of the resource but provide a qualified name. For example, arn:aws:s3:::techp.websitebackup/* or arn:aws:s3:::techp.websitebackup/foo/bar (because the user does not have privileges on every bucket in your account)
doc_23536119
If I do this, it works: Restrictions.like("DBFieldName", object.getFieldName()); Now, I need to add the %, but if I do something like: Restrictions.like("DBFieldName", "%" + object.getFieldName()); I get this error: java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Blob What should I do? Thank you A: you cant compare a String value to blob through Criteria because this last will try to cast the the string to Blob which is not possible (basicly java.sql.Blob is an interface)if you realy need to do such comparision, the only solution you have is to get the Blob value and create a string based on it, use this example: byte[] bdata = blob.getBytes(1, (int) blob.length()); String text = new String(bdata); and do you comparision on your java Side.
doc_23536120
The code I'm using is: req = urllib2.Request(url) fh = urllib2.urlopen(req) with contextlib.closing(ZipFile("test.csv.zip", "w", zipfile.ZIP_STORED)) as f: f.write(fh.read()) f.close() What this does is to print the contents of the csv file to stdout and create an empty zipfile. Any ideas of what could be wrong? Thanks, Isaac A: Take a look at the documentation for ZipFile.write(). Here is the function signature: ZipFile.write(filename[, arcname[, compress_type]]) The first argument should be the file name of the file that you are adding to the zip archive, not the contents of the file. Instead you are passing the entire contents of the downloaded resource as the file name and, because that will likely be illegal (too long), you see the file contents dumped as part of the error message of the raised exception. To fix this you need to use is ZipFile.writestr(): req = urllib2.Request(url) fh = urllib2.urlopen(req) with ZipFile("test.csv.zip", "w", zipfile.ZIP_STORED) as f: f.writestr('test.csv', fh.read()) If it is your intention to compress only a single file, you probably don't need to use a zip archive, and you might be better off using gzip or bzip2.
doc_23536121
WhatI have done so far: func startBlink() { UIView.animate(withDuration: 0.8,//Time duration delay:0.0, options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat], animations: { self.alpha = 0 }, completion: nil) } But this code blinks the ui view for infinite number of time. I used another code but that was blinking for one time only. What I want: So I am pretty close but I really want to blink the UIView for finite number of times i.e 30 times, and it must stop after 30th blink. Please help me in this, I think I have clear in my question. Please help me out. A: Use this function to animate View. I hope it can help extension UIView { func flash(numberOfFlashes: Float) { let flash = CABasicAnimation(keyPath: "opacity") flash.duration = 0.2 flash.fromValue = 1 flash.toValue = 0.1 flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) flash.autoreverses = true flash.repeatCount = numberOfFlashes layer.add(flash, forKey: nil) } } A: There is a builtin in class function for the count and call it in the block. class func setAnimationRepeatCount(_ repeatCount: Float) func startBlink() { UIView.animate(withDuration: 0.8,//Time duration delay:0.0, options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat], animations: { UIView.setAnimationRepeatCount(30) // repeat 30 times. self.alpha = 0 }, completion: nil) }
doc_23536122
But before I go about receiving and sending payments I want to make sure that any new user signing up to my website already has a paypal account. IE when they sign up to my website I'd like to first of all check that the email address they supplied me with is already linked to a valid paypal account. I've never had to do this before so if someone could explain in very simple language how I might go about doing this I'd be really grateful. I'm using the cakephp framework incase that makes any difference to the answer. thanks A: This may be what you're looking for: AddressVerify API Confirms whether a postal address and postal code match those of the specified PayPal account holder. After supplying an email address, PayPal will return with one of 3 responses for the email parameter: None, Confirmed, or Unconfirmed. If it is None, then the request value does not match any email address on file at PayPal. Although this API requires both the email address and shipping/billing information, it can be solely used to verify the email address. By supplying invalid shipping/billing information, the API will still respond with whether the email matches any on file at PayPal, and also match whether your invalid shipping/billing information matches the information on file with the matched email address. An expected PayPal response may reflect the above: Array ( [CONFIRMATIONCODE] => Confirmed [STREETMATCH] => Unconfirmed [ZIPMATCH] => Unconfirmed [COUNTRYCODE] => US [TOKEN] => a134k1j34lk134gv13dshjg52b ) CONFIRMATIONCODE will be your only concern when verifying a PayPal email address. Please, check the above link for more information. A: Setting up an IPN Listener is one way that's often used to verify most of the important information you're referring to. There's a decent tutorial that you can check out since paypal's example might not be enough on it's own.
doc_23536123
I Have just created a new big method which also adds a lot more data to the database. When I call this, it appears to work fine the first time it has run, but, if I run it again within a few minutes of the previous attempt, I get the following error: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. I am unsure how to fix this, can anyone advise anything? (other than not to run this within a few minutes of the last attempt!). A: This Error usually occurs when you try to save an entity model which has not defined well the primary key (composite key) as like in the database. Define the keys in EntityTypeConfiguration file like this.HasKey(f => new { f.ID1, f.ID2 }); A: Possible duplicate of: * *InvalidOperationException when calling SaveChanges in .NET Entity framework *Autonumber with Entity Framework Here are u useful links on working with self-tracking entities and the Object State Manager * *http://msdn.microsoft.com/en-us/library/bb896269.aspx *http://msdn.microsoft.com/en-us/library/ff407090.aspx
doc_23536124
I added icudt46l.zip to the assets folder and *.so to the libs/armeabi folder. As it's an upgrade, I want to encrypt the unencrypted database. I tested the code on a Samsung S2 (Android 2.3.3) and a Sony Z1 (Android 4.4.2) and it works correctly, the update from an unencrypted database as well with a new encrypted database. With my Samsung Galaxy S4 (Android 4.2.2) I constantly get a Fatal signal 11 when I try to open the unencrypted database SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(originalFile, "", null) . It's the first call of a SQLcipher-method in my code (besides net.sqlcipher.database.SQLiteDatabase.loadLibs(inContext) ). If I'm changing the package-name from the manifest it runs on the S4 (so it gets a fresh clean database). As I thought of an OOM-Exception I tested the code on the S2 again. I generated an 10MB SQLite unencrypted database and transformed it with my code correctly. Can anyone give me a hint, what I'm doing wrong? A: Sounds like the guy here has the same Problem, maybe it helps. https://groups.google.com/forum/#!topic/sqlcipher/hZFpNSSP-c8
doc_23536125
Possible Duplicate: How to get screenshot to include the invoking window (on XP) I'm currently using CopyFromScreen(0, 0, 0, 0, imageSize) to capture the desktop but unfortunately, there is a particular winform's contents which it didn't capture (the rest are alright). This winform's job is pretty simple; it's just a ticker program. Black background and a label that's moving per millisecond or so, that's all. No borders. I can't use directx's CaptureScreen (I've tried) because the graphic card's driver doesn't allow me to access the front buffer (there's nothing in the back buffer). I can't use SendKey({PRTSC}) either because I can't overwrite the clipboard's content. What's interesting however, is that by pressing the keyboard's "Print Screen" and pasting it in MS Paint, the ticker program was captured perfectly. It just didn't work via CopyFromScreen in the code. How do I get it working, or is there any other workaround for this without resorting to win32 APIs? EDIT: I have discovered why didn't it work. It turns out that my ticker program's form had TransparentKey set to anything other than null (maroon in this case). When TransparentKey is not null, CopyFromScreen will not work. It just copies a blank image. Does anyone knows how to get both (TransparentKey and CopyFromScreen) working together? lol EDIT 2 (SOLVED): As posted below, I have discovered that CopyFromScreen is actually a wrapper around BitBlt. Instead of calling CopyFromScreen, I used the BitBlt call here: How can I save a screenshot directly to a file in Windows? However, I modified the code a little. Change the call to: WIN32_API.BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC, 0, 0, WIN32_API.SRCCOPY | WIN32_API.CAPTUREBLT); And add this to WIN32_API class: public const int CAPTUREBLT = 1073741824 And now it's possible to capture desktop with TransparentKey. A: Capture the Screen into a Bitmap or http://www.csharphelp.com/2006/11/capturing-the-screen-image-using-c/ might be of help.
doc_23536126
I think that the code is simple. async onSubmit() { try { const user = await Auth.signIn(this.loginForm['username'].value, this.loginForm['password'].value); } catch (error) { console.log('error signing in', error); } } Here is my DEMO, however it says that I miss some packages such http and https. A: make sure you are calling Amplify.configure to configure which User Pool you are connecting to - https://docs.amplify.aws/lib/auth/start/q/platform/js#re-use-existing-authentication-resource you are using Auth.signIn correctly, but it needs to be configure with Amplify.configure before you can use it, for example (no-angular specific): // ./index.js import { Amplify } from "aws-amplify"; Amplify.configure({ aws_cognito_region: "us-east-1", aws_user_pools_id: "xxxxxxx", aws_user_pools_web_client_id: "xxxxxxx", aws_mandatory_sign_in: "enable", }); // ./components/sign-in.js try { await Auth.signIn(username, password); let user = Auth.currentUserInfo(); console.log(user); // { // "username": "...", // "attributes": { // "sub": "...", // "email_verified": true, // "phone_number_verified": true, // "phone_number": "...", // "email": "..." // } // } } catch (error) { console.log("error signing in", error); } A: You simply don't implement the front-end functionality to add a new user. Then, in your Cognito user pool config, there is an option User sign ups allowed? which you would set to Only administrators can create users. Edit: Also, consider using the hosted UI, it may save you some front-end work.
doc_23536127
my app.scss code .my-nav .toolbar .toolbar-background { background-color: blue; } how I am trying to override It in the other screen where I want it to be black home.scss .my-nav .toolbar .toolbar-background { background-color: black; } Any help would be appreciated A: The order of the imports should be as below if you are importing in an scss file @import './app' @import './home' if you are importing in a javascript file(your project must support import scss files in javascript) import './app.scss' import './home.scss' A: home.scss .my-nav .toolbar .toolbar-background { background-color: black !important; } give important to end of property automatically override other attributes
doc_23536128
I am on win 7. I have successfully setup everything using this tutorial: http://www.kgx.net.nz/2010/03/cygwin-sshd-and-windows-7/ I am up to this command: ssh-host-config ..but I receive the error in the title. I have searched google and many other places. I cannot find one instance of somebody having this problem. Any ideas? A: See http://allthingsmarked.com/2006/08/17/how-to-set-up-a-windows-ssh-server-for-vnc-tunneling/ You probably forgot to check the openssh. I forgot this when downloading to a folder using the setup. A: Don't download all the packages at once I did this and thought everything was fine until I got the same error. Just download the openssh package and make sure the X is in the box, it a big file so could take a while. A: This error can also happen if you need to add your cygwin\bin path to your windows path. If you add it to your Windows path, you might be all set. I would add it at the end so that you don't potentially mess up other Windows commands. Make sure to close all shell and Bash windows before trying again. Otherwise the change won't take effect.
doc_23536129
Axis2-web runs fine, but when I request the WSDL of my service I just get an expcetion: Caused by: java.lang.NoClassDefFoundError: javax/lang/model/element/Element at com.sun.tools.ws.processor.modeler.annotation.WebServiceWrapperGenerator.<init>(WebServiceWrapperGenerator.java:130) at com.sun.tools.ws.processor.modeler.annotation.WebServiceAp.process(WebServiceAp.java:181) at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:793) at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:722) at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1700(JavacProcessingEnvironment.java:97) at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1029) at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1163) at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1108) at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:824) at com.sun.tools.javac.main.Main.compile(Main.java:439) ... 42 more Caused by: java.lang.ClassNotFoundException: javax.lang.model.element.Element not found by com.sun.xml.bind [150] at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1460) at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72) at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 52 more Usually a NoClassDefFoundError means a dependency is missing, but 'javax.lang.model.element.Element' is from the JRE ('rt.jar') so I have no clue what is wrong here. More Details: Eclipse Juno, Glassfish 3.1.2, Axis2-1.6.2, Dynamic Web Project
doc_23536130
A: You should be able to use this snippet: ((RemoteEndpointMessageProperty)OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]).Address;
doc_23536131
For example: if I type "user" for the username and "pass" for the password the view should display "Dog, Cat, Mouse, Parrot, Goldfish" in a list. The JSON file can be modified if my syntax is incorrect. JSON: [ { "username": "user", "password": "pass", "type": "Animals", "items": ["Dog", "Cat", "Mouse", "Parrot", "Goldfish" ] }, { "username": "helloworld", "password": "firstprogram", "type": "States", "items": ["Not Running", "Inactive", "Active", "Background", "Suspended" ] }, { "username": "movielover", "password": "bestmovies", "type": "Movies", "items": ["Kill Bill", "Us", "Parasite", "Coco", "Inception" ] }, ] Swift UI Code: import SwiftUI struct LoginView: View { var userName = "user" var items: UserModel = UserModelData().userInformation[0]//this only displays data for the first item in the array, I would like to check each item,find the one that contains userName, and use that index. var body: some View{ VStack{ Text("\(items.username)'s \(items.type)") .font(.title) .fontWeight(.bold) if userName == items.username{ Form{ List(items.items, id: \.self){ item in Text(item) } } } } } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView() } } A: You can use first(where:) to find an item in your array that matches a given condition (in this case, that the user names match). It returns an optional since there's no guarantee that there will be an item that matches. I had to stub out UserModel and UserModelData since you didn't include them, so you'll need to make sure the type names match what you had. struct UserModel { var username : String var password : String var items : [String] var type: String } struct UserModelData { var userInformation : [UserModel] = [] } struct LoginView: View { var userName = "user" private var userModelData = UserModelData() var userInformation : UserModel? { userModelData.userInformation.first { $0.username == userName } } var body: some View{ VStack { if let userInformation = userInformation { Text("\(userInformation.username)'s \(userInformation.type)") .font(.title) .fontWeight(.bold) Form { List(userInformation.items, id: \.self) { item in Text(item) } } } } } } A: You can achieve this using filter: var item: UserModel = UserModelData().userInformation.filter({ $0.username == "user" && $0.password == "pass" }).first Additionally you could move this logic to the UserModelData and do something like: var serModelData = UserModelData() lazy var item: UserModel = userModelData.retrieveUserModel(for: "user", and: "pass") Where: class UserModelData { ... func retrieveUserModel(for username: String, and password: String) { userInformation .filter({ $0.username == username && $0.password == password }).first } }
doc_23536132
The PostgreSQL one starts successfully, but when the Keycloak one tries to connect to PostgreSQL returns a connection refused. I put all the environment variables to Keycloak to connect to that PostgreSQL container withEnv("DB_VENDOR", "postgres"); withEnv("DB_DATABASE", KeycloakDS); withEnv("DB_SCHEMA", test); withEnv("DB_USER", postgres); withEnv("DB_PASSWORD", keycloak); withEnv("DB_ADDR", postgres); withEnv("DB_PORT", ${DB_PORT}); withEnv("KEYCLOAK_USER", admin); withEnv("KEYCLOAK_PASSWORD", admin); where ${DB_PORT} is the port where the PostgreSQL is deployed and the DB_ADDR is the alias that PostgreSQL container has in a network that I made, where are both containers. Am I missing something? Has anyone tried too with success? Thanks in advance. A: ${DB_PORT} must be 5432, since you connect directly to the container and not through the exposed port.
doc_23536133
A: in your case it could be: class XY : Object { @Getter(fluent = true) public boolean hasObject; } OR @Accessors(fluent = true) class XY : Object { public boolean hasObject; } according to the docs: fluent - A boolean. If true, the getter for pepper is just pepper(), and the setter is pepper(T newValue). Furthermore, unless specified, chain defaults to true. Default: false. A: I found out help from lombok-how-to-customise-getter-for-boolean-object-field. By this I will be have the altering accessor level and the code getter old fashion, @Getter(AccessLevel.NONE) private boolean hasObject; public boolean hasObject() { return hasObject; } I will be keeping this question open. Is this the only way to change getter method name or I will wait for better suggestions. A: Just like this: @Data class ExampleClass { private Object data; @Accessors(fluent = true) private boolean hasObject; } This will provide getData() and hasObject() methods. A: Combining the Accessors and Getter, you might get the folllowing: class ExampleClass { @Accessors(fluent = true) @Getter private boolean hasObject; } is an equivalent to the Vanilla Java: class ExampleClass { private boolean hasObject; public hasObject() { return hasObject; } Which is what you wanted, I guess.
doc_23536134
I have used following two methods but they doesnt seem to work, input = gzopen (argv[i], "r"); Second method. arg = argv[1]; cmd = malloc(sizeof(prefix) + strlen(arg) + 1); if (!cmd) { fprintf(stderr, "%s: malloc: %s\n", argv[i], strerror(errno)); return 1; } sprintf(cmd, "%s%s", prefix, arg); input = popen(cmd, "r"); I would be grateful if anyhelp can be provided. Thank you in advance. A: I am inferring a little bit here since you don't show us the prototype of the library function you're using, but you say in a comment that this works for you when the file is uncompressed: fd = open(argv[i], O_RDONLY); but using gzopen() or popen() does not. So I gather that the library function you're using takes a file descriptor argument and reads and interprets the data itself. This leads to what your immediate problem must be-- open() returns an "int" file descriptor, but gzopen() and popen() do not. The zlib documentation defines gzopen() this way: ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); So it returns a custom 'gzFile' file descriptor type; you can't pass this to a function that plans to do read(), expecting an int file descriptor. Likewise, popen() returns a stdio FILE* file descriptor, not the int kind, and passing this to something that expects an int will also not work. So if you wanted to use zlib, you would have to use its own gzread() function and then pass the data you read to your library function through an int type descriptor, possibly through a pipe. This would be cumbersome. Your better bet might be using popen() as you tried, but use the stdio fileno() function to get the int descriptor that underlies the FILE*, and pass that to your library function. So assuming that 'prefix' in your original code was something like "gzip -dc ", a command that would stream decompressed data from your file to stdout, we could modify your code to something like this (also, you assigned arg the value 'argv[1]' but used 'argv[i]' elsewhere-- I am assuming the '1' was a typo): char *prefix, *arg, *cmd; FILE *pinput; int fd; prefix = "gzip -dc "; arg = argv[i]; cmd = malloc(strlen(prefix) + strlen(arg) + 1); if (!cmd) { fprintf(stderr, "%s: malloc: %s\n", argv[i], strerror(errno)); return 1; } sprintf(cmd, "%s%s", prefix, arg); pinput = popen(cmd, "r"); fd = fileno(pinput); Then you should be able to pass 'fd' to your library function and have it work as it did with the uncompressed data. And don't forget to free(cmd) when you're all done with it!
doc_23536135
Link to text that is distorted on windows Firefox and Windows Chrome: http://dansdemos.info/prelaunch/hitch/20140219_1735/bk_promos/mergecopy You've already invested in creating a great book... Link to sample that is supposed to have same styles, but does not distort in windows Firefox and Windows Chrome: http://dansdemos.info/prelaunch/hitch/20140219_1735/bk_promos/hammeredShitTextProblem The styles in effect are: p { color: #777777; font-size: 14px; letter-spacing: 0.1px; line-height: 23px; width: 307px; font-family: open sans,arial; } * { border: 0 none; margin: 0; outline: 0 none; padding: 0; text-align: left; } *::-moz-placeholder { color: #666666; font-size: 16px; font-weight: 300; } Any ideas on why the text is distorted in Windows only? And why it is not distorted in the sample with the same styles?
doc_23536136
After inspecting the page I see the following errors: A: Try this...and you check this also you must add check package.json and delete "test" "echo \"Error: no test specified\" && exit 1" inside "scripts" object. Let's add the start command instead. "start": "webpack-dev-server --hot" And also check your node_moduls folder, and also you must do npm install
doc_23536137
public class BusinessLogicRegex : ValidationAttribute, IClientValidatable { private const string _defaultErrorMessage = "Invalid Password. {0}"; private string _description; //Other private members ... public BusinessLogicRegex(string getMember, Type getMemberType, string descriptionMember, Type descriptionMemberType) : base(_defaultErrorMessage) { //Omitted the guts of initializing validation for brevity ... } public override string FormatErrorMessage(string name) { return String.Format(ErrorMessage, _description); } } But when FormatErrorMessage is called, ErrorMessage is null. Why doesn't this base(_defaultErrorMessage) set the ErrorMessage property and how should I set it while still giving the user of this attribute the ability to override it? Edit - 2nd, cleaner Example: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class TestValidator : ValidationAttribute { public TestValidator() : base("Test Error on {0}") { } public override string FormatErrorMessage(string name) { return String.Format(ErrorMessage, name); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } } Here again, FormatErrorMessage throws a null reference exception because ErrorMessage is null. However ErrorMessageString == "Test Error on {0}". So my mistake seems to be in thinking that calling base("Test Error on {0}") sets the ErrorMessage property. I don't understand this at all. Here how the base constructor describes its errorMessage parameter: The error message to associate with a validation control Here is what MSDN says about the ErrorMessageString property: The error message string is obtained by evaluating the ErrorMessage property or by evaluating the ErrorMessageResourceType and ErrorMessageResourceName properties. The two cases are mutually exclusive. The second case is used if you want to display a localized error message. Yet inside of FormatErrorMessage at runtime, ErrorMessage, ErrorMessageResourceType and ErrorMessageResourceName are all null. So that description makes it sound like ErrorMessageString should also be null to me. This leaves me very confused about the usage and interaction between all of these properties and the constructor. A: So I looked at the source code and I see why it's confusing. The ValidationAttribute class maintains a private _defaultErrorMessage field of its own. When I call base(errorMessage) it forwards my string as a lambda to the constructor that accepts a Func<string> errorMessageAccessor and sets that to a private _errorMessageResourceAccessor field. The ErrorMessageString getter first calls a method named SetupResourceAccessor where it determines whether to use The ErrorMessage property is supported by a private _errorMessage field that appears to only be set by the ErrorMessage property setter. If _errorMessageResourceAccessor is null (which it is not in my case because I set it in the base constructor), this method will decide whether to set _errorMessageResourceAccessor to the default error message, a localized resource message, or the ErrorMessage property. However, if it is not null, it will leave _errorMessageResourceAccessor set to its current value. This is the case I am hitting. Lastly, the ErrorMessage property is supported by an _errorMessage field which appears to only get set by the ErrorMessage setter. The getter will return the default error message if ErrorMessage has not be explicitly set. Once the setter is called, it clears _errorMessageResourceAccessor. So to try to summarize, calling ErrorMessage will give you the explicitly set error message or the default error message (which I actually don't know where it gets set. Maybe by an inheriting class?). Calling ErrorMessageString will give you a message in what looks to be the following order of presedence: * *The explicitly set ErrorMessage *Localized value from ErrorMessageResourceName if it and ErrorMessageResourceType are set *Constructor errorMessage string *Default error message if nothing else is set
doc_23536138
.table-cell-required-field { -fx-control-inner-background: -sif-required_field-color; -fx-background-color:-fx-table-cell-border-color, -fx-control-inner-background; -fx-border-color: deepskyblue deepskyblue deepskyblue deepskyblue ; -fx-background-insets: 0, 0 0 1 0; -fx-padding: 0.0em; -fx-text-fill: -fx-text-inner-color; } .table-cell-required-field:selected { -fx-background-color: -fx-focus-color, -fx-cell-focus-inner-border, -fx-focus-color; -fx-background-insets: 0, 1, 2; } This works just fine - however, when the table isn't focused, the selected field is staying -fx-focus-color rather than reverting back to the standard in modena which has it as gray - which is confusing the users. I have tried to use focus as a psuedo class as well - but looking in ScenicView both cells show both selected and focused and this has no change. Here is an example of what I need to happen when the table isn't focused: However when I select the required field and then selected the other table it stays blue - I need this to go gray when it doesn't have focus. I would appreciate any help in what I am missing. Thanks! A: Try .table-cell-required-field { -fx-control-inner-background: -sif-required_field-color; -fx-background-color:-fx-table-cell-border-color, -fx-control-inner-background; -fx-border-color: deepskyblue deepskyblue deepskyblue deepskyblue ; -fx-background-insets: 0, 0 0 1 0; -fx-padding: 0.0em; -fx-text-fill: -fx-text-inner-color; } .table-view .table-cell-required-field:selected { -fx-background-color: -fx-focus-color, -fx-cell-focus-inner-border, -fx-selection-bar-non-focused; -fx-background-insets: 0, 1, 2; } .table-view:focused .table-cell-required-field:selected { -fx-background-color: -fx-focus-color, -fx-cell-focus-inner-border, -fx-focus-color; -fx-background-insets: 0, 1, 2; } Typically for styling at this level I look at the default modena.css stylesheet, which you can extract from your jfxrt.jar file, or see at the OpenJFX source.
doc_23536139
String manipulation when given an integer parameter Python I'll explan. I have this SVG image (just an example): <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4000 4000"> <defs> <style>.cls-1{opacity:0.05;}.cls-2{opacity:0.1;}.cls-3{opacity:0.2;}.cls-4{opacity:0.08;}</style> </defs> <title>shader</title> <g id="shader"> <path class="cls-1" d="M1850,1434.82a211.94,211.94,0,0,0-49.86-12.11c-172.54-20-337.7,181.45-333.37,371.56,2.51,110,62.25,236.26,159.68,295.51-121-45.56-197-190.72-199.85-315.16C1422.3,1584.51,1587.45,1383,1760,1403.06,1792.12,1406.79,1822.38,1418,1850,1434.82Z" /> <path class="cls-1" d="M2575.47,1764.59c-.67,124.47-74.15,271-194.33,318.62,96.39-61,153.92-188.21,154.5-298.27,1-190.16-167.63-388.72-339.79-365.68a212.08,212.08,0,0,0-49.68,13c27.35-17.35,57.43-29,89.5-33.34C2407.84,1375.87,2576.48,1574.44,2575.47,1764.59Z" /> <path class="cls-2" d="M1869.31,1609a158.22,158.22,0,0,0-18.56-4.78c-98.1-19-195.56,57.9-217.67,171.85-17.27,89,16.5,174.22,78.84,216.37-87.16-28.22-139.71-129.44-119-236,22.12-114,119.58-190.89,217.68-171.85A158.2,158.2,0,0,1,1869.31,1609Z" /> <path class="cls-2" d="M2294.05,1987.37c61.58-43.24,93.85-129,75-217.7-24.1-113.55-122.89-188.78-220.64-168a156.86,156.86,0,0,0-18.48,5.11,158.48,158.48,0,0,1,58.3-25.46c97.76-20.75,196.54,54.48,220.65,168C2431.45,1855.52,2380.68,1957.62,2294.05,1987.37Z" /> <path class="cls-3" d="M2214.61,2081.59c0,74.18-105.25,164.48-213.18,165.42-117.12,1-215.68-90.36-215.68-165.63a55.33,55.33,0,0,1,1.46-12.65c39.94,53.41,121.8,99,214,98.28,85.64-.67,169.74-46.83,210.9-100.17A45.83,45.83,0,0,1,2214.61,2081.59Z" /> <path class="cls-4" d="M1097,2439.73c-83.85-36.5-164-99.38-215-176-77.46-116.54-125.85-323-16.55-426.93,45.17-43,107.55-59.14,173.62-56q-.82,10.15-1.4,20.33c-50.28,4.26-96.49,21.49-132,55.29-109.31,103.91-60.91,310.39,16.54,426.93C964.94,2347.64,1028.26,2402.24,1097,2439.73Z" /> <path class="cls-4" d="M3125.8,2259.28c-49.63,77.57-128.8,141.88-212.06,179.83,68.19-38.68,130.6-94.42,172.23-159.49,75.41-117.87,120.2-325.16,9.09-427.16-35.33-32.43-80.57-48.85-129.62-52.73q-.36-10.47-.91-20.79c64.45-3.41,125.43,11.93,170.36,53.18C3246,1934.11,3201.21,2141.4,3125.8,2259.28Z" /> <path class="cls-2" d="M2247.57,3056.69C2229,3156,2139.35,3296.86,2001.43,3298c-135,1.16-227.85-132.31-245.4-235.86a178.64,178.64,0,0,1-1.42-47.38c.3,2.46.65,4.92,1.07,7.38,17.55,103.55,110.38,237,245.4,235.86,137.92-1.18,227.6-142.05,246.14-241.34,1.07-5.76,1.87-11.52,2.38-17.35C2251.54,3019.91,2251,3038.33,2247.57,3056.69Z" /> <g class="cls-3"> <path d="M2267.51,3173.33c-11.06,5.09-30.83,7.25-66-2.54q3.45-5.48,6.65-11c24.86,7.24,42.33,8.69,54.58,7.3A52.66,52.66,0,0,0,2267.51,3173.33Z" /> <path d="M2566.83,3042.84a38.52,38.52,0,0,0,9.66-5.13,41.64,41.64,0,0,1-19.57,15.22c-29.25,10.51-62.64-17.51-63-17.8a18.94,18.94,0,0,0-19.87-2.93,19.13,19.13,0,0,1,3.08-5,18.94,18.94,0,0,1,26.7-2.14C2504.19,3025.33,2537.58,3053.35,2566.83,3042.84Z" /> <path d="M2632.39,3018.8c-6,19.09-16,34.68-28.85,45.72a105.14,105.14,0,0,0,18.94-35.63c7.32-23.08,8.67-50.8,3.61-74.15-6.17-28.49-22.66-54.2-47.68-74.34-21.8-17.55-48.41-29.47-74.94-33.58-41.18-6.37-84.4,5.86-125,35.36a247,247,0,0,0-26.12,22,250.49,250.49,0,0,1,36-32.06c40.59-29.5,83.81-41.72,125-35.36,26.53,4.11,53.14,16,74.94,33.58,25,20.14,41.51,45.85,47.69,74.34C2641.06,2968,2639.71,2995.72,2632.39,3018.8Z" /> </g> <path class="cls-1" d="M1360.7,2126.07c11.9-10.67-113.73-80.72-109.94-279,.11-5.45.07-10.91.22-16.37,8.5,180.23,141.67,258.15,141.84,277.92C1392.85,2112.33,1373.28,2120.71,1360.7,2126.07Z" /> <path class="cls-1" d="M2610.35,2101.65c-.2-23.12,135.56-86.47,140.69-279.55.35,8.32.14,16.65.54,25,9.56,197.82-123.27,264.93-110.31,278.16C2627.73,2121,2610.39,2105.61,2610.35,2101.65Z" /> <path class="cls-4" d="M2877,2377.46c0,209.25-420.37,512-840.86,524.16-461.31,13.34-910.31-319.75-910.31-497.75q0-12.16.85-23.59c25.71,181.25,461.62,494.28,909.11,481.34,410.88-11.88,821.64-301.22,840.2-509.67Q2877,2364.22,2877,2377.46Z" /> <path class="cls-4" d="M1730.65,3184.68a54.77,54.77,0,0,1-51.13,6.84c-16.08-6-29-18.39-38.52-36.88a116,116,0,0,1-11.55-36.67c-2.74-20.52,1-39.29,10.41-54.29-.07-.45-.14-.89-.19-1.35-7.55-63.51,14.39-136.94,61.84-207.16q9.77,2.91,19.62,5.67c-40.3,65.3-59.68,119-52.7,177.78,0,.46-.06-.45,0,0-9.41,15-11.81,48.57-9.07,69.09a116.08,116.08,0,0,0,11.55,36.67c9.48,18.49,22.44,30.9,38.52,36.88a54.69,54.69,0,0,0,19.13,3.46C1729.26,3184.72,1730,3184.71,1730.65,3184.68Z" /> <path class="cls-4" d="M2377.29,3113.47c-3.09,26.72-17.73,62.24-48.78,74.41a54.79,54.79,0,0,1-51.25-6c.38,0,.77,0,1.15,0a55,55,0,0,0,20-3.8c31.05-12.18,45.68-47.7,48.78-74.42,2.38-20.56-.59-54.27-10.26-69.11.06-.44,0,.46,0,0,5.81-57.38-13.43-108.74-52.78-171.85q10-2.79,20-5.76c46.28,67.88,68.24,138.92,62,201-.05.46-.11.9-.17,1.35C2375.61,3074.2,2379.68,3092.91,2377.29,3113.47Z" /> <path class="cls-4" d="M1985.53,3389.64a54.89,54.89,0,0,1-69.38,34.82c-26.37-8.75-93.26-15.62-132.68,1.84a54.92,54.92,0,0,1-77-46.67,54.85,54.85,0,0,0,71.84,26.72c39.42-17.46,106.32-10.6,132.69-1.85a54.9,54.9,0,0,0,72.06-55.64A54.7,54.7,0,0,1,1985.53,3389.64Z" /> <path class="cls-4" d="M2298.58,3378a54.86,54.86,0,0,1-76.19,48c-39.72-16.76-106.49-8.73-132.71.47a54.89,54.89,0,0,1-68.2-74.4,54.91,54.91,0,0,0,73,54.36c26.22-9.21,93-17.24,132.7-.47a54.83,54.83,0,0,0,71.37-28Z" /> <path class="cls-4" d="M2138.19,3086.24c-46.08,57.6-126.38,59.74-136.76,59.84-10.83.12-89.18-.38-134.63-57-21.19-26.39-28.4-57-27.06-94.28,1.63,28.47,9.6,52.76,26.88,74.28,45.46,56.63,123.81,57.13,134.63,57,10.38-.11,90.69-2.25,136.77-59.85,19.78-24.72,28.06-52.83,29.13-85.79C2169.07,3022.24,2161.85,3056.66,2138.19,3086.24Z" /> <path class="cls-2" d="M2750.8,1816.91c-15.74-308.51-265-613.11-481.5-613.11-155.64,0-248.88,116.58-268,116.75-22.73.2-95.64-116.75-268-116.75-218.18,0-471.06,310.31-482.1,621.74q-.78-13.72-.81-28.48c-.26-318.49,259.27-643.25,482.47-643.26,172.41,0,245.31,117,268,116.75,19.15-.17,112.39-116.75,268-116.75,223.52,0,482,324.77,482.27,643.26Q2751.16,1807.25,2750.8,1816.91Z" /> <path class="cls-2" d="M2473.67,674.35c-.15-17.72,8.93-28.23,62.15-5.43-69.23-42.34-129.15-60.54-128.88-29.37.57,65.4,174.11,150.61,135.25,190.15-47.82,48.66-143.94-40.34-539.76-11.2-533.75,39.29-964.77,540.12-966.09,1028.56-.35,129.83,38.54,280.85,111.58,425.48v0l1.29,2.52q1.86,3.66,3.74,7.3c.87-1.71,1.76-3.39,2.66-5.06l.66-1.21q2.73-5,5.66-9.77l.66-1.08q1.44-2.33,2.93-4.61l0-.08c1-1.56,2-3.09,3.1-4.61l.69-1q1.5-2.16,3-4.26l.15-.21q1.6-2.19,3.25-4.33c.25-.33.5-.66.76-1q1.5-1.95,3-3.85l.31-.39q1.65-2,3.33-4l.9-1q1.44-1.68,2.89-3.31l.61-.69c70.21-78.43,175.19-95.5,175.07-109.27,0-3.27-2.87-7.43-7.63-12.9-25.54,13.92-113.62,31-172.71,99.27-46.31-115.84-85.59-250.75-85.31-351.82,1.33-488.44,452-960.07,985.73-999.36,395.82-29.14,491.95,59.86,539.77,11.2C2661.39,829.46,2474.24,739.75,2473.67,674.35Z" /> <path class="cls-2" d="M2966.2,1847.06c1.35-482.72-270.46-754.2-640.08-890.61-86.12-31.59-74.29-16.76-109.17-28.08,398.15,129.18,710.58,402,709.16,909-.32,115-27.37,241.26-86.32,372.62-57.8-80.49-163.52-88.39-192.17-100.84-4.72,5.46-7.52,9.79-7.49,13.56.13,15.13,121.52,20.18,190.45,107h0q5.36,6.73,10.25,14.14l0,0c1.08,1.63,2.13,3.28,3.17,5l0,.08c1,1.68,2.05,3.38,3,5.1a.41.41,0,0,1,.05.09q1.5,2.6,2.93,5.26l0,.07c1,1.79,1.89,3.6,2.81,5.45l0,0q1.38,2.77,2.7,5.64c1.5-3,3-6.05,4.48-9.09h0C2929.62,2119.3,2965.85,1972.14,2966.2,1847.06Z" /> <path class="cls-2" d="M1949.22,3291.58c-.57,4.42-1.08,8.93-1.52,13.56-50.19-13.56-92.55-45.85-124.81-85.56q1.26-5.46,2.59-10.73C1857.73,3247.49,1899.7,3278.64,1949.22,3291.58Z" /> <path class="cls-2" d="M2178.62,3217.15h0c-31.79,39.62-73.27,72.47-123,86.94q-.84-6.9-1.87-13.49c49.09-13.81,90.24-45.54,122-84.13Q2177.25,3211.71,2178.62,3217.15Z" /> <path class="cls-2" d="M2194,3308c-52.67-5-105.6,3.5-136.57,13.54q-.4-4.95-.91-9.74c30.69-10.1,83.68-18.74,136.52-13.88Q2193.55,3302.92,2194,3308Z" /> <path class="cls-2" d="M1947.33,3309.2c-.28,3.2-.52,6.45-.74,9.75-31.15-9.5-84.22-17.07-136.78-11.17.23-3.4.49-6.77.78-10.09C1863.34,3291.92,1916.47,3299.63,1947.33,3309.2Z" /> <path class="cls-1" d="M1512.69,2523.35l-4.87-.57h0q-42.43-4.94-84.78-10.74c-32.77-40.15-56-82.73-67.74-125.83-8.9-32.68,14.68-60.05,47.08-55.44,5.22.73,10.43,1.47,15.65,2.19l2.44.33C1439.87,2399.23,1469.68,2463.73,1512.69,2523.35Z" /> <path class="cls-1" d="M1740.15,2712.92a810.14,810.14,0,0,1-76.37-28.11c-88-37.57-162.38-88.33-216.88-145.75q40.57,5.33,81.21,9.86l1.48.16C1582.24,2611.78,1651.21,2667.87,1740.15,2712.92Z" /> <path class="cls-1" d="M2647.24,2386.21c-11.75,43.09-35,85.68-67.74,125.83q-36.18,5-72.45,9.29l-11.58,1.37c41.19-59.77,69.41-124,87.46-189.53l3.16-.43,10.13-1.42,3.94-.55C2632.55,2326.16,2656.14,2353.53,2647.24,2386.21Z" /> <path class="cls-1" d="M2555.63,2539.06c-48.1,50.68-111.69,96.17-186.44,132a790.65,790.65,0,0,1-74.71,31.12c75.86-43.85,135.64-96,182.09-153.34l1.48-.19,7.14-.93,1.67-.19Q2521.26,2543.58,2555.63,2539.06Z" /> <path class="cls-2" d="M2304.15,2857q-39.86,11.91-80.78,20.95-8.65,1.92-17.35,3.68-25.77,5.23-51.81,9.2a972.49,972.49,0,0,1-118.06,10.79,1000.28,1000.28,0,0,1-179.37-11.42q-29-4.41-57.48-10.33c-3-.62-6-1.26-9-1.9q-45.07-9.72-88.76-22.8-8.44,12.48-15.79,25.09c30.82,9.66,62.31,18.19,94.3,25.39l.74-1.09,1.46-2.1c-.38,1.15-.75,2.3-1.11,3.43q34.26,7.68,69.24,13.27a1002.45,1002.45,0,0,0,186.06,12.46A975.24,975.24,0,0,0,2159.79,2920q33.12-5.21,65.84-12.5c1.77-.39,3.54-.78,5.3-1.19q45.21-10.26,89.19-24.13Q2312.7,2869.55,2304.15,2857Z" /> </g> <g id="outline_shader" data-name="outline+shader"> <path class="cls-2" d="M2214.79,2101.6c0,74.18-105.25,164.48-213.18,165.42-117.12,1-215.68-90.36-215.68-165.63q0-1.65.09-3.27c0-.3.06-.59.08-.89.06-.78.12-1.55.21-2.32,0-.35.1-.69.15-1s0-.41.08-.62c9.52,72.67,103.87,154.73,214.89,153.76,102.62-.89,202.81-82.57,212.43-154.36,0,.13,0,.26.08.39s0,.28.07.41a44.2,44.2,0,0,1,.66,5.1l0,.5C2214.75,2099.9,2214.79,2100.75,2214.79,2101.6Z" /> </g> In the previous question I asked about the style. in the style we have cls 1 - 4. I wanted to get an input say 5 so that in the style the cls will start from 6 until 9. Now I need that each class tag in the path will change as well. cls-1 to cls-6... cls-4 to cls-9 etc. How can one do so? Would I need to iterate over all path in the XML? Thanks. A: There is probably a parser doing the job, but by using open and re.sub, you can do: import re def increment_value_in_string (s, inc_value): return re.sub('(?<=cls-)\d*',lambda m: str(inc_value+int(m.group(0))),s) # note: '(?<=cls-)\d*' is slightly different than in my answer to your previous # question as the pattern is less restrictive # open your svg file and read svg_file = open('path_to_your_file\file.svg','r') svg_txt = svg_file.read() # increment the value after cls- by 5 increment_value = 5 svg_txt_modif = increment_value_in_string (svg_txt, increment_value) # write back to a svg file file_modif_svg = open('path_to_your_file\file_modif.svg','wb') file_modif_svg.write(svg_txt_modif) file_modif_svg.close() The file file_modif.svg has the value incremented by 5 everytime digits are after the pattern 'cls-' A: Use LXML python module to parse the SVG file. Then you can access all of the nodes and attributes quickly and easily. I do this all the time for XML, HTML, and SVG. Brute force string parsing is almost never the right way to go especially when dealing with a well formed language syntax like XML, SVG, and CSS. I'm typing on my phone so I can't provide you with any examples right now. However, rest assured that LXML is simple to use and gives you a robust solution; robust unlike any string parsing code that you hack together. Using XPath, you can easily find all of the nodes and modify their attributes. In your case: for node in doc.xpath ("//path"): node.get ("class")
doc_23536140
CSS @font-face { font-family: themify; src: url({{ asset('admin_assets/icons/themify-icons/fonts/themify.eot@-fvbane') }}); src: url({{ asset('admin_assets/icons/themify-icons/fonts/themify.eot@') }}) format("embedded-opentype"), url({{ asset('admin_assets/icons/themify-icons/fonts/themify.woff') }}) format("woff"), url({{ asset('admin_assets/icons/themify-icons/fonts/themify.ttf') }}) format("truetype"), url({{ asset('admin_assets/icons/themify-icons/fonts/themify.svg@-fvbane') }}) format("svg"); font-weight: 400; font-style: normal; } I can't seen to understand where the problem is. I looked up on the internet and many places says I also have to use {{ asset('') }} in CSS files as well. But with or without, it made no difference. A: In looking at your code above I am going make the following assumptions: * *You are including the snippet above which defines your font class and the path to the assets in a blade template file within a block and it not compiled. *You are trying to access files that located most likely within the node_modules within your app using the asset('...') helper tag. (I am guessing something like node_modules/admin_assets/icons/themify-icons/fonts/ ....) The issues as I would understand it given the assumptions above is that the helper tag asset() helper tag cannot access the node_modules in-line and the asset() serves relative from the public folder in your project. With that being said you will either need to manually copy the files where you want in the public folder and call them. You can still use the helper tag. Or, you can in your webpack.mix.js file using npm run dev to build it you can copy the files in your build from the node_modules folder with something like: const mix = require('laravel-mix'); ... mix.copy('node_modules/admin_assets/icons/themify-icons/fonts', 'public/fonts'); ... * *https://laravel.com/docs/8.x/mix#copying-files-and-directories *https://laravel.com/docs/8.x/helpers#method-asset I hope that helps and explains what is happening.
doc_23536141
I would like to know why my last example writes 0 ms: private Task<List<ACTION>> GetActions() { return Task.Factory.StartNew(() => { using (var context = new DbContext()) { return context.ACTION.ToList(); } }); } - var sw1 = new Stopwatch(); sw1.Start(); var sync1 = context.ACTION.ToList(); var sync2 = context.ACTION.ToList(); sw1.Stop(); Debug.WriteLine(sw1.ElapsedMilliseconds); //4XX MS var sw2 = new Stopwatch(); sw1.Start(); var t1 = GetActions(); var t2 = GetActions(); var tasks = new Task[] { t1, t2 }; Task.WaitAll(tasks); sw2.Stop(); Debug.WriteLine(sw2.ElapsedMilliseconds); //0 MS A: Because you start the sw1 in the second sample as well. var sw2 = new Stopwatch(); sw1.Start();
doc_23536142
So the camera table has entries id(INT) which is unique, name(VARCHAR), reviewRank(INT), price(INT), and failRate(INT). Here is an example of the TABLE setup and inserts code: CREATE TABLE CAMERA( id INTEGER, name VARCHAR(30), reviewRank INT, price INT, failRate INT, PRIMARY KEY(id))ENGINE=INNODB; INSERT INTO CAMERA VALUES(1,'Camera 1',5,100,1); INSERT INTO CAMERA VALUES(2,'Camera 2',4,300,7); INSERT INTO CAMERA VALUES(3,'Camera 3',1,10,99); INSERT INTO CAMERA VALUES(4,'Camera 4',1,10,6); Criteria is that a higher reviewRank is better, a lower price is better, and a lower failRate is better. And if multiple cameras share the best value for one of the columns then we choose the one with the best values in the other two columns or if multiple cameras have the same values in multiple columns such as CAMERA(3,'Camera 3',1,10,99) and CAMERA(4,'Camera 4',1,10,6) do then the last column determines the outcome. Basically any camera with the best value in any of the three columns automatically becomes a candidate for the list of top cameras to choose from. But if multiple cameras have the best value for the same column then we need to determine which is the best of these by looking at the values of the other columns. So using the database state above the query would return cameras (1,'Camera 1',5,100,1) and (4,'Camera 4',1,10,6) since camera id 1 has the highest reviewRank and lowest failRate and camera id 4 and camera id 3 tie for having the lowest price but camera id 4 has a lower failRate than camera id 3. So basically I am trying to figure a way to go about finding the top choices where there are multiple column comparisons using MySQL preferably using a single query if possible. My initial thoughts were something like this SELECT DISTINCT C.* FROM CAMERA C WHERE C.reviewRank>=ALL(SELECT reviewRank FROM CAMERA) OR C.price<=ALL(SELECT price FROM CAMERA) OR C.failRate<=ALL(SELECT failRate FROM CAMERA); However this is obviously wrong since it does not cover all of the possible permutations. And after doing quite a bit of searching for a way to go about this I still have no idea how to go about this. A: I believe that the ORDER BY clause accomplishes what you're looking for: SELECT topC.Id, topC.Name, topC.ReviewRank, topC.Price, topC.FailRate FROM Camera topC JOIN ( (SELECT c.ReviewRank, c.Price, c.FailRate FROM Camera c ORDER BY c.ReviewRank DESC, c.Price, c.FailRate LIMIT 1) UNION (SELECT c.ReviewRank, c.Price, c.FailRate FROM Camera c ORDER BY c.Price, c.FailRate, c.ReviewRank DESC LIMIT 1) UNION (SELECT c.ReviewRank, c.Price, c.FailRate FROM Camera c ORDER BY c.FailRate, c.Price, c.ReviewRank DESC LIMIT 1) ) values ON values.ReviewRank = topC.ReviewRank AND values.Price = topC.price AND values.FailRate = topC.FailRate
doc_23536143
i have a form that has many text boxes and combo boxes some of this controls - not all of them - can not be empty if the user click on save button i want the labels of that empty controls turns to red .... i tried if (cmbNyaba.SelectedIndex == -1) { lblNyaba.ForeColor = Color.Red; return; } else { lblNyaba.ForeColor = Color.Black; } if (txtCaseHasr.Text == "") { lblHasrNum.ForeColor = Color.Red; return; } else { lblHasrNum.ForeColor = Color.Black; } if (txtCaseNum.Text == "") { lblCaseNum.ForeColor = Color.Red; return; } else { lblCaseNum.ForeColor = Color.Black; } but i think its not a good way should i use tag property or what ? thanks i tried public static Boolean ValidateControle(Control MyObjet, int oblig = 0) { ErrorProvider err = new ErrorProvider(); String mess = ""; Boolean valid = true; if (MyObjet != null) { if (oblig == 1) { mess = "Can not be empty !"; } if (MyObjet.Text.Trim().Length == 0) valid = false; if (MyObjet is ComboBox) { ComboBox cmb = (MyObjet as ComboBox); if (cmb.SelectedIndex == -1) { mess = "Select at least one element !"; valid = false; } } if (valid == false) { err.SetError(MyObjet, mess); MyObjet.BackColor = Color.FromArgb(253, 108, 119); } else { err.SetError(MyObjet, ""); MyObjet.BackColor = Color.White; } err.SetIconAlignment(MyObjet, ErrorIconAlignment.MiddleRight); } return valid; } private void btnSave_Click(object sender, EventArgs e) { if (cmbCaseCrime.SelectedIndex == -1 || cmbMember.SelectedIndex == -1 || cmbCaseType.SelectedIndex == -1 || string.IsNullOrEmpty(txtCaseNum.Text) || string.IsNullOrEmpty(txtCaseHasr.Text)) { ValidateControle(cmbCaseCrime, 1); ValidateControle(cmbMember, 1); ValidateControle(cmbCaseType, 1); ValidateControle(txtCaseHasr, 1); ValidateControle(txtCaseNum, 1); return; } string str = btnSave.Text; switch (str) { case "add": DataTable dt = new DataTable(); dt = cs.Verify_CASES(txtCaseNum.Text, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue)); if (dt.Rows.Count > 0) { MessageBox.Show("already added ", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { ce.ADD_CASE(txtCaseNum.Text, txtCaseHasr.Text, dtp_CaseComingDate.Value, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue), Convert.ToInt32(cmbCaseStatus.SelectedValue), Convert.ToInt32(cmbCaseCrime.SelectedValue), Convert.ToInt32(cmbMember.SelectedValue), txtCaseStatusDate.Text); MessageBox.Show("added successfuly", " ", MessageBoxButtons.OK, MessageBoxIcon.Information); this.txtidCase.Text = ce.GET_LAST_CASE_ID().Rows[0][0].ToString(); this.btnAddRemain.Enabled = true; this.cmbCaseRemain.Focus(); this.btnSave.Enabled = false; } A: First you maust declare the ErrorProvider as global under form class and add a void ClearError as : public partial class Form1 : Form { ErrorProvider err = new ErrorProvider(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void ClearError() { // ErrorProvider err = new ErrorProvider(); foreach (Control cn in this.Controls) { err.SetError(cn,""); err.Clear(); cn.BackColor = Color.White; } } And you must change your btnSave_Click as : private void btnSave_Click(object sender, EventArgs e) { bool test =true ; ClearError (); // for clear all mark error in all conrols in the form test= ValidateControle(cmbCaseCrime, 1); test= ValidateControle(cmbMember, 1); test= ValidateControle(cmbCaseType, 1); test= ValidateControle(txtCaseHasr, 1); test= ValidateControle(txtCaseNum, 1); if (test ==false ) { MessageBox .Show("You have some error !"); return; } string str = btnSave.Text; switch (str) { case "add": DataTable dt = new DataTable(); dt = cs.Verify_CASES(txtCaseNum.Text, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue)); if (dt.Rows.Count > 0) { MessageBox.Show("already added ", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { ce.ADD_CASE(txtCaseNum.Text, txtCaseHasr.Text, dtp_CaseComingDate.Value, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue), Convert.ToInt32(cmbCaseStatus.SelectedValue), Convert.ToInt32(cmbCaseCrime.SelectedValue), Convert.ToInt32(cmbMember.SelectedValue), txtCaseStatusDate.Text); MessageBox.Show("added successfuly", " ", MessageBoxButtons.OK, MessageBoxIcon.Information); this.txtidCase.Text = ce.GET_LAST_CASE_ID().Rows[0][0].ToString(); this.btnAddRemain.Enabled = true; this.cmbCaseRemain.Focus(); this.btnSave.Enabled = false; } I hope that fix your issue, and please vote up the answer and mark it as solved. A: The first thing you can do is to find all controls of a given type using this.Controls.OfType<T>. For example, finding which labels are empty could look like var labels = this.Controls.OfType<Label>(); foreach(var label in labels) if(label.Text == "") //the actions you want to do. In case you have some container controls, though, you'll have to also iterate through them. The second approach you can try is using the Validating and Validated events. A: You can use this function : public static Boolean ValidateControle(Control MyObjet, int oblig=0) { ErrorProvider err=new ErrorProvider (); String mess = ""; Boolean valid = true; if (MyObjet != null) { if (oblig == 1) { mess = "Can not be empty !"; } if (MyObjet.Text.Trim().Length == 0) valid = false; if (MyObjet is ComboBox) { ComboBox cmb = (MyObjet as ComboBox); if (cmb.SelectedIndex == -1) { mess = "Select at least one element !"; valid = false; } } if (valid == false) { err.SetError(MyObjet, mess); MyObjet.BackColor = Color.FromArgb(253, 108, 119); } else { err.SetError(MyObjet, ""); MyObjet.BackColor = Color.White; } err.SetIconAlignment(MyObjet, ErrorIconAlignment.BottomRight); } return valid; } And you can use the oblig parametre to specify if control can be empty. In this call you can specefy witch controls are mandatorys with passing 1 in second parameter Call function by : ValidateControle(textBox1, 1); ValidateControle(comboBox1,1); ValidateControle(comboBox2,0); Or : foreach ( Control cn in this.Controls ) { ValidateControle(cn); } A: For that you must declare your provider in the class like: public partial class Form1 : Form { ErrorProvider err = new ErrorProvider(); public Form1() { InitializeComponent(); } For testing you must reccord or not you can do: private void button3_Click(object sender, EventArgs e) { bool test =true ; test= ValidateControle(textBox1, 1); test= ValidateControle(comboBox1,1); if (test) { //continue working and saving the record } else { //Stop and traancate recording } } For clear all error sign you can declare a void as : private void ClearError() { foreach (Control cn in this.Controls) { err.SetError(cn,""); err.Clear(); cn.BackColor = Color.White; } } you can call this function if you want clear error sign. Please if my answers are helpful for you vote up and mark it solved
doc_23536144
I'm assuming it would be something like adding an image above the navbar to show the bump but that doesn't seem right since the actual button in the navbar wouldn't extend into the curved area. Here's a link to an image of the navbar in question:
doc_23536145
I read that using Javascript/JQuery we can do that, but on googling I didn't find a simple example of doing that, any example/reference will be of great help. A: The short answer goes like this: jQuery is for DOM manipulation. Headers and footers are DOM elements. That's why you can use jQuery to create them. Something a little longer: <body> <div id='header'> </div> <div id='content'> This is where you would put all your regular content on your page, maybe if it's dynamically generated content. You just have to supply those other two divs all the time (not really - more later) </div> <div id='footer'> </div> </body> <script> //assuming you have a reference to jQuery in the header // first let's build an object. var myHeader = $('div').class('headerClassDiv').append('<div class="nestedHeaderClass" />'); $('#header').append(myHeader); // do the same for the footer: var myFooter = $('div').class('footerClassDiv').append('<div class="nestedFooterClass" />'); $('#footer').append(myFooter); </script> But this is a really contrived example. I think that you need to focus more on writing a few good webpages before you try and add content dynamically. Especially if this is your very first day. my particular advice is to use something like the Visual Studio designer environment or something similar where you can see both the HTML and the visual effect at one time and try adding elements and that you read a LOT of stuff on good HTML design. A: The code sample below shows the script to make a header and footer with Javascript. function createHeaderAndFooter() { var header="<!--header html-->"; var footer="<!--footer html-->"; document.body.innerHTML=header+document.body.innerHTML+footer; } window.addEventListener("load", createHeaderAndFooter); If you want the same header and footer across all pages, you could put the script tag below on all your pages. <script type="text/javascript src="headerFooter.js"></script> A: Actually you do not need JavaScript for footer. I had the related problem, becasue I'm working on 100% HTML site and can't include PHP footer. There have the solution to make footer including html document in html document: <object type="text/html" width=100% height="250" data="footer.html"> A: Try to use the "js-header"-package. You can create your header with a class, its super easy. By the way its using JQuery too. Look here: JS-Header package
doc_23536146
{"list_of_something":[ {"first_name": "name", "property_one": "property", "property_two": "property" }, {"first_name": "name", "property_one": "property", "property_two": "property" }, .... I want to put it in one item. I tried this if json_data.get('list_of_something'): for item in json_data['list_of_something']: resource = {"first_name": item.get('first_name'), "property_one": item.get('property_one'), } but it only collects the last entry. I want to collect it like one item "resource", that contains every thing from "list_of_something". How can i do this? UPD. I need only a few fields ,not every field from list_of_something A: if json_data.get('list_of_something'): resource = [] for item in json_data['list_of_something']: resource.append({"first_name": item.get('first_name'), "property_one": item.get('property_one'), "property_two": item.get('property_two')}) Is a resource list in that format what you're looking for ? You could simply do this: resource = json_data['list_of_something'] A: The thing you are after is already a list of the items in the result of your json.loads() operation. Your message could imply that you may want to rename the keys. You made the first key "second_name" in the second entry after the first one being "first_name". Anyway, you can do something like: resource = json_data.get('list_of_something') if resource: <rename the keys in a for loop if that is what you wanted> <do the thing to the stuff to achieve the outcome> else: <handle 'list_of_something' not being in the json> A: As per your requirement I can see that you want particular keys from the dict element in the json_data list to be present inside the dict element for the resource list. Consider keeping the required keys in a list and then iterating over it. Refer to the snippet below json_data = {"list_of_something":[ {"first_name": "name", "property_one": "property", "property_two": "property" }, {"first_name": "name", "property_one": "property", "property_two": "property" } ] } resource = [] list_of_keys_required = ["first_name", "property_one"] if json_data.get('list_of_something'): for item in json_data['list_of_something']: new_dict = {} for key,value in item.items(): if key in list_of_keys_required: new_dict[key] = value resource.append(new_dict) print(resource) The above will give you the output as [{'first_name': 'name', 'property_one': 'property'}, {'first_name': 'name', 'property_one': 'property'}]
doc_23536147
<img src={src} alt=""> is the same as: <img {src} alt=""> My question is whether there is a possibility to do the same in React.js? E.g.: <button {type}>Click me!</button> A: No, you can't do it. But you can use spread operator to pass the list props. const props = {src, type}; <button {...props}>Click me!</button>
doc_23536148
Here is my stack trace [SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0 System.Security.PermissionSet.Demand() +76 System.Data.Common.DbConnectionOptions.DemandPermission() +79 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6265031 System.Data.SqlClient.SqlConnection.Open() +258 NHibernate.Connection.DriverConnectionProvider.GetConnection() +224 NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() +30 NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) +78 NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) +149 NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) +803 NHibernate.Cfg.Configuration.BuildSessionFactory() +129 DALC.Contest.save() +128 A: Without a bit more information this sounds like a AppDomain Security issue. Here are a few links. The first is probably the one that will help you the most: System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data How to provide extra trust for an Internet Explorer hosted assembly .NET Framework Enterprise Security Policy Administration and Deployment
doc_23536149
When the application runs in VNC client viewer, the terminal windows will not be opened since the display port is not 0. In order to fix this issue, I need to know where my application is running at either on Server or Client, so I can set it to the correct display port. Thanks! Tom
doc_23536150
TID: [46] [] [2016-09-04 19:09:10,344] @tenant1.edu [46] [IS]ERROR {org.wso2.carbon.core.util.AnonymousSessionUtil} - Error occurred while getting tenant user realm for tenant id : 46 org.wso2.carbon.registry.core.exceptions.RegistryException: Error occurred while getting tenant user realm for tenant id : 46 at org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService.getUserRealm(EmbeddedRegistryService.java:441) at org.wso2.carbon.core.util.AnonymousSessionUtil.getRealmByTenantDomain(AnonymousSessionUtil.java:133) at org.wso2.carbon.core.services.authentication.AuthenticationAdmin.login(AuthenticationAdmin.java:92) at sun.reflect.GeneratedMethodAccessor108.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) Caused by: org.wso2.carbon.user.core.UserStoreException: Error occurred while getting tenant user realm for tenant id : 46 at org.wso2.carbon.user.core.common.DefaultRealmService.getTenantUserRealmInternal(DefaultRealmService.java:193) at org.wso2.carbon.user.core.common.DefaultRealmService.access$000(DefaultRealmService.java:60) at org.wso2.carbon.user.core.common.DefaultRealmService$1.run(DefaultRealmService.java:153) at org.wso2.carbon.user.core.common.DefaultRealmService$1.run(DefaultRealmService.java:150) at java.security.AccessController.doPrivileged(Native Method) at org.wso2.carbon.user.core.common.DefaultRealmService.getTenantUserRealm(DefaultRealmService.java:150) at org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService.getUserRealm(EmbeddedRegistryService.java:436) ... 67 more Caused by: org.wso2.carbon.user.core.UserStoreException: Error while reading realm configuration from file at org.wso2.carbon.user.core.config.RealmConfigXMLProcessor.buildTenantRealmConfiguration(RealmConfigXMLProcessor.java:230) at org.wso2.carbon.user.core.tenant.JDBCTenantManager.getTenant(JDBCTenantManager.java:323) at org.wso2.carbon.user.core.tenant.JDBCTenantManager.getTenant(JDBCTenantManager.java:53) at org.wso2.carbon.user.core.common.DefaultRealmService.getTenantUserRealmInternal(DefaultRealmService.java:172) ... 73 more Caused by: org.wso2.carbon.CarbonException: Error in building Document at org.wso2.carbon.utils.CarbonUtils.replaceSystemVariablesInXml(CarbonUtils.java:1082) at org.wso2.carbon.user.core.config.RealmConfigXMLProcessor.preProcessRealmConfig(RealmConfigXMLProcessor.java:241) at org.wso2.carbon.user.core.config.RealmConfigXMLProcessor.buildTenantRealmConfiguration(RealmConfigXMLProcessor.java:211) ... 76 more Caused by: java.lang.NullPointerException at org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:93) at org.wso2.carbon.utils.CarbonUtils.replaceSystemVariablesInXml(CarbonUtils.java:1078) ... 78 more TID: [46] [] [2016-09-04 19:09:10,345] @tenant1.edu [46] [IS]ERROR {org.wso2.carbon.core.services.authentication.AuthenticationAdmin} - System error while Authenticating/Authorizing User : Error occurred while getting tenant user realm for tenant id : 46 TID: [-1234] [] [2016-09-04 19:09:10,895] ERROR {org.apache.catalina.core.ApplicationDispatcher} - Servlet.service() for servlet bridgeservlet threw exception java.lang.NullPointerException TID: [-1234] [] [2016-09-04 19:09:10,896] ERROR {org.apache.tiles.servlet.context.ServletTilesRequestContext} - Servlet Exception while including path org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to compile class for JSP at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:378) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155) at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) During this time I can login to the WSO2 Administrative console using the super admin account. However, all the tenant admin logins are failing. The issue goes away once the identity server is restarted. Any help in this regard is appreciated. A: This issue is already identified with[1] and fixed for 5.2.0. Can you try with a latest pack and see if you can reproduce this? [1] https://wso2.org/jira/browse/IDENTITY-5030 [2] https://wso2.org/jenkins/view/All%20Builds/job/product-is_release-productis-5.2.0/org.wso2.is$wso2is/
doc_23536151
pod 'SnowplowTracker', '~> 1.3' However I am getting this error when I run my pod install: [!] CocoaPods could not find compatible versions for pod "SnowplowTracker": In Podfile: RNVideo (from `../node_modules/react-native-video`) was resolved to 3.9.2, which depends on MCTracker (~> 1.1.0) was resolved to 1.1.0, which depends on SnowplowTracker (= 1.1.4) SnowplowTracker (~> 1.3) Specs satisfying the `SnowplowTracker (~> 1.3), SnowplowTracker (= 1.1.4)` dependency were found, but they required a higher minimum deployment target. How can I solve this problem? Thank you
doc_23536152
const content = await axios.request(getData(id)).then(res => res.data) Where getData returns a configuration object. I am importing axios like so: import * as axios from 'axios' A: When we look at axios type definition file, we can see that it uses default export. So, instead of using import * as axios from axios, the correct way is using import for default. import axios from 'axios' axios.request({ // params }); Tested in vscode, it didn't give compile error. Hope it helps. A: @deerawan's Answer looks correct. but still you are confused you can refer axios reference page. https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index
doc_23536153
... textInputElement.onKeyDown.listen((KeyboardEvent ev) { if (new String.fromCharCode(ev.keyCode).length > 0) { callAFunction(); } }); ... (+ the same change for the onKeyUp event) When I tested this in Dartium I saw that by focusing the input element and then pressing any key, a keydown event is triggered with ev.keyCode = ev.which = 229 and ev.charCode = 0. Immediately after this event, another keydown event is triggered with the correct ev.keyCode = ev.which of the pressed key and ev.charCode = 0. I did not understand where this 229 key was coming from but I saw that it is a printable character, å. I searched the Internet and I have found that others have this issue, and sometimes they are using other programming languages and technologies. One relevant link is this and the chosen fix is in this very small commit - they chose to ignore all events which have keyCode = 229 with the explanation that recent versions of Chrome/Chromium/WebKit started to send these keydown events before every standard keyboard events, and that their meaning is that the user pressed some button. but input method is still processing that or input method editor is processing key input. My question is, is it OK to ignore keydown events with keyCode = 229 if new String.fromCharCode(229) returns the printable character "å"? I thought about the possible situation of having a real key that produces the same key code and its corresponding character. I thank you for any kind of help! A: The short answer is No. You can ignore keydown events with keyCode = 229, but only if they follow immediately after a keypress event. If you hold certain keys down, some browsers send a repeated keydown event with a keyCode value of 229, while others send the original keydown keyCode again. Some browsers send 0 as the keyCode associated with the keypress event, and place the character code in a charCode property. In all cases, as far as I can tell from my tests, the order of events is always predictable: keydown (event.keyCode = key-keyCode ex: 65 = "A") keypress (event.keyCode = 0 | character-keyCode ex: 97 = "a") - conflated model event.charCode = character-keyCode - split model keydown (event.keyCode = 229 | key-keyCode ex: 229 | 65) - may be repeated keyup (event.keyCode = key-keyCode ex: 65) The letter å is used in a number of Scandinavian languages. Here are the events received in Safari 6.1.5 when the keyboard is set to Swedish or Finnish, and the å character (to the left of the P key) is pressed: EVENT keyCode keydown 219 ("[" key position) keypress 229 (å) keydown 229 (repeatedly, indicating that the Input Monitor is busy) keyup 219 Notice that the initial keydown keyCode is 219, not 229. To generate a 229 keyCode on the initial keydown event, you can press any "dead key". On the Swedish keyboard on Mac, for example, the key immediately to the left of of the BACKSPACE key is ´ (acute accent), as used in words like déjà-vu. When you press a dead key, the character appears in the input field, but the insertion point does not move. When you subsequently type a character that can be combined with it, the browser may replace the initial dead key character with a composite character (´ + e = é) which has its own Unicode value. Here are the events that you will see in Safari 6.1.5 when the user presses and releases ´ followed by e on a Swedish keyboard: EVENT keyCode keydown 229 (dead key) keyup 187 (acute accent) keydown 229 (second key is being treated) keyup 69 ("E") Note that there are no keypress events sent at all, because there is no "é" key as such which has been pressed. If you want to determine which character the user entered, you can wait until after the second keyup, then read the character from the input field. In other words, you can ignore any keydown events with a 229 keyCode after a keypress event, but if you ignore all 229 keyCodes, you may prevent users from adding various diacritical characters. For more information on keyCode 229, from the w3.org site: keyCode property of key events
doc_23536154
The app only writes periodically some data to a file on a volume mounted to the container (defined in my docker-compose.yml) I try to use fs.writeSync and fs.writeFileSync Both ways results with correct data in the file. However, if I use the second way, docker stats have incorrect (zero) data for output (Block IO) for the container. Why? 1) const fs = require('fs') setInterval(() => fs.writeFileSync('/data/file.txt', (new Array(1024)).join('.')), 100) 2) const fs = require('fs') const fd = fs.openSync(`/data/file.txt`, 'w') setInterval(() => fs.writeSync(fd, (new Array(1024)).join('.')), 100)
doc_23536155
here is the screenshot and noticed some errors after checking the version of angular cli. When i'm trying to create a project using "ng-new my-app"(without quote) it gives me this error here is the screenshot A: You are not using the correct command name. Use: ng new my-app A: Make sure you installed Angular CLI globally: npm i -g @angular/cli Then the command ng new will be recognized in your shell. A: I have finally fixed the problem on the first screenshot, i updated my angular cli to version 6.0.1 using cmd, i was using git bash for updating my angular cli before, I think other modules was not installed globally that is why i received that error when checking the angular version. Finally no errors On the second screenshot i don't know why i could not still create a project and received that error on desktop and users folder, but i could successfully create a project in other locations like drive D:\ or E:\ using ng new command.
doc_23536156
For Table 4, make sure your program actually prints the table based on the length of the longest title. You will have to write code to find the length of the longest title, then use that number. For instance, if the data only had CS 208 and MA 311, the table would look like CS 208 Discrete Mathematics 24 MA 311 Linear Algebra 7 def BreakData(courses): #List with data in parts lis = [] # Maximum length of course title max_len = 0 for acourse in courses: #checking enrollment, check for 3, 2, 1 the enrollment lies between 1-999 if acourse[-3].isdigit(): enrollment = acourse[-3:] elif acourse[-2].isdigit(): enrollment = acourse[-2:] else: enrollment = acourse[-1] # Index till which there is course title ind = len(acourse)-len(enrollment) #Appending list #Using slicing, gives the character at index 0,1 ie index <2 lis.append((acourse[:2], acourse[2:5], acourse[5:ind], enrollment)) max_len = max(max_len, len(acourse[5:ind])) return lis, max_len def table1(courses): print("\nTable 1\n") for acourse in courses: #Printing department code and course number print(acourse[:2], acourse[2:5]) print("\n") def table2(courses): print("\nTable 2\n") # Calling BreakData function for divided data courses, max_len = BreakData(courses) for acourse in courses: # Printing allspace seperated data print(acourse[0], acourse[1], acourse[2], acourse[3]) def table3(courses): print("\nTable 3\n") # Calling BreakData function for divided data courses, max_len = BreakData(courses) total = 0 for acourse in courses: #Truncating the course tite, keeping 20 characters #If length is small, adding spaces name = (acourse[2] + " "*20)[:20] total += int(acourse[3]) print('{:<0s}{:>4s}{:>21s}{:>4s}'.format(acourse[0], acourse[1], name, acourse[3])) #Adding spaces to print total tot = " "*21 + "Total:" + " "*0 print(tot, str(total)) print("\n") def table4(courses): print("\nTable 4\n") #Sorting list courses.sort() # Calling BreakData function for divided data and max_length of course title courses, max_len = BreakData(courses) for acourse in courses: #Adding max_length spaces to make all course title length equa1=l name = (acourse[2] + " "*max_len)[:max_len] print('{:>0s}{:>4s}{:>46s}{:>4s}'.format(acourse[0], acourse[1], name, acourse[3])) def main(): courses = ['CS152Introduction to Python Programming21', 'CS369Operating Systems Administration8', 'CS352Data Structures19', 'CS208Discrete Mathematics124', 'CS319Computer Architecture14', 'MA221Calculus and Analytical Geometry for Majors I12', 'MA311Linear Algebra7', 'MA150Precalculus Mathematics27', 'CS335Introduction to Cybersecurity20', 'IS361Data Management Systems22', 'MG315Advanced Business Statistics6'] #Printing all tables table1(courses) table2(courses) table3(courses) table4(courses) #a) add a record to the list to demonstrate your code still computes a total correctly courses.append('CS377Digital Forensics17') #b) add a second record to the list to demonstrate your code still sorts the list correctly, courses.append('CS225Programming Concepts55') #c) add a third record to the list to show that your program always creates a neat table, no matter how long or short the titles are. courses.append('MA360Modern Geometries6') #Printing all tables after adding values table1(courses) table2(courses) table3(courses) table4(courses) #Calling main function main() I tried to sort but sorts by total text not text of title alone
doc_23536157
const data = [ { category: 'Techonology', subcategory: 'laptop', sale: 19000, profit: 909049, }, { category: 'Furniture', subcategory: 'badge', sale: 2009900, profit: 699600, }, { category: 'Techonology', subcategory: 'chair', sale: 30000, profit: 500, }, { category: 'Furniture', subcategory: 'bed', sale: 400, profit: 200000, }, ] The output should look like this: { "name": "data", "children": [ { "name": "Techonology", "children": [ { "name": "laptop", "children": [ { "name": "sale", "value": 19000 } ] }, { "name": "chair", "children": [ { "name": "sale", "value": 30000 } ] } ] }, { "name": "Furniture", "children": [ { "name": "badge", "children": [ { "name": "sale", "value": 2009900 } ] }, { "name": "bed", "children": [ { "name": "sale", "value": 400 } ] } ] } ] } A: I assume you get the data from some site with this structure already define and this cannot be changed. Another way I suggest you to change the structure you're getting to something more manageable. Anyway, following your structure or not, when you need to build a tree you must work recursively, to get the deepest structure and define correctly what you need. Keep in mind this: * *In your structure, you only have a subcategory per item but you can have a lot of entries with the same parent category where the only change is the subcategory element, this is not too optimal. *Since the structure becomes already defined, I think is better to treat and reorder it before arming the tree structure *To get a full example, I modified your data structure adding two children elements, because some of "subcategories" you have does not appear there. So, the structure I used was : var data1 = [ { category: 'Techonology', subcategory: 'laptop', sale: 19000, profit: 909049, }, { category: 'badge', sale: 19000, profit: 909049, }, { category: 'childrenchair', sale: 19000, profit: 909049, }, { category: 'chair', subcategory: 'childrenchair', sale: 19000, profit: 909049, }, { category: 'Furniture', subcategory: 'badge', sale: 2009900, profit: 699600, }, { category: 'Techonology', subcategory: 'chair', sale: 30000, profit: 500, }, { category: 'Furniture', subcategory: 'bed', sale: 400, profit: 200000, }, ] and the code below defines the tree structure: // loops the data to get all subcategory elements, this is used to // avoid unnecessary iterations. allChildren = data1.map(item=> item.subcategory).filter(item => !!item); // this map has the data with the structure we need preparedData = new Map() data1.forEach(item => { console.log(1, item.category, item.subcategory); const data = preparedData.get(item.category) ?? {children: []}; data.isChildren = allChildren.includes(item.category); if(item.subcategory) data.children.push(item.subcategory); preparedData.set(item.category, Object.assign(item, data)); }); tree = []; /** getChildren method is recursive, it will be called for each category or subcategory with children's (recursively) */ getChildren = item=> { const children = item.children.filter(item=> { if(!preparedData.has(item)) return; const data = preparedData.get(item); const {category: name, sale, profit} = data; subchildren = data.children.length ? getChildren(item) : []; return {name, sale, profit, children: subchildren}; }); return children; }; // loop the data preparedData.forEach(item=>{ // it the item has the property isChildren as true, then is a subcategory and // is not necessary to check it in the first level of the tree if(item.isChildren) return; const {category: name, sale, profit} = item; children = item.children.length ? getChildren(item) : []; tree.push({name, sale, profit, children}); }); I checked this code in the devtools console and runs, you can copy and pasted it to check and then make the adjusts required
doc_23536158
In this example, column a is dtype object, but the first item is string while all the others are int: import numpy as np, pandas as pd df=pd.DataFrame() df['a']=np.arange(0,9) df.iloc[0,0]='test' print(df.dtypes) print(type(df.iloc[0,0])) print(type(df.iloc[1,0])) My question is: is there a quick way to identify which columns with dtype=object contain, in fact, mixed types like above? Since pandas does not have a dtype = str, this is not immediately apparent. However, I have had situations where, importing a large csv file into pandas, I would get a warning like: sys:1: DtypeWarning: Columns (15,16) have mixed types. Specify dtype option on import or set low_memory=False Is there an easy way to replicate that and explicitly list the columns with mixed types? Or do I manually have to go through them one by one, see if I can convert them to string, etc? The background is that I am trying to export a dataframe to a Microsoft SQL Server using DataFrame.to_sql and SQLAlchemy. I get an OverflowError: int too big to convert but my dataframe does not contain columns with dtype int - only object and float64. I'm guessing this is because one of the object columns must have both strings and integers. A: Setup df = pd.DataFrame(np.ones((3, 3)), columns=list('WXY')).assign(Z='c') df.iloc[0, 0] = 'a' df.iloc[1, 2] = 'b' df W X Y Z 0 a 1.0 1 c 1 1 1.0 b c 2 1 1.0 1 c Solution Find all types and count how many unique ones per column. df.loc[:, df.applymap(type).nunique().gt(1)] W Y 0 a 1 1 1 b 2 1 1
doc_23536159
$bills = Bill::leftJoin('important_dates', 'important_dates.id', '=', 'bills.important_date_id') ->selectRaw("IF(bills.credit_card_id IS NULL AND important_dates.sent_at IS NOT NULL, important_dates.sent_at, bills.date) AS 'constructed_date'") ->havingRaw('constructed_date BETWEEN \''.$data_model['date_from'].'\' AND \''.$data_model['date_to'].'\''); If I use $bills->get() it works perfectly fine, returning what it is supposed to. But if I use $bills->count() an error is thrown with message Unknown column 'constructed_date' in 'having clause'. Does that mean that I mustn't have having clause when using ->count() function? The SQL query looks like this: select IF(bills.credit_card_id IS NULL AND important_dates.sent_at IS NOT NULL, important_dates.sent_at, bills.date) AS 'constructed_date' from bills left join important_dates on important_dates.id = bills.recipient_batch_id having constructed_date BETWEEN '2018-02-01' AND '2020-02-29' order by constructed_date asc A: Because when you using count(), laravel will use SELECT COUNT(*) to cover select IF(bills.credit_card_id IS NULL AND important_dates.sent_at IS NOT NULL, important_dates.sent_at, bills.date) AS 'constructed_date' after that, mysql cannot find the constructed_date, so the error occurs. You can use whereBetween instead of havingRaw, it can prevent SQL-injection: ->whereBetween(DB::raw('IF(bills.credit_card_id IS NULL AND important_dates.sent_at IS NOT NULL, important_dates.sent_at, bills.date)'), array($data_model['date_from'], $data_model['date_to'])) So this time you can use count(), because when it change select count(*), there is no need to use constructed_date.
doc_23536160
https://learn.microsoft.com/en-us/rest/api/compute/virtual-machines/list But I dont see it in the azure package https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/compute/arm-compute/src/computeManagementClient.ts Am I overlooking how they're translating the restful pattern to the JS SDK? A: They do! I don't know why I didn't see it in that file, but my VScode autocomplete (their package is well typed) showed what I'm looking for: const result = await this.ComputeManagementClient.virtualMachines.list('testing_group') A: They do list the VM //this is used to list all the VM's const vm_list = await compute_client.virtualMachines.listAll(); //this is used to list the VM const vm_list = await compute_client.virtualMachines.list();
doc_23536161
Currently my code in the view is: %td= collection_select(:schedule, "subject_id[#{i}]", Subject.all, :id, :prefix, prompt: true) %td= grouped_collection_select(:schedule, "course_ids[#{i}]", Subject.all, :courses, :prefix, :id, :coursetitle, prompt: true) The grouped collection select has everything separated by subject perfectly, but I would like it to hide all the other subjects' values so that only the subject selected in collection select show. I did see a video utilizing javascript that did this, but it was a much older version of Rails and no longer works. Thanks in advance for your help!
doc_23536162
This works fine: require_once("PHPMailer_Loader.php"); use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; SendEmailWindows("foo@bar.com", "smtp test", "test body"); function SendEmailWindows($emailTo, $subject, $body){ $mail = new PHPMailer; [... all the rest of the function code] } Yet when I try to move those 2 use statements into my PHPMailer_Loader.php script (placed at the very bottom of the file), it breaks with this error: Fatal error: Class 'PHPMailer' not found in [...]\EmailTester.php on line 12 Just for tidyness and compactness I'd like to move everything into the include except for the function and the calling line. A: The PHP manual is saying this: The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. [...] Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules. The "Importing rules are per file basis" part being the important one here. You can use PHPMailer\PHPMailer\PHPMailer in your include file, but that only means that PHPMailer (without having to specify the full class name) will be available inside your include file and not in the parent file (the one which includes your include file). tl;dr You need to specify your use ...; statements in every file you want that specific use to apply.
doc_23536163
router.post('/register', [ check('email').custom((value, {req}) => { return new Promise((resolve, reject) => { Users.findOne({email:req.body.email}, function(err, user){ if(err) { reject(new Error('Server Error')) } if(Boolean(user)) { reject(new Error('E-mail already in use')) } resolve(true) }); }); }) ] .... How would i pass Users? A: express-validator is only aware of the request object itself, what keeps its complexity pretty low for the end-user. More importantly, it only truly knows about the request's input locations -- body, cookies, headers, query and params. Your custom validator is completely correct. That being said, it might not be testable, as you seem to be depending on global context. In order to make it testable, the 2 options that I see are: 1. Inject req.Users: This one would involve using some middleware that sets your store objects onto req: // Validator definition const emailValidator = (value, { req }) => { return req.Users.findOne({ email: value }).then(...); } // In production code // Sets req.Users, req.ToDo, req.YourOtherBusinessNeed app.use(myObjectsStore.middleware); app.post('/users', check('email').custom(emailValidator)); // In tests req = { Users: MockedUsersObject }; expect(emailValidator('foo@bar.com', { req })).rejects.toThrow('email exists'); 2. Write a factory function that returns an instance of your validator: This is my preferred solution, as it doesn't involve using the request object anymore. // Validator definition const createEmailValidator = Users => value => { return Users.findOne({ email: value }).then(...); }; // In production code app.post('/users', [ check('email').custom(createEmailValidator(myObjectsStore.Users)), ]); // Or in tests expect(createEmailValidator(MockedUsersObject)('foo@bar.com')).rejects.toThrow('email exists'); Hope this helps! A: Converting my comments into a final, conclusive answer here : A validator is simply supposed to validate the fields of request entities against the given criteria of data type / length / pattern. You would need to write the method yourself, to determine if the user pre-exists or not. An express-validator ( or rather any validator ) would not do the task of cherry picking if the item exists in your list of items ( or your data-source), neither should it interact with the data-source concerned.
doc_23536164
import netCDF4 as nc import numpy as np import matplotlib.pyplot as plt import csv as cs import pandas as pd ncfile = nc.Dataset('C:\Users\mmso2\Google Drive\ENVI_I-PAC_2007_10_21_21_22_47.nc')#office machine SARwind = ncfile.variables['sar_wind'] ModelWind = ncfile.variables['model_speed'] LON = ncfile.variables['longitude'] LAT = ncfile.variables['latitude'] LandMask = ncfile.variables['mask'] #clean the data of values = 70 SARwind_nan = SARwind[:].copy() SARwind_nan[SARwind_nan == 0.0] = np.nan SARwind_nan[SARwind_nan == 70.0] = np.nan #clear the data of values where there is land # % pos = land; neg = water LandMask_NaN = LandMask[:].copy() #LandMask_NaN[int(float(LandMask_NaN))]### will not convert LandMask_NaN[LandMask_NaN >0.0] = np.nan #error here The error I get is #error line 37, in <module> LandMask_NaN[LandMask_NaN >= 0.0] = np.nan ValueError: cannot convert float NaN to integer When trying LandMask_NaN[int(float(LandMask_NaN))] or LandMask_NaN[float(int(LandMask_NaN))] before trying to convert to NaN, I get TypeError: only length-1 arrays can be converted to Python scalars When checking for the type of LandMask I get <type 'netCDF4._netCDF4.Variable'> I am not sure how to find out the variable type? Update: Details of nc variables NetCDF dimension information: Name: x size: 848 type: WARNING: x does not contain variable attributes Name: y size: 972 type: WARNING: y does not contain variable attributes Name: xfit size: 6 type: WARNING: xfit does not contain variable attributes NetCDF variable information: Name: acquisition_time dimensions: () size: 1.0 type: dtype('float64') units: u'seconds since 2000-01-01 00:00:00' long_name: u'Acqusition time in Julian seconds since 2000-01-01T00:00:00Z' standard_name: u'time' calendar: u'gregorian' Name: nx dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of elements in this file' Name: ny dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of lines in this file' Name: nx0 dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of elements in SIO file' Name: ny0 dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of lines in SIO file' Name: nx00 dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of elements in original SAR file' Name: ny00 dimensions: () size: 1.0 type: dtype('int32') units: u'1' long_name: u'Number of lines in original SAR file' Name: xn dimensions: () size: 1.0 type: dtype('float32') units: u'1' long_name: u'1' Name: yn dimensions: () size: 1.0 type: dtype('float32') units: u'1' long_name: u'1' Name: line_size dimensions: () size: 1.0 type: dtype('float32') units: u'm' long_name: u'Line size' Name: pixel_size dimensions: () size: 1.0 type: dtype('float32') units: u'm' long_name: u'Pixel size' Name: model_time_js dimensions: () size: 1.0 type: dtype('float64') units: u'seconds since 2000-01-01 00:00:00' long_name: u'Model time julian seconds since 2000-01-01T00:00:00Z' Name: model_time_js_tau dimensions: () size: 1.0 type: dtype('float64') units: u'seconds since 2000-01-01 00:00:00' long_name: u'Model time plus tau julian seconds since 2000-01-01T00:00:00Z' Name: upper_left_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: upper_right_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: upper_left_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: upper_right_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: start_center_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: start_center_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: scene_center_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: scene_center_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: lower_left_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: lower_right_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: lower_left_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: lower_right_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: end_center_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: end_center_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: northernmost_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: southernmost_latitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_north' long_name: u'degrees' Name: easternmost_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: westernmost_longitude dimensions: () size: 1.0 type: dtype('float32') units: u'degrees_east' long_name: u'degrees' Name: nrcs_slope dimensions: () size: 1.0 type: dtype('float32') Name: nrcs_bias dimensions: () size: 1.0 type: dtype('float32') Name: sigma dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'1' long_name: u'Normalized Radar Cross Section.' coordinates: u'longitude latitude' Name: sar_wind dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'm s-1' long_name: u'SAR-derived wind speed at 10-m height neutral stability' standard_name: u'wind_speed' coordinates: u'longitude latitude' Name: input_dir dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'degrees' long_name: u'Interpolated directions used for wind inversion' coordinates: u'longitude latitude' Name: model_speed dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'm s-1' long_name: u'Interpolated model wind speed (=1 for non model directions)' standard_name: u'wind_speed' coordinates: u'longitude latitude' Name: mask dimensions: (u'y', u'x') size: 824256 type: dtype('int16') units: u'1' long_name: u'Interpolated land mask distance from shore line. Positive values land / Negative value water' flag_values: array([-1, 0, 1], dtype=int16) flag_meanings: u'water shore land' coordinates: u'longitude latitude' Name: longitude dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'degrees_east' long_name: u'Longitude array in decimal degrees' standard_name: u'longitude' Name: latitude dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'degrees_north' long_name: u'Latitude array in decimal degrees' standard_name: u'latitude' Name: rlook dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'degrees' long_name: u'Radar look direction array in decimal degrees from North' coordinates: u'longitude latitude' Name: incid dimensions: (u'y', u'x') size: 824256 type: dtype('float32') units: u'degrees' long_name: u'Incident angle array in degrees from nadir' coordinates: u'longitude latitude' Name: icemask dimensions: (u'y', u'x') size: 824256 type: dtype('int16') units: u'1' long_name: u'Ice mask 0=no_data 1=water 2=land 3=sea_ice 4=snow' flag_values: array([0, 1, 2, 3, 4], dtype=int16) flag_meanings: u'no_data water land sea_ice snow' coordinates: u'longitude latitude' Name: lon_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute longitude in degs from pixel/lines' Name: lon_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Longitude pixel exponents' Name: lon_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Longitude line exponents' Name: lat_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute latitude in degs from pixel/lines' Name: lat_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Latitude pixel exponents' Name: lat_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Latitude line exponents' Name: i_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute pixel from longitue/latitude' Name: i_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Pixel longitude exponents' Name: i_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Pixel latitude exponents' Name: j_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute line from longitue/latitude' Name: j_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Line longitude exponents' Name: j_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Line latitude exponents' Name: incid_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute incid in degs from pixel/lines' Name: incid_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Incid pixel exponents' Name: incid_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Incid line exponents' Name: rlook_coef dimensions: (u'xfit',) size: 6 type: dtype('float64') units: u'1' long_name: u'Coefficients to compute radar look direction in degs from pixel/lines' Name: rlook_xexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Radar look direction pixel exponents' Name: rlook_yexp dimensions: (u'xfit',) size: 6 type: dtype('float32') units: u'1' long_name: u'Radar look direction line exponents' A: It'll be helpful if you share the netcdf file, but here are a few ideas of what's going on: Variables are not currently being read-in as numpy arrays. You need to add indexing parameters to cast them to arrays. Without the file, I'm not sure what they are, but surely some are multi-dimensional. For example: SARwind = ncfile.variables['sar_wind'][:,:] ModelWind = ncfile.variables['model_speed'][:,:] LON = ncfile.variables['longitude'][:] LAT = ncfile.variables['latitude'][:] LandMask = ncfile.variables['mask'][:,:] Then you can simply assign SARwind to a new variable SARWind_nan and input nan values as you have been doing. SARWind_nan = SARwind SARwind_nan[SARwind_nan == 0.0] = np.nan SARwind_nan[SARwind_nan == 70.0] = np.nan With LandMask properly read-in (again, I think this is very likely 2D, not 1D as you have), you can similarly assign to a new variable LandMask_nan and input nan values. Double check the type of LandMask, it's possibly an integer. ncdump or ncks are good tools for examining netcdf contents. LandMask_NaN = LandMask LandMask_NaN[LandMask_NaN > 0.0] = np.nan
doc_23536165
NSString *htmlString = [NSString stringWithFormat:@"<html><head> <meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = %@\"/></head> <body style=\"background:#F00;margin-top:0px;margin-left:0px\"> <div><object width=\"%@\" height=\"%@\"> <param name=\"movie\" value=\"%@\"></param> <param name=\"wmode\" value=\"transparent\"></param> <embed src=\"%@\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"%@\" height=\"%@\"></embed> </object></div></body></html>",@"320",@"320",@"460",self.videoURL,self.videoURL,@"320",@"460"]; Now, when the frame is of dimensions 320x460, it works fine. But on changing the orientation, I need the iframe to resize to 480x300. But that will be possible if I load the html string in my webview again after changing dimensions, which will cause the video to start loading again, which is not I want. I want the video to resume from the point upto which it has been played back. How do I accomplish this? A: // Most important use video tag in html to play that video then and then only following trick works or you can achieve same by using some youtube api for IOS when you change orientation of device call Javascript method which pause current video and call method which returns current playback time of video store that time in variable. when change in orientation completes load html string with width and height attribute set for video tag according to your requirement and call javascript code which starts playing that video from the last playback time which you have stored in variable. // Take help of w3schools website for javascript code and HTML related stuff. and search for how to call javascript from objective c and vice-verse and also search for youtube apis for controlling video from webview of IOS. you will defiantly get solution. i have done similar thing in one of my project successfully. All the best.
doc_23536166
def func(arg): if arg in precomputed: return precomputed[arg] else: return expensive_function(arg) Now it would be a bit cleaner if I could do something like this using dict.get() default values: def func(arg): return precomputed.get(arg, expensive_function(arg)) The problem is, expensive_function() runs regardless of whether precomputed.get() succeeds, so we get all of the fat for none of the flavor. Is there a way I can defer the call to expensive_function() here so it is only called if precomputed_get() fails? A: If it's cleanliness you are looking for, I suggest using library rather than reinventing the wheel: from functools import lru_cache @lru_cache def expensive_function(arg): # do expensive thing pass Now all calls to expensive_function are memoised, and you can call it without dealing with cache yourself. (If you are worried about memory consumption, you can even limit the cache size.) To answer the literal question, Python has no way of creating functions or macros that lazily evaluate their parameters, like Haskell or Scheme do. The only way to defer calculation in Python is to wrap it in a function or a generator. It would be less, not more, readable than your original code. A: def func(arg): result = precomputed[arg] if arg in precomputed else expensive_function(arg) return result
doc_23536167
<div class="col-lg-8 col-xs-12" style="background-color:#F30;height:150px;">Second Section</div> <div class="col-lg-4 col-xs-12" style="background-color:#F90;height:150px;">Third Column</div> <div class="col-lg-8 col-xs-12 col-xs-pu11-12"style="background-color:#CF0;height:150px;">Fourth Column</div> On mobile view I want the Fourth column should appear on top and Column first should appear at last A: Assuming you're using the latest version of Bootstrap, you can use the "push" and "pull" modifier classes, like so: <div class="row"> <div class="col-md-9 col-md-push-3"> ... </div> <div class="col-md-3 col-md-pull-9"> ... </div> </div> Resources: * *http://www.getbootstrap.com/css/#grid-column-ordering
doc_23536168
$("#first_name").change(function() { $('.showvalue').text("First Name Successfully Updated."); }); $("#last_name").change(function() { $('.showvalue').text("last Name Successfully Updated."); }); A: This will show "First Name Successfully Updated." for the first name and "Last Name Successfully Updated." for the last name: var names = ['First', 'Last']; for (var i = 0; i < names.length; i++) { var name = names[i]; $("#" + name.toLowerCase() + "_name").change(function() { $('.showvalue').text(name + " Name Successfully Updated."); }); } So this keeps your capitalization of the field names. This solution is also easy to extend with more fields. A: Combine the selectors and then in event handler check the id in order to determine which message to use: $("#first_name, #last_name").change(function() { var prefix = this.id === 'first_name' ? 'First' :'Last'; $('.showvalue').text( prefix + " Name Successfully Updated."); }); A: You may reusing the same function in javascript for elements using CLASS selector (example class: changeTrigger). <p>First Name <input type="text" id="first_name" class="changeTrigger" data-ref="First Name"/></p> <p>Last Name <input type="text" id="last_name" class="changeTrigger" data-ref="Last Name"/></p> <p class='showvalue'></p> Second, define a function to handle multi elements in same CLASS $(".changeTrigger").change(function(){ //You may use data-ref to attach "FIELD NAME" on element. var refName = $(this).data("ref"); $('.showvalue').text(refName + " Successfully Updated."); }); https://jsfiddle.net/u3f8505q/
doc_23536169
What I want to do: * *[In C#] Read variable from graphic memory to cpu memory *[In C#] Set variable to zero *[In C#] Execute normal drawing of my scene *[In Shader] One of the fragment passes writes something to the variable (UPDATE) *Restart the loop (UPDATE) I pass the current mouse coordinates to the fragment shader with uniform variables. The fragment shader then checks if it is the corresponding pixel. If yes it writes a certain color for colorpicking into the variable. The reason I dont write to a FS output is that I simply didn't find any solution on the internet on how to get this output into my normal memory. Additionaly i would have an output for each pixel instead of one What I want is basically a uniform variable that a shader can write to. Is there any kind of variable/object that fits my needs and if so how performant will it be? A: A "uniform" that your shader can write to is the wrong term. Uniform means uniform (as in the same value everywhere). If a specific shader invocation is changing the value, it is not uniform anymore. You can use atomic counters for this sort of thing; increment the counter for every test that passes and later check for non-zero state. This is vastly simpler than setting up a general-purpose Shader Storage Buffer Object and then worrying about making memory access to it coherent. Occlusion queries are also available for older hardware. They work surprisingly similarly to atomic counters, where you can (very roughly) count the number of fragments that pass a depth test. Do not count on its accuracy, use discard in your fragment shader for any pixel that does not pass your test condition and then test for a non-zero fragment count in the query readback. As for performance, as long as you can deal with a couple frames worth of latency between issuing a command and later using the result, you should be fine. If you try to use either, an atomic counter or an occlusion query and read-back the result during the same frame, you will stall the pipeline and eliminate CPU/GPU parallelism. I would suggest inserting a fence sync object in the command stream and then checking the status of the fence once per-frame before attempting to read results back. This will prevent stalling.
doc_23536170
userid1_userid2/image.bmp OR userid2_userid1/image.bmp How do I grant access to those images only to users with userid1 or userid2? I tried several things but the documentation is not really clear to me. A: Solved by using these rules: service firebase.storage { match /b/{bucket}/o { match /{path}/{spath} { allow read,write: if path[0:28] == request.auth.uid || path[29:57] == request.auth.uid; } } }
doc_23536171
For example if file contains 12 10 10 should be the value on index 12. How can I do that in Java? A: To store in an array is not a good idea as you don’t know what would be the largest index in a given file and you would end up with ArrayIndexOutOfBoundException. Use HashMap<Integer, Integer> to store the data from the file. First integer will be the key & second integer will be the value of that key. I would suggest you read about Maps in java first and implement it yourself. :)
doc_23536172
I was able to flash my Nexbox A95X (s905x) 2Gb Ram 8gb storage once yesterday. The next day I tried to flash my second box which is a 2gb Ram 16gb storage same model. But before I plug in the box by USB transfer cable, I have to import the .img firmware file into the USB burning tool program. When I import any .img file into the USB Tool program, it closes with a pop up that basically says Fatal error, please check crash.dmp. Here is my crash.dmp file which can be downloaded here: http://s000.tinyupload.com/index.php?file_id=05475691369172656462 I always install the USB burning tool as administrator and run it as administrator. I tried installing a newer version of the USB burning tool program on top of the current installation. I uninstalled the USB burning tool and the libusb driver it installed. Then I used ccleaner to clear the cache and fix the registries. I even tried uninstalling the USB burning tool with Revo uninstaller in advanced mode and it deleted all related files and registries using revo uninstaller. I tried deleting the log file. Nothing I have done has fixed it. Can any of you please tell me what else I can try? A: Never mind. I fixed it by doing this: * *uninstall usb burning tool *delete Amlogic folder in c:/Program Files (x86)/ *delete Amlogic Inc. in regedit HKEY_CURRENT_USER/Software
doc_23536173
Since the fragment creation chain (onCreate(), onCreateView() etc) are called in a different thread than the onPostNetworkRequestWithCode() which repaints the views, I am having a race condition sometimes when the onPostNetworkRequestWithCode() method does not find a view to paint. How can I ask it to wait till the view creation is done and then resume post that? public class MeStatsTableFragment extends Fragment implements HttpResponseHandlerWithResponseCode { private static final String LINKED_USER_ID = "linkedUserId"; private Context mContext; public MeStatsTableFragment() { // Required empty public constructor } public static MeStatsTableFragment newInstance(long linkedUserId, Context context) { MeStatsTableFragment fragment = new MeStatsTableFragment(); Bundle args = new Bundle(); args.putLong(LINKED_USER_ID, linkedUserId); fragment.setArguments(args); fragment.mContext = context; return fragment; } /** * This is responsible for painting the chart after data is obtained by parent Me Fragment */ @Override public void onPostNetworkRequestWithCode(HttpResponseCode responseCode) { long linkedUserId = getArguments().getLong(LINKED_USER_ID); MePageInfo m = App.getAppData().getMePageInfoById(linkedUserId); View v = getView(); if (v == null) { Log.d("XXX", "Stats fragment Got stuck at view == null in Stats Fragment"); // do nothing else, just return } else{ v.findViewById(R.id.text_name).setText(m.name); // do other painting similarly with the view and the variable m } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_me_stats_table, container, false); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } } A: You could use greenrobot EventBus (https://github.com/greenrobot/EventBus) - and make a sticky post, in a case when there is no fragment yet. Here is more info about sticky post and register - https://github.com/greenrobot/EventBus/blob/master/HOWTO.md#sticky-events
doc_23536174
console.log("Caller Function Name"+arguments.callee.caller.name); A: You can override qInstallMessageHandler default function and provide your custom function which also prints line number / caller. You can find an example in the linked documentation. Another partial example: void loggingMessageHandler(QtMsgType type, const QMessageLogContext & context, const QString & msg) { QString timeStr(QDateTime::currentDateTime().toString("dd-MM-yy HH:mm:ss:zzz")); QString contextString(QString("[%1 %2]").arg(context.file).arg(context.line)); mutex.lock(); QString level; if(logFile.isOpen()) { switch (type) { case QtInfoMsg: level = QString("INF"); break; case QtDebugMsg: level = QString("DEB"); break; case QtWarningMsg: level = QString("WAR"); break; case QtCriticalMsg: level = QString("CRT"); break; case QtFatalMsg: level = QString("FTL"); break; } QTextStream stream(&logFile); stream << timeStr << " " << contextString << "\t" << level << "\t" << msg << endl; stream.flush(); } #if defined(Q_OS_WIN) OutputDebugString(reinterpret_cast<const wchar_t *>(level.append(' ' + msg + '\n').utf16())); #elif defined(Q_OS_ANDROID) android_default_message_handler(type, context, level.append(" " + msg)); #else // MACX || IOS || LINUX fprintf(stderr, "%s\n", level.append(" " + msg).toLocal8Bit().constData()); #endif mutex.unlock(); } If logFile is open, logging data is wrote to that in a critical section delimited by a QMutex otherwise it is simply output to the standard output of each platform. Whatever is the handler you define, it can be combined with categorized logging (available since Qt 5.2) to easily setup a custom logging facility tailored on your needs. You just need to define your logging categories, as described in this blog post, and call qCDebug, qCInfo(), qCWarning() and so on. Depending on the active categories (set via the static function setFilterRules() of QLoggingCategory) different logging info can be printed or skipped. That's especially interesting now that Qt 5.8 is available. Since this release, you can use categories also in QML, i.e. you can call console functions and pass along a category, e.g. function myFancyFunction() { // foo code console.log(myFancyCategory, "message"); // bar code } Also, categories declaration can be done fully in QML via the ad hoc type LoggingCategory. ADDENDUM (Qt < 5.0) The proposed solution works in a Qt 5.0+ environment with categories fully usable with Qt 5.3+ and QML categories available in Qt 5.8+; in a Qt 4.x environment you should override qInstallMsgHandler but you do not have a QMessageLogContext. That means you should manage file/line info outside the handler, e.g. you have to use Q_FUNC_INFO or rely on __FILE__ and __LINE__ in C++ (note that the latters have been removed in latest 5.x releases as e.g. discussed here).
doc_23536175
Each line represent a row in the data base and there are 500-1000 rows to be inserted at a time. Is is better to insert the data in the database directly by calling store procedure(the procedure contain the logic to call log file and insert data) OR Is it better to parse it in the application and insert data. 29 2011-02-01 11:00:40 1 0 1 0 30 2011-02-01 11:00:44 1 0 1 0 32 2011-02-01 11:00:49 1 0 1 0 A: This is probably .tsv format (tab separated values). LOAD DATA LOCAL INFILE 'uniq.csv' INTO TABLE tbl FIELDS TERMINATED BY '\t' ENCLOSED BY '' LINES TERMINATED BY '\n' (column1, column2, column3) \t is tab character. Change it for space if it doesnt work. Manual processing row after row will be not efficient, because hard disk will be accessed many times when you try to read row by row. LOAD command should read whole file at once. You should remember, that indexes can seriously slow down inserts like this. If you need to read a lot of data (100000 rows for example) - sometimes its better to drop index, insert, and re-create index after inserting. A: You could alternatively use BCP (Bulk copy) command. Import this log file in excel and save it as csv with separate column names. Use the following syntax to import into tables in cmd prompt. go to $\Program Files\Microsoft SQL Server\100\Tools\Binn in cmd prompt bcp in TableName "D:\logs\log.csv" -c -S Servername -U username -P password -t "," -r "\n" you can alternatively specify -n instead of -c... -t :- comma seperated, -r :- Row terminator A: It is better (for performance) to insert data in bulk (using the LOAD FROM, or transactions. I am assuming store does something similar), than to insert them one at a time with a query per row.
doc_23536176
struct hashElem { int freq; int error; }; //basically this function adds some value to to the error field of each element struct hashErrorAdd{ const int error; hashErrorAdd(int _error): error(_error){} __host__ __device__ struct hashElem operator()(const hashElem& o1,const int& o2) { struct hashElem o3; o3.freq = o1.freq; o3.error = o1.error + (NUM_OF_HASH_TABLE-o2)*error; //NUM_OF_HASH_TABLE is a constant return o3; } }; struct hashElem freqError[SIZE_OF_HASH_TABLE*NUM_OF_HASH_TABLE]; int count[SIZE_OF_HASH_TABLE*NUM_OF_HASH_TABLE]; thrust::device_ptr<struct hashElem> d_freqError(freqError); thrust::device_ptr<int> d_count(count); thrust::transform(thrust::device,d_freqError,d_freqError+new_length,d_count,hashErrorAdd(perThreadLoad)); //new_length is a constant This code on compilation gives the following error: error: function "hashErrorAdd::operator()" cannot be called with the given argument list argument types are: (hashElem) object type is: hashErrorAdd Please can anybody explain to me why I am getting this error? and how I can resolve it. Please comment in case I am not able to explain the problem clearly. Thankyou. A: It appears that you want to pass two input vectors to thrust::transform and then do an in-place transform (i.e. no output vector is specified). There is no such incarnation of thrust::transform Since you have passed: thrust::transform(vector_first, vector_last, vector_first, operator); The closest matching prototype is a version of transform that takes one input vector and creates one output vector. In that case, you would need to pass a unary op that takes the input vector type (hashElem) only as an argument, and returns a type appropriate for the output vector, which is int in this case, i.e. as you have written it (not as your intent). Your operator() does not do that, and it cannot be called with the arguments that thrust is expecting to pass to it. As I see it, you have a couple options: * *You could switch to the version of transform that takes two input vectors and produces one output vector, and create a binary op as functor. *You could zip together your two input vectors, and do an in-place transform if that is what you want. Your functor would then be a unary op, but it would take as argument whatever tuple was created from dereferencing the input vector, and it would have to return or modify the same kind of tuple. As an aside, your method of creating device pointers directly from host arrays looks broken to me. You may wish to review the thrust quick start guide.
doc_23536177
I tried assigning the enterprise app owner using graph API, output shows success. unfortunately from GUI my user is still not an owner of that app. I guess this issue is with the role I got for the user. Any input to solve this issue? A: I tried adding owner to a enterprise application using the below API for a owner where the user doesn't even have the Application Developer Role assigned to it . https://graph.microsoft.com/beta/servicePrincipals/{SPobjectid}/owners/$ref Request Body: { "@odata.id":"https://graph.microsoft.com/v1.0/directoryObjects/userobjectId" } Note: It was also the same if I assigned the user Application Developer as a Active assignment in assigned roles. If you are using the below API then the user will be added to owners section in the App registration blade: https://graph.microsoft.com/v1.0/applications/appregobjectId/owners/$ref Request Body: { "@odata.id":"https://graph.microsoft.com/v1.0/directoryObjects/userobjectId" }
doc_23536178
before function test () { return 'test' ; } after function test() { return 'test'; } A: At the moment it's formatted to: function test() { return 'test'; } As I can see the only problem is with the number of spaces after return. I've created a new issue for it, please star/vote. If you find other cases where formatting doesn't work as expected, feel free to report them directly to YouTrack.
doc_23536179
jdk.nashorn.api.scripting.NashornScriptEngine scriptEngine =(NashornScriptEngine) factory.getEngineByName("nashorn"); ScriptContext context = scriptEngine.getContext(); Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("x","Guest"); engine.eval("Hello, ${x}",context); But I'm getting javax.script.ScriptException. Is Sttring interpolation supported? Thanks A: There are two things worth mentioning: * *if you want to evaluate Groovy script, you might need to use new ScriptEngineManager().getEngineByExtension("groovy"); *the script passed to engine.eval() method has to be a valid Groovy code. The script code you passed to the eval method is not a valid Groovy code - you expect to interpolate a string, but you didn't put it inside the double quotes. Consider the following example: ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("groovy"); ScriptContext context = engine.getContext(); Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("x","Guest"); Object result = engine.eval("\"Hello, ${x}\"", context); System.out.println(result); The output: Hello, Guest Alternatively, you may pass a Groovy script that prints the interpolated script. In this case the code may look like this: ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("groovy"); ScriptContext context = engine.getContext(); Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("x","Guest"); engine.eval("println \"Hello, ${x}\"", context); It produces the same output, but does not assign Hello, Guest to a variable.
doc_23536180
I have a main component that controls state. It has all of the functions to update state and passes these down to child components via props. I've simplified the code to focus on one of these functions. Here's the component now, all works as it should: ManageMenu.js import React from 'react' class ManageMenu extends React.Component { constructor() { super() this.toggleEditing = this.toggleEditing.bind(this) // Set initial state this.state = { menuSections: [] } } toggleEditing(id) { const menuSections = this.state.menuSections menuSections.map(key => (key.id === id ? key.details.editing = id : '')) this.setState({ menuSections }) } render() { return ( ... ) } } export default ManageMenu The toggleEditing is passed via props to a child component that uses it to render an editing form if the edit button is clicked. I have about 10 of these different functions in this component and what I would like to do is move them to an external lib/methods.js file and then reference them. Below is the code I would like to have, or something similar, but React doesn't like what I'm doing. Throws a syntax error: Failed to compile. Error in ./src/components/ManageMenu.js Syntax error: Unexpected token toggleEditing(id, menuSectionId, this.state, this) Here is what I would like to do... lib/methods.js const toggleEditing = function(id, state, that) { const menuSections = state.menuSections menuSections.map(key => (key.id === id ? key.details.editing = id : '')) that.setState({ menuSections }) } module.exports = { toggleEditing } And then in my component: ManageMenu.js import React from 'react' import { toggleEditing } from '../lib/methods' class ManageMenu extends React.Component { constructor() { super() // Set initial state this.state = { menuSections: [] } } toggleEditing(id, this.state, this) render() { return ( ... ) } } export default ManageMenu Any help is appreciated, thanks! A: Thanks to @Nocebo, the answer on how to externalize functions is here: Externalise common functions in various react components In my particular situation, * *I need to remove the “floating” toggleEditing(id, this.state, this) call in the middle of nowhere. Update: This error happens “because it is invoking a method within a class definition.” (see Pineda’s comment below) *Remove the leading this. on the right side of the this.toggleEditing statement in constructor() *Update the function in lib/methods.js to remove the state and that variables since its bound to this in the constructor() See updated code below. ManageMenu.js import React from 'react' import { toggleEditing } from '../lib/methods' class ManageMenu extends React.Component { constructor() { super() this.toggleEditing = toggleEditing.bind(this) // Set initial state this.state = { menuSections: [] } } render() { return ( ... ) } } export default ManageMenu lib/methods.js const toggleEditing = function(id) { const menuSections = this.state.menuSections menuSections.map(key => (key.id === id ? key.details.editing = id : '')) this.setState({ menuSections }) } module.exports = { toggleEditing } A: You're error arises because you are invoking toggleEditing in your ManageMenu.js class definition rather than defining a function. You can achive what you want by setting a local class member this.toggleEditing to the bound function returned by the .bind method and do so within the constructor: import React from 'react' import { toggleEditing } from '../lib/methods' class ManageMenu extends React.Component { constructor() { super() this.state = { menuSections: [] } // bind external function to local instance here here this.toggleEditing = toggleEditing.bind(this); } // don't invoke it here, bind it in constructor //toggleEditing(id, this.state, this) render() { return ( ... ) } } export default ManageMenu
doc_23536181
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string cs = "Data Source=.;Initial Catalog=test;Integrated Security=SSPI"; SqlConnection con = new SqlConnection(cs); SqlCommand comma = new SqlCommand("select * from try", con); con.Open(); GridView1.DataSource = comma.ExecuteReader(); GridView1.DataBind(); con.Close(); } } } A: The issue is with the connection string you are using. Data Source=.;Initial Catalog=test;Integrated Security=SSPI Check the SQL Server instance name running on your local. Data Source=**.\YourInstanceName**;Initial Catalog=test;Integrated Security=SSPI You can test your connection string validity by trying to add a connection in Server Explorer (Tools -> Connect to Server - VS2015). Good luck
doc_23536182
function_1 : This is a the first function, and usually the next function is the second function. How do I increment the next function. function_2 : This is the second function. Here I stop. How do I create a macro that would search through the whole word document, determined that the next number is function_3, and inserted function_3 into the document as the current cursor position. A: Try this: Public Sub Test1() On Error GoTo MyErrorHandler Dim sourceDocument As Document Set sourceDocument = ActiveDocument Dim findRange As Range Set findRange = sourceDocument.Range findRange.Find.ClearFormatting findRange.Find.MatchWildcards = True Dim functionNumber As String Dim largestNumber As Long largestNumber = -1 Do While findRange.Find.Execute(findtext:="function_[0-9]{1,} :") = True 'findRange.Select functionNumber = Left$(findRange.Text, Len(findRange.Text) - 2) functionNumber = Mid$(functionNumber, 10) If functionNumber > largestNumber Then largestNumber = functionNumber DoEvents Loop sourceDocument.Range.InsertAfter "function_" & largestNumber + 1 & " :" Exit Sub MyErrorHandler: MsgBox "Test1" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description End Sub
doc_23536183
I have a batch job that is kicked off by quartz daily at midnight. The job tries to read one or more flat files and processes them. Sometimes the file the job reads is NOT where it needs to be. so getting FileNotFoundException. We would like to email the production support team that the required data file was not available. I think something along the lines of the following is the preferred way to do that in springbatch. Am I correct or is there a better way. Should my notifyProdSupLister in the batch:chunk statement? <batch:step id="readDataFileStep" next="processDataFileStep"> <batch:listeners> <batch:listner ref="notifyProdSupListner"/> </batch:listeners> <batch:tasklet .....> <batch:chunk reader="stagedDataReader" processor="extractProcessor" writer="extractOutputWriter" commit-interval="1"> <batch:listeners> <batch:listener ref="chunkListener" /> </batch:listeners> </batch:chunk> </batch:tasklet> </batch:step> I am assuming my listner would look something like package com.mkyong.listeners; public class notifyProdSupListner implements ItemReadListener<Domain> { @Override public void onReadError(Exception ex) { if (ex instanceof FileNotFoundException) { //mail support group } } } A: In FlatFileItemReader (I hope that's what you are using) you can set property strict=false if you dont want to fail job in case source is not present. and for your case you can keep it true(which is default value, it will throw IllegalStateException which your can catch through JobExecutionListener in afterJob. There you will get JobExecution from which you can get getAllFailureExceptions() and check if it failed for the reason that file dont exist. and then do what ever you want to do for handling it. A: I discovered that what I want to do can't be done that way. I have job launcher and the job launcher won't launch the job unless there is an input file and it is readable. While the ItemReadListener would allow me to do things if their was a problem reading the file. Because there was no input file, the launcher would have never started the job in the first place
doc_23536184
Please assist if anyone has a solution
doc_23536185
doc_23536186
https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start?view=aspnetcore-6.0&tabs=visual-studio Now first problem is decimal handeling In my model->Movies I have this property: Column(TypeName = "decimal(18, 2)")] public decimal Price { get; set; } When I create a new item and give it a price of 1 It shows as 1,00 If I try to edit the price to 1,1 I get this error: The field Price must be a number. (If I change tha value in the database to 1,01, and try to change it to 1,02 in the UI I get the same error) I live in Denmark we use , as decimal seperator If I try with 1**.**1 it saves and shows as 11 Now how and here do I make the change? On the model property or is there some application wide option or how do I control what is the decimal seperator? I hope I don't have to change in the create, edit and details pages. I think that could introduce a lot of possible errors when building a real world application? In the edit.cshtml there is this <div class="form-group"> <label asp-for="Movie.Price" class="control-label"></label> <input asp-for="Movie.Price" class="form-control" /> <span asp-validation-for="Movie.Price" class="text-danger"></span> </div>
doc_23536187
Notice: Undefined index: v in C:\inetpub\ts61\show.php on line 67161 I just want to default to a set behaviour if none of the conditions are able to be met. It seems to be from this call (but I can't be certain): if (($_GET['v']) == NULL){}` In this code: if (!isset($_GET['v'])) { echo("<script>alert('I'm okay!!!');</script>"); } else { if ($_GET["v"] == 'a') { echo("<script>alert('I'm okay!!!');</script>"); } elseif ($_GET["v"] == '1') { echo("<script>alert('I'm okay!!!');</script>"); } elseif ($_GET["v"] == '7') { echo("<script>alert('I'm okay!!!');</script>"); } elseif ($_GET["v"] == '14') { echo("<script>alert('I'm okay!!!');</script>"); } elseif ($_GET["v"] == '28') { echo("<script>alert('I'm okay!!!');</script>"); } } if (($_GET['v']) == NULL) { echo("<script>alert('I just errored!!!');</script>"); } I hate using querystrings but the user needs the ability to bookmark... is this a terrible way to do it? A: Instead of using the if-else statements, use the switch-case-default statements, with which you can define a default value.
doc_23536188
A: MyFile = Dir(CurDir() & "\" & "*.frm") Do While MyFile <> "" ' do stuff to file MyFile = Dir Loop
doc_23536189
From a performance standpoint, I know that always opening a connection to a database every time I execute a query may not be a very good practice (and also that when I try to use mysql_real_escape_string() to filter input, it doesn't work, because there's no active database connection). But I would like to be more clarified about this. Is it very wrong to do? Why? And I would also like to know about good alternatives to this. Here's the class: class DB { private $conn; //database data private $dbhost; private $dbname; private $dbuser; private $dbpass; /** * Constructor * @dbhost string the database host * @dbname string the database name * @dbuser string the database username * @dbpass string the database password */ public function __construct ($dbhost, $dbname, $dbuser, $dbpass) { $this->dbhost = $dbhost; $this->dbname = $dbname; $this->dbuser = $dbuser; $this->dbpass = $dbpass; } /** * Connects to mysql database */ private function open () { $this->conn = mysql_connect ($this->dbhost, $this->dbuser, $this->dbpass) or die ("Error connecting to database"); mysql_select_db ($this->dbname) or die ("Error selecting database"); } /** * Closes the connection to a database */ private function close () { mysql_close($this->conn); } /** * Executes a given query string * @param string $query the query to execute * @return mixed the result object on success, False otherwise */ public function query ($query) { $this->open(); $result = mysql_query($query, $this->conn) or die ("Error executing query ".$query." ".mysql_error()); $this->close(); return $result; } } A: (I know that the connection is supposed to close by PHP itself after the script finishes, but I don't like to rely very much on that). Why? This is a feature of the language. There's no reason to not trust it. A lot of websites are running just fine counting on PHP to close their stuff. As programmers, of course, we want to close it ourselves. That's fine. But opening and closing a database connection for every query is a horrible idea. The better way to do it is to call open() from your constructor, and rename your close() to __destruct(). According to the documentation, __destruct will be called "as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence." Sounds like an ideal place to stash away the closing code for your database connection.
doc_23536190
import java.util.Properties import org.apache.spark.SparkConf import org.apache.spark.streaming.StreamingContext import org.apache.spark.streaming.Seconds import twitter4j.conf.ConfigurationBuilder import twitter4j.auth.OAuthAuthorization import twitter4j.Status import org.apache.spark.streaming.twitter.TwitterUtils import org.apache.spark.streaming._ import org.apache.kafka.common.serialization.StringDeserializer import org.apache.spark.streaming.kafka010._ import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe import org.apache.kafka.clients.producer.{ KafkaProducer, ProducerRecord } import org.apache.spark.SparkContext import org.apache.spark.SparkConf object Testing { def main(args: Array[String]) { val appName = "TwitterData" val conf = new SparkConf() conf.set("spark.master", "local") conf.set("spark.app.name", appName) val sc = new SparkContext(conf) //create context val ssc = new StreamingContext(sc, Seconds(10)) // values of Twitter API. val consumerKey = "" // Your consumerKey val consumerSecret = "" // your API secret val accessToken = "" // your access token val accessTokenSecret = "" // your token secret //Connection to Twitter API val cb = new ConfigurationBuilder cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret) val auth = new OAuthAuthorization(cb.build) val tweets = TwitterUtils.createStream(ssc, Some(auth)) val englishTweets = tweets.filter(_.getLang() == "en") val statuses = englishTweets.map(status => (status.getText(), status.getUser.getName(), status.getUser.getScreenName(), status.getCreatedAt.toString)) statuses.foreachRDD { (rdd, time) => print("INSIDE ForEACH") rdd.foreachPartition { partitionIter => val props = new Properties() val bootstrap = "localhost:9092" //-- your external ip of GCP VM, example: 10.0.0.1:9092 props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer") props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer") props.put("bootstrap.servers", bootstrap) val producer = new KafkaProducer[String, String](props) partitionIter.foreach { elem => val dat = elem.toString() println("before data....") print(dat) val data = new ProducerRecord[String, String]("twitterData", null,dat) // "twitterData" is the name of Kafka topic producer.send(data) } producer.flush() producer.close() } } ssc.start() ssc.awaitTermination() I used below command to start consumer for reading messages but unable to read any messages. It doesn't throw any error but messages are not getting displayed in the consumer window. bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic twitterData I tried testing my code and I found that it never goes till the statement "before data..." and I think that's why its not getting published to the topic. Below is the sample of eclipse console messages I get when I start executing this code: 20/01/08 17:54:03 INFO MemoryStore: Block input-0-1578486242800 stored as values in memory (estimated size 88.0 KB, free 1971.2 MB) 20/01/08 17:54:03 INFO BlockManagerInfo: Added input-0-1578486242800 in memory on Siddhe:62039 (size: 88.0 KB, free: 1971.2 MB) 20/01/08 17:54:03 WARN RandomBlockReplicationPolicy: Expecting 1 replicas with only 0 peer/s. 20/01/08 17:54:03 WARN BlockManager: Block input-0-1578486242800 replicated to only 0 peer(s) instead of 1 peers 20/01/08 17:54:03 INFO BlockGenerator: Pushed block input-0-1578486242800 20/01/08 17:54:03 INFO MemoryStore: Block input-0-1578486243000 stored as values in memory (estimated size 4.6 KB, free 1971.2 MB) 20/01/08 17:54:03 INFO BlockManagerInfo: Added input-0-1578486243000 in memory on Siddhe:62039 (size: 4.6 KB, free: 1971.2 MB) 20/01/08 17:54:03 WARN RandomBlockReplicationPolicy: Expecting 1 replicas with only 0 peer/s. 20/01/08 17:54:03 WARN BlockManager: Block input-0-1578486243000 replicated to only 0 peer(s) instead of 1 peers 20/01/08 17:54:03 INFO BlockGenerator: Pushed block input-0-1578486243000 20/01/08 17:54:04 INFO MemoryStore: Block input-0-1578486243800 stored as values in memory (estimated size 112.1 KB, free 1971.1 MB) 20/01/08 17:54:04 INFO BlockManagerInfo: Added input-0-1578486243800 in memory on Siddhe:62039 (size: 112.1 KB, free: 1971.1 MB) 20/01/08 17:54:04 WARN RandomBlockReplicationPolicy: Expecting 1 replicas with only 0 peer/s. 20/01/08 17:54:04 WARN BlockManager: Block input-0-1578486243800 replicated to only 0 peer(s) instead of 1 peers 20/01/08 17:54:04 INFO BlockGenerator: Pushed block input-0-1578486243800 Let me know what I am missing over here.
doc_23536191
In the pod spec, I set the ephemeral-storage to be at least 100Gi (see resource description below). However, when I run $ df -h in the pod, the ephemeral storage (of type emptyDir) has a size of 124G. I would have expected it to have 100G like I requested. The overlay storage I would have expected to be close to 1474Gb (nodes SSD disk size) My requirement is to have a temporary volume on the pod which is deleted when the pod dies. The reason for it is that I need fast disk IO instead of network IO when storing on a persistent volume. Pod resource description: kind: Pod apiVersion: v1 metadata: name: {{ .Values.name }} labels: for: devs spec: containers: - name: {{ .Values.name }} image: "{{ .Values.image.acr }}/{{ .Values.image.name }}:{{ .Values.image.tag }}" command: ["/bin/sleep", "3650d"] imagePullPolicy: {{ .Values.image.pullPolicy }} resources: requests: cpu: "1" memory: 12G ephemeral-storage: 100Gi limits: cpu: "2" memory: 24G ephemeral-storage: 300Gi volumeMounts: - mountPath: {{ .Values.pvc.mount }} name: volume - mountPath: /cache name: cache-volume restartPolicy: Always volumes: - name: volume persistentVolumeClaim: claimName: {{ .Values.pvc.name }} - name: cache-volume emptyDir: {} {{- if .Values.tolerations }} tolerations: {{- toYaml .Values.tolerations | nindent 4 }} {{- end }} A: Kubernetes supports several different kinds of ephemeral volumes for different purposes emptyDir is one of those. emptyDir is itself a temporary storage in pod and delete when pod dies. Commonly used as temporary space for a pod. All containers within a pod can access the data on the volume. Data written to this volume type persists only for the lifespan of the pod. Once you delete the pod, the volume is deleted. This volume typically uses the underlying local node disk storage, though it can also exist only in the node's memory. The ephemeral storage (of type emptyDir) has a size of 124G. I would have expected it to have 100G like I requested emptyDir is managed by kubelet on each node. emptyDir: empty at Pod startup, with storage coming locally from the kubelet base directory (usually the root disk) or RAM You can also refer this github discussion where different user has reported same kind of issue. Conculsion : ephemeral-storage varies from its require size because you have filesystem running on node is using as empheral storage,The kubelet also writes node-level container logs into the first filesystem, and treats these similarly to ephemeral local storage. That might be reason for exteding the size of empheral storage and as there is also set limit of 300GB for empheral storage.
doc_23536192
Here's the code for the SmartPTR so far: template <typename TYPE> class SmartPointer { TYPE* pData; public: SmartPointer(void) : pData(0) { std::cout << "DEFAULT CTOR" << std::endl; } SmartPointer(TYPE* data) : pData(data) { std::cout << "CTOR WITH TYPE*" << std::endl; } SmartPointer(const SmartPointer<TYPE>& rhs) { std::cout << "COPY CTOR" << std::endl; } ~SmartPointer(void) { delete pData; } SmartPointer<TYPE>& operator=(const SmartPointer<TYPE>& rhs) { pData = rhs.pData; return *this; } TYPE* operator->(void) { return pData; } TYPE& operator*(void) { return *pData; } }; The class I'm using with this is farily forward. It's a simple Person class that can be found anywhere on the internet, with contructor, copy constructor and overloaded assignment operator. Now with the simple cases I have no problem. SmartPointer<Person> p(new Person("Henry", 42)); p->Display(std::cout, *p); // Prints: Henry - 42 SmartPointer<Person> q(p); // Causes runtime error. SmartPointer<Person> q; q = p; // The same runtime error as with copy constructor. Any idea where did this go wrong? If it helps here's the Person class: class Person { std::string name; unsigned age; public: Person(const char* name, unsigned age) : name(name), age(age) { std::cout << "PERSON CTOR CALLED!" << std::endl; } Person(const Person& rhs) : name(rhs.name), age(rhs.age) { std::cout << "PERSON COPY CTOR CALLED!" << std::endl; } ~Person(void) { } public: Person& operator=(const Person& rhs) { std::cout << "PERSON ASSIGNMENT OPERATOR CALLED!" << std::endl; name = std::string(rhs.name); age = rhs.age; return *this; } public: static std::ostream& Display(std::ostream& os, const Person& p); }; std::ostream& Person::Display(std::ostream& os, const Person& p) { return os << p.name << " - " << p.age << std::endl; } Thanks for every help! - Joe. A: Your smart pointer simply copies the underlying pointer in the copy constructor and assignment operator. It also deletes the pointer in the destructor. So each time you copy or you assign one of these smart pointers, you get more than one object holding a pointer to something they will all attempt to delete. Concerning the copy constructor (thanks to @andyprowl for pointing this out), the smart pointer class holds an uninitialized pointer, which it tries to call delete on in the destructor. This is undefined behaviour. There is no general solution to this problem: you have to specify how you want the smart pointer to behave, and what kind of ownership, if any, it implements.
doc_23536193
Why? What I should do ? var Request = require("sdk/request").Request; var quijote = Request({ url: "http://www.latin1files.org/", onComplete: function (response) { console.log(response.text); } }); quijote.get(); Addon: https://addons.cdn.mozilla.net/_files/478037/proxylist-initial.rev19-fx.xpi So the addon is not working if I want to use Request or Timer. How to resolve this ? I think the problem is in settings files, maybe in bootstrap.js or harness-options.json, or somewhere where it must be initialized, but i don't know much about firefox addon sdk. I know that above code must work, but i need to include or to declare something that will allow me to use Request. A: That must be declared in harness-options.json A: There is no request.js file in your /resources/addon-sdk/lib/sdk/ folder. As you can see in the comments to the announcement of SDK 1.15, bundling the SDK modules with the extension is no longer necessary (since FF21).
doc_23536194
https://www.woolworths.co.za/prod/Food/Fruit-Vegetables-Salads/Salads-Herbs/Cucumbers/English-Cucumber-300-g-650-g/_/A-20004019 using scrapy and scrapy-splash. The problem that I am running into is that it seems like the price and image are fetched from somewhere using javascript (if I load the webiste in chrome and disable javascript, I can't see either of the elements and of course, they don't show up if I use scrapy.Request). I have tried using scrapy_splash.SplashRequest but still no luck. Please help. Here is the code for my spider import scrapy from scrapy_splash import SplashRequest class Myspider(scrapy.Spider): name = 'WooliesSpider' def __init__(self): self.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0"} # download_delay = 10.0 item_dict = {} # handle_httpstatus_list = [301] base_url = 'https://www.woolworths.co.za' def get_category_from_link(link): base = "https://www.woolworths.co.za/cat/Food/" text_after_base = link[:len(base)] category = text_after_base[:text_after_base.find('/')] return category def start_requests(self): urls = [ 'https://www.woolworths.co.za/dept/Food/_/N-1z13sk5' ] for url in urls: yield SplashRequest(url=url, callback=self.parse) def parse(self,response): containers = response.css('div.lazyload-container.landing__block.landing__block--half-fourth') #print(containers) link_tags = [c.css('a.landing__link') for c in containers] #print(link_tags[0]) link = link_tags[0] url = self.base_url+link.attrib['href'] print(url) yield SplashRequest(url,callback=self.parse_product_page) # for link in link_tags: # url = self.base_url+link.attrib['href'] # print(url) # yield scrapy.Request(url,callback=self.parse_product_page) #input() def parse_product_page(self,response): print('parse_product_page') items = response.css('div.product-list__item') item = items[0] link = item.css('a.product--view').attrib['href'] url = self.base_url+link print(url) yield SplashRequest(url=url,callback=self.parse_item_page,endpoint='render.html', args={'wait':0.5}) # yield scrapy.Request(url,callback=self.parse_item_page) # for item in items: # link = item.css('a.product--view').attrib['href'] # url = self.base_url+link # print(url) # input() # yield scrapy.Request(url,callback=self.parse_item_page) def parse_item_page(self,response): print('*****parse_item_page*****') print(response.css('figure.zoom')) print(response.css('span.price')) And here is the output from the console 2021-07-18 21:49:11 [scrapy.utils.log] INFO: Scrapy 2.5.0 started (bot: SavR-Bot) 2021-07-18 21:49:11 [scrapy.utils.log] INFO: Versions: lxml 4.5.0.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d 10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.19041-SP0 2021-07-18 21:49:11 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor 2021-07-18 21:49:11 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'SavR-Bot', 'DOWNLOAD_DELAY': 1.2, 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage', 'NEWSPIDER_MODULE': 'Scrapers.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['Scrapers.spiders'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/34.0.1847.131 Safari/537.36'} 2021-07-18 21:49:11 [scrapy.extensions.telnet] INFO: Telnet Password: 875e1f88a8eb7813 2021-07-18 21:49:11 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2021-07-18 21:49:14 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy_splash.SplashCookiesMiddleware', 'scrapyjs.SplashMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2021-07-18 21:49:15 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy_splash.SplashDeduplicateArgsMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2021-07-18 21:49:15 [scrapy.middleware] INFO: Enabled item pipelines: [] 2021-07-18 21:49:15 [scrapy.core.engine] INFO: Spider opened 2021-07-18 21:49:15 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2021-07-18 21:49:15 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2021-07-18 21:49:15 [py.warnings] WARNING: c:\users\user\appdata\local\programs\python\python38\lib\site-packages\scrapy_splash\request.py:41: ScrapyDeprecationWarning: Call to deprecated function to_native_str. Use to_unicode instead. url = to_native_str(url) 2021-07-18 21:49:16 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.woolworths.co.za/robots.txt> (referer: None) 2021-07-18 21:49:16 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://localhost:8050/robots.txt> (referer: None) 2021-07-18 21:49:23 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.woolworths.co.za/dept/Food/_/N-1z13sk5 via http://localhost:8050/render.html> (referer: None) https://www.woolworths.co.za/cat/Food/Food-Cupboard/International-Cuisine/_/N-1ele3tm 2021-07-18 21:49:31 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.woolworths.co.za/cat/Food/Food-Cupboard/International-Cuisine/_/N-1ele3tm via http://localhost:8050/render.html> (referer: None) parse_product_page https://www.woolworths.co.za/prod/Food/Food-Cupboard/Pasta-Rice-Grains/Pasta/Spaghetti-500-g/_/A-6009178658413 2021-07-18 21:49:36 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.woolworths.co.za/prod/Food/Food-Cupboard/Pasta-Rice-Grains/Pasta/Spaghetti-500-g/_/A-6009178658413 via http://localhost:8050/render.html> (referer: None) *****parse_item_page***** [] [] 2021-07-18 21:49:36 [scrapy.core.engine] INFO: Closing spider (finished) 2021-07-18 21:49:36 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 1874, 'downloader/request_count': 5, 'downloader/request_method_count/GET': 2, 'downloader/request_method_count/POST': 3, 'downloader/response_bytes': 4552254, 'downloader/response_count': 5, 'downloader/response_status_count/200': 4, 'downloader/response_status_count/404': 1, 'elapsed_time_seconds': 21.456216, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2021, 7, 18, 19, 49, 36, 851956), 'log_count/DEBUG': 5, 'log_count/INFO': 10, 'log_count/WARNING': 1, 'request_depth_max': 2, 'response_received_count': 5, 'robotstxt/request_count': 2, 'robotstxt/response_count': 2, 'robotstxt/response_status_count/200': 1, 'robotstxt/response_status_count/404': 1, 'scheduler/dequeued': 6, 'scheduler/dequeued/memory': 6, 'scheduler/enqueued': 6, 'scheduler/enqueued/memory': 6, 'splash/render.html/request_count': 3, 'splash/render.html/response_count/200': 3, 'start_time': datetime.datetime(2021, 7, 18, 19, 49, 15, 395740)} 2021-07-18 21:49:36 [scrapy.core.engine] INFO: Spider closed (finished)
doc_23536195
swich(i){ case 1: break; case 2: break; } I want to insert "case", but how do I create PsiSwitchLabelStatement? A: You can create any Java statement using this method: PsiElementFactory.SERVICE.getInstance(project).createStatementFromText(text, null)
doc_23536196
(Below is the picture of the output:) Input: >>> from nltk.book import * Output (After I hit 'Enter'): So now my questions are what is the error about and if there is a way to solve it, then what should I need to do? Thanks for looking into my problem. A: This appears to be a known bug with nltk and Python 3. It seems to have been fixed within the past two weeks, but I expect you'll have to wait until there's a release that contains the fix. You could try installing from source.
doc_23536197
Example: Enter name: james231 output: james231 james231 james231 james231 james231 Mang Jose Mang Jose Mang Jose Correct output should be: Enter Name: james231 output: Mang Jose for(int i=0; i< name.length(); i++) { if(!(name.charAt(i) >='A' && name.charAt(i) <= 'Z' || name.charAt(i) >='a' && name.charAt(i) <= 'z' || name.charAt(i) == ' ')) { System.out.println("Name: Mang Jose"); } else if(name.charAt(i) >='A' && name.charAt(i) <= 'Z' || name.charAt(i) >='a' && name.charAt(i) <= 'z' || name.charAt(i) == ' ') { System.out.println("\nName: "+name); } } A: You'll need an additional variable - let's call it useDefaultName. Before the loop you need to set it to false - you don't want to use the default name unless an error occurs. Then if anywhere in the loop an invalid character is found, you can simply set useDefaultName to true and break from the loop. After the loop, if useDefaultName is true. If so, System.out.println("Name: Mang Jose"); else output name. Your code will look like this: boolean useDefaultName = false; for(int i=0; i< name.length(); i++) { if(!(name.charAt(i) >='A' && name.charAt(i) <= 'Z' || name.charAt(i) >='a' && name.charAt(i) <= 'z' || name.charAt(i) == ' ')) { useDefaultName = true; break; } } if (useDefaultName) System.out.println("Name: Mang Jose"); else System.out.println("Name: " + name); This should be good if you're trying to learn how to write code and want to do all of the basics yourself. Otherwise I'd suggest using regular expressions or patterns (see other answers). A: The problem is that you check your string char by char. The first five chars (james) are valid, so your code prints the name five times (once for each char), while the last three chars 231 are invalid, thus your code prints the default name. So I'd go for some way to check your whole string at once and not char by char. You may use regular expressions for this: Pattern p = Pattern.compile("[a-zA-Z]+"); String name = "james231"; //use your userinput here! if(p.matcher(name).matches()) { System.out.println("Name: " + name); } else { System.out.println("Name: Mang Jose"); } //prints: //Name: Mang Jose demo @ ideone This way you check the whole string if it only contains letters (lowercase and uppercase). If this is the case it prints the given name, otherwise it prints the default name. If you want to allow more characters, simply add them to the character class. For example if you want to allow spaces, you change it to [a-zA-Z ].
doc_23536198
I'm trying to set up a force directed graph with groups that can expand or collapse on click, similar to GerHobbelt's example for d3.js. I'm using cola.js with d3 because I need geometric constraints. I've set up a script that works fine in both Chrome and Firefox (versions 44.0.2403.125 and 39.0 respectively). That script visualizes this JSON network, which has seven nodes, five links, and three groups. If I switch to this network instead (comment line 309, uncomment line 310 in my script), which has a few hundred nodes and links, and 25 groups, then the Chrome javascript console gives me thousands of assertion failed errors as soon as it starts. The visualization is a little glitchy (nodes jump back and forth over the edges of group rectangles) but it seems to run okay despite the errors. Using the non-minified versions of cola and d3, all the errors have the following stack trace: generateConstraints @ cola.js:1479 generateGroupConstraints @ cola.js:1428 generateYGroupConstraints @ cola.js:1524 Projection.project @ cola.js:1673 Projection.yProject @ cola.js:1653 Projection.projectFunctions @ cola.js:1666 Descent.stepAndProject @ cola.js:2472 Descent.computeNextPosition @ cola.js:2508 Descent.rungeKutta @ cola.js:2527 Layout.tick @ cola.js:3543 (anonymous function) @ cola.js:4063 d3_timer_mark @ d3.js:2122 d3_timer_step @ d3.js:2102 In Firefox, I get no errors at all with either network. I can use Firefox for now but I have no idea how to resolve the errors I get in Chrome. This is my first javascript project, so I assume I've done something stupid with scoping or function definitions. Any advice on this would be helpful; thanks! A: This question is resolved in issue #130 over at the webCola github repo (thanks to Tim Dwyer). The issue was that I thought I set the node boundaries at lines 313 and 314 in my JSFiddle, but node properties don't seem to be carried over properly in my network() function. I don't see why, but that's clearly what's happening. The quick fix from Tim is to set the node boundaries in init() after getting the current network elements. See the updated JSFiddle.
doc_23536199
* *Hi, i don't undestand why this doesn't work, i am trying to retrieve whatever comes after "offer" in the specified url and then display it but when i click on the Offer button on android screen nothing happens. Please help if you could. I have the internet permission in manifest. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.ListView; public class LoggedIn extends Activity { AlertDialog alertDialogStores; ObjectItem[] ObjectItemData = new ObjectItem[5]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logged_in); // a button to show the pop up with a list view View.OnClickListener handler = new View.OnClickListener(){ public void onClick(View v) { switch (v.getId()) { case R.id.buttonShowPopUp: LoaderTask task = new LoaderTask(); task.execute(); break; } } }; findViewById(R.id.buttonShowPopUp).setOnClickListener(handler); } class LoaderTask extends AsyncTask<Void , Void ,String>{ ProgressDialog progressDialog ; public LoaderTask(){ progressDialog = new ProgressDialog(SplashActivity.this); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.setMessage("Loading app data..."); } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected String doInBackground(Void... params) { return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressDialog.dismiss(); showPopUp(result); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public String connect(String url) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response; try { response = httpclient.execute(httpget); //Log.i(TAG,response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result= convertStreamToString(instream); instream.close(); return result; } } catch (ClientProtocolException e) { } catch (IOException e) { } return null; } public void showPopUp(String result){ try{ JSONArray jsonArray = new JSONArray(result); for(int i = 0 ; i <= 5 ; i++){ JSONObject o = jsonArray.getJSONObject(i); String http_response = o.getString("offer"); System.out.println("test "+http_response); //ObjectItemData[i] = new ObjectItem(o); ObjectItemData[0] = new ObjectItem(http_response); ObjectItemData[1] = new ObjectItem(http_response); ObjectItemData[2] = new ObjectItem(http_response); ObjectItemData[3] = new ObjectItem(http_response); ObjectItemData[4] = new ObjectItem(http_response); // adapter instance ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData); // create a new ListView, set the adapter and item click listener ListView listViewItems = new ListView(this); listViewItems.setAdapter(adapter); listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem()); // put the ListView in the pop up alertDialogStores = new AlertDialog.Builder(LoggedIn.this) .setView(listViewItems) .setTitle("Offers") .show(); } } catch(Exception e){e.printStackTrace();} finally{System.out.println("Success"); } } } A: class LoaderTask extends AsyncTask<Void , Void ,String>{ ProgressDialog progressDialog ; public LoaderTask(){ progressDialog = new ProgressDialog(SplashActivity.this); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.setMessage("Loading app data..."); } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected String doInBackground(Void... params) { return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressDialog.dismiss(); showPopUp(result); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public String connect(String url) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response; try { response = httpclient.execute(httpget); //Log.i(TAG,response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result= convertStreamToString(instream); instream.close(); return result; } } catch (ClientProtocolException e) { } catch (IOException e) { } return null; } public void showPopUp(String result){ try{ JSONArray jsonArray = new JSONArray(result); for(int i = 0 ; i < jsonArray.length() ; i++){ JSONObject o = jsonArray.getJSONObject(i); String http_response = o.getString("offer"); System.out.println("test "+http_response); ObjectItemData[i] = new ObjectItem(http_response); } //and populate your listview here } catch(Exception e){e.printStackTrace();} finally{System.out.println("Success"); } } and call this to do task new LoaderTask().execute();