id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23525300
Thanks! A: I don’t think this is supported in gfxdraw yet. You could define a new arc function as follows: def draw_arc(surface, col, x, y, r, start_angle, stop_angle, width=1): """Draw an arc given the centre and radius""" pygame.draw.arc( surface, col, (x - r, y - r, r * 2, r * 2), start_angle, stop_angle, width=width ) Note that this function uses radians and works anticlockwise. gfxdraw uses degrees and works clockwise.
doc_23525301
I'm doing the call with: $("#form").ajaxForm({ type: "POST", headers: { Authorization: $cookieStore.get("userPassword"), FeatureName: name, }, success: function (data) { console.log("reload page"); }, dataType: "text" }).submit(); I get the error: Failed to convert property value of type 'java.lang.String' to required type 'com.Option' for property 'option' this is the whole output line: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'modelDTO' on field 'option': rejected value [{"id":3,"optionName":"Other"}]; codes [typeMismatch.modelDTO.option,typeMismatch.option,typeMismatch.com.Option,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [modelDTO.option,option]; arguments []; default message [option]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.Option' for property 'option'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.Option] for property 'option': no matching editors or conversion strategy found] this is my controller and the DTO @RequestMapping(value = "/save", method = RequestMethod.POST) @Transactional public @ResponseBody void save(@ModelAttribute("form") ModelDTO model) ... public class ModelDTO implements Serializable { private static final long serialVersionUID = 3276874897891652914L; private Long userId; private Option option; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Option getOption() { return option; } public void setOption(Option option) { this.option = option; } } Does spring allow do this work? A: Since you are sending data to your controller through the request method POST, you need to annotate your ModelDTO model with @RequestBody and remove @ResponseBody unless your method is actually supposed to return something. Also, make sure the data you send through your form actually matches your ModelDTO. A: I got the solution, I don't need change anything of my code only add initBinderAll in the controller where I'm doing the binding. With this solution we can handle the data which are not converting automatically. like: @InitBinder public void initBinderAll(WebDataBinder binder) { binder.registerCustomEditor(Option.class, new OptionPropertyEditor()); } and create the custom PropertyEditorSupport like: public class OptionPropertyEditor extends PropertyEditorSupport
doc_23525302
Undefined variable key_2captcha I run this code to pass a CAPTCHA to 2captcha server: <?php $id_Captcha=0; $key_2captcha="key2captcha"; function send_captcha($base_file){ $ch = curl_init("http://2captcha.com/in.php"); curl_setopt($ch, CURLOPT_POSTFIELDS, array('method'=>"base64", 'key'=>$key_2captcha, 'numeric'=>1, 'max_len'=>1, 'body'=>$base_file, 'submit'=>'download and get the ID')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($ch); curl_close($ch); return $postResult; } function getSolveCaptcha($id_captcha){ $c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($c); curl_close($c); return $postResult; } ?> I run this code in XAMPP. A: I thinks you have a variabile scope resolution problem. If you want to use the variable into a generic function, you have to pass this variable as parameter in the signature of function. Not use variable as global because is a bad practice, you have to make generic function so you have to use generic parameter. Try this code: <?php $id_Captcha=0; $key_2captcha="key2captcha"; function send_captcha($base_file, $key_2captcha){ $ch = curl_init("http://2captcha.com/in.php"); curl_setopt($ch, CURLOPT_POSTFIELDS, array('method'=>"base64", 'key'=>$key_2captcha, 'numeric'=>1, 'max_len'=>1, 'body'=>$base_file, 'submit'=>'download and get the ID')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($ch); curl_close($ch); return $postResult; } function getSolveCaptcha($id_captcha, $key_2captcha){ $c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($c); curl_close($c); return $postResult; } //Call Example send_captcha($base_file, $key_2captcha); ?> A: Use below code use $key_2captcha with global. in both function. read variable scope in PHP function getSolveCaptcha($id_captcha){ global $key_2captcha; $c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($c); curl_close($c); return $postResult; } A: Use below code with $GLOBALS — References all variables available in global scope <?php $id_Captcha=0; $key_2captcha="key2captcha"; function send_captcha($base_file){ $ch = curl_init("http://2captcha.com/in.php"); curl_setopt($ch, CURLOPT_POSTFIELDS, array('method'=>"base64", 'key'=>$GLOBALS['key_2captcha'], 'numeric'=>1, 'max_len'=>1, 'body'=>$base_file, 'submit'=>'download and get the ID')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($ch); curl_close($ch); return $postResult; } function getSolveCaptcha($id_captcha){ $c = curl_init("http://2captcha.com/res.php?key=".$GLOBALS['key_2captcha']."&action=get&id=".$id_captcha); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($c); curl_close($c); return $postResult; } ?> Ref PHP.net
doc_23525303
i have used GWT's grid and each row is highighted in background color using CSS. but applied css is not printed in printed page. how can i print with css? I am calling Print functionality as below: Print.it("<link rel='StyleSheet' type='text/css' media='paper' href='mainApplication.css'>", DOM.getElementById("myId")); in mainApplication.css i placed style as below: @media print { print_background { background-color: #EBECE4 !important; } } is my CSS style correct? Please help me. in the code : i created a horizontal panel and added GWT grid to it as below. HorizontalPanel recordsPanel = new HorizontalPanel(); //GWT grid is created and the same is added to recordsPanel recordsPanel .add(grid). i applied css style for grid rows as below: recordsGrid.getRowFormatter().addStyleName(i, "print_results_background"); Now i want to print the records with css style. Thanks! A: You CSS style isn't correct for a trivial issue: lack of dot (.) before print_background class. Correct code is: @media print { .print_background { background-color: #EBECE4 !important; } } A: paper is not a valid value for the media attribute. Correct your link tag as follows: <link rel='stylesheet' type='text/css' media='print' href='mainApplication.css' /> Ignoring other syntactic mistakes as mentioned by other posters, please refer to RAS's comment on the question also (regarding the differing class name). Reference * *Media Types on W3C A: I think you are missing in the css to specify if print_background its an id # or a class .
doc_23525304
No after upgrade it is php7 which runs for cli => /etc/php/7.0/cli But it cannot detect the SQLite3, and I get 'PHP Fatal error: Class 'SQLite3' not found' error. I tried to install it again with this command: sudo apt-get install sqlite3 But it says it is installed now. How can I solve this problem that php7 could detect SQLite3? Thanks in advance A: sudo apt install php-sqlite3 This worked for me and installed php7.0-sqlite3 and setup the config files. This is for Ubuntu 16.04 and higher. A: sudo apt-get install php7.0-sqlite3
doc_23525305
Thank you.
doc_23525306
I want to make message box for validating surveys. the message box contain the message because error of stuffing. I want my message box keep showing, so i can click the sheets which contain error of stuffing without closing the message box. So, the message box will guide me to fix the error in that sheets This is my previous code: Private Sub CommandButton1_Click() Dim error As String error = “” If (vehicle = True) And (gasoline_month = 0) Then error = error & “- the expenditure of gasoline should not be empty” & Chr(10) End If If error = “” Then msgbox “clean”, vbInformation Else MsgBox error, vbCritical End Sub Thank you, I hope anyone can help me,, (sorry for my bad english) A: Hi it is not possible with msgbox in VBA , you have to use userform for achieve this. Add a userform in and place buttons as you need and try. if you stuck somewhere do let us know.
doc_23525307
I want to capture heap accesses in the [heap] VMA. Again as far as I know, .bss mappings happen at compile time by the fronted (e.g., Clang). Where should I change, in order to filter heap accesses?
doc_23525308
However, we are looking to port the code to python. Is there a function in sklearn, nltk or some other package which can give the same functionality? Thanks! A: If your data is plain text, you can use CountVectorizer in order to get this job done. For example: from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(min_df=2) corpus = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?', ] vectorizer = vectorizer.fit(corpus) print vectorizer.vocabulary_ #prints {u'this': 4, u'is': 2, u'the': 3, u'document': 0, u'first': 1} X = vectorizer.transform(corpus) Now X is the document-term matrix. (If you are into information retrieval you want to consider also Tf–idf term weighting. It can help you get the document-term matrix easily with a few lines. Regarding the sparsity - you can control these parameters: * *min_df - the minimum document frequency allowed for a term in the document-term matrix. *max_features - the maximum number of features allowed in the document-term matrix Alternatively, If you already have the document-term matrix or Tf-idf matrix, and you have the notion of what is sparse, define MIN_VAL_ALLOWED, and then do the following: import numpy as np from scipy.sparse import csr_matrix MIN_VAL_ALLOWED = 2 X = csr_matrix([[7,8,0], [2,1,1], [5,5,0]]) z = np.squeeze(np.asarray(X.sum(axis=0) > MIN_VAL_ALLOWED)) #z is the non-sparse terms print X[:,z].toarray() #prints X without the third term (as it is sparse) [[7 8] [2 1] [5 5]] (use X = X[:,z] so X remains a csr_matrix.) If it is the minimum document frequency you wish to set a threshold on, binarize the matrix first, and than use it the same way: import numpy as np from scipy.sparse import csr_matrix MIN_DF_ALLOWED = 2 X = csr_matrix([[7, 1.3, 0.9, 0], [2, 1.2, 0.8 , 1], [5, 1.5, 0 , 0]]) #Creating a copy of the data B = csr_matrix(X, copy=True) B[B>0] = 1 z = np.squeeze(np.asarray(X.sum(axis=0) > MIN_DF_ALLOWED)) print X[:,z].toarray() #prints [[ 7. 1.3] [ 2. 1.2] [ 5. 1.5]] In this example, the third and fourth term (or columns) are gone, since they only appear in two documents (rows). Use MIN_DF_ALLOWED to set the threshold.
doc_23525309
var parseURL = function() { var language = $routeParams.language; var url = $location.path(); boatType = parseBoatType(url, language); var destination = parseDestination(url, language); searchBoats(destination, boatType); }; parseURL(); var parseBoatType = function(url, language) { var boatType = UrlService.parseUrlBoatType(url, language); var boatTypeParsed = UrlService.parseBoatType(url, language); // boat type is parsed if(boatTypeParsed) { BoatType.getBoatTypeByName({name: boatTypeParsed}, function success(result) { boatTypeAux = result; return boatTypeAux; }); } else { return null; } }; var parseDestination = function(url, language) { // departure is parsed var departure = UrlService.parseUrlDeparture(url); return $http.get("http://" + API_SERVER_URL + "/translatedDepartures?departure="+departure+";lang="+ language+";matchStart="+true).then(function(response) { departure = response.data.map(function(source) { return source.element_translation; }); ... Note: When I run BoatType.getBoatTypeByName in parseBoatType function the code is still running and I run searchBoats before I get the results. Update: searchBoats methods will look like: var searchBoats = function(destination, boatType) { Boat.query({ destination: destination, boatType: boatType }, function success(result) { console.log("getOptionList.query realizada"); $scope.boats = result; ... According to your answer I have a callback BoatType.getBoatTypeByName({name: boatTypeParsed}, function success(result) { boatTypeAux = result; calling to a factory service to my api: angular.factory('BoatType', function ($resource, SERVER_URL) { var boatTypes = $resource('http://' + SERVER_URL + '/:action', { action: 'boat_types' }, { query: { method: 'GET', isArray: true }, getBoatTypeById: { method: 'GET', params: { action: 'getBoatTypeById' }, isArray: false }, getBoatTypesById: { method: 'GET', params: { action: 'getBoatTypesById' }, isArray: true }, getBoatTypeByName: { method: 'GET', params: { action: 'getBoatTypeByName' }, isArray: false } }); return boatTypes; } ) New update According to the comments of @zero298, now my code looks like this: var parseURL = function() { var language = $routeParams.language; var url = $location.path(); // You need to wait on your async calls var boatsPromise = $q.all([ parseBoatType(url, language), parseDestination(url, language) ]).then(function(resultArr){ var boatType = resultArr[0], destination = resultArr[1]; // Return something else to wait on return searchBoats(destination, boatType); }); var parseBoatType = function(url, language) { BoatType.getBoatTypeByName({name: boatTypeParsed}, function success(result) { return result; }); }; var parseDestination = function(url, language) { return "whatever"; }; // The service .factory('BoatType', function($resource, SERVER_URL){ var boatTypes = $resource('http://' + SERVER_URL +'/:action', {action:'boat_types'}, { query: {method:'GET', isArray: true}, getBoatTypeByName: {method:'GET', params:{action: 'getBoatTypeByName'}, isArray: false} }); return boatTypes; } ) Although, the function searchBoats waits until parseBoatType and parseDestination are executed, note parseBoatType has a callback to a service with a $resource call to an API (which I think is asynchnous), so as result, the searchBoats function is executed before the callback gets the result. A: You aren't waiting on any of your asynchronous calls. Look at the documentation for $http and by extension $q. You need to be doing something like this: function parseURL() { var language = $routeParams.language; var url = $location.path(); // You aren't waiting on anything that is async // You need to wait on your async calls var boatsPromise = $q.all([ parseBoatType(url, language), parseDestination(url, language) ]).then(function(resultArr){ var boatType = resultArr[0], destination = resultArr[1]; // Return something else to wait on return searchBoats(destination, boatType); }); // Either wait on it here and do some more stuff boatsPromise.then(console.log); // Or return it so that something higher in the callstack can wait return boatsPromise; } Your searchBoats function should also act like parseDestination and return a $q (Promise) to wait on: function searchBoats(destination, boatType) { /* * I would recommend against putting stuff on to $scope * in an async chain unless you are at the very root * of the chain otherwise you lose context * and are unable to .then() */ // Retun a then()able object return Boat.query({ destination: destination, boatType: boatType }, function success(result) { console.log("getOptionList.query realizada"); return result; }); }
doc_23525310
So what is the best design for handling the upgrading (and downgrading) of a whole firmware version?
doc_23525311
Whole code: uniform sampler2D texture_0; uniform vec3 uColor; varying vec2 varTexCoords; void main(void) { //vec4 col = texture2D(texture_0, varTexCoords); vec4 col = vec4(0.0, 0.0, 0.0, 0.5); gl_FragColor = col; } Can someone explain to me why: Works: vec4 col = texture2D(texture_0, varTexCoords); //vec4 col = vec4(0.0, 0.0, 0.0, 0.5); gl_FragColor = col; Doesn't work: //vec4 col = texture2D(texture_0, varTexCoords); vec4 col = vec4(0.0, 0.0, 0.0, 0.5); gl_FragColor = col; Works: vec4 col = texture2D(texture_0, varTexCoords); col.rgb = uColor; //col.a = 0.5; gl_FragColor = col; Also works: vec4 col = texture2D(texture_0, varTexCoords); col.rgb = uColor; col.a *= 0.5; gl_FragColor = col; Doesn't work: vec4 col = texture2D(texture_0, varTexCoords); col.rgb = uColor; col.a = 0.5; gl_FragColor = col; And this one dosen't work even though many examples seem to use it: gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); Error occurence in code is here: glEnableVertexAttribArray(textureCoords); CHECK_GL_ERROR("glEnableVertexAttribArrayCheck"); All code related to the shader: inline void Renderer::renderText(float x, float y, string msg) { mat4 proj; Matrix::projection2D(proj, (float) nScreenWidth_, (float) nScreenHeight_, 0.0f); mat4 res, restmp; mat4 pos; mat4 rot; mat4 scale; //Vector3D p(72.0f, 88.0f, 1.0f); //Vector3D p(20.0f, 20, 1.0f); Vector3D r(0.0f, 0.0f, 0.0f); Vector3D s(1.0f, nScreenWidth_ / nScreenHeight_, 1.0f); //Matrix::translate(pos, p.getX(), p.getY(), p.getZ()); //Matrix::rotateZ(rot, r.getZ()); float widthMod = nScreenWidth_ / 100.0f; float heightMod = nScreenHeight_ / 100.0f; Matrix::translate(pos, x * widthMod, y * heightMod, 1.0f); Matrix::rotateZ(rot, r.getZ()); //Matrix::scale(scale, s.getX() * widthMod, s.getY() * heightMod, 1.0f); Matrix::scale(scale, 16.0f, 16.0f, 1.0f); Matrix::multiply(proj, pos, res); Matrix::multiply(res, rot, restmp); Matrix::multiply(restmp, scale, res); // Select shader program to use. int shaderId = features_->getText()->getShaderId(); glUseProgram(shaderId); CHECK_GL_ERROR("glUseProgram"); int matrix = glGetUniformLocation(shaderId, "uWVP"); int color = glGetUniformLocation(shaderId, "uColor"); int texture = glGetUniformLocation(shaderId, "texture_0"); CHECK_GL_ERROR("glGetUniformLocation"); int textureCoords = glGetAttribLocation(shaderId, "attrTexCoords"); int vertices = glGetAttribLocation(shaderId, "attrPos"); CHECK_GL_ERROR("glGetAttribLocation"); // Specify WVP matrix. glUniformMatrix4fv(matrix, 1, false, res); CHECK_GL_ERROR("glUniformMatrix4fv"); // Bind the texture. glActiveTexture(GL_TEXTURE0); CHECK_GL_ERROR("glActiveTexture"); glBindTexture(GL_TEXTURE_2D, features_->getText()->getFontMapId()); CHECK_GL_ERROR("glBindTexture"); glUniform1i(texture, 0); CHECK_GL_ERROR("glUniform1i"); glEnableVertexAttribArray(vertices); CHECK_GL_ERROR("glEnableVertexAttribArray"); glBindBuffer(GL_ARRAY_BUFFER, 0); CHECK_GL_ERROR("glBindBuffer"); glEnable(GL_BLEND); CHECK_GL_ERROR("glEnable"); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CHECK_GL_ERROR("glBlendFunc"); //string text = output_; for (unsigned int i = 0; i < msg.length(); i++) { unsigned short l = static_cast<unsigned short>(msg[i]) - 32; mat4 delta, resmove; Matrix::translate(delta, 1.6f, 0.0f, 0.0f); Matrix::multiply(res, delta, resmove); Matrix::copy(resmove, res); glUniformMatrix4fv(matrix, 1, false, res); CHECK_GL_ERROR("glUniformMatrix4fv"); float col[] = {0.0f, 1.0f, 0.0f}; glUniform3fv(color, 1, col); CHECK_GL_ERROR("glUniform3fv"); glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 0, features_->getText()->vertices_); CHECK_GL_ERROR("glVertexAttribPointer"); glEnableVertexAttribArray(textureCoords); CHECK_GL_ERROR("glEnableVertexAttribArrayCheck"); glVertexAttribPointer(textureCoords, 2, GL_FLOAT, GL_FALSE, 0, features_->getText()->getSymbol(l)); CHECK_GL_ERROR("glVertexAttribPointer"); glDrawArrays(GL_TRIANGLES, 0, 18 / 3); CHECK_GL_ERROR("glDrawArrays"); } glDisable(GL_BLEND); CHECK_GL_ERROR("glDisable"); } The error is GL_INVALID_VALUE and only occurs after executing code, not after compiling and linking shader. A: This is probably what is happening : (I say "compiler" here, but it's probably the linker that does the actual purging) The shader compliler drops this one : varying vec2 varTexCoords; If the compiler determines that a variable is not used, it will be discarded. The last example is good : vec4 col = texture2D(texture_0, varTexCoords); col.rgb = uColor; col.a = 0.5; gl_FragColor = col; The compiler understands that the original value in col is overwritten by the uColor uniform and the 0.5 constant. The texture read is dropped, so the varying is also dropped. Then your attrTexCoords will also most likely be dropped, so your textureCoords variable containing the attrib locations is -1. Here on the other hand, the compiler cannot remove the texture read because col.bg will contain values from the texture. vec4 col = texture2D(texture_0, varTexCoords); col.r = uColor.r; col.a = 0.5; gl_FragColor = col;
doc_23525312
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: { adminpanel: path.join(__dirname, 'theme/peakbalance/es6/adminpanel.js') }, output: { path: path.join(__dirname, 'theme/peakbalance/amd/src'), filename: '[name]_bundle.js', libraryTarget: 'amd' }, module: { loaders: [{ test:/\.(js|jsx)$/, loader:'babel', query: { presets: ["es2015", "stage-0", "react"] } }] } }; So i have been struggling with this issue for quite some time now. I am coding in a old php system called moodle, which are tightly coupled with the AMD system, i would like to use new JS technologies instead of jquery 1.12 like react, immutable, redux etc. though, so i am trying to make the last part of the build chain export an AMD module. What i have right now: var webpack = require('webpack'); var path = require('path'); module.exports = { entry: { adminpanel: path.join(__dirname, 'theme/peakbalance/amd/es6/adminpanel.js') }, output: { path: path.join(__dirname, 'theme/peakbalance/amd/src'), filename: '[name]_bundle.js' }, module: { loaders: [{ test:/\.(js|jsx)$/, loader:'babel', query: { presets: ['es2015', 'stage-0', 'react'], plugins: ['transform-es2015-modules-amd'] }, include:path.join(__dirname,'./theme/peakbalance/amd/es6') }, { test:/\.json$/, loaders:['json-loader'], include:path.join(__dirname,'./theme/peakbalance/amd/es6') }, { test:/\.(png|jpg)$/, loader:'url?limit=25000' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" }, { test: /\.(woff|woff2)/, loader:"url?prefix=font/&limit=5000" }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" }] } }; So as you can see, i am trying to use a transform-es2015-modules-amd plugin for the loader, this plugin works perfect if i use it together with the babel-cli like this: babel --plugins transform-es2015-modules-amd ./theme/peakbalance/es6/adminpanel.js then it outputs: define(["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var AdminPanel = function () { function AdminPanel() { _classCallCheck(this, AdminPanel); this.init = this.init.bind(this); } _createClass(AdminPanel, [{ key: "init", value: function init(herpderp) { console.log("herpderp42424"); console.log("herp"); var app = new App(); } }]); return AdminPanel; }(); exports.default = AdminPanel; }); }); When its being run through webpack with just: webpack -w it outputs: /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { export default class AdminPanel { constructor() { this.init = this.init.bind(this); } init(herpderp) { console.log("herpderp42424"); console.log("herp"); console.log("alright alright"); let app = new App(); } } /***/ } /******/ ]); So now it doesn't even transpile it from es6 to es5 and its absolutely not a AMD module structure. I basically just want the exact same behavior as the babel cli, but with webpack doing its magic, since i'll probably go beyond 1 file, so i need the files to be concatted, i looked at something like the babel-plugin-inline-import plugin, that i would be able to use with the babel-cli for multiple files, but i really think that webpack is more smooth. Have anyone fixed this issue?? EDIT 1: I have changed my webpack configuration to something simplified like so: var webpack = require('webpack'); var path = require('path'); module.exports = { entry: { adminpanel: path.join(__dirname, 'theme/peakbalance/es6/adminpanel.js') }, output: { path: path.join(__dirname, 'theme/peakbalance/amd/src'), filename: '[name]_bundle.js', library: 'amd' }, module: { loaders: [{ test:/\.(js|jsx)$/, loader:'babel', query: { presets: ["es2015", "stage-0", "react"] } }] } }; And now atleast webpack is transpileing it to the following: var amd = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var AdminPanel = function () { function AdminPanel() { _classCallCheck(this, AdminPanel); this.init = this.init.bind(this); } _createClass(AdminPanel, [{ key: "init", value: function init(herpderp) { console.log("herpderp42424"); console.log("herp"); console.log("alright alright"); var app = new App(); } }]); return AdminPanel; }(); exports.default = AdminPanel; /***/ } /******/ ]); But setting a variable called amd equal to what im exporting, is hardly a substitute for a Define call according to the AMD standard. A: I think what is happening is babel transforms to AMD and then Webpack transforms AMD into __webpack_require__ ready for the browser. What you probably want to do is ditch the transform-es2015-modules-amd plugin and update your Webpack config to include output.libraryTarget = 'amd'. Then Webpack will export the entire bundle as AMD. https://webpack.github.io/docs/configuration.html#output-library
doc_23525313
These new inputs are created this way: function addAttachmentRow() { var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>'; $("#attachment_list").append(htmlRow); } and I am trying to prepare validating function, but this code: $( document ).ready(function() { $('input[name^="file_name"]').each(function() { $(this).keydown(function(){ if ($(this).val().length < 2) { $(this).css("background-color", "#FFCCCC"); $(this).css("border", "1px solid #665252"); $(this).css("color", "#B20000"); } else { $(this).css("background-color", "#F5FFEB"); $(this).css("border", "1px solid #5CE65C"); $(this).css("color", "#145214"); } }); }); }); but it only applies to the very first element which is created statically. It does not effect elements, created when "addAttachmentRow" is clicked and new input added. Changing it to $('input[name^="file_name[]"]').each(function() { doesn't help either, and I just need to have [] in input's name. Any ideas? Thanks in advance. A: Yes. It happens. It doesn't select the element with that code. You will need to use $(document).on method instead of this. Solution: Use this code $(document).on('event', 'selector', function() { // code }); e.g. $(document).on('each', 'input[name^="file_name[]"]', function() { alert('Event fired!'); }); A: You need to bind event with the document for dynamic elements: $(function(){ $(document).on('keydown', 'input[name^="file_name"]', function(e) { /* to do here */ }); }); Try this demo: $(function() { $(document).on('keydown', 'input[name^="file_name"]', function(e) { var err = 2 > $.trim(this.value).length; $(this).toggleClass('rest', !err).toggleClass('err', err); }); }); function addAttachmentRow() { var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>'; $("#attachment_list").append(htmlRow); } .rest { background-color: #F5FFEB; border: 1px solid #5CE65C; color: #145214; } .err { background-color: #FFCCCC; border: 1px solid #665252; color: #B20000; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type='button' value='Add' onclick='addAttachmentRow()' /> <table id='attachment_list'> </table>
doc_23525314
I think problem with xmlAppdelegate class. my problem is how to manage delegate class.And how to manage in storyboard. http://www.edumobile.org/iphone/iphone-programming-tutorials/parsing-an-xml-file/ If storyboard into demo then please update link. Thanx in Advance A: There are many tutorials on the Internet that will help you accomplish what you are trying to achieve. You have to use NSXmlParser class in order to parse the xml. There are also other third party libraries to parse xml but i would suggest you to stick with NXXmlParser since there are more help available for it if you face some sort of issues. Since you have asked for parsing xml and the project have to have StoryBoards, HERE is a good tutorial to achieve exactly what you want to do and will give you a good head start. Hope this helps!
doc_23525315
A: I did. Please see my github project, with the seven steps required. FWIW, it is on us at Typesafe to make this process much easier for developers, and we are focused on that. Our goal is to make it as simple as the Activator process (download a simple ZIP file, expand and run).
doc_23525316
import numpy as np from sys import argv from PIL import Image from skimage import measure # Inicialization spritesToFind = argv[1] spriteSize = argv[2] sheet = Image.open(argv[3]) # To grayscale, so contour finding is easy grayscale = sheet.convert('L') # Let numpy do the heavy lifting for converting pixels to black or white data = np.asarray(grayscale).copy() # Find the contours we need contours = measure.find_contours(data, 0.8) # Now we put it back in PIL land sprite = Image.fromarray(data) sprite.save(str(spritesToFind), "PNG") A: If you just want to cut out the smallest rectangle containing the contour you can use the (x,y) coordinates in the contour to create a bounding box going from (min(x), min(y)) to (max(x),max(y)). If you want to zero out everything not inside a contour, you should look into how you can determine if a point is within a polygon, and then zero out everypoint point that is not inside the contour. A: Where contours is a list of countours found using measure.find_contours, and x is your image. This shows how to do both a rectangle bounding box extract image_patch and how to extract just the pixels that are part of the polygon new_image: from matplotlib import path contour = contours[0] path = path.Path(contour) top = min(contour[:,0]) bottom = max(contour[:,0]) left = min(contour[:,1]) right = max(contour[:,1]) new_image = np.zeros([bottom-top,right-left]) for xr in range(new_image.shape[0]): for yr in range(new_image.shape[1]): if(path.contains_point([top+xr,left+yr])): new_image[xr, yr] = x[top+xr, left+yr] image_patch = x[top:bottom,left:right] plt.imshow(image_patch) plt.show() plt.imshow(new_image) plt.show()
doc_23525317
The cordova-res command returns an error. Here what is returns with the --verbose option. cordova-res Caught fatal error: [Error: pngload_buffer: non-recoverable state cordova-res pngload_buffer: non-recoverable state cordova-res pngload_buffer: non-recoverable state cordova-res pngload_buffer: non-recoverable state cordova-res vips2png: unable to write to target target cordova-res ] +361ms Error: pngload_buffer: non-recoverable state pngload_buffer: non-recoverable state pngload_buffer: non-recoverable state pngload_buffer: non-recoverable state vips2png: unable to write to target target What could be wrong ?
doc_23525318
Can anyone help me out with this? This is my Adapter: public class AdapterListViewData extends BaseAdapter{ private LayoutInflater mInflater; private Context context; private ArrayList<DataShow> listData = new ArrayList<DataShow>(); public AdapterListViewData(Context context,ArrayList<DataShow> listData) { this.context = context; this.mInflater = LayoutInflater.from(context); this.listData = listData; } public int getCount() { // TODO Auto-generated method stub return listData.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return position; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub HolderListAdapter holderListAdapter; if(convertView == null) { convertView = mInflater.inflate(R.layout.adapter_listview, null); holderListAdapter = new HolderListAdapter(); holderListAdapter.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle); holderListAdapter.txtDetail = (TextView) convertView.findViewById(R.id.txtDetail); holderListAdapter.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); convertView.setTag(holderListAdapter); }else{ holderListAdapter = (HolderListAdapter) convertView.getTag(); } holderListAdapter.txtTitle.setText(listData.get(position).getTitle()); holderListAdapter.txtDetail.setText(listData.get(position).getDetail()); holderListAdapter.checkBox.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context,"CheckBox "+ position +" check!!",Toast.LENGTH_SHORT).show(); } }); convertView.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context,"List "+ position +" click!!",Toast.LENGTH_SHORT).show(); } }); return convertView; } } MainActivity: public class CustomListViewActivity extends Activity { private AdapterListViewData adapterListViewData; private ArrayList<DataShow> listData = new ArrayList<DataShow>(); private ListView listViewData; String AddedTask ; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = getIntent(); listViewData = (ListView)findViewById(R.id.listViewData); if (intent.hasExtra("NewTask")) { AddedTask = this.getIntent().getExtras().getString("NewTask"); listData.add(new DataShow(AddedTask,"")); } adapterListViewData = new AdapterListViewData(getBaseContext(),listData); listViewData.setAdapter(adapterListViewData); adapterListViewData.notifyDataSetChanged(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar actions click switch (item.getItemId()) { case R.id.action_settings: return true; case R.id.action_add_task: Intent i = new Intent(CustomListViewActivity.this, AddTask.class); startActivity(i); return true; default: return super.onOptionsItemSelected(item); } } } DataShow: public class DataShow { private String title; private String detail; public DataShow(String title,String detail) { // TODO Auto-generated constructor stub this.title = title; this.detail = detail; } public String getTitle(){ return this.title; } public String getDetail(){ return this.detail; } } Holder: public class HolderListAdapter { TextView txtTitle; TextView txtDetail; CheckBox checkBox; } Second Activity: public class AddTask extends Activity { Button addtask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_task); // get action bar ActionBar actionBar = getActionBar(); // Enabling Up / Back navigation actionBar.setDisplayHomeAsUpEnabled(true); addtask = (Button) findViewById(R.id.btnaddlist); findViewById(R.id.btnaddlist).setOnClickListener( new View.OnClickListener() { public void onClick(View arg0) { EditText edit = (EditText) findViewById(R.id.tskname); Intent i = new Intent(AddTask.this, CustomListViewActivity.class); //Bundle bundle = new Bundle(); String TaskName = edit.getText().toString(); //bundle.putString("NewTask", TaskName); i.putExtra("NewTask", TaskName); //i.putExtras(bundle); startActivity(i); } }); } } A: I believe you should call adapterListViewData.notifyDataSetChanged(); inside of if (intent.hasExtra("NewTask")) { AddedTask = this.getIntent().getExtras().getString("NewTask"); listData.add(new DataShow(AddedTask,"")); } That is, if (intent.hasExtra("NewTask")) { AddedTask = this.getIntent().getExtras().getString("NewTask"); listData.add(new DataShow(AddedTask,"")); // you are adding new data here adapterListViewData.notifyDataSetChanged(); // just refresh the adapter here } For debugging purpose, check what value you're getting for NewTask in MainActivity.class. Log.d("track",AddedTask); DataShow class constructor expects a title and detail. Did you check whether it adds the value & you missed detail which is empty right? listData.add(new DataShow(AddedTask,"")); Try supplying static data. One more thing, check whether your adapter is null or not when adding new data send back from the secondActivity by, if (adapterListViewData != null) { AddedTask = this.getIntent().getExtras().getString("NewTask"); listData.add(new DataShow(AddedTask,"")); adapterListViewData.notifyDataSetChanged(); } else { adapterListViewData = new AdapterListViewData(getBaseContext(),listData); listViewData.setAdapter(adapterListViewData); } A: You are creating a new instance of adapterListViewData everytime your onCreate is called that is why the previous data has been wiped out. Add a checking in your onCreate to prevent this from happening. if ( adapterListViewData == null ) { adapterListViewData = new AdapterListViewData(getBaseContext(),listData); listViewData.setAdapter(adapterListViewData); } A: Your old data got removed becaus it is not transmitted to the new activity that you start after creating the new item. You should use startActivityForResult to create new task and call Add the new task to the list adapterListViewData in onActivityResult and call notifyDataSetChanged in it.
doc_23525319
Currently I'm looking into setting up SysInternals' procdump.exe to monitor an application of ours that exhibits spurious disappearances -- that is, the user reports that the application is simply "gone" without any trace after a short visible hang of the application's window. My first idea was to run procdump -e -x . MyApp.exe which would record a crash dump when the application encounters an unhandled exception, but then I saw that there is also a -t switch, that -- -t - Write a dump when the process terminates. automatically generates a dump when the process terminates. Now the problem I have tested the -t switch with our app by inserting a ExitProcess or TerminateProcess call at a defined location where I can trigger it. While the app behaves as expected, i.e. TerminateProcess immediately "kills" the running app and ExitProcess takes a while because global cleanup is run, the dump generated this way is useless in both cases. The dumps I get for -t always contain only a sinlge thread (where the app was running over 20 thread at termination time) and the callstack isn't even at a useful location. (It just seems to be one random thread from the terminated app.) Am I doing something wrong? Can I usefully use procdump -t to track down unexpected calls of process exit functions at all? A: Can I usefully use procdump -t to track down unexpected calls of process exit functions at all? I think not and here's why: test process calc.exe CommandLine: "C:\Program Files\Sysinternals\procdump.exe" -t calc.exe I try to carefully suggest that procdump is waiting on calc.exe process handle. 0:000> kb ChildEBP RetAddr Args to Child 0017f2e0 77135e6c 75336872 00000002 0017f334 ntdll!KiFastSystemCallRet 0017f2e4 75336872 00000002 0017f334 00000001 ntdll!NtWaitForMultipleObjects+0xc 0017f380 76cbf14a 0017f334 0017f3a8 00000000 KERNELBASE!WaitForMultipleObjectsEx+0x100 0017f3c8 76cbf2c2 00000002 7ffdb000 00000000 kernel32!WaitForMultipleObjectsExImplementation+0xe0 0017f3e4 011c6135 00000002 0017f46c 00000000 kernel32!WaitForMultipleObjects+0x18 WARNING: Stack unwind information not available. Following frames may be wrong. 0017fc30 011c999e 00000003 013d1de0 013d1e78 procdump+0x6135 0017fc78 76cc1194 7ffdb000 0017fcc4 7714b495 procdump+0x999e 0017fc84 7714b495 7ffdb000 77ad79b5 00000000 kernel32!BaseThreadInitThunk+0xe 0017fcc4 7714b468 011c99f5 7ffdb000 00000000 ntdll!__RtlUserThreadStart+0x70 0017fcdc 00000000 011c99f5 7ffdb000 00000000 ntdll!_RtlUserThreadStart+0x1b 0:000> dd 17f46c 0017f46c 00000238 00000268 0:000> !handle 238 f Handle 238 Type Process Attributes 0 GrantedAccess 0x1fffff: Delete,ReadControl,WriteDac,WriteOwner,Synch Terminate,CreateThread,,VMOp,VMRead,VMWrite,DupHandle,CreateProcess,SetQuota,SetInfo,QueryInfo,SetPort HandleCount 5 PointerCount 52 Name <none> Object Specific Information Process Id 1580 Parent Process 2476 Base Priority 8 In the crash dump file gets stack last complete process thread (TID 3136) just before the end of the process. 0:000> ~ . 0 Id: dc8.c40 Suspend: -1 Teb: 7ffdd000 Unfrozen 0:000> .formats c40 Evaluate expression: Hex: 00000c40 Decimal: 3136 Crash dump file is created after the completion of the last thread, and before the end of the process.
doc_23525320
nan_location = df2.isnull() first_columns = list(range(1,len(df.columns))) second_columns = list(range(len(df.columns), len(df2.columns))) for i in range(len(nan_location)): if True in list(nan_location.iloc[i]): if list(np.where(list(nan_location.iloc[i]))[0]) == first_columns: if list(np.where(list(nan_location.iloc[i+1]))[0]) == colunas_segundo: for colunas in second_columns: df2.at[i+1, df2.columns[colunas]]=df2[df2.columns[colunas]][i] df2=df2.drop(df2.index[i]) elif list(np.where(list(nan_location.iloc[i]))[0]) == second_columns: if list(np.where(list(nan_location.iloc[i+1]))[0]) == first_columns: for colunas in first_columns: df2.at[i+1, df2.columns[colunas]]=df2[df2.columns[colunas]][i] df2=df2.drop(df2.index[i])
doc_23525321
/outputs [ { id: 0, ... } { id: 1, ... } ] /outputs/:id { id: 0, ... } Is there a community adapter which supports this style? Regards, Bodo A: I hacked the origin adapter myself. I currently only tested create and findAll but the rest should work too: https://gist.github.com/bodokaiser/5858197
doc_23525322
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, p_date)) [date], SUM(p_amount) [sum] FROM tbl_Payments WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, p_date)) BETWEEN '20130701' AND '20130731' GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, p_date)) column names: p_date,p_amount A: Your query looks correct except few things like * *Replace [] with backticks "`" for escaping *DATE and TIME function syntax are different in MySQL than SQL Server. For more information on MySQL DATE and TIME functions see Date and Time Functions *Try using a minimum date like 1-1-1 instead of 0 select DATEDIFF('1-1-1', now()) select DATE_ADD('1-1-1', interval DATEDIFF(now(), '1-1-1') day); With all this the below query should work fine in MySQL SELECT DATE_ADD('1-1-1', interval DATEDIFF(p_date, '1-1-1') day) `date`, SUM(p_amount) `sum` FROM tbl_Payments WHERE DATE_ADD('1-1-1', interval DATEDIFF(p_date, '1-1-1') day) BETWEEN '20130701' AND '20130731' GROUP BY DATE_ADD('1-1-1', interval DATEDIFF(p_date, '1-1-1') day)
doc_23525323
However, now that I've finished implementation based on Chrome's behaviour, I came to realize that none of this is working in Firefox. That is I cannot pick any date at all when the calendar opens up. All the dates are deactivated and not clickable. I have tried to find the reason for this through a google search but cannot find anything related to this problem. Any idea why this is happenning and how to fix it?
doc_23525324
[Output] [1]: https://i.stack.imgur.com/IZoa3.png Here's my whole js file that is connected to an react application. import React from "react"; function ShowHidePassword(){ const [values, setValues] = React.useState({ password: "", passwordConf: "", showPassword: true, }); const clickShowPassword = (event) => { setValues({ ...values, showPassword: !values.showPassword }); event.preventDefault(); }; const passwordChange = (prop) => (event) => { setValues({ ...values, [prop]: event.target.value }); }; const mouseDownPassword = (event) => { event.preventDefault(); }; return ( <div> <input type={values.showPassword ? "text" : "password"} onChange={passwordChange("password")} value={values.password} id="signup-password" placeholder="PASSWORD" /> <input type={values.showPassword ? "text" : "passwordConf"} onChange={passwordChange("passwordConf")} value={values.passwordConf} id="signup-password-confirm" placeholder="CONFIRM PASSWORD" /> <br/> <button className="hide-password2" onClick={clickShowPassword} onMouseDown={mouseDownPassword}> {values.showPassword===false? <i className="bi bi-eye-slash"></i> :<i className="bi bi-eye"></i> } Show Password </button> </div> ); }; export default ShowHidePassword; A: In your second input you used passwordConf as an input type, I think this happened because u copied the first input and batch-replaced all "password" words with "passwordConf", happens to the best of us :)
doc_23525325
I cannot also publish to a remote cluster using Visual Studio. As I get the following error: WARNING: Failed to contact Naming Service. Attempting to contact Failover Are there any alternative ways of pushing up an application? The Azure Service Fabric on Azure experience just isn't working for me and I've wasted days on it. Thanks in advance! Powershell deployment script below: # Variables $endpoint = 'XXX-asf.australiaeast.cloudapp.azure.com:19000' $privateThumbprint = 'XXX' $publicThumbprint = 'XX' $projectPath = "C:\dev\asf-network-hops\AsfNetworkHops\AsfNetworkHops\AsfNetworkHops.sfproj" $projectConfiguration = "Debug" $packagePath = Resolve-Path "$projectPath\..\pkg\$projectConfiguration" $applicationTypeName = "AsfNetworkHopsType" $applicationName = "fabric:/AsfNetworkHops" $imageStoreConnectionString = "fabric:ImageStore" # Connect # $conn = Connect-ServiceFabricCluster -ConnectionEndpoint $endpoint ` # -KeepAliveIntervalInSec 10 ` # -X509Credential -ServerCertThumbprint $privateThumbprint ` # -FindType FindByThumbprint -FindValue $publicThumbprint ` # -StoreLocation CurrentUser -StoreName My $imageStoreConnectionString = "" $conn = Connect-ServiceFabricCluster -ConnectionEndpoint XXX-asf.australiaeast.cloudapp.azure.com:19000 ` -KeepAliveIntervalInSec 10 ` -X509Credential -ServerCertThumbprint XXX` -FindType FindByThumbprint -FindValue XXX` -StoreLocation CurrentUser -StoreName My if (-not $conn) { $conn throw "Connection error!" } # Clean, Compile, & Package dotnet clean $projectPath /p:Configuration=$projectConfiguration /nologo dotnet msbuild $projectPath /t:Package /nologo /p:Platform="x64" /p:Configuration=$projectConfiguration /nologo /p:WarningLevel=1 Write-Host "Uploading package $packagePath" Copy-ServiceFabricApplicationPackage $packagePath -ImageStoreConnectionString $imageStoreConnectionString -ApplicationPackagePathInImageStore $applicationTypeName -ShowProgress -ShowProgressIntervalMilliseconds 500 -TimeoutSec 1000000 -CompressPackage
doc_23525326
localpouchdb.sync(cloudantremoteDBURL, { doc_ids:['1450853987668'] }) Some error is thrown by cloudant error: true message: "Something wrong with the request" name: "bad_request" reason: "filter parameter must be of the form `designname/filtername`" Anyone able to syn pouchDB with cloudant using doc_ids options? A: I raised a support ticket with IBM Cloudant, and confirmed that _doc_ids filter is not yet implemented in the cloudant. Following is the response from their support: Unfortunately, Cloudant doesn't currently implement the _doc_ids filter on the _changes feed. We are planning a release early in the new year which includes the latest CouchDB feature set, including the _doc_ids filter. A: According to the docs on sync http://pouchdb.com/api.html#sync you should be setting the source and target, then passing the doc_ids into the options Something like PouchDB.sync(localDB, cloudantremoteDBURL, { doc_ids:['1450853987668'] })
doc_23525327
Sample data: Start End id 1 2 01 2 3 01 3 0 01 3 4 02 4 7 02 In this I should merge the rows with the same id of the sequential rows and start attribute of beginning row is less than end value of the last row. Also should store them in a table Output of sample input: Start End id 1 3 01 3 0 01 3 7 02 The logic is failing with the procedure I wrote. A: Assuming that your data is good (no gaps in start/end): select MIN(Start) [Start], MAX(End) [End], id from YourTable group by id
doc_23525328
So, my question is how do I make sure, pacakges not installed through composer get registered in the autoloader A: The best way would be not to pull manualy from your private repo, but use composer also in this case. To accomplish this, you will need a private composer repository - like one with satis. If that is not an option for any reason, you can configure the autoloader in your project /composer.json like this: { "name": "...", "autoload": { "psr-0": { "MyVendor\\MyBundleBundle": "vendor/foo", } }, .... } But I strongly recommend the satis way.
doc_23525329
The performance of this app was good until it was modified to use VCL styles. The group doing that work had to abandon the effort when it was found that the themed version might take over a minute to redraw itself after a single click. It turned out that enabling double-buffering at the form level worked to make the repainting performance acceptable when the user clicks on a control. Scrolling is still a problem however. The controls on the form are not able to paint themselves fast enough to keep up with a user scrolling by rolling the mouse wheel. The scrollbar gets moved, a part of the client area gets redrawn, then the next mouse wheel message gets processed, a little bit of the client gets redrawn, and so on until the user quits rolling the mouse and there's time to redraw the whole thing. The code that does the scrolling looks like this: procedure ScrollControl(Window: TScrollingWinControl; ScrollingUp: boolean; Amount: integer = 40); var Delta: integer; // This is needed to tell the child components that they are moving, // The TORCombo box, for example, needs to close a dropped down window when it moves. // If Delphi had used standard scroll bars, instead of the customized flat ones, this // code wouldn't be needed procedure SendMoveMessage(Ctrl: TWinControl); var i: integer; begin for i := 0 to Ctrl.ControlCount - 1 do begin if Ctrl.Controls[i] is TWinControl then with TWinControl(Ctrl.Controls[i]) do begin SendMessage(Handle, WM_MOVE, 0, (Top * 65536) + Left); SendMoveMessage(TWinControl(Ctrl.Controls[i])); end; end; end; begin Delta := Amount; if ScrollingUp then begin if Window.VertScrollBar.Position < Delta then Delta := Window.VertScrollBar.Position; Delta := - Delta; end else begin if (Window.VertScrollBar.Range - Window.VertScrollBar.Position) < Delta then Delta := Window.VertScrollBar.Range - Window.VertScrollBar.Position; end; if Delta <> 0 then begin Window.VertScrollBar.Position := Window.VertScrollBar.Position + Delta; SendMoveMessage(Window); end; end; What I think I want to do is to (right before the outermost call to SendMoveMessage) * *make a DC for Window *allocate an offscreen bitmap the size of Window's client area *arrange for all drawing operations on Window and its children to be drawn to the offscreen bitmap *Call SendMoveMessage and *bitblt the offscreen bitmap into Window's client area and free the bitmap and DC. But I cannot see how to do step 3. Is it even possible?
doc_23525330
[ { "id": 1, "name": "Snoop Dogg" }, { "id": 2, "name": "Eminem" }, { "id": 3, "name": "50 Cent" } ] Is it possible? If it is how? I've tried tuple validation - but it's not perfect cause order matters there Thanks in advance for replies! A: You can do that with a combination of allOf and contains: { "allOf": [ { "contains": { "const": [ ... list0 ... ] } }, { "contains": { "const": [ ... list1 ... ] } }, { "contains": { "const": [ ... list2 ... ] } } ] }
doc_23525331
@IBOutlet weak var previousLabel: UILabel! @IBOutlet weak var backButton: UIButton! var delegate: FourthToFirst? var label = "" // MARK: - Lifecycle method override func viewDidLoad() { super.viewDidLoad() previousLabel.text = label let fourthViewController = storyboard?.instantiateViewController(withIdentifier: "FourthViewController") as? FourthViewController navigationController?.pushViewController(fourthViewController!, animated: true) } // MARK: - IBAction @IBAction func backToFirst(_ sender: Any) { navigationController?.popToRootViewController(animated: true) } Actually I am in fourthviewController it was going recursively(i.e pushing the fourthViewcontroller again and again, nonstop) if I pressed back button in the controller I have to go back(i.e firstviewcontroller) problem is: In my code it was going (i.e non stop) I can't press the back button to go back(i.e firstviewcontroller) A: navigationController?.popViewController(animated: true) instead of navigationController?.popToRootViewController(animated: true) could be what's you need mate. (Based on what's you just edited)
doc_23525332
A: Use setStore or setStoreId methods: $collection = Mage:getResourceModel('catalog/category_collection'); // or $collection = Mage::getModel('catalog/category')->getCollection(); $collection->setStoreId($myStoreId) ->load(); UPDATE: There is a simple script to check this: <?php require 'app/Mage.php'; Mage::app('admin'); $collection = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('name') ->setStoreId(2) ->load(); echo $collection->count(), "\n"; foreach ($collection as $item) { echo $item->getName(), "\n"; } If you have 3 store views there will 3 storeIds. There are 0 - for admin store, 1 - for default store and 2 (or other value) for another store. I have just checked this and it works. A: I have add below code and its working for me $storecategoryid = Mage::app()->getStore($storeid)->getRootCategoryId(); from this code i get store root categoryid. $category = Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('is_active',array('eq' => 1))->load(); from this i get whole category collection foreach($category as $cat) { if($cat->getData('level')==2 && $cat->getData('parent_id')==$storecategoryid) { echo 'my code'; } } This way I get store category. A: $rootCategoryId = Mage::app()->getStore()->getRootCategoryId(); $categories = Mage::getModel('catalog/category')->getCollection(); $categories->addAttributeToFilter('path', array('like' => "1/{$rootCategoryId}/%")); A: Props going to @xpoback for the correct answer. I wanted to reiterate the answer as there are a few answers that are somewhat correct and some that are not. Short answer, use this: $rootId = Mage::app()->getStore()->getRootCategoryId(); $collection = Mage::getModel('catalog/category') ->getResourceCollection() ->addAttributeToSelect('*') ->addFieldToFilter('path', array('like' => "1/{$rootId}/%")) ->addIsActiveFilter(); For all who want to know the issues with other answers read on. First off, the @Muffadal's answer is functional, but is extremely slow in terms of performance. You want to keep the data querying up to mySQL and not use php looping over a big collection (provided you have more than a few categories in your store). The comment under that answer to use addPathsFilter('/' . $storecategoryid . '/') is also correct, but will be slower than using the LIKE operator in this case (see article) @Serjio's method will not work in terms of distinguishing between different categories. What it will do is pull store specific translations. Example Store 1 has named the category Rings, Store 2 has named the same category My Rings. If we make the call from store 2 using his code, it will pull all categories no matter the Root, but will pull the Store 2's naming convention - My Rings A: In Magento 1.9 $storeId=2; $rootCategoryId = Mage::app()->getStore($storeId)->getRootCategoryId(); $categories = Mage::getModel('catalog/category') ->getCollection() ->setStoreId($storeId) ->addFieldToFilter('is_active', 1) ->addAttributeToFilter('path', array('like' => "1/{$rootCategoryId}/%")) ->addAttributeToSelect('*'); foreach($categories as $categorie) { $catid=$cat->getId(); $catname=$categorie->getName(); $catp=catp$categorie->getParent_id(); }
doc_23525333
SQL_ATTR_CONNECTION_TIMEOUT = 113 connection_timeout = 3 login_timeout = 3 connection = pyodbc.connect('DSN=Visual FoxPro Database;UID=;;SourceDB=Comp.DBC;' 'SourceType=DBC;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;',timeout=login_timeout,attrs_before={SQL_ATTR_CONNECTION_TIMEOUT: connection_timeout}) cursor = connection.cursor() cursor.execute("select from database") rows = cursor.fetchall() alot of the documentation mentions to try connection.timeout = 3 but this does not work it breaks the script. Whats the simliest way to fix this? im using mkleehammer/pyodbc to run the query. The code works fine apart from the timeout
doc_23525334
import sys exitCode = 2 if(sys.argv.__len__() > 1): exitCode = sys.argv[1] print('exit code is ' + str(exitCode)) sys.exit(exitCode) I am calling it from a .bat file like this: @echo off cd C:\Users\bmq22\projects\Python\ExitCodeTesting\dist main.exe 10 echo return code is: %ERRORLEVEL% pause I was hoping that %ERRORLEVEL% would contain the return code from the exe (10 in this case), but it does not. This is the output from the .bat file: exit code is 10 10 return code is: 1 Press any key to continue . . . So I can see my Python return code printed on the screen, but I can't figure out how to capture it for use in the batch file. Any help is appreciated. A: Update: I am an idiot. Needed to convert the exit code argument to an int before exiting.
doc_23525335
My mind... has exploded. Consider: use strict; my Int $n = 6; my Str $x = "a"; my @l = $n, $x; say @l ~~ List; Prints True, as expected. Consider, then: use strict; my Int $n = 6; my Str $x = "a"; my List @l = $n, $x; # <-- only change is the type notation say @l ~~ List; Which dies with: Type check failed in assignment to @l; expected List but got Int So... the type of List is List but I can't say it's List because that's a sin! What's going on here? Is this a bug? Or am I bringing my irrelevant Python and Go idioms to Perl and breaking things? A: my List @l = $n, $x; doesn't do what you think it does. It doesn't declare that @l is a List. It declares that the elements of @l will be Lists. You don't need to declare that @l will be an array; you already did that when you used the sigil. You can move the explosion around by replacing List with Int to make Perl 6 expect a list of Ints. A: my List @l; is shorthand notation for my @l is Array of List; which places a List type constraint on the elements of the array. The type constraint on the container is already expressed via the @ sigil, corresponding to the role Positional, whereas a % sigil corresponds to the role Associative. The case of $ variables is similar insofar as there's also a container involved (a Scalar) with a constraint on its single element. However, the constraint also allows direct rebinding to a decontainerized value1. 1 If the above does not make sense to you, you should look into the difference between assignment = and binding :=. It might also be instructive to inspect the variable via .VAR.WHAT. Note that we can also rebind to another scalar container as long as its element meets the type constraint at time of binding. This can be used to subvert the type system: my Int $a; my $b = 42; $a := $b; $b = "not cool"; say $a; Not cool :(
doc_23525336
function calcLog(val) { return (val > 0) ? Math.log(val * Math.E) : null; } function calcAntiLog(val) { return (val > 0) ? Math.round(Math.exp(val) / Math.E) : null; } function calcTotalAntiLog(valMatrix, idx) { if (valMatrix) { sum = 0; for (i = 0; i < valMatrix.length; i++) { sum += calcAntiLog(valMatrix[i][idx]); } return sum; } return ""; } function calcTotalAntiLog2(hcObj) { if (hcObj) { var idx = hcObj.x; sum = 0; for (i = 0; i < hcObj.axis.chart.series.length; i++) { sum += calcAntiLog(hcObj.axis.chart.series[i].yData[idx]); } return sum; } return null; } function das(hcObj) { if (hcObj) { var idx = hcObj.x; sum = 0; zeroVisits = 0; for (i = 0; i < hcObj.axis.chart.series.length; i++) { sum += calcAntiLog(hcObj.axis.chart.series[i].yData[idx]); if (i == 0) zeroVisits = sum; } return (100 * (sum - zeroVisits)) / sum; } return null; } Please refer http://jsfiddle.net/rutup/6hxPU/26/
doc_23525337
* *Search for a list of Customer's *Get a couple of Field Values, one of which is used in the next Search, the other is the ID *Search for a list of Custom Records, the criteria being one of the fields I just fetched *Get a field value *And use the Customer ID fetched earlier to assign the Custom Record field value to a Custom field on the Customer. But it is dropping out on the second search, saying that it is returning "undefined" due to invalid Search Criteria. I'm assuming that the field I get from the first search is not working in the Criteria of the second search? My code is below - is it an obvious one (as usual), or is it literally the wrong way to go about this? /** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/search'], function getShipSuburbId(search) { function execute() { var customerSearchObj = search.create({ type: "customer", filters: [ ["custentity_store_shipping_suburb","isnotempty",""] ], columns: [ search.createColumn({ name: "entityid" }), search.createColumn({name: "custentity_store_shipping_suburb"}) ] }); var custSearchResult = customerSearchObj.runPaged({pageSize: 1000}); log.debug({title: "customerSearchObj result count", details: custSearchResult.count}); var custNumPages = custSearchResult.pageRanges.length; var custAllResults = []; var i = 0; while (i < custNumPages) { custAllResults = custAllResults.concat(custSearchResult.fetch(i).data); i++; } return custAllResults; for (var j = 0; j < custAllResults.length; j++) { var currentRecord = custAllResults[j].getValue({ name: "entityid" }); var shipSub = custAllResults[j].getValue({ name: "custentity_store_shipping_suburb" }); }; var shipSubIdSearch = search.create({ type: "customrecord_suburb", filters: [ ["name","is",shipSub] ], columns: [ search.createColumn({ name: "internalid", summary: "MAX", label: "Internal ID" }) ] }); var allSubIdResults = shipSubIdSearch.runPaged({pageSize: 1}); log.debug({title: "shipSubIdSearch result count", details: allSubIdResults.count}); var subNumPages = custSearchResult.pageRanges.length; var subAllResults = []; var m = 0; while (m < subNumPages) { subAllResults = subAllResults.concat(allSubIdResults.fetch(m).data); m++; } return subAllResults; for (var k = 0; k < subAllResults.length; k++) { var shipSubId = subAllResults[k].getValue({ name: "internalid" }); }; var setSuburbId = currentRecord.setValue({ fieldId: 'custentity_shipping_suburb_id', value: shipSubId }); return setSuburbId; } return { execute : execute }; }); NEW CODE BELOW /** *@NApiVersion 2.x *@NScriptType ScheduledScript */ define(['N/search', 'N/record'], function getShipSuburbId(search, record) { function execute() { var customerSearchObj = search.create({ type: "customer", filters: [ ["custentity_store_shipping_suburb", "isnotempty", ""] ], columns: [ search.createColumn({ name: "entityid" }), search.createColumn({name: "custentity_store_shipping_suburb"}) ] }); // The first search, which draws a list of Customers var custSearchResult = customerSearchObj.runPaged({pageSize: 1000}); // Run paged log.debug({title: "customerSearchObj result count", details: custSearchResult.count}); var custNumPages = custSearchResult.pageRanges.length; var custAllResults = []; var i = 0; while (i < custNumPages) { custAllResults = custAllResults.concat(custSearchResult.fetch(i).data); i++; } for (var j = 0; j < custAllResults.length; j++) { var currentRecord = custAllResults[j].getValue({ name: "entityid" }); var shipSub = custAllResults[j].getValue({ name: "custentity_store_shipping_suburb" }); log.debug({title: "currentRecord", details: currentRecord}); log.debug({title: "shipSub", details: shipSub}); // I've left this "for" operation open for the next search - possible issue? var shipSubIdSearch = search.create({ type: "customrecord_suburb", filters: [ ["name", "is", shipSub] ], columns: [ search.createColumn({ name: "internalid", summary: "MAX", label: "Internal ID" }) ] }); // Second search. This should only return one result each time it is run var subIdRun = shipSubIdSearch.run(); log.debug({title: "subIdRun result count", details: subIdRun.count}); var shipSubId = subIdRun.each( function (result) { log.debug({ title: "Fetch ID", details: result.getValue({name: "internalid"}) }) return true; }); log.debug({title: "shipSubId result", details: shipSubId}); var myRecord = record.load({ type: 'customer', id: currentRecord }); // Load the Customer record, based on the id fetched in the first search log.debug({title: "myRecord", details: myRecord}); myRecord.setValue({ fieldId: 'custentity_shipping_suburb_id', value: shipSubId }); // And set the value of the Custom field, based on value from second search } } return { execute : execute }; }); And screenshot of Execution Log on New Script: A: I tried to edit some of your code to get your closer to the answer. I've left comments explaining steps you'll need to take. Try this and let me know how it goes! /** *@NApiVersion 2.1 *@NScriptType ScheduledScript */ define(['N/search', "N/record"], function (search, record) { function execute() { let customers = []; let storeShippingSuburbIds = []; let storeShippingSuburbId; let searchCustomers = search.create({ type: "customer", filters: [ ["custentity_store_shipping_suburb", "isnotempty", ""] ], columns: [ search.createColumn({name: "entityid"}), search.createColumn({name: "custentity_store_shipping_suburb"}) ] }); var pagedData = searchCustomers.runPaged({pageSize: 1000}); pagedData.pageRanges.forEach(function (pageRange) { let page = pagedData.fetch({index: pageRange.index}); page.data.forEach(function (result) { customers.push([ result.getValue({name: "entityid"}), result.getValue({name: "custentity_store_shipping_suburb"}) ]) storeShippingSuburbIds.push(result.getValue({name: "custentity_store_shipping_suburb"})); return true; }); }); /* * I think you want the search operator of anyof here. */ search.create({ type: "customrecord_suburb", filters: [ ["name", "anyof", storeShippingSuburbIds] ], columns: [ search.createColumn({ name: "internalid", summary: "MAX", label: "Internal ID" }) ] }).run().each(function (result) { storeShippingSuburbId = result.getValue(result.columns[0]); }); /* * You'll need to use record.load() here or record.submitFields(), depending on a few things. * But, it won't work as it is because it doesn't know what the "current record" is. */ let myRecord = record.load(); myRecord.setValue({ fieldId: 'custentity_shipping_suburb_id', value: storeShippingSuburbId }); myRecord.save(); } return { execute: execute }; }); A: I have found the best way to approach multiple levels of searching, is to gather the results of each search into an array. Once I have finished dealing with the results of one search, then process each element of the array one by one, whether that be searching, querying, editing, etc. The advantages of this include: * *If a scheduled script, this allows me to check the governance usage after the first search, and reschedule with the array of results as a parameter if necessary. *Handling other logic like sorting or formulas on the array elements, before continuing with other operations. *Potentially faster processing, particularly if you don't need to process any further operations on some results of the first search. *This is just personal preference, but it makes it easier to split elements of the script into separate functions and maintain readability and logical sequence.
doc_23525338
private static final String CURRENT_VERSION_JOB_EXECUTION = "SELECT VERSION FROM %PREFIX%JOB_EXECUTION WHERE JOB_EXECUTION_ID=?"; by spring (it is already written in JdbcJobExecutionDao) i am gettting this error Encountered fatal error executing joborg.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0 it is not able to get record from batch_job_execution table but record is present in table. my app is running on kubernetes and i m getting this error from kubernetes but not from my local code. A: According to the documentation Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned. You can approach this in few ways: * *Modify your query to always return 1 result. *Catch the exception and apply a behavior that you find fit. For example you can check this guide and use it as an example. *Use query method instead to avoid this exception. Please let me know if that helped.
doc_23525339
I am migrating a working .Net Framework Website from IIS 8.5 on a Microsoft Windows Server 2012 to IIS 10 on a Microsoft Windows Server 2019. The new web site is showing the error HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. As far as I can see the website on the new server is configured the same as on the existing. Neither have directory Browsing enabled nor a default file set as is recommended by most of the posts which exist discussing this error. I have run the following which is also recommended. %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir The problem still exists. I came across a post saying there might be an issue if paths referenced in the web.config are not correct but they look fine. Has anyone got any insight into what else might cause this issue? Are there any differences between IIS 8.5 and IIS 10 or between windows servers 2012 and 2019 which might cause this issue? Thanks A: This problem occurs because the website doesn't have the Directory Browsing feature enabled. Also, the default document isn't configured. To resolve this problem, use one of the following methods: Method 1: Enable the Directory Browsing feature in IIS To resolve this problem, follow these steps: * *Start IIS Manager. To do it, select Start, select Run, type inetmgr.exe, and then select OK. *In IIS Manager, expand server name, expand Web sites, and then select the website that you want to change. *In the Features view, double-click Directory Browsing. *In the Actions pane, select Enable. Method 2: Add a default document To resolve this problem, follow these steps: * *Start IIS Manager. To do it, select Start, select Run, type inetmgr.exe, and then select OK. *In IIS Manager, expand server name, expand Web sites, and then select the website that you want to change. *In the Features view, double-click Default Document. *In the Actions pane, select Enable. *In the File Name box, type the name of the default document, and then select OK. More information you can refer to this link: HTTP Error 403.14 - Forbidden when you open an IIS webpage. A: All those clowns glibly posting that "HTTP Error 403.14 - Forbidden: The Web server is configured to not list the contents of this directory" can be fixed by configuring the web site by either enabling the Directory Browsing feature or adding a default document are really not understanding what they are talking about. Anyone can copy a solution from one post and paste to another. I'm not going to pretend I know what I am talking about but I have fixed my issue and will share what I did here to see in the hope it helps others. I created a project (of the same type as the application I was trying to deploy) using my IDE (MSVS) in the same .Net version of the application I was trying to deploy. In this case it was creation of an MVC project in .Net Framework 4.5. I did nothing to it. All I wanted was a skeleton. I replaced all the files in the home directory of the web site I had an issue with, with the files of this skeleton project. I attempted to browse to the web site and it worked successfully. Note the directory browsing was not enabled nor was a default directory set. This proved to me that those settings were irrelevant. Having googled around, some sites point to paths in config files causing an issue if they do not exist, eg a logging path to d:\logs where that directory was missing. It didn't fix my issue but there's no harm checking. I stumbled across a post which talked about the roles and features enabled on the server. In Web Server (IIS)/Web Server/Application Development they had selected "Application Initialisation" and "ASP". The Windows Sever 2012 server I was moving the application from, where it work without a hitch, did not have those selected so had not selected them on the Windows Server 2019 I was moving them to when I set that server up. It made no sense that this would be the solution but having tried everything else I activated those two options. Stone me if the issue was resolved. As a check I removed those two options and the problem came back and when I reselected them it went away again. This struck me as pretty conclusive only having thought I'd found the cause of the problem I built the website from scratch and the problem came back again. It took a number of iterations but eventually I got there, more by luck than judgement and whatever the cause was it was due to an issue in the application which wasn't being logged in event viewer so focus on permissions to files being written to: not only that the app pool account is set up on the directories it needs access to but also that it has modify or even full control. All those muppets robotically posting advice on configuring the web site by either enabling the Directory Browsing feature or adding a default document will no doubt copy this and paste it into their posts to claim the credit but c'est la vie. I hope this post is of use to someone, apart from those muppets.
doc_23525340
I want to block anyone from probing my server by IP urls (like http://192.168.1.1 -- any public IP address) while allowing properly URLs to my server (proper like http://www.example.com). I feel there are four ways: * *Create a virtual host entry in httpd.conf file that "traps an IP url. *Create a mod_rewrite entry to rewrite IP url that also "traps" it. *Create an IPTABLES entry that is capable of detecting IP urls and dropping those connection requests. *Do nothing because nothing can be done. Which of the three (or recommend alternative) would be the best way to handle it. How woudl I do it? Thanks. A: Very simple. Set the following as the VERY FIRST virtual host: NameVirtualHost *:80 <VirtualHost *:80> <Directory "/path/to/root/site"> AllowOverride All Options None Options Indexes FollowSymLinks Includes ExecCGI Order deny,allow Deny from none Allow from all php_admin_value open_basedir /path/to/root/site </Directory> ServerAdmin admin@localhost DocumentRoot "/path/to/root/site" ServerName NX-DOMAIN </VirtualHost> Inside of the /path/to/root/site, just make a simple .html file or something saying "404 Not Found" or even pop in a .htaccess redirect or something. For your real sites, add these as the second, third, fourth, etc... virtual hosts: <VirtualHost *:80> <Directory "/path/to/real/site1/"> AllowOverride All Options Indexes FollowSymLinks Includes ExecCGI Order allow,deny Allow from all </Directory> ServerAdmin you@domain.com DocumentRoot "/path/to/real/site1" ServerName www.domain.com ServerAlias domain.com php_admin_value open_basedir /path/to/real/site1 </VirtualHost> That way, any request to a domain you don't host (if someone points their domain to your IP or someone visits the raw IP) will get dumped to your custom error page. Hope this helps.
doc_23525341
let document: mongodb::bson::Document = client .database("demo") .collection("folder") .find_one(doc!{}) .await? .unwrap(); println("{:?}", document); // How to convert `document` to json string? I want to send this JSON string from server as response. A: mongodb::bson::Document implements Serialize from serde, so you can use serde_json::to_string, or other functions from serde_json to serialize the data to JSON.
doc_23525342
I am starting to think about spliting/partitioning this table by date, maybe action? so maybe anyone have any experience with that and can share some advice with me? big thanks for any help! CREATE TABLE `history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `barcode` varchar(100) DEFAULT NULL, `bag` varchar(100) DEFAULT NULL, `action` int(10) unsigned DEFAULT NULL, `place` int(10) unsigned DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, `old_price` decimal(10,2) DEFAULT NULL, `user` int(11) DEFAULT NULL, `amount` int(10) DEFAULT NULL, `rotation` int(10) unsigned DEFAULT NULL, `discount` decimal(10,2) DEFAULT NULL, `discount_type` tinyint(2) unsigned DEFAULT NULL, `original` int(10) unsigned DEFAULT NULL, `was_in_shop` int(10) unsigned DEFAULT NULL, `cate` int(10) unsigned DEFAULT NULL COMMENT 'grupe', `sub_cate` int(10) unsigned DEFAULT NULL, `comment` varchar(255) DEFAULT NULL, `helper` varchar(255) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `barcode` (`barcode`), KEY `action` (`action`), KEY `original` (`original`), KEY `created_at` (`created_at`), KEY `bag` (`bag`) ) ENGINE=InnoDB AUTO_INCREMENT=16274267 DEFAULT CHARSET=utf8 for example query: select cate, SUM(amount) AS amount, SUM(IF(discount>0,(price*amount)-discount, (price*amount))) AS sum, SUM(IF(discount>0,IF(discount_type=1, (discount*price)/100,discount),0) ) AS discount from history where (history.action = '4' and history.created_at >= '2017-11-01 00:00:00' and history.created_at <= '2017-11-23 23:59:59' ) and LENGTH(barcode) > 7 and history.deleted_at is null group by cate this query is used to get amount, sum, discount info about sold products (action 4) in this example it is information between 2017-11-01 and 2017-11-23 and EXPLAIN gives me this: id - 1 select_type - SIMPLE table - history type - ref possible_keys - action,created_at key - action key_len - 5 ref - const rows - 1444272 Extra - Using where; Using temporary; Using filesort so it takes 1.5 million rows with table that holds data from 2017-01-01 until now, so after 2 years it will take 3 million rows and etc... when I need to take just 2017-11 products sold information. And I have a lot of more queries similar to this one. A: * *Use smaller datatypes (shrinking the table size helps with performance) INT takes 4 bytes; other sizes are available. *PARTITIONing does not intrinsically provide any performance. *history.deleted_at is null -- consider actually deleting the rows. *Learn about 'composite' indexes, such as INDEX(action, created_at) . (Only one index is used at a time.) The big improvement comes by building and maintaining Summary Table(s); see http://mysql.rjweb.org/doc.php/summarytables . Then run the queries against them. And most of the indexes can go away. Fix some of those; then I can help you further. More A Comment asks about how to maintain the summary table id two different ways. Either can be viable, depending on more, as yet unspecified, details: * *INSERT INTO Fact table, and immediately use IODKU to insert or update the Summary table. *Do the summarization "on demand" -- This, when a user asks for the data, first run the INSERT .. SELECT .. to capture the not-yet-summarized rows and put the counts/subtotals into the Summary table. The latter choice works, but there are two things to watch out for: * *If no user comes along in a long time, then the summarization could be costly. The simple fix is to also have a cron job periodically "catching up". Be sure to interlock the code so that cron and user are not both updating the same rows at the same time. *If the Summary table has a 'natural' PRIMARY KEY, such as a date (day or hour) and a couple of dimension values, then you are like have trouble with the INSERT. Either avoid that as the PK (thereby leading to multiple rows, which is not 'bad') or use IODKU in the form INSERT ... ON DUPLICATE KEY ... SELECT ... GROUP BY ...; and use the VALUES(xx) function.
doc_23525343
using namespace boost::asio; ... io_service io_service_; io_service io_service_1; ip::tcp::acceptor* acceptor_; acceptor_ = new ip::tcp::acceptor(io_service_); ip::tcp::endpoint ep( ip::tcp::v4(), LISTEN_PORT); acceptor_->open(ep.protocol()); acceptor_->bind(ep); acceptor_->listen(); ip::tcp::acceptor* acceptor_1; acceptor_1 = new ip::tcp::acceptor(io_service_1); acceptor_1->open(ep.protocol()); acceptor_1->bind(ep); acceptor_1->listen(); ... boost::thread th( boost::bind(&io_service::run, &io_service_)); boost::thread th( boost::bind(&io_service::run, &io_service_1)); ... when running will display error dialog: boost::exception_detail::clone_impl< boost::exception_detail::error_info_injector > at memory location 0x001FF704. can you help me how to make a server with Multiple threads, each thread use an io_service instance? Update: as I read in Boost.Asio C++ Network Programming, have 3 way to use io_service with thread: * *Single-thread with one io_service and one handler thread(thread running io_service::run()) *Multi-threaded with a single io_service instance and several handler threads *Multi-threaded with several io_service instances and several threads I can implement case 1 and 2. But with case 3, I don't know how to implement it to handle many concurrent connections, should I use 1 thread to handle 1 io_service(as above)? Is case 3 has better performance(can handle more concurrent connections) than case 2? A: You can only have one acceptor listening on a given port. If you want to handle multiple clients with one port, you'll need to set the option reuse_address on your acceptor. That way the socket you pass to async_accept() will use a different port, leaving your listen port free to accept a connection from another client. boost::asio::io_service ios_; boost::asio::ip::tcp::acceptor acceptor_(ios_); void handle_client(boost::shared_pointer<boost::asio::ip::tcp::socket> sock); void start_accept(); int main() { boost::asio::ip::tcp::endpoint ep(ip::tcp::v4(), LISTEN_PORT); acceptor_.open(ep.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(ep); acceptor_.listen(); boost::thread_group threads; for (int i = 0; i < NUM_WORKER_THREADS; ++i) { threads.create_thread(boost::bind(&io_service::run, &ios_)); } start_accept(); threads.join_all(); } void start_accept() { boost::shared_pointer<boost::asio::ip::tcp::socket> sock(ios_); acceptor_.async_accept(*sock, boost::bind(handle_client, sock)); } void handle_client(boost::shared_pointer<boost::asio::ip::tcp::socket> sock) { start_accept(); // talk to the client } See Boost's HTTP server example for a more complete example. A: You can use multiple threads, but you need to use 1 acceptor for a port. IO services are thread-safe, so you can use one service on many threads. You can even have multiple io services, no problem. You can't bind multiple acceptors to the same port though (unless you bind to different logical network interfaces, perhaps, but that's not really "the same port" then). #include <boost/asio.hpp> #include <boost/thread.hpp> using namespace boost::asio; using namespace boost; int main() { io_service io_service_; ip::tcp::acceptor acceptor_(io_service_, { {}, 6767 }); acceptor_.bind({ ip::tcp::v4(), 6767 }); boost::thread_group tg; for (unsigned i = 0; i < thread::hardware_concurrency(); ++i) tg.create_thread(boost::bind(&io_service::run, &io_service_)); // ... // tg.join_all(); }
doc_23525344
(However, I made an apparently huge mistake a couple of days ago: I ran into an error when reading the csv file, so I specified the engine attribute of pd.read_csv as 'python' and I believe this launched it all: every time I re-ran the script that updates the csv, all the text data got encoded again, possibly in utf-8 instead of csv's orriginal windows-1252.) Edit: I realized thank to Tomalak's comments below that the real problem wasn't this modification but me manually modifying the csv file using Excel a number of times along the way. The older the csv entries, the more the subsequent encoding-recoding affected them: for the newest entries, there is no issue but for the oldest ones, I now have a single heart emoji appearing in the csv as: * *��� I found numerous entries in the csv file where I could easily apply the .encode('windows-1252').decode('utf-8') 3-6 times (depending on how old the given entry is and therefore how many times it got re-encoded) and obtained a favorable outcome, such as: * *😞 stands for the sad/disappointed face emoji (). Applying the encoding-decoding pattern four times returned: \U0001f61e which is good enough for me; I can easily use unicodedata library's excellent conversion method to obtain their corresponding unicodedata.name. I believe that's how I should be storing emojis from now on... My understanding about applying the above mentioned encode-decode pattern numerous times is that I cannot overdo it. If one string needs only three of these patterns while the next cell needs six, I could just do something like this (yes, I know iterrows() is a terribly inefficient approach but just for the example): for idx, _ in df.iterrows(): tmp = df.loc[idx, 'text'] for _ in range(6): tmp = tmp.encode("windows-1252").decode("utf-8") df.loc[idx, 'text'] = tmp The problem is, however, that there are still quite a lot of entries where the above solution doesn't work. Let's just consider the above mentioned encoded string which stands for a red heart: * *��� Applying .encode("windows-1252").decode("utf-8") three times yields: ��� but when attempting to apply the pattern the fourth time, I get: UnicodeEncodeError: 'charmap' codec can't encode character '\ufffd' in position 1: character maps to <undefined>. My hunch is, not all strings were encoded by windows-1252...? Is there any hope to get back my data in an uncorrupted format?
doc_23525345
Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse (default-cli) on project CaseInstall: Execution default-cli of goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse failed: For artifact {null:null:null:jar}: The groupId cannot be empty. -> [Help 1] I am using STS 3.2.0 and maven 3.1.1 version. These are the dependencies I added, <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>2.7.7</version> </dependency> Did anyone face the same problem? UPDATE: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse (default-cli) on project CaseInstall: Execution default-cli of goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse failed: For artifac t {null:null:null:jar}: The groupId cannot be empty. -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse (default-cli) on project CaseInstall: Execution default-cli of goal org.apache.maven.plugins:mave n-eclipse-plugin:2.9:eclipse failed: For artifact {null:null:null:jar}: The groupId cannot be empty. at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:224) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:317) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:152) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214) at org.apache.maven.cli.MavenCli.main(MavenCli.java:158) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal org.apache.maven.plugins:maven-eclipse-plugin:2.9:eclipse failed: For artifact {null:null:null:jar}: The groupId cannot be empty. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:115) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208) ... 19 more Caused by: org.apache.maven.artifact.InvalidArtifactRTException: For artifact {null:null:null:jar}: The groupId cannot be empty. at org.apache.maven.artifact.DefaultArtifact.validateIdentity(DefaultArtifact.java:130) at org.apache.maven.artifact.DefaultArtifact.<init>(DefaultArtifact.java:123) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createArtifact(DefaultArtifactFactory.java:157) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createArtifact(DefaultArtifactFactory.java:117) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createArtifact(DefaultArtifactFactory.java:111) at org.apache.maven.artifact.factory.DefaultArtifactFactory.createArtifact(DefaultArtifactFactory.java:39) at org.apache.maven.repository.legacy.LegacyRepositorySystem.createArtifact(LegacyRepositorySystem.java:119) at org.apache.maven.project.DefaultProjectBuilder.initProject(DefaultProjectBuilder.java:604) at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:160) at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:312) at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:270) at org.apache.maven.project.artifact.MavenMetadataSource.retrieveRelocatedProject(MavenMetadataSource.java:578) at org.apache.maven.project.artifact.MavenMetadataSource.retrieve(MavenMetadataSource.java:191) at org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector.recurse(DefaultLegacyArtifactCollector.java:532) at org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector.recurse(DefaultLegacyArtifactCollector.java:584) at org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector.collect(DefaultLegacyArtifactCollector.java:144) at org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector.collect(DefaultLegacyArtifactCollector.java:100) at org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector.collect(DefaultLegacyArtifactCollector.java:782) at org.apache.maven.plugin.ide.AbstractIdeSupportMojo.doDependencyResolution(AbstractIdeSupportMojo.java:560) at org.apache.maven.plugin.ide.AbstractIdeSupportMojo.execute(AbstractIdeSupportMojo.java:507) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:106) ... 20 more [ERROR] Here is my pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.coder</groupId> <artifactId>WebserviceDemo</artifactId> <name>WebserviceDemo</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.7</java-version> <org.springframework-version>3.1.1.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> <cxf.version>2.7.7</cxf.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit</groupId> <artifactId>com.springsource.org.junit</artifactId> <version>4.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.test</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.10.Final</version> </dependency> <dependency> <groupId>net.sourceforge.jtds</groupId> <artifactId>jtds</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>20030825.184428</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>20030825.183949</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3</version> </dependency> <!-- Drools --> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>5.4.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>5.4.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-spring</artifactId> <version>5.4.0.Final</version> </dependency> <!-- Beanutils --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <!-- apache cxf --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12</version> <configuration> <forkMode>always</forkMode> <skipTests>true</skipTests> </configuration> </plugin> <plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-codegen-plugin</artifactId> <version>2.7.7</version> <executions> <execution> <id>generate-sources-proposal</id> <phase>generate-sources</phase> <configuration> <sourceRoot>src/main/java-generated</sourceRoot> <wsdlOptions> <wsdlOption> <wsdl>src/main/resources/wsdl/service.wsdl</wsdl> <extraargs> <extraarg>-p</extraarg> <extraarg>com.coder.service</extraarg> <extraarg>-autoNameResolution</extraarg> </extraargs> </wsdlOption> </wsdlOptions> </configuration> <goals> <goal>wsdl2java</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <configuration> <filesets> <fileset> <directory>src/main/java-generated</directory> </fileset> </filesets> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>com.springsource.repository.bundles.release</id> <name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name> <url>http://repository.springsource.com/maven/bundles/release</url> </repository> <repository> <id>com.springsource.repository.bundles.external</id> <name>SpringSource Enterprise Bundle Repository - External Releases</name> <url>http://repository.springsource.com/maven/bundles/external</url> </repository> <repository> <id>com.springsource.repository.bundles.milestone</id> <name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name> <url>http://repository.springsource.com/maven/bundles/milestone</url> </repository> <repository> <id>com.springsource.repository.bundles.snapshot</id> <name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name> <url>http://repository.springsource.com/maven/bundles/snapshot</url> </repository> <repository> <id>repository.springframework.maven.release</id> <name>Spring Framework Maven Release Repository</name> <url>http://maven.springframework.org/release</url> </repository> <repository> <id>repository.springframework.maven.milestone</id> <name>Spring Framework Maven Milestone Repository</name> <url>http://maven.springframework.org/milestone</url> </repository> <repository> <id>repository.springframework.maven.snapshot</id> <name>Spring Framework Maven Snapshot Repository</name> <url>http://maven.springframework.org/snapshot</url> </repository> <repository> <id>jboss</id> <name>JBoss repository</name> <url>https://repository.jboss.org/nexus/content/repositories/releases</url> </repository> </repositories> </project> UPDATE: Could someone help me on this, please!!! A: You are missing the groupId on a couple of plugins. I had this problem once as well. Try adding it to them. (You will have to look it up for what each is (the clean one is probably org.apache.maven.plugins ) Just from looking briefly I can see that it is missing from: <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <configuration> <filesets> <fileset> <directory>src/main/java-generated</directory> </fileset> </filesets> </configuration> </plugin> So they would (possibly) become: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <configuration> <filesets> <fileset> <directory>src/main/java-generated</directory> </fileset> </filesets> </configuration> </plugin> Good luck with it!
doc_23525346
I created a new application using Visual studio 2008. The only thing it does is Response.Write("Hello world!") in the onLoad-function. I compiled it and uploaded it to a virtual folder (app) in the ISV directory in CRM. If I now go to crm.mycrm.nl:5555/ISV/app I get: 'Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' doesn't exist. Parameter name: Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 With stack trace [ArgumentException: 'Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' doesn't exist. Parameter name: Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35] Microsoft.Crm.Authentication.BaseAuthenticationSettings.CreateType(String typeName, Type requiredBaseType) +265 Microsoft.Crm.Authentication.BaseAuthenticationSettings.CreateProvider(String typeName, IDictionary`2 configuration) +28 Microsoft.Crm.Authentication.AuthenticationPipelineSettings.LoadPipeline() +262 Microsoft.Crm.Authentication.AuthenticationPipelineSettings.get_AuthenticationProvider() +16 Microsoft.Crm.Authentication.AuthenticationEngine.Execute(Object sender, EventArgs e) +524 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 A: Okay, I fixed it. The thing is, you have to put your assemblies into the CRMWeb folder, and your aspx file into the ISV folder.
doc_23525347
I'd like to have a function that processes some input X and produces a gglot graph using geom_point. That function should allow to map columns of X to various aesthetics inside aes() (via arguments .shapefac, .colfac, etc.), but also allow to set e.g. point colour and shape manually (e.g. colour = "tomato"), outside of aes(). The problem If .shapefac or .colfac arguments are provided, the aesthetics get overridden by the specification of shape and colour, respectively. This is explained e.g. here. What I've tried One workaround would be to remove the shape and colour arguments, and allow them to be specified using ... in geom_point. This works, but needs some advanced R knowledge for a user of such a function. The question Does anybody know if there is * *a way to change the default setting for the shape and colour arguments outside of aes() in geom_point? *a way to override the specification of the shape and colour arguments, if an aesthetic is used? *another way to reach the goal stated above, without using ...? Any hints or explanations are much appreciated! The following function and plots hopefully illustrate the problem. define function library(mlbench) data("Ionosphere") cplot <- function(X, v = 1:ncol(X), .shapefac = NULL, .colfac = NULL, shape = 21, colour = "black", center = TRUE, scale = FALSE, x = 1, y = 2, plot = TRUE) { library(ggplot2) # some code processing X to Y d.pca <- prcomp(X, center = center, scale. = scale) Y <- data.frame(X, d.pca$x) v <- round(100 * (d.pca$sdev^2 / sum(d.pca$sdev^2)), 2) # plot PCA p <- ggplot(Y, aes_string(x = paste0("PC",x), y = paste0("PC",y))) + geom_point(aes_string(shape = .shapefac, colour = .colfac), shape = shape, color = colour) + labs(x = paste0("PC ", x, " (", v[x], "%)"), y = paste0("PC ", x, " (", v[y], "%)")) + theme_bw() if (plot) print(p) invisible(p) } setting colour and shape arguments outside aes() This works as it should. cplot(Ionosphere, v = 3:34, colour = "tomato", shape = 4) setting shape inside aes() when shape outside aes() has a default of 21 The default shape = 21 outside aes() overrides the shape aesthetic. cplot(Ionosphere, v = 3:34, .shapefac = "Class") setting colour inside aes() when colour outside aes() has a default of "black" The default colour = "black" outside aes() overrides the colour aesthetic. cplot(Ionosphere, v = 3:34, .colfac = "Class") failed trials to set default shape and colour to NULLor NA # results in an empty plot (shape = NA) cplot(Ionosphere, v = 3:34, .shapefac = "Class", shape = NA) #> Warning: Removed 351 rows containing missing values (geom_point). # results in an error cplot(Ionosphere, v = 3:34, .shapefac = "Class", shape = NULL) #> Error: Aesthetics must be either length 1 or the same as the data (351): shape Created on 2021-09-20 by the reprex package (v2.0.1) A: One option to achieve your desired result may look like so: * *If the aesthetics are provided set the color and/or shape params to NULL *Make use of modifyList to construct a list of arguments to be passed to geom_point which includes the mapping and the non-NULL parameters. Making use modifyList will drop any NULL. *Make use of do.call to call geom_point with the list of arguments. Note: I slightly changed your function to select only numeric columns for the PCA. library(mlbench) library(ggplot2) data(Ionosphere) cplot <- function(X, .shapefac = NULL, .colfac = NULL, shape = 21, colour = "black", center = TRUE, scale = FALSE, x = 1, y = 2, plot = TRUE) { col_numeric <- unlist(lapply(X, is.numeric)) # some code processing X to Y d.pca <- prcomp(X[, col_numeric], center = center, scale. = scale) Y <- data.frame(X, d.pca$x) v <- round(100 * (d.pca$sdev^2 / sum(d.pca$sdev^2)), 2) colour <- if (is.null(.colfac)) colour shape <- if (is.null(.shapefac)) shape mapping <- aes_string(shape = .shapefac, colour = .colfac) args <- modifyList(list(mapping = mapping), list(color = colour, shape = shape)) geom <- do.call("geom_point", args) p <- ggplot(Y, aes_string(x = paste0("PC", x), y = paste0("PC", y))) + geom + labs( x = paste0("PC ", x, " (", v[x], "%)"), y = paste0("PC ", x, " (", v[y], "%)") ) + theme_bw() if (plot) print(p) invisible(p) } cplot(Ionosphere, colour = "tomato", shape = 4) cplot(Ionosphere, .shapefac = "Class") cplot(Ionosphere, .colfac = "Class") cplot(Ionosphere, .colfac = "Class", .shapefac = "Class") cplot(Ionosphere, .shapefac = "Class", shape = NULL)
doc_23525348
\"(?P<citation>[^\"\.\;]+)\" It works, but it also captures empty citations " " which is a space character between the end of a citation and the beginning of the next one. Is there a way to exclude that without affecting any other space characters ? A: The negated character class [^".;]+ matches any char except the listed, which can also be a whitespace char. (Note athat you don't have to escape the characters in the character class) If you want to allow whitespace chars, but not only whitespace chars, you can use a negative lookahead (?!\s+") asserting that there are not only whitespace chars until the next double quote. "(?P<citation>(?!\s+")[^".;]+)" Regex demo Without using a lookahead, you can make sure to match at least a single char [^\s".;] except being one of the chars that you don't allow or matching a whitespace char between optional negated character classes. "(?P<citation>[^".;]*[^\s".;][^".;]*)" See another regex demo
doc_23525349
I tried to use android:launchMode="singleInstance" in my Manifest in every Activity. But this is not helping. I attache the Manifest file and screenshot. I would be very happy if you could help me. Cheers. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pekostudio.dogtrace"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-feature android:name="android.hardware.location.gps" /> <uses-feature android:name="android.hardware.bluetooth_le" /> <application android:allowBackup="true" android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:largeHeap="true" android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" android:launchMode="singleInstance" android:resizeableActivity="false" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> <receiver android:name=".Bluetooth.GetAllCollarsService$GetRawBluetoothDataReceiver" android:enabled="true"> <intent-filter> <action android:name="pekostudio.dogtrace.BLUETOOTH_RAW_DATA" /> </intent-filter> </receiver> <service android:name=".Utils.LocationFinder" android:exported="false" /> <service android:name=".Bluetooth.GetAllCollarsService" android:exported="false" /> <service android:name=".Bluetooth.BluetoothLeService" android:enabled="true" android:stopWithTask="true" /> <service android:name=".MapDownload.DownloadService" android:enabled="true" android:exported="true" /> <activity android:name=".Activities.GoogleMapActivity" android:configChanges="orientation" android:label="@string/app_name" android:launchMode="singleInstance" android:screenOrientation="portrait" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".Activities.SplashActivity" android:configChanges="orientation" android:screenOrientation="portrait" android:theme="@style/SplashTheme" android:launchMode="singleInstance"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Activities.OfflineMap" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".Activities.CompassActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".Activities.AnimalDetailActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:parentActivityName=".Activities.GoogleMapActivity" android:screenOrientation="portrait" android:theme="@style/AppTheme.NoActionBar"/> <activity android:name=".Activities.SettingsActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:parentActivityName=".Activities.GoogleMapActivity" android:screenOrientation="portrait"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="pekostudio.dogtrace.Activities.GoogleMapActivity" /> </activity> <activity android:name=".Activities.EditAnimalsActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait" /> <activity android:name=".Activities.EditAnimalActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait" /> <activity android:name=".Activities.DeviceScanActivity" android:configChanges="orientation" android:screenOrientation="portrait" android:launchMode="singleInstance" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".Activities.AvailableMapsListActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait"/> <activity android:name=".Activities.AboutActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait"/> <activity android:name=".Activities.CalibrateActivity" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait"/> <activity android:name=".Activities.MapMarkerPreview" android:configChanges="orientation" android:launchMode="singleInstance" android:screenOrientation="portrait" android:theme="@style/AppTheme.NoActionBar" /> </application>
doc_23525350
$('#banner div').hide(); $('.vert-menu li a').click(function(){ $('.vert-menu li').removeClass('active'); $(this).parent().addClass('active'); var currentTab = $(this).attr('href'); $('#banner div').hide(); $(currentTab).show(); return false; }); Now I am trying to hide div again when mouseout from #banner div and .vert-menu li a I tried this code but it is not working. ('.vert-menu li a, #banner div').mouseleave(function() { $('.vert-menu li').removeClass('active'); $('#banner div').hide(); }); here is the full code on jsfiddle http://jsfiddle.net/TT3Qf/1/ A: Check this DEMO http://jsfiddle.net/TT3Qf/3/ Working fine, you forgot $ sign in front of mouseleave function? $('#banner div').hide(); $('.vert-menu li a').on('click',function () { $('.vert-menu li').removeClass('active'); $(this).parent().addClass('active'); var currentTab = $(this).attr('href'); $('#banner div').hide(); $(currentTab).show(); return false; }); $('.vert-menu li a, #banner div').mouseleave(function() { $('.vert-menu li').removeClass('active'); $('#banner div').hide(); });
doc_23525351
The problem occurs when I dismiss the keyboard and then click the home button and dismiss the app into the background. By reopening my app, I return to the screen on which I just was. When I click on the UITextView, it gives it firstResponder status and the UIKeyboard reappears. If you check the properties of the UIKeyboard, the appearance is still set to dark but for the first second the keyboard is on the screen it shows as light. Does anyone know how to force a refresh of the keyboard between the app entering the foreground and the keyboard being displayed? A: I do not believe there is anything you can do at this time to fix this. I had a simple project I had just done to send in a bug report to Apple, but it didn't fail in the demo project as it does in my code. I was going to toss that project away when I saw your problem. So I have verified that even in the very latest unreleased Xcode and iOS beta this still happens. But, since I had the project already, I did enter a bug report on it with the demo project so Apple can see it for themselves. 15586497 "Keyboard flashes from white to dark under one specific test" If you want to enter your own bug you can say its a dup of the number above, then no need for a demo project. IMHO, these things do get fixed, but not for a while - maybe iOS 8 if you're lucky, so I think you're just going to have to live with it, or switch to using a white keyboard.
doc_23525352
Below is how the RavenDB repository is set up with dummy data : public class EmployeeRepository { private static readonly Lazy<IDocumentStore> Store = new Lazy<IDocumentStore>(CreateInstance); public static IDocumentStore DocumentStore { get { return Store.Value; } } private static IDocumentStore CreateInstance() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "Data", UseEmbeddedHttpServer = false, DefaultDatabase = "EmployeeDocumentDB" }.Initialize(); using (var session = documentStore.OpenSession()) { //TODO: Generates test data and can be deleted. PopulateEmployeesIfStoreIsEmpty(session); } return documentStore; } private static void PopulateEmployeesIfStoreIsEmpty(IDocumentSession session) { if (!session.Query<Employee>().Any()) { var document1 = new Employee { Id=1, JoiningDate = new DateTime(2015, 01, 15), BirthDate = new DateTime(1980, 01, 01) }; var document2 = new Employee { Id = 2, JoiningDate = new DateTime(2015, 02, 15), BirthDate = new DateTime(1985, 01, 01) }; session.Store(document1); session.Store(document2); session.SaveChanges(); } } public IQueryable<Employee> GetEmployees() { using (var session = DocumentStore.OpenSession()) { return session.Query<Employee>(); } } } Here is how the Employee class looks like : public class Employee { public int Id { get; set; } public DateTime JoiningDate { get; set; } public DateTime BirthDate { get; set; } } And here is how the ApiController looks like : public class EmployeeController : ApiController { [HttpGet] [Route("employee/list")] public IHttpActionResult GetEmployees(ODataQueryOptions<Employee> options) { try { EmployeeRepository employeeRepository = new EmployeeRepository(); var queryable = options.ApplyTo(employeeRepository.GetEmployees(), new ODataQuerySettings { EnableConstantParameterization = false, HandleNullPropagation = HandleNullPropagationOption.False }); var employees = RetriveEmployeeListFromQueryable(queryable); return Ok(employees); } catch (Exception e) { return Content(HttpStatusCode.InternalServerError, e.Message); } } private List<Employee> RetriveEmployeeListFromQueryable(IQueryable queryable) { var employees = new List<Employee>(); var enumerator = queryable.GetEnumerator(); while (enumerator.MoveNext()) { var employee = enumerator.Current as Employee; employees.Add(employee); } return employees; } } I am using OData to Consume above code using a ApiController and when I fire below query in the web browser http://localhost/employee/list?$filter=BirthDate eq 1985-01-01 I get an error stating : "Could not understand how to translate 'IIF((($it.JoiningDate.Kind == Utc) OrElse ($it.JoiningDate.Kind == Local)), new DateTimeOffset($it.JoiningDate.ToUniversalTime()).ToOffset(-06:00:00), new DateTimeOffset($it.JoiningDate, (UTC-06:00) Central Time (US & Canada).GetUtcOffset($it.JoiningDate)).ToUniversalTime().ToOffset(-06:00:00))' to a RavenDB query.\ \ Are you trying to do computation during the query?\ \ RavenDB doesn't allow computation during the query, computation is only allowed during index. Consider moving the operation to an index."
doc_23525353
But I want to set it programmatically using the JS Management SDK. This is one of the things I have tried... const mod: ContentTypeModels.IModifyContentTypeData[] = [ { op: 'addInto', path: '/elements/codename:page_url', value: { validation_regex: { regex: '^[a-zA-Z-/]{1,60}$', flags: 'i', validation_message: 'URL slug must only contain (English/Latin) characters, forward slashes and hyphens', is_active: true, }, }, }, ] That gives me the error >> Invalid operation with index '0': Unexpected path part 'codename:page_url' In the hope that the problem is just with the path I have tried several other permutations, without success. Is what I want possible in place i.e. without deleting and re-adding the element? And if so how? A: The addInto operation is for adding new elements, so if there is no url slug element you can add a new one and specify the regular expression: [ { "op": "addInto", "path": "/elements", "value":{ "depends_on": { "element": { "id": "d395c03d-2b20-4631-adc6-bc4cd9c88b0b" } }, "validation_regex": { "regex": "^[a-zA-Z-/]{1,60}$", "flags": "i", "validation_message": "URL slug must only contain (English/Latin) characters, forward slashes and hyphens", "is_active": true }, "name": "some_slug", "guidelines": null, "is_required": false, "type": "url_slug", "codename": "some_slug" } ] For updating just regex of existing url slug element you need to use the replace operation instead: [ { "op": "replace", "path": "/elements/codename:some_type/validation_regex", "value":{ "regex": "^[a-zA-Z-/]{1,60}$", "flags": "i", "validation_message": "URL slug must only contain (English/Latin) characters, forward slashes and hyphens", "is_active": true } } ] You can find more info in our API reference -> https://kontent.ai/learn/reference/management-api-v2/#operation/modify-a-content-type
doc_23525354
This is my JSON data : { "stock": { "head": [ "name", "est", "date" ], "body": [ { "row": [ "TEST", "10.58", "2013-09-05 13:37:20" ] } ] }, "year": { "head": [ "name", "est", "date" ], "body": [ { "row": [ "TEST", "0", "2013-09-05 13:37:35" ] } ] } } This is my javascript code: var getdata = $.ajax({ type : 'POST', url : 'testjson.php', data : data, dataType : 'json' }); getdata.done(function(result){ var queryHead = result.stock.head; // This returns data var queryBody = result.stock.body; // But this doesn't return data. Empty }); JSON data successfully returned, but not being parsed correctly. queryHead works fine but queryBody does not work
doc_23525355
$this->view->foo = "bar"; (I call this vars, as VIEW-VARS) In view script, I render this with: echo $this->foo; So, I wonder if it's possible to define "view vars" inside models(not in controllers) that can be rendered in the view scripts. A: Assigning information to the view is the job of the controller, and doing what you're suggesting would muddy the boundaries of the MVC pattern. What you should really be doing is assigning the model to the view (in the controller), and then access the various parts of the model within the view. Alternatively, you can assign only the relevant parts of the model in your controller. A: Ignoring the fact that a model should indeed not be responsible for configuring the view, there are cases in which it is allowed (for instance the ViewModel pattern). There are a couple of ways of retrieving or providing a view instance: * *Inject the view instance. From the controller you can provide the model the instance by injecting it ($model->setView($this->view)). *Retrieve the view instance via the ViewRenderer helper: $view = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view; *Retrieve the view instance via the Application bootstrapper: $view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->bootstrap('view')->getResource('view');
doc_23525356
The Button doesn't work. What's wrong? LOGCAT 04-01 19:54:55.901: E/AndroidRuntime(32078): FATAL EXCEPTION: main 04-01 19:54:55.901: E/AndroidRuntime(32078): java.lang.NullPointerException 04-01 19:54:55.901: E/AndroidRuntime(32078): at com.dreamgoogle.gihf.Quotes$1.onClick(Quotes.java:43) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.view.View.performClick(View.java:3524) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.view.View$PerformClick.run(View.java:14194) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.os.Handler.handleCallback(Handler.java:605) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.os.Handler.dispatchMessage(Handler.java:92) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.os.Looper.loop(Looper.java:137) 04-01 19:54:55.901: E/AndroidRuntime(32078): at android.app.ActivityThread.main(ActivityThread.java:4476) 04-01 19:54:55.901: E/AndroidRuntime(32078): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 19:54:55.901: E/AndroidRuntime(32078): at java.lang.reflect.Method.invoke(Method.java:511) 04-01 19:54:55.901: E/AndroidRuntime(32078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:816) 04-01 19:54:55.901: E/AndroidRuntime(32078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:583) 04-01 19:54:55.901: E/AndroidRuntime(32078): at dalvik.system.NativeStart.main(Native Method) A: "i" is an integer. Use String.valueOf(i), StringBuilder or substitution String.format("%d", i)); A: If your views are initialized properly, most probable thing is that your string array is null. Change this: String[] str; with this String[] str = new String[]{"Hahahaha", "Woohoo!", "It's-a-me, Mario!", "Mamma mia!"}; A: The problem is you had declared the variable .But you forget to initialize them ImageButton next; ImageButton previous; ImageButton copytext; TextView q; TextView nm; For these widegets you must intalize them eg :previous=(ImageButton)findViewById(R.id.name_in_your_layout_xml); or if it is dynamic previous= new ImageButton(context); I think you Forget to do this.Thats why its showing the NPE Edit :If you use any function to set this the call it onCreare() In your case you must call it before click events EDIT with your new code you forget to give this nm = (TextView) findViewById(R.id.your_id_layout_xml); A: the problem is nm is never bound to a component in the view. Thats the reason for the NPE here: nm.setText(String.valueOf(i)) ; Add this to your class: private void varSet() { next = (ImageButton) findViewById(R.id.next); previous = (ImageButton) findViewById(R.id.previous); copytext = (ImageButton) findViewById(R.id.copy); q = (TextView) findViewById(R.id.quotes); nm = (TextView) findViewById(R.id.YOUR_ID); // BOUND nm HERE WITH YOUR ID str = new String[] { "In order to succeed, your desire for success should be greater than your fear of failure.", "A successful man is one who can lay a firm foundation with the bricks others have thrown at him.", "Success is not final, failure is not fatal: it is the courage to continue that counts.", "Try not to become a man of success. Rather become a man of value.", }; };
doc_23525357
For example, let's say I had an index like this: { "company":"google" }, { "company":"amazon" }, { "company":"goodyear" } and I do a search query like "goo" that returns google and goodyear. Is there a way I can keep track over time of how often an entity is getting hit? Something like { "company":"google", "tracking_num_hits": 1 }, { "company":"amazon", "tracking_num_hits": 0 }, { "company":"goodyear", "tracking_num_hits": 1 } and if I then search "amazon" it updates to { "company":"google", "tracking_num_hits": 1 }, { "company":"amazon", "tracking_num_hits": 1 }, { "company":"goodyear", "tracking_num_hits": 1 } Is there a way for elasticsearch to do this, and if not what is the best way to track this on the backend? A: You could leverage Top hits aggregation for your use case. top_hits metric aggregator keeps track of the most relevant document being aggregated. top hit aggregation returns buckets of search hits. Generally, the top hit aggregation is used as a subaggregation so that the top matching documents can be aggregated in buckets. Example Query : curl -X POST "localhost:9200/sales/_search?size=0&pretty" -H 'Content-Type: application/json' -d' { "aggs": { "top_tags": { "terms": { "field": "type", "size": 3 }, "aggs": { "top_sales_hits": { "top_hits": { "sort": [ { "date": { "order": "desc" } } ], "_source": { "includes": [ "date", "price" ] }, "size": 1 } } } } } } ' A: You'll have to increment these tracking markers yourself, perhaps with an _update_by_query call as soon as you've obtained the hits: POST myindex/_update_by_query { "query": { "terms": { "company.keyword": [ "google", "goodyear" ] } }, "script": { "source": "if (ctx._source.tracking_num_hits != null) { ctx._source.tracking_num_hits++ } else { ctx._source.tracking_num_hits = 1 }" } }
doc_23525358
I mean , I have single SVG file and based rulers/scales i choose graphically , I want to slice the single SVG into different SVG files. Hope I am clear A: Yes, although, you'd think this was classified information - or just simply impossible - based on how hard it is to find this basic fact.... Apparently, all you need to do is reference the viewBox from a URI "fragment".. I have confirmed, it does indeed work. Take the following example... The lesson of the story, in case you miss it, is... image.svg#svgView(viewBox(100,100,100,100)) image.svg is defined as <svg .... viewBox="0,0,400,400" width="400" height="400"> http://example.com/image.svg http://example.com/image.svg#svgView(viewBox(100,100,100,100)) A: If you're working with SVG in Java, the Batik SVG Toolkit will provide a lot of functionality (I confess I don't know what you mean by slicing, however) A: All you have to do is edit the <svg> tag. Edit width and height, set the viewBox attribute on the main svg element to the rectangle you want, render, repeat. Each svg will contain all the data from the original but will only display the part of the drawing inside the viewBox. See http://dingoskidneys.com/~dholth/svg/ viewbox = "x y width height" A: If your goal in slicing the svg was to create 'hot links' or an image map .. this is how to do it! Simply slice the svg in Illustrator then when saving ('Save As') the svg, be sure to nab the code ('SVG Code' at bottom) which will include slice references such as: <rect id="_x3C_Slice_x3E__1_" x="88" y="22.5" class="yj4" width="227" height="88"/> which are LINKABLE by surrounding with a link tag: <a href="#"><rect id="_x3C_Slice_x3E__1_" x="88" y="22.5" class="yj4" width="227" height="88"/></a> Hope this helps.
doc_23525359
This is my nginx.conf: user http; worker_processes auto; worker_cpu_affinity auto; events { multi_accept on; worker_connections 1024; } http { charset utf-8; sendfile on; tcp_nopush on; tcp_nodelay on; server_tokens off; log_not_found off; types_hash_max_size 4096; client_max_body_size 16M; # MIME include mime.types; default_type application/octet-stream; # logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log warn; # load configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; server{ listen 80; listen [::]:80; server_name test.local; root /home/marvw/Programme/Privat/Test; location / { index index.php index.html index.htm; } } } Whats rather weird is that both the error and the access log is straight up emtpy. I triple-checked the URL, it definetly is correct. Nginx is running without any errors, this is my systemd status output: Active: active (running) since Sat 2019-12-21 00:45:40 +01; 7min ago Process: 2171 ExecStart=/usr/bin/nginx -g pid /run/nginx.pid; error_log stderr; (code=exited, status=0/SUCCESS) Main PID: 2172 (nginx) Tasks: 9 (limit: 4915) Memory: 7.9M CGroup: /system.slice/nginx.service ├─2172 nginx: master process /usr/bin/nginx -g pid /run/nginx.pid; error_log stderr; ├─2173 nginx: worker process ├─2174 nginx: worker process ├─2175 nginx: worker process ├─2176 nginx: worker process ├─2177 nginx: worker process ├─2178 nginx: worker process ├─2179 nginx: worker process └─2180 nginx: worker process Dez 21 00:45:40 <<personal information>> systemd[1]: Starting A high performance web server and a reverse proxy server... Dez 21 00:45:40 <<personal information>> systemd[1]: Started A high performance web server and a reverse proxy server. A: Try adding test.local to your hosts or changing it to localhost. "Server not found" is not an Nginx problem.
doc_23525360
So we setup a passive ftp-connection and start the php-script via shell/cronjob. Currently we are trying to fetch 5000 files and it breaks after 2000 files and about 3 minutes. This is the output: [root vhosts]# /usr/local/psa/admin/bin/php /var/www/vhosts/domain.com/httpdocs/fetchFTPdata.php user password action PHP Warning: ftp_get(): Unable to build data connection: Operation not permitted in /var/www/vhosts/domain.com/httpdocs/fetchFTPdata.php on line 771 PHP Warning: ftp_put(): Unable to build data connection: Operation not permitted in /var/www/vhosts/domain.com/httpdocs/fetchFTPdata.php on line 551 And here is how we setup the connection: $ftp_conn = ftp_ssl_connect($url, 21, 3600); if (!$ftp_conn) return false; if (@ftp_login($ftp_conn, $usname, $pwd)) { $this->ftp_conn = $ftp_conn; if (!ftp_pasv($ftp_conn, $true)) { $this->writeLog('Passive FTP-Mode not available.'); return false; } return true; } This is how we put the files: if (!ftp_put($this->ftp_conn, $remote_file, $local_file, FTP_BINARY)) return ('error'); Any ideas on why this stops working after a specific amount of time?
doc_23525361
settings = new TrackerSettings() .setUseGPS(false) .setUseNetwork(true) .setUsePassive(true) .setTimeBetweenUpdates(30 * 60 * 1000); tracker = new LocationTracker(getBaseContext(), settings) { @Override public void onLocationFound(Location location) { // Do some stuff currentLatDouble = location.getLatitude(); currentLngDouble = location.getLongitude(); } @Override public void onTimeout() { } }; tracker.startListening(); but, I'm getting this error: W/LocationTracker: Provider (network) fr.quentinklein.slt.ProviderError: Provider is not enabled | ProviderError{provider='network'} Isn't WiFi a network provider or do I need to write some code related to LocationManager too? Please let me know what is wrong here. A: Added the following permission in manifest file <uses-permission android:name="android.permission.INTERNET" /> Allows applications to open network sockets. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> Allows an app to access approximate location. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> Allows an app to access precise location. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Allows applications to access information about networks. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> Allows applications to access information about Wi-Fi networks. Additionally <uses-feature android:name="android.hardware.location.network" android:required="false" /> <uses-feature android:name="android.hardware.location.gps" android:required="false" />
doc_23525362
fig2 <- plot_ly(iris,x =~Sepal.Length, y=~Sepal.Width, z=~Petal.Length, marker = list(size = 2), color = ~Petal.Width) %>% layout(scene = list(camera =list(projection='orthographic'), aspectmode = "manual", aspectratio = list(x=1, y=5,z=0.5)))%>% add_markers() A: You just need to put the value for projection also in a named list. Reference: https://plotly.com/r/reference/layout/scene/#layout-scene-camera-projection Replace projection='orthographic' with projection=list(type = 'orthographic'). plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, z = ~Petal.Length, marker = list(size = 2), color = ~Petal.Width) %>% layout( scene = list(camera = list(projection = list(type = 'orthographic')), aspectmode = "manual", aspectratio = list(x=1, y=5,z=0.5)) ) %>% add_markers()
doc_23525363
this is my code try { //get connection to the database Connection myconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cbt_for_java", "root",""); //create a statement Statement mystmt=myconn.createStatement(); //execute sql query ResultSet myrs = mystmt.executeQuery("select * from jamb WHERE ID = '1'"); //process the result set //System.out.println(myrs.getString("ID") + "." + myrs.getString("question")); //q=myrs.getString("ID") + "." + myrs.getString("question"); } catch(Exception exc) { exc.printStackTrace(); } BorderLayout questionareaLayout = new BorderLayout(); JPanel questionp = new JPanel(); JTextArea question=new JTextArea(22,111); question.setEditable(false); question.setText(System.out.println(myrs.getString("ID") + "." + myrs.getString("question")); questionp.add(question); add(questionp); A: Your problem is here: question.setText(System.out.println(myrs.getString("ID") + "." + myrs.getString("question")); JTextArea's setText() method accepts String as a parameter. System.out.println() does not return a String! It just prints the String you gave it to the console. So, to fix it: question.setText(myrs.getString("ID") + "." + myrs.getString("question")); A: while(myrs.next()) { question.setText(question.getText() + myrs.getString("id") + ": " + myrs.getString("question")); //value in getString depends on your table. } If you want to separate the results, e.g. with line break, simply add "\n" between the two strings.
doc_23525364
For example I want to get fruit name from the input, so the code: $('.fruit').click(function(){ var name = $(this).text(); getFuitName(name); }); function getFruitName(name){ var fruit = firebase.database().ref('fruit/' + name ); fruit.once('value', function(snapshot) { console.log(snapshot.val().name); }); } What should I do? Any special approach to do this? A: I found the solution. I've to separated the database references like this: var database = firebase.database(); // I add this line $('.fruit').click(function(){ var name = $(this).text(); getFuitName(name); }); function getFruitName(name){ var fruit = database.ref('fruit/' + name ); //and then modified this line fruit.once('value', function(snapshot) { console.log(snapshot.val().name); }); }
doc_23525365
I have looked into OnetoManyMetadata object but could not find it anywhere. A: https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.messages.retrieveentityrequest.aspx var cl = new CrmServiceClient(...); var q = new RetrieveEntityRequest { EntityFilters = EntityFilters.Relationships, LogicalName = "..." }; var r = (cl.Execute(q) as RetrieveEntityResponse).EntityMetadata; var OtM = r.OneToManyRelationships; var MtM = r.ManyToManyRelationships; var MtO = r.ManyToOneRelationships;
doc_23525366
<span class='together'>line one,<br><span class='indent'>line two.</span><br>Line three,<br><span class='indent'>line four,<br>line five,<br>line six,<br>line seven;<br>line eight.<br>Line nine;<br>line ten,<br>line eleven,<br>line twelve.</span><br>Line thriteen,<br><span class='indent'>line fourteen,<br>line fifteen,<br>line sixteen,<br>line seventeen,<br>line eighteen.</span></span> I am trying to find a regex expression that will find all the <br>'s that are between the <span class='indent'> and it's closing </span>. The <span class='together'> encapsulates the whole sting and should just be ignored. At the moment the best I can do is: <span class='indent'>.*?(<br>).*?<\/span> which doesn't work at all. The first <br> this grabs is outside of the <span> and then it skips over a bunch of other <br>'s that I want (See here). Is this possible? Should I instead use <span class='indent'>(.*?)\<\/span> and then parse the captured group later? As you can tell my regex knowledge is pretty limited. A: In comments of other answer you wrote The content between the spans will only have a <br> tag in it and no other HTML... If there are only <br> tags / no other tags before <span class='indent'> try with a lookbehind. There's only finite repitition allowed so need to set a limit to what max length inside the span could be. (?s)(?<=<span class='indent'>(?:(?!</?span).){0,9999}?)<br> Just picked 9999, you might need higher value depending on input. Demo at regexplanet (click Java). (?!</?span). The negative lookahead is used to not skip a span when looking behind. This only works for data like your sample and not with any nested spans. Use parser in this case.
doc_23525367
// Open an AF_PACKET type socket fd, _ := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW, unix.ETH_P_ALL) // Create a link layer Sockaddr sockaddr := &unix.SockaddrLinklayer{ Protocol: unix.ETH_P_ALL, Ifindex: 5, Hatype: 803, Pkttype: 0, Halen: 0, } sendmmsg takes a file descriptor (fd), a pointer to an array of mmsghdr structures, an unsigned int vlen which is the length of the array of mmsghdr structs, and a flags value. So using Go, assuming I'm not passing any flags and that I have an array of mmsghdr structs of length 2 called mymsgvec, I should be able to send my datagram with: unix.Syscall6(unix.SYS_SENDMMSG, uintptr(fd), (uintptr)(unsafe.Pointer(mymsgvec)), uintptr(2), 0, 0, 0) To create mymsgvec I first define a mmsghdr type following its description in the sendmmsg manpage: type mmsghdr struct { msghdr unix.Msghdr msglen uint32 } I then create a msghdr from my buffer buf: msghdr := &unix.Msghdr { Name: (*byte)(unsafe.Pointer(sockaddr)), Namelen: uint32(unsafe.Sizeof(*sockaddr)), Iov: &unix.Iovec { Base: &buf[0], Len: uint64(len(buf)), }, Iovlen: uint64(1), } Then finally I create mymsgvec with mymsgvec := &[]mmsghdr{ {msghdr: *msghdr, msglen: uint32(len(msg))}, {msghdr: *msghdr, msglen: uint32(len(msg))}, } When I try to send this using unix.Syscall6 as described above it fails with the error message too long, although the message is only 44 bytes. I assume the issue is something to do with how I'm constructing mmsghdrs, but I'm not sure. Could someone please point to where I'm going wrong here? Thanks!
doc_23525368
I have an image (.png) saved on my GitHub account, and I want to show it in a Jupyter notebook markdown cell. [IMAGE](https://github.com/user/repo/blob/master/imagename.png) doesn't work. It provides a link to the image instead of showing the image itself when the cell is run. How can I show the image in the notebook instead of making the user click a link? A: You can use it like this ![PyTorch Logo](https://raw.githubusercontent.com/pytorch/pytorch/master/docs/source/_static/img/pytorch-logo-dark.png) Now, the question comes, how can we get this URL. So, for example, you want to get this image (https://github.com/pytorch/pytorch/blob/master/docs/source/_static/img/pytorch-logo-dark.png). Goto GitHub, do right-click on this image and open it in the next tab. Copy the URL from the next tab and use it in the above-defined command.
doc_23525369
alt text http://dl.dropbox.com/u/1563210/budget%20obj%20graph.jpg I am running into some confusion as to how to map the Debit class, which implements 2 interfaces. I may be overthinking it; I'm still learning NH. Thanks for any input. EDIT What's confusing me is that the only properties that my concrete classes have, they are getting from those interfaces. This is why I think I will have to map the Interfaces along with the concrete classes. A: NHibernate doesn't know or care about the interfaces. You can't, for example, use NHibernate to query for objects that implement a specific interface. You have a table-per-class mapping so you should map it with subclass declarations as described in the documentation. A: I'm very new to NHibernate myself but have done something similar so hopefully if I post something along the right lines It'll give us a start so you can comment and in the spirit of stackoverflow someone can edit my answer perhaps. I think basically the hbm needs to use "subclass", "joined-subclass" or "union-subclass" to achieve what you're looking for. <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="YourAssembly.Bll" namespace="YourAssembly.Bll.Domain"> <class name="Transaction" table="Transaction"> <id name="Id"> <generator class="native"/> </id> <property name="Amount" not-null="true" /> <property name="Currency"/> <joined-subclass name="Debit" table="DebitTransaction"> <key column="TransactionId"/> <property name="CardHolderName" not-null="true" /> </joined-subclass> </class> </hibernate-mapping> The Hibernate docs on inheritance are very useful
doc_23525370
I want to take href for Matches from this website https://www.hltv.org/matches My previous code is elif message.text == "Matches": url_news = "https://www.hltv.org/matches" response = requests.get(url_news) soup = BeautifulSoup(response.content, "html.parser") match_info = [] match_items = soup.find("div", class_="upcomingMatchesSection") print(match_items) for item in match_items: match_info.append({ "link": item.find("div", class_="upcomingMatch").text, "title": item["href"] }) And i dont know how i can get links from this body.Appreciate any help A: What happens? You try to iterate over match_items but there is nothing to iterate, cause you only selected the section including the matches but not the matches itself. How to fix? Select the upcomingMatches instead and iterate over them: match_items = soup.select("div.upcomingMatchesSection div.upcomingMatch") Getting the url you have to select an <a>: item.a["href"] Example from bs4 import BeautifulSoup as bs import requests url_news = "https://www.hltv.org/matches" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'} response = requests.get(url_news, headers=headers) soup = BeautifulSoup(response.content, "html.parser") match_info = [] match_items = soup.select("div.upcomingMatchesSection div.upcomingMatch") for item in match_items: match_info.append({ "title": item.get_text('|', strip=True), "link": item.a["href"] }) match_info Output [{'title': '09:00|bo3|1WIN|K23|Pinnacle Fall Series 2|Odds', 'link': '/matches/2352066/1win-vs-k23-pinnacle-fall-series-2'}, {'title': '09:00|bo3|INDE IRAE|Nemiga|Pinnacle Fall Series 2|Odds', 'link': '/matches/2352067/inde-irae-vs-nemiga-pinnacle-fall-series-2'}, {'title': '10:00|bo3|OPAA|Nexus|Malta Vibes Knockout Series 3|Odds', 'link': '/matches/2352207/opaa-vs-nexus-malta-vibes-knockout-series-3'}, {'title': '11:00|bo3|Checkmate|TBC|Funspark ULTI 2021 Asia Regional Series 3|Odds', 'link': '/matches/2352092/checkmate-vs-tbc-funspark-ulti-2021-asia-regional-series-3'}, {'title': '11:00|bo3|ORDER|Alke|ESEA Premier Season 38 Australia|Odds', 'link': '/matches/2352122/order-vs-alke-esea-premier-season-38-australia'},...] A: You can try this out. * *All the match information is present inside a <div> with classname as upcomingMatch *Select all those <div> and from each <div>, extract the match link which is present inside the <a> tag with class name as match. Here is the code: import requests from bs4 import BeautifulSoup url_news = "https://www.hltv.org/matches" headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"} response = requests.get(url_news,headers=headers) soup = BeautifulSoup(response.text, "lxml") match_items = soup.find_all("div", class_="upcomingMatch") for match in match_items: link = match.find('a', class_='match a-reset')['href'] print(f'Link: {link}') Link: /matches/2352235/malta-vibes-knockout-series-3-quarter-final-1-malta-vibes-knockout-series-3 Link: /matches/2352098/pinnacle-fall-series-2-quarter-final-2-pinnacle-fall-series-2 Link: /matches/2352236/malta-vibes-knockout-series-3-quarter-final-2-malta-vibes-knockout-series-3 Link: /matches/2352099/pinnacle-fall-series-2-quarter-final-3-pinnacle-fall-series-2 . . .
doc_23525371
AWS provide examples in Node, but what would this look like in Java? https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-action-lambda-example-functions.html exports.handler = function(event, context, callback) { ... // Stop processing rule set, dropping message callback(null, {'disposition':'STOP_RULE'}); } else { callback(null, null); } }; How would I do this with the Java SDK though? @Override public Object handleRequest(Object request, Context context) { //Return what? } Simply returning the String "STOP_RULE" doesn't work. A: It appears that the Java SDK works the same ways as Node. The difference been that the SDK must use Jackson to serialize the objects on the way out. Returning JSON Strings won't work, but objects will: return Collections.singletonMap("disposition", "STOP_RULE");
doc_23525372
4 votes to close despite no one reading the actual question. no answer accepted. I have found a link that explains. https://hackernoon.com/the-decline-of-stack-overflow-7cb69faa575d#.d05jjnucn So long SO, account closed. A: Assuming you know processA name, you could use EnumProcesses() to get the list of all processes, then GetModuleBaseName() to check the name of each process (you will need to open them with OpenProcess() before that) and when you find the right one : QueryFullProcessImageName() with the Id given by EnumProcesses() A: Use the technique from https://stackoverflow.com/a/3137081/6172310 to obtain the Process ID (pid) of the parent process. Call OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) to get a handle to the process (don't forget to close the handle when you are done!) Call QueryFullProcessImageName(processHandle, 0, outputString, sizeof(outputString)) to get the image name.
doc_23525373
I know how to read table data using class selectors but I do not know how to read only the rows within rowspan. I could not find any useful information anywhere here but if there is already an answer, please provide me with a link. If not, help me to understand the idea. I tried jquery each(), next(), javascript for loop but none of these led me to anything working. This where I'm stuck: $("#test tr td:last-child input:submit").on("click", function() { var rsp = $(this).closest("tr").find(".hostname").attr('rowspan'); if(rsp>0) { $(this).closest('tr').nextAll().slice(0,rsp-1).each(function(){ //read data etc. $(this).addClass('sth-class'); //mark a row with a class }); } }); Below is a table I'm trying to read. <table id="test" width="100%" border="1"> <tr> <td class="hostname">a1</td> <td class="srvc_desc">b1</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:42</td> <td class="srvc_dur">0d 3h 53m 12s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="hostname" rowspan="4">a2</td> <td class="srvc_desc">b2</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:47:02</td> <td class="srvc_dur">0d 3h 11m 55s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="srvc_desc">b3</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:13</td> <td class="srvc_dur">0d 3h 49m 55s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="srvc_desc">b4</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:14</td> <td class="srvc_dur">0d 3h 53m 10s</td> <td class="srvc_att">3/3</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="srvc_desc">b5</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:42</td> <td class="srvc_dur">0d 3h 53m 12s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="hostname">a3</td> <td class="srvc_desc">b6</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:42</td> <td class="srvc_dur">0d 3h 53m 12s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> <tr> <td class="hostname">a4</td> <td class="srvc_desc">b5</td> <td class="srvc_stat">CRITICAL</td> <td class="srvc_last">05-02-2013 00:54:42</td> <td class="srvc_dur">0d 3h 53m 12s</td> <td class="srvc_att">1/1</td> <td class="srvc_excp">Connection refused by host</td> <td> <input class="send" type="submit" onclientclick="Javascript:return false;" value="Check" /> </td> </tr> </table> A: try this: $("#test tr td:last-child input:submit").on("click", function() { var rsp = $(this).closest("tr").find(".hostname").attr('rowspan'); if(rsp>0) { $(this).closest('tr').nextAll().slice(0,rsp-1).each(function(){ var data = readData($(this)); $(this).addClass('sth-class'); //mark a row with a class }); } }); function readData(row){ var data = []; row.children("td:not(:last-child)").each(function(){ data.push($(this).html()); }); return data; } working fiddle here: http://jsfiddle.net/QDD5R/4/ I hope it helps. You have to read a row one by through each or any other loop. thanks.
doc_23525374
doc_23525375
from flask_socketio import SocketIO, emit from flask import Flask app = Flask(__name__) socketio = SocketIO(app) @socketio.on('response') def message(data): time.sleep(1) emit('sensor', {"data": "hello"}) @socketio.on('connect') def connect(): emit('after connect') if __name__ == '__main__': socketio.run(app) and script tag in html looks like this: <script> var socket = io("ws://192.168.100.3:5000"); socket.on('after connect', function(msg) { console.log('connected') socket.emit('response', msg) }); socket.on('sensor', function(msg) { console.log(msg.data) socket.emit('response', msg) }); </script> Everything works, I got the communication, but one thing that concerning me is that in terminal where server run I get code 200 for GET and POST requests. 192.168.100.10 - - [17/Apr/2022 11:36:27] "GET /socket.io/?EIO=2&transport=polling&t=1650191787548-1094&sid=faed6806df0a437d8d17bd8a294f8754 HTTP/1.1" 200 - 192.168.100.10 - - [17/Apr/2022 11:36:27] "POST /socket.io/?EIO=2&transport=polling&t=1650191788570-1095&sid=faed6806df0a437d8d17bd8a294f8754 HTTP/1.1" 200 - I get response in console I think communication is right. But with those request that I am "making" every second resources usage in web browser is getting bigger. Small amount but still. As far as I know WebSockets should not send HTTP requests to server, but it has to be TCP/IP constant connection. What am I doing wrong, or it is my WebSockets understanding wrong? A: The GET and POST requests are there because you are using Socket.IO. As stated in its documentation, Socket.IO starts with HTTP long-polling before it attempts to establish a WebSocket connection. It will also fallback to HTTP long-polling if it cannot use WebSocket.
doc_23525376
A: It is possible that your script relies on environment variables that get set by the terminal log in session. I don't know about KDE, but in Gnome, you can check "Open with Terminal" to ensure that the program is launched from a new Terminal session (with the same environment you'd get from ~/.bashrc). My suggestion is to add the following to the start of your script to ensure that it is being invoked: echo "I've been called: $@" > i_was_invoked.txt And then, elsewhere in your script, you should put printf/echo statements to determine where it has gone awry. If you do that and post your script, it may be possible to assist you further.
doc_23525377
My ViewModel implements it and it plain works. The problem is i need to change the border around my control according to the given validation error string. My current implementation works only for the first validation, after that the triggers are not being triggered again. My View.xaml (partial): <TextBox Grid.Row="1" Grid.Column="3" MaxLength="10" Text="{Binding Code, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Style="{DynamicResource TextBoxStyle}" Validation.ErrorTemplate="{StaticResource ErrorTemplate}"/> My ErrorTemplate: <ControlTemplate x:Key="ErrorTemplate"> <Border BorderThickness="2" x:Name="ValidationBorder"> <AdornedElementPlaceholder x:Name="ValidationElement"/> <Border.Style> <Style TargetType="Border"> <Setter Property="BorderBrush" Value="Black"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=ValidationElement, Path=AdornedElement.(Validation.Errors), Converter={StaticResource ValidationConverter}}" Value="NotValid"> <Setter Property="BorderBrush" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding ElementName=ValidationElement, Path=AdornedElement.(Validation.Errors), Converter={StaticResource ValidationConverter}}" Value="Valid"> <Setter Property="BorderBrush" Value="LawnGreen"/> </DataTrigger> </Style.Triggers> </Style> </Border.Style> </Border> </ControlTemplate> I set a breakpoint into the converter, i get the right value, but the problem persists, the trigger is only being fired once and after that never again. Any suggestions what i may have missed?
doc_23525378
In my view controller I have two IBAction methods for "clearAll" and "Undo". I have created a custom class called drawing.h and .m where I have written functions for handling touch events. Below are my functions. The problem is undo and redo work but the last color select in all line in drawn in undo and redo. A: I Have Mistake In Touch End Method In Array Last Array Not Remove on last object - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UIGraphicsBeginImageContext(self.tempimage.bounds.size); [self.tempimage.layer renderInContext:UIGraphicsGetCurrentContext()]; rawImage = UIGraphicsGetImageFromCurrentImageContext(); [self.tempimage.image drawInRect:CGRectMake(0, 0, tempimage.frame.size.width, tempimage.frame.size.height) blendMode:blendmode alpha:opacity]; UIGraphicsEndImageContext(); #if PUSHTOFILE lineIndex++; [self performSelectorInBackground:@selector(writeFilesBG) withObject:nil]; #else NSDictionary *lineInfo = [NSDictionary dictionaryWithObjectsAndKeys:rawImage, @"IMAGE",nil]; [pointsArray addObject:lineInfo]; UIBezierPath *_path=[pointsArray lastObject]; [_stack addObject:_path]; [pointsArray removeLastObject]; [self.tempimage setNeedsDisplay]; #endif }
doc_23525379
JCS jcs = JCS.getInstance("region-name"); I'm trying to register some kind of listener that can be used to receive a notification/event when an element is removed or expired from the cache... I've been digging through the JCS javadoc for awhile now and I've tried: - adding an Implementation of IElementEventHandler to the default ElementAttributes of the cache ... it never gets called. - using the various implementations of ICacheObserver to register an ICacheListener but that never gets called either. I'm not necessarily sure this point is the correct way of doing it as I think this is intended for more advanced uses of JCS ... Does anyone know how (or if it's possible) to register some kind of listener/obsverver/whatever that will accomplish this? My final goal is to be able to be notified of when something is removed from the cache basically ... I don't particularly care about how provided it isn't a massive kludge :P A: From what I can tell after a short review of the JCS source, it looks like those interfaces are only tied to the remote cache stuff - which I've never used. Additionally, I examined LRUMemoryCache and a few others and it looks like the calls to remove don't link in to any event handlers. Long story short, I couldn't find anything in JCS that does what you are asking. I won't say it is impossible, but I would say it looks unlikely. You can check out the source here and look further. Good luck. A: Create an abstract class that registers the events your interested in capturing. This works for me to capture the two events. private static final Set<Integer> EVENTS = new HashSet<Integer>(); { EVENTS.add(IElementEventHandler.ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND); EVENTS.add(IElementEventHandler.ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND); } @Override public synchronized void handleElementEvent(IElementEvent event) { // Check for element expiration based on EVENTS. LOG.debug("Handling event of type : " + event.getElementEvent() + "."); if (EVENTS.contains(event.getElementEvent())) { ElementEvent elementEvent = (ElementEvent)event; CacheElement element = (CacheElement)elementEvent.getSource(); handleEvent(element); } } // Abstract method to handle events protected abstract void handleEvent(CacheElement element); } Add this abstract event handler to the jcs factory definition as follows JCS jcs = JCSCacheFactory.getCacheInstance(regionName); IElementAttributes attributes = jcs.getDefaultElementAttributes(); attributes.addElementEventHandler(handler); jcs.setDefaultElementAttributes(attributes);
doc_23525380
EDIT: The motivation for this is not immutability per se, which is more to do with the design of the objects. (In fact, in my use case, the parameter is collection which will be mutated in the implementation of the abstract method.) Rather, I want to communicate to anyone implementing my abstract class/method that these variables should not be reassigned. I know that I can communicate that via the java-doc, but I was looking for something more contractual - that they would have to follow, rather than just be guided to follow. In a non-abstract method, I can do this using the final keyword - for example: public class MyClazz { public void doSomething(final int finalParameter){ finalParameter++; // compile error - cannot assign a value to final variable } } However, if I use the final keyword in an abstract method, this does not form part of the contract - that is, implementations of the abstract method do not require the final keyword, and the parameter can be reassigned: public abstract class MyAbstractClazz { public abstract void doSomething(final int finalVariable); } public class MyExtendedClazz extends MyAbstractClazz { @Override public void doSomething(int finalVariable) { // does not require final keyword finalVariable++; // so the variable is modifiable } } As pointed out in answers to this SO Question, the final keyword does not form part of the method signature, which is why the implementation of the abstract class does not require it. So, there are two questions: * *Why is the final keyword not part of the method signature? I understand that it isn't, but I want to know if there's a particular reason why it isn't. *Given that the final keyword is not part of the method signature, is there an alternative way of making parameters in an abstract method unassignable? Other research: * *this SO question touches on the same issue, but doesn't either of my two questions. In fact, the second question is explicitly asked, but does not receive an answer. *lots of questions/blogs etc. on the final keyword refer to "the final word". However, with respect to this question, the relevant comment is as follows (which, while useful, doesn't address my two questions): Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden. A: Parameters are passed by value, if you call the method using certain variable, this variable wont get modified even if you reassign the parameter inside the method, that's why it doesn't make sense for final to be part of the contract. A: I have an abstract class with an abstract method, the parameters for which I want to be final - that is, I do not want to allow implementations of the abstract class & method to reassign the parameter. Why not? That's an implementation detail. It's unobservable to the calling code, so there's no reason why the abstract method should specify it. That's why it's not part of the method signature, either - just like synchronized isn't. A method should implement its documented contract - but how it chooses to do so is up to it. The contract can't say anything useful about the finality of a parameter, as Java always uses pass-by-value.
doc_23525381
To achieve this I tried a method proposed in this StackOverflow post. It uses the following code to obtain a byte[] necessary for MessageDigest: public static byte[] convertToHashableByteArray(Object obj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; byte[] byteOutput = null; try { out = new ObjectOutputStream(bos); out.writeObject(obj); byteOutput = bos.toByteArray(); } catch (IOException io) { io.printStackTrace(); } finally { try { if(out != null) { out.close(); } } catch(IOException io) { io.printStackTrace(); } try { bos.close(); } catch(IOException io) { io.printStackTrace(); } } return byteOutput; } This, however, causes the problem that only objects implementing the serializable interface will be serialized/converted into a byte[]. To circumvent this issue I applied toString() to the given obj in the catch clause to enforce getting a byte[] in all cases: public static byte[] convertToHashableByteArray(Object obj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; byte[] byteOutput = null; try { out = new ObjectOutputStream(bos); out.writeObject(obj); byteOutput = bos.toByteArray(); } catch (IOException io) { String stringed = obj.toString(); byteOutput = stringed.getBytes(); } finally { try { if(out != null) { out.close(); } } catch(IOException io) { io.printStackTrace(); } try { bos.close(); } catch(IOException io) { io.printStackTrace(); } } return byteOutput; } However, this still feels utterly wrong for me. So my question is, whether there is a better alternative to convert arbitrary objects to byte[] to be able to compute hashes. Preferably a solution that works without using additional libraries or one using well established ones like Apache Commons. (Beside that I am also open for other approaches to obtain SHA1/SHA512 hashes of arbitrary Java objects.) A: Perhaps you can use UUIDs for your objects as immutable unique identifiers? A: There are so many things wrong here... * *You should have proper key classes with equals and hashCode implemented, instead of using random objects. *Serialization performance overhead can easily mean that such map will be slower than even trivial iteration search. *Default hashcode should not be used in most cases, as it might be different for objects which are 'equal' from business point of view. You should reimplement hashcode together with equals (which comes back to point 1). Whenever it has collisions due to pointer aliasing is irrelevant if it won't work poperly *Way overcomplicated method of closing in-memory streams. Just close them one after another, it is not external resource - if it fails, just let it fail, you don't need to close everything 100% in case of failures. You can also use one of closeable utilities (or try/catch with resources) to avoid some overhead *You don't need complicated digest of that byte array - use Arrays.hashCode, it WILL be good enough for your use cases (remember - don't do it anyway, point 1) If you are still reading and still not willing to implement point 1, go back to point 1. And again. And again. And to finally answer you question, use hessian serialization. http://hessian.caucho.com/doc/hessian-overview.xtp It is very similar to java one, just faster, shorter output and allows serializing objects which do not implement Serializable interface (at the risk of messing things up, you need to set special flag to allow that). A: If you want to serialize a given object, i suggest you change your méthod like this : public static byte[] convertToHashableByteArray(Serializable obj){ .......... .......... }
doc_23525382
It is that I cannot see the output on Eclipse IDE once I run the C++ app (no errors). I though t the thing that I receive that 'Access denied' message on cmd might be the culprit for the mentioned trouble. Just trying out all the things. Best regards A: Did you add cygwin to your path in windows? A: I'm not familiar to cygwin, but theres a code you can try. It is similar to "sudo" on linux, and it gives you more privileges... It's called "runas". Take a look on this site: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true
doc_23525383
I've linked each html page of the website to its own CSS style sheet and they all work, except for one. All the files are in the same root folder and if I check the 'Page Source' when opening my problematic page in a browser (FireFox) there are no errors showing up, so I'm really lost. h1 { display: inline-block; font-family: Tahoma; } nav { display: inline-block; float: right; font-family: Tahoma; } address { float: right; } <!DOCTYPE html> <html> <head> <title>About X</title> <LINK rel="stylesheet" type="text/css" href="about.css"> </head> <body> <header> <img src="images\logo.jpg" width="100" height="80" alt="logo"> <h1>Mister X</h1> <nav> <a href=///C:/Users/Soniaa/Desktop/web%20design/webpage.html>Pictures</a> <a href=file:///C:/Users/Soniaa/Desktop/web%20design/News.html>News</a> <a href=file:///C:/Users/Soniaa/Desktop/web%20design/About.html>About</a> <a href="http://www.saatchiart.com/sorinatibacov">Shop</a> </nav>email@gmail.com</address> </header> <figure><img src="images/pic.jpg" width="300" height="300" alt="Portrait"> <figcaption>Short Bio... </figcaption> </figure> <h2>Education</h2> <ul> <li>this</li> <li>that</li> </ul> <h2>Personal Exhibitions</h2> <dl> <dt>2010</dt> <dd>...</dd> <dt>2006</dt> <dd>...<dd> <dd>...</dd> <h2>Group Exhibitions</h2> <dl> <dt>2008</dt> <dd>...</dd> <dd>...</dd> <footer>© Mister x <br> <A HREF="https://www.facebook.com/..."><IMG SRC="images/fb.png" width="30" height="30" ALT="Facebook"></A> <A HREF="https://www.behance.net/...><IMG SRC="images/be.png" width="30" height="30" ALT="Behance"></A> <br> Webdesign by me </footer> </body> </html> The actual page has a lot of definition lists in it (no idea if that would have anything to do with it). The same CSS works with my "Home" page, for example, which has the same header. Maybe I'm missing something very obvious, but any help would appreciated! EDIT: Thank you to everyone who took the time to answer! Unfortunately I didn't find the problem but I think maybe I didn't give enough details so I'll rephrase and repost the question (I didn't want to delete this because someone else might find a helpful answer for themselves). Hope that's okay... A: Is your CSS in the same directory as your HTML file? If it's not you probably should do something like <link rel="stylesheet" type="text/css" href="css/about.css"> Also make sure you did not make any typo's. If what you are describing is really true it should work. A: Your markup is fine there seems to be no problem with it.The files are working perfectly on my computer.Try erasing the history of your browser and then reload it, or change the browser and see if it works.
doc_23525384
I want to convert it to a Photoshop .psd file, so I can later apply transformations in photoshop on the annotated alpha layers. I guess it a very simple task but I haven't find any way to do it from the packages I found by googling it. I guess it should be something in the lines of the following: >> im.shape (.., .., 4) psd = PSD() psd.add_layers_from_numpy(im, names=["R", "G", "B", "alpha-1", "alpha-2") with open(of, 'wb') as f: psd.write(f) If you know how to do this, please let me know. Thanks in advance! A: I opened your PSD file in Photoshop and saved it as a TIFF. I then checked with tiffinfo and determined that your file is saved as RGB with 3 layers of "Extra samples": tiffinfo MULTIPLE_ALPHA.tif TIFF Directory at offset 0x8 (8) Subfile Type: (0 = 0x0) Image Width: 1000 Image Length: 1430 Resolution: 72, 72 pixels/inch Bits/Sample: 8 Compression Scheme: None Photometric Interpretation: RGB color <--- HERE Extra Samples: 3<unspecified, unspecified, unspecified> <--- HERE Orientation: row 0 top, col 0 lhs Samples/Pixel: 6 Rows/Strip: 1430 Planar Configuration: single image plane Software: Adobe Photoshop 21.2 (Macintosh) DateTime: 2020:09:08 19:34:38 You can load that into Python with: import tifffile import numpy as np # Load TIFF saved by Photoshop im = tifffile.imread('MULTIPLE_ALPHA.tif') # Check shape print(im.shape) # prints (1430, 1000, 6) # Save with 'tifffile' tifffile.imwrite('saved.tif', im, photometric='RGB') And now check that Photoshop looks at and treats the tifffile image the same as your original: You may want to experiment with the compress parameter. I noticed your file comes out as 8.5MB uncompressed, but as 2.4MB of lossless Zip-compressed data if I use: tifffile.imwrite('saved.tif', im, photometric='RGB', compress=1) Note that reading/writing with compression requires you to install imagecodecs: pip install imagecodecs Note that I am not suggesting it is impossible with a PSD-writer package, I am just saying I believe you can get what you want with a TIFF. Keywords: Image processing, Photoshop, PSD, TIFF, save multi-channel, multi-layer, multi-image, multiple alpha, tifffile, Python
doc_23525385
I am trying x.push({id: 'abc'}); Its not functioning. Is Syntax correct? A: in Following line string creating error because, I don't know why are you using this? var x = [{id: string}]; try this var x = []; x.push({id: 'abc'});
doc_23525386
#include <openssl/evp.h> #include <string.h> int do_crypt(void) { int outlen, inlen; FILE *in, *out; in = fopen("in.txt", "r"); out = fopen("out.txt", "w"); unsigned char key[32]; strcpy(key, "10000000000000000000000000000002"); unsigned char iv[8]; unsigned char inbuf[BUFSIZE], outbuf[BUFSIZE]; EVP_CIPHER_CTX ctx; const EVP_CIPHER * cipher; EVP_CIPHER_CTX_init(&ctx); cipher = EVP_aes_256_cfb(); EVP_EncryptInit(&ctx, cipher, key, 0); while(1) { inlen = fread(inbuf, 1, BUFSIZE, in); if(inlen <= 0) break; if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) return 0; fwrite(outbuf, 1, outlen, out); } if(!EVP_EncryptFinal(&ctx, outbuf, &outlen)) return 0; fwrite(outbuf, 1, outlen, out); EVP_CIPHER_CTX_cleanup(&ctx); return 1; } int do_decrypt(char *infile) { int outlen, inlen; FILE *in, *out; in = fopen("out.txt", "r"); out = fopen("out2.txt", "w"); unsigned char key[32]; strcpy(key, "10000000000000000000000000000002"); unsigned char iv[8]; unsigned char inbuf[BUFSIZE], outbuf[BUFSIZE]; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_DecryptInit(&ctx, EVP_aes_256_cfb(), key, 0); while(1) { inlen = fread(inbuf, 1, BUFSIZE, in); if(inlen <= 0) break; if(!EVP_DecryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) return 0; fwrite(outbuf, 1, outlen, out); } if(!EVP_DecryptFinal(&ctx, outbuf, &outlen)) return 0; fwrite(outbuf, 1, outlen, out); EVP_CIPHER_CTX_cleanup(&ctx); return 1; } main(int argc, char **argv){ if(atoi(argv[1]) == 1) do_crypt(0); if(atoi(argv[1]) == 2) do_decrypt(0); } What could be wrong? A: What's wrong is your expectation that the whole message becomes unreadable because a single byte was changed. Which parts of the message become unreadable depends on the chosen encryption mode. You're using CFB. This means if you change a single byte in the ciphertext, the corresponding byte and the block after that get corrupted, and the cipher recovers from the error afterwards. PCBC will corrupt all output after the error. But it still does not detect the error. I recommend adding authentication (either a MAC, or a mode with integrated authentication such as AES-GCM). A: This is exactly what is supposed to be. Greatly oversimplifying, message is encrypted and decrypted from left to right. Until decryption routine hits changed byte, decrypted text MUST match original message. What happens after changed byte is dependent on cipher mode, but decryption of the left part of the text cannot be affected by this change.
doc_23525387
public void serialize() { try { XmlSerializer ser = new XmlSerializer(typeof(Repository<Student>)); StreamWriter myWriter = new StreamWriter("stud.xml"); ser.Serialize(myWriter, rep); myWriter.Close(); } catch (Exception e) { Console.WriteLine("Error " + e.Message); } } And this is the class I want to serialize: public class Repository<T> : MyStack<T> { public int size; public int capacity; public SLL<T> stud; public Repository() { /* * Creator for class Repository. */ this.stud = new SLL<T>(); this.capacity = 20; this.size = 0; } where MyStack is an interface, and SSL<T> is singly-linked list I have implemented. A: Please add the full details of your exception to isolate the problem. From the code that you posted, it looks like your classes are not serializable. Are the Repository, MyStack, SSL serializable classes (do you have the [Serializable] attribute on all the types of the members that will be serialized?) A: It looks odd to serialise the repository class. Instead I would serialise the SLL<T> object, since that is the actual data you are interested in. The repository is just wrapper object for getting to data, thus there's no reason to serialise that. As Cosmin mentions, make sure you place a [Serializable] attribute on SLL<> [Serializable] public class SLL<T> { } A: Here is an example how to serialize. i think you might miss some important parts: [Serializable] public class User { [XmlElement("login")] [Key] public string login { get; set; } [XmlElement("KDP")] public int KDP { get; set; } [XmlElement("attended")] public int attended { get; set; } etc. the public getters and setters are important if you ever plan to deserialize. and here is example how to serialize list of these: [XmlArrayItem(typeof(User))] [XmlElement("usersList")] public static List<User> usersList = new List<User>(); using (StreamWriter myWriter = new StreamWriter(usersPath, false)) { userSerializer.Serialize(myWriter, usersList); myWriter.Close(); } hope it helps. A: Use [XmlIgnore] attribute for the property which is causing error generating the xml document, so that other things can be parsed.
doc_23525388
My problem (quite complicated to explain) is that I want the first ticked DIV appears at the top (no matter which one is triggered first) and the next ticked DIV below the first. If the first is hidden by unticking the checkbox, the second one moves to the top, and the next ticked appears below, etc... Can some one help in doing that and show me how to ? Thanks a lot ! A: How this http://jsbin.com/okevuy/5/ example code $('#red_div').animate({ 'height': '50', 'opacity': '1', 'margin-left': '0px' }, 300); else $('#red_div').animate({ 'height': '0', 'opacity': '0', 'margin-left': '-80px' }, 300); }); A: I've edit your example: http://jsbin.com/okevuy/7/edit. Check it. What have been changed: "height: 50px" if div visible, height:0px otherwise. Hope it will solve your issue. A: It is still taking spaces since you are just moving them instead of hiding them. You can try hide/show the div when animate is complete: if ($(this).is(':checked')) $('#red_div').show().animate({ 'opacity': '1', 'margin-left': '0px' }, 300); else $('#red_div').animate({ 'opacity': '0', 'margin-left': '-80px' }, 300, function(){ $(this).hide();}); }); http://jsfiddle.net/WqbH4/ A: try this markup: Add a wrapper around the boxes <div id="mianwrapper" > <div id='red_div' class='divs'></div> <div id='blue_div' class='divs'></div> <div id='green_div' class='divs'></div> </div> script: $(document).ready(function () { $('#checkbox_red_div').click(function () { if ($(this).is(':checked')){ checkPosition("red_div"); $('#red_div').show(10); $('#red_div').animate({ 'opacity': '1', 'margin-left': '0px' }, 300)} else $('#red_div').animate({ 'opacity': '0', 'margin-left': '-80px', "display":"none" }, 300 , function(){$('#red_div').fadeOut(100)}); }); $('#checkbox_blue_div').click(function () { if ($(this).is(':checked')) { checkPosition("blue_div"); $('#blue_div').show(10); $('#blue_div').animate({ 'opacity': '1', 'margin-left': '0px' }, 300 )} else $('#blue_div').animate({ 'opacity': '0', 'margin-left': '-80px', }, 300 , function(){$('#blue_div').fadeOut(100)} ); }); $('#checkbox_green_div').click(function () { checkPosition("green_div"); if ($(this).is(':checked')){ $('#green_div').show(10); $('#green_div').animate({ 'opacity': '1', 'margin-left': '0px' }, 300)} else $('#green_div').animate({ 'opacity': '0', 'margin-left': '-80px', }, 300 , function(){$('#green_div').fadeOut(100)}); }); function checkPosition(getBox) { $("#"+getBox).appendTo("#mianwrapper"); } }); Css: Small change in css #red_div{ border:solid 1px red; width:100px; height:50px; opacity:1; float:left; clear:left; } #blue_div{ border:solid 1px blue; width:100px; height:50px; opacity:1; float:left; clear:left; } #green_div{ border:solid 1px green; width:100px; height:50px; opacity:1; float:left; clear:left; }
doc_23525389
http://example.com/admin/test.php?action=edit&id=2 However I need to add in a rule to redirect this to another url with a query string like this: http://example.com/admin/login.php?redirect=test.php%3Faction%3Dedit%26id%3D2 I added a rule like this: RewriteRule ^admin/(.*)?$ /login.php?redirect=/admin/$1?%{QUERY_STRING} [R,L] And it works for the most part but there is one problem, the query string is not being escaped so it is thinking those are other $_GET variables. It looks like this: http://example.com/admin/login.php?redirect=test.php%3Faction=edit&id=2 So the redirect is reading as test.php?action=edit. It is missing the id=2 because it is reading it as another $_GET variable instead of part of the $_GET['redirect']. Is it possible to escape the %{QUERY_STRING} ? I have googled everything I can think of and cannot find an answer anywhere. A: Well, if you don't mind having a bunch of &'s at the end of your encoded URL, you can use optional captures and encode the & by hand. Something like: RewriteCond %{QUERY_STRING} ^([^&]+)(?:&(.*)|)$ RewriteRule ^admin/(.*)?$ /login.php?redirect=/admin/$1\%3F%1\%26%2 [L,NE,R] So if you go to: http://example.com/admin/test.php?a=1&b=2 you get redirected to: http://example.com/login.php?redirect=/admin/test.php%3Fa=1%26b=2 However, going to: http://example.com/admin/test.php?a=1 will redirect you to: http://example.com/login.php?redirect=/admin/test.php%3Fa=1%26 and your php script will extract the $_GET['redirect'] parameter as: /admin/test.php?a=1&. As long as you don't mind having that stray ampersand at the end. If you have a lot of possible variables, and don't care about the ampersand, just add more (?:&(.*)|) to the end of the querystring condition and match them with backreferences (example, 4): RewriteCond %{QUERY_STRING} ^([^&]+)(?:&(.*)|)(?:&(.*)|)(?:&(.*)|)$ RewriteRule ^admin/(.*)?$ /login.php?redirect=/admin/$1\%3F%1\%26%2\%26%3\%26%4 [L,NE,R]
doc_23525390
One REST API accepts an array of strings as input: @RequestMapping(value = "/import", method = RequestMethod.POST) @CrossOrigin public void importComicFiles(@RequestParam("filenames") String[] filenames) { for (String filename : filenames) { ... } } When the front end sends an array of string values using the following: importFiles(filenames: string[]): Observable<Response> { const formData: FormData = new FormData(); for (let index = 0; index < filenames.length; index++) { formData.append('filenames', filenames[index]); } return this.http.post(`${this.apiUrl}/files/import`, formData); } then the Java code receives each string as a separate element in the array. Even if those strings have spaces in them. HOWEVER, when the importFiles method is called with a single string then the Java code behaves as if the value received is an array spit on a single space at the end of the string. An example input string is: /Users/mcpierce/Google Drive/comics/DC/2018-01-17/Superman Vol.2016 #39 (March, 2018).cbz Java treats this string as if it were two strings: /Users/mcpierce/Google Drive/comics/DC/2018-01-17/Superman Vol.2016 #39 (March, and 2018).cbz If I change the Java code to just treat the filenames parameter as a string (rather than as a List or a String[]) then I get the whole string. If it's more than one then each is separated by a common (,). Any ideas? A: I would say Spring is operating just fine. But the way we use the request params is wrong. Spring delimits the request parameters and injects as array. GET http://example.com?filenames=1,2,3,4 Above can be injected into @RequestParam("filenames[]") String[] filenames with each one entry in array. In your case it would be treated as different entries coz of the comma. Try posting it as request body object instead as a request param and use to get the array? A: You can try by adding the [] to the parameter value as well. @RequestParam("filenames[]") String[] filenames
doc_23525391
A: you would use ajax to invoke the server and request the url. The server does its thing and sends the url back in the response. You would then use javascript to update the dom (i.e. html) on the page. I recommend using a framework like jquery to make the ajax request and update the DOM. Plenty of examples are online. A: use servlet or JSP you can set the response to send values you want. AJAX use httpRequestXML to send request and can have a callback function to have response
doc_23525392
I’m trying to assign a date() function to a property of foo() class like that. class Foo{ public $dt = date("F-d-Y H:j:s"); function today(){} //just some empty method }; $g = new Foo(); echo $g->dt; I get Parse error: syntax error, unexpected '(', expecting ',' or ';' //this is date() line I also tried that. class Foo{ public $dt; function today(){ echo $this->dt = date("F-d-Y H:j:s"); } }; $g = new Foo(); $g->today(); No errors and everything works fine. So, seems to me, that we can't assign date() to a class property directly. Please point me to a right direction. Thanks in advance. A: If you provide an initialization of a class property, it has to be a constant, not a function call. If you want to compute the initial value, do it in the class constructor method. class Foo { public $dt; function __construct() { $this->dt = date("F-d-Y H:j:s"); } } $g = new Foo(); echo $g->dt; From the PHP documentation: This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
doc_23525393
So, if the back URL is mywebsite.com/admin/add_new_article.php I want to change the back URL to mywebsite.com/admin/index.php Thank you all! A: <script type="text/javascript"> history.pushState(null, null, '<?php echo $_SERVER["REQUEST_URI"]; ?>'); window.addEventListener('popstate', function(event) { window.location.assign("http://www.yoururl.com/"); }); </script> Hope it helps!
doc_23525394
Here is some sample HTML: <ul> <li>This</li> <li>Should</li> <li>Be Replaced</li> </ul> <div> <ul> <li>So should</li> <li>this</li> </ul> </div> <div class='no-cufon'> <ul> <li>Don't replace this</li> </ul> </div> Note that most of my HTML is dynamic--otherwise I'd just go ahead and change the markup. I'm using the command Cufon.replace('*:not(.no-cufon) li'); to replace the text, but it's still targeting all <li> tags In my developer console (Chrome 12), I get the following values with these jQuery selectors: $("body *").length 11 $("body *:not(.no-cufon)").length 10 $("body * li").length 6 $("body *:not(.no-cufon) li").length 6 For some reason the <li> tags under the no-cufon class are still being matched in my final jQuery selector. So if that doesn't work--what will? A: body :not(.no-cufon) li is matching the same lis as body .no-cufon ul li, because the uls themselves are :not(.no-cufon). Try this instead: Cufon.replace('body > :not(.no-cufon) > li, body > :not(.no-cufon) > ul > li'); A: How about filter()? With the following it selects all li elements that don't have no-cufon parents. Cufon.replace($('li').filter(function(){ if ($(this).parents('.no-cufon').length == 0) return true; })); example: http://jsfiddle.net/niklasvh/prr4W/
doc_23525395
My error - https://ibb.co/hiJ4xy Code Fetching Data Results results; String Name, Score; private void fetchResults() { mDatabaseReference.child("Users").child(id).child("Quiz").child("Results").child(id).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) { Name = childDataSnapshot.getKey().toString(); Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class)); results = new Results(Name, Score); resultsList.add(results); mAdapter.notifyDataSetChanged(); } mAdapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { throw databaseError.toException(); } }); } Class public class Results { private String Name; private String Score; public Results() { } public Results(String Name, String Score) { this.Name = Name; this.Score = Score; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getScore() { return Score; } public void setScore(String score) { Score = score; } } Can anyone point out where i have gone wrong please... before i used to not get the name also and somehow i managed to get it and now struggling with the score Error Process: com.appmaster.akash.messageplus, PID: 8881 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at com.appmaster.akash.messageplus.TakingQuizDone$1.onDataChange(TakingQuizDone.java:68) at com.google.android.gms.internal.zzduz.zza(Unknown Source) at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source) at com.google.android.gms.internal.zzdxa.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:742) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5571) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635) A: Change this: Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class)); into this: Score =childDataSnapshot.child(Name).getValue().toString(); Your datasnapshot is at the userid, then you iterated inside of it and used getKey() to be able to retrieve the name, then to retrieve the value just get the value of the child Name. A: You need to change Score = String.valueOf(childDataSnapshot.child(Name).getValue(Results.class)); into this: Score = (String) childDataSnapshot.getValue(); The problem with your implementation was that you were already iterating over the children of dataSnapshot. So you didn't need to give the key and get the value, the childDataSnapshot has the value.
doc_23525396
My testing model looks like this: public class Person { public int Id { get; set; } public string Name { get; set; } public virtual Address Address { get; set; } } public class Address { public int Id { get; set; } public string Name { get; set; } } I've created and saved an object of type Person with both Name and Address properties assigned. My problem is that if I fetch the Person object back from the database and I change the Address property (ex. to null) then EF doesn't detect the change! My code is this: using (var ctx = new EFContext()) { Person p = ctx.People.First(); // p.Address IS NOT NULL! p.Address = null; var entry = ctx.Entry(p); } Why is entry.State Unchanged ? Edit: If I call SaveChanges, the record is saved correctly (the Address become null)! Edit 2: I've created the foreign key property as billy suggested. If I inspect the Person object in Visual Studio, the State is Modified. If I don't stop with the debugger inspecting the object's values, the state is Unchanged! Edit 3: Loading the Person object using ctx.People.Include(x => x.Address).First(); solves the problem. Is there a way to avoid calling Include and continue to modify the Address property instead of the AddressId one? A: You need to include the Address nav. prop. in your query, otherwise EF won't consider changes to it when you save : using (var ctx = new EFContext()) { Person p = ctx.People.Include(x => x.Address).First(); //p.Address IS NOT NULL! p.Address = null; var entry = ctx.Entry(p); } You could also use foreign keys in your model, which I like very much : public class Person { public int Id { get; set; } public string Name { get; set; } public virtual Address Address { get; set; } public int? AddressId {get; set;} } ... using (var ctx = new EFContext()) { Person p = ctx.People.First(); p.AddressId = null; var entry = ctx.Entry(p); } A: First of all: You MUST follow @billy's advice to use Include. Your remark "p.Address IS NOT NULL!" is only true because you are watching p.Address in the debugger and thereby triggering lazy loading in the debugger, so the change of setting the address to null is detected. In release mode or when you don't inspect the properties in the debugger your code wouldn't work and no changes would be saved. So, the answer to your Edit 3 is: No. Second: var entry = ctx.Entry(p) only returns entity states and you didn't change an entity state but instead a relationship state, or more precisely you deleted a relationship. You can't inspect relationship states with the DbContext API but only with the ObjectContext API: Person p = ctx.People.Include(x => x.Address).First(); p.Address = null; var objCtx = ((IObjectContextAdapter)ctx).ObjectContext; var objentr = objCtx.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted); objentr will have an entry of type RelationshipEntry now: EF will consider this relationship entry together with entity state entries when you call SaveChanges() and delete the relationship, i.e. set the Address foreign key column of the Person in the database to NULL. About Edit 2: Changing a foreign key property (which is a scalar property in your model) is a change of the entity itself, so the entity state will be Modified in this case. A: In my application, before a reload is requested or the user leaves the item/view, I perform some checks to make sure there are no unsaved changes. This is basically running off the currently accepted answer, but I wanted to provide an implementation and bring to the attention that you must call Context.ChangeTracker.DetectChanges() before the ObjectContext.ObjectStateManager can pick up relationship changes! I spent quite a bit of time debugging this, silly! _EagleContext.ChangeTracker.DetectChanges(); var objectContext = ((IObjectContextAdapter)_EagleContext).ObjectContext; var changedEntities = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified); if (_EagleContext.ChangeTracker.Entries().Any(e => e.State == EntityState.Modified) || changedEntities.Count() != 0) { var dialogResult = MessageBox.Show("There are changes to save, are you sure you want to reload?", "Warning", MessageBoxButton.YesNo); if (dialogResult == MessageBoxResult.No) { return; } } // Continue with reloading...
doc_23525397
However, when I try to do this I get the following error: "The data provider required to connect to the local data file could not be found. The file be added to the project by the typed DataSet associated with the file will not be generated" followed by the error: "The operation could not be completed" Note that this is for an ASP.NET MVC Project. A: There are some limitations in the SQL Compact 4 provider tooling, described here (under Scenarios not enabled by SQL Server Compact 4.0) - http://blogs.msdn.com/b/sqlservercompact/archive/2011/01/12/microsoft-sql-server-compact-4-0-is-available-for-download.aspx In addition to the service pack, you must install the SQL Server Compact 4 tools on top - http://erikej.blogspot.com/2010/12/visual-studio-tools-for-sql-server.html A: My "solution" was just to open the database in web matrix to alter the schema. Perhaps this was just an issue with the beta of VS 2010 SP1.
doc_23525398
Then, I added the CGO directives to my main.go and built the program with "go build". I'm doing all this on windows. but windows totally ignores these directives. If I start the program, it crashes because wpcap.dll is missing. Here are my directives: // #cgo solaris LDFLAGS: -L /opt/local/lib -lpcap // #cgo linux LDFLAGS: -lpcap // #cgo dragonfly LDFLAGS: -lpcap // #cgo freebsd LDFLAGS: -lpcap // #cgo openbsd LDFLAGS: -lpcap // #cgo darwin LDFLAGS: -lpcap // #cgo windows CFLAGS: -I C:/WpdPack/Include // #cgo windows,386 LDFLAGS: -L C:/WpdPack/Lib -lwpcap // #cgo windows,amd64 LDFLAGS: -L C:/WpdPack/Lib/x64 -lwpcap // #include <stdlib.h> // #include <pcap.h> What am I doing wrong?
doc_23525399
Thanks. Edit: Including a sample of my data. UserID ItemID Rating 835793 165937 3 154738 11214 3 938459 748288 3 819375 789768 6 738571 98987 3 847509 153777 3 991757 124458 3 968685 288070 2 236349 8337 3 127299 545885 3 A: Figured it out. In my "Remove Duplicate Rows" module up the chain a bit I was only removing duplicates by UserID instead of UserID and ItemID. This still left quite a bit of rows but I'm assuming it messed with the stratification.