text
stringlengths
15
59.8k
meta
dict
Q: Web API Serialize/Deserialize Derived types I have a Web API that returns a list of objects, when the client passes Accept application/json I want my globally registered json formatter to include TypeNameHandling for the derived types during serialization. However this doesn't work and I can't see why this shouldn't work ? My objects public class BaseClass { public int Id { get; set; } } public class SubClass : BaseClass { public string SubClassProp { get; set; } } public class SubClassA : SubClass { public string SubClassAProp { get; set; } } public class SubClassB : SubClass { public string SubClassBProp { get; set; } } WebApiConfig public static void Register(HttpConfiguration config) { var formatters = GlobalConfiguration.Configuration.Formatters; var jsonFormatter = formatters.JsonFormatter; var settings = jsonFormatter.SerializerSettings; settings.Formatting = Formatting.Indented; settings.NullValueHandling = NullValueHandling.Ignore; settings.TypeNameHandling = TypeNameHandling.Auto; } Web API Controller public class MyController : ApiController { [HttpGet] public async Task<IList<BaseClass>> GetClasses() { return new List<BaseClass> { new SubClassA { Id = 1, SubClassProp = "SubClass", SubClassAProp = "SubClassAProp" }, new SubClassB { Id = 2, SubClassProp = "SubClass", SubClassBProp = "SubClassBProp" } }; } } Call from API Client in same solution var client = new HttpClient() { BaseAddress = new Uri("uri goes here...")} client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var resp = await client.GetAsync("uri goes here...")); var jsonContent = await resp.Content.ReadAsStringAsync(); var ListOfClasses = JsonConvert.DeserializeObject<IList<BaseClass>>(jsonContent, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); I'am expecting to get one element which is SubClassA and one that is SubClassB, but both is BaseClass ? I also want it to be possible to Deserialize json to object in Post method. And this should be possible for both json and xml
{ "language": "en", "url": "https://stackoverflow.com/questions/39749090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flutter add round app icon for android in VSCode I added app-icons to my app for both iOS and Android. I watched this Tutorial and it is working so far. But the problem I have is that my Android Icon looks like this at the moment: But the icon should fill the circle. In the tutorial it is shown how you can do it in Android Studio, but I am using VSCode. I tried searching for it but couldn't find anything.. How can I get this done? By the way, I am not using flutter_launcher_icons . A: It seems that you can't do it from vs code, it has to be done in android studio... I have searched for an answer as well as I was stuck with this and ended up doing it in android studio. If someone has a solution please share. A: Flutter has its own default icon for every app in its Android and Ios folder so there are few steps that I would like to show to change the app icon. Head over to https://appicon.co/ and generate your own icon using icon image (the zip file contains two main folders android and Assets.xcassets) For android: Go inside android\app\src\main\res in your flutter app and there paste the android folder content. For IOS: Go inside ios\Runner in your flutter app and there paste the Assets.xcassets content Restart your emulator or rebuild your application
{ "language": "en", "url": "https://stackoverflow.com/questions/68763960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to convert string object to json object in javascript I have changed data in string format where it was like [object object] but I want to change the string object into json object I tried json.parse but it not changing into json object can you please suggest me where I am doing wrong and how to fix this try { var timekeep = await Orders.findAndCountAll({ where: { cid: orders_info.cid, }, order: [ ['id', 'DESC'] ], limit: 1, raw: true, }); var cont1 = JSON.stringify(timekeep.rows[0]); var obj = JSON.parse(cont1); } catch (err) { console.log(err) } console.log('org data' + timekeep) console.log('data as string' + cont1); // now when I am trying to print console.log('data as json' + obj); the output of the console.logs org data [object Object] data as sttring{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null} data as json [object object] A: From what I can see you are already converting it to a JSON with var obj = JSON.parse(cont1); So you already have a JSON, it's just that how you're printing it is wrong. To it with a comma instead of +. console.log('data as json', obj) The + is doing a string concatenation, and it's attempting to concatenate a string with an object A: After String concat it prints data as json [object object]. if you put , instead of + will print that object correctly. In the snippet, you can see the difference. var jsonstr = '{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}'; console.log(JSON.parse(jsonstr)); console.log('data as json' , JSON.parse(jsonstr)); console.log('data as json' + JSON.parse(jsonstr)); A: console.log just the object; if you want log object and a string use , instead of + jsonString = '{"key1":"value1","key2":"value2"}' jsonObject = JSON.parse(jsonString) console.log(jsonObject) // logging just the object console.log('jsonObjectName' , jsonObject) // logging object with string console.log('jsonObject.key1 : ' + jsonObject.key1 ) // this may come handy with certain IE versions function parseJSON(resp){ if (typeof resp === 'string') resp = JSON.parse(resp); else resp = eval(resp); return resp; }
{ "language": "en", "url": "https://stackoverflow.com/questions/55572227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: plotting a sympy plot in web2py I want to plot a sympy plot in web2py by writing a web2py function myplot4() and call it using http://host:port/app/controller/myplot4.png This is the demo sympy code for a plot which works in a python shell. from sympy import symbols from sympy.plotting import plot x = symbols('x') p1 = plot(x*x) p2 = plot(x) p1.append(p2[0]) p1 I found a recipe in http://www.web2pyslices.com/slice/show/1357/matplotlib-howto This recipe works fine but it imports FigureCanvasAgg and Figure whereas in sympy the import is plot function Can somebody tell me how to write similar functions for plotting sympy plot in web2py based on this recipe (or otherwise) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure def pcolor2d(title='title',xlab='x',ylab='y', z=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]): fig=Figure() fig.set_facecolor('white') ax=fig.add_subplot(111) if title: ax.set_title(title) if xlab: ax.set_xlabel(xlab) if ylab: ax.set_ylabel(ylab) image=ax.imshow(z) image.set_interpolation('bilinear') canvas=FigureCanvas(fig) stream=cStringIO.StringIO() canvas.print_png(stream) return stream.getvalue() then try actions like the following: def myplot2(): response.headers['Content-Type']='image/png' return pcolor2dt(z=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]) and call them with http://host:port/app/controller/myplot2.png A: I found the answer by experimenting and it is trivial. def plot_sympy(): from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import io from sympy import symbols from sympy.plotting import plot x = symbols('x') p1 = plot(x*x) p2 = plot(x) p1.append(p2[0]) s = io.BytesIO() p1.save(s) fig=Figure() canvas=FigureCanvas(fig) canvas.print_tif(s) return s.getvalue() def myplot4(): response.headers['Content-Type']='image/png' return plot_sympy()
{ "language": "en", "url": "https://stackoverflow.com/questions/46973057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Define multiple variables at the same time in MATLAB I want to define multiple variables at the same time. For example, I want to define a = 1 b = 2 c = 3 like this. So I made a matrix with [a,b,c]: x = [a, b, c]; y = [1, 2, 3]; x = y So I want to get the following answer. a = 1 b = 2 c = 3 If I use [a, b, c] = deal(1, 2, 3) then, I can get a = 1 b = 2 c = 3 But I want to use matrix x instead of [a, b, c] So if I use, x = deal(1,2,3) there is an error. Is there any solution? A: Maybe I don't understand the question but if you want to use the matrix x instead of [a, b, c] why don't you just define it as x = [1, 2, 3]; From your question it sounds to me as if you are overcomplicating the problem. You begin by wanting to declare a = 1; b = 2; c = 3; but what you want instead according to the end of your question is x = [1, 2, 3]; If you define x as above you can the refer to the individual elements of x like >> x(1), x(2), x(3) ans = 1 ans = 2 ans = 3 Now you have the best of both worlds with 1 definition. You can refer to a, b and c using x(1), x(2), x(3) instead and you've only had to define x once with x = [1, 2, 3];. A: You cannot deal into a numeric array, but you can deal into a cell array and then concatenate all the elements in the cell array, like this: [x{1:3}] = deal(1, 2, 3); % x is a cell array {1, 2, 3} x = [x{:}]; % x is now a numeric array [1, 2, 3]
{ "language": "en", "url": "https://stackoverflow.com/questions/32244836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ERROR 1055 i fixed but why did it gave the error on the first place? I've set the username as a unique key not null CREATE TABLE IF NOT EXISTS `users`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `username` VARCHAR(255) NOT NULL, `created_at` TIMESTAMP DEFAULT NOW(), PRIMARY KEY (`id`), UNIQUE KEY `uk_uname` (`username`) ); But while trying to discover what i the most popular day where people sign in, i got an error. SELECT `username`, DAYNAME(`created_at`) AS `day` FROM `users` GROUP BY `day`; "users.username which is not functionally dependent on columns in group by clause" so i searched through stackoverflow and most people were saying to disable the ONLY_FULL_GROUP_BY, but i don't want to disable it, why cant i learn how to use it? to make the code work i had to add ANY_VALUE(username) it worked. an answer in another post: " For other use cases: You don't necessarily have to disable ONLY_FULL_GROUP_BY Given a case like this, According to mysql docs, "This query is invalid if name is not a primary key of t or a unique NOT NULL column. In this case, no functional dependency can be inferred and an error occurs:" " BUT didn't i made username as an unique key? why the error?
{ "language": "en", "url": "https://stackoverflow.com/questions/52121039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: velocity foreach loop - iterated array gets updated without being used in an assignment I faced a very strange behaviour in the foreach loop of the following velocity template: <html> <body> <table> #set( $arrayOfArray = [[1]] ) #set( $new_arrOfArray = [] ) #set( $new_arr = [] ) <tr><td>Line 9</td><td>arrayOfArray: $arrayOfArray</td></tr> #foreach ($arr in $arrayOfArray) <tr><td>Line 11</td><td>arrayOfArray: $arrayOfArray</td></tr> #set( $new_arr = $arr ) <tr><td>Line 13</td><td>arrayOfArray: $arrayOfArray</td></tr> #if ($new_arr.add([ true ])) #end <tr><td>Line 15</td><td>arrayOfArray: $arrayOfArray</td></tr> #if ($new_arr.add([5,6])) #end <tr><td>Line 17</td><td>arrayOfArray: $arrayOfArray</td></tr> #if ($new_arrOfArray.add($new_arr)) #end <tr><td>Line 19</td><td>arrayOfArray: $arrayOfArray</td></tr> #end <tr><td>Line 21</td><td>arrayOfArray: $arrayOfArray</td></tr> </table> </body> </html> As you can see I'm looping through an array of array (for the sake of simplicity I just put a single array into $arrayOfArray in this example, but real life is of course more complex). As you can also see from the code I do not manipulate the variable $arrayOfArray at all. However, the code generates the following output: Line 9 arrayOfArray: [[1]] Line 11 arrayOfArray: [[1]] Line 13 arrayOfArray: [[1]] Line 15 arrayOfArray: [[1, [true]]] Line 17 arrayOfArray: [[1, [true], [5, 6]]] Line 19 arrayOfArray: [[1, [true], [5, 6]]] Line 21 arrayOfArray: [[1, [true], [5, 6]]] So, it seems whenever I add a new array element to $new_arr the variable $arrayOfArray gets also updated. Is anyone able to explain this behaviour?? Any help highly appreciated. Andreas A: I'm a bit uncertain what you need to do. Would cloning help ? Replacing #set( $new_arr = $arr ) by #set( $new_arr = $arr.clone() ) will keep your $arrayOfArray untouched, while the $new_arrOfArray will be [[1, [true], [5, 6]]] at the end. But maybe I'm missing some point here ... A: By #set( $new_arr = $arr ) you are setting $new_arr to be a reference to $arr. $arr, in turn, is a reference to $arrayOfArray at a certain index. When calling new_arr.add(), you're thereby calling $arrayOfArray[$someIndex].add() by reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/44153262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: String key phrase matching In levenstein how are you, hw r u, how are u, and hw ar you can be compare as same, Is there anyway i can achieved this if i have a phrase like. phrase hi, my name is john doe. I live in new york. What is your name? phrase My name is Bruce. wht's your name key phrase What is your name response my name is batman. im getting the input from user.I have a table with a list of possible request with response. for example the user will ask about 'its name', is there a way i can check if a sentence has a key phrase like What is your name and if its found it will return the possible response like phrase = ' hi, my name is john doe. I live in new york. What is your name?' //I know this one will work if (strpos($phrase,"What is your name") !== false) { return $response; } //but what if the user mistype it if (strpos($phrase,"Wht's your name") !== false) { return $response; } is there i way to achieve this. levenstein works perfect only if the lenght of strings are not that long with the compared string. like hi,wht's your name my name is batman. but if it so long hi, my name is john doe. I live in new york. What is your name? its not working well. if there are shorter phrase, it will identify the shorter phrase that have a shorter distance and return a wrong response i was thinking another way around is to check some key phrase. so any idea to achieve this one? i was working on something like this but maybe there is a better and proper way i think $samplePhrase = 'hi, im spongebob, i work at krabby patty. i love patties. Whts your name my friend'; $keyPhrase = 'What is your name'; * *get first character of keyPhrase. That would be 'W' iterate through *$samplePhrase characters and compare to first character of keyPhrase *h,i, ,i,m, ,s,p etc. . . *if keyPhrase.char = samplePhrase.currentChar *get keyPhrase.length *get samplePhrase.currentChar index *get substring of samplePhrase base on the currentChar index to keyPhrase.length *the first it will get would be work at krabby pa *compare work at krabby pa to $keyPhrase ('What is your name') using levenstiens distance *and to check it better use semilar_text. 11.if not equal and distance is to big repeat process. A: My suggestion would be to generate a list of n-grams from the key phrase and calculate the edit distance between each n-gram and the key phrase. Example: key phrase: "What is your name" phrase 1: "hi, my name is john doe. I live in new york. What is your name?" phrase 2: "My name is Bruce. wht's your name" A possible matching n-gram would be between 3 and 4 words long, therefore we create all 3-grams and 4-grams for each phrase, we should also normalize the string by removing punctuation and lowercasing everything. phrase 1 3-grams: "hi my name", "my name is", "name is john", "is john doe", "john doe I", "doe I live"... "what is your", "is your name" phrase 1 4-grams: "hi my name is", "my name is john doe", "name is john doe I", "is john doe I live"... "what is your name" phrase 2 3-grams: "my name is", "name is bruce", "is bruce wht's", "bruce wht's your", "wht's your name" phrase 2 4-grmas: "my name is bruce", "name is bruce wht's", "is bruce wht's your", "bruce wht's your name" Next you can do levenstein distance on each n-gram this should solve the use case you presented above. if you need to further normalize each word you can use phonetic encoders such as Double Metaphone or NYSIIS, however, I did a test with all the "common" phonetic encoders and in your case it didn't show significant improvement, phonetic encoders are more suitable for names. I have limited experience with PHP but here is a code example: <?php function extract_ngrams($phrase, $min_words, $max_words) { echo "Calculating N-Grams for phrase: $phrase\n"; $ngrams = array(); $words = str_word_count(strtolower($phrase), 1); $word_count = count($words); for ($i = 0; $i <= $word_count - $min_words; $i++) { for ($j = $min_words; $j <= $max_words && ($j + $i) <= $word_count; $j++) { $ngrams[] = implode(' ',array_slice($words, $i, $j)); } } return array_unique($ngrams); } function contains_key_phrase($ngrams, $key) { foreach ($ngrams as $ngram) { if (levenshtein($key, $ngram) < 5) { echo "found match: $ngram\n"; return true; } } return false; } $key_phrase = "what is your name"; $phrases = array( "hi, my name is john doe. I live in new york. What is your name?", "My name is Bruce. wht's your name" ); $min_words = 3; $max_words = 4; foreach ($phrases as $phrase) { $ngrams = extract_ngrams($phrase, $min_words, $max_words); if (contains_key_phrase($ngrams,$key_phrase)) { echo "Phrase [$phrase] contains the key phrase [$key_phrase]\n"; } } ?> And the output is something like this: Calculating N-Grams for phrase: hi, my name is john doe. I live in new york. What is your name? found match: what is your name Phrase [hi, my name is john doe. I live in new york. What is your name?] contains the key phrase [what is your name] Calculating N-Grams for phrase: My name is Bruce. wht's your name found match: wht's your name Phrase [My name is Bruce. wht's your name] contains the key phrase [what is your name] EDIT: I noticed some suggestions to add phonetic encoding to each word in the generated n-gram. I'm not sure phonetic encoding is the best answer to this problem as they are mostly tuned to stemming names (american, german or french depending on the algorithm) and are not very good at stemming plain words. I actually wrote a test to validate this in Java (as the encoders are more readily available) here is the output: =========================== Created new phonetic matcher Engine: Caverphone2 Key Phrase: what is your name Encoded Key Phrase: WT11111111 AS11111111 YA11111111 NM11111111 Found match: [What is your name?] Encoded: WT11111111 AS11111111 YA11111111 NM11111111 Phrase: [hi, my name is john doe. I live in new york. What is your name?] MATCH: true Phrase: [My name is Bruce. wht's your name] MATCH: false =========================== Created new phonetic matcher Engine: DoubleMetaphone Key Phrase: what is your name Encoded Key Phrase: AT AS AR NM Found match: [What is your] Encoded: AT AS AR Phrase: [hi, my name is john doe. I live in new york. What is your name?] MATCH: true Found match: [wht's your name] Encoded: ATS AR NM Phrase: [My name is Bruce. wht's your name] MATCH: true =========================== Created new phonetic matcher Engine: Nysiis Key Phrase: what is your name Encoded Key Phrase: WAT I YAR NAN Found match: [What is your name?] Encoded: WAT I YAR NAN Phrase: [hi, my name is john doe. I live in new york. What is your name?] MATCH: true Found match: [wht's your name] Encoded: WT YAR NAN Phrase: [My name is Bruce. wht's your name] MATCH: true =========================== Created new phonetic matcher Engine: Soundex Key Phrase: what is your name Encoded Key Phrase: W300 I200 Y600 N500 Found match: [What is your name?] Encoded: W300 I200 Y600 N500 Phrase: [hi, my name is john doe. I live in new york. What is your name?] MATCH: true Phrase: [My name is Bruce. wht's your name] MATCH: false =========================== Created new phonetic matcher Engine: RefinedSoundex Key Phrase: what is your name Encoded Key Phrase: W06 I03 Y09 N8080 Found match: [What is your name?] Encoded: W06 I03 Y09 N8080 Phrase: [hi, my name is john doe. I live in new york. What is your name?] MATCH: true Found match: [wht's your name] Encoded: W063 Y09 N8080 Phrase: [My name is Bruce. wht's your name] MATCH: true I used a levenshtein distance of 4 when running these tests, but I am pretty sure you can find multiple edge cases where using the phonetic encoder will fail to match correctly. by looking at the example you can see that because of the stemming done by the encoders you are actually more likely to have false positives when using them in this way. keep in mind that these algorithms are originally intended to find those people in the population census that have the same name and not really which english words 'sound' the same. A: What you are trying to achieve is a quite complex natural language processing task and it usually requires parsing among other things. What I am going to suggest is to create a sentence tokenizer that will split the phrase into sentences. Then tokenize each sentence splitting on whitespace, punctuation and probably also rewriting some abbreviations to a more normal form. Then, you can create custom logic that traverses the token list of each sentence looking for specific meaning. Ex.: ['...','what','...','...','your','name','...','...','?'] can also mean what is your name. The sentence could be "So, what is your name really?" or "What could your name be?" I am adding code as an example. I am not saying you should use something that simple. The code below uses NlpTools a natural language processing library in php (I am involved in the library so feel free to assume I am biased). <?php include('vendor/autoload.php'); use \NlpTools\Tokenizers\ClassifierBasedTokenizer; use \NlpTools\Classifiers\Classifier; use \NlpTools\Tokenizers\WhitespaceTokenizer; use \NlpTools\Tokenizers\WhitespaceAndPunctuationTokenizer; use \NlpTools\Documents\Document; class EndOfSentence implements Classifier { public function classify(array $classes, Document $d) { list($token, $before, $after) = $d->getDocumentData(); $lastchar = substr($token, -1); $dotcnt = count(explode('.',$token))-1; if (count($after)==0) return 'EOW'; // for some abbreviations if ($dotcnt>1) return 'O'; if (in_array($lastchar, array(".","?","!"))) return 'EOW'; } } function normalize($s) { // get this somewhere static $hash_table = array( 'whats'=>'what is', 'whts'=>'what is', 'what\'s'=>'what is', '\'s'=>'is', 'n\'t'=>'not', 'ur'=>'your' // .... more .... ); $s = mb_strtolower($s,'utf-8'); if (isset($hash_table[$s])) return $hash_table[$s]; return $s; } $whitespace_tok = new WhitespaceTokenizer(); $punct_tok = new WhitespaceAndPunctuationTokenizer(); $sentence_tok = new ClassifierBasedTokenizer( new EndOfSentence(), $whitespace_tok ); $text = 'hi, my name is john doe. I live in new york. What\'s your name? whts ur name'; foreach ($sentence_tok->tokenize($text) as $sentence) { $words = $whitespace_tok->tokenize($sentence); $words = array_map( 'normalize', $words ); $words = call_user_func_array( 'array_merge', array_map( array($punct_tok,'tokenize'), $words ) ); // decide what this sequence of tokens is print_r($words); } A: First of all fix all short codes example wht's insted of whats $txt=$_POST['txt'] $txt=str_ireplace("hw r u","how are You",$txt); $txt=str_ireplace(" hw "," how ",$txt);//remember an space before and after phrase is required else it will replace all occurrence of hw(even inside a word if hw exists). $txt=str_ireplace(" r "," are ",$txt); $txt=str_ireplace(" u "," you ",$txt); $txt=str_ireplace(" wht's "," What is ",$txt); Similarly Add as many phrases as you want.. now just check all possible questions in this text & get their position if (strpos($phrase,"What is your name")) {//No need to add "!=" false return $response; } A: You may think of using the soundex function to convert the input string into a phonetically equivalant writing, and then proceed with your search. soundex
{ "language": "en", "url": "https://stackoverflow.com/questions/18841541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Studio: emulator won't install I am running Android Studio 3.2.1 on 32-bit Windows Vista. When it came to running a default tryout application and the emulator choosing window popped up I couldn't install am emulator. It asked me which version of Android and dimensions but then the window closes and the app doesn't run. Any ideas about what is going wrong here and how to fix it? Thanks. A: I've actually figured out what went wrong. The emulator instances now show up when I run the application but then upon launching the app in the emulator I get the following error messages: Emulator: emulator: ERROR: Windows 7 or newer is required to run the Android Emulator. Emulator: Process finished with exit code 1 So no, it's not possible to run the emulator on Windows Vista. A: Try GenyMotion Android Emulator , it has a lot of features.
{ "language": "en", "url": "https://stackoverflow.com/questions/53870916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Script, Run functions in sequence without exceeding execution time I have a lot of functions that fetch JSON API data from a website, but if I run them in sequence in this way, I get the exceeding execution time error: function fetchdata () { data1(); data2(); data3(); data4(); ... } I can schedule a trigger to run them at 5 minutes one of the other (cause a single one runs in 3 minutes), but I would like to know if there is any other way around. Thank you EDIT: Every "data" function is like this one: function data1() { var addresses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Import"); var baseUrl = 'https://myapiurl'; var address = addresses.getRange(2, 1, 500).getValues(); for(var i=0;i<address.length;i++){ var addrID = address[i][0]; var url = baseUrl.concat(addrID); var responseAPI = UrlFetchApp.fetch(url); var json = JSON.parse(responseAPI.getContentText()); var data = [[json.result]]; var dataRange = addresses.getRange(i+2, 2).setValue(data); } } data2 is for rows 502-1001, data3 is for rows 1002-1501, and so on... A: I just removed the concat because it has performance issues according to MDN but obviously the real problem is the fetch and there's not much we can do about that unless you can get your external api to dump a bigger batch. You could initiate each function from a webapp and then have it return via withSuccessHandler and then start the next script in the series and daisy chain your way through all of the subfunctions until your done. Each sub function will take it's 3 minutes or so but you only have to worry about keeping each sub function under 6 minutes that way. function data1() { var addresses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Import"); var baseUrl = 'https://myapiurl'; var address = addresses.getRange(2, 1, 500).getValues(); for(var i=0;i<address.length;i++){ var responseAPI = UrlFetchApp.fetch(baseUrl + address[i][0]); var json = JSON.parse(responseAPI.getContentText()); var data = [[json.result]]; var dataRange = addresses.getRange(i+2, 2).setValue(data); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/47142481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change the colour of my text without using the colour attribute? (HTML & CSS) On my website, I have used a customisable template for my navigation bar. The thing I want to do is to change the underlining colour of the text and not change the actual colour of the text (and as you know the underlining feature and the text have to be in the same selector. Now you might be thinking, just make a vertical rule and colour it! The thing is, I do not know the amount of space between an underline and a piece of text. Is there any way to colour the text a different colour from the underline? Thanks! Screenshots: Code Input: 1 Result: 2 A: One solution would be to "fake" the underline with a bottom border. It might not work depending on the structure of your HTML, but something like this: text-decoration: none; border-bottom: 1px solid #FF0000; A: You cannot isolate the underline color and control it separate from text color; it inherits the same color from the text. However, you can use border, instead. nav a { color: white text-decoration: none; border-bottom: 1px solid salmon; background-color: salmon; } nav a.active { color: #333; border-bottom: 1px solid #333; } A: Use inline-block as display value for each link and apply a bottom border: ul li a{ display:inline-block; border-bottom:2px solid #eeeeee; float:left; padding: 10px; background-color:red; color:#ffffff; text-decoration:none; } change padding, background color and font color as per your style. A: This is another solution. Put the mouse over the element! ul{ margin: 0; padding: 0; } ul li a{ height: 50px; position: relative; padding: 0px 15px; display: table-cell; vertical-align: middle; background: salmon; color: black; font-weight: bold; text-decoration: none; } ul li a:hover:after{ display: block; content: '\0020'; position: absolute; bottom: 0px; left: 0px; width: 100%; height: 3.5px; background: #000000; z-index: 9; } <ul> <li><a href='#'>Menu Item</a></li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/33423011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error in React-Router: 'Type expected. TS1110' after deleting my node_modules folder and package-lock.json My project was working perfectly well but I went and accidentally deleted my node_modules folder and package-lock.json and then reinstalled everything using npm install and now I'm getting this error Type expected. TS1110 149 | failed: true; 150 | }; > 151 | declare type ParamParseSegment<Segment extends string> = Segment extends `${infer LeftSegment}/${infer RightSegment}` ? ParamParseSegment<LeftSegment> extends infer LeftResult ? ParamParseSegment<RightSegment> extends infer RightResult ? LeftResult extends string ? RightResult extends string ? LeftResult | RightResult : LeftResult : RightResult extends string ? RightResult : ParamParseFailed : ParamParseFailed : ParamParseSegment<RightSegment> extends infer RightResult ? RightResult extends string ? RightResult : ParamParseFailed : ParamParseFailed : Segment extends `:${infer Remaining}` ? Remaining : ParamParseFailed; This is the tsconfig that is in my project. It's the same as it was before when it was working { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "noImplicitAny": false, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react", "downlevelIteration": true, }, "include": [ "src" ] } Output of tsc -v is Version 4.5.5. Output of node -v is v16.13.0 if that is of any use. I'm thinking I might have broken something related to the TS compiler? I don't think the problem is with the react router library... A: Fixed by uninstalling and reinstalling TS using npm uninstall typescript --save npm install typescript --save-dev A: If you are using Visual Studio, and combine front-end with backend in one solution, you should check if the version of package Microsoft.TypeScript.MSBuild is up to date. A: I have fixed the error by doing the following in my project with storybook npm i [email protected] npm i @types/[email protected]
{ "language": "en", "url": "https://stackoverflow.com/questions/71315604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Array of Embedded Documents: comparison between fields and value I'm approaching MongoDB and I have a database with this structure: { "_id" : 14185, "ranges" : [ { "first" : 17, "last" : 19 }, { "first" : 6, "last" : 9 } ] } { "_id" : 16478, "ranges" : [ { "first" : 26, "last" : 30 }, { "first" : 3, "last" : 5 } , { "first" : 3, "last" : 5 } ] } { "_id" : 17896, "ranges" : [ { "first" : 124, "last" : 130 }, { "first" : 140, "last" : 146 } ] } So, I always have the "ranges" array, containing many documents: each one of these, has a "first" and "last" value. Given a value, such as 29, I'd like to write a query which gives me something like { "_id" : 16478, "ranges" : [ { "first" : 26, "last" : 30 } ] } Is it possible? A: You should use a question $projection with $elemMatch like so: db.collection.find({'ranges.first': {$lt: 29} ,'ranges.last': {$gt: 29} },{ ranges: { $elemMatch: {first: {$lt: 29} ,last: {$gt: 29} } }}).lean();
{ "language": "en", "url": "https://stackoverflow.com/questions/56794693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ASP.NET Core: How to skip running authentication on [AllowAnonymous] How to identify if authentication is not needed for current request? We have a custom authentication handler, simplified here: internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions> { static readonly string[] DontCheckAuth = new string[] { "/servers", "/user/profile/", "/highscore/list", "/highscore/metadata/" }; protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { /* if url contains any of DontCheckAuth then return AuthenticateResult.NoResult() else do custom auth */ } } So everything works OK, but HandleAuthenticateAsync is run on every request, even on URLs I have marked as [AllowAnonymous]. Currently I just check the URL and compare it to hard-coded list of URLs that does not require authentication. How can I automate this process so I don't have to manually update the list of URLs (which I forget to do for new APIs)?
{ "language": "en", "url": "https://stackoverflow.com/questions/57287569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Linux Device Driver: Error reporting for partial read()/write() I am implementing a Linux device driver that can have partial reads and writes. For example, the caller may have requested to read N bytes from the device, but part of the way through an error was encountered and now the driver has M bytes available to pass back to userspace. How do I report the error back to userspace? For example, I would normally do something like return -EIO; in the event of an I/O error, but this does not tell the whole story (i.e., the caller might be interested in the fact that there still are M usable bytes). I'm aware of the fact that setting errno isn't a thing in kernel space (see here: "'errno' undeclared" when compile Linux kernel), but is there any way that in my scenario I can return M, but also indicate the cause of the short read? How is this generally handled by other device drivers? Do you just return the error code and don't try to indicate that part of the buffer might be usable?
{ "language": "en", "url": "https://stackoverflow.com/questions/50847121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the required key value from JMeter JSON Response I want to validate my API response which is in JSON format. In my case I want to get and validate 'IsActive' value for 'SysCreatedUserId' or for particular 'Id'. Please find the below JSON file. I tried with JSON Assertion but no success till now. Can anyone please help on the same. [ { "Version": null, "StatusCode": 200, "Result": [ { "AccountId": "e26290ff-38c9-4733-a3d3-e57d5f8318ef", "OrganizationLevelTypeId": "b2761fb7-cb1e-4860-81c4-7205e7b742d7", "Name": "LevelName_-928016457_updated", "ParentId": null, "IsActive": true, "RowVersion": "", "IsWolfpack": false, "LastActivityDate": "2018-06-21T09:38:50.83", "WolfpackConfiguration": { "Id": "00000000-0000-0000-0000-000000000000", "LevelId": "00000000-0000-0000-0000-000000000000", "AssociationLevelId": null, "IsPublic": false, "Level": null, "AssociationLevel": null }, "ChildOrganizationLevels": null, "OrganizationLevelUsers": [], "FragmentSettings": null, "OrganizationLevelCode": "00000000-0000-0000-0000-000000000000", "SysCreatedUserId": "720abe00-1267-4ede-aa0f-505e11f806de", "SysEditedUserId": "720abe00-1267-4ede-aa0f-505e11f806de", "SysCreatedDateTime": "2018-06-21T09:38:50.83", "SysEditedDateTime": "2018-06-21T09:38:51.82", "Id": "3cb5ee8d-1382-49fc-850c-013c65ab81b0" }, { "AccountId": "e26290ff-38c9-4733-a3d3-e57d5f8318ef", "OrganizationLevelTypeId": "b2761fb7-cb1e-4860-81c4-7205e7b742d7", "Name": "LevelName_-1910968947_updated", "ParentId": null, "IsActive": false, "RowVersion": "", "IsWolfpack": false, "LastActivityDate": "2018-06-21T10:26:38.28", "WolfpackConfiguration": { "Id": "00000000-0000-0000-0000-000000000000", "LevelId": "00000000-0000-0000-0000-000000000000", "AssociationLevelId": null, "IsPublic": false, "Level": null, "AssociationLevel": null }, "ChildOrganizationLevels": null, "OrganizationLevelUsers": [], "FragmentSettings": null, "OrganizationLevelCode": "00000000-0000-0000-0000-000000000000", "SysCreatedUserId": "720abe00-1267-4ede-aa0f-505e11f806de", "SysEditedUserId": "720abe00-1267-4ede-aa0f-505e11f806de", "SysCreatedDateTime": "2018-06-21T10:26:38.28", "SysEditedDateTime": "2018-06-21T10:26:39.74", "Id": "30ebcf1c-35a2-4135-91d0-0b2b08564361" } ] } ] A: You need to use Filter Expression like: $..[?(@.Id == '3cb5ee8d-1382-49fc-850c-013c65ab81b0')].SysCreatedUserId Demo: More information: JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios
{ "language": "en", "url": "https://stackoverflow.com/questions/50970688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting up mysql with RoR, had XAMPP I just got my RoR environment all set up and running. I made my first application with sqlite. I now want to try Mysql. I have XAMPP from when I did a bit of PHP over a year ago, therefor MYSQL is installed. I now want to set up my applications with mysql. I am setting mysql to start from the XAMPP conrol panel. Go to my application and type 'gem install mysql' to get started but I get: Fetching: mysql-2.9.0.gem (100%) ERROR: While executing gem ... (Errno::EACCES) Permission denied - /Users/lambert/.rvm/gems/ruby-1.9.3-p362/cache/mysql-2.9.0.gem Any ideas, my next step would be to uninstall my XAMPP installation altogether and download mysql, get started from scratch and follow the tutorials all over the web. But if it can be kept... A: You have to install mysql2 adapter for working mysql with RoR. Use this command to install the adapter. gem install mysql2 then create the project with rails new MyProject -d mysql this will create your project with MySQL as database. after that in database.yml file you can edit your username, password for MySQL. A: I don't think you need XAMPP to use MySQL with RoR. Put this in your gemfile: gem 'mysql2' Run bundle install on the console. And set up the credentials on database.yml file like this: development: adapter: mysql2 encoding: utf8 database: your_database_name_development username: username password: password And see if it works, run on the console: rake db:create rake db:migrate Hope I could help!
{ "language": "en", "url": "https://stackoverflow.com/questions/14464352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Volumetric Fog using Unity's shader graph I was wondering if it was possible to create a volumetric fog using unity shader graph. I'm struggling to achieved this shader. Thanks in advance. A: It is possible, but it requires deep knowledge of shader writing. Why not use the built-in Volumetric Fog? Unity has its own implementation, and installation guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/60971038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Include in Android Development I am very new in Android development. Was just wondering is there any way to include codes in "activity" just like we do in php? Can we use Layouts from one activity to another activity, without actually writing them. For eg. In php we can include <?php include("page.php");?> A: It is all automatically included. You are perhaps thinking of import statements. The Activities you write in the same package will automatically be included. For other code, you can just press [Ctrl/Command][Shift][O] in Eclipse to auto-import. A: Answer is yes, there is an include statement, but only works on xml layout. below you can find one example of it. the real purpose of this include is to use it like a template <include android:layout_height="wrap_content" layout="@layout/activity_header_template" /> and if your question is related to the java source code, there is also an import option but that is not like c++, or php methods where you write some piece of code and attach the include file where ever you want. if you want some thing like that it should be a library For Instance, import ActionBarSherlock Library into your project. Go to your project properties by right clicking on your project > Properties > Android > Add > Select ActionBarSherlockLib > Apply > OK. and then inside your main activity class import com.actionbarsherlock.app.SherlockActivity; // this is how you import the just a library A: is there any way to include codes in "activity" If by "codes in activity" you mean "XML layout files", then, yes, there is an <include> tag that you can use. If by "codes in activity" you mean Java code, then that is not possible, as Java does not support an include directive the way C/C++ do.
{ "language": "en", "url": "https://stackoverflow.com/questions/20764030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: What is the alternate of numpy.digitize() function in Julia? I would like to know, how may I replicate the numpy.digitize() functionality in julia? I am trying to convert this python example to Julia. Python Example x = np.array([0.2, 6.4, 3.0, 1.6]) bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) inds = np.digitize(x, bins) Output: array([1, 4, 3, 2], dtype=int64) I tried using searchsorted function in Julia but it doesn't replicate the output form python. Please suggest a solution to this problem. Thanks in advance!! A: You may use searchsortedlast with broadcasting: julia> x = [0.2, 6.4, 3.0, 1.6] 4-element Array{Float64,1}: 0.2 6.4 3.0 1.6 julia> bins = [0.0, 1.0, 2.5, 4.0, 10.0] 5-element Array{Float64,1}: 0.0 1.0 2.5 4.0 10.0 julia> searchsortedlast.(Ref(bins), x) 4-element Array{Int64,1}: 1 4 3 2
{ "language": "en", "url": "https://stackoverflow.com/questions/66235466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VB.NET Extension methods error ''' <summary> ''' Transforms an item to a list of single element containing this item. ''' '</summary> <Extension()> _ Public Function ToList(Of T)(ByVal item As T) As List(Of T) Dim tList As New List(Of T) tList.Add(item) Return tList End Function usage Dim buttonControl As New System.Windows.Forms.Button Dim controls = buttonControl.ToList(Of System.Windows.Forms.Control)() compile time error (on the last line) Extension method 'Public Function ToList() As System.Collections.Generic.List(Of T)' defined in '...Utils' is not generic (or has no free type parameters) and so cannot have type arguments. Was is das? A: Try this: <Extension()> _ Public Function ToList(Of TItem, TList As {New, List(Of TItem)})(ByVal item As TItem) As TList Dim tList As New TList tList.Add(item) Return tList End Function Basically your return type was a generic (declared as List (of T)). The function decaration here does it so that the return type is a list of the type that is being extended. A: Try this. <Extension()> Public Function ToList(Of T)(ByVal Item As Object) As List(Of T) Dim tlist1 As New List(Of T) tlist1.Add(Item) Return tlist1 End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/5218413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does this construct mean "__builtin_expect(!!(x), 1)" Specifically, I am asking about the double '!' in the params of the __built_in. Is it a double negation, per the 'C' language? thanks- A: The !! is simply two ! operators right next to each other. It's a simple way of converting any non-zero value to 1, and leaving 0 as-is.
{ "language": "en", "url": "https://stackoverflow.com/questions/24999408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: run part of a script in IPython I'd like to run part of a scritp (script.py) in IPython, up to line 90. I have tried %run -d -b90 script.py as well as %run -d -b 90 script.py but I got the following message I failed to find a valid line to set a breakpoint after trying up to line: 100. Please set a valid breakpoint manually with the -b option How can I do this in the IPython console? there is always the possibility to use an external command and copy the lines I am interested in to another file and run that new script. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/38483968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: issue with code=H10 error when deploying strapi with heroku I am trying to deploy a strapi app to heroku and followed all the instructions in https://strapi.io/documentation/3.0.0-beta.x/guides/deployment.html#heroku to the letter but the end results is an application error. can anyone please tell me where I am wrong :/ 2020-04-09T14:17:07.788133+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=strapi-kisho.herokuapp.com request_id=5ecab12a-5c4b-4276-b277-71aea1655129 fwd="46.227.240.1" dyno= connect= service= status=503 bytes= protocol=https 2020-04-09T14:17:09.128795+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=strapi-kisho.herokuapp.com request_id=170ffef2-e307-4a5d-82b8-d4d29a197a2c fwd="46.227.240.1" dyno= connect= service= status=503 bytes= protocol=https 2020-04-09T14:17:21.011324+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=strapi-kisho.herokuapp.com request_id=a6834f30-c180-427f-a926-ba9570548c38 fwd="46.227.240.1" dyno= connect= service= status=503 bytes= protocol=https 2020-04-09T14:17:22.086307+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=strapi-kisho.herokuapp.com request_id=d7855a00-aa16-4c6a-bc08-af1986dd0c38 fwd="46.227.240.1" dyno= connect= service= status=503 bytes= protocol=https
{ "language": "en", "url": "https://stackoverflow.com/questions/61123480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing CSS style with Vue.js I am trying to make website and I need to get access to my style thorough Vue. I need to access CSS with Vue because style .skill-bar is background of bar and .skill-bar-fill is green filament which is supposed to have width based on number defined in Vue: So I mean how can I change style of this .skill-bar-fill anytime I want by just changing number in Vue? How can I change width of .skill-bar-fill separately in every item? HTML <div class="w-100 skill-bar"> <div class=" skill-bar-fill"> {{ programming.item1}} %</div> </div> CSS .skill-bar{ text-align: center; color: $black; font-size: 0.75rem; height: 1rem; background: $bg-light; border-radius: 1rem; } .skill-bar-fill{ height: 1rem; background: $green; border-radius: 1rem; } Vue export default { name: 'Items', data() { return{ programming: {item1: 95, item2: 90, }, } } } And I am trying A: Keep the class skill-bar-fill and use style binding : <div class="w-100 skill-bar"> <div class=" skill-bar-fill" :style="{width:programming.item1+'%'}"> {{ programming.item1}} %</div> </div> You couldn't modify a property of that class since it's not unique and each item is unique. A: This answer is based on original question. Your requirement has been simplified so your solution is fine and below is probably not required For the first instance, you could use a CSS variable for the width attribute, and programatically change the variable. For subsequence instances, this won't work by itself because they share the CSS so for those you'd need an object style syntax. Pass a property to the first child so it knows it's the first one and it needs to set the variable Setting CSS variable in Vue: Add var into css class For subsequent children use object syntax: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1 It's not clear to me why you the width of divs needs to reference the first uncle - what if the second skill is higher than the first? - but the above might be the answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/63161997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: increase/decrease each channel of image in android is to slow i m trying to implement some image filters fro that i use this code @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imageView=(ImageView) findViewById(R.id.imgView); bgr = BitmapFactory.decodeResource(getResources(), R.drawable.test02); int A, R, G, B; int pixel; // scan through all pixels for(int x = 0; x < bgr.getWidth(); ++x) { for(int y = 0; y < bgr.getHeight(); ++y) { // get pixel color pixel = bgr.getPixel(x, y); A = Color.alpha(pixel); R = Color.red(pixel); G = Color.green(pixel); B = Color.blue(pixel); // increase/decrease each channel R += value; if(R > 255) { R = 255; } else if(R < 0) { R = 0; } G += value; if(G > 255) { G = 255; } else if(G < 0) { G = 0; } B += value; if(B > 255) { B = 255; } else if(B < 0) { B = 0; } // apply new pixel color to output bitmap bgr.setPixel(x, y, Color.argb(A, R, G, B)); } System.out.println("x"); } imageView.setImageBitmap(bgr); } the problem is this is to slow is any other way to do it, OR make it faster.. A: You should read up about using a ColorMatrix. This matrix can perform exactly the operation you are performing manually. In your case, since you are just adding a constant value to each component, your matrix would have a = g = m = s = 1, and e = j = o = value, and the rest of your matrix would be zeroes. Then you can use setColorFilter() to apply a ColorMatrixColorFilter to your ImageView. A: Maybe using a bitwise operation proves faster? for(int x = 0; x < bgr.getWidth(); ++x) { for(int y = 0; y < bgr.getHeight(); ++y) { // get pixel color pixel = bgr.getPixel(x, y); int alpha = (pixel & 0xff000000) >> 24; int R = (pixel & 0x00ff0000) >> 16; int G = (pixel & 0x0000ff00) >> 8; int B = (pixel & 0x000000ff); // increase/decrease each channel R += value; if(R > 255) { R = 255; } else if(R < 0) { R = 0; } G += value; if(G > 255) { G = 255; } else if(G < 0) { G = 0; } B += value; if(B > 255) { B = 255; } else if(B < 0) { B = 0; } // apply new pixel color to output bitmap bgr.setPixel(x, y, (alpha << 24) + (red << 16) + (green << 8) + blue); } If that proves too slow aswell,using a ColorMatrix would be the best way to do it,even if i presume it does the exact same filtering,it probably is more efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/12740042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract a certain content from html using python BeautifulSoup I have been trying to extract Bacillus circulans from following html: <tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr></th> <td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow-y:hidden"><a href="/kegg-bin/show_organism?tax=1397">ag</a>&nbsp;&nbsp;Addendum (Bacillus circulans)<br> </div></td></tr> but I am not sure which tag it is under and how to get into that tag. I would appreciate your help. Thank you, Xp edit: I am actually trying to get bacillus circulans from KEGG addenlum page import urllib from bs4 import BeautifulSoup as BS url = 'http://www.kegg.jp/entry/ag:CAA27061' page = urllib.urlopen(url).read() soup = BS(page, 'html.parser') tags = soup('div') for i in tags.contents: print i Above is what I know how to do. Since there are more organisms to retrieve, I don't think I can use 're' to match a patter. I want to find a tag that associates with Addenlum org, and fetch the organism names A: from bs4 import BeautifulSoup as soup html='''<tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr></th> <td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow-y:hidden"><a href="/kegg-bin/show_organism?tax=1397">ag</a>&nbsp;&nbsp;Addendum (Bacillus circulans)<br> </div></td></tr>''' html=soup(html) print(html.text) A simple way that prints Organism ag Addendum (Bacillus circulans) Then you can print(html.text.split('(')[1].split(')')[0]) Which prints Bacillus circulans A: You could do this using bs4 and regular expressions. BeautifulSoup Part from bs4 import BeautifulSoup h = """ <tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr> </th> <td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow- y:hidden"><a href="/kegg-bin/show_organism? tax=1397">ag</a>&nbsp;&nbsp;Addendum (Bacillus circulans)<br> </div></td></tr> """ soup = BeautifulSoup(html_doc, 'html.parser') Your content lies inside a <div> tag. tag = soup.find('div') t = tag.text #'ag\xa0\xa0Addendum (Bacillus circulans)\n' Regular Expression Part import re m = re.match(('(.*)\((.*)\).*', t) ans = m.group(2) #Bacillus circulans A: The usual preliminaries. >>> import bs4 >>> soup = bs4.BeautifulSoup('''\ ... <tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr></th><td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow-y:hidden"><a href="/kegg-bin/show_organism?tax=1397">ag</a>&nbsp;&nbsp;Addendum (Bacillus circulans)<br></div></td></tr>''', 'lxml') Then I prettify the soup to see what I'm up against. >>> for line in soup.prettify().split('\n'): ... print(line) ... <html> <body> <tr> <th align="left" class="th10" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid" valign="top"> <nobr> Organism </nobr> </th> <td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"> <div style="width:555px;overflow-x:auto;overflow-y:hidden"> <a href="/kegg-bin/show_organism?tax=1397"> ag </a> Addendum (Bacillus circulans) <br/> </div> </td> </tr> </body> </html> I can see that the string you want is one of three items that constitute the contents of a div element. My first step is to identify that element, and I use its style attribute. >>> parentDiv = soup.find('div', attrs={"style":"width:555px;overflow-x:auto;overflow-y:hidden"}) I examine the three items in its contents, and I'm reminded that strings don't have a name; it's None. >>> for item in parentDiv.contents: ... item, item.name ... (<a href="/kegg-bin/show_organism?tax=1397">ag</a>, 'a') ('\xa0\xa0Addendum (Bacillus circulans)', None) (<br/>, 'br') Then to isolate that string I can use: >>> BC_string = [_ for _ in parentDiv.contents if not _.name] >>> BC_string ['\xa0\xa0Addendum (Bacillus circulans)'] Edit: Given information from comment, this is how to handle one page. Find the heading for 'Organism' (in a nobr elment), then look for the div that contains the desired text relative to that element. Filter out the string(s) from other elements that are contents of that div, then use a regex to obtain the parenthesised name of the organism. If the regex fails then offer the whole string. >>> import bs4 >>> import requests >>> soup_2 = bs4.BeautifulSoup(requests.get('http://www.kegg.jp/entry/ag:CAA27061').content, 'lxml') >>> organism = soup_2.find_all('nobr', string='Organism') >>> parentDiv = organism[0].fetchParents()[0].fetchNextSiblings()[0].find_all('div')[0] >>> desiredContent = [_.strip() for _ in parentDiv.contents if not _.name and _.strip()] >>> if desiredContent: ... m = bs4.re.match('[^\(]*\(([^\)]+)', desiredContent[0]) ... if m: ... name = m.groups()[0] ... else: ... name = "Couldn't match content of " + desiredContent ... >>> name 'Bacillus circulans'
{ "language": "en", "url": "https://stackoverflow.com/questions/44476523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ibatis filling up Nested object in Java I have one java class which resembles to class A { String a; B bclass; } class B { String b; String c; } my ibatis query is : Select a,b,c from A_TABLE and resultmap I want is something like this where I can fill properties of class B (B.b,B.c) as well. <resultMap class="A" id="resmap"> <result property="a" column="A" jdbcType="VARCHAR"/> <result property="bclass.b" column="B" jdbcType="VARCHAR"/> <result property="bclass.c" column="C" jdbcType="VARCHAR"/> </resultmap> any idea how I can fill this object A from ibatis query so I have all 3 a,b,c properties filled? A: The mapping of inner objects is made with association tag. You need something like this: <resultMap id="resmap" type="A"> <result property="a" column="a"/> <association property="b" javaType="B"> <result property="b" column="b"/> <result property="c" column="c"/> </association> </resultMap> Check documentation as well, it's explained in details.
{ "language": "en", "url": "https://stackoverflow.com/questions/70958299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Segmentation fault when trying to compare calling object with another object I have following code wherein I am trying to compare this object with another object. But when I try to run It gives segmentation fault. While telling me what changes to be made also tell me why this throws segmentation fault #include<iostream> using namespace std; class opo { public: bool operator==(opo temp); }; bool opo::operator==(opo temp) { if(*this == temp) { cout<<"same\n"; return true; } else { cout<<"diff\n"; return false; } } int main() { opo a1,a2; a1==a2; return 0; } A: You have a infinite recursive loop. if(*this == temp) calls bool operator==(opo temp) which contains the if statement which in turn call the function again and so on. This will cause the program to run out of resources eventually cause a stack overflow or segfault. When you ceck for equality you need to check the members. Since you class is stateless(no members) any two objects should be equal. If you had class members like class Foo { public: int a, b; }; Then we would have a comparison object like bool Foo::operator ==(const Foo & rhs) { return a == rhs.a && b == rhs.b; // or with std::tie return std::tie(a, b) == std::tie(rhs.a, rhs.b); } A: bool opo::operator==(opo temp) { if(*this == temp) // calls this->operator==(temp) This just calls the same function again, leading to an infinite recursion and, eventually, stack overflow. You need to come up with some actual way to tell if two objects are identical, and then do that. As an aside, your operator's signature is weird. You're forcing a temporary copy of the right-hand-side argument (a2 in your original code). A more normal implementation might look like struct opo { int m_value = 0; bool operator== (opo const &) const; }; bool opo::operator==(opo const &other) const { // actually compare something return m_value == other.m_value; } Notes: * *we take the right-hand-side argument by reference, meaning we don't create a temporary copy *we take it by const reference, meaning we promise not to change it (why would you change something while comparing it?) *our operator is also marked const, so we'er promising not to change the left-hand-side either *I added a member so I have something to compare
{ "language": "en", "url": "https://stackoverflow.com/questions/36844315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Classic ASP Array not returning values, error 500 I'm working on executing the same code several times to produce a table. My first thoughts went out to using an array to do this. Here is what i have got so far: Dim iRow iRow = 0 'alternate color for rows Do While Not rsGlobalWeb.EOF If iRow Mod 2 = 0 Then response.write "<tr bgcolor=""#FFFFFF"">" Else response.write "<tr bgcolor=""#EEEEEE"">" End If 'some other code SqlBackup = "SELECT * FROM CMDBbackup WHERE Naam_Cattools = '" & rsGlobalWeb("Device_name") & "'" Set rsBackup = Server.CreateObject("ADODB.Recordset") rsBackup.Open SqlBackup, dbGlobalWeb, 3 'declaration of array Dim fieldname(5),i fieldname(0) = "Device_name" fieldname(1) = "Image" fieldname(2) = "Backup" fieldname(3) = "Uptime" fieldname(4) = "Processor" fieldname(5) = "Nvram" For i = 0 to 5 If rsGlobalWeb(fieldname(i)) <> "" Then response.write("<td>" & rsGlobalWeb(fieldname(i)) & "</td>") Else If Not rsBackup.EOF Then If Not IsNull(rsBackup(fieldname(i))) And (rsBackup(fieldname(i)) <> "") Then response.write("<td>" & rsBackup(fieldname(i)) & " (backup)</td>") End if Else response.write("<td>No data found</td>") End if End if Next response.write("</tr>") iRow = iRow + 1 rsGlobalWeb.MoveNext Loop The issue i have now is that the following error occurs even tho i have friendly messages turned off: "500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed." The logfile shows the following: "DaEngineSDB.asp |58|800a000d|Type_mismatch 80 -" Where the 58 is the line with the Dim Fieldname. Without the array it does show the remainder of the code (i have 1 other field which gets added). If i remove the array and fill the fieldname(i) with a normal string value it also works fine. I was trying out stuff that google says but after attempting several things i am still running up to a wall. Any ideas what it could be? Thanks in advance, Erik A: First you should turn on error displaying in your iis, or read the error log for its description, google it if not sure how. Without error description, it's way too difficult to check what is wrong. A: Problem solved! After banging my head against the wall for a day i found out that i stupidly declared the array inside the DO WHILE loop. Moved the declaration out of it and problem solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7737756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gulp+browserify - get file name/line on error I use gulp to build my browserified files, problem is that when i have a syntax error the build fails with a generic message: events.js:141 throw er; // Unhandled 'error' event ^ SyntaxError: Unexpected token As you can see it's impossible to understand which file caused the error. Is there a way to get the file name/line that caused the error? A: Consider using gulp-debug https://github.com/sindresorhus/gulp-debug it is a plugin that help you see what files are run through your gulp pipeline
{ "language": "en", "url": "https://stackoverflow.com/questions/36263263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to retrieve a data from a table and insert into another table? I am trying to retrieve "customer_id" from Customer table and insert it into fare_tariff(tariff_id, customer_id, total_price) So I retrieve the customer_id from Customer table as below: using (SqlCommand command = new SqlCommand("SELECT customer_id FROM Customer WHERE UserName = '" + username + "' Password = '"+password +"' ", connection)) { string cust_id = customer_id.ToString(); SqlDataReader myReader = command.ExecuteReader(); if (myReader.Read()) { cust_id = myReader["customer_id"].ToString(); } int c_id = Convert.ToInt32(cust_id); myReader.Close(); custID(c_id); } and insert the customer_id into table fare_tariff like below: using (SqlCommand command = new SqlCommand("INSERT INTO flight_reservation(tariff_id, customer_id, total_price) VALUES(@val1,@val2,@val3)", connection)) { command.Parameters.Add("@val1", SqlDbType.Int).Value = tariff_id; command.Parameters.Add("@val2", SqlDbType.Int).Value = customer_id; command.Parameters.Add("@val3", SqlDbType.VarChar).Value = total_price.ToString(); command.ExecuteNonQuery(); } I declared customer_id as a variable for storing customer_id. Problem is : tariff_id and total_price inserted successfully but the column customer_id is null yet. Help needed. A: Fetching data to the client and returning row by row back to the server can well produce big overhead. There's better way to do the same, so called "insert/select" query: using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "insert into Flight_Reservation(\n" + " Customer_Id,\n" + " Tariff_Id,\n" + " Total_Price)\n" + " select Customer_Id,\n" + " @prm_Tariff_Id,\n" + " @prm_Total_Price\n" + " from Customer\n" + " where (UserName = @prm_UserName)\n" + " (Password = @prm_Password)"; command.Parameters.Add("@prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id; command.Parameters.Add("@prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString(); command.Parameters.Add("@prm_UserName", SqlDbType.VarChar, 80).Value = username; command.Parameters.Add("@prm_Password", SqlDbType.VarChar, 80).Value = password; command.ExecuteNonQuery(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/16248174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WAMP 2.2 and Subversion 1.7.5., how does it work? So i have been working with WAMP for a long time and recently decided to include Subversion and try to connect it with the Apache server installed with WAMP. I have been running over about 6 to 8 guides so far of which almost all of them tell me the same deal. Copy the mod_dav.so files and such to the module directory of the Apache installation, then copy the intl3_svn.dll and libdb48.dll files to the /bin folder of Apache HTTP Server etc. Change the httpd.conf file for Apache to include the new modules as well as a new directory definition for SVN things. But every single guide seems to mention different mod_dav.so files and different .dll files. To top it off, when i got the files copied every single time i restart Apache it won't work. It simply refuses to work with the changes to the httpd.conf file even though I literally copied it from the guides. Is there anyone that has experience with installing subversion 1.7.5. with WAMP server 2.2 that could help me out? EDIT: The error log of the Apache Server actually doesn't really say anything at all. I added the following lines to the list of loaded modules in the httpd.conf file: LoadModule dav_module modules/mod_dav.so LoadModule dav_svn_module modules/mod_dav_svn.so LoadModule authz_svn_module modules/mod_authz_svn.so The dav_module already existed in the standard httpd.conf file and i only had to enable it by removing the '#' tag. A: I hope this article will guide you in a proper way of installing subversion on WAMP server. If it works don't forgot to promote it to correct answer.. So it may help others.
{ "language": "en", "url": "https://stackoverflow.com/questions/11924719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hadoop Mapreduce tasktrackers keep ignoring HADOOP_CLASSPATH. Zookeeper trying to connect to localhost rather than cluster address I have a Hadoop cluster (Cloudera CDH4.2) with 5 datanodes. I'm trying to run a MapReduce job which creates an HBaseConfiguration object. The tasktracker attempts fail, because they're trying to connect to localhost:2181 rather than the address of the actual zookeeper installation. I'm aware that this is because the tasktrackers are not being supplied with the correct classpath containing the hbase configuration. However, if I run the job like so: HADOOP_CLASSPATH=`/usr/bin/hbase classpath` hadoop jar myjar.jar The documentation indicates this should solve the problem. The first entry in hbase classpath is /usr/lib/hbase/conf which is a symlink to /etc/hbase/conf, so in theory, this should add the hbase configuration into the HADOOP_CLASSPATH variable. However, the logs from the tasktracker show this: 2013-08-14 12:47:24,308 INFO org.apache.zookeeper.ZooKeeper: Client environment:java.class.path=<output of `hadoop classpath`> .... 2013-08-14 12:47:24,309 INFO org.apache.zookeeper.ZooKeeper: Initiating client connection, connectString=localhost:2181 sessionTimeout=180000 watcher=hconnection ..... 2013-08-14 12:47:24,328 WARN org.apache.zookeeper.ClientCnxn: Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect java.net.ConnectException: Connection refused So, for some reason, the tasktrackers are completely ignoring my effort to set HADOOP_CLASSPATH to hbase classpath. The documentation (http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/mapreduce/package-summary.html#classpath) states this should just work. What's wrong? I'm aware I could work around this by explicitly specifying the zookeeper quorum address in the jar code, but I need this jar to be portable, and pick up the local configuration without recompiling, so I don't see hard coding the address as a viable option. A: if you made java programming: conf.set("hbase.zookeeper.quorum", "server1,server2,server3"); conf.set("hbase.zookeeper.property.clientPort", "2181"); if you used command:add -Dhbase.zookeeper.quorum sudo hadoop jar /opt/cloudera/parcels/CDH-4.3.0-1.cdh4.3.0.p0.22/lib/hbase/hbase.jar rowcounter -Dhbase.zookeeper.quorum=server1,server2,server3 hly_temp
{ "language": "en", "url": "https://stackoverflow.com/questions/18232473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the difference between the reader monad and a partial function in Clojure? Leonardo Borges has put together a fantastic presentation on Monads in Clojure. In it he describes the reader monad in Clojure using the following code: ;; Reader Monad (def reader-m {:return (fn [a] (fn [_] a)) :bind (fn [m k] (fn [r] ((k (m r)) r)))}) (defn ask [] identity) (defn asks [f] (fn [env] (f env))) (defn connect-to-db [] (do-m reader-m [db-uri (asks :db-uri)] (prn (format "Connected to db at %s" db-uri)))) (defn connect-to-api [] (do-m reader-m [api-key (asks :api-key) env (ask)] (prn (format "Connected to api with key %s" api-key)))) (defn run-app [] (do-m reader-m [_ (connect-to-db) _ (connect-to-api)] (prn "Done."))) ((run-app) {:db-uri "user:passwd@host/dbname" :api-key "AF167"}) ;; "Connected to db at user:passwd@host/dbname" ;; "Connected to api with key AF167" ;; "Done." The benefit of this is that you're reading values from the environment in a purely functional way. But this approach looks very similar to the partial function in Clojure. Consider the following code: user=> (def hundred-times (partial * 100)) #'user/hundred-times user=> (hundred-times 5) 500 user=> (hundred-times 4 5 6) 12000 My question is: What is the difference between the reader monad and a partial function in Clojure? A: The reader monad is a set of rules we can apply to cleanly compose readers. You could use partial to make a reader, but it doesn't really give us a way to put them together. For example, say you wanted a reader that doubled the value it read. You might use partial to define it: (def doubler (partial * 2)) You might also want a reader that added one to whatever value it read: (def plus-oner (partial + 1)) Now, suppose you wanted to combine these guys in a single reader that adds their results. You'll probably end up with something like this: (defn super-reader [env] (let [x (doubler env) y (plus-oner env)] (+ x y))) Notice that you have to explicitly forward the environment to those readers. Total bummer, right? Using the rules provided by the reader monad, we can get much cleaner composition: (def super-reader (do-m reader-m [x doubler y plus-oner] (+ x y))) A: You can use partial to "do" the reader monad. Turn let into a do-reader by doing syntactic transformation on let with partial application of the environment on the right-hand side. (defmacro do-reader [bindings & body] (let [env (gensym 'env_) partial-env (fn [f] (list `(partial ~f ~env))) bindings* (mapv #(%1 %2) (cycle [identity partial-env]) bindings)] `(fn [~env] (let ~bindings* ~@body)))) Then do-reader is to the reader monad as let is to the identity monad (relationship discussed here). Indeed, since only the "do notation" application of the reader monad was used in Beyamor's answer to your reader monad in Clojure question, the same examples will work as is with m/domonad Reader replaced with do-reader as above. But, for the sake of variety I'll modify the first example to be just a bit more Clojurish with the environment map and take advantage of the fact that keywords can act as functions. (def sample-bindings {:count 3, :one 1, :b 2}) (def ask identity) (def calc-is-count-correct? (do-reader [binding-count :count bindings ask] (= binding-count (count bindings)))) (calc-is-count-correct? sample-bindings) ;=> true Second example (defn local [modify reader] (comp reader modify)) (def calc-content-len (do-reader [content ask] (count content))) (def calc-modified-content-len (local #(str "Prefix " %) calc-content-len)) (calc-content-len "12345") ;=> 5 (calc-modified-content-len "12345") ;=> 12 Note since we built on let, we still have destructing at our disposal. Silly example: (def example1 (do-reader [a :foo b :bar] (+ a b))) (example1 {:foo 2 :bar 40 :baz 800}) ;=> 42 (def example2 (do-reader [[a b] (juxt :foo :bar)] (+ a b))) (example2 {:foo 2 :bar 40 :baz 800}) ;=> 42 So, in Clojure, you can indeed get the functionality of the do notation of reader monad without introducing monads proper. Analagous to doing a ReaderT transform on the identity monad, we can do a syntactic transformation on let. As you surmised, one way to do so is with partial application of the environment. Perhaps more Clojurish would be to define a reader-> and reader->> to syntactically insert the environment as the second and last argument respectively. I'll leave those as an exercise for the reader for now. One take-away from this is that while types and type-classes in Haskell have a lot of benefits and the monad structure is a useful idea, not having the constraints of the type system in Clojure allows us to treat data and programs in the same way and do arbitrary transformations to our programs to implement syntax and control as we see fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/22264115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why am I getting Insufficient Mapping Error? I run code first based on a pre-existing database and I'm getting a Mapping Error. I tried to put foreign key annotation but without success. Here it the classes mapping: [Table("tablle_1")] public partial class Table1 { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Table1() { Table2 = new HashSet<Table2>(); } [Key] [Column(Order = 0)] public long usu_id_apr { get; set; } [Other non-important columns] [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public long usu_numweb { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Table2> Table2 { get; set; } } [Table("Table2")] public partial class usu_twebnotifi { [Key] [Column(Order = 0)] public long usu_id_not { get; set; } [Other non-important columns] [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public long usu_numweb { get; set; } [StringLength(999)] public string usu_obsnot { get; set; } public long? usu_id_apr { get; set; } public virtual Table1 Table1 { get; set; } } And here it is the OnModelCreation method modelBuilder.Entity<Table1>() .HasMany(e => e.Table2) .WithOptional(e => e.Table1) .HasForeignKey(e => new { e.usu_id_apr, e.usu_numweb }); When I the run it, I get this error: Data.Table1_Table2: : Multiplicity conflicts with the referential constraint in Role 'my_foreign_key' in relationship 'Table1_Table2'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. Table1_Table2_Source_Table1_Table2_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical. Could you help me? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/56703484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSONDecodeError: Expecting value: line 1 column 1 (char 0) / While json parameter include I'm trying to retrieve data from https://clinicaltrials.gov/ and althought I've specified the format as Json in the request parameter: fmt=json the returned value is txt by default. As a consequence i'm not able to retrieve the response in json() Good: import requests response = requests.get('https://clinicaltrials.gov/api/query/study_fields?expr=heart+attack&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=&fmt=json') response.text Not Good: import requests response = requests.get('https://clinicaltrials.gov/api/query/study_fields?expr=heart+attack&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=&fmt=json') response.json() Any idea how to turn this txt to json ? I've tried with response.text which is working but I want to retrieve data in Json() A: You should use the JSON package (that is built-in python, so you don't need to install anything), that will convert the text into a python object (dictionary) using the json.loads() function. Here you can find some examples. A: You can use following code snippet: import requests, json response = requests.get('https://clinicaltrials.gov/api/query/study_fields?expr=heart+attack&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=&fmt=json') jsonResponse = json.loads(response.content)
{ "language": "en", "url": "https://stackoverflow.com/questions/75263505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel validation - required only when two conditions are true I want purchaser_first_name and purchaser_last_name to be required only when the value of gift input in the request is true and the value of authenticated input is false. What I have tried so far: public function rules() { return [ 'gift' => 'required', 'authenticated'=>required, 'purchaser_first_name' => 'required_if:gift,true,required_if:authenticated,false', 'purchaser_last_name' => 'required_if:gift,true,required_if:authenticated,false', ]; } This approach turns out to use OR operator instead I want the AND operator. A: You can try like this: 'purchaser_first_name' => Rule::requiredIf(function () use ($request) { return $request->input('gift') && !$request->input('authenticated'); }), In the function, you can set your logic. I'm not sure what you need for real, but it's good for a start. Also, check docs for more info about that. A: Try to change your validation code as below : return [ 'gift' => 'required', 'authenticated'=>'required', 'purchaser_first_name' => 'required_if:gift,true|required_if:authenticated,false', 'purchaser_last_name' => 'required_if:gift,true|required_if:authenticated,false', ];
{ "language": "en", "url": "https://stackoverflow.com/questions/63776072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how do I figure out what version of xerces used in my OpenJDK library? I am developing a Java application using Spring framework. Spring uses the Apache Xerces library which is included inside rt.jar comes with my java OpenJDK 8 installation. I wonder how do I know what exact version of Xerces is used in rt.jar? The suggested answer at How to find what apache.xerces version does spring-framework use? does not answer my question here. It does not tell how to find out the xerces version from rt.lib A: Up to java 8 you check the bundled xerces version with: java com.sun.org.apache.xerces.internal.impl.Version After java 8 (i.e from java 9 upwards) you can extract the jmods/java.xml.jmod with: jmod extract java.xml.jmod And then look in the just extracted legal/xerces.md. Usually the version is on the first line stated as a commented text.
{ "language": "en", "url": "https://stackoverflow.com/questions/63243062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get an iterator over the unique keys in a C++ multimap? I am using a std::multimap to map from a key to a set of matching values. I have a situation where I want to be able to list/iterate over the unique keys in the map. How do I get an iterator of the unique keys in a C++ multimap? Another option is using a map<K, set<V>>, but that requires more manual management. A: If you expect the number of duplicate keys to be small, just keep incrementing the iterator until the key value changes. If you expect the number of duplicate keys to be large, just use upper_bound to get an iterator to the element with the next key value.
{ "language": "en", "url": "https://stackoverflow.com/questions/18282689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Destructuring argument for key along with object in javascript How can I get the passed in object course along with the id key using destructuring the argument as in following code snippet ? ... return ( <div> {course.map(course => { return <Course key={course.id} course={course} />; })} </div> ); For instance I've tried like(see below) this, but its not valid ... return ( <div> {course.map(({id} = course) => { return <Course key={id} course={course} />; })} </div> ); The object for reference const course = [ { name: "Half Stack application development", id: 1 }, { name: "Node.js", id: 2 } Are there any way to do this or is it not possible yet? A: Destructure id and spread the rest course.map( ({ id, ...item }) => ( <div id={id}> {item.foo} </div> )) A: You can't destruct an object into its an element and itself. It could be better destruct item in the callback function like below. console.log('-------Only get rest obj------'); const courses = [{ name: "Half Stack application development", id: 1 }, { name: "Node.js", id: 2 }]; courses.forEach(({id, ...item}) => console.log('rest obj:', item)); console.log('----Get full obj and destruct---------'); courses.forEach(item => { const { id } = item; console.log('id:', id); console.log('item:', item); }); A: return ( <div> {course.map(item => { return <Course key={item.id} course={item} />; })} </div> ); You are trying to use the course variable again inside map function. Rename outer most variable from course to courses. return ( <div> {courses.map(course => { return <Course key={course.id} course={course} />; })} </div> ); A: Consider below example return ( <div> {course.map(({ id, ...course }) => { return <Course key={id} course={course} />; })} </div> ); It does gets us the id but course object does have all the keys of the original object(ie, it doesn't have the id now).
{ "language": "en", "url": "https://stackoverflow.com/questions/59309523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: First time using decorators, what am I missing? class User: def __init__(self): self.score = 0 self.wins = 0 self.losses = 0 def tally(self, func): def wrapper_function(w): print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score)) return func(w) return wrapper_function() @tally def record_win(self, w=1): self.wins += w user1 = User() user1.record_win() The error that I'm getting is: TypeError: tally() missing 1 required positional argument: 'func' EDIT This post is different from the one here because in that post the decorator functions were not instance methods.. which I see now adds some peculiar requirements. A: Your problem is that you are defining tally as an instance method, but it's really just a decorator function (it can't be called on an instance in any reasonable way). You can still define it in the class if you insist (it's just useless for instances), you just need to make it accept a single argument (the function to wrap), without self, and make the wrapper accept self (while passing along any provided arguments to the wrapped function): class User: # ... other methods unchanged ... def tally(func): def wrapper_function(self, *args, **kwargs): # Accept self + arbitrary arguments to make decorator useable on more functions print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score)) return func(self, *args, **kwargs) # Pass along self to wrapped function along with arbitrary arguments return wrapper_function # Don't call the wrapper function; you have to return it so it replaces the decorated function @tally def record_win(self, w=1): self.wins += w # Optionally, once tally is no longer needed for new methods, but before dedenting out of class definition, do: del tally # so it won't stick around to appear as a possible method to call on instances # It's done all the work it needs to do after all Removing the w argument in favor of *args, **kwargs means you don't need to specialize to specific function prototypes, nor duplicate the defaults of the function you're wrapping (if they don't pass the argument, the default will get used automatically).
{ "language": "en", "url": "https://stackoverflow.com/questions/69127485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Block animations - how to cycle an array of UIImage I'm going the direction of block animations, having tried to implement multiple animations and an "on finish" event with UIImageView animations but failing. I have a UIImage array, which I need to cycle backwards through, displaying as I go. Here is what I have so far: __block int i = 9; [UIView animateWithDuration:4.0 animations:^{ self.fooView.image = fooImage[i]; [self.view addSubview:self.fooView]; i--; } completion:NULL]; This does happily display the 9th element of fooImage[], but it doesn't iterate through the rest. Is this a misunderstanding about what blocks can actually do in this context? I tried to also wrap a while loop, decrementing "i", but I ended up with the first element only (I sort of expected that). How should one iterate through an array in this instance - perhaps have 9 different animation blocks? Any tips will be gratefully received, and thanks for your time sc. A: Your animations completion handler is NULL, which means nothing is happened after animation is completed. And it's strange to use animations block if you actually animate nothing. Animations won't wait 4 seconds before calling competition handler if there is nothing to animate. __block int i = 9; void(^process)(void(^recursive)()); process = ^(void(^recursive)()) { --i; [UIView animateWithDuration:4.0 animations:^{ NSLog(@"%d", i); } completion:^(BOOL finished) { recursive(recursive); }]; }; process(process);
{ "language": "en", "url": "https://stackoverflow.com/questions/7052485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using TS\ES6 getters for accessing deep properties (like shortcut) Is it fine to use getters for accessign deep properties of a class property? Or there's a more delicate way to do this? Example: const myObject = { very: { deeply: { nested: { property: { with: { a: { long: { name: "hello world" } } } } } } } }; class Sample { constructor(private myObj) {} get name(): string { return this.myObj.very.deeply.nested.property.with.a.long.name; } } Repo: https://codesandbox.io/s/tses6-getters-as-a-shortcut-for-deep-object-properties-h6rgr
{ "language": "en", "url": "https://stackoverflow.com/questions/67090081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Map matrix onto other matrix, row by row I am trying to map a matrix onto another matrix, row by row. Maybe it's better to show this by a simple example: Let startMatrix <- t(matrix( c(2.3, 1.2, 3.6, 6.9, 5.3, 6.7), nrow = 3, ncol = 2)) mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3, 5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2)) Now mapMatrix functions as a sort of grid of startMatrix, that is [1, 1.3, 2, 2.5, 3] is the grid for the first row of startMatrix and [5, 5.6, 6, 6.2, 7] is the grid for the second row of startMatrix. Furthermore, the startMatrix is mapped to its nearest element smaller than himself, e.g. 2.3 goes to 2 and 6.7 to 6.2. Thus, when mapping startMatrix onto mapMatrix the outcome should be a matrix that looks as follows: result = [2, 1, 3 ; 6.2, 5, 6.2] where ; indicates the end of the row. I am looking for an approach that is fast, as such procedure will have to be performed for over 10.000 times for matrices with over 100 rows and 1000 columns. A: Take note that each row of mapMatrix must be ascending startMatrix <- t(matrix( c(2.3, 1.2, 3.6, 6.9, 5.3, 6.7), nrow = 3, ncol = 2)) mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3, 5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2)) res <- do.call(rbind,lapply(1:nrow(startMatrix), function(m) mapMatrix[m,][findInterval(startMatrix[m,],mapMatrix[m,])])) Hope this helps! > res [,1] [,2] [,3] [1,] 2.0 1 3.0 [2,] 6.2 5 6.2
{ "language": "en", "url": "https://stackoverflow.com/questions/33660344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PrimeFaces - JSF tree's context menu can't show Now I want to use JSF tree's mouse right menu, which is just like the link's example. When I click the mouse right, the menu can be show and disappear immediately. I don't know how to show the mouse right key menu (treecontext). Can you give some advice about that? Thanks. http://www.primefaces.org/showcase/ui/treeContextMenu.jsf <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:form id="treeform"> <p:tree value="#{treeBean.root}" var="node" id="tree" rendered="true" dynamic="true" cache="false" selectionMode="single" selection="#{treeBean.selectedNode}"> <p:ajax event="expand" listener="#{treeBean.onNodeExpand}"/> <p:ajax event="collapse" listener="#{treeBean.onNodeCollapse}" /> <p:ajax event="select" listener="#{tableBean.showScenario}" update=":mainForm:scenarioDetailTable :mainForm:dynaFormGroup :mainForm:breadcrumbmenu :mainForm:accordingpanel1:treeform:tree :mainForm:accordingpanel1:treeform:treecontext" /> <p:ajax event="unselect" listener="#{treeBean.onNodeUnselect}" update=":mainForm:scenarioDetailTable :mainForm:dynaFormGroup :mainForm:breadcrumbmenu :mainForm:accordingpanel1:treeform:tree :mainForm:accordingpanel1:treeform:treecontext" /> <p:treeNode id="treeNode" rendered="true" animate="true" expandedIcon="ui-icon-folder-open" collapsedIcon="ui-icon-folder-collapsed"> <h:outputText value="#{node.name}" id="lblNode"/> </p:treeNode> </p:tree> <p:contextMenu id="treecontext" for="tree" rendered="true" > <p:menuitem value="Add Product" disabled="#{tableBean.selectedProjectNodeLevel==1?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createproductdlg').show()" onclick="PF('createproductdlg').show()" /> <p:menuitem value="Add Capability" disabled="#{tableBean.selectedProjectNodeLevel==2?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createcapabilitydlg').show()" onclick="PF('createcapabilitydlg').show()" /> <p:menuitem value="Add Feature" disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createfeaturedlg').show()" onclick="PF('createfeaturedlg').show()" /> <p:menuitem value="Add Scenario" disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" icon="ui-icon-contact" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('scenariodlg').show()" onclick="PF('scenariodlg').show()" /> <p:menuitem value="Delete" update="tree" actionListener="#{treeBean.create}" icon="ui-icon-close"/> </p:contextMenu> </h:form> </ui:composition> some part of main page code <h:form id="mainForm"> <p:layout id="fulllayout" fullPage="true"> <!-- top menu start --> <p:layoutUnit id="layoutunittop" position="north" size="50"> <p:breadCrumb id="breadcrumbmenu" rendered="true"> <p:menuitem value="Categories" url="#" /> <p:menuitem value="Project" url="#" disabled="true" /> <p:menuitem value="Add Product" disabled="#{tableBean.selectedProjectNodeLevel==1?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createproductdlg').show()" onclick="PF('createproductdlg').show()" /> <p:menuitem value="Add Capability" disabled="#{tableBean.selectedProjectNodeLevel==2?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createcapabilitydlg').show()" onclick="PF('createcapabilitydlg').show()" /> <p:menuitem value="Add Feature" disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createfeaturedlg').show()" onclick="PF('createfeaturedlg').show()" /> <p:menuitem value="Add Scenario" disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" update=":mainForm:scenarioDetailTable :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('scenariodlg').show()" onclick="PF('scenariodlg').show()" /> </p:breadCrumb> </p:layoutUnit> <!-- top menu end --> <!-- menu begin --> <p:layoutUnit id="layoutunitleft" position="west" size="360" resizable="true" collapsible="true" header="Options" minSize="260"> <p:accordionPanel id="accordingpanel1" rendered="true" > <p:tab id="accordingpanel1tab" title="Project"> <ui:include src="tree.xhtml" /> </p:tab> <p:tab title="Test Set"> <h:outputText value="Test Set" /> </p:tab> <p:tab title="Report"> <!-- <h:outputText value="Report" /> --> <!-- <p:calendar mode="inline" navigator="none"/> --> </p:tab> </p:accordionPanel> </p:layoutUnit> <!-- menu end --> ....
{ "language": "en", "url": "https://stackoverflow.com/questions/21047876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Watermark onto a posted imaged So on this website an admin posts an image, before it is sent to the database via sql I want to add a watermark. This is my code for this part. if(!$_POST['name'] | !$_POST['cat'] | !$_POST['frame'] | !$_POST['molding'] | !$_POST['price'] | $_FILES["photo"]["tmp_name"]) { die('You did not fill in a required field.'); } $image = file_get_contents($_FILES['photo']['tmp_name']); $_POST['name'] = addslashes($_POST['name']); $_POST['price'] = addslashes($_POST['price']); $_POST['molding'] = addslashes($_POST['molding']); $_POST['frame'] = addslashes($_POST['frame']); $_POST['cat'] = addslashes($_POST['cat']); // Load the stamp and the photo to apply the watermark to $stamp = imagecreatefrompng('watermark2.PNG'); $save_watermark_photo_address = 'watermark_photo2.jpg'; // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 0; $marge_bottom = 0; $sx = imagesx($stamp); $sy = imagesy($stamp); $imgx = imagesx($image); $imgy = imagesy($image); $centerX=round($imgx/2) - ($sx/2); $centerY=round($imgy/2) - ($sy/2); // Copy the stamp image onto our photo using the margin offsets and the photo // width to calculate positioning of the stamp. imagecopy($image, $stamp, $centerX, $centerY, 0, 0, imagesx($stamp), imagesy($stamp)); // Output and free memory //header('Content-type: image/png'); imagejpeg($image, $save_watermark_photo_address, 80); The save part at the end was to check it. Anything that uses $image comes up with the error expects parameter 1 to be resource, string given in. I think it means the images format is wrong but I have no idea how to fix it. For anyone's information before I added the watermark code everything works perfectly. A: for more clarification, you may want to use this old colde: $image = file_get_contents($_FILES['photo']['tmp_name']); new code: $imgData= file_get_contents($_FILES['photo']['tmp_name']); $image = imagecreatefromstring( $imgData); this is a clarification of my comment above.
{ "language": "en", "url": "https://stackoverflow.com/questions/26816119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ternary operator in javascript when variable is empty I have used the ternary operator in php $foo = get_field('foo') ?: null; but I'm looking forn an equivalent in javascript. So far I've tried the var foo = <?php echo $foo; ?> || null;. But since <?php echo $foo; ?> in this case is null/empty the console is giving me the error Uncaught SyntaxError: Unexpected token || since the variable is var foo = || null;. Is there another way of using ternary operators in javascript? A: Your problem has nothing to do with ternary operator, but with PHP output to javascript. The safest way is: var foo = <?php echo json_encode($foo); ?> || null ; The json_encode() function makes sure that the variable is echoed in a form that JS understands. A: You need to return a falsy value from php. Your code was almost correct. It was only missing the quotes around it. var foo = '<?php echo $foo; ?>' || null; console.log('foo', foo); // null This is because when $foo is empty, it will be var foo = '' || null; and since '' is falsy in Javascript, it will return null.
{ "language": "en", "url": "https://stackoverflow.com/questions/42693619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intel HAXM install hangs on macOS Sierra I'm trying to install HAXM 6.2.1 on a MacBook Pro running MacOS Sierra, but the installer hangs. Attempting to install via the GUI .dmg, the dialog "This package will run a program to determine if the software can be installed" appears. I click "Continue," and then the installer hangs. The dialog does not disappear, but cannot be moved or dismissed. Attempting to install via the command line installer simply hangs with no further information. Attempting to install via the command line silent install, the installer hangs with the haxm-isRunning process active. Googling for "haxm-isRunning" yields 0 results. No log file appears to be generated. No console entries are found containing the string "haxm," so I think there are no relevant console entries either. I'm at a loss and not sure what else to try. Any advice or suggestions? A: I had the same problem. HAXM installation would never exit and had to use "force quit" in order to kill it. Found a log message in /var/log/system.log that seemed to coincide with the installation. It was from a totally different application but the same error reoccurred each time I tried to run the HAXM installer: ... com.apple.xpc.launchd[1] (com.paloaltonetworks.authorized[284]): Service exited due to signal: Segmentation fault: 11 sent by exc handler[0] The errors referred to a daemon called "authorized" from paloaltonetworks. Every time I tried to run the HAXM installer I would see a Segmentation Fault error logged related to the authorized daemon. So I disabled the authorized daemon temporarily by editing the /Library/LaunchDaemons/com.paloaltonetworks.authorized.plist file and set RunAtLoad to false as well as KeepAlive to false and rebooted. Probably would have been enough to unload and reload the daemon via launchctl but whatever. After rebooting with the authorized daemon disabled I was able to successfully install HAXM. No issues. Then I re-enabled the authorized daemon by reverting the changes to /Library/LaunchDaemons/com.paloaltonetworks.authorized.plist and rebooted. Palo Alto Networks Traps (authorized daemon is related to this application) tool is working and HAXM is installed. All good. Hope this helps. A: BTW -- it traps is indeed your problem (and it was for me) you can also just disable from the command line the traps stuff if you can sudo. $ sudo bash # cd /Library/Application Support/PaloAltoNetworks/Traps/bin # ./cytool runtime stop all --- INSTALL HAXM and whatever else --- # ./cytool runtime start all That should do the trick without having to reboot, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/46649216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stop eclipse formatter from removing certain useful parts of HTML code <tr ng-repeat="rows in CalendarBean.weekList"> <td ng-repeat="cellList in rows"> <div id="{{cellList.fullDate}}" ng-click="onDateSelect(cellList.fullDate)" class=" {{cellList.timeClass}} {{cellList.leaveFlag}}+{{cellList.holidayFlag}}" style="border:{{cellList.borderColor}}; background-color: {{cellList.ColorCode}}" align='center'> <div class="row"> <span style="color: {{cellList.dateNumberColor}}" class="class1"> {{cellList.date}} </span> </div> </div> </td> </tr> I have this code. background-color: {{cellList.ColorCode}} this part and some closing second braces are getting removed while I am formatting my code in eclipse Luna. Any suggestion how to stop this?
{ "language": "en", "url": "https://stackoverflow.com/questions/49045188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to serve file under root path using Nginx? I have a website laike9m.com, which is served by Nginx. I want to access a text file AAA.txt with url laike9m.com/AAA.txt. The text file is on my server, let's say it's $HOME/AAA.txt. Redirection is not allowed. Current Nginx conf file is here. Thank you. A: location ~ ^(.*\.txt)$ { alias /home/laike9m/$1; } Solved it.
{ "language": "en", "url": "https://stackoverflow.com/questions/33075861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CFReadStreamOpen Returns Error kCFStreamErrorDomainPOSIXDomain I want to make a MD5 of an Image so I am doing this with below code CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath, size_t chunkSizeForReadingData, BOOL *isAbort) { // Declare needed variables CFStringRef result = NULL; CFReadStreamRef readStream = NULL; // Get the file URL CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)filePath, kCFURLPOSIXPathStyle, (Boolean)false); if (!fileURL) goto done; // Create and open the read stream readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, (CFURLRef)fileURL); if (!readStream) goto done; bool didSucceed = (bool)CFReadStreamOpen(readStream); if (!didSucceed) goto done; // Initialize the hash object CC_MD5_CTX hashObject; CC_MD5_Init(&hashObject); // Make sure chunkSizeForReadingData is valid if (!chunkSizeForReadingData) { chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData; } // Feed the data to the hash object bool hasMoreData = true; while (hasMoreData) { if(*isAbort){ NSLog(@"hasMoreData isAborted"); if (readStream) { CFReadStreamClose(readStream); CFRelease(readStream); } if (fileURL) { CFRelease(fileURL); } return nil; } uint8_t buffer[chunkSizeForReadingData]; CFIndex readBytesCount = CFReadStreamRead(readStream, (UInt8 *)buffer, (CFIndex)sizeof(buffer)); if (readBytesCount == -1) break; if (readBytesCount == 0) { hasMoreData = false; continue; } CC_MD5_Update(&hashObject, (const void *)buffer, (CC_LONG)readBytesCount); } // Check if the read operation succeeded didSucceed = !hasMoreData; // Compute the hash digest unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(digest, &hashObject); // Abort if the read operation failed if (!didSucceed) goto done; // Compute the string result char hash[2 * sizeof(digest) + 1]; for (size_t i = 0; i < sizeof(digest); ++i) { snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i])); } result = CFStringCreateWithCString(kCFAllocatorDefault, (const char *)hash, kCFStringEncodingUTF8); done: if (readStream) { CFReadStreamClose(readStream); CFRelease(readStream); } if (fileURL) { CFRelease(fileURL); } return result; } Above code is properly working in Mac OS, But I am doing the same thing in iOS and it is not working. As far as I know I am passing the fileUrl exactly right but in the CFReadStreamOpen() it returns the kCFStreamErrorDomainPOSIX and I came to know that this error no is 1 and it states that it is "Operation Not Permitted" I have gone through this link What to do in order to read the stream of any PHAsset of iOS device does changing the below file ownership affects in this context: A: PHAsset contains only metadata about image. In order to fetch image data you need to use PHImageManager. func requestImageData(for asset: PHAsset, options: PHImageRequestOptions?, resultHandler: @escaping (Data?, String?, UIImageOrientation, [AnyHashable : Any]?) -> Void) -> PHImageRequestID You can use CFReadStreamCreateWithBytesNoCopy to create CFReadStreamRef with data.
{ "language": "en", "url": "https://stackoverflow.com/questions/49666209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telegram Menu Keyboard bot Hello i have a question about bots in telegram, 2 years ago we could create telegram bots easily with chatfual bot, now i need make a bot that has menu button from bottom and when user tap on the button it answers the user and send the message like before, is there any full tutorial about it from youtube? i searched but i didn't get answer because all of the videos talks about inlinekeyboard but i need menu keyboard buttons not inlinekeyboard, i need full tutorial of python or any other language that tells me how can i make buttons like this, or is there any website that help me make bots like i said without coding? i don't want make these type of bots from other bots of telegram i want coding way or websites. thanks. like this picture also want make more buttons whithin button A: Check that, it's tottaly what you search : https://irazasyed.github.io/telegram-bot-sdk/usage/keyboards/#keyboards And https://medium.com/@chutzpah/telegram-inline-keyboards-using-google-app-script-f0a0550fde26
{ "language": "en", "url": "https://stackoverflow.com/questions/62443957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to upload canvas and image to the server with Javascript I have html code as follows: <div id="wrapper"> <img id="photo" src="http://autralis.blob.core.windows.net/thumbnails/1024x768/36/74/57/36745738883478623422431720268247042049573454290037543508541937745291910806066.jpg"/> <canvas id="canvas"></canvas> </div> <button id="save-button" onclick="onSaveChanges()">Save</button> Thus I have an image and on that image I want to draw canvas. That works fine. But now I want to upload it to the server, but not only the canvas. I want to upload image and the canvas, together as one image. How can I do that? Here is my js code where I try to upload it: function onSaveChanges(){ save_button_label.classList.add('hide'); save_button_spinner.classList.remove('hide'); var body = new FormData(); var canvasData = canvas.toDataURL("image/png"); body.append('photo', canvasData); var xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.onload = function (e) { if (xhr.readyState === 4 && xhr.status === 200) { // const result = JSON.parse(xhr.responseText); renderMessage(success, upload_success_msg) } }; xhr.onerror = function (e) { renderMessage(errors, upload_error_msg) }; xhr.send(body); } But with var canvasData = canvas.toDataURL("image/png"); I get only the canvas, and not the image also. Any idea what can I do to upload image and canvas together as one image? Thanks in advance. UPDATE The red border is canvas and the blue border is the image. I want to upload it as one image, thus both together as one. A: I changed html a little bit: <div id="result" style="background-color: red;"> <img id="photo" src="assets/images/audi.png"/> <canvas id="canvas"></canvas> </div> And I used HTML2Canvas library, which takes a screenshot of the whatever you want and save it as image. The javascript is as follows: function upload_to_server(canvasData){ return fetch(api_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({photo: canvasData}) }).then(function (value) { if(value.ok){ return value.json().then(function (response) { // Do something with response }) } }).catch(function (reason) { // Handle error }) } function onSaveChanges(){ save_button_label.classList.add('hide'); save_button_spinner.classList.remove('hide'); html2canvas(document.getElementById("result")).then(function(canvas) { var canvasData = canvas.toDataURL("image/" + image_type + ""); upload_to_server(canvasData) }); } I hope that it will help someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/48619138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any need/advantage of calling an api using the http client service when using websockets in angular? I am trying to learn how to use socket.io by building a simple chat app using the socket.io library and MEAN stack. From looking at some open source projects(like this one) I have seen that the client, mainly when executing the chat logic, communicates with the server via websockets and not the http client service provided by angular. Does this mean that when using web-sockets for real time updates there is no need to use http to communicate with the server? A: Most assuredly not. It is not a matter of angular though, it's just choosing the right tool for the right thing. Long story short: * *If it is a request/response model, then use http. Why? * *Because it's easier to handle. Proxies, dns and load balancers need no extra configuration to handle. Web Sockets do. *You have already setup 1 so it's not a problem. How will you handle caching, routing, gziping, SEO and all the out of the box stuff the http protocol and rest-apis handle? Everything you build, all communications will need their own security consideration, design patterns etc. *How will you handle the stateful nature of web sockets? They are currently supporting only vertical scaling, whereas rest apis scale both horizontally and vertically. If you really need a full duplex communication (there is server push only without sockets), then you should limit web socket usage to the cases where you really need it. Even in this case, go through a framework like signalR. All modern browsers support websockets but a lot of users still don't have browsers that do support them. SignalR falls back to long polling in those cases. If you use it on all cases, imagine what would happen if you use such a browser and you apply long polling for each request. I could go on, but I think you get the meaning.
{ "language": "en", "url": "https://stackoverflow.com/questions/58654499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prioritize Tasks in Android I have a map application, and every time that the user moves the map I have to make a new request to the back-end to receive the points. Right now I'm already optimizing a lot the process of getting the points. But I'd like to add prioritizing functionality to my Threads. It's executing the Threads in serial (one before the other). But my optimizations work better when I already process a larger bound thread before. Here is how I'm implementing my AsyncTask right now: plotPinsThread = new AsyncTask<Void, Boolean, List<Loja>>() { final boolean oldMy = showMyStores; final boolean oldOthers = showOtherStores; @Override protected List<Loja> doInBackground(Void... params) { try { publishProgress(true); Log.d(TAG, "=====> Inicio de requisição de pontos"); List<Loja> lojas = new ArrayList<>(); publishProgress(true); if (showMyStores && !isCancelled()) { publishProgress(true); lojas.addAll(lojasDAO.getLojasList(cliente, currentBounds, LojaJsonDAO.DEALERSHIPS, this)); } if (showOtherStores && !isCancelled()) { publishProgress(true); lojas.addAll(concorrentesDAO.getLojasList(others, currentBounds, LojaJsonDAO.COMPETITORS, this)); } return lojas; } catch (JSONException e) { Log.e(TAG, "Erro de Json", e); } return new ArrayList<>(); } @Override protected void onProgressUpdate(Boolean... values) { if (values[0]) { loading.setVisibility(View.VISIBLE); } else { loading.setVisibility(View.GONE); } } @Override protected void onCancelled() { Log.d(TAG, "Uma Thread foi cancelada: "); } @Override protected void onPostExecute(List<Loja> list) { publishProgress(true); boolean isLojasLoaded = lojasCarregadas.containsAll(list); if (!isLojasLoaded && isEnoughZoom() && oldMy == showMyStores && oldOthers == showOtherStores && !isCancelled()) { clearMarkers(); for (Loja loja : list) { publishProgress(true); if (loja.getPosition() != null) { mMap.addMarker(getMarker(loja)); } } lojasCarregadas.addAll(list); Log.d(TAG, "=====> Final de requisição de pontos"); } else { String msg = (isLojasLoaded) ? "já carregados." : "invalidos"; Log.d(TAG, "=====> Final de requisição, dados " + msg); } publishProgress(false); } }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); I read something about executors and I had the insight of creating a executor that would implement a PriorityQueue where I would make the Threads with larger bounds execute before the smaller ones. (the param currentBounds) I don't know how to do it, or if I should implement it with another thread approach. PS: If I implements a Executor, is there some way to get the params of the AsyncTask on it? A: You need a custom executor. When you call execute(), it uses a default executor that runs all tasks serially. If you call executeOnExecutor() you can specify an executor. The default one is serial, there's also THREAD_POOL_EXECUTOR which will run tasks in parallel. If you want a priority queue, you'll need to write your own that keeps a priority queue of tasks and executes them serially based on priority.
{ "language": "en", "url": "https://stackoverflow.com/questions/30200393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ Can't figure out arrays and functions Possible Duplicate: Stuck on C++ functions and arrays Stuck on this problem: I can't get it to run and i am stuck on getting the array functions to return to main. Thanks for any help. Requires the utilization of a 2 dimensional array to store the pounds of food eaten by 3 monkeys each of the seven days of the week. Create a function to obtain the pounds eaten for each monkey, each day of the week. Create a second function to determine pass through the array to calculate the total all of the moneys ate, and then the average eaten on one day. Create a third function to determine which monkey ate the least amount of food and on what day. Also output the amount the monkey ate on that day. Create a fourth function to determine which monkey ate the most amount of food on a single day. Output the monkey number, the pounds eaten, and the weekday. #include <iostream> using namespace std; const int monkeys = 3; const int weekdays = 7; double monkeyWeek[monkeys][weekdays]; double largest; double least; double average; int index; int dayCount; double amount; double amountEaten(double[] [weekdays], int); double mostEaten (double[] [weekdays],int); double leastEaten (double[][weekdays], int); int main(){ double mostBananas (double[] [weekdays],int); double leastBananas (double[][weekdays],int); //double bananaAverage (double[][weekdays], int); } double amountEaten(double array[] [weekdays], int) { cout << "Please enter the amount of food eaten per monkey per day." << endl; double amount = array[0][0]; for (index = 0; index < monkeys; index++) { for (dayCount = 0; dayCount < weekdays; dayCount++) { cout << endl << "Please enter the amount of pounds eaten by monkey" << (index +1) << endl << "for day " << (dayCount +1) << ": "; cin >> monkeyWeek[monkeys] [weekdays] ; if (monkeyWeek[monkeys] [weekdays] < 1) cout << endl <<"Must feed positive amount" << endl; } } } double mostEaten( double array[] [weekdays], int size) { double largest = array[0][0]; for (int count = 0; count < size; count++) { for (int col = 0; col < count; col++) { if (array[count][weekdays] > largest) largest = array[count][weekdays]; } } return largest; } double leastEaten(double array[] [weekdays], int size) { double least = array[0][0]; for (int count = 0; count < size; count++) { for (int col = 0; col < size; col++); { if (array[count][weekdays] < least) least = array[count][weekdays]; } } return least; } A: You are just declaring the functions, you haven't made a call to any functions at all. Use the sample below and change your program accordingly. Example: int main() { int i_array={0,1,2,3,4,5}; function(i_array); // Call a function printf("%d",i_array[0]); // will print 100 not 0 } void function(int [] i_array) { i_array[0]=100; }
{ "language": "en", "url": "https://stackoverflow.com/questions/13281089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How do I run several linear regressions at once in R? If I have a dataset with variable A, X, Y, and Z and I want to run two linear regressions - both have A as the dependent variable but one has X as the independent variable and the other has Y (note - NOT multiple regression), what can I do? lm(A ~ X, Y, df = df) doesn't seem to work, and obviously lm(A ~ X + Y, df = df) becomes a multiple regression. I can use lm(A ~ ., - Z, df = df) but I'm looking for a way that I could pick and choose multiple variables to use as the independent variable. Thanks. A: lmList in nlme can run multiple regressions at once: library(nlme) DF <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10) DF2 <- cbind(A = DF$A, stack(DF[c("X", "Y")])) lmList(A ~ values | ind, DF2) A: Here is an alternative using formulas() from package modelr : df <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10) library(modelr) ll <- formulas(~ A, m1 = ~ X, m2 = ~ Y ) results_list <- lapply(ll, lm, data = df)
{ "language": "en", "url": "https://stackoverflow.com/questions/64391589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement search box for dropdown in angular I want to implement search box without any third party libraries, i want search to be inside the dropdown. how to do this <select class="form-control" [(ngModel)]="selected5" [ngModelOptions]="{standalone: true}" formControlName="manpower_requirement"> <option selected *ngFor="let person of newArray" [ngValue]="person">{{ person.positions }} </option> </select> A: filter your newArray. Add an input for the search and bind it to searchValue with [(ngModel)]="searchValue" then in the setter, filter newArray. so: private _searchValue:string set searchValue(value:string) { this._searchValue = value; this.newArray = this.newArray.filter(v=>v.contains(value)); } Note - this is unchecked, there may be typos. But this is the idea of a way to do it
{ "language": "en", "url": "https://stackoverflow.com/questions/64857213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting HTTP Status 500 when location href or when forwarding from Servlet? I get this error: HTTP Status 500 - type Exception report message descriptionThe server encountered an internal error () that prevented it from fulfilling this request. exception org.apache.jasper.JasperException: java.lang.NullPointerException root cause java.lang.NullPointerException note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1-b24 logs. GlassFish Server Open Source Edition 3.1-b24 when I try to forward from a jsp to another jsp or when I forward in a servlet... The thing is that Y modify some datils from my page and I want to go back to the login-page and log in again to see if the update was successful !... Any ideas on this error ?... Thankx A: A NullPointerException is a rather trivial exception and has actually nothing to do with JSP/Servlets, but with basic Java in general (look, it's an exception of java.lang package, not of javax.servlet package). It just means that some object is null while your code is trying to access/invoke it using the period . operator. Something like: SomeObject someObject = null; someObject.doSomething(); // NullPointerException! The 1st line of the stacktrace tells you in detail all about the class name, method name and line number where it occurred. Fixing it is relatively easy. Just make sure that it's not null or bypass the access altogether. You should rather concentrate on why it is null and/or why your code is trying to deal with null.
{ "language": "en", "url": "https://stackoverflow.com/questions/8013800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why is execstack required to execute code on the heap? I wrote the code below to test shellcode (for unlinking /tmp/passwd) for an assignment in a security class. When I compile with gcc -o test -g test.c, I get a segfault on the jump into the shellcode. When I postprocess the binary with execstack -s test, I no longer get a segfault and the shellcode executes correctly, removing /tmp/passwd. I am running gcc 4.7.2. It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former. Is this expected behavior? If so, what is the rationale? #include <stdio.h> #include <stdlib.h> char* shellcode; int main(){ shellcode = malloc(67); FILE* code = fopen("shellcode.bin", "rb"); fread(shellcode, 1, 67, code); int (*fp)(void) = (int (*) (void)) shellcode; fp(); } Here is the output of xxd shellcode.bin: 0000000: eb28 5e89 760c 31c0 8846 0bfe c0fe c0fe .(^.v.1..F...... 0000010: c0fe c0fe c0fe c0fe c0fe c0fe c0fe c089 ................ 0000020: f3cd 8031 db89 d840 cd80 e8d3 ffff ff2f ...1...@......./ 0000030: 746d 702f 7061 7373 7764 tmp/passwd A: The real "unexpected" behavior is that setting the flag makes the heap executable as well as the stack. The flag is intended for use with executables that generate stack-based thunks (such as gcc when you take the address of a nested function) and shouldn't really affect the heap. But Linux implements this by globally making ALL readable pages executable. If you want finer-grained control, you could instead use the mprotect system call to control executable permissions on a per-page basis -- Add code like: uintptr_t pagesize = sysconf(_SC_PAGE_SIZE); #define PAGE_START(P) ((uintptr_t)(P) & ~(pagesize-1)) #define PAGE_END(P) (((uintptr_t)(P) + pagesize - 1) & ~(pagesize-1)) mprotect((void *)PAGE_START(shellcode), PAGE_END(shellcode+67) - PAGE_START(shellcode), PROT_READ|PROT_WRITE|PROT_EXEC); A: Is this expected behavior? Looking at the Linux kernel code, I think that the kernel-internal name for this flag is "read implies exec". So yes, I think that it's expected. It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former. Why would you need the complete heap to be executable? If you really need to dynamically generate machine code and run it or so, you can explicitly allocate executable memory using the mmap syscall. what is the rationale? I think that the idea is that this flag can be used for legacy programs that expect that everything that's readable is also executable. Those programs might try to run stuff on the stack and they might try to run stuff on the heap, so it's all permitted.
{ "language": "en", "url": "https://stackoverflow.com/questions/23276488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Meteor JS: Organizing Code for Sharing Code Between Template Helpers Inside my Meteor JS Project's client/templates/pages folder I have these files: 1.) admin_add_product.html and admin_add_product.js 2.) admin_edit_product.html and admin_edit_product.js Inside both admin_add_product.js and admin_edit_product.js I have the same exact code that I use for both files: var ucwords = function(str) { return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" "); }; var editForDB = function(str){ return ucwords(str.trim()); } var makeHidden = function(object){ object.addClass('hidden'); } var removeHidden = function(object){ object.removeClass('hidden'); } var makeDisabled = function(object){ object.addClass('disabled'); } var removeDisabled = function(object){ object.removeClass('disabled'); } I would like to organise my code so that I don't REPEAT any code unnecessarily. I wish to put the above snippet of code somewhere where I can share between Template helpers (in this case between admin_add_product.js and admin_edit_product.js) so if ever I do need to edit it I just need to edit it in one place rather than two or more.... I already tried Template.registerHelper but I have found that that only works inside the .html file......... How do I organise my code in Meteor JS to do this? Is this even possible in Meteor JS given that each template helper file is supposedly enclosed inside a function(){} closure??? A: Variables declared with var have a file scope, and are indeed inside a closure like you mentioned. However, if you declare new variables without the var keyword, they are accessible throughout your project (given you load files in the right order), as Meteor declares these variables outside the closure. In your case the solution is to declare your form functions without var, or maybe better declare a new object without var and put them as methods in there: FormHelpers = {}; FormHelpers.ucwords = function(str) { return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" "); }; ... You can then use these helpers in both you add and edit tenplates, or anywhere else you need them. More info on namespacing in the Meteor docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/29729993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Analytics with First Party Cookie I am in the process of setting up Google Analytics (GA) on a Wordpress site. As part of this, I want to include a custom cookie (for users that consent) that allows me to segment the analytics of users based on what settings they have active on the site (via a custom plugin). I have managed to successfully implement this most of the way (the cookie is included in many of the tagged events). However, I have included the custom cookie in a Gravity Form that is being submitted on the website, and there are a number of instances of a form being submitted successfully, tagged with a cookie ID, but that cookie ID is not showing up in Google Analytics as an option to segment page views, for example. I have a record of the cookie being generated on my Apache server, but it has not made its way through to GA. Is there a way to see all events with a specific attribute in GA? Or is this only possible with a custom report (which necessarily requires you to filter out events that don't have a specific metric). (I'm primarily a back-end developer, and have limited experience with GA. Apologies if there is something very obvious that I have not done.) A: You would need to create a custom dimension in Google Analytics, retrieve the cookie value and pass it to the GA code (how exactly would depend on the version of the GA code that you use, as they have recently shifted from the analytics.js library to gtag.js).
{ "language": "en", "url": "https://stackoverflow.com/questions/47817595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image resize script I'm searching a javascript that can resize images similar to script thats available as a plugin in vBulletin CMS: I want the script to be used in blogger blog so that all images i upload into a post are resized to a smaller res and on clicking the image should be displayed in original dimensions Something of the sort getelementbyID("img"). are there any script providing this feature? Pls help me out Thanks in advance. A: Something like a lightbox, perhaps? I know the specific interaction you're asking about, and personally, I've always found it really obnoxious. A: If you don't want to use a server side script to automatically create a smaller version of the image that you would link to the larger version, I wouldn't recommend using JavaScript to resize an image either. I'd recommend setting the image's dimensions in CSS and then attaching a click handler with JS that showed the image in some sort of overlay (or just using HTML to link to the larger image file).
{ "language": "en", "url": "https://stackoverflow.com/questions/6314005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically load the material-ci-icons icon I use Material-ui@next and material-ui-next@next material-ui@next load one icon usage: import AddIcon from 'material-ui-icons/AddIcon'; function AddIconButton(props) { return ( <AddIcon /> ); } But I want dynamically load the material-ci-icons icon For example, I have variable menus const menus = [ { Name: 'menu1', Icons: 'face', }, { Name: 'menu2', Icon: 'extension', } ]. How to display the icon on the page according to the menus A: I faced with this problem too. i use this link: dynamically load an icon. save my menu icon name at database and use <Icon>{props.iconName}</Icon> but, it doesn't work for me. so because i don't have so much time i just save the SVG format of material ui icon in my database and restore it at my JSX. i got SVG format of icons from inspect element of browser from material ui icon web page
{ "language": "en", "url": "https://stackoverflow.com/questions/45416796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences I am trying to integrate elastic search with hibernate search.For doing this I am using following maven dependencies. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search-orm</artifactId> <version>5.7.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search-elasticsearch</artifactId> <version>5.6.1.Final</version> </dependency> But while deploying the application I am getting below error. java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences(Ljava/util/Collection;Ljava/util/Map;)Ljava/util/Map. I know this question has already been asked but I am not able to find out the root cause of error.Any suggestion.......... A: You're using multiple modules of Hibernate Search, but without different versions (5.7.0.Final and 5.6.1.Final). Use the same version for each Hibernate Search module, in your case 5.7.0.Final: <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search-orm</artifactId> <version>5.7.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search-elasticsearch</artifactId> <version>5.7.0.Final</version> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/44454773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Observable in for loop? I would like to call an observable REST service in a for loop. It returns base64 encoded csv file. I would like to decode it and concatenate it into one string and return it. After that I am trying to subsrciibe to that method and click the DOM to download. I get empty string with only "\r\n" in it. Why doesn't it wait for REST to return the file before returning? downloadFilesAndConcatenate(): Observable<any> { let concatenatedFileDecoded: string = '\r\n'; for (let i = 0; i < this.fileIDs.length; i++) { this.restService.getFile(this.fileIDs[i]).subscribe(response => { this.fileResultSet = response; this.message = response.message; this.file = this.fileResultSet.result; let fileCSVbase64 = this.file.fileBytes let fileCSVDecoded = atob(fileCSVbase64); concatenatedFileDecoded += fileCSVDecoded; }, error => { this.message = error.error.message; }); return new Observable( observer => { observer.next(concatenatedFileDecoded) observer.complete(); }); } } And then I subscribe to it: download() { if (this.dateEnd !== null && typeof this.dateEnd !== "undefined") { debugger; this.downloadFilesAndConcatenate() // Multiple files .subscribe( (result) => { debugger; const link = document.createElement( 'a' ); link.style.display = 'none'; document.body.appendChild( link ); const blob = new Blob([result], {type: 'text/csv'}); const objectURL = URL.createObjectURL(blob); link.href = objectURL; link.href = URL.createObjectURL(blob); link.download = this.file.name; link.click(); }, (err) => { console.error(err); }, () => console.log("download observable complete") ); } else { this.downloadFile(); // Only one file } } A: because it is asynchroniuos code. it is expected that sync code will be executed earlier than async. correct code would be like this downloadFilesAndConcatenate(): Observable<string> { return forkJoin(this.fileIDs.map(id => this.restService.getFile(id))).pipe( map(responses => '\r\n'+responses.map(r => atob(r.result.fileBytes)).join('')) catchError(e => this.message = e.error.message) ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/70500841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to set java web application's context root when working with reverse proxy * *My old way using mod_jk in apache and configure virtual host in tomcat In the JSP file, I refer to CSS as below /<%=request.getContextPath()%>/css/styles.css while the home link is set to /<%=request.getContextPath()%>/ so this worked fine when I use mod_jk in apache to work with tomcat using ajp; * *When I try to configure reverse proxy as below ProxyPass / http://localhost:800/mywebapp ProxyPassReverse / http://localhost:800/mywebapp the home page can be retrieved fine but the css request becomes http://mydomain.com/mywebapp/mywebapp/css/style.css so the css file can not be retrieved correctly; * *I think one possible way is to always use relative path like ./style.css or ../style.css a. since header/footer are shared, and the home page is in a different level with detail page, it's inconvenient to use relative path because they're at a different level b. still, I think the home link will have to be /<%=request.getContextPath()%>/ so I wonder what's the way to set contextroot fine in java web and also work fine with reverse proxy? thx a lot A: As I know your application server (Tomcat) isn't able to be aware of a reverse proxy presence. Generally speaking, it can be contacted through any number of reverse proxies or directly by browsers. A network configuration is usually used to limit this, not HTTP or Java. So, you must accurately rely on relative URLs to make your application work well. When I have to deal with reverse proxy presence (almost always due to SSO architectures), I embed a "junction" configuration string item (the portion of the URL used in the proxy to map the application) and use it in the only places where I need to build an absolute URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/8708009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to vectorize process of spltting vector I have a vector of numbers (here random). I'd like to calculate the consecutive relation of something (here means to clarify example) on the left and right side of each number in a vector. Here is a procedural example. I'm interested in the vectorized form. from numpy.random import rand import numpy as np numbers = rand(40) k=np.zeros(numbers.shape) for i in range(*numbers.shape): k[i]=np.mean(numbers[:i])/np.mean(numbers[i:]) This example will return nan in the first iteration but it is not a problem now. A: Here's a vectorized way - n = len(numbers) fwd = numbers.cumsum()/np.arange(1,n+1) bwd = (numbers[::-1].cumsum()[::-1])/np.arange(n,0,-1) k_out = np.r_[np.nan,fwd[:-1]]/bwd Optimizing a bit further with one cumsum, it would be - n = len(numbers) r = np.arange(1,n+1) c = numbers.cumsum() fwd = c/r b = c[-1]-c bwd = np.r_[1,b[:-1]]/r[::-1] k_out = np.r_[np.nan,fwd[:-1]]/bwd A: I spent some time and there is a simple and universal solution: numpy.vectorize with excluded parameter, where vector designated to be split must be excluded from vectorisation. The example still uses np.mean but can be replaced with any function: def split_mean(vect,i): return np.mean(vect[:i])/np.mean(vect[i:]) v_split_mean = np.vectorize(split_mean) v_split_mean.excluded.add(0) numbers = np.random.rand(30) indexes = np.arange(*numbers.shape) v_split_mean(numbers,indexes)
{ "language": "en", "url": "https://stackoverflow.com/questions/58961233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Function that reads and stores values from configuration file I'm relatively new to C++ programming and I am just trying to create a function that opens a configuration file, reads each line and column, then stores the values into some array. So my config file will look like this which simply just stores values: 12345 10 20 67890 30 40 ... ... What I want to do is open this file, read each line and store the values into an [i][j] array. So for the above, it would be stored as: [0][0] = 12345 [0][1] = 10 [0][2] = 20 [1][0] = 67890 [1][1] = 30 [1][2] = 40 I have been looking at the fopen function to open the file, but when I research on how to store these values how I want (using functions like fgets), I keep hitting a wall. My attempt thus far: #include <iostream> using namespace std; int main() { FILE *fp; fp = fopen("configFile.conf","r"); char a[20]; char b[20]; char c[20]; fscanf(fp, "%s\t%s\t%s", a, b, c); cout << a << " " << b << " " << c << endl; } output: 12345 10 20 Now I want to just modify this loop through until the end of the file and store the values in an array based off the i'th element. A: This is C code : #include <stdio.h> int main() { FILE *fp; int i = 0; fp = fopen("configFile.conf", "r"); if(fp == NULL) // To check for errors { printf("Error \n"); } char a[20][20]; // Declared a 2D array char b[20][20]; char c[20][20]; while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs { printf("%s %s %s\n", a[i], b[i], c[i]); i++; } return 0; } C++ code is : #include <iostream> using namespace std; int main() { FILE *fp; int i = 0; fp = fopen("configFile.conf", "r"); if(fp == NULL) // To check for errors { cout<< "Error" << endl; } char a[20][20]; // Declared a 2D array char b[20][20]; char c[20][20]; while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs { cout << a[i] << " " << b[i] << " " << c[i] << endl; i++; } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/64886675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access Parent Element Within href So... this is a simple question with a simple answer, but somehow my RTFMing isn't proving any results. I have a link within a div, like so: <div> <a href=''>Close</a> I'd like to close that div with that link, and I've been trying the following code: <div> <a href="javascript:this.parentNode.style.display='none'">Close</a> However, it still hasn't worked... any suggestions are greatly appreciated. A: Change it to this: <div> <a href="#" onclick="this.parentNode.style.display='none'">Close</a> The reason is that when using href="javascript:..., this doesn't refer to the element that received the event. You need to be in an event handler like onclick for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/5054342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create this below JSON response using python DRF Since I am new to this DRF I am facing some difficulties creating this JSON. I have created an API endpoint and the output of that API endpoint is like this now as shown below "meta": { "limit": 1, "page_count": 1, "total_count": 1 }, "results": { "id": 1234567, "curriculum": { "ES Math": [ { "grade_level": "ES", "subject": "Math", "subject_abbr": "Math", "product_id": 438, "product_title": "Test1", "ratings": [ { "source": "A", "report_url": "********", "Org1_rating": [ { "name": "green_alignment_ratings", "value": 12, "label": "Meet Expectations", "label_color": "Green" }, { "name": "green_usability_ratings", "value": 12, "label": "Meet Expectations", "label_color": "Green" } ], "Org2_rating": [ { "name": "Overall", "value": null, "label": "Tier 1: Exemplifies Quality", "label_color": null } ] } ] }, { "grade_level": "ES", "subject": "Math", "subject_abbr": "Math", "product_id": 2085, "product_title": "Test2", "ratings": [ { "source": "A", "report_url": "********", "Org1_rating": [ { "name": "green_alignment_ratings", "value": 12, "label": "Meet Expectations", "label_color": "Green" }, { "name": "green_usability_ratings", "value": 12, "label": "Meet Expectations", "label_color": "Green" } ], "Org_rating2": "null" } ] } ] } } } But I want the output to be in this format below { "meta": { "limit": 1, "page_count": 1, "total_count": 1 }, "results": { "id": 1234567, "curriculum": { "ES Math": [ { "grade_level": "ES", "subject": "Math", "subject_abbr": "Math", "product_id": 438, "product_title": "Test1", "ratings": [ { "review_org": "Org1", "review_url": "url", "review_items": [ { "name": "green_alignment_ratings", "value": 14, "label": "Meets Expectations", "label_color": "Green" }, { "name": "green_usability_ratings", "value": 34, "label": "Green", "label_color": 38 } ] }, { "review_org": "Org2", "review_url": "url", "review_items": [ { "name": "Overall", "value": null, "Label": "Tier I, Exemplifies quality", "scale": null } ] } ] }, { "grade_level": "ES", "subject": "Math", "subject_abbr": "Math", "product_id": 2085, "product_title": "Test2", "ratings": [ { "review_org": "Org1", "review_url": "url", "review_items": [ { "name":"green_alignment_ratings", "value": 14, "label": "Meets Expectations", "label_color": "Green" }, { "name":"green_usability_ratings", "value": 34, "label": "Meets Expectations", "label_color": "Green" } ] }, { "review_org": "Org2", "review_url": "url", "review_items": [] } ] } ] } } } And I tried something with the serializer below but this is yeilding some different JSON only. class CurriculumSerializer(ModelSerializer): grade_level = serializers.CharField(source='grade_level_dim') subject_abbr = serializers.CharField(source='subject_abbr_dim') product_id = serializers.IntegerField(source='dim_id') product_title = serializers.CharField(source='title_dim') ratings = serializers.SerializerMethodField() class Meta: model = Table2 fields = [ 'grade_level', 'subject', 'subject_abbr', 'product_id', 'product_title', 'ratings' ] def get_ratings(self,obj): queryset = Table2.objects.all() c = queryset.filter(id=obj.id, title_dim = obj.title_dim, ratings_source__isnull=False).distinct('id',) if c.exists(): serializer = RatingsSerializer(c, many=True) return serializer.data else: data = 'null' return data class RatingsSerializer(ModelSerializer): review_items = serializers.SerializerMethodField() Louisiana_rating = serializers.SerializerMethodField() class Meta: model = Table3 fields = ['source','report_url','review_items','Louisiana_rating'] def get_review_items(self, obj): queryset = Table3.objects.all() c = queryset.filter(source__iexact = 'Org1', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim) # print(c.query) if c.exists(): serializer = reportSerializer(c, many=True) return serializer.data else: data = 'null' return data def get_Louisiana_rating(self, obj): queryset = Table3.objects.all() c = queryset.filter(source__iexact = 'Org2', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim) if c.exists(): serializer = reportSerializer(c, many=True) return serializer.data else: data = 'null' return data class reportSerializer(ModelSerializer): class Meta: model = Table3 fields = ['name', 'value', 'label', 'label_color'] class DistrictDetailSerializer(ModelSerializer): curriculum = serializers.SerializerMethodField() class Meta: model = Table1 exclude = ('finance_total', 'revenue_total') def get_curriculum(self, obj): queryset_list = Table2.objects.all() c = queryset_list.filter(id=obj.id)\ .distinct('col1','col2') if c.exists(): serializer = CurriculumSerializer(c, many=True) curriculum_map = {} for d in serializer.data: key = f"{d['grade_level']} {d['subject_abbr']}" if key in curriculum_map: curriculum_map[key].append(d) else: curriculum_map[key] = [d, ] return curriculum_map else: data = 'null' return data The table3 has all details for ratings like source, report_url, name,label,value,label_colour I want this values as show in the JSON below. A: This error usually occurs if the user account was not given/assigned to the Virtual Machine User Login role on the VMs. Please check this https://learn.microsoft.com/en-us/azure/active-directory/devices/howto-vm-sign-in-azure-ad-windows#azure-role-not-assigned to assign required roles and try login.
{ "language": "en", "url": "https://stackoverflow.com/questions/69783608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to empty/flush Windows READ disk cache in C#? If I am trying to determine the read speed of a drive, I can code a routine to write files to a filesystem and then read those files back. Unfortunately, this doesn't give an accurate read speed because Windows does disk read caching. Is there a way to flush the disk read cache of a drive in C# / .Net (or perhaps with Win32 API calls) so that I can read the files directly from the drive without them being cached? A: Why DIY? If you only need to determine drive speed and not really interested in learning how to flush I/O buffers from .NET, you may just use DiskSpd utility from http://research.microsoft.com/barc/Sequential_IO/. It has random/sequential modes with and without buffer flushing. The page also has some I/O related research reports you might find useful. A: const int FILE_FLAG_NO_BUFFERING = 0x20000000; return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,64 * 1024, (FileOptions)FILE_FLAG_NO_BUFFERING | FileOptions.Asynchronous & FileOptions.SequentialScan); A: Constantin: Thanks! That link has a command-line EXE which does the testing I was looking for. I also found a link off that page to a more interesting article (in Word and PDF) on this page: Sequential File Programming Patterns and Performance with .NET In this article, it talks about Un-buffered File Performance (iow, no read/write caching -- just raw disk performance.) Quoted directly from the article: There is no simple way to disable FileStream buffering in the V2 .NET framework. One must invoke the Windows file system directly to obtain an un-buffered file handle and then ‘wrap’ the result in a FileStream as follows in C#: [DllImport("kernel32", SetLastError=true)] static extern unsafe SafeFileHandle CreateFile( string FileName, // file name uint DesiredAccess, // access mode uint ShareMode, // share mode IntPtr SecurityAttributes, // Security Attr uint CreationDisposition, // how to create uint FlagsAndAttributes, // file attributes SafeFileHandle hTemplate // template file ); SafeFileHandle handle = CreateFile(FileName, FileAccess.Read, FileShare.None, IntPtr.Zero, FileMode.Open, FILE_FLAG_NO_BUFFERING, null); FileStream stream = new FileStream(handle, FileAccess.Read, true, 4096); Calling CreateFile() with the FILE_FLAG_NO_BUFFERING flag tells the file system to bypass all software memory caching for the file. The ‘true’ value passed as the third argument to the FileStream constructor indicates that the stream should take ownership of the file handle, meaning that the file handle will automatically be closed when the stream is closed. After this hocus-pocus, the un-buffered file stream is read and written in the same way as any other. A: Response of Fix was almost right and better than PInvoke. But it has bugs and doesn't works... To open up File w/o caching one needs to do following: const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; FileStream file = new FileStream(fileName, fileMode, fileAccess, fileShare, blockSize, FileFlagNoBuffering | FileOptions.WriteThrough | fileOptions); Few rules: * *blockSize must be hard drive cluster size aligned (4096 most of the time) *file position change must be cluster size aligned *you can't read/write less than blockSize or block not aligned to it's size And don't forget - there is also HDD Cache (which slower and smaller than OS cache) which you can't turn off by that (but sometimes FileOptions.WriteThrough helps for not caching writes). With those options you have no reason for flushing, but make sure you've properly tested that this approach won't slow things down in case your implementation of cache is slower. A: I found this article and it seems that this is a complicated program because you also have to flush other caches.
{ "language": "en", "url": "https://stackoverflow.com/questions/122362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Python - huge memory consumption while parsing folder of CSV files I have several folders, each of them contains many CSV files. I need to parse them to make some plots etc. The problem is, that memory consumption is huge and after while it skyrockets to cca 3.4GB. I have no idea what's the cause of this behavior, I've never met a memory-related problem with Python before. I've found memory profiler, which gives me this output: Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py Line # Mem usage Increment Line Contents ================================================ 560 293.340 MiB 0.000 MiB @profile 561 def getAllDataClassifiedFromFolder(measuredFuncFolderArg, 562 yLabelArg, 563 filenameArgs, 564 slideshowCreator, 565 samplesArgs=None): 566 567 293.340 MiB 0.000 MiB sampleSourcesInds = {} 568 293.340 MiB 0.000 MiB summarySourcesAvg = {} 569 293.340 MiB 0.000 MiB summarySourcesAvgInds = {} 570 293.340 MiB 0.000 MiB summarySourcesFull = {} 571 572 3342.426 MiB 3049.086 MiB for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True): 573 # Ignorovat skryte slozky kvuli GITu atd. 574 # TODO mozna nebude treba 575 293.340 MiB -3049.086 MiB filenames = [f for f in filenames if not f[0] == '.'] 576 293.340 MiB 0.000 MiB dirnames[:] = [d for d in dirnames if not d[0] == '.'] 577 578 ########################## 579 # Parsovani jedne slozky # 580 ########################## 581 582 # Vsechna data z jedne slozky (funkce na urcitem radku) 583 293.340 MiB 0.000 MiB folderData = [] 584 585 # Nacitam parametry dane v nazvu CSV souboru 586 293.340 MiB 0.000 MiB funcLabelArg = filenameArgs.getFuncLabel() 587 293.340 MiB 0.000 MiB xLabelArg = filenameArgs.getXLabel() 588 293.340 MiB 0.000 MiB otherUserArgs = filenameArgs.getConfigLst() 589 590 # 'Rozlozim' config argument na jednotlive hodnoty 591 293.340 MiB 0.000 MiB keyLst = filenameArgs.getLstOfParams() 592 593 3382.207 MiB 3088.867 MiB for filename in filenames: 594 # Nactu data 595 3382.207 MiB 0.000 MiB p = LabeledCSVParser('{}/{}'.format(dirpath, filename)) 596 3382.207 MiB 0.000 MiB p.parse() 597 3382.207 MiB 0.000 MiB data = p.getDicData() 598 599 # Vytvorit a zapsat 'samples', pokud jsou zadany 600 # parametrem 'samplesArgs' We can see, that in lines 572 and 593 memory consumption rises dramatically. Do you have any idea why? I suppose it's something with os.walk... So, have you ever seen this before? And if you have, could you, please, tell me, how to deal with this? I've tried to add an explicit destructor to the LabeledCSVParser object, but it has a very little effect on memory. In addition, it appears, that there's no significant memory consumption in parse() function. So, I'll try to inspect iterating through files a little more. Edit 1 Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py Line # Mem usage Increment Line Contents ================================================ 100 3271.395 MiB 0.000 MiB @profile 101 def parse(self): 102 """ 103 Funkce pro parsovani 'ostitkovaneho' CSV. 104 105 Predpoklada CSV ve tvaru: 106 107 # Label 1 108 data1, data2 109 data3, data4 110 111 # Label 2 112 data5, data6 113 data7, data8 114 ... 115 116 Labely se mohou opakovat, ziskane hodnoty 117 se ulozi do ruznych listu ve slovniku __dicData, 118 kde jejich spolecnym klicem bude label. 119 """ 120 121 3271.395 MiB 0.000 MiB currentLabel = self.__parsedFile.readline().split('#')[1].strip() 122 3271.395 MiB 0.000 MiB dataBlock = list() 123 3271.395 MiB 0.000 MiB self.__dicData[currentLabel] = list() 124 125 # Ulozim soucasny dataBlock do __dicData pod klic currentLabel 126 # - hodnoty se do tohoto dataBlocku zapisuji pozdeji diky 127 # referenci 128 3271.395 MiB 0.000 MiB self.__dicData[currentLabel].append(dataBlock) 129 130 3272.949 MiB 1.555 MiB for row in self.__parsedFile: 131 # Kontrola, jestli se jedna o label nebo radek s daty 132 3272.949 MiB 0.000 MiB if row.__contains__('#'): 133 134 # Vytvorim novy dataBlock 135 3271.395 MiB -1.555 MiB dataBlock = list() 136 137 # Zisk nazvu labelu z radku 138 3271.395 MiB 0.000 MiB tmpLabel = row.split('#')[1].strip() 139 140 # Label se stane 'aktualnim' - nasledujici 141 # data se budou zapisovat k nemu 142 3271.395 MiB 0.000 MiB currentLabel = tmpLabel 143 144 # Pokud neni label 'zaevidovany', pridam 145 # jej do __dicData jako klic 146 3271.395 MiB 0.000 MiB if currentLabel not in self.__dicData.keys(): 147 3271.395 MiB 0.000 MiB self.__dicData[currentLabel] = list() 148 149 3271.395 MiB 0.000 MiB self.__dicData[currentLabel].append(dataBlock) 150 else: 151 # Pridam rozparsovany radek do aktualniho 152 # bloku dat jako n-tici 153 3272.949 MiB 1.555 MiB dataBlock.append(tuple(row.strip().split(','))) Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py Line # Mem usage Increment Line Contents ================================================ 558 293.543 MiB 0.000 MiB @profile 559 def getAllDataClassifiedFromFolder(measuredFuncFolderArg, 560 yLabelArg, 561 filenameArgs, 562 slideshowCreator, 563 samplesArgs=None): 564 565 293.543 MiB 0.000 MiB sampleSourcesInds = {} 566 293.543 MiB 0.000 MiB summarySourcesAvg = {} 567 293.543 MiB 0.000 MiB summarySourcesAvgInds = {} 568 293.543 MiB 0.000 MiB summarySourcesFull = {} 569 570 2746.160 MiB 2452.617 MiB for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True): 571 # Ignorovat skryte slozky kvuli GITu atd. 572 # TODO mozna nebude treba 573 #filenames = [f for f in filenames if not f[0] == '.'] 574 #dirnames[:] = [d for d in dirnames if not d[0] == '.'] 575 576 ########################## 577 # Parsovani jedne slozky # 578 ########################## 579 580 # Vsechna data z jedne slozky (funkce na urcitem radku) 581 293.543 MiB -2452.617 MiB folderData = [] 582 583 # Nacitam parametry dane v nazvu CSV souboru 584 293.543 MiB 0.000 MiB funcLabelArg = filenameArgs.getFuncLabel() 585 293.543 MiB 0.000 MiB xLabelArg = filenameArgs.getXLabel() 586 293.543 MiB 0.000 MiB otherUserArgs = filenameArgs.getConfigLst() 587 588 # 'Rozlozim' config argument na jednotlive hodnoty 589 293.543 MiB 0.000 MiB keyLst = filenameArgs.getLstOfParams() 590 591 293.543 MiB 0.000 MiB print('nacitam data') 592 3271.395 MiB 2977.852 MiB for filename in filenames: 593 # Nactu data 594 3271.395 MiB 0.000 MiB p = LabeledCSVParser('{}/{}'.format(dirpath, filename)) 595 3271.395 MiB 0.000 MiB p.parse() 596 3271.395 MiB 0.000 MiB data = p.getDicData() 597 598 3271.395 MiB 0.000 MiB print('zapisuji samples') 599 # Vytvorit a zapsat 'samples', pokud jsou zadany 600 # parametrem 'samplesArgs' 601 3271.395 MiB 0.000 MiB if samplesArgs: 602 sampleSourcesInds[filename] = {} 603 for sampleArg in samplesArgs: 604 prevNumOfSources = slideshowCreator.getNumOfDataSources() 605 slideshowCreator.createAndAddDataSource(data[sampleArg], 100, True, 0, 2) 606 sampleSourcesInds[filename][sampleArg] = list(range(prevNumOfSources, 607 slideshowCreator.getNumOfDataSources())) 608 609 # Ziskam nazvy parametru z nazvu souboru 610 3271.395 MiB 0.000 MiB args = filename[0:filename.rfind('.')].split('_') 611 612 3271.395 MiB 0.000 MiB print('tvorim slovnik') 613 # Priradim konkretni hodnoty z nazvu CSV souboru 614 # k zadanym parametrum filenameArgs 615 3271.395 MiB 0.000 MiB d = {key: (args[i] if i < len(args) else '') for i, key in enumerate(keyLst)} 616 617 # Pridam do slovniku nactena data ze souboru 618 3271.395 MiB 0.000 MiB d['Data'] = data 619 620 3271.395 MiB 0.000 MiB print('pridavam slovnik do folderData') 621 3271.395 MiB 0.000 MiB folderData.append(d) 622 623 ############################################################### 624 # Rozdelim nactena data ze slozky do skupin podle volitelnych # 625 # argumentu (preconditioner, schur complement...) # 626 ############################################################### 627 2742.480 MiB -528.914 MiB print('rozdeluji data do kategorii') 628 # Ulozene prumerne hodnoty yLabel za vsechna 629 # volani funkce 630 2742.480 MiB 0.000 MiB folderDataGroupsAvg = {} 631 632 # Ulozene hodnoty yLabel ze vsech volani fce 633 # 634 # TODO mozna bude treba zapsat jako zdroj pro 635 # graf jednotlivych iteraci solveru 636 2742.480 MiB 0.000 MiB folderDataGroupsFull = {} 637 638 2745.746 MiB 3.266 MiB for i, val in enumerate(folderData): 639 # Ziskam hodnoty konfiguracnich argumentu 640 # a ulozim je jako n-tici 641 2745.746 MiB 0.000 MiB optArgsTup = tuple([str(val[arg]) for arg in otherUserArgs]) 642 643 # Pokud jeste neni, pridam n-tici s konfiguracnimi 644 # parametry jako klic pro slovnik s prumernymi 645 # hodnotami spotreby 646 2745.746 MiB 0.000 MiB if optArgsTup not in folderDataGroupsAvg: 647 2743.320 MiB -2.426 MiB folderDataGroupsAvg[optArgsTup] = {} 648 2743.320 MiB 0.000 MiB folderDataGroupsFull[optArgsTup] = {} 649 650 2745.746 MiB 2.426 MiB if folderData[i][funcLabelArg] not in folderDataGroupsAvg[optArgsTup]: 651 2744.539 MiB -1.207 MiB folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] = [] 652 2744.539 MiB 0.000 MiB folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] = [] 653 654 # Fce pro ziskani hodnot z Blade summary, 655 # ktere slouzi jako yLabelArg. 656 # Nepsano jako lambda kvuli fyz. delce kodu funkce. 657 2745.746 MiB 1.207 MiB def getYLabelVals(ind): 658 2745.746 MiB 0.000 MiB retLst = [] 659 2745.746 MiB 0.000 MiB for subLst in folderData[ind]['Data']['Blade summary']: 660 2745.746 MiB 0.000 MiB for item in subLst: 661 2745.746 MiB 0.000 MiB if item[0] == yLabelArg: 662 2745.746 MiB 0.000 MiB retLst.append(float(item[1])) 663 2745.746 MiB 0.000 MiB return retLst 664 665 # Zapisu hodnoty ze vsech volani fce pro jedno nastaveni 666 # do folderDataGroupsFull 667 2745.746 MiB 0.000 MiB folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] \ 668 2745.746 MiB 0.000 MiB .append((folderData[i][xLabelArg], getYLabelVals(i))) 669 670 # Ziskam prumernou spotrebu ze vsech volani fce pro jedno 671 # nastaveni (Prec, Schur) a jeden popisek funkce 672 # (pocet jader...). 673 # 674 # TYTO UDAJE PRIDAM do folderDataGroupsAvg. 675 2745.746 MiB 0.000 MiB folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] \ 676 2745.746 MiB 0.000 MiB .append((folderData[i][xLabelArg], numpy.mean(getYLabelVals(i)))) 677 678 2745.746 MiB 0.000 MiB print('zapidu folderDataGroupsAvg jako zdroj') 679 # Ziskani dat z folderDataGroupsAvg a jejich zapis jako zdroje 680 2746.160 MiB 0.414 MiB for key, vals in sorted(folderDataGroupsAvg.items()): 681 2746.160 MiB 0.000 MiB summarySourcesAvg[key] = {} 682 683 # TODO promyslet, jestli nebude lepsi sloucit summarySourcesAvg a summarySourcesAvgInds 684 # do jednoho slovniku 685 2746.160 MiB 0.000 MiB summarySourcesAvgInds[key] = {} 686 687 2746.160 MiB 0.000 MiB for subKey, val in sorted(vals.items()): 688 # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd. 689 2746.160 MiB 0.000 MiB summarySourcesAvg[key][subKey] = val 690 691 # Zapisu data do zdroju pro vykreslovani grafu 692 2746.160 MiB 0.000 MiB summarySourcesAvgInds[key][subKey] = slideshowCreator.getNumOfDataSources() 693 2746.160 MiB 0.000 MiB slideshowCreator.createAndAddDataSourcesTexCode([sorted(val)], 0, False, 0, 1) 694 695 2746.160 MiB 0.000 MiB print('ziskam data z folderDataGroupsFull') 696 # Ziskani dat z folderDataGroupsFull 697 # 698 # TODO mozna bude potreba i zapis zdroju pro 699 # grafy jednotlivych iteraci 700 2746.160 MiB 0.000 MiB for key, vals in sorted(folderDataGroupsFull.items()): 701 2746.160 MiB 0.000 MiB summarySourcesFull[key] = {} 702 703 2746.160 MiB 0.000 MiB for subKey, val in sorted(vals.items()): 704 # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd. 705 2746.160 MiB 0.000 MiB summarySourcesFull[key][subKey] = val 706 707 2746.160 MiB 0.000 MiB return summarySourcesAvg, sampleSourcesInds, summarySourcesAvgInds, summarySourcesFull
{ "language": "en", "url": "https://stackoverflow.com/questions/38789141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get clean website url with php? I'm using $wsurl as my websites clean url $wsurl = 'http://'. $_SERVER['HTTP_HOST'] . '/'; But recently when I want to echo it from websites admin panel it gave me result: http://localhost/admin/>http://localhost/?page=166 instead of http://localhost/?page=166 More Detailed What i use: <a target="_blank" href="><?=$wsurl?>?page=<?=$new_id?>">Link</a> What i get as html output <a target="_blank" href=">localhost/?page=170">Link</a> But when i click it from admin panel, it opens page localhost/admin>http://localhost/?page=170 (instead of http://localhost/?page=170) which doesn't exist at all How to deal with that problem? I want to get websites main url from everywhere within ws. For ex, if i'm in admin panel http://localhost/admin/index.php the $wsurl will be http://localhost/ If my admin panels url looks like http://mydomain.com/admin/index.php the $wsurl will be http://mydomain.com/ A: If you are facing issues like that then you can try this : $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo 'http://'.parse_url($url, PHP_URL_HOST) . '/';
{ "language": "en", "url": "https://stackoverflow.com/questions/7722104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CreateChooser is not working in Android v5.1 I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this? var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var m_documentMobiNames = shortName + "." + fileType; var mobileFileName = Path.Combine(pathFile, m_documentMobiNames); var shareIntentsLists = new List<Intent>(); Intent sendIntent = new Intent(); sendIntent.SetAction(Intent.ActionSend); sendIntent.SetType("application/pdf"); var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0); if (resInfos.Count > 0) { foreach (var resInfo in resInfos) { string packageName = resInfo.ActivityInfo.PackageName; if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle")) { Intent intent = new Intent(); intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name)); intent.SetAction(Intent.ActionSend); intent.SetType("application/pdf"); intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName)); intent.SetPackage(packageName); shareIntentsLists.Add(intent); } } } if (shareIntentsLists.Count > 0) { chooserIntent = Intent.CreateChooser(new Intent(), "Share with"); chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName)); chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray()); chooserIntent.SetFlags(ActivityFlags.ClearTop); chooserIntent.SetFlags(ActivityFlags.NewTask); context.StartActivity(chooserIntent); await Task.FromResult(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/46870684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Axios delete is ignoring the second argument This is my createAsyncThunk export const removePlayer = createAsyncThunk( 'player/removePlayer', async (playerId: any, thunkAPI) => { try { await axios.delete(URL, playerId) } catch (error) { return thunkAPI.rejectWithValue(error) } } ) And this is the function that dispatches the action <Button variant='outlined' onClick={() => { dispatch(removePlayer(player._id)) }}><DeleteIcon /></Button> I have used createAsyncThunk for other CRUD operations like Read, Create and Update and they all work just fine. Am I using axios.delete wrong? This is what I feel. As you can see, all I want to do is pass in the player ID, then delete it, simple as that. I used very similar logic for axios.put, axios.get and axios.post and they all work fine EDIT I can solve this by adding a id parameter to the route like so router.delete('/:id', deletePlayer) But im just curious if there is another alternative, because with axios post get and put, I can do it without using any params A: But im just curious if there is another alternative Typically DELETE requests do not have a request body though that doesn't mean you cannot use one. From the client side, something like this... axios.delete("/url/for/delete", { data: { playerId } }); will send an application/json request with body {"playerId":"some-id-value"}. On the server side, with Express you would use this router.delete("/url/for/delete", async (req, res, next) => { const { playerId } = req.body; try { // do something with the ID... res.sendStatus(204); } catch (err) { next(err.toJSON()); } }); To handle JSON payloads you should have registered the appropriate middleware app.use(express.json());
{ "language": "en", "url": "https://stackoverflow.com/questions/74024498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a simple way to use OpenSSL BIO objects in Java or are there any alternatives? Could anyone tell me is there any way to use OpenSSL's BIO objects from Java? I'm working on a project, which is intended to provide support for handling of PEAP (https://en.wikipedia.org/wiki/Protected_Extensible_Authentication_Protocol) packets by TinyRadius. I have tried to search any existing PEAP implementations in Java, but, it seems, there is no one. Successfully, I have found an implementation, written in Python, which uses pyOpenSSL to decrypt and encrypt data within PEAP sessions. But the problem is that the code uses several OpenSSL features, which are not provided by javax.net.ssl like reading and writing into BIO objects of a SSL session or getting a master key and secure random, generated by the client from a session. Here is an example of code, which I'm trying to port: def get_keys(self): self.master_key = self.ssl_connection.master_key() self.server_sec_random = self.ssl_connection.server_random() self.client_sec_random = self.ssl_connection.client_random() ... def write(self, data): self.ssl_connection.bio_write(data) ... def read(self): return self.ssl_connection.bio_read(4096) I have studied pyOpenSSL and found that all these calls are just wrappers for OpenSSL library functions through libffi (http://sourceware.org/libffi), but I have no idea of how implement the same functionality in Java. As far as I understand the only way for me is use JNI (or JNA) to call OpenSSL functions. Also, I need to implement the code for managing lifetime of objects, created during OpenSSL access but I do not know how to do that, because I do not have any prior experience with native code from Java. If anyone knows other ways to utilize OpenSSL from Java or maybe some ready-to-use implementations or ports of OpenSSL, please tell me - all answers are highly appreciated. Thanks! A: After numerous searches for ways to utilize OpenSSL from Java I have ended up with JNA wrapper implementation, which, suprisingly, appeared to be pretty simple. Fortunately, OpenSSL is designed in such way that in vast majority of use-cases we do not need to exactly know the type of the value, returned from the call to OpenSSL function (e.g. OpenSSL does not require to call any methods from structures or work with structure fields directly) so there is no need in huge and complex wrappings for OpenSSL's data types. Most of OpenSSL's functions operate with pointers, which may be wrapped into an instance of com.sun.jna.Pointer class, which is equivalent to casting to void* in terms of C, and the callee will determine the correct type and de-reference the given pointer correctly. Here is a small code example of how to load ssleay32.dll, initialize the library and create a context: 1) Define the interface to ssleay32.dll library (functions list may be obtained from OpenSSL GitHub repo or by studying the export section of the dll): import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; public interface OpenSSLLib extends Library { public OpenSSLLib INSTANCE = (OpenSSLLib) Native.loadLibrary("ssleay32", OpenSSLLib.class); // Non-re-enterable! Should be called once per a thread (process). public void SSL_library_init(); public void SSL_load_error_strings(); // Supported context methods. public Pointer TLSv1_method(); ... // Context-related methods. public Pointer SSL_CTX_new(Pointer method); public void SSL_CTX_free(Pointer context); public int SSL_CTX_use_PrivateKey_file(Pointer context, String filePath, int type); public int SSL_CTX_use_certificate_file(Pointer context, String filePath, int type); public int SSL_CTX_check_private_key(Pointer context); public int SSL_CTX_ctrl(Pointer context, int cmd, int larg, Pointer arg); public void SSL_CTX_set_verify(Pointer context, int mode, Pointer verifyCallback); public int SSL_CTX_set_cipher_list(Pointer context, String cipherList); public Pointer SSL_new(Pointer context); public void SSL_free(Pointer ssl); ... } 2) Initialize the library: ... public static OpenSSLLib libSSL; public static LibEayLib libEay; ... static { libSSL = OpenSSLLib.INSTANCE; libEay = LibEayLib.INSTANCE; libSSL.SSL_library_init(); libEay.OPENSSL_add_all_algorithms_conf(); // This function is called from // libeay32.dll via another JNA interface. libSSL.SSL_load_error_strings(); } ... 3) Create and initialize SSL_CTX and SSL objects: public class SSLEndpoint { public Pointer context; // SSL_CTX* public Pointer ssl; // SSL* ... } ... SSLEndpoint endpoint = new SSLEndpoint(); ... // Use one of supported SSL/TLS methods; here is the example for TLSv1 Method endpoint.context = libSSL.SSL_CTX_new(libSSL.TLSv1_method()); if(endpoint.context.equals(Pointer.NULL)) { throw new SSLGeneralException("Failed to create SSL Context!"); } int res = libSSL.SSL_CTX_set_cipher_list(endpoint.context, OpenSSLLib.DEFAULT_CIPHER_LIST); if(res != 1) { throw new SSLGeneralException("Failed to set the default cipher list!"); } libSSL.SSL_CTX_set_verify(endpoint.context, OpenSSLLib.SSL_VERIFY_NONE, Pointer.NULL); // pathToCert is a String object, which defines a path to a cerificate // in PEM format. res = libSSL.SSL_CTX_use_certificate_file(endpoint.context, pathToCert, certKeyTypeToX509Const(certType)); if(res != 1) { throw new SSLGeneralException("Failed to load the cert file " + pathToCert); } // pathToKey is a String object, which defines a path to a priv. key // in PEM format. res = libSSL.SSL_CTX_use_PrivateKey_file(endpoint.context, pathToKey, certKeyTypeToX509Const(keyType)); if(res != 1) { throw new SSLGeneralException("Failed to load the private key file " + pathToKey); } res = libSSL.SSL_CTX_check_private_key(endpoint.context); if(res != 1) { throw new SSLGeneralException("Given key " + pathToKey + " seems to be not valid."); } SSLGeneralException is the custom exception, simply inherited from RuntimeException. ... // Create and init SSL object with given SSL_CTX endpoint.ssl = libSSL.SSL_new(endpoint.context); ... Next steps may be creating of BIO objects and linking them to the SSL object. Regarding to the original question, client/server secure randoms and the master key may be obtained via such methods: public int SSL_get_client_random(Pointer ssl, byte[] out, int outLen); public int SSL_get_server_random(Pointer ssl, byte[] out, int outLen); public int SSL_SESSION_get_master_key(Pointer session, byte[] out, int outLen); Please, note, that JNA will search dlls to load looking into jna.library.path parameter. So, if the dlls are located, for example in directory D:\dlls, you must specify such VM option: -Djna.library.path="D:/dll" Also, JNA requires 32-bit JRE for 32-bit dlls (probably, libffi constraint?). If you try to load a 32-bit dll using 64-bit JRE, you'll get an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/33735188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: downgrade laravel project 5.5 to 5.0.* First of all sorry about my English! I'm in situation where I need to downgrade my Laravel project because some history about php version running on installation server (php 5.4). After I set my composer.json and run update, I get this error   composer update --no-interaction --ansi  C:\composer\composer.bat update --no-interaction --ansi  Loading composer repositories with package information  Updating dependencies (including require-dev)  Package operations: 46 installs, 0 updates, 0 removals   - Installing psy/psysh (v0.4.4): Downloading (connecting...)  Downloading (failed)  Downloading (connecting...)  Downloading (failed)  Downloading (connecting...)  Downloading (failed) Failed to download psy/psysh from dist: The "https://api.github.com/repos/bobthecow/psysh/zipball/489816db71649bd95b416e3ed9062d40528ab0ac" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:  error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version  Failed to enable crypto  failed to open stream: operation failed   Now trying to download from source   - Installing psy/psysh (v0.4.4): Cloning 489816db71 from cache   489816db71649bd95b416e3ed9062d40528ab0ac is gone (history was rewritten?)       [RuntimeException]   Failed to execute git checkout "489816db71649bd95b416e3ed9062d40528ab0ac" -   - && git reset --hard "489816db71649bd95b416e3ed9062d40528ab0ac" --     fatal: reference is not a tree: 489816db71649bd95b416e3ed9062d40528ab0ac      update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [--with-dependencies] [--with-all-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]...    Failed to update packages for ./composer.json. could someone help me to fix this error?!
{ "language": "en", "url": "https://stackoverflow.com/questions/51249680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with ComboBox - DropDownStyles + Disable Text Edit So i've looked at a few stackoverflow posts and nothing seems to be solving my issue. Tried: How to show text in combobox when no item selected? And some others, can't find link now. Application: http://puu.sh/5mQtX.png So for the drop down menu at the bottom, I was trying to make the text display "Select Email Use" but whenever adding the text using the DropDownList in the DropDownStyle menu, the text disappears. But I want to make it so the user cannot just edit the text. Don't have any code exactly for the program right now. From the SOF post I linked above, I tried everything in that post to fix the issue but nothing exactly helps. i am using Visual C# 2010 Windows Form Application A: You can use Text Property of ComboBox Control to show Default Text Try: ComboBox1.Text="Select Email Use"; It will be shown ByDefault A: I think you have to draw the string yourself, here is the working code for you, there is a small issue with the flicker, the string is a little flickering when the mouse is hovered on the combobox, even enabling the DoubleBuffered doesn't help, however it's acceptable I think: public partial class Form1 : Form { public Form1(){ InitializeComponent(); comboBox1.HandleCreated += (s,e) => { new NativeComboBox{StaticText = "Select Email Use"} .AssignHandle(comboBox1.Handle); }; } public class NativeComboBox : NativeWindow { public string StaticText { get; set; } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0xf)//WM_PAINT = 0xf { var combo = Control.FromHandle(Handle) as ComboBox; if (combo != null && combo.SelectedIndex == -1) { using (Graphics g = combo.CreateGraphics()) using (StringFormat sf = new StringFormat { LineAlignment = StringAlignment.Center }) using (Brush brush = new SolidBrush(combo.ForeColor)) { g.DrawString(StaticText, combo.Font, brush, combo.ClientRectangle, sf); } } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/20064795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to integrate Google Play Games Services Realtime Multiplayer into LibGDX for both Android and iOS? I have integrated real-time multiplayer in LibGDX for Android. Now I am wondering how to implement it also for iOS. I have a few questions: Is this possible? Can Android and iOS players play together? What are the possible ways to implement? A: It is possible, of course. Have a look at interfacing. For the iOS app I would use the Multi-OS engine. Use the normal gdx-setup jar file to create moe module.
{ "language": "en", "url": "https://stackoverflow.com/questions/39674885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve the formated URL from open_id form I just added OpenID to my website using the PHP janrain libraries, and I got everything working but I have a question about how to do something. After receiving the openid_url from the user, I pass it to the openid lib, which then processes the url and gets it ready to send to the OP. How can I retrieve that URL? Why I ask is because my script currently sees http://mysite.com and mysite.com as different URLs. I know the library normalizes the URL, I just don't know how to extract it. I hope I made sense, and thank you for helping. A: You get the final URL you want to use for tracking purposes back with a Auth_OpenID_SuccessResponse object, in the claimed_id attribute. (The getDisplayIdentifier() method outputs a version more intended for human consumption, which may or may not be different.)
{ "language": "en", "url": "https://stackoverflow.com/questions/1025160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to fix 'shopify.api_version.VersionNotFoundError' I am building a simple “Hello World” using Python, Flask and the Shopify Embedded SDK. Following this tutorial----> https://medium.com/@dernis/shopify-embedded-sdk-with-python-flask-6af197e88c63. After doing all the work when I go to the link ' https://localhost:5000/shopify/install?shop=khawaja-kaleem-com.myshopify.com ' to install the application to test store it gives me this error. Need to fix it. shopify.api_version.VersionNotFoundError. TRACEBACK (MOST RECENT CALL LAST) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\92344\Downloads\HelloShopify-master\helloshopify\shopify_bp\views.py", line 36, in install session = shopify.Session(shop_url) File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\session.py", line 47, in __init__ self.version = ApiVersion.coerce_to_version(version) File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\api_version.py", line 18, in coerce_to_version raise VersionNotFoundError shopify.api_version.VersionNotFoundError A: You need to specify the API version you wish to use. Set the version before you make any calls. 2020-10 is the default for now. See the documentation, it explains everything to you. https://help.shopify.com/en/api/versioning A: The ShopifyAPI package specifies the allowed versions in the 'shopify/api_version.py' file. In my case the Shopify platform latest API version is '2022-10' but the latest version allowed by the ShopifyAPI package is '2022-07'. It seems that the ShopifyAPI package is not always updated quickly after the release of a new API version on the Shopify platform. Try aligning the API version to one of the versions allowed to work around this error.
{ "language": "en", "url": "https://stackoverflow.com/questions/56520956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can i see the log written by uisng Gauge.writemessage()? Just now i am started switching from testNg to Gauge framework for many reasons, now my question is where i can find the log which was written by using Gauge.writemessage inbuilt method. Or else is there any way to customize the location for the sam.? A: That message will be in the Gauge report under the step it was executed in. I personally look at the html reports, but I would assume it is in the xml option as well. If you want something instantaneous you can write to the console where real time messages are output. This also helps if some sort of bug in the code prevents the reports from being written (like an infinite loop that keeps the report from being written at the end of the full execution). Here is what it would look like. The gray box is the GaugeMessage. A: Gauge.writeMessage api allows you to push messages to the reports at logical points. For example, the step implementation below @Step("Vowels in English language are <vowelString>.") public void setLanguageVowels(String vowelString) { Gauge.writeMessage("Setting vowels to " + vowelString); vowels = new HashSet<>(); for (char ch : vowelString.toCharArray()) { vowels.add(ch); } } yields this html report:
{ "language": "en", "url": "https://stackoverflow.com/questions/54090709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I replace Fragment inside Dialog inside a DialogFragment? I'm trying to use https://github.com/rockerhieu/emojicon library in order to produce an EmojiKeyboard over the softkeyboard just like WhatsApp and Telegram does. After some research, I figure that the way they do is by creating a Dialog over the soft keyboard. The library is a fragment that needs to replace some element of the layout in execution time. The replacement happens int this class: /** * Class responsible for managin user's interaction with the Emoji Keyboard */ public class EmojiKeyboardManager { public static final String TAG = "EmojiKeyboardManager"; private AppCompatActivity mActivity; private FrameLayout mEmojiconContainer; private EmojiconEditText mEditEmojicon; private LinearLayout mEmojiconButton; private ImageView mEmojiconButtonImg; // CONSTRUCTOR public EmojiKeyboardManager(AppCompatActivity activity) { this.mActivity = activity; this.implementEmojiconButton(); this.implementInputTextListener(); //this.initEmojiconFragment(Boolean.FALSE); } // INITIALIZATIONS private void implementEmojiconButton() { this.mEmojiconButtonImg = (ImageView) this.mActivity.findViewById(R.id.emojiButton); this.mEmojiconButton = (LinearLayout) this.mActivity.findViewById(R.id.emojiButtonWrapper); EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.FALSE); this.mEmojiconButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (EmojiKeyboardManager.this.mEmojiconButtonImg.isSelected()) { EmojiKeyboardManager.this.hideEmojiconKeyboard(Boolean.TRUE); } else { EmojiKeyboardManager.this.showEmojiconKeyboard(); } } }); } public void showEmojiconKeyboard() { LayoutUtil.dismissSoftKeyboard(this.mEditEmojicon); EmojiKeyboardManager.this.mEmojiconButtonImg.setImageResource(R.drawable.ic_keyboard_black_36dp); DialogFragment newFragment = SampleDialogFragment.newInstance(); newFragment.show(this.mActivity.getSupportFragmentManager(), "dialog"); //this.mEmojiconContainer.setVisibility(FrameLayout.VISIBLE); EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.TRUE); } public void hideEmojiconKeyboard(Boolean showSoftkeyboard) { EmojiKeyboardManager.this.mEmojiconButtonImg.setImageResource(R.drawable.input_emoji); LayoutUtil.dismissSoftKeyboard(EmojiKeyboardManager.this.mEditEmojicon); //this.mEmojiconContainer.setVisibility(FrameLayout.GONE); EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.FALSE); if (showSoftkeyboard) { EmojiKeyboardManager.this.mEditEmojicon.requestFocus(); LayoutUtil.showSoftKeyboard(EmojiKeyboardManager.this.mEditEmojicon); } } private void implementInputTextListener() { this.mEditEmojicon = (EmojiconEditText) this.mActivity.findViewById(R.id.message); this.mEditEmojicon.clearFocus(); } // GETTERS AND SETTERS public EmojiconEditText getmEditEmojicon() { return this.mEditEmojicon; } public Boolean isEmojikeyboardAttached() { return EmojiKeyboardManager.this.mEmojiconButtonImg.isSelected(); } } In order to achieve what I need I'm using a subclass of DialogFragment that creates a Dialog like that: public class SampleDialogFragment extends DialogFragment { private Dialog dialog; static SampleDialogFragment newInstance() { SampleDialogFragment f = new SampleDialogFragment(); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { this.dialog = new Dialog(this.getActivity(), android.R.style.Theme_NoTitleBar); this.dialog.setContentView(R.layout.rsc_emoji_keyboard); this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL); this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH); this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); this.dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); WindowManager.LayoutParams lp = this.dialog.getWindow().getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = (int) App.context().getResources().getDimension(R.dimen.soft_keyboard_min_height); lp.gravity = Gravity.BOTTOM | Gravity.LEFT; lp.dimAmount = 0; return this.dialog; } } And I display the Dialog like that: DialogFragment newFragment = SampleDialogFragment.newInstance(); .show(this.mActivity.getSupportFragmentManager(), "dialog"); The layout of the Dialog looks like that: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <FrameLayout android:id="@+id/emoji_keyboard" android:layout_width="match_parent" android:layout_height="@dimen/soft_keyboard_min_height"/> </LinearLayout> Where the FrameLayout should be replaced by the Library Fragment. I've tried to use the replace Fragment code after creating the Dialog in the Parent Activity and also overriding the show() method of the DialogFragment but I always get a view not found exception. How can I replace the framelayout in by the library fragment? EDIT: Follow it is the stack trace 02-13 22:47:50.613 25553-25606/br.com.instachat.demo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 02-13 22:47:50.725 25553-25606/br.com.instachat.demo I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (I3193f6e94a) OpenGL ES Shader Compiler Version: E031.28.00.02 Build Date: 10/09/15 Fri Local Branch: mybranch15039904 Remote Branch: quic/LA.BF.1.1.3_rb1.2 Local Patches: NONE Reconstruct Branch: NOTHING 02-13 22:47:50.727 25553-25606/br.com.instachat.demo I/OpenGLRenderer: Initialized EGL, version 1.4 02-13 22:47:50.757 25553-25553/br.com.instachat.demo E/RecyclerView: No adapter attached; skipping layout 02-13 22:47:50.791 25553-25623/br.com.instachat.demo I/RegIntentService: br.com.instachat.demo:string/token_received_successfully 02-13 22:47:50.796 25553-25553/br.com.instachat.demo E/RecyclerView: No adapter attached; skipping layout 02-13 22:47:51.395 25553-25553/br.com.instachat.demo I/RegIntentService: br.com.instachat.demo:string/token_sent_to_app_server_successfully 02-13 22:47:51.410 25553-25553/br.com.instachat.demo I/FragmentContacts: br.com.instachat.demo:string/contact_sync_success 02-13 22:47:53.010 25553-25553/br.com.instachat.demo I/FragmentContacts: br.com.instachat.demo:string/get_chatroomid_success 02-13 22:47:53.011 25553-25553/br.com.instachat.demo I/FragmentContacts: chatroom retrieved (via request) has title: Hall 9000 02-13 22:47:53.066 25553-25553/br.com.instachat.demo I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead. 02-13 22:47:53.440 25553-25606/br.com.instachat.demo D/OpenGLRenderer: endAllActiveAnimators on 0xb82bf2a0 (LinearLayout) with handle 0xb83b6700 02-13 22:47:53.952 25553-25553/br.com.instachat.demo E/FragmentManager: No view found for id 0x7f0d00e3 (br.com.instachat.demo:id/emoji_keyboard) for fragment EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3} 02-13 22:47:53.952 25553-25553/br.com.instachat.demo E/FragmentManager: Activity state: 02-13 22:47:53.953 25553-25553/br.com.instachat.demo D/FragmentManager: Local FragmentActivity a698ff2 State: 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mCreated=truemResumed=true mStopped=false mReallyStopped=false 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mLoadersStarted=true 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: Active Fragments in 6fb086b: 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: #0: SampleDialogFragment{3355fc8 #0 dialog} 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mFragmentId=#0 mContainerId=#0 mTag=dialog 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mState=5 mIndex=0 mWho=android:fragment:0 mBackStackNesting=0 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mAdded=true mRemoving=false mResumed=true mFromLayout=false mInLayout=false 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mHidden=false mDetached=false mMenuVisible=true mHasMenu=false 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mRetainInstance=false mRetaining=false mUserVisibleHint=true 02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager: mFragmentManager=FragmentManager{6fb086b in HostCallbacks{d98e861}} 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: #1: EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3} 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mFragmentId=#7f0d00e3 mContainerId=#7f0d00e3 mTag=null 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mState=0 mIndex=1 mWho=android:fragment:1 mBackStackNesting=0 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mAdded=true mRemoving=false mResumed=false mFromLayout=false mInLayout=false 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mHidden=false mDetached=false mMenuVisible=true mHasMenu=false 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mRetainInstance=false mRetaining=false mUserVisibleHint=true 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mFragmentManager=FragmentManager{6fb086b in HostCallbacks{d98e861}} 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: mArguments=Bundle[{useSystemDefaults=false}] 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: Added Fragments: 02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager: #0: SampleDialogFragment{3355fc8 #0 dialog} 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: #1: EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3} 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: FragmentManager misc state: 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: mContainer=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: mCurState=5 mStateSaved=false mDestroyed=false 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: View Hierarchy: 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: com.android.internal.policy.PhoneWindow$DecorView{f889320 V.ED.... ... 0,0-1080,1920} 02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{5a1ae9e V.E..... ... 0,0-1080,1776} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.view.ViewStub{ceeaf86 G.E..... ... 0,0-0,0 #10203ab android:id/action_mode_bar_stub} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.FrameLayout{3b1ca13 V.E..... ... 0,72-1080,1776} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.FitWindowsLinearLayout{bf70450 V.E..... ... 0,0-1080,1704 #7f0d0080 app:id/action_bar_root} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.ViewStubCompat{2bfc047 G.E..... ... 0,0-0,0 #7f0d0081 app:id/action_mode_bar_stub} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.ContentFrameLayout{15d6649 V.E..... ... 0,0-1080,1704 #1020002 android:id/content} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.RelativeLayout{f64fb4e V.E..... ... 0,0-1080,1704 #7f0d0094 app:id/activity_canvas} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.design.widget.AppBarLayout{ee4f46f V.E..... ... 0,0-1080,168 #7f0d0095 app:id/toolbar_wrapper} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.Toolbar{6d0157c V.E..... ... 0,0-1080,168 #7f0d0096 app:id/toolbar} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.RelativeLayout{c997e5a V.E..... ... 168,0-528,168} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: com.mikhaellopez.circularimageview.CircularImageView{d196b08 V.ED.... ... 0,15-135,152 #7f0d0097 app:id/thumbnail} 02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{576688b V.E..... ... 150,27-360,141} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.AppCompatTextView{dc70d68 V.ED.... ... 0,0-210,65 #7f0d0098 app:id/name} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.AppCompatTextView{a469581 V.ED.... ... 0,65-99,114 #7f0d0099 app:id/status} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.ImageButton{70d1e05 VFED..C. ... 0,0-168,168} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.ActionMenuView{48ca098 V.E..... ... 816,0-1080,168} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.view.menu.ActionMenuItemView{e995357 VFED..CL ... 0,12-144,156 #7f0d00f2 app:id/action_attach_media} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.ActionMenuPresenter$OverflowMenuButton{41af862 VFED..C. ... 144,12-264,156} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.RecyclerView{4612626 VFE..... F.. 0,168-1080,1506 #7f0d009a app:id/messages} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{e610267 V.E..... ... 0,1506-1080,1704 #7f0d009b app:id/bottomLayoutWrapper} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{b39814 V.E..... ... 24,24-1056,174} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{84608bd V.E..... ... 0,0-882,150} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{ba97eb2 V.E...C. ... 1,0-145,150 #7f0d00da app:id/emojiButtonWrapper} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.AppCompatImageView{b715e03 V.ED.... .S. 36,39-108,111 #7f0d00db app:id/emojiButton} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: com.rockerhieu.emojicon.EmojiconEditText{33c2180 VFED..CL ... 145,0-822,150 #7f0d00b7 app:id/message} 02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{bcf73b9 V.E..... ... 822,38-822,111} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager: android.widget.LinearLayout{624b074 VFE..... ... 0,0-0,0} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.AppCompatAutoCompleteTextView{6acd3fe VFED..CL ... 0,0-0,73 #7f0d00ec app:id/autotext} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager: android.support.v7.widget.AppCompatImageButton{4a1d75f VFED..C. ... 882,0-1032,150 #7f0d00dc app:id/send} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager: android.view.View{e881223 V.ED.... ... 0,1776-1080,1920 #1020030 android:id/navigationBarBackground} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager: android.view.View{4ba94d9 V.ED.... ... 0,0-1080,72 #102002f android:id/statusBarBackground} 02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/AndroidRuntime: Shutting down VM 02-13 22:47:53.968 25553-25553/br.com.instachat.demo E/AndroidRuntime: FATAL EXCEPTION: main Process: br.com.instachat.demo, PID: 25553 java.lang.IllegalArgumentException: No view found for id 0x7f0d00e3 (br.com.instachat.demo:id/emoji_keyboard) for fragment EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3} at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1059) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) at android.os.Handler.handleCallback(Handler.java:746) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) SOLVED I was able to manage the issue by using the code below: public class SampleDialogFragment extends DialogFragment { static SampleDialogFragment newInstance() { SampleDialogFragment f = new SampleDialogFragment(); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.rsc_emoji_keyboard, container, false); this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL); this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH); this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); this.getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); WindowManager.LayoutParams lp = this.getDialog().getWindow().getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = (int) App.context().getResources().getDimension(R.dimen.soft_keyboard_min_height); lp.gravity = Gravity.BOTTOM | Gravity.LEFT; lp.dimAmount = 0; getChildFragmentManager() .beginTransaction() .replace(R.id.emoji_keyboard, EmojiconsFragment.newInstance(false)) .commit(); return v; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/35381896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: convert hex to decimal with awk incorrect (with --non-decimal-data or strtonum) awk hex to decimal result is incorrect, not equal with bash/python echo 0x06375FDFAE88312A |awk --non-decimal-data '{printf "%d\n",$1}' or echo 0x06375FDFAE88312A |awk '{printf "%d\n",strtonum($1)}' the result is 447932102257160448, but with python the result is 447932102257160490 python -c "print int('0x06375FDFAE88312A', 16)" A: You need to use --bignum option, as this answer suggests. (Supported in gawk since version 4.1). echo 0x06375FDFAE88312A |awk --bignum '{printf "%d\n",strtonum($1)}' echo 0x06375FDFAE88312A |awk --bignum --non-decimal-data '{printf "%d\n",$1}' The problem is that AWK typically uses double floating point number to represent numbers by default, so there is a limit on how many exact digits can be stored that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/57781308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TSQL getting record count and records in single query I got this tasks table that has TODO items. We are retrieving the todo items and the count of Finished, Pending tasks using separate query in single stored procedure even though it is querying from same table. Here is the query, select TaskName 'Task/TaskName', CASE IsDone WHEN '1' THEN 'True' ELSE 'False' END 'Task/IsDone', ( SELECT COUNT(*) FROM Tasks WHERE IsDone = '1' ) 'CompletedCount' FROM Tasks FOR XML PATH('Tasks') here is the output '<Tasks> <Task> <TaskName>Write a email to Mayor<TaskName> <IsDone>True</IsDone> <CompletedCount>2<CompletedCount> </Task> </Tasks>' CompletedCount is present in each Task which is unnecessary also is there anyway i can query the count too without explicitly writing this SELECT COUNT(*) FROM Tasks WHERE IsDone = '1' How do i get a output as below '<Tasks> <CompletedCount>2<CompletedCount> <Task> <TaskName>Write a email to Mayor<TaskName> <IsDone>True</IsDone> </Task> <Task> <TaskName>Organize Campaign for website<TaskName> <IsDone>False</IsDone> </Task> </Tasks>' A: select ( select count(*) from Tasks where IsDone = 1 for xml path('CompletedCount'), type ), ( select TaskName, case IsDone when 1 then 'True' else 'False' end as IsDone from Tasks for xml path('Task'), type ) for xml path('Tasks') Update: You can do it with a singe select if you first build your task list and then query the XML for the completed count. I doubt this will be any faster than using two select statements. ;with C(Tasks) as ( select TaskName, case IsDone when 1 then 'True' else 'False' end as IsDone from Tasks for xml path('Task'), type ) select C.Tasks.value('count(/Task[IsDone = "True"])', 'int') as CompletedCount, C.Tasks from C for xml path('Tasks') A: You can use type to calculate part of the XML in a subquery: declare @todo table (TaskName varchar(50), IsDone bit) insert @todo values ('Buy milk',1) insert @todo values ('Send thank you note',1) select sum(case when isdone = 1 then 1 end) as 'CompletedCount' , ( select TaskName 'TaskName' , case when isdone = 1 then 'True' else 'False' end 'IsDone' from @todo for xml path('Task'), type ) as 'TaskList' from @todo for xml path('Tasks') This prints: <Tasks> <CompletedCount>2</CompletedCount> <TaskList> <Task> <TaskName>Buy milk</TaskName> <IsDone>True</IsDone> </Task> <Task> <TaskName>Send thank you note</TaskName> <IsDone>True</IsDone> </Task> </TaskList> </Tasks>
{ "language": "en", "url": "https://stackoverflow.com/questions/8784744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HID reports/scan codes for iPhone's/iPad's home button I'm creating a very simple Arduino BT keyboard for iOS using a RN-42-HID Bluetooth module. I've been able to connect to an iPad and send it a few HID reports. So far, I can make the cursor go left, right, up and down, as well as select a certain app. Yay! I do this using the HID raw reports as detailed by Roving Network's HID manual. I've been trying to figure out how to make my iPad go to the home screen, or change the page. When I connect with a regular BT keyboard, with VoiceOver enabled, the BT keyboard combination of "ctrl + alt + H" makes the iPad return to the home page. When I send the corresponding HID raw report, the iPad doesn't return home. const byte HOME1[] = { //equivalent to keyboard ctrl + opt/alt + h 0xFD,0x09,0x01,0x05,0x00,0x0B,0x00,0x00,0x00,0x00,0x00}; It sees the "H", and prints "H" when I have a text field open, but it just doesn't return to the home page. I've also tried sending the modifier keys just as a combination of 3 scan codes at the same time, but that didn't work on the iPad, either. const byte HOME2[] = { //equivalent to keyboard ctrl + opt/alt + h 0xFD,0x09,0x01,0x00,0x00,0xE0,0xE2,0x0B,0x00,0x00,0x00}; Am I sending the report in the right format? Am I sending the right scan codes? Even if you don't have the actual scan code, it would be nice if there was a way to figure out what code activates the home page. Does anyone know how I can find the scan code for the home button (and for page turn, which also involves the alt button)? A: I had a similar issue but with a different combination of keys. I found that i had to split the action into 3 steps: Ctrl+alt+ "letter", then Ctrl+alt, then all buttons released. So just looking at your code, maybe try sending this sequence: 0xFD,0x09,0x01,0x05,0x00,0x0B,0x00,0x00,0x00,0x00,0x00 //ctrl + alt + h 0xFD,0x09,0x01,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //ctrl + alt 0xFD,0x09,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //all released. A: I'm not sure of a raw report, but I did manage it with [0xFD,0x03,0x03,0x01,0x00] (down), and [0xFD,0x03,0x03,0x00,0x00] (up)
{ "language": "en", "url": "https://stackoverflow.com/questions/17621359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use the same object animator property (translationx) twice on one object at the same time I have spent the entire day trying to figure this out. I have tried a plethora of code combinations but none of them want to work. Well technically they do work but not the way I'm wanting it to. If I add translationY property it works. I'm basically wanting run 2 animations, both translationx, on a single object at the same time. The object should go from left to right for the entire width of the screen and be moving back and forth a short distance at the same time. So the main question is, is it possible to achieve this or is it not possible to use the same property with an AnimatorSet at the same time? here is the current code I'm working with: private void _ballLevel20Animation () { move1.cancel(); int center = (board.getMeasuredWidth() / 2); int lr = board.getMeasuredWidth(); final float left = Float.valueOf(100 - center); final float right = Float.valueOf(center - 100); int center1 = (board.getMeasuredWidth() / 6); final float left1 = Float.valueOf(100 - center); final float right1 = Float.valueOf(center - 100); move1.setTarget(ball); move1.setPropertyName("translationX"); move1.setFloatValues(left, right); move1.setRepeatCount(ObjectAnimator.INFINITE); move1.setDuration((int)(ball_duration_increa)); move1.setRepeatMode(ValueAnimator.REVERSE); bounce_ani.setTarget(ball); bounce_ani.setPropertyName("translationX"); bounce_ani.setFloatValues((float)(SketchwareUtil.getDip(getApplicationContext(), (int)(-20))), (float)(SketchwareUtil.getDip(getApplicationContext(), (int)(20)))); bounce_ani.setRepeatCount(ObjectAnimator.INFINITE); bounce_ani.setDuration((int)(ball_duration_increa / 6)); bounce_ani.setRepeatMode(ValueAnimator.REVERSE); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.play(bounce_ani).with(move1); animatorSet.start(); /*bounce_ani.setFloatValues(right1, left1);*/ } A: You could try adding an animation listener to the animation. In the listener, there is onAnimationEnd() which gets called when the animation is done. Here, you may call succeeding animations such that they appear that they are chained. Android Guide on Animation - Animation Listeners
{ "language": "en", "url": "https://stackoverflow.com/questions/54230791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Transitions on tab load - bug I am creating a home screen and I have 3 tabs that you can go between on the home screen. When you click one all the li's within the tab transition in to the page but if you click between the tabs quickly then they don't always load. This only seems to effect Chrome on pc and mac and sometimes safari on mac. Fine on firefox on pc and mac. http://codepen.io/2ne/pen/1f7dbb81f464fb5b0e1a4f5bacc30a56 Tab JS $(document).ready(function() { $('nav li').click(function(){ $('nav li').removeClass('active'); $(this).addClass('active'); $('.tab').removeClass('active'); $('#' + $(this).attr('data-tab')).addClass('active'); }); }); Portion of css .tab-content .tab li { opacity: 0; transform: translatey(-50px) scale(0); } .tab-content .tab.active li { transition: all 500ms ease; transform-origin: top center; transform: translatey(0) scale(1); opacity: 1; } @for $i from 1 through 50 { .tab-content .tab.active li:nth-child(#{$i}) { transition-delay: (#{$i * 0.1}s); } } A: You need to add vendor specific values for transform and transition properties. Below is the modified CSS: $headerColour: #456878; $headerHeight: 58px; $headerLineHeight: $headerHeight - 2px; @import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900); .cf:after { clear: both; content: " "; display: table; } body { background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/12596/bg.png"); background-attachment: fixed; -ms-background-size: contain; background-size: contain; color: #fff; font-family: "Lato"; font-size: 18px; font-weight: 300; overflow-y: scroll; } header { background: $headerColour; height: $headerHeight; position: relative; } header li { position: absolute; top: 0; line-height: $headerLineHeight; } header li.logo { left: 20px; } header li.user { right: 20px; } .wrapper { position: absolute; top: 120px; left: 0; right: 0; margin: auto; width: 80%; } nav { margin-bottom: 50px; margin-left: 20px; } nav li { color: rgba(255, 255, 255, 0.75); cursor: pointer; float: left; font-size: 20px; margin-right: 60px; -webkit-transition: color 500ms ease 0s; -moz-transition: color 500ms ease 0s; -ms-transition: color 500ms ease 0s; -o-transition: color 500ms ease 0s; transition: color 500ms ease 0s; width: 100px; } nav li:not(.active):hover, nav li.active { color: rgba(255, 255, 255, 1); } nav li.active { font-size: 22px; font-weight: 400; } .tab-content .tab { position: absolute; margin-bottom: 100px; visibility: hidden; } .tab-content .tab.active { visibility: visible; } .tab-content .tab > ul { margin-bottom: 100px; } .tab-content .tab li { background: #fff; height: 200px; width: 200px; float: left; background: #fff; margin: 20px; -ms-border-radius: 30px; border-radius: 30px; -ms-opacity: 0; opacity: 0; -webkit-transform: translatey(-50px) scale(0); -moz-transform: translatey(-50px) scale(0); -ms-transform: translatey(-50px) scale(0); -o-transform: translatey(-50px) scale(0); transform: translatey(-50px) scale(0); } .tab-content .tab.active li { -webkit-transition: all 500ms ease; -moz-transition: all 500ms ease; -ms-transition: all 500ms ease; -o-transition: all 500ms ease; transition: all 500ms ease; -webkit-transform-origin: top center; -moz-transform-origin: top center; -ms-transform-origin: top center; -o-transform-origin: top center; transform-origin: top center; -webkit-transform: translatey(0) scale(1); -moz-transform: translatey(0) scale(1); -ms-transform: translatey(0) scale(1); -o-transform: translatey(0) scale(1); transform: translatey(0) scale(1); -ms-opacity: 1; opacity: 1; } @for $i from 1 through 50 { .tab-content .tab.active li:nth-child(#{$i}) { transition-delay: (#{$i * 0.1}s); } } Code Pen: http://codepen.io/anon/pen/gIDsv
{ "language": "en", "url": "https://stackoverflow.com/questions/21768920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flutter & Firestore - problem about "startAfter" pagination I am able to use "startAfter" and "limit" to do pagination but it have bug. For example, in Firestore DB I have 7 records: {"title": "item1", "create_datetime": "2018-11-11 11:11:11"} {"title": "item2", "create_datetime": "2018-11-11 11:11:11"} {"title": "item3", "create_datetime": "2018-11-11 11:11:11"} {"title": "item4", "create_datetime": "2018-11-11 11:11:11"} {"title": "item5", "create_datetime": "2018-11-11 11:11:11"} {"title": "item6", "create_datetime": "2018-11-11 11:11:11"} {"title": "item7", "create_datetime": "2018-12-22 22:22:22"} When the page size is 5, first page is ok because I used: .orderBy('create_datetime').limit(5) It gives me item 1-5. When it load second page, I used: .orderBy('create_datetime').startAfter(['2018-11-11 11:11:11']).limit(5) The problem is that the second page result had item7 only, item6 was disappeared. "startAt" have the same problem too. I really hope it has "offset" function. Does anyone have solution? A: Your query will always return 'item7' because you always starting after 2018-11-11 11:11:11 so it will ignore all the other items and go to the last 2018-11-11 11:11:11 and skip from there. You need to get the last item returned and keep a reference to it, then on your startAfter use the document reference to start after. Usually, flutter's startAfter requires a list to keep a reference to it. Look at Firebase query cursors A: Currently flutter don't support startAfter(lastDocFetched) or startAt(anyDoc). This is required as you said it starts with the string matching values, not at a particular document.
{ "language": "en", "url": "https://stackoverflow.com/questions/53491952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: query nutch 2 table result from cassandra 2 dose not look right I am using Nutch 2.2.1 and Cassandra 2 to craw pages. for a test i just inject one url to Cassandra and explore the database. Using CQL i can query the table in the webpage keyspace cqlsh:simplex> select * from webpage.f; key | column1 | value --------------------------------------+---------+-------------------- 0x6564752e6373752e7777773a687474702f | 0x6669 | 0x00278d00 0x6564752e6373752e7777773a687474702f | 0x73 | 0x3f800000 0x6564752e6373752e7777773a687474702f | 0x7473 | 0x00000145a266703e which is fine if i convert those hex bytes to string. the key will be the reverted url. then i write java code to read the table f using datastax java driver 2 (http://www.datastax.com/documentation/developer/java-driver/2.0/java-driver/whatsNew2.html) i followed the sample code Cluster cluster = Cluster.builder().addContactPoint("10.20.104.181").build(); Session session = cluster.connect(); ResultSet results = session.execute("SELECT * FROM webpage.f"); for (Row row : results) { System.out.println("Key"); System.out.println(toStrFromByteBuffer(row.getBytes("key"))); System.out.println("column1"); System.out.println(toStrFromByteBuffer(row.getBytes("column1"))); System.out.println("value"); System.out.println(toStrFromByteBuffer(row.getBytes("value"))); } cluster.close(); public static String toStrFromByteBuffer(ByteBuffer buffer) { byte[] ar=buffer.array(); System.out.println(ar.length); return new String(ar,Charset.forName("UTF-8")); } the result is below. You can see row.getBytes("key") returns a whole row data not a specific column value. Could some master help on this? A: Nutch stores its data in the f column family as BytesType. The column names are stored as UTF8Type. If you want to get the data as a String you have to convert it first. A row is completely stored in the ByteBuffer. In your example you convert the whole byte buffer to String what gives you the whole row. When you select one row, you get the current position an limit of that row. So you have to read from begin:buffer current pointer position to buffer limit. For example to get the websites content in the "cnt" field: // This is the byte buffer you get from selecting column "cnt" ByteBuffer buffer; int length = buffer.limit() - buffer.position(); byte[] cellValue = new byte[length]; buffer.get(cellValue, 0, length); return new String(cellValue, Charset.forName("UTF-8"));
{ "language": "en", "url": "https://stackoverflow.com/questions/23327152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need help on choosing locks for thread synchronization I have several modifying threads and some reading threads, which all access the global variable X. I want to make my synchronization policy like this: When a thread try to modify X, it will require a lock first, and several modifying threads can have several locks required. When a thread try to read X, it must wait until all the modifying threads drop their locks. Is there any solution to this situation in linux pthread library? Many thanks A: You are looking for a read/write lock (or reader-writer lock). I believe there is one in pthreads (pthread_rwlock_*).
{ "language": "en", "url": "https://stackoverflow.com/questions/976310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing a class method from within an Active Record scope? I am having issues with the scope in this model and I'm at a loss at how best to fix it. I would like to call the distinct_mechanics_sql from within the scope to keep things cleaner, but when I run this I get an "undefined local variable or method" error. Here is the model: class Mechanics < ActiveRecord::Base scope :with_moz, -> { joins("JOIN (#{distinct_mechanics_sql}) mh ON mh.mechanic_id = mechanics.id") } def distinct_mechanics_sql """ SELECT DISTINCT ON (mechanic_id) * FROM checkups ORDER BY mechanic_id, updated_at DESC """ end end Any help would be greatly appreciated! A: Scopes are same as class methods, so within the scope you are implicitly call another class methods. And your distinct_mechanics_sql is an instance method, to use it inside a scope declare it as: def self.distinct_mechanics_sql or def Mechanics.distinct_mechanics_sql or class << self def distinct_mechanics_sql ... end end
{ "language": "en", "url": "https://stackoverflow.com/questions/27259171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to correctly send a matplotlib.figure.Figure to a private telegram channel on Python3 via Telegram API? Say I have the following df called df_trading_pair_date_time_index which contains the following data: Open High Low Close End Date Start Date 2022-08-12 00:25:00 23834.13 23909.27 23830.00 23877.62 2022-08-12 00:29:59.999 2022-08-12 00:30:00 23877.62 23968.52 23877.62 23936.89 2022-08-12 00:34:59.999 2022-08-12 00:35:00 23936.89 23989.95 23915.92 23962.50 2022-08-12 00:39:59.999 2022-08-12 00:40:00 23960.64 23985.03 23935.60 23966.71 2022-08-12 00:44:59.999 2022-08-12 00:45:00 23966.71 23996.94 23958.00 23983.68 2022-08-12 00:49:59.999 2022-08-12 00:50:00 23982.53 24009.67 23958.89 23996.59 2022-08-12 00:54:59.999 2022-08-12 00:55:00 23995.49 24005.30 23963.92 23964.37 2022-08-12 00:59:59.999 2022-08-12 01:00:00 23965.31 24000.00 23940.61 23975.64 2022-08-12 01:04:59.999 2022-08-12 01:05:00 23977.04 23996.85 23928.95 23943.09 2022-08-12 01:09:59.999 2022-08-12 01:10:00 23944.05 23972.86 23885.00 23905.23 2022-08-12 01:14:59.999 2022-08-12 01:15:00 23905.23 23944.66 23901.74 23925.72 2022-08-12 01:19:59.999 2022-08-12 01:20:00 23925.72 23951.21 23917.84 23945.03 2022-08-12 01:24:59.999 2022-08-12 01:25:00 23945.03 23961.78 23935.12 23945.60 2022-08-12 01:29:59.999 2022-08-12 01:30:00 23945.60 23949.86 23919.90 23934.50 2022-08-12 01:34:59.999 2022-08-12 01:35:00 23934.49 23934.50 23853.65 23895.44 2022-08-12 01:39:59.999 2022-08-12 01:40:00 23895.44 23932.11 23894.67 23906.00 2022-08-12 01:44:59.999 2022-08-12 01:45:00 23905.42 23927.26 23878.57 23902.75 2022-08-12 01:49:59.999 2022-08-12 01:50:00 23902.76 23915.00 23888.08 23889.19 2022-08-12 01:54:59.999 When running df_trading_pair_date_time_index.dtypes the following output is presented: Open float64 High float64 Low float64 Close float64 End Date datetime64[ns] dtype: object And when running df_trading_pair_date_time_index.index the following output is returned: DatetimeIndex(['2022-08-12 00:25:00', '2022-08-12 00:30:00', '2022-08-12 00:35:00', '2022-08-12 00:40:00', '2022-08-12 00:45:00', '2022-08-12 00:50:00', '2022-08-12 00:55:00', '2022-08-12 01:00:00', '2022-08-12 01:05:00', '2022-08-12 01:10:00', '2022-08-12 01:15:00', '2022-08-12 01:20:00', '2022-08-12 01:25:00', '2022-08-12 01:30:00', '2022-08-12 01:35:00', '2022-08-12 01:40:00', '2022-08-12 01:45:00', '2022-08-12 01:50:00'], dtype='datetime64[ns]', name='Start Date', freq=None) In order to plot the data above, I used the following code: import requests import mplfinance as mpf import matplotlib.pyplot as plt import pandas as pd # Plotting # Create my own `marketcolors` style: mc = mpf.make_marketcolors(up='#2fc71e',down='#ed2f1a',inherit=True) # Create my own `MatPlotFinance` style: s = mpf.make_mpf_style(base_mpl_style=['bmh', 'dark_background'],marketcolors=mc, y_on_right=True) # Plot it btc_plot, axlist = mpf.plot(df_trading_pair_date_time_index, figratio=(10, 6), type="candle", style=s, tight_layout=True, datetime_format = '%H:%M', ylabel = "Precio ($)", returnfig=True) # Add Title axlist[0].set_title("BTC/USDT - 5m", fontsize=25, style='italic', fontfamily='fantasy' ) After running btc_plot in the console, the following chart is returned: And finally when running type(btc_plot) the following output is returned: matplotlib.figure.Figure The problem: I am having a hard time dealing with a "simple" thing, I want to send such plotted trading chart to a private telegram channel through the Telegram API with Python3, so according to this section of the Telegram API Documentation, the following line should work: requests.post(f'https://api.telegram.org/bot{bot_str}/sendPhoto', data = {'chat_id':f'-100{channel_id_str}', 'photo': btc_plot, 'caption':'Fue detectada una señal bajista en el par BTC/USDT!'}) However, after running that statement, all I got was a <Response [400]> without any explanation nor exception from the console. So, I do think that it may be happening because I'm trying to send a matplotlib.figure.Figure object, but I mistakenly thought that btc_plot had stored a png object just because an image was returned after running btc_plot in the console, so I am lost. Ironically, the following sentence works as expected with a <Response [200]> as output: requests.post(f'https://api.telegram.org/bot{bot_str}/sendMessage', data = {'chat_id':f'-100{channel_id_str}', 'text': 'Fue detectada una señal bajista en el par BTC/USDT!'}) May I get here some alternative solution or an improvement to my current one? A: Found an alternative, which I think it actually always was the right way to do it. import telegram btc_plot.savefig('signal.png',dpi=300, bbox_inches = "tight") telegram.Bot(token= token_str).send_photo(chat_id= chat_id_str, photo=open("signal.png", 'rb'), caption="Fue detectada una señal bajista en el par BTC/USDT!") Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/73331428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: question about SQLAlchemy's choice of join targets I'm going through the SQLAlchemy ORM tutorial (https://docs.sqlalchemy.org/en/latest/orm/tutorial.html#querying-with-joins) and there's a part that confused me more than it helped me: What does Query select from if there’s multiple entities? The Query.join() method will typically join from the leftmost item in the list of entities, when the ON clause is omitted, or if the ON clause is a plain SQL expression. To control the first entity in the list of JOINs, use the Query.select_from() method: query = session.query(User, Address).select_from(Address).join(User) Is the "list of entities" the list within query()? More to the point, when would the ON clause not be omitted? By ON clause does it mean a relationship like User.addresses (previously defined for example as User.addresses = relationship(Address)) used like join(User.addresses)? Is that the type of "ON clause" that would prevent us from needing select_from() since the join() parameter itself would contain the necessary information for determining which table we intend to join with? Surely there must be some way to specify join targets without having them always defaulting to the first table in query() since otherwise it wouldn't be possible to build certain complex queries. A: Let's start from the beginning. When you pass items to query(), it will build a SELECT statement from these items. If they are models, then it will enumerate all the fields of such models. The query will automatically add the tables to select FROM. Unless you tell it to, the query will not perform joins automatically, so you must add assume what tables to look up your values from. Additional clauses like join() tell the query how the JOIN operation should be performed. Additional arguments to join() will be used as the ON clause, otherwise the query will infer the clause based on mapper-defined relationships. So to summarize, the ON clause is omitted whenever you do not specify additional arguments to join(). In the following expression, the ON clause is omitted: query(User, Address).join(Address) This does not mean that the SQL emitted will not have an ON clause; it will do the right thing by inferring the proper ON clause using the relationships defined on the model. When there are multiple possibilities, you need to specify the clause yourself: query(Person).join(Person.parent1).join(Person.parent2) should result in a query that returns a person and both of their parents. In this case, the ON clause was not omitted.
{ "language": "en", "url": "https://stackoverflow.com/questions/55679506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using SVG, hover on X, Y or Z to make X and Z rotate I have an element (logo) on my webpage which contains three other elements, I want to make it so when the logo as a whole is hovered, two of the elements within the logo (two of the letters) will rotate around their centre indefinitely. I have achieved rotating elements with CSS animations, but only to get an element to rotate when itself is hovered. I cannot figure out how to get multiple elements to rotate when any of the three elements are hovered using CSS. I have the three elements in their own svg tags as data URI, all within a single g, which itself is in an a href that links to the home page. <header><a id="logoLink" href=""> <g class="logoSvg"> <svg id="c" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 34.68 37.2"><defs><style>.cls-1{fill:#e94a4a;}</style></defs><title>logo</title><path class="cls-1" d="... </svg> <svg id="hri" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 76.88 79.53"><defs><style>.cls-1{fill:#e94a4a;}</style></defs><title>logo copy</title><path class="cls-1" d="M </svg> <svg id="s" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 31.19 37.2"><defs><style>.cls-1{fill:#e94a4a;}</style></defs><title>logo copy 2</title><path class="cls-1" d="M </svg> </g> </a> In the html doc I also have a script source with SnapSVG content, as well as linking to the SnapSVG source code: <script src="js/logoAni.js"></script> The SnapSVG js is as follows: var logo = $("#logoSvg"); var c = $("#c"); var hri = $("#hri"); var s = $("#s"); function rollover(){ c.transform('r0,100,100'); c.animate({transform: "r360,100,100"},1000,mina.linear,anim); s.transform('r0,100,100'); s.animate({transform: "r360,100,100"},1000,mina.linear,anim); } logo.hover(rollover); I'm assuming that the snap code is wrong. Perhaps I don't need to use snap at all? Update: Here's a recent jfiddle https://jsfiddle.net/Lc12bvyn/ A: You could use @keyframes animation and nested styles in SCSS to achieve something like this without javascript. Not sure if you're wanting to go this route, but it seems the most straightforward to me. Particularly you're looking to set the animation-iteration-count to infinite on the elements that you want to rotate. The below code is just some rough concept stuff, not sure the animation you're looking to set, or the full context of your elements, etc. .logoSvg { &:hover { &:first-child { animation-name: someAnimation; animation-iteration-count: infinite; } &:last-child { animation-name: someAnimation; animation-iteration-count: infinite; } } } @keyframes someAnimation { 0%: {transform: some transformation}; 100%: {transform: some transformation}; } I hope this is helpful Chris, or at least gets you going in the right direction. A: The rollover code itself looks ok (assuming missing code is, if you still get stuck I would put up a jsfiddle or jsbin), it's just applying to the wrong type of elements. I'm guessing you are using jquery for the selections? If so, I'm not sure that will work..rather than doing.. var logo = $("#logoSvg"); try var logo = Snap("#logoSvg"); That way you will get the Snap element (which links to the DOM element) to operate on, not a DOM or jquery object. You can't transform the 'svg' element itself typically (as it doesn't technically support the transform attribute as far as I'm aware). So, I would put the two svgs you want to transform inside a g/group element and transform that g element. You could look into css, but css transforms on svg don't always play nice regarding browser support, so whilst Davids answer may be good for normal elements, I'm not sure it would play nice for svg elements (especially rotations), do test different browsers very early if you do try that method.
{ "language": "en", "url": "https://stackoverflow.com/questions/38726512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: json post request size limit (now a verified php-mysqli bug) I'm sending a request to my PHP application through a JSON-encoded ajax request (form process). A post-request with character length of 4174 is successfully processed and the result is received correctly. Adding one additional character to the request causes my application to loop infinitely until Apache2 seg-faults. There are only 2 fields, one for a 3-digit id, and the rest is text from a text area. I'm using the Zend Framework to drive my application, Apache2.2.3, PHP 5.2.8, JSON plugin version 1.2.1, MySQL 5.0.77 Anyone have any ideas... here is another update:: tracked this issue to NOT a json request problem, but an issue with the query i am running. I'm performing an INSERT ON DUPLICATE KEY UPDATE query that inflates the text size of the query. I can run this query find from the command line, however from PHP it's failing. Currently investigating the issue. Anyone interested could see the query here.. ** this is a bug with the mysqli plugins for php, for some reason the db handler doesn't like this code. If/when I have time to properly test, you'll see my results.** INSERT INTO element_attribute_values (ElementAttributeId,ElementId,value) VALUES (1,'553','444st text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this itext this itext this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test tex this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is sotext this ime test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test tex tesxthis is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is fsome test texttext this i this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is sometext this i test text this is some test text this is some test text this is sothis is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text thisf iffffffff4444') ON DUPLICATE KEY UPDATE value='444st text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this itext this itext this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test tex this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is sotext this ime test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test tex tesxthis is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is fsome test texttext this i this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is sometext this i test text this is some test text this is some test text this is sothis is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text this is some test text thisf iffffffff4444' A: I don't know if this is related or not but I was using jQuery recently using the $.ajax() method to submit POST data from a text field to a php script. The php script would then parse the data (XML) for the bits of information that I needed. I noticed an error on my firephp output that it was unable to parse the XML from the POSTed form. I then had it output the strlen() and the data and noticed it was cutting it from around 7k bytes down to 268 (or 256 or something I forget the exact amount). This made it an incomplete and not valid XML pile of data. I fixed this by using the $.post() method instead. Worked perfectly. A: You could simply check the length of your string, and if it's over the limit, split it up. Run the first portion in the insert, then do a += update on the field with the second portion. It's a bit crude, but it gets around the bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/612657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: nodejs proxy local api calls to external rest api service (no express.js) I'm running the demo app of angularjs (angular-seed) using nodejs with the default project file /scripts/web-server.js (see below) I would like node js to proxy/redirect all the local calls to /api to the external Rest api endpoint http://www.mywebsite.com/api in order to avoid the cross domain origin policy. How should I edit the web-server.js below to achieve the proxy redirect? All the example I found do use express.js. I'm using node.js only as development environment so I've no interest in using express.js. Default web-server.js nodejs script: #!/usr/bin/env node var util = require('util'), http = require('http'), fs = require('fs'), url = require('url'), events = require('events'), request = require('request'); ; var DEFAULT_PORT = 8000; function main(argv) { new HttpServer({ 'GET': createServlet(StaticServlet), 'HEAD': createServlet(StaticServlet) }).start(Number(argv[2]) || DEFAULT_PORT); } function escapeHtml(value) { return value.toString(). replace('', '>'). replace('"', '"'); } function createServlet(Class) { var servlet = new Class(); return servlet.handleRequest.bind(servlet); } /** * An Http server implementation that uses a map of methods to decide * action routing. * * @param {Object} Map of method => Handler function */ function HttpServer(handlers) { this.handlers = handlers; this.server = http.createServer(this.handleRequest_.bind(this)); } HttpServer.prototype.start = function(port) { this.port = port; this.server.listen(port); util.puts('Http Server running at http://localhost:' + port + '/'); }; HttpServer.prototype.parseUrl_ = function(urlString) { var parsed = url.parse(urlString); parsed.pathname = url.resolve('/', parsed.pathname); return url.parse(url.format(parsed), true); }; HttpServer.prototype.handleRequest_ = function(req, res) { var logEntry = req.method + ' ' + req.url; if (req.headers['user-agent']) { logEntry += ' ' + req.headers['user-agent']; } util.puts(logEntry); req.url = this.parseUrl_(req.url); var handler = this.handlers[req.method]; if (!handler) { res.writeHead(501); res.end(); } else { handler.call(this, req, res); } }; /** * Handles static content. */ function StaticServlet() {} StaticServlet.MimeMap = { 'txt': 'text/plain', 'html': 'text/html', 'css': 'text/css', 'xml': 'application/xml', 'json': 'application/json', 'js': 'application/javascript', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif', 'png': 'image/png',   'svg': 'image/svg+xml' }; StaticServlet.prototype.handleRequest = function(req, res) { var self = this; var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){ return String.fromCharCode(parseInt(hex, 16)); }); var parts = path.split('/'); if (parts[parts.length-1].charAt(0) === '.') return self.sendForbidden_(req, res, path); fs.stat(path, function(err, stat) { if (err) return self.sendMissing_(req, res, path); if (stat.isDirectory()) return self.sendDirectory_(req, res, path); return self.sendFile_(req, res, path); }); } StaticServlet.prototype.sendError_ = function(req, res, error) { res.writeHead(500, { 'Content-Type': 'text/html' }); res.write('\n'); res.write('Internal Server Error\n'); res.write('Internal Server Error'); res.write('' + escapeHtml(util.inspect(error)) + ''); util.puts('500 Internal Server Error'); util.puts(util.inspect(error)); }; StaticServlet.prototype.sendMissing_ = function(req, res, path) { path = path.substring(1); res.writeHead(404, { 'Content-Type': 'text/html' }); res.write('\n'); res.write('404 Not Found\n'); res.write('Not Found'); res.write( 'The requested URL ' + escapeHtml(path) + ' was not found on this server.' ); res.end(); util.puts('404 Not Found: ' + path); }; StaticServlet.prototype.sendForbidden_ = function(req, res, path) { path = path.substring(1); res.writeHead(403, { 'Content-Type': 'text/html' }); res.write('\n'); res.write('403 Forbidden\n'); res.write('Forbidden'); res.write( 'You do not have permission to access ' + escapeHtml(path) + ' on this server.' ); res.end(); util.puts('403 Forbidden: ' + path); }; StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) { res.writeHead(301, { 'Content-Type': 'text/html', 'Location': redirectUrl }); res.write('\n'); res.write('301 Moved Permanently\n'); res.write('Moved Permanently'); res.write( 'The document has moved here.' ); res.end(); util.puts('301 Moved Permanently: ' + redirectUrl); }; StaticServlet.prototype.sendFile_ = function(req, res, path) { var self = this; var file = fs.createReadStream(path); res.writeHead(200, { 'Content-Type': StaticServlet. MimeMap[path.split('.').pop()] || 'text/plain' }); if (req.method === 'HEAD') { res.end(); } else { file.on('data', res.write.bind(res)); file.on('close', function() { res.end(); }); file.on('error', function(error) { self.sendError_(req, res, error); }); } }; StaticServlet.prototype.sendDirectory_ = function(req, res, path) { var self = this; if (path.match(/[^\/]$/)) { req.url.pathname += '/'; var redirectUrl = url.format(url.parse(url.format(req.url))); return self.sendRedirect_(req, res, redirectUrl); } fs.readdir(path, function(err, files) { if (err) return self.sendError_(req, res, error); if (!files.length) return self.writeDirectoryIndex_(req, res, path, []); var remaining = files.length; files.forEach(function(fileName, index) { fs.stat(path + '/' + fileName, function(err, stat) { if (err) return self.sendError_(req, res, err); if (stat.isDirectory()) { files[index] = fileName + '/'; } if (!(--remaining)) return self.writeDirectoryIndex_(req, res, path, files); }); }); }); }; StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) { path = path.substring(1); res.writeHead(200, { 'Content-Type': 'text/html' }); if (req.method === 'HEAD') { res.end(); return; } res.write('\n'); res.write('' + escapeHtml(path) + '\n'); res.write('\n'); res.write(' ol { list-style-type: none; font-size: 1.2em; }\n'); res.write('\n'); res.write('Directory: ' + escapeHtml(path) + ''); res.write(' *'); files.forEach(function(fileName) { if (fileName.charAt(0) !== '.') { res.write(' *' + escapeHtml(fileName) + ''); } }); res.write(''); res.end(); }; // Must be last, main(process.argv);
{ "language": "en", "url": "https://stackoverflow.com/questions/20635799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling I am trying to remove an item from listview which is not starting a specific text "Dev". But the application is crashing when I remove an item and refresh the recycler list via notifydatasetChanged(). This question has been already asked and I have seen all the solutions but I can't find a proper solution to this. EvelistAdapter.java public class EvelistAdater extends RecyclerView.Adapter<EvelistAdater.ViewHolder> { Context cxt; ArrayList<Dbbean> adapterlist; int row_index; public EvelistAdater(Context cxt, ArrayList<Dbbean> list) { adapterlist=list; this.cxt=cxt; Log.d("LIst count",""+adapterlist.size()); } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.scanlistadp, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { if(adapterlist.get(position).blename.startsWith("Dev")) { holder.tv_country.setText(adapterlist.get(position).blename); }else{ removeAt(position); } } @Override public int getItemCount() { return adapterlist.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ TextView tv_country; RelativeLayout layout; ImageView setting; public ViewHolder(View view) { super(view); tv_country = (TextView)view.findViewById(R.id.tshirtname); setting = (ImageView) view.findViewById(R.id.setting); layout = (RelativeLayout)view.findViewById(R.id.layout); } } public void removeAt(int position) { adapterlist.remove(position); notifyDataSetChanged(); } } LOGCAT E/UncaughtException: java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:2586) at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onItemRangeChanged(RecyclerView.java:4951) at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyItemRangeChanged(RecyclerView.java:11371) at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyItemRangeChanged(RecyclerView.java:11362) at android.support.v7.widget.RecyclerView$Adapter.notifyItemChanged(RecyclerView.java:6650) at com.scanner.com.eve.EvelistAdater.removeAt(EvelistAdater.java:94) at com.scanner.com.eve.EvelistAdater.onBindViewHolder(EvelistAdater.java:44) at com.scanner.com.eve.EvelistAdater.onBindViewHolder(EvelistAdater.java:19) at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6354) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6387) at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5343) at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5606) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5448) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5444) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3600) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3329) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3867) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) at android.widget.LinearLayout.onLayout(LinearLayout.java:1495) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) at android.widget.LinearLayout.onLayout(LinearLayout.java:1495) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:636) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586) at android.widget.LinearLayout.onLayout(LinearLayout.java:1495) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336) at android.widget.FrameLayout.onLayout(FrameLayout.java:273) at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2895) at android.view.View.layout(View.java:16655) at android.view.ViewGroup.layout(ViewGroup.java:5438) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107) at android.view.ViewR A: Filter the data in list before passing to Adapter ArrayList<Dbbean> list = yourlist; Create a filtered list ArrayList<Dbbean> filteredList = new ArrayList<>(); for(Dbbean dbean : list){ if(dbean.blename.startsWith("Dev") filteredList.add(dbean); } Pass filtered list to Adapter EvelistAdapter adapter = new EvelistAdaptr(this,filteredList); yourRecyclerView.setAdapter(adapter); A: Do not call removeItem inside onBindViewHolder directly. If you want to remove item then just do it before setting adapter. Provide the filtered ArrayList<Dbbean> list to adpater in first place .Later you can remove item from adapter on any specified action. Do not use notifyDataSetChanged() until you are not sure which dataset is changed. Use : notifyItemRemoved() for a particular item removed for position . A: this is causing the problem you are just forcefully making changes to the onBindViewHolder which is drawing something right now again to redraw. @Override public void onBindViewHolder(ViewHolder holder, final int position) { if(adapterlist.get(position).blename.startsWith("Dev")) { holder.tv_country.setText(adapterlist.get(position).blename); }else{ removeAt(position); } } public void removeAt(int position) { adapterlist.remove(position); notifyDataSetChanged(); } suggestion better check this condition and remove the items when you are about to notify the adapter from fragment or activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/48162513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }