text
stringlengths
15
59.8k
meta
dict
Q: Foreach loop vs if/elseif in nested hashtable using Powershell My goal is to create a PowerShell script that monitors host hardware health and alerts (via exit codes) if a component status is not "GREEN". The following information is pulled from the software API as a hashtable by default. For readability purposes, this is the information in JSON format, which I converted using the convertto-json cmdlet: "host": { "serial_number": "55555", "status": "GREEN", "name": "hostname", "raid_card": { "serial_number": "55555", "status": "GREEN", "product_name": "PRODUCT", }, "battery": { "percent_charged": 100, "health": "HEALTHY", "status": "GREEN" }, "accelerator": { "temperature": 36, "status": "GREEN" }, "logical_drives": [ "@{serial_number=55555555555; health=HEALTHY}", "@{serial_number=55555555556; health=HEALTHY}" ] } } If any of the components (battery, raid_card, accelerator or logical_drives) is not green, then the top host.status value would change to "RED." The logic I envision is to do an initial if statement in which if host.value is "GREEN" then exit 0 (meaning it is up) and just output a message. Else, do a foreach loop to search and identify which component is not "GREEN." This is where I am stuck with the logic. The first problem I have is not knowing if a foreach loop is most appropriate for this problem. If it is, how could you structure the foreach loop since one of the components, logical drives, has a nested hashtable inside. The second problem I have is how could you retrieve the component name if the status is not "GREEN"? I didn't get far but this is the structure I was initially going with: if (host.value -eq "GREEN"){ Write-Host "Message: host hardware is healthy" Exit 0; } else{ foreach ($components in $response.host){ if ($_.status -ne "GREEN){ Write-Host "Message: host.??? is not healthy" Exit 1; } } One alternative structure is to just do if/elseif statements instead of the foreach loop. The problem with this is that it is not very elegant and its repetitiveness suggests there is a better way. if (host.value -eq "GREEN"){ Write-Host "Message: host hardware is healthy" Exit 0; } else{ if (host.raid_card.status -ne "GREEN"){ Write-Host "Message: host.raid_card.product_name is not healthy" Exit 1; } elseif (host.battery.status -ne "GREEN"){ Write-Host "Message: host battery is host.battery.status" Exit 1; } elseif (host.accelerator.status -ne "GREEN"{ Write-Host "Message: accelerator temperature is host.accelerator.temperature" Exit 1; } } Any recommendations on how to better structure this would be appreciated! A: I would suggest putting the components you would like to iterate one step deeper in the structure and also make sure every component has similar 'status' properties to check (which isn't the case in your json example) like so: { "host": { "serial_number": "55555", "status": "GREEN", "name": "hostname", "components": { "raid_card": { "serial_number": "55555", "status": "GREEN", "product_name": "PRODUCT" }, "battery": { "percent_charged": 100, "health": "HEALTHY", "status": "GREEN" }, "accelerator": { "temperature": 36, "status": "GREEN" }, "logical_drives": { "serial_number": "55555555555", "health": "HEALTHY", "status": "GREEN" } } } } When you have that in place, you can use code like this to check the status of each component: # Set up an return variable (exit code) [int]$exitCode = 0 # $machine is the variable name i used to import the json above if ($machine.host.status -eq "GREEN") { Write-Host "Message: Machine $($machine.host.name) - hardware is healthy" } else { foreach ($component in $machine.host.components.PSObject.Properties) { if ($component.Value.status -ne "GREEN") { Write-Host "Message: Machine $($machine.host.name) - $($component.Name) is not healthy" $exitCode = 1 } } } Exit $exitCode Of course you have different items in there and for now i can see the array of logical drives may be a problem. If you want to have the script tell you which logical drive is causing the status to be "not GREEN" you need to provide an if statement inside the foreach loop to iterate over every drive.
{ "language": "en", "url": "https://stackoverflow.com/questions/51155364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs $routeProvider service not working with view I am trying to create a simple angularjs application to implement $routeProvider service. In my index.html page I provided a div with ngView directive as <div ng-view></div> which would display contents of login.html page in /pages directory. I followed tutorial on this link on angularjs site. But I don't understand why it is still not working. Here is my directory structure: /Writer (App Folder) ---/js ------app.js ------controllers.js ---/pages ------login.html ---index.html I am providing code of my controllers and html pages. Please take a look and point out if any flaw. index.html: <html ng-app="Writer"> <head> <script data-require="angular.js@*" data-semver="2.0.0-alpha.45" src="bower_components/angular/angular.min.js"></script> <script src="bower_components/angular-route/angular-route.min.js"></script> <script src="https://jspm.io/system@0.16.js"></script> <script src="js/app.js"></script> <script src="js/controllers.js"></script> </head> <body> <div ng-view></div> </body> </html> app.js: angular.module('Writer', ['AllControllers','ngRoute']) .config(['$routeProvider', function($routeProvider){ $routeProvider.when('/Diary',{ templateUrl:'pages/login.html', controller: 'LoginFormController' }) .otherwise({redirectTo : '/Diary'}); }]); controllers.js: var app = angular.module('AllControllers',[]); app.controller('LoginFormController',['$scope',function($scope){ $scope.whichForm = 1; $scope.setForm = function(formId){ $scope.whichForm = formId; }; $scope.isSetForm = function(formId){ return $scope.whichForm===formId; } }); login.html: <div class="loginForms"> <div class="login" ng-show="isSetForm(1)"> <form> <table> <tr> <td><input type="text" name="username" placeholder="Username" ng-model="username"/></td> </tr> <tr> <td><input type="password" name="password" placeholder="Password" ng-model="password"/></td> </tr> <tr> <td><input type="submit" name="Login" value="Login" /></td> </tr> <tr><td><span>Or</span></td></tr> <tr> <td><input type="submit" name="Register" value="Register" ng-click="setForm(2)"/></td> </tr> </table> </form> </div> <div class="register" ng-show="isSetForm(2)"> <form> <table> <tr> <td><input type="text" name="username" placeholder="Username" ng-model="username"/></td> </tr> <tr> <td><input type="text" name="email" placeholder="Email" ng-model="email"/></td> </tr> <tr> <td><input type="password" name="password" placeholder="Password" ng-model="password"/></td> </tr> <tr> <td><input type="password" name="confirmpass" placeholder="Confirm Password" ng-model="confirmPass"/></td> </tr> <tr> <td><input type="submit" name="Register" value="Register" /></td> </tr> <tr><td><span>Or</span></td></tr> <tr> <td><input type="submit" name="Login" value="Already Registered?" ng-click="setForm(1)"/></td> </tr> </table> </form> </div> </div> *Please note I am calling the functions defined in controllers.js with $scope service, in login.html directly as: <div class="login" ng-show="isSetForm(1)"> . Is this approach wrong? Sorry for a long post but if you could help I'll be very grateful as I am just beginning with angularjs.
{ "language": "en", "url": "https://stackoverflow.com/questions/35634220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to fix "image not being saved into my database(i.e image model field)"? I am building a Portfolio web app with Django. I am unable to save an image into my database in my web app. Also, to replace an existing image in the database does not work. Note: I don't get any error message from Django. The web app will tell me no file being added. On the Django Admin section(Django site administration page "localhost:8000/admin" I am able to add a new image and change an existing one. How can I enable this functionality without going to django admin section. Here's my code views.py: from django.views.generic.edit import CreateView, UpdateView from django.urls import reverse_lazy from .models import Jobs class JobsCreateView(CreateView): model = Jobs fields = ['image'] template_name = "new_job.html" class JobsUpdateView(UpdateView): model = Jobs fields = ['image'] template_name = "change_job.html" success_url = reverse_lazy('home') models.py: from django.db import models from django.urls import reverse class Jobs(models.Model): image = models.ImageField(upload_to="images/") upload_date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('home', args=[str(self.id)]) If you need any additional information from me, please let me know or you can see the complete code of this project here
{ "language": "en", "url": "https://stackoverflow.com/questions/54461240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automated Tests Don't show up in Session FrontEnd. Unreal Engine Sorry for bothering you guys but i have been having problems in trying to make some tests to show up in the automated test framework. I wrote two basic tests (c++) just to see what would happen in a plugin but i can't see them, when i open the session frontend. Can somebody help ? This is probably a minor error ... Thank you very much in advance! #include "FMyTestUtils.h" #include "Misc/AutomationTest.h" #include "Tests/AutomationCommon.h" #include "PlayableArea.h" #include "UnrealEd.h" IMPLEMENT_SIMPLE_AUTOMATION_TEST(FPACountTest, "Tests.FTrialTest", EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter); bool FPACountTest::RunTest(const FString& Parameters) { AutomationOpenMap("/Game/StarterContent/Maps/FTest_CountPAS.FTest_CountPAS"); UWorld* World = FMyTestUtils::GetWorld(); TestNotNull("Check if World is properly created", World); if (!World) return false; int32 PACount = 0; for (TActorIterator<APlayableArea> It(World); It; ++It) { PACount++; } TestTrue("Check if there are 4 PAS on the level", PACount == 3); ADD_LATENT_AUTOMATION_COMMAND(FExitGameCommand); return true; } I also tried the one in the Unreal Documentation: #include "MyBot.h" IMPLEMENT_SIMPLE_AUTOMATION_TEST(FPlaceholderTest, "TestGroup.TestSubgroup.Placeholder Test", EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter); bool FPlaceholderTest::RunTest(const FString& Parameters) { // Make the test pass by returning true, or fail by returning false. return false; } A: I discovered the issue! I was adding the classes in the visual studio so the Unreal couldn't find them. I just had to move the classes from the file "Intermediate" and put it in the "source" and generate the visual studio project files again and then build and it showed up!
{ "language": "en", "url": "https://stackoverflow.com/questions/58466806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: no python keywords in autocomplete suggestions using QScintilla and PyQt I was expecting autocomplete suggestions of Python keywords (i.e. for, range, lambda) and hoping for autocomplete suggestions with standard library modules and functions (i.e. sys, os.path, etc.) when setting up an api with the QsciLexerPython lexer, but in the code example below, compressed and updated from this website, the only auto-completion that happens are the four strings added to the list. Am I doing something wrong, and if so how do I get python keywords to register in the autocomplete? (My main question here of course) If rather this is the expected behavior, what role does the lexer play in the autocomplete and why are the keywords from the lexer not being assigned to the autocomplete lists in this example? Lastly, is it possible to have python standard library modules and sub-modules in the autocomplete, and what does that require? """Base code originally from: http://kib2.free.fr/tutos/PyQt4/QScintilla2.html""" import sys from PyQt5 import QtWidgets, Qsci app = QtWidgets.QApplication(sys.argv) editor = Qsci.QsciScintilla() lexer = Qsci.QsciLexerPython() editor.setLexer(lexer) ## setup autocompletion api = Qsci.QsciAPIs(lexer) api.add("aLongString") api.add("aLongerString") api.add("aDifferentString") api.add("sOmethingElse") api.prepare() editor.setAutoCompletionThreshold(1) editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAPIs) editor.show() editor.setText(open(sys.argv[0]).read()) sys.exit(app.exec_()) A: Thanks to ekhumoro for guiding me to the answer. The QsciAPIs class has a load method, and PyQt comes with a set of api files. Below is the code that does proper autocompletion in the manner I was looking for: """Base code originally from: http://kib2.free.fr/tutos/PyQt4/QScintilla2.html""" import sys import os import PyQt5 from PyQt5 import QtWidgets, Qsci app = QtWidgets.QApplication(sys.argv) editor = Qsci.QsciScintilla() lexer = Qsci.QsciLexerPython(editor) editor.setLexer(lexer) ## setup autocompletion api = Qsci.QsciAPIs(lexer) # import the desired api file pyqt_path = os.path.dirname(PyQt5.__file__) api.load(os.path.join(pyqt_path, "Qt/qsci/api/python/Python-3.6.api")) api.prepare() editor.setAutoCompletionThreshold(1) editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll) editor.show() editor.setText(open(sys.argv[0]).read()) sys.exit(app.exec_()) A: qscintilla does not know the keywords of python nor of the libraries, QsciAPIs hopes that you provide information, in the following part I show some functions that return the keywords and the name of the standard libraries. qscintilla will only autocomplete with the words you provide, if you want an intelligent autocomplete, I recommend you do a logic that recognizes the points or parenthesis and filter the words you provide to QsciAPIs. import sys from PyQt5 import QtWidgets, Qsci import keyword import pkgutil app = QtWidgets.QApplication(sys.argv) editor = Qsci.QsciScintilla() lexer = Qsci.QsciLexerPython() editor.setLexer(lexer) ## setup autocompletion api = Qsci.QsciAPIs(lexer) for key in keyword.kwlist + dir(__builtins__): api.add(key) for importer, name, ispkg in pkgutil.iter_modules(): api.add(name) api.prepare() editor.setAutoCompletionThreshold(1) editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAPIs) editor.show() editor.setText(open(sys.argv[0]).read()) sys.exit(app.exec_())
{ "language": "en", "url": "https://stackoverflow.com/questions/46697404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mixing Angular.js and Bootstrap 3 - where are the incompatibilites? This is a conceptual question. I am considering adding AngularJS to my next project, for which I've already elected using Twitter Bootstrap 3 for UI controls. I see some possible friction in other stackoverflow questions, between the two frameworks, but am not quite sure what is the root reason for possible incompatibilities between the two. They both listen to events, but bootstrap is mainly a front-end display library, whereas in my view, angular.js goes much deeper. Perhaps someone can fundamentally explain where the incompatibilities begin to arise. Hopefully in a way directly lending to determine how much it's a good idea to mix the two in the same project, or what should be avoided if doing so. This would save huge amounts of time learning through debug after it's too late, or avoiding the wrong architecture in the first place. A: The potential problem is that Bootstrap uses jQuery for a lot of its UI functionality. Anything changed by jQuery is not reflected in Angular by itself - for instance checking a checkbox using "regular" javascript (or jquery) will not update its ng-model automatically in the way a user checking it would. I'd say most bootstrap plugins can be made into directives, just like Angular-strap have done. But that can be a lot of work. Some common ones (like growl) are also available as stand-alone angular projects on Github.
{ "language": "en", "url": "https://stackoverflow.com/questions/19350661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I GET array from API but when i try show it in the table it show me empty array (noob ReactJs) I created a Be api I that exist a Get request to get all the tasks from this API , { "tasks": [ { "_id": "5f0b19c11f072e0984459ff5", "title": "some Edited random stuff ", "description": "some Edited random stuff", "creater": "vladi", "__v": 0 }, { "_id": "5f0b19d71f072e0984459ff6", "title": "vladi task ", "description": "vladi description", "creater": "vladi", "__v": 0 } ] in my TaskReducer i make it tasks: { tasks: [] }, now in my fronted page i ask to see it all in a table <tbody> {this.props.tasks.tasks.map((task, taskID) => <tr key={taskID}> <th scope="row" > 2{task.title}</th> <td >3{task.description}</td> <td >4{task.creater}</td> <td >5{task.dateCreated}</td> <td > <span className="pointer" onClick={() => this.handlerClickDeleteTask(task.taskID)}>delete </span> <span className="pointer" onClick={() => this.handlerClickViewTask(task.taskID)}>edit </span> <span className="pointer" onClick={() => this.handlerClickEditTask(task.taskID)}>view </span> </td> </tr> )} </tbody> but when i open the table it look empty (even not showing the numbers there) this is the link to the repository if someone have idea or think need more https://github.com/VladiKonovalov/Fronted/blob/master/src/containers/Tasks.js A: under usersActions.js file you are setting users instead of tasks. case "SET_TASKS": state = { ...state, users: action.payload } break; default: it should be like: case "SET_TASKS": state = { ...state, tasks: action.payload } break; default:
{ "language": "en", "url": "https://stackoverflow.com/questions/62923926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS: try to be "pure" or mix with HTML? When creating a new application using ExtJS, is it preferable to use as little HTML as possible, i.e. just the minimal boilerplate HTML file that loads CSS and Javascript files, and do most of the stuff in JavaScript, using ExtJS' layouts, controls etc.; or is it preferable to create normal HTML files with a little bit of ExtJS here and there? A: The widget framework is geared towards minimal HTML. Building a rich application using Ext JS is much more like building a desktop application than building a web page. It just happens to be written in JavaScript and runs in a browser. Start with the boilerplate HTML file, then build your application purely in .js files. Communicate to your web service for data using REST and JSON. A: You can do either, although Ext is really more geared toward building UI's in code. You can use Ext Core much as you would jQuery to have a "little bit here and there" but once you get into serious widget/UI development you'll inevitably spend a lot more time in your .js files. Some of the widgets do support instantiation from markup, but not all of them (and it was never built from the ground up to be markup-based like Dojo and maybe some others).
{ "language": "en", "url": "https://stackoverflow.com/questions/2243757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Python: Why does right shift >> round down and where should it be used? I've never used the >> and << operators, not because I've never needed them, but because I don't know if I could have used them, or where I should have. 100 >> 3 outputs 12 instead of 12.5. Why is this. Perhaps learning where to best use right shift will answer that implicitly, but I'm curious. A: >> and << are the right and left bit shift operators, respectively. You should look at the binary representation of the numbers. >>> bin(100) '0b1100100' >>> bin(12) '0b1100' A: The other answers explain the idea of bitshifting, but here's specifically what happens for 100>>3 100 128 64 32 16 8 4 2 1 0 1 1 0 0 1 0 0 = 100 100 >> 1 128 64 32 16 8 4 2 1 0 0 1 1 0 0 1 0 = 50 100 >> 2 128 64 32 16 8 4 2 1 0 0 0 1 1 0 0 1 = 25 100 >> 3 128 64 32 16 8 4 2 1 0 0 0 0 1 1 0 0 = 12 You won't often need to use it, unless you need some really quick division by 2, but even then, DON'T USE IT. it makes the code much more complicated then it needs to be, and the speed difference is unnoticeable. The main time you'd ever need to use it would be if you're working with binary data, and you specifically need to shift the bits around. The only real use I've had for it was reading & writing ID3 tags, which stores size information in 7-bit bytes, like so: 0xxxxxxx 0xxxxxxx 0xxxxxxx 0xxxxxxx. which would need to be put together like this: 0000xxxx xxxxxxxx xxxxxxxx xxxxxxxx to give a normal integer in memory. A: Right shift is not division Let's look at what right-shift actually does, and it will become clear. First, recall that a number is stored in memory as a collection of binary digits. If we have 8 bits of memory, we can store 2 as 00000010 and 5 as 00000101. Right-shift takes those digits and shifts them to the right. For example, right-shifting our above two digits by one will give 00000001 and 00000010 respectively. Notice that the lowest digit (right-most) is shifted off the end entirely and has no effect on the final result. A: Bit shifting an integer gives another integer. For instance, the number 12 is written in binary as 0b1100. If we bit shift by 1 to the right, we get 0b110 = 6. If we bit shift by 2, we get 0b11 = 3. And lastly, if we bitshift by 3, we get 0b1 = 1 rather than 1.5. This is because the bits that are shifted beyond the register are lost. One easy way to think of it is bitshifting to the right by N is the same as dividing by 2^N and then truncating the result. A: I have read the answers above and just wanted to add a little bit more practical example, that I had seen before. Let us assume, that you want to create a list of powers of two. So, you can do this using left shift: n = 10 list_ = [1<<i for i in range(1, n+1)] # Where n is a maximum power. print(list_) # Output: [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] You can timeit it if you want, but I am pretty sure, that the code above is one the fastest solutions for this problem. But what I cannot understand is when you can use right shift.
{ "language": "en", "url": "https://stackoverflow.com/questions/2314181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CSS : Drop down navigation menu visited In the following code, when I'm hovering dropdown #1 item #1 the hover effect of dropdown #1 item #1 goes off, where I need to make it stay until I'm out of that menu item and sub items of it. http://jsfiddle.net/kLDrG/ HTML Page <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="navmenu.css"> </head> <body> <div id="nav"> <div id="nav_wrapper"> <ul> <li><a href="#">item #1</a> </li> <li> <a href="#">item #2</a> </li> <li> <a href="#">dropdown #1</a> <ul> <li><a href="#">dropdown #1 item #1</a> </li> <li><a href="#">dropdown #1 item #2</a> </li> <li><a href="#">dropdown #1 item #3</a> </li> </ul> </li> <li> <a href="#">dropdown #2</a> <ul> <li><a href="#">dropdown #2 item #1</a> </li> <li><a href="#">dropdown #2 item #2</a> </li> <li><a href="#">dropdown #2 item #3</a> </li> </ul> </li> <li> <a href="#">item #3</a> </li> </ul> </div> <!-- Nav wrapper end --> </div> <!-- Nav end --> </body> </html> CSS File #body { padding: 0; margin: 0; font-family: Arial; font-size: 17px; } #nav { } #nav_wrapper { width: 960px; margin: 0 auto; text-align: left; } #nav ul { list-style-type: none; padding: 0; margin: 0; position: relative; min-width: 200px; } #nav ul li { display: inline-block; } #nav ul li:hover { background-color: #ffb108; } #nav ul li a{ color: #ffb108; font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif; font-weight:bold; display: block; padding: 15px; text-decoration: none; } #nav ul li a:visited{ color:#FFF; } #nav ul li a:hover{ color:#FFF; } #nav ul li:hover ul { display: block; } #nav ul ul { display: none; position: absolute; background-color: #ffb108; border-top: 0; margin-left: 0px; } #nav ul ul li { display: block; } #nav ul ul li a{ color: #FFF; } #nav ul ul li a:hover { color: #333; } A: You need to add the following: #nav ul li:hover a { color: #fff; } This styles the a tag within the hovered li. Hope that makes sense! A: The reason is you have the :hover that changes the color applied to the <a>, not the <li>. You should have a hover on the <li> style the <a> and it will work correctly. CSS: #nav ul li:hover a{ color:#FFF; } JSFiddle Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/24807455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent file loaded in memory entirely while checking its size using CommonsMultipartFile ? (java, spring) I have a form object that is being filled correctly automagically by Spring. Within this form object I have a field: CommonsMultipartFile file; The user can upload a file and the form object contains the file properly. All is good. However, I want to make sure a user cannot upload files larger than 2 MB. I have made a check and also that works. The problem: When I upload a very large file (say 500MB), I will end up with such a large file in memory in my form object (I assume this). Is there any way to prevent this? Like, is there any way to check the file size with a validator, but without the need to load up the entire file before checking? A: Assuming that you're using CommonsMultipartResolver, then you can use its maxUploadSize property to limit this. See docs for an example. A: In order to catch that MaxUploadSizeExceededException, I use the following : In the controller, you should implement the HandlerExceptionResolver interface. Then, implement the resolveException method : // Catch file too big exception @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { if (exception instanceof MaxUploadSizeExceededException) { // Do something with exception here } // Goes back to original view here Map<String, Object> model = new HashMap<String, Object>(); model.put("uploadFile", new UploadFile()); return new ModelAndView(associatedView,model); }
{ "language": "en", "url": "https://stackoverflow.com/questions/5029259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to let default values come from the database? Why does the user object still have Nothing for createdAt and updatedAt? Why are those fields not getting assigned by the database? share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User email String createdAt UTCTime Maybe default=CURRENT_TIME updatedAt UTCTime Maybe default=CURRENT_TIME deriving Show |] main = runSqlite ":memory:" $ do runMigration migrateAll userId <- insert $ User "saurabhnanda@gmail.com" Nothing Nothing liftIO $ print userId user <- get userId case user of Nothing -> liftIO $ putStrLn ("coulnt find userId=" ++ (show userId)) Just u -> liftIO $ putStrLn ("user=" ++ (show user)) Output: UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 1}} user=Just (User {userEmail = "saurabhnanda@gmail.com", userCreatedAt = Nothing, userUpdatedAt = Nothing}) A: (Edit: see solution below using triggers) The problem: Default values don't override explicitly setting a column to NULL Per the SQLite docs: The DEFAULT clause specifies a default value to use for the column if no value is explicitly provided by the user when doing an INSERT. The issue is that when Persistent is doing the insert, it's specifying the createdAt and updatedAt columns as NULL: [Debug#SQL] INSERT INTO "user"("email","created_at","updated_at") VALUES(?,?,?); [PersistText "saurabhnanda@gmail.com",PersistNull,PersistNull] To reach this conclusion, I modified your snippet to add SQL logging (I just copied the source of runSqlite and changed it to log to STDOUT). I used a file instead of in-memory database just so I could open the database in a SQLite editor and verify that the default values were being set. -- Pragmas and imports are taken from a snippet in the Yesod book. Some of them may be superfluous. {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Control.Monad.IO.Class (liftIO) import Data.Time import Control.Monad.Trans.Resource import Control.Monad.Logger import Control.Monad.IO.Class import Data.Text share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User email String createdAt UTCTime Maybe default=CURRENT_TIME updatedAt UTCTime Maybe default=CURRENT_TIME deriving Show |] runSqlite2 :: (MonadBaseControl IO m, MonadIO m) => Text -- ^ connection string -> SqlPersistT (LoggingT (ResourceT m)) a -- ^ database action -> m a runSqlite2 connstr = runResourceT . runStdoutLoggingT . withSqliteConn connstr . runSqlConn main = runSqlite2 "bar.db" $ do runMigration migrateAll userId <- insert $ User "saurabhnanda@gmail.com" Nothing Nothing liftIO $ print userId user <- get userId case user of Nothing -> liftIO $ putStrLn ("coulnt find userId=" ++ (show userId)) Just u -> liftIO $ putStrLn ("user=" ++ (show user)) Here's the output I get: Max@maximilians-mbp /tmp> stack runghc sqlite.hs Run from outside a project, using implicit global project config Using resolver: lts-3.10 from implicit global project's config file: /Users/Max/.stack/global/stack.yaml Migrating: CREATE TABLE "user"("id" INTEGER PRIMARY KEY,"email" VARCHAR NOT NULL,"created_at" TIMESTAMP NULL DEFAULT CURRENT_TIME,"updated_at" TIMESTAMP NULL DEFAULT CURRENT_TIME) [Debug#SQL] CREATE TABLE "user"("id" INTEGER PRIMARY KEY,"email" VARCHAR NOT NULL,"created_at" TIMESTAMP NULL DEFAULT CURRENT_TIME,"updated_at" TIMESTAMP NULL DEFAULT CURRENT_TIME); [] [Debug#SQL] INSERT INTO "user"("email","created_at","updated_at") VALUES(?,?,?); [PersistText "saurabhnanda@gmail.com",PersistNull,PersistNull] [Debug#SQL] SELECT "id" FROM "user" WHERE _ROWID_=last_insert_rowid(); [] UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 1}} [Debug#SQL] SELECT "email","created_at","updated_at" FROM "user" WHERE "id"=? ; [PersistInt64 1] user=Just (User {userEmail = "saurabhnanda@gmail.com", userCreatedAt = Nothing, userUpdatedAt = Nothing}) Edit: Solution using triggers: You can implement created_at and updated_at columns with triggers. This approach has some nice advantages. Basically there's no way for updated_at to be enforced by a DEFAULT value anyway, so you need a trigger for that if you want the database (and not the application) to manage it. Triggers also solve for updated_at being set when executing raw SQL queries or batch updates. Here's what this solution looks like: CREATE TRIGGER set_created_and_updated_at AFTER INSERT ON user BEGIN UPDATE user SET created_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE user.id = NEW.id; END CREATE TRIGGER set_updated_at AFTER UPDATE ON user BEGIN UPDATE user SET updated_at=CURRENT_TIMESTAMP WHERE user.id = NEW.id; END Now the output is as expected: [Debug#SQL] INSERT INTO "user"("email","created_at","updated_at") VALUES(?,?,?); [PersistText "saurabhnanda@gmail.com",PersistNull,PersistNull] [Debug#SQL] SELECT "id" FROM "user" WHERE _ROWID_=last_insert_rowid(); [] UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 1}} [Debug#SQL] SELECT "email","created_at","updated_at" FROM "user" WHERE "id"=? ; [PersistInt64 1] user=Just (User {userEmail = "saurabhnanda@gmail.com", userCreatedAt = Just 2016-02-12 16:41:43 UTC, userUpdatedAt = Just 2016-02-12 16:41:43 UTC}) The main downside to the trigger solution is that it's a slight hassle to set up the triggers. Edit 2: Avoiding Maybe and Postgres support If you'd like to avoid having Maybe values for createdAt and updatedAt, you can set them on the server to some dummy value like so: -- | Use 'zeroTime' to get a 'UTCTime' without doing any IO. -- The main use case of this is providing a dummy-value for createdAt and updatedAt fields on our models. Those values are set by database triggers anyway. zeroTime :: UTCTime zeroTime = UTCTime (fromGregorian 1 0 0) (secondsToDiffTime 0) And then let the server set the values through triggers. Slightly hacky, but in practice works great. Postgresql triggers The OP asked for SQLite but I'm sure people are reading this for other databases as well. Here's the Postgresql version: CREATE OR REPLACE FUNCTION create_timestamps() RETURNS TRIGGER AS $$ BEGIN NEW.created_at = now(); NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; CREATE OR REPLACE FUNCTION update_timestamps() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; CREATE TRIGGER users_insert BEFORE INSERT ON users FOR EACH ROW EXECUTE PROCEDURE create_timestamps(); CREATE TRIGGER users_update BEFORE UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE update_timestamps(); A: According to http://www.yesodweb.com/book/persistent The default attribute has absolutely no impact on the Haskell code itself; you still need to fill in all values. This will only affect the database schema and automatic migrations. do time <- liftIO getCurrentTime insert $ User "saurabhnanda@gmail.com" time time
{ "language": "en", "url": "https://stackoverflow.com/questions/35231697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Displaying another table field in GridView based on ID of record in another table I currently have an SQL Table called Attendance and another table called Student. The attendance Table has the fields: AttendanceID, Date, Present, StudentID and Module ID. My student table has the fields StudentID and Name. One page in my application allows the user to enter the Students ID in a textbox where all the date, present, ModuleID from the Attendance Table are shown in a Gridview for the corresponding StudentID that is entered in the Textbox. Here is my code so far which works: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RegisterConnectionString %>" SelectCommand="SELECT * FROM [Attendance] WHERE ([StudentID] = @StudentID)"> <SelectParameters> <asp:ControlParameter ControlID="pnumTextBox" Name="StudentID" PropertyName="Text" Type="String" /> </SelectParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" style="position:absolute; top: 241px; left: 357px; width: 356px;" AutoGenerateColumns="False" DataKeyNames="AttendanceID" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="AttendanceID" HeaderText="AttendanceID" InsertVisible="False" ReadOnly="True" SortExpression="AttendanceID" /> <asp:CheckBoxField DataField="Present" HeaderText="Present" SortExpression="Present" /> <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" /> <asp:BoundField DataField="StudentID" HeaderText="StudentID" SortExpression="StudentID" /> <asp:BoundField DataField="ModuleID" HeaderText="ModuleID" SortExpression="ModuleID" /> </Columns> </asp:GridView> Along with displaying the AttendanceID, StudentID, ModuleID, Present, and Date, I need to display the Student Name field from the Student Table which has the same ID as entered in the textbox, how do I achieve this? I think it is possible to do this in the SELECT command but Im unsure how. Any help is appreciated, thanks in advance! A: SELECT A.AttendanceID,A.Date,A.Present,A.ModuleID,S.StudentID,S.Name FROM attendance A ,student S WHERE A.StudentID = S.StudentID AND S.StudentID = "Your Value from the textbox"; INNER JOIN I prefer to use objectDataSource rather than SQLDataSource. to separate your layers.and use parameterized query to avoid sql injection and validate the user entry.
{ "language": "en", "url": "https://stackoverflow.com/questions/5816566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Count and sum associative array I have the following array which contains 10k records or so Array ( [0] => Array ( [0] => 111 [1] => 14/02/2020 [2] => 36 ) [6] => Array ( [0] => 222 [1] => 29/12/2019 [2] => 1 ) [7] => Array ( [0] => 222 [1] => 27/11/2019 [2] => 3 ) [8] => Array ( [0] => 333 [1] => 12/09/2019 [2] => 4 ) The result I want would be to count how many times each value at [0] occurs along with the sum of what's in [2] to show something like the following Array ( [0] => Array ( [0] => 111 [1] => 1 [2] => 36 ) [1] => Array ( [0] => 222 [1] => 2 [2] => 4 ) [2] => Array ( [0] => 333 [1] => 1 [2] => 4 ) I have tried a few things but the code got too unwieldy so I have now come back to a blank piece of paper. I tried array_count_values of a multi dimensional array? which is close as it gives me the count of what is at [0] but seems a bit overkill and I don't get the sum of [2] A: <?php $entries = [ [111, '14/02/2020', 36], [222, '29/12/2019', 1], [222, '27/11/2019', 3], [333, '12/09/2019', 4], ]; $results = []; foreach ($entries as $entry) { $results[$entry[0]] = [ $entry[0], ($results[$entry[0]][1] ?? 0) + 1, ($results[$entry[0]][2] ?? 0) + $entry[2], ]; } $results = array_values($results); print_r($results); or <?php $entries = [ [111, '14/02/2020', 36], [222, '29/12/2019', 1], [222, '27/11/2019', 3], [333, '12/09/2019', 4], ]; $results = []; foreach ($entries as $entry) { if (!isset($results[$entry[0]])) { $results[$entry[0]] = [$entry[0], 0, 0]; } ++$results[$entry[0]][1]; $results[$entry[0]][2] += $entry[2]; } $results = array_values($results); print_r($results);
{ "language": "en", "url": "https://stackoverflow.com/questions/61303650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: encoding vertex positions into textures, positions dont match and index is always zero I am trying to make a tool to encode vertex positions into a texture. The tool takes a sequence of Wavefront obj files and exports 2 textures. I am, for the most part, following this guide. I am using C# and Veldrid for my program. My program also shows a preview to see what the result looks like. I am having trouble getting my preview to use the textures correctly. The textures have the below mapping. Texture 1: * *RG - X Position *BA - Y Position Texture 2: * *RG - Z Position *BA - Normals, eventually haven't gotten their yet. I have two issues. My first issue is the decoded position is not being decoded correctly. The second issue is that gl_VertexIndex seems to always be zero. For my first issue, in order to see what was going on, I set the texture coords for the texture to 0, 0 to sample the first vertex of the first frame. I also removed any view transformation so that I could see the actual values in renderdoc. In Renderdoc, the VS_Input is 11.67803, 1.00, -11.06608 and the VS_Out is 5.75159, 1.99283, -5.03286. When using gl_VertexIndex, all the vertices for VS_Out read the same thing. #version 450 layout(location = 0) in vec3 Position; layout(location = 1) in vec3 Normal; layout(location = 2) in vec2 TexCoords; layout(location = 3) in uint Id; layout(location = 0) out vec3 outNormal; layout(location = 1) out vec4 outDebug; layout(set = 0, binding = 0) uniform MVP { mat4 Model; mat4 View; mat4 Projection; }; layout(set=0, binding=1) uniform sampler textureSampler; layout(set=0, binding=2) uniform texture2D posTex; layout(set=0, binding=3) uniform texture2D normalTex; float RemapRange(float value, float from1, float to1, float from2, float to2){ return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } float DecodeFloatRG (vec2 enc){ vec2 kDecodeDot = vec2 (1.0, 1 / 255.0); return dot(enc, kDecodeDot); } void main(){ outDebug = Projection * View * Model * vec4(Position, 1.0f); vec2 coords = vec2(0, 0); vec4 pos = textureLod(sampler2D(posTex, textureSampler), coords, 0); vec4 normal = textureLod(sampler2D(normalTex, textureSampler), coords, 0); vec3 decodedPos; decodedPos.x = DecodeFloatRG(pos.xy); decodedPos.y = DecodeFloatRG(pos.zw); decodedPos.z = DecodeFloatRG(normal.xy); float x = RemapRange(decodedPos.x, 0.0f, 1.0f, -13.0f, 13.0f); //right now this is hardcoded float y = RemapRange(decodedPos.y, 0.0f, 1.0f, -13.0f, 13.0f); float z = RemapRange(decodedPos.z, 0.0f, 1.0f, -13.0f, 13.0f); //gl_Position = Projection * View * Model * vec4(x, y, z, 1.0f); gl_Position = vec4(x, y, z, 1.0f); //gl_Position = vec4(Position, 1.0f); outNormal = Normal; } For the second issue, the shader is the same, but instead I'm using: coords = vec2(gl_VertexIndex, 0) I'm also not sure that using vertex index is the best way to go about this, as it seems like most game engines don't have this exposed. On the CPU side, I encode the textures using the below: //https://forum.unity.com/threads/re-map-a-number-from-one-range-to-another.119437/ protected float RemapRange(float value, float from1, float to1, float from2, float to2){ return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } //https://medium.com/tech-at-wildlife-studios/texture-animation-techniques-1daecb316657 protected Vector2 EncodeFloatRG (float v){ Vector2 kEncodeMul = new Vector2(1.0f, 255.0f); float kEncodeBit = 1.0f / 255.0f; Vector2 enc = kEncodeMul * v; enc.X = fract(enc.X); enc.Y = fract(enc.Y); enc.X -= enc.Y * kEncodeBit; return enc; } float fract(float x){ return x - MathF.Floor(x); } This is what the loop writing the pixels looks like. There is another one for the second texture, but it's pretty much the same. posImg.Mutate(c => c.ProcessPixelRowsAsVector4(row => { for (int x = 0; x < row.Length; x++) { var obj = meshes[y]; var vertex = obj.Vertices[x]; var pixel = new Vector4(); float X = RemapRange(vertex.Position.X, bounds.Min, bounds.Max, 0.0f, 1.0f); float Y = RemapRange(vertex.Position.Y, bounds.Min, bounds.Max, 0.0f, 1.0f); var encodedX = EncodeFloatRG(X); var encodedY = EncodeFloatRG(Y); pixel.X = encodedX.X; pixel.Y = encodedX.Y; pixel.Z = encodedY.X; pixel.W = encodedY.Y; row[x] = pixel; } y += 1; })); How I am creating and loading the textures in veldrid. As far as the sampler goes, it is a gd.PointSampler. I have tried turning SRGB on and off on the ImageSharpTexture() and using R8_G8_B8_A8_UNorm_SRgb and R8_G8_B8_A8_UNorm and pretty much any combo of those. var posTex = new Veldrid.ImageSharp.ImageSharpTexture(posPath, false, true); var normalTex = new Veldrid.ImageSharp.ImageSharpTexture(normalPath, false, true); var posDeviceTex = posTex.CreateDeviceTexture(gd, gd.ResourceFactory); var normalDeviceTex = normalTex.CreateDeviceTexture(gd, gd.ResourceFactory); var posViewDesc = new TextureViewDescription(posDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm_SRgb); var normalViewDesc = new TextureViewDescription(normalDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm_SRgb); positionTexture = gd.ResourceFactory.CreateTextureView(posViewDesc); normalTexture = gd.ResourceFactory.CreateTextureView(normalViewDesc); EDIT: I tried hard-coding the value of pixel (0, 0) of the texture in the shader like below. When I do this the result is correct and matches the original vertex position. When reading the pixel values of the texture in the shader and exporting them directly the values are wrong, so I am thinking there is some compression or color space weirdness going on when reading then texture in. Like in the shader the correct value for the pixel at 0,0 should be (0.9490196, 0.03529412, 0.5372549, 0.30588236), but in renderdoc it shows as (0.55492, 0.28516, 0.29102, 0.54314) outDebug = Projection * View * Model * vec4(Position, 1.0f); vec2 coords = vec2(0.0, 0.0); vec4 pos = textureLod(sampler2D(posTex, textureSampler), coords, 0); vec4 normal = textureLod(sampler2D(normalTex, textureSampler), coords, 0); pos = vec4(0.9490196, 0.03529412, 0.5372549, 0.30588236); normal = vec4(0.07058824, 0.96862745, 1, 1); vec3 decodedPos; decodedPos.x = DecodeFloatRG(pos.xy); decodedPos.y = DecodeFloatRG(pos.zw); decodedPos.z = DecodeFloatRG(normal.xy); float x = RemapRange(decodedPos.x, 0.0f, 1.0f, -13.0f, 13.0f); float y = RemapRange(decodedPos.y, 0.0f, 1.0f, -13.0f, 13.0f); float z = RemapRange(decodedPos.z, 0.0f, 1.0f, -13.0f, 13.0f); gl_Position = vec4(x, y, z, 1.0f); Texture 1: Texture 2: Google Drive With Textures, Obj, and Metadata A: So I figured this out, This code block need to be var posTex = new Veldrid.ImageSharp.ImageSharpTexture(posPath, false, true); var normalTex = new Veldrid.ImageSharp.ImageSharpTexture(normalPath, false, true); var posDeviceTex = posTex.CreateDeviceTexture(gd, gd.ResourceFactory); var normalDeviceTex = normalTex.CreateDeviceTexture(gd, gd.ResourceFactory); var posViewDesc = new TextureViewDescription(posDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm); var normalViewDesc = new TextureViewDescription(normalDeviceTex, PixelFormat.R8_G8_B8_A8_UNorm); positionTexture = gd.ResourceFactory.CreateTextureView(posViewDesc); normalTexture = gd.ResourceFactory.CreateTextureView(normalViewDesc); Instead. While fixing this someone also mentioned I needed to declare my TextureViews before my sampler if I wanted to use the same sampler for both textureViews. as far as gl_VertexIndex goes I'm looking into how to map the data into a spare uv channel instead as this should always be available in any game engine.
{ "language": "en", "url": "https://stackoverflow.com/questions/69340483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to emulate GL_TEXTURE_EXTERNAL_OES texture? I have a OpenGL ES 2.0 QNX application that uses camera input, makes some processing and renders something to screen. All my shaders take GL_TEXTURE_EXTERNAL_OES texture from the camera as input and it's format is YUV422. I want to test my application on the target platform (QNX) using RGB images in png format. The question is: how can I create GL_TEXTURE_EXTERNAL_OES texture from RGB image to emulate the input from the camera for my application? A: Answering own question. Steps to create GL_TEXTURE_EXTERNAL_OES texture from RGB buffer on QNX. 1.Converting RGB to YUV422 format on CPU 2.Creating pixmap buffer using screen EGLNativePixmapType pObjEglPixmap = ... 3.Binding pixmap to GL_TEXTURE_EXTERNAL_OES texture using EGLImageKHR object EGLImageKHR pObjTextureEglImage = eglCreateImageKHR(eglDisplay, EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, pObjEglPixmap, NULL); GLuint pObjTextureId; glGenTextures(1, &pObjTextureId); glBindTexture(GL_TEXTURE_EXTERNAL_OES, pObjTextureId); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)pObjTextureEglImage);
{ "language": "en", "url": "https://stackoverflow.com/questions/51500335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to fix an app that is modifying or disabling SELinux on the device to resubmit to Google Play yesterday I wanted to submit my app and after like a minute I got the following message from Google: Hello Google Play Developer, I reviewed your app, com.., and had to reject it because it violates the malicious behavior policy. If you submitted an update, the previous version of your app is still live on Google Play. Here’s how you can submit your app for another review: Make the appropriate changes to your app. We determined that your app degrades a user’s device security by modifying or disabling SELinux on the device. Apps that introduce or exploit security vulnerabilities are explicitly prohibited. Read through the Malicious Behavior policy for more details. Make sure your app is compliant with all other policies listed in the Developer Program Policies. Remember that additional enforcement could occur if there are further policy issues with your apps. Sign in to your Developer Console and submit the modified, policy compliant APK. Make sure to increment the version number of the APK. If you’ve reviewed the policy and feel this rejection may have been in error, please reach out to our policy support team. One of my colleagues will get back to you within 2 business days. Best, Lena Google Play Review Team So I actually do not know where I offend that policy. I searched for the keywords in my code: setenforce getenforce But it's not there And I also checked my permissions in the Android Manifest, nothing to worry about I guess: <uses-permission android:name="com.android.vending.BILLING" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> So I am wondering how to fix my app, that I can resubmit it and it will appear in Google Play! Thank You for your help! Best, Manuel A: I had these SDK included in project: * *AppLovin *Facebook *LeadBolt *MoPub *RevMob *Upsight *Vungle I have deleted all of them except Vungle. After that I received another message from Google. This time they warned me about Vungle version. I had to update Vungle SDK to version 3.3 or higher. Now my app is published without any problems. So If you have any of the above SDKs, try removing one by one and upload new version of APK. (I removed all, since I didn't need them)
{ "language": "en", "url": "https://stackoverflow.com/questions/35770792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSHint error: myApp is not defined (W117) Why i have this error with jshint ..? : JSHint: 'myApp' is not defined. (W117) My app.js: myApp = angular.module('autoApp', ['ngRoute', 'uiGmapgoogle-maps', 'ngTable', 'ngAnimate', 'ngTouch']) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: '/partials/cars.html', controller: 'AutoAppCtrl' }).when('/contact', { templateUrl: '/partials/contact.html', controller: 'ContactCtrl' }).when('/services', { templateUrl: '/partials/services.html', controller: 'AutoAppCtrl' }).when('/carDetails/:id', { templateUrl: '/partials/carDetails.html', controller: 'CarDetailsCtrl' }).otherwise({ redirectTo: '/' }); }); A: Because...myApp is not defined. Add a var in front of it to declare it. Otherwise, you're relying on The Horror of Implicit Globals (which only "works" in loose mode anyway), so JSHint is quite rightly telling you not to do that. A: The error describes the problem perfectly. myApp is not defined. Define it with var myApp A: First thing is you need to use var myApp there instead of myApp only. Secondly you don't need to. Even if you use var myApp, a global variable would be created. To avoid it, use angular.module('autoApp') (no second argument) wherever you want reference to myApp.
{ "language": "en", "url": "https://stackoverflow.com/questions/29096355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How To Format Timestamp I have col1 in myTable which is varchar, and I have to insert here timestamp eg:- 09-MAY-11 10.23.12.0000 AM. Now please tell me: * *How to insert into myTable with taking sysdate in above format... *How to retrieve data from col1 in tha same timestamp format.. A: INSERT: insert into myTable (col1) VALUES (to_char(systimestamp, 'dd-mon-yyyy hh.mi.ss.ff4 AM') ); SELECT: select to_timestamp(col1, 'dd-mon-yyyy hh.mi.ss.ff4 AM') from myTable ; But it is much better to store the data directly as a timestamp. Then you can compare the values ​​or modify them directly. create table myTable1( col1 timestamp default systimestamp);
{ "language": "en", "url": "https://stackoverflow.com/questions/5960401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: React-Table :Custom-pagination design I create custom pagination in my react-table, I add the page number which you can see in below description now I want to add the forward-slash after each page number I tried something but its look like very different from my needs..so give the appropriate way to do that thanks for helping in advance code which I tried is shown below [![import React from "react"; import './Pagination.css' type IProps = { pages: number, page: number, PageButtonComponent: any, onPageChange: any, previousText: string, nextText: string, onPageSizeChange: any; pageSizeOptions: any; data: any; showPageSizeOptions:any; rowsText:string; pageSize:number } type IState = { visiblePages: any } const defaultButton = (props: any) => <button {...props}>{props.children}</button>; export default class Pagination extends React.Component<IProps, IState> { constructor(props: IProps) { super(props); this.changePage = this.changePage.bind(this); this.state = { visiblePages: this.getVisiblePages(0, props.pages) }; } componentWillReceiveProps(nextProps: Readonly<IProps>): void { if (this.props.pages !== nextProps.pages) { this.setState({ visiblePages: this.getVisiblePages(0, nextProps.pages) }); } this.changePage(nextProps.page + 1); } filterPages = (visiblePages: any, totalPages: number) => { return visiblePages.filter((page: number) => page <= totalPages); }; getVisiblePages = (page: number, total: number) => { if (total < 7) { return this.filterPages(\[1, 2, 3, 4, 5, 6\], total); } else { if (page % 5 >= 0 && page > 4 && page + 2 < total) { return \[1, page - 1, page, page + 1, total\]; } else if (page % 5 >= 0 && page > 4 && page + 2 >= total) { return \[1, total - 3, total - 2, total - 1, total\]; } else { return \[1, 2, 3, 4, 5, total\]; } } }; changePage(page: any) { const activePage = this.props.page + 1; if (page === activePage) { return; } const visiblePages = this.getVisiblePages(page, this.props.pages); this.setState({ visiblePages: this.filterPages(visiblePages, this.props.pages) }); this.props.onPageChange(page - 1); } render() { const { PageButtonComponent = defaultButton } = this.props; const { visiblePages } = this.state; const activePage = this.props.page + 1; return ( <div className="row"> <div className='col-md-4 leftpagination'> <span className={"totalText"}>{"Total " + this.props.data.length}</span> &nbsp; &nbsp; {this.props.showPageSizeOptions && <span className="select-wrap -pageSizeOptions"> <select onChange={e => this.props.onPageSizeChange(Number(e.target.value))} value={this.props.pageSize} > {this.props.pageSizeOptions.map((option:number, i:number) => ( <option key={i} value={option}> {option} {this.props.rowsText} </option> ))} </select> </span>} </div> <div className='col-md-8'> <div className="Table__pagination"> <div className="Table__prevPageWrapper"> <PageButtonComponent className="Table__pageButton" onClick={() => { if (activePage === 1) return; this.changePage(activePage - 1); }} disabled={activePage === 1} > {this.props.previousText} </PageButtonComponent> </div> <div className="Table__visiblePagesWrapper"> {visiblePages.map((page: number, index: number, array: \[\]) => { return ( <PageButtonComponent key={page} className={ activePage === page ? "Table__pageButton Table__pageButton--active" : "Table__pageButton" } onClick={this.changePage.bind(null, page)} > {array\[index - 1\] + 2 < page ? `...${page}` : + page} </PageButtonComponent> ); })} </div> <div className="Table__nextPageWrapper"> <PageButtonComponent className="Table__pageButton" onClick={() => { if (activePage === this.props.pages) return; this.changePage(activePage + 1); }} disabled={activePage === this.props.pages} > {this.props.nextText} </PageButtonComponent> </div> </div> </div> </div> ); } }][1]][1] I want the result like the page looks like < 1 / 2 / 3.../ 11 > but when I tried its look like < /1 /2 /3 ...> A: Here I have written simple code for pagination design. You can use it. HTML for pagination <a>1</a> <a>2</a> <a>3</a> Style for pagination link <style> a::after { content: " /"; margin: 0 5px; } a:last-child::after { display: none; } </style> Your pagination link will be look like below You can modified the design as per your site. Hope this will work for you!
{ "language": "en", "url": "https://stackoverflow.com/questions/57709021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to create an application of AudioRecorder test in which audio is recorded by the system as well as from the environment How to create an application of AudioRecorder test in which audio is recorded by the system as well as from the environment I mean system automatically record his voice as well as the user voice please help me to write code? I tried but I don't get any clue how to write code?
{ "language": "en", "url": "https://stackoverflow.com/questions/74875254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows 7 reinstallation and Visual Studio Express 2010/Community 2013 registration key I have to reinstall my Windows 7. Do I have to obtain a new registration key for my Visual Studio Express 2010/Community 2013 or I can use my old key from previous installation? Best Regards, Jacek A: I do know that express is a free version. If you are talking about registration keys as in free to premium, then you do not have to worry as all your codes save via cloud and you don't have to get a new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/28078079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript load theme on page change Hello everyone I have written a script to change a site theme trough JS and global vars, as follows: var theme = "dark"; var themeProperties = ['--bodybgcolor', '--breadcrumbbg', '--navbarbg', '--txtcolor', '--linkcolor', '--linkvisited', '--linkhovercolor', '--navlinkcolor', '--navlinkvisited', '--navlinkhovercolor', '--navlinkbg', '--themebg', '--themeborder', '--iconpos', '--logo', '--cardbg', '--cardLogobg', '--cardshadow', '--cardtxtcolor', '--breadcrumbsvg']; var themeValues = [['#050505', '#181818', '#050505', '#f1f1f1', '#f1f1f1', '#f1f1f1', '#1BDC88', '#f1f1f1', '#f1f1f1', '#1BDC88', '#5050504d', '#f1f1f1', '#1BDC88', 'left', 'url(../img/logo-sfondo-nero.webp)', '#181818', '#ffffff', '#141414', '#f1f1f1', 'invert(100%) sepia(100%) saturate(0%) hue-rotate(302deg) brightness(101%) contrast(102%)'], ['#ffffff', '#f1f1f1', '#ffffff', '#000000', '#000000', '#000000', '#1BDC88', '#000000', '#000000', '#1BDC88', '#ababab4d', '#000000', '#1BDC88', 'right', 'url(../img/logo-sfondo-bianco.webp)', '#ededed', '#e1e1e1', '#e1e1e1', '#000000', 'invert(0%) sepia(97%) saturate(14%) hue-rotate(160deg) brightness(103%) contrast(102%)']]; window.readyState(setupWindow()); document.readyState(setupPage()); function setupWindow() { sessionStorage.setItem('panelTheme', theme); } function setupPage() { alert(sessionStorage.getItem('panelTheme'));/*this was for debugging in order to know if it was run or not*/ } function changeTheme() { localstTheme = sessionStorage.getItem('panelTheme'); if (localstTheme == 'dark') { theme = 'light'; setTheme('light'); } else { theme = 'dark'; setTheme('dark'); } } function setTheme(theme) { if (theme == 'dark') { sessionStorage.setItem('panelTheme', theme); for (var i = 0; i < themeProperties.length; i++) { document.documentElement.style.setProperty(themeProperties[i], themeValues[0][i]); } } if (theme == 'light') { sessionStorage.setItem('panelTheme', theme); for (var i = 0; i < themeProperties.length; i++) { document.documentElement.style.setProperty(themeProperties[i], themeValues[1][i]); }/**/ } } I have to find a way to keep the current theme changed when a new page has been selected throug the html page(eg. i go from home to info). My thinking was to use the sessionStorage variable i've set in order to reset all the global variables to the theme selected ones but I can't do it and I'm currently lost. setupPage() does not produce the alert and I don't really know why, alert was there to see if it ran correctly on page ready state, before i was using setTheme(sessionStorage.getItem('panelTheme')) and was not working Many thanks to all of you in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/75177943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in datatable select statement in c# I have a SELECT statement I'm running on a data table. The problem is that it gives me the error "the expression contains an invalid string constant". I know it has to do with the single quote at the end of my query but i cannot think of why its not working. Here is the code: DataRow[] foundRow = dt.Select("Student='" + Student.ID + "' AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'"); A: This looks like a classic SQL injection problem. What if the description contains a single apostrophe i.e. "Wasn't available", this will break your code. In addition, if Student is an integer value (i.e. it is an integer/auto-incrementing ID or equivalent in your DB) it should not be wrapped in quotes, giving you - DataRow[] foundRow = dt.Select("Student=" + Student.ID + " AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'");
{ "language": "en", "url": "https://stackoverflow.com/questions/6665469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JTextArea & JPanel different classes one window...is it possible? So i have two classes: public class TimeServer extends JPanel implements TimeVariables { public TimeServer() { JTextArea serverLog = new JTextArea(); // Create a scroll pane to hold text area JScrollPane scrollPane = new JScrollPane(serverLog); JPanel serverWin = new JPanel(); serverWin.add(scrollPane); } and another class that has: private JPanel mainWin = new JPanel(); private JPanel gridArea = new JPanel(); //hold cells TimeServer serverWin = new TimeServer(); public class TimClient extends JFrame implements Runnable, TimeVariables { his.add(mainWin, BorderLayout.CENTER); mainWin.setLayout(new BorderLayout()); // mainWin.setLayout(new GridLayout(1,2)); //Create Grid gridArea.setLayout(new GridLayout(10, 10, 2, 2)); for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) gridArea.add(cell[i][j] = new Cell(i, j, this)); gridArea.setBorder(new LineBorder(Color.black, 1)); jlblTitle.setHorizontalAlignment(JLabel.CENTER); jlblTitle.setFont(new Font("SansSerif", Font.BOLD, 16)); jlblTitle.setBorder(new LineBorder(Color.black, 1)); jlblStatus.setBorder(new LineBorder(Color.black, 1)); mainWin.add(gridArea, BorderLayout.CENTER); mainWin.add(serverWin, BorderLayout.PAGE_END); // Place the panel and the labels to the frame setLayout(new BorderLayout()); // implicit anyway add(jlblTitle, BorderLayout.NORTH); add(mainWin, BorderLayout.CENTER); add(jlblStatus, BorderLayout.SOUTH); } public static void main(String[] args) { // Create a frame TimClient frame = new TimClient("Time Client"); //frame.getContentPane().add(BorderLayout) // Display the frame frame.setSize(620, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } all i want to do is keep the server log and grid in the JPanel next to one another, could you explain how? also how do i add the JPanel in the server class to the one in client? Here's a sketch of how i'd like it to look: A: Your problems above appear to stem from a bad Swing code practice, one that seems to be reinforced by Swing code generators (although I'm not sure if you're currently using this tool) and the official Swing tutorials, and that is: * *First and foremost, you should avoid having your Swing GUI classes extend JFrame as that unnecessarily paints your GUI code into a corner that requires a bit of effort to get out of. *Instead gear your Swing GUI code towards making JPanels, panels which now can easily be placed into other JPanels, or into JFrames, JDialogs, JOptionPanes, swapped in CardLayouts,... wherever they are needed. *Instead, create, fill, and pack your JFrames when they are needed. So I suggest that you do just this: * *change your code above so that the classes do not extend JFrames, and instead create JPanels, *Create a master JPanel that uses a BorderLayout *Add your grid to the above, BorderLayout.CENTER *Add your JTextArea-containing JScrollPane and its JPanel into the master JPanel in the BorderLayout.PAGE_END position. *Create your JFrame to hold and display the master JPanel. If you've done a good job of separated your GUI code from your logic code, then it should be easy to re-write the GUI code while keeping your same logic (or "model") code. Edit 2 Regarding your changed question where now the first class extends JPanel, simply add that JPanel to your JFrame in the BorderLayout.LINE_END end (also known as BorderLayout.EAST) position.
{ "language": "en", "url": "https://stackoverflow.com/questions/21370687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting issue with fetching details in mysql Here is my table having tax details: Image of records in table I would like to fetch details of a tax record when I have an integer (say, 2500) between the start_range_cost and end_range_cost. My current SQL using 3000 as an example: SELECT * FROM `hotel_tax_details` WHERE `start_range_cost`>=3000 AND `end_range_cost`<=3000 A: Based solely on the query in your OP and the records in your image nothing would be returned. It would only return if both start_range_cost AND end_range_cost were exactly 3000 which none of the records match, but this is just because you've got the < and > signs flipped around. Try using BETWEEN, I feel it's less prone to comparison mistakes if you're upper and lower bounds inclusive in your comparison. Assuming: * *2500 is the number in the range searching for from your example *You want to be lower and upper bound inclusive (base on your image, it looks like it) You can use BETWEEN to make this clearer: SELECT * FROM hotel_tax_details WHERE 2500 BETWEEN start_range_cost AND end_range_cost; You could also fix the original query and correct the comparison: SELECT * FROM `hotel_tax_details` WHERE `start_range_cost`<=2500 AND `end_range_cost`>=2500 A: Hope this helps SELECT * FROM hotel_tax_details WHERE 2500 BETWEEN start_range_cost AND end_range_cost
{ "language": "en", "url": "https://stackoverflow.com/questions/50209360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS not loading in WKWebView I am trying to create a simple WebView app using UITabBarViewController. The CSS does not load when I use Tab Bar. If I use a simple View Controller, the CSS loads. There are no other changes to the code. let request: NSMutableURLRequest = NSMutableURLRequest(url: myUrl) if (webView != nil) { } else { self.loadView() self.webView.navigationDelegate = self } if (self.finishedUrl != myUrl.absoluteString) { webView.load(request as URLRequest) } A: So, I was able to solve the problem and the problem was /. If you put / to the end of url, CSS doesn't load. But, if you don't put / to the end, CSS gets loaded. A: Replace your if condition, it doesn't make sense to perform actions on a nil webview. if (webView != nil) { } else { self.loadView() self.webView.navigationDelegate = self } if (self.finishedUrl != myUrl.absoluteString) { webView.load(request as URLRequest) } should be: if (webView != nil) { self.loadView() self.webView.navigationDelegate = self } if (self.finishedUrl != myUrl.absoluteString) { webView.load(request as URLRequest) // also make sure this is being executed. } A: I had the same problem. My styles.css file was being referenced in the .HTML files just file, and it worked great loading up directly in a browser. The problem that I had was that my styles.css wasn't included in any of my Targets. After I checked the box, it loaded up great. A: I've got the same problem but nothing here helped me. The solution was to remove the folder path in the link, even if they were inside these folders in my Bundle. Instead of having this: <link rel="stylesheet" href="css/style.css" /> Removed the folder part and left this: <link rel="stylesheet" href="style.css" /> And it worked. The same happened with the .js file A: I had the same issue and resolved it by adding the resources as "Create folder instance" instead of "Create groups". Create groups indexes the file but strips it of its path. Calling the file is done by calling the filename (unique filename is important in the group). Create folder instance maintains the folder structure Cfr. Create groups vs Create folder reference in Xcode
{ "language": "en", "url": "https://stackoverflow.com/questions/55097448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between string and string? in c# In c#, the string type is inherently nullable, right? This morning I was working with the Environment.GetEnvironmentVariable() method, and noticed it returns type string?. Is the ? added to the return type redundant, and just there to indicate that it returns null when there are no environment variables that match the variable name you asked for? Or is there a more significant difference between string and string? in .net/c#?
{ "language": "en", "url": "https://stackoverflow.com/questions/70290104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSItemProvider with type identifier "com.apple.pkpass" I am building a share extension for iOS and would like to accept Passbook passes. I have the share extension working in that: NSItemProvider *itemProvider = inputItem.attachments.firstObject; [itemProvider hasItemConformingToTypeIdentifier:@"com.apple.pkpass"]; returns true. However, I'm lost at attempting to load this item. I've tried coercing it to NSData using this and other types: [itemProvider loadItemForTypeIdentifier:@"com.apple.pkpass" options:nil completionHandler:^(NSdata *item, NSError *error) { NSLog(@"%@", item); }]; However, none work. Does anybody know how to use Passbook passes in a share extension? I preferably would like an NSData object. A: Get the returned data as "id" type first, then create your PKPass object by "initWithData" with your returned data. You don't need to convert it to NSData. Remember to import Passkit.
{ "language": "en", "url": "https://stackoverflow.com/questions/30447936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do i solve this problem java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager? I'm currently working on a webservice using Netbeans 11.3 on a local Glassfish-server version 5.1.0 JDK/JRE version 1.8.0_221 When trying to post by using the webservice i receive the following error msg: java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager at sun.security.ssl.Handshaker.init(Handshaker.java:282) at sun.security.ssl.Handshaker.<init>(Handshaker.java:242) at sun.security.ssl.ClientHandshaker.<init>(ClientHandshaker.java:160) at sun.security.ssl.SSLSocketImpl.initHandshaker(SSLSocketImpl.java:1339) at sun.security.ssl.SSLSocketImpl.doneConnect(SSLSocketImpl.java:700) at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:679) at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264) at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:259) I've tried changing both JDK and JRE using the PCs environment variables and in the IDE but i keep getting the same error msg. I only found 1 more thread with a similar problem to mine: java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager Where changing JDK to 1.8.0_221 resolved the issue. Can anyone tell me why this isn't working or do you need any further information? Thanks A: I found a fix in this thread: JavaWeb java.lang.NoClassDefFoundError: sun/security/ssl/HelloExtension "Had basically the same problem, eventually solved it with this solution here. In your glassfish folder go to glassfish5/glassfish/modules/endorsed/ and open the grizzly-npn-bootstrap.jar file with winrar or your preferred unzipper. Delete the sun folder and try running your program again." I've been stuck with this for over a week and finally found this fix. Now using the post-function works!
{ "language": "en", "url": "https://stackoverflow.com/questions/65669116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this pointer incrementing by 0x10 not 0x04? In the code below, when writing to the memory why does this line of code: temp = ((int*) mem_allocate + i); not increment the memory locations in consecutive 4 bytes? The memory locations resulted due to this are: 0x20000818 0x20000828 0x20000848 ... and so on. I wanted to write the data in 0x20000818 0x2000081C 0x20000820 ... and so on. #include <stdio.h> #include <stdlib.h> int main() { int n = 1024; int* mem_allocate; int loop = 0; int i = 0; mem_allocate = (int*) malloc(n*sizeof(int)); for(i=0; i<40; i++) { int* temp; temp = ((int*) mem_allocate + i); i=i+3; *temp =0xAAAAAAAAu; *mem_allocate = *temp; mem_allocate = temp; if (i == 40) { loop = 1; } } if (loop == 1) { free(mem_allocate); } return 0; } A: Your loop control variable i is incremented by one in the for loop: for(i=0; i<40; i++) and then by a further 3 by: i=i+3; So i is overall incremented by 4 in each iteration. Pointer arithmetic accounts for the size of the object pointed to. Here you are pointing to a 32 bit (4 byte) integer, and incrementing by 4 each time, so the address is incremented by 4 x 4 = 16 bytes. You should have: for( i = 0; i < 10; i++ ) { int* temp = mem_allocate + i ; // i=i+3; REMOVE THIS! ... Note that the cast was unnecessary; mem_allocate was already an int* as is the type of the expression mem_allocate + i. Your code is flawed in other ways, unrelated to the question you have asked - specifically the ill-advised modification of mem_allocate - if you modify it, any attempt to free it will be invalid. Consider: #include <stdint.h> #include <stdlib.h> int main() { const int n = 1024; uint32_t* mem_allocate = malloc( n * sizeof(*mem_allocate) ) ; for( int i = 0; i < n; i++ ) { mem_allocate[i] = 0xAAAAAAAAu; } free( mem_allocate ) ; return 0 ; } As you can see you made a simple thing unnecessarily complicated.
{ "language": "en", "url": "https://stackoverflow.com/questions/51443140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Remove NaN from 2D numpy array For example, if I have the 2D array as follows. [[1,2,3,NAN], [4,5,NAN,NAN], [6,NAN,NAN,NAN] ] The desired result is [[1,2,3], [4,5], [6] ] How should I transform? I find using x = x[~numpy.isnan(x)] can only generate [1,2,3,4,5,6], which has been squeezed into one dimensional array. Thanks! A: Just apply that isnan on a row by row basis In [135]: [row[~np.isnan(row)] for row in arr] Out[135]: [array([1., 2., 3.]), array([4., 5.]), array([6.])] Boolean masking as in x[~numpy.isnan(x)] produces a flattened result because, in general, the result will be ragged like this, and can't be formed into a 2d array. The source array must be float dtype - because np.nan is a float: In [138]: arr = np.array([[1,2,3,np.nan],[4,5,np.nan,np.nan],[6,np.nan,np.nan,np.nan]]) In [139]: arr Out[139]: array([[ 1., 2., 3., nan], [ 4., 5., nan, nan], [ 6., nan, nan, nan]]) If object dtype, the numbers can be integer, but np.isnan(arr) won't work. If the original is a list, rather than an array: In [146]: alist = [[1,2,3,np.nan],[4,5,np.nan,np.nan],[6,np.nan,np.nan,np.nan]] In [147]: alist Out[147]: [[1, 2, 3, nan], [4, 5, nan, nan], [6, nan, nan, nan]] In [148]: [[i for i in row if ~np.isnan(i)] for row in alist] Out[148]: [[1, 2, 3], [4, 5], [6]] The flat array could be turned into a list of arrays with split: In [152]: np.split(arr[~np.isnan(arr)],(3,5)) Out[152]: [array([1., 2., 3.]), array([4., 5.]), array([6.])] where the (3,5) split parameter could be determined by counting the non-nan in each row, but that's more work and doesn't promise to be faster than than the row iteration.
{ "language": "en", "url": "https://stackoverflow.com/questions/51316245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Floating box css I have a Joomla site with K2 component. And I have a bad look "issue". Please see the image: Css box foating problem Here is a part from the css file what I think that it applies to here: /* --- Item groups --- */ div.itemList {} div#itemListLeading {} div#itemListPrimary {} div#itemListSecondary {} div#itemListLinks {background:#f7fafe;border:1px solid #ddd;margin:8px 0;padding:8px;} div.itemContainer {float:left;} div.itemContainerLast {} /* this class is appended to the last container on each row of items (useful when you want to set 0 padding/margin to the last container) */ /* --- Item block for each item group --- */ div.catItemView {padding:4px;} /* this is the item container for this view - we add a generic padding so that items don't get stuck with each other */ /* Additional class appended to the element above for further styling per group item */ div.groupLeading {} div.groupPrimary {} div.groupSecondary {} div.groupLinks {padding:0;margin:0;} div.catItemIsFeatured {background:#ddd;border:1px dotted; padding:3px;margin:1px;} /* Attach a class for each featured item */ So, I like the right side look. Thank you! A: The reason why CSS failed to achieve the results desired is because CSS only cares about horizontal position, i.e. everything is laid out horizontally first, and then vertically. Therefore, the next float on the subsequent row will only be positioned below the tallest element in the first row float, therefore leaving unfilled vertical spaces when the previous row of floats have containers with shorter heights. I'd recommend jQuery Masonry :) http://masonry.desandro.com/ A: You can use column-count to achieve the required look. Keep in mind that the order of the items will be different from when you float. Float: 1 2 3 4 5 6 Columns: 1 4 2 5 3 6 Simply set column-count: 2 on the parent of the items. Note that it doesn't work in all browsers: http://caniuse.com/#search=column
{ "language": "en", "url": "https://stackoverflow.com/questions/15040449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I deconcatenate or unconcatenate a string value in a pandas dataframe? im new to python and want to understand how to work with dataframes I have a dataframe- desc13month Out[45]: OutputValues CntOutputValues 0 12-99-Annual (AE) 217 1 21-581-Ineligible Services(IPS) 210 2 125-99-Annual (AE),126-22-Jermaine (JE) 196 3 22-99-Annual (AE) 181 4 21-50-Prime (PE) 169 I want the OutputValues column to be unconcatenated. If you notice, the last string for example "Annual" depends on the second string 99. if its is 22 it changes to Jermaine.Sometimes there could be multiple like we see for row 2. My final output should indicate these columns and an additional column which has that last string illustration- desc13month Out[45]: OutputValues CntOutputValues final 0 12-99-Annual (AE) 217 Annual (AE) 1 21-581-Ineligible Services(IPS) 210 Ineligible Services(IPS) 2 125-99-Annual (AE),126-22-Jermaine (JE) 196 Annual (AE),Jermaine (JE) 3 22-99-Annual (AE) 181 Annual (AE) 4 21-50-Prime (PE) 169 Prime (PE) A: IIUC, Let's try Series.str.replace: df['final'] = df['OutputValues'].str.replace(r'\d+-\d+-', '') OutputValues CntOutputValues final 0 12-99-Annual (AE) 217 Annual (AE) 1 21-581-Ineligible Services(IPS) 210 Ineligible Services(IPS) 2 125-99-Annual (AE),126-22-Jermaine (JE) 196 Annual (AE),Jermaine (JE) 3 22-99-Annual (AE) 181 Annual (AE) 4 21-50-Prime (PE) 169 Prime (PE) A: There are two parts to your question, one is handling the strings, and the other, applying that to the data frame. For handling the strings, if the patterns remain the same meaning you are sure that each string will be digits-digits-chars and multiple values are separated by ',' then you can use something like this function: def deconcat(output_value): output_value = output_value.split(',') result = '' for part in output_value: _, _, item = part.split('-') result += item + ", " return result.rstrip(', ') The function takes a string, splits it by ',' if there are multiple values, then for each value, splits by '-' and adds the third part to a resulting string. Now you only have to apply this function to the whole dataframe and create your new column: df['final'] = df.OutputValues.apply(deconcat) This will apply the function to each row of the OutputValues in the dataframe, and add the resulting string to a new column called 'final'.
{ "language": "en", "url": "https://stackoverflow.com/questions/64246761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JTS + reading geodata: Number of points must be 0 or >3 I'm trying to read some geodate from file. I'm using the geotools package in java. I have the geodata available as kml, gml and.shp, those are pretty big files. Those come from an external bron and are formatted correctly. When I want to read tools, GeoTools uses JTS. I also tried working with JTS directly but I get the same error message. The error I get is: java.lang.IllegalArgumentException: Number of points must be 0 or >3 at com.vividsolutions.jts.geom.LinearRing.validateConstruction(LinearRing.java:98) at com.vividsolutions.jts.geom.LinearRing.<init>(LinearRing.java:90) at com.vividsolutions.jts.geom.GeometryFactory.createLinearRing(GeometryFactory.java:324) at com.vividsolutions.jts.geom.GeometryFactory.createLinearRing(GeometryFactory.java:314) I get this error halfway through the file. I checked all files manually: all "linearrings" have more than three points. It also doesn't matter which file I'm trying to read. Code snippet: File file = new File(bwkFilePath); Map map = new HashMap(); map.put("url", file.toURL()); DataStore dataStore = DataStoreFinder.getDataStore(map); A part from a KML-file <MultiGeometry> <Polygon> <altitudeMode> relativeToGround </altitudeMode> <outerBoundaryIs> <LinearRing> <coordinates> 5.301275,50.883145,1 5.301244,50.883233,1 5.301302,50.88329999999999,1 5.301146,50.883552,1 5.301037,50.883757,1 5.301124,50.88386299999999,1 5.301524,50.884123,1 5.301924,50.88421500000001,1 5.302014,50.884129,1 5.301751,50.88367,1 5.301275,50.883145,1 </coordinates> </LinearRing> </outerBoundaryIs> </Polygon> <Point> <coordinates> 5.30152,50.883681,0 </coordinates> </Point> </MultiGeometry> A: All linearring must have 3 point at least and also their first point and last point must be same. in this example its true but may be your file contains wrong one.
{ "language": "en", "url": "https://stackoverflow.com/questions/27605270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate does not find the hibernate.cfg.xml I made a java project with gradle, so simple, it is a task manager, i have a Person class and a Task class, i want to use hibernate but, hibernate doesn't load the hibernate.cfg.xml, i tried many solutions, but anything has worked. I have a HibernateUtil.java writen like this: package org.gradle.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory( new StandardServiceRegistryBuilder().build() ); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } This is the layout: /my-project /src /main /java /org /gradle Main.java /controllers PersonController.java TaskController.java /domains Person.java Task.java Person.hbm.xml Task.hbm.xml /util HibernateUtil.java /java /resources hibernate.cfg.xml /org /gradle /test /java /org /gradle PersonTest.java TaskTest.java And this is the full trace: Sep 26, 2014 11:32:11 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final} Sep 26, 2014 11:32:11 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.6.Final} Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found Exception in thread "main" java.lang.ExceptionInInitializerError at org.gradle.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20) at org.gradle.util.HibernateUtil.<clinit>(HibernateUtil.java:9) at org.gradle.controllers.PersonController.add(PersonController.java:10) at org.gradle.Main.main(Main.java:12) Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2093) at org.hibernate.cfg.Configuration.configure(Configuration.java:2074) at org.hibernate.cfg.Configuration.configure(Configuration.java:2054) at org.gradle.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14) ... 3 more I hope you guys could help me, this is breaking my mind. If you need something more, please let me know. A: According to this tutorials on Hibernate 4+Gradle: your resources folder should be under main, not under java: Edit: probably, you are missing something in the way you are building the sessionfactory: Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); instead of : return new Configuration().configure().buildSessionFactory( new StandardServiceRegistryBuilder().build() ); you have to applysettings to pass properties of your configuration to the builder:
{ "language": "en", "url": "https://stackoverflow.com/questions/26062057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a Simple 1D CNN in PyTorch with Multiple Channels The dimensionality of the PyTorch inputs are not what the model expects, and I am not sure why. To my understanding... in_channels is first the number of 1D inputs we would like to pass to the model, and is the previous out_channel for all subsequent layers. out_channels is the desired number of kernels (filters). kernel_size is the number of parameters per filter. Therefore, we would expect, as data passed to forward, a dataset with 7 1D channels (i.e. a 2D input). However, the following code throws an error that is not consistent with what I expect, where this code: import numpy import torch X = numpy.random.uniform(-10, 10, 70).reshape(-1, 7) # Y = np.random.randint(0, 9, 10).reshape(-1, 1) class Simple1DCNN(torch.nn.Module): def __init__(self): super(Simple1DCNN, self).__init__() self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2) self.act1 = torch.nn.ReLU() self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1) def forward(self, x): x = self.layer1(x) x = self.act1(x) x = self.layer2(x) log_probs = torch.nn.functional.log_softmax(x, dim=1) return log_probs model = Simple1DCNN() print(model(torch.tensor(X)).size) Throws the following error: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-5-eca5856a2314> in <module>() 21 22 model = Simple1DCNN() ---> 23 print(model(torch.tensor(X)).size) ~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 487 result = self._slow_forward(*input, **kwargs) 488 else: --> 489 result = self.forward(*input, **kwargs) 490 for hook in self._forward_hooks.values(): 491 hook_result = hook(self, input, result) <ipython-input-5-eca5856a2314> in forward(self, x) 12 self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1) 13 def forward(self, x): ---> 14 x = self.layer1(x) 15 x = self.act1(x) 16 x = self.layer2(x) ~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 487 result = self._slow_forward(*input, **kwargs) 488 else: --> 489 result = self.forward(*input, **kwargs) 490 for hook in self._forward_hooks.values(): 491 hook_result = hook(self, input, result) ~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input) 185 def forward(self, input): 186 return F.conv1d(input, self.weight, self.bias, self.stride, --> 187 self.padding, self.dilation, self.groups) 188 189 RuntimeError: Expected 3-dimensional input for 3-dimensional weight [20, 7, 5], but got 2-dimensional input of size [10, 7] instead Edit: See below for solution, motivated by Shai. import numpy import torch X = numpy.random.uniform(-10, 10, 70).reshape(1, 7, -1) # Y = np.random.randint(0, 9, 10).reshape(1, 1, -1) class Simple1DCNN(torch.nn.Module): def __init__(self): super(Simple1DCNN, self).__init__() self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2) self.act1 = torch.nn.ReLU() self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1) def forward(self, x): x = self.layer1(x) x = self.act1(x) x = self.layer2(x) log_probs = torch.nn.functional.log_softmax(x, dim=1) return log_probs model = Simple1DCNN().double() print(model(torch.tensor(X)).shape) A: You are forgetting the "minibatch dimension", each "1D" sample has indeed two dimensions: the number of channels (7 in your example) and length (10 in your case). However, pytorch expects as input not a single sample, but rather a minibatch of B samples stacked together along the "minibatch dimension". So a "1D" CNN in pytorch expects a 3D tensor as input: BxCxT. If you only have one signal, you can add a singleton dimension: out = model(torch.tensor(X)[None, ...])
{ "language": "en", "url": "https://stackoverflow.com/questions/55720464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Regarding a clean React-Native elements app, getting: 'loose' mode configuration must be the same for Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: /Users/neil/rne/src/index.tsx: 'loose' mode configuration must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled). at enableFeature (/Users/neil/rne/node_modules/@babel/helper-create-class-features-plugin/lib/features.js:51:13) at PluginPass.pre (/Users/neil/rne/node_modules/@babel/helper-create-class-features-plugin/lib/index.js:82:35) at transformFile (/Users/neil/rne/node_modules/@babel/core/lib/transformation/index.js:97:27) at transformFile.next () at run (/Users/neil/rne/node_modules/@babel/core/lib/transformation/index.js:35:12) at run.next () at Function.transform (/Users/neil/rne/node_modules/@babel/core/lib/transform.js:25:41) at transform.next () at step (/Users/neil/rne/node_modules/gensync/index.js:261:32) at /Users/neil/rne/node_modules/gensync/index.js:273:13
{ "language": "en", "url": "https://stackoverflow.com/questions/73178551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Limitations of parallelizing heterogeneous tasks I was reading Java Concurrency in Practice and a paragraph came across which said something like this:- Under 6.3.4 Limitations of parallelizing heterogeneous tasks A further problem with dividing heterogeneous tasks among multiple workers is that the tasks may have disparate sizes. If you divide tasks A and B between two workers but A takes ten times as long as B, you’ve only speeded up the total process by 9%. Finally, dividing a task among multiple workers always involves some amount of coordination overhead; for the division to be worthwhile, this overhead must be more than compensated by productivity improvements due to parallelism. Now if you go through the bold part, is it correct to say that worker threads' co-ordination overhead must be more than the performance improvement I achieve using parallelism of threads? Could some one please help me understand it? A: No, the bolded bit changes the meaning of the sentence quite significantly: Finally, dividing a task among multiple workers always involves some amount of coordination overhead; for the division to be worthwhile, this overhead must be more than compensated by productivity improvements due to parallelism. If that was simply "must be more than the productivity improvements..." then you would be right. What the above is saying is that the performance penalty you incur by dividing the tasks among your worker threads (the overhead), must be less than the performance increase you gain by doing it at all. For instance, if your overhead is 10 seconds and your performance gain is only 5 seconds, then parallelising the operation has actually decreased your overall performance. If your overhead is 10 seconds but the performance gain is 50 seconds, you've ended up with a 40 second reduction in the overall execution time (i.e. an improvement). Another way of saying it would be "...this overhead must be offset by the productivity improvements due to parallelism.".
{ "language": "en", "url": "https://stackoverflow.com/questions/33143229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Node js url being requested multiple times I am new to Node js. I am trying to import a save a large CSV file into mongoDB using node js. My method name is 'saveCSVintoDB'. I am using csvtojson converter in this method to parse the file. As the file has more than 1 million records, the converter takes around 2 mins to parse the complete file. Meanwhile, My node js method 'saveCSVintoDB' is being requested again and the parsing starts all over again.I don't want this to happen. I don't face this problem with smaller files as they are parsed much faster and the next request takes over from there on. The problem is only while waiting for about 2 mins while the parsing happens. I don't understand this behavior. I am stuck with this for a long time. Can some body please explain this and suggest some possible alternative? Thanks, Naresh A: You can try adding a timestamp to check when it is being requested the second time: console.log("got request @" + new Date()); Since processing is taking time, the request is getting timed out and hence another request is being fired. You need to increase the timeout interval. In vanilla JS: var server = http.createServer(function (req, res) { ... }); server.timeout = 120000; If you are using Express then you can use Connect Middleware for Timeout support: var timeout = express.timeout // express v3 and below var timeout = require('connect-timeout'); //express v4 app.use(timeout(120000)); Edit: Handling the multiple request issue: Most of the answers on SO hint that second request is made for favicon. But I checked on my local machine that this is not the case with the second request made after interval of around 2 minute by printing the req.url which points to the same page which in your case will be /saveCollection. I can suggest a hack which worked on my local machine: * *Send headers: res.writeHead(200, { 'Content-Type': 'application/json' }); upon request. This will buy us 2 minutes time. *Now setup a interval which will keep feeding browser every 2 minutes with dummy data. *When the computation is completed remove the interval, send the actual result and close the response. Here's an example: router.post('/saveCollection', function(req, res,next) { console.log("col name:"+req.param("collName")); var fileStream=fs.createReadStream(req.files.myFile.path); var csvConverter=new Converter({constructResult:false}); csvConverter.on("end_parsed",function() { console.log('file completely parsed:'); clearInterval(si); res.write(", 'success':true}"); res.end(); }); i = 0; var si = setInterval(function() { i++; res.write(",'dummy" + i + "' : 'piece'"); }, 1000 * 60); //this should be kept a little less than two minutes console.log('before parsing'); res.writeHead(200, { 'Content-Type': 'application/json' }); res.write("{'dummy':'piece'"); fileStream.pipe(csvConverter); }); There is no other way to do this that I can think of. Even if you ignore the second request, still the first request will expire and browser will probably show an error. There is another work around, start computing and send a response back as soon as computing starts and then use sockets to check the status.
{ "language": "en", "url": "https://stackoverflow.com/questions/28273052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use assemby reference like an Project reference in Visual Studio? I have a C# project with some referenced dll's. To inspect the whole Project it would be nice to replace the referenced dll's against the existing project references temporarily. The benefits were "the search in the whole solution" and "Go to Definition" makes more sense. Is there a trick to replace references in the *.csproj file? Or is there a Visual Studio extension to achieve the benefits? Thanks A: I found a solution with ReSharper. You can open and disassemble the references with the extension ReSharper and set break points.
{ "language": "en", "url": "https://stackoverflow.com/questions/13508605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When building the library matio, the configure script throws the error "C compiler cannot create executables" For building the library matio, I first need to execute a configure script and afterwards run make. The configure script however throws the following error: configure: error: in `/home/user/matio-master': configure: error: C compiler cannot create executables More specifically, the error happens while executing core tests. Below you see a section of the config.log. What could be the reason for the fail and how can I fix it? ## ----------- ## ## Core tests. ## ## ----------- ## configure:2135: checking for a BSD-compatible install configure:2203: result: /usr/bin/install -c configure:2214: checking whether build environment is sane configure:2274: result: yes configure:2415: checking for a thread-safe mkdir -p configure:2454: result: /bin/mkdir -p configure:2467: checking for gawk configure:2483: found /bin/gawk configure:2494: result: gawk configure:2505: checking whether make sets $(MAKE) configure:2527: result: yes configure:2622: checking whether to enable maintainer-specific portions of Makefiles configure:2631: result: no configure:2651: checking build system type configure:2669: result: x86_64-pc-linux-gnu configure:2691: checking host system type configure:2706: result: x86_64-pc-linux-gnu configure:2819: checking for pgcc configure:2849: result: no configure:2819: checking for icc configure:2849: result: no configure:2819: checking for gcc configure:2835: found /home/user/gcc configure:2846: result: gcc configure:2880: checking for C compiler version configure:2888: gcc --version >&5 gcc (GCC) 6.3.0 Copyright (C) 2016 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. configure:2892: $? = 0 configure:2899: gcc -v >&5 Using built-in specs. COLLECT_GCC=/cadappl_sde/ictools/gcc/6.3.0/bin/gcc COLLECT_LTO_WRAPPER=/sysmnt/cadappl_sde/ictools/gcc/6.3.0/bin/../libexec/gcc/x86_64-redhat-linux/6.3.0/lto-wrapper Target: x86_64-redhat-linux Configured with: ../gcc-6.3.0/configure --prefix=/cadappl_sde/ictools/gcc/6.3.0 --with-isl=/cadappl_sde/ictools/gcc/6.3.0 --with-gmp=/cadappl_sde/ictools/gcc/6.3.0 --with-mpfr=/cadappl_sde/ictools/gcc/6.3.0 --with-mpc=/cadappl_sde/ictools/gcc/6.3.0 --enable-static --enable-shared --enable-bootstrap --enable-checking=release --disable-werror --disable-nls --enable-threads=posix --disable-libunwind-exceptions --enable-__cxa_atexit --enable-gnu-unique-object --enable-languages=c,c++,fortran,java,go,objc,obj-c++ --enable-c99 --disable-libada --enable-plugin --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux --enable-libstdcxx-time --enable-long-long --disable-multilib Thread model: posix gcc version 6.3.0 (GCC) configure:2903: $? = 0 configure:2910: gcc -V >&5 gcc: error: unrecognized command line option '-V' gcc: fatal error: no input files compilation terminated. configure:2914: $? = 1 configure:2937: checking for C compiler default output file name configure:2959: gcc -L/boost_filesystem -L/boost_system conftest.c >&5 configure:2963: $? = 0 configure:3001: result: configure: failed program was: | /* confdefs.h. */ | #define PACKAGE_NAME "MATIO" | #define PACKAGE_TARNAME "matio" | #define PACKAGE_VERSION "1.5.13" | #define PACKAGE_STRING "MATIO 1.5.13" | #define PACKAGE_BUGREPORT "t-beu@users.sourceforge.net" | #define PACKAGE "matio" | #define VERSION "1.5.13" | #define MATIO_PLATFORM "x86_64-pc-linux-gnu" | #define MATIO_MAJOR_VERSION 1 | #define MATIO_MINOR_VERSION 5 | #define MATIO_RELEASE_LEVEL 13 | #define MATIO_VERSION 1513 | #define MATIO_VERSION_STR "1.5.13" | /* end confdefs.h. */ | | int | main () | { | | ; | return 0; | } configure:3007: error: in `/home/user/matio-master': configure:3010: error: C compiler cannot create executables See `config.log' for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/53801845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reply to specific comment using django recursive relationship and react js Model is class Comment(models.Model): profile = models.ForeignKey(Profile,on_delete=models.CASCADE) account = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) content = models.TextField(max_length=160) reply = models.ForeignKey('Comment',null=True,related_name="replies",on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) adding and showing comment using react class CommentExampleComment extends Component { state={ comment:'', id:'' } changeHandler=event=>{ var vals =event.target.value // var jpt = {...this.state.comment} // this.props.comments.map(el=>(this.setState({ // comment:vals, // id:el.id this.setState({comment:vals}) // file:event.target.files } submitHandler=e=>{ e.preventDefault() var formData = new FormData() formData.append('content',this.state.comment) formData.append('id',this.actionInput.value) //used to add comment to db axios.post('http://127.0.0.1:8000/account/api/comments/1',formData).then(res=>{ console.log(res.data) }).catch(err=>{ console.log(err) }) // used for showing comment this.props.onShowComment() } return( <Aux> <br></br> // THIS IS COMMENT SECTION <div class="main-comment-section"> <form method="POST" onSubmit={this.submitHandler}> <textarea id="w3mission" onChange = {this.changeHandler} rows="4" cols="50"></textarea> <button name ="button">Comment</button> </form> {this.props.comments.map(el=>( <div> <blockquote class="blockquote"> <p class="mb-0">{ el.content }</p> <footer class="blockquote-footer">-by <cite title="Source Title"></cite></footer> </blockquote> <blockquote class="blockquote"> <p class="mb-0"></p> <footer class="blockquote-footer">-by <cite title="Source Title"></cite></footer> </blockquote> */} //THIS IS REPLY SECTION <div class="form-group row"> <form method="post" onSubmit={this.submitHandler}> <h1>{el.id}</h1> <input type="hidden" name="id" ref={(input) => { this.actionInput = input }} value ={el.id}/> <textarea id="w3mission" onChange = {this.changeHandler} rows="4" cols="50"></textarea> <button name ="button">Reply</button> </form> </div> </div> ))} </div> </Aux>)}} var mapStateToProps = state=>{ return{ comments:state.cmnts.comment } } var mapDispatchToProps = dispatch=>{ return{ onShowComment:()=>dispatch(actions.commentList()) } } export default connect( mapStateToProps, mapDispatchToProps )( CommentExampleComment ); PROBLEM IS : when i try to submit the reply value passed through hidden field "(input type="hidden" name="id" ref={(input) => { this.actionInput = input }} value ={el.id})"is always the last comment id but i want the value of the comment id to be id corresponding to that particular comment.I want the value to capture the comment id while replying to that comment A: onChange = {e => this.changeHandler(e, el.id) } grab el.id on changeHandler and store in state, use this state in your api call.
{ "language": "en", "url": "https://stackoverflow.com/questions/60545488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PIP permission denied on Mac OSX even with --user I've recently come to know the terrors of using pip with sudo to install packages. Instead, it is recommended using the --user flag. The problem is that even with the user flag I can't install ANYTHING with PIP, accusing of permission denied. Anyone ever had this problem before? Here's a little demo of the error when trying to install the package Cython: OSError: [Errno 13] Permission denied: '/Users/myusername/Library/Python/2.7' Thank you in advance for your help. P.S: I know about the alternative of using a virtualenv, but I really wanna stick to using pip on the clear. Edit: It turns out I have access to /Library/Python but not to ~/Library/Python. Which seems strange to me, why would I have access to systemwide files but not to my own? Is this normal? A: Try to use sudo command. sudo pip install cython
{ "language": "en", "url": "https://stackoverflow.com/questions/42652461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Render an user interface in memory let's say I have hwnd handle and would like to add some GUI controls in memory. I also receive all user input via events. So, is it possible to use wxwidgets to add a user interface to an image which will be drawn onto the a Window ( using such hwnd handle ). If so, does wxwidget have some facilities to keep track of state of the GUI? I'm new to wxwidgets and so please excuse my general questions. Many thanks, Christian A: The only way to add GUI controls to an image, is to draw them yourself. The only way to do that, would be to create an image GUI element, and position the other GUI elements relative to the image element. However, this will not do double-buffering of the UI like you want to do, it doesn't actually draw the UI elements in the image, just places them on top of the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/11623038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically install self signed certificate in IE Trusted Root Certification Authorities store I created a self signed certificate but the browser tells me "This CA Root Certificate is not trusted. To enable trust, install this certificate in the Trusted Root Certification Authorities store". I did by going into IE --> Internet Options --> Content --> Certificates --> ect... I actually had to export the self signed certificate and then import it into the Trusted Root Certification. Only after the certificate was located under the ROOT store in the users machine that IE did not display any WARNINGS. This will be deployed in a production environment, so having the users manually do the above steps is unacceptable. How can I automatically do this? I just want them to accept and not have that "Certificate Error" and have the URL bar turned "RED" in IE. I'm using Tomcat 5.5. I also followed the same steps as in the Tomcat SSL How To Tutorial http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html Thanks in advance. A: Java 6 provides a cryptographic provider named SunMSCAPI to access the windows cryptography libraries API. This provider implements a keystore "Windows-Root" containing all Trust Anchors certificates. It is possible to insert a certificate in this keystore. KeyStore root = KeyStore.getInstance("Windows-ROOT"); root.load(null); /* certificate must be DER-encoded */ FileInputStream in = new FileInputStream("C:/path/to/root/cert/root.der"); X509Certificate cacert = (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(in); root.setCertificateEntry("CACert Root CA", cacert); The user will be prompted if for confirmation. If the operation is canceled by the user then a KeyStoreException is thrown. Some technotes about the provider can be found here: http://download.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunMSCAPI A: Think about it. If this were possible, what would stop any fraudulent site from doing the same thing and making it look like their site was trusted? The whole point is that the user HAS to OK the certificate installation. A: First of all, possibility to do this would compromise user's security, so it would be a security hole, so no, there's no easy way to do this. Next, different software has different certificate stores. Microsoft and Chrome browser use CryptoAPI stores, Firefox has it's own store (Chrome can also use firefox's one AFAIK). Adobe's software has it's own store (in addition to CryptoAPI one).
{ "language": "en", "url": "https://stackoverflow.com/questions/5252800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Synchronization in Java - Vector vs ArrayList I am attempting to understand the difference between the Vector and ArrayList classes in terms of thread-safety. Vector is supposedly internally synchronized. Is it synchronized by each element, or as a whole? (I could imagine the case where multiple threads could access the vector at the same time, but multiple threads could not access the same element at the same time). If you look at the code below, getAo() is not equivalent to getV() because the synchronized keyword when used in a method signature synchronizes on the containing class object (an instance of VectorVsArrayList) to my knowledge. HOWEVER, is getAoSync() equivalent to getV()? By equivalent, I mean does the ao instance variable start behaving like a Vector object in terms of synchronization as long as all access to it goes through the getter method? public class VectorVsArrayList { private ArrayList<?> ao = null; private Vector<?> v = null; public ArrayList<?> getAoSync(){ synchronized(ao){ return ao; } } public synchronized ArrayList<?> getAo() { return ao; } public Vector<?> getV() { return v; } } A: Short answer: No, it's not equivalent. When you use synchronized around that return ao;, the ArrayList is only synchronized during the return instruction. This means that 2 threads cannot get the object at the exact same time, but once they have got it, they can modify it at the same time. If 2 threads execute this code, the add() is not thread safe: ArrayList<?> list = getAo(); // cannot be executed concurrently list.add(something); // CAN be executed concurrently Side note: don't use Vectors, take a look at this post to know why. A: They aren't equivalent. What you're looking for is Collections.synchronizedList which can "wrap around" any list, including ArrayList. A: to do the equivalent of Vector you should protect any access to any element in the collection, the method getAo simply sychronize the access to the array list. If two threads call getAo and after each thread call "add" method over this arraylist then you could have a multi thread problem (because "add" is not synch"). I recommend you to check the atomic classes like CopyOnWriteArrayList: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
{ "language": "en", "url": "https://stackoverflow.com/questions/22540075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error Failed to execute aapt, when compiling project in React-Native I have this error since Monday, no modifications have been made since last week. And on Monday I started giving problems. * *Glade: 2.14.1 *React-Native: 0.49.3 *compileSdkVersion 25 *targetSdkVersion 22 A: This has nothing to do with React Native, one of your resource files references an nonexisting value (dialogCornerRadius). Locate the reference (Android Studio to the rescue) and fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/50647948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TYPO3 Hook for preview for multiple languages I have a TYPO3 installation with multiple languages. Now I want to create a function that if i.e. a french editor, with french settings, goes to the View (or preview of a page) that he gets the french version and not the default language. My first idea was to use the PageLayoutViewDrawItemHookInterface and then change the URL for the right language in ext_localconf.php $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['tx_editordashboard'] = \Vendor\Editordashboard\Hooks\Backend\CheckUserCountry::class; in my CheckUserCountry.php class <?php namespace TRUMPF\Editordashboard\Hooks\Backend; use \TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface; use \TYPO3\CMS\Backend\View\PageLayoutView; class CheckUserCountry implements PageLayoutViewDrawItemHookInterface { /** * Preprocesses the preview rendering of a content element. * * @param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object * @param bool $drawItem Whether to draw the item using the default functionalities * @param string $headerContent Header content * @param string $itemContent Item content * @param array $row Record row of tt_content */ public function preProcess(PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$itemContent, array &$row) {echo "bam";} } But the Hook doesn't work if I click on the "View" Button. Any ideas so solve the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/55529523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make ROC Curves with survey objects I'm trying to build a ROC curve with data from a survey object from surveyr. But the pROC function cannot coerce a survey object back to a data frame for the analyses and it doen't work with the survey object if (!require("pacman")) install.packages("pacman") pacman::p_load(tidyverse, haven, survey, sjPlot, pROC, surveydata) roccurve1 <- roc(apoio_ag ~fitted(Model1), data = psurvey) roccurve2 <- roc(apoio_ag ~fitted(Model2), data = psurvey) roccurve3 <- roc(apoio_ag ~fitted(Model3), data = psurvey) Erro message Error in as.data.frame.default(data, optional = TRUE) : cannot coerce class ‘"svyrep.design"’ to a data.frame Those are the packages and the code that I'm currently using. Anyone has an idea on how to solve that? A: The pROC::roc function doesn't accept sampling weights, so it's not just a matter of data formats -- you can extract a data frame from a survey object with model.frame, but roc still won't be doing a weighted analysis. There's a WeightedROC package that fits weighted ROC curves. You could do something like (not tested because there isn't a reproducible example) WeightedROC(fitted(Model3), Model3$y, weights(psurvey))
{ "language": "en", "url": "https://stackoverflow.com/questions/70710042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plotting a Lognormal Distribution I am trying to plot a lognormal distribution so I can compare it with a histogram of my sample data using the code below but my plot does not look right. Is there something with my code that I am not doing correctly? The C array has a length of 17576 import matplotlib.pyplot as plt import numpy as np data=np.loadtxt(F) C=data[:,3] x = np.ma.log(C) avg = np.mean(x) std = np.std(x) dist=lognorm(std,loc=avg) plt.plot(C,dist.pdf(C),'r') plt.show() A: It looks like your x data are not in sorted order. Try this ind = np.argsort(C) xx = C[ind] yy = dist.pdf(C)[ind] plt.plot(xx, yy, 'r') Plot just connects all the (x,y) pairs with straight lines, so you need to make sure you trace your function from left-right (or right-left). Alternatively, you can skip the lines between the plot: plt.plot(C, dist.pdf(C), 'ro')
{ "language": "en", "url": "https://stackoverflow.com/questions/11957798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux echo byte array to serial port I would like to echo an array of bytes from the linux terminal to serial port. Have already seen this Sending bytes to serial port from UNIX command line? and from that deduced the command will be something like the following: printf '%b' '\x9c8684a4624000a0b2668a84400003f00301000000048ab0c0' > /dev/ttyUSB0 To debug the ideia I redirected it to a file with printf '%b' '\x9c8684a4624000a0b2668a84400003f00301000000048ab0c0' > file.raw and checked the file with hexedit. But so I've found that ASCII values were been written instead. In the end I expect the following in the file: 9c 86 84 a4 62 40 00 a0 b2 66 8a 84 40 00 03 f0 03 01 00 00 00 04 8a b0 c0
{ "language": "en", "url": "https://stackoverflow.com/questions/32529106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to deal with ASP.NET Core 2.0 Chunked Web Api Call with EF Core I've got an Angular 6 application that makes calls to Web API controllers that use EF Core. By default, EF Core will not load foreign entities (lazy loading maybe?), so following suggestions, I used the following code to include such entities: var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync(); The problem is, when the controller returns members, it sends a header of: Transfer-Encoding: chunked Making the result/data unreadable by my Angular application (to be expected I guess, since the response is chunked). Any suggestions? Is this standard behavior by Web API? What can I do to return a viable JSON? Thanks Edit #1, per johnny 5 request: API Controller: public async Task<IActionResult> GetDepartmentMembers([FromRoute] int id) { var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync(); if (members == null) { return NotFound(); } return Ok(members); } Angular Service: getDepartmentMembers(departmentId: number): Observable<Person[]> { return this.http.get<Person[]>('http://localhost:49659/api/departments/' + departmentId + '/members'); } Angular Component: getDepartmentMembers(departmentId: number) { this.departmentService.getDepartmentMembers(departmentId).subscribe(data => { this.departmentMembers = data; }); } Response Headers: A: Just as a guess since you haven't posed the error, you're not returning the correct json, paticularly in the case of the 404, I'm not really familiar with the way your doing this, but usually you would just return a list of Persons I'm not even sure why you would want to 404 just because the department doesn't have personal, instead of just returning an Empty List. Id first verify by changing you're code to look something like this: public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id) { return await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync(); } If that works it's would appear to be how you're handing your NotFound responses, then you can modify your code to use a global error handler. Usually I create a custom exception e.g InvalidId to handle my 404's etc public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id) { var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync(); if (members == null) { throw new InvalidId(); } return members; } Then you need to create a global error handler to handle your invalid id exception
{ "language": "en", "url": "https://stackoverflow.com/questions/51253152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Application to FTP files from windows server I have an ASP.NET MVC website which clients post files to as part of an order process. These files can be up to 200MB. I have a need to transfer these files to another server via FTP. I don't really want to burden IIS with this. So was thinking of writing c# app to handle the file transfer which ran every x minutes and use windows service to run it. Would this be an ok solution or is there something that could handle this for me already? If I wrote the application should I let windows service handle the scheduling i.e. start the app every x minutes or should I just get it start the app on say startup and let the app handle the sleep/wakeup. I was envisaging something quite rudimentary. Using SQL to track what needs uploading and has been uploaded. Are there any other considerations particular to a window service? The website runs on iis8 on a windows 2012 vps. A: One architecture tip -- use a simple executable and a scheduled task rather than write a service. You don't need to worry about memory leakage over months then. You could probably implement this without writing any code -- you can script ftp.exe pretty effectively. I'd just script it to push all the files, and then, presuming FTP.EXE exited with 0, to clean out the uploads folder and rinse and repeat.
{ "language": "en", "url": "https://stackoverflow.com/questions/15145384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Graph API, Development of Facebook page post targeting( make visible only specified country/city ) So I have developed APP with FB Graph API. This app writes posts on specified Facebook page. I decided that I need attach target of country and city to posts. So I have written code like this: if( count( $DataArray ) > 0 ) { $MessageData = null; $AccessToken = $this->GetAccessToken(); foreach( $DataArray as $ItemArray ) { $CleanTitle = $this->ValidateTitle( $ItemArray['title'], $NotAcceptableWords ); $GenerateMessageStr = "{$CleanTitle} - http://someutl/ID/{$Item['id']}/Feed/"; $MessageData = array ( 'access_token' => $AccessToken, 'message' => $GenerateMessageStr, 'targeting' => "{'cities':'Tbilisi','countries':'Georgia'}" ); try { $this->FacebookObject->api("/{$this->FacebookPageId}/feed", 'POST', $MessageData); } catch (FacebookApiException $e) { print_r($e); } } } But after executing, the posts still seems like public and no some targeting is attached. A: Try feed_targeting instead of targeting! All parameters which you can target like languages,cities,counties are facebook specific. You can resolve them via autocomplete data : "{'locales':[1001],'countries':[GE],'cities':[825886]}" Nice feature for automatic posting with targeting but so bad documented in the Facebook documentation... A: The right solution is: You generate the key for the city (using the API) and use the country's 2 letter code. $messageData will be: $messageData = [ 'access_token' => $AccessToken, 'message' => $GenerateMessageStr, 'targeting' => "{'cities': <generated city key>,'countries':'GE'}" ] If you're using API v2.8 and the current Facebook PHP SDK (5): $request = new \Facebook\FacebookRequest( $fbApp, $accessToken, 'POST', '/<facebook-page-id>/feed', [ 'message' => 'With Geolocate Ib', 'targeting' => "{'geo_locations': {'cities': [{'key':" . <city key> . "}]}}" ] ); The targeting flags makes sure only those in the specified city, region etc sees the post. feeds_targeting might still allow people not in those city/region to see the posts.
{ "language": "en", "url": "https://stackoverflow.com/questions/18684614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular Forms: "No value accessor for ..." Using the AngularDart Material package. Could really use some help on this error: "No value accessor for (username) or you may be missing formDirectives in your directives list." Minimal setup (formDirectives is specified in directives list): login.html <form (ngSubmit)="onSubmit()" #form="ngForm"> <material-input class="username" ngControl="username" [(ngModel)]="username" [required]="true" [floatingLabel]="true" label="Username"> </material-input> </form> login.dart import 'package:angular/angular.dart'; import 'package:angular_components/angular_components.dart'; import 'package:angular_forms/angular_forms.dart'; @Component( selector: 'login', styleUrls: const ['style.css'], templateUrl: 'login.html', directives: const [formDirectives,MaterialInputComponent,] ) class LoginComponent { String username; void onSubmit() {} } A: You need the ControlValueAccessor for material-input in your directives list. Better to use materialInputDirectives instead of MaterialInputComponent directly as it has the other directives you might want to use to interact with the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/51297778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: My website Google page rank is always showing zero even after doing SEO Please guide me to get my site in Google ranking as after doing some SEO still Google page rank is zero. A: SEO is a wide field and PageRank one of possibly thousands of signals in Googles ranking algorithms: PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is... Wikipedia A: Also what sort of time scale are you talking about? As in if you did all this in the last week it can take a long time for googles bots to re-index your site. Proper SEO can take months before reaping the benefits.
{ "language": "en", "url": "https://stackoverflow.com/questions/20656606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Python Regex to Check Long List of Strings Match a Pattern I would like to test a string: BASE[A-Z] + SINGLE CHAR {F,G,H,J,K,M,N,Q,U,V,X,Z} + SINGLE NUMERIC [0-9] The 'BASE' is at least one character long. eg. 'ESZ6' -> True, 'ESSP6' -> False I appreciate I can do: import re prog = re.compile('[A-Z]+[FGHJKMNQUVXZ]{1}[\d]{1}') ... if prog.search(string): print('This matched...') I then wanted to use: matches = [i for i in items if prog.search(item)] Is this the optimal way of implementing this? A: This depends on what you mean by, 'test a string'. Do you want to check if the entire string matches your pattern, or if the pattern just happens to occur in your string, e.g. 'ESZ6' vs. "I've got an ESZ6 burning a hole in my pocket'. Can other characters abut your target, eg. '123ESZ6ARE'? Assuming we're just testing individual tokens like 'ESZ6' and 'ESSP6', then here are some code ideas: import re items = ('ESZ6', 'ESSP6') prog = re.compile(r"[A-Z]+[FGHJKMNQUVXZ]\d$") matches = [item for item in items if prog.match(item)] Use .match() instead of .search() unless you want an unanchored search. Drop the final '$' if you want the end unanchored. (If using Python 3.4 or later, and want an anchored search, you can probably drop the '$' and use .fullmatch instead of .match) Pattern match operators only match one character sans repetition operators so you don't need the {1} indications. Use raw strings, r"\d", when dealing with patterns to keep Python from messing with your back slashes. Your description and your examples don't match exactly so I'm making some assumptions here.
{ "language": "en", "url": "https://stackoverflow.com/questions/34817015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create an excel output file from Biztalk as resulting of a query from SQL I have a query in SQL Server that returns me 5 columns with some data. I want to create a BizTalk application that saves me the result of my query in an Excel file. I will create a SP for polling, using wcf adapter to do the communication between BT and SQL. I don't know how to generate a file.xls. Is it possible? Thanks A: Any .xls file can be saved as a XML Workbook ( File-Save As from Excel), which is an XML document. You can see that this an XML doc you open it in notepad. Now, the trick is to get hands on the schema used for generating this, which is perhaps proprietary for microsoft and may not be given out. So, the workaround is, if your excel file is failrly simple, you can save it as the Workbook and see the XML and generate an XSD based on it. Now, map your incoming XML to this Workbook XSD and the resultant XML will open directly in Excel, when you double-click on it. Hope this helps. A: in that case you need to developed a custom pipeline biztalk-custom-excel-pipeline-component
{ "language": "en", "url": "https://stackoverflow.com/questions/13051071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: VBA Not detecting Spaces Present in Text for Determining Hierarchy I am VBA writing code to clean up data that has its hierarchy indicated by the number of spaces at the beginning of item name within a column but they are all in the same column (see Below). Project B Implementation AB - Item 1 BK - Item 2 CC - Item 3 CM - Item 4 SR - Environmental/R Desired format after cleaning: Project B | Implementation | AB - Item 1 Project B | Implementation | BK - Item 2 Project B | Implementation |CC - Item 3 Project B | Implementation |CM - Item 4 Project B | Implementation | SR - Environmental VBA seems to be unable to detect all the spaces at the beginning and so I have not been able to automate the sorting without using find and replace approach first to prepare the data for cleaning. See code used below after the range has been selected. Note, that this code works when the spaces are replaced with symbols ["(P)", "(I)", "(S)"] using find/replace and then using those symbols in the if statements instead of the " ". For i = 1 To NumRow If InStr(b_Range.Value2(i, 1), " ") <> 0 Then b(k, 1) = Replace(b_Range.Value2(i, 1), " ", "") ElseIf InStr(b_Range.Value2(i, 1), " ") <> 0 Then b(k, 2) = Replace(b_Range.Value2(i, 1), " ", "") ElseIf InStr(b_Range.Value2(i, 1), " ") <> 0 Then b(k, 3) = Replace(b_Range.Value2(i, 1), " ", "") For j = 1 To NumCol - 1 A(k, j) = CDbl(b_Range.Value2(i, 1 + j)) Next j k = k + 1 b(k, 1) = b(k - 1, 1) b(k, 2) = b(k - 1, 2) End If Next i Let me know your thoughts! A: Using your posted data this works for me: Sub Tester() Dim ws As Worksheet, c As Range, rng As Range, arr, proj, impl, rw As Long, v Set rng = Selection 'for example ReDim arr(1 To rng.Rows.Count, 1 To 3) 'size the output array proj = "" impl = "" rw = 0 For Each c In Selection.Cells v = c.value Select Case Len(v) - Len(LTrim(v)) '# of leading spaces Case 4: proj = Trim(v) 'or a range (eg) Case 3 To 7 Case 12: impl = Trim(v) Case 20 rw = rw + 1 arr(rw, 1) = proj arr(rw, 2) = impl arr(rw, 3) = Trim(v) End Select Next c Range("D1").Resize(rw, 3).value = arr 'output the results array End Sub Input/Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/72688663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AES encryption under contiki on CC2650 I am currently trying to add AES encryption to an existing beacon-demo that uses the TI cc2650 sensortag. I am using the AES API provided by contiki under core/lib. My main looks like this: static const uint8_t AES_key[16] = { 0xC0 , 0xC1 , 0xC2 , 0xC3 , 0xC4 , 0xC5 , 0xC6 , 0xC7 , 0xC8 , 0xC9 , 0xCA , 0xCB , 0xCC , 0xCD , 0xCE , 0xCF };// AES Key static uint8_t plain_text[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // Plain-text to be encrypted. const struct aes_128_driver AES_128; . . . printf("Plain_Text: %d \r\n", plain_text); AES_128.set_key(AES_key); AES_128.encrypt(plain_text); printf("Encrypted_Text: %p\r\n", plain_text); Unfortunately when I run the code the plain text is unchangeable. Using some extra prints, I realize that the encrypt function is working but the output is still unchangeable. Can someone please tell me what am I doing wrong here? Please note that I already added the following line to my conf file: #define AES_128_CONF aes_128_driver A: Well as @kfx pointed out in the comments const struct aes_128_driver AES_128 was shadowing the global variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/46173613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rectilinear polygon intersection I am looking for / trying to develop an optimal algorithm for rectilinear polygon intersection with rectangles. The polygons I am testing do not have holes. Answers like those given here and here are for very general polygons, and the solutions are understandably quite complex. Hoping that the S.O. community can help me document algorithms for the special cases with just rectilinear polygons. I am looking for the polygon filled in green in the image below: A: The book Computational Geometry: an Introduction by Preparata and Shamos has a chapter on rectilinear polygons. A: Use a sweep line algorithm, making use of the fact that a rectilinear polygon is defined by its vertices. Represent the vertices along with the rectangle that they belong to, i.e. something like (x, y, #rect). To this set of points, add those points that result from the intersections of all edges. These new points are of the form (x, y, final), since we already know that they belong to the resulting set of points. Now: * *sort all points by their x-value *use a sweep line, starting at the first x-coordinate; for each new point: * *if it's a "start point", add it to a temporary set T. Mark it "final" if it's a point from rectangle A and between y-coordinates from points from rectangle B in T (or vice versa). *if it's an "end point", remove it and its corresponding start point from T. After that, all points that are marked "final" denote the vertices of the resulting polygon. Let N be the total number of points. Further assuming that testing whether we should mark a point as being "final" takes time O(log(n)) by looking up T, this whole algorithm is in O(N*log(N)). Note that the task of finding all intersections can be incorporated into the above algorithm, since finding all intersections efficiently is itself a sweep line algorithm usually. Also note that the resulting set of points may contain more than one polygon, which makes it slightly harder to reconstruct the solution polygons out of the "final" vertices.
{ "language": "en", "url": "https://stackoverflow.com/questions/6083264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Change display property and id attribute I have 2 sections: <section class="notes animate" id="need" style="background:#fff; height:900px; padding-top:70px;"> <!--stuff ---> </section> <section class="focus" id="need" style="display:none;"> <!--stuff ---> </section> I want to display the second section when window is lowered to width less than 1043px. And hide the first section by display:none Update: How can I remove id attribute of first section, when width is less than 1043? A: You should use CSS media queries. You can read more about it here: http://www.w3schools.com/css/css_rwd_mediaqueries.asp For example: @media only screen and (max-width: 1043px) { section.focus { display: block; } } A: Firstly you cannot use same ID for more than one div. So change the id of one div. And to hide the second div and show the first div: Use CSS: @media only screen and (max-width: 1043px) { .focus { display: block; } .notes { display: none; } } A: In response to your requirement for removing the ID attribute, try the following JavaScript. It can only do it once however, and if you are interested in performance you should consider investigating debounce/throttle for the resize handler. (http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/) $(window).on('resize', function() { if($(window).width() < 1043) { $('.notes').removeAttr('id'); $(window).off('resize'); } }); However, the media queries answers are the correct approach to show/hide based on screen width.
{ "language": "en", "url": "https://stackoverflow.com/questions/41220485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Clicking register causes android app to crash Clicking on register makes the app crash when the email and password fields are empty, but when the name field is empty it works properly what seems to be the problem? xml file: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:gravity="center_vertical|center_horizontal" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.zachmarcelo.softcash.LoginActivity" android:background="#fff" > <!-- Login progress --> <ImageView android:layout_width="match_parent" android:layout_height="47dp" android:layout_marginBottom="20dp" android:visibility="visible" app:srcCompat="@drawable/icon_ewallet_" /> <ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:visibility="gone" /> <ScrollView android:id="@+id/login_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"> <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical|center_horizontal" android:orientation="vertical"> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="match_parent" android:textColorHint="@color/colorHint" > <EditText android:id="@+id/reg_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" android:inputType="text" android:textSize="20sp" android:textColor="@android:color/background_dark" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/TextLabel" android:textColorHint="@color/colorHint"> <EditText android:id="@+id/reg_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="@android:color/darker_gray" android:hint="Email" android:maxLines="1" android:singleLine="true" android:textColor="@android:color/background_dark" android:inputType="textEmailAddress" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/TextLabel" android:textColorHint="@color/colorHint"> <EditText android:id="@+id/reg_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="@android:color/background_dark" android:hint="Password" android:imeActionId="6" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true" android:textColor="@android:color/background_dark" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/register" style="?android:textAppearanceSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:background="@color/colorAccent" android:gravity="center" android:paddingLeft="20sp" android:paddingRight="20sp" android:text="Register" android:textStyle="bold" android:layout_marginBottom="20dp"/> <TextView android:id="@+id/signin" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Already have an account?" android:textAlignment="center" android:textColor="@color/colorPrimary" android:textSize="12dp" /> </LinearLayout> </ScrollView> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> code: package com.example.zachmarcelo.softcash; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.Patterns; import android.view.View; import android.view.WindowManager; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; public class RegisterActivity extends AppCompatActivity implements View.OnClickListener { private EditText reg_password, reg_username, reg_email; private FirebaseAuth mAuth; private ProgressBar progressBar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); progressBar = new ProgressBar(getApplicationContext()); reg_password = findViewById(R.id.reg_password); reg_email = findViewById(R.id.reg_email); reg_username = findViewById(R.id.reg_username); progressBar = findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); mAuth = FirebaseAuth.getInstance(); findViewById(R.id.register).setOnClickListener(this); findViewById(R.id.signin).setOnClickListener(this); } @Override protected void onStart() { super.onStart(); if (mAuth.getCurrentUser() != null) { Intent i = new Intent(RegisterActivity.this, HomeActivity.class); startActivity(i); finish(); } } private void registerUser() { final String username = reg_username.getText().toString().trim(); final String email = reg_email.getText().toString().trim(); String password = reg_password.getText().toString().trim(); if (username.equals("")) { reg_username.setError(getString(R.string.input_error_name)); reg_username.requestFocus(); return; } if (email.equals("")) { reg_email.setError(getString(R.string.input_error_email)); reg_email.requestFocus(); return; }else{ if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { reg_email.setError(getString(R.string.input_error_email_invalid)); reg_email.requestFocus(); return; } } if (password.equals("")) { reg_password.setError(getString(R.string.input_error_password)); reg_password.requestFocus(); return; }else{ if (password.length() < 8) { reg_password.setError(getString(R.string.input_error_password_length)); reg_password.requestFocus(); return; } } progressBar.setVisibility(View.VISIBLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { User user = new User( username, email ); FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { progressBar.setVisibility(View.GONE); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); if (task.isSuccessful()) { Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show(); Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); finish(); } else { Toast.makeText(RegisterActivity.this, getString(R.string.registration_failed), Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.register: registerUser(); break; case R.id.signin: Intent i = new Intent(this, LoginActivity.class); startActivity(i); finish(); break; } } } error log: 09-03 13:25:24.942 15875-15875/com.example.zachmarcelo.softcash E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.zachmarcelo.softcash, PID: 15875 android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 4: TypedValue{t=0x2/d=0x1010099 a=1} at android.content.res.TypedArray.getColor(TypedArray.java:492) at android.widget.TextView.<init>(TextView.java:955) at android.widget.TextView.<init>(TextView.java:872) at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:75) at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71) at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103) at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024) at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at android.widget.Editor.showError(Editor.java:505) at android.widget.Editor.onFocusChanged(Editor.java:1237) at android.widget.TextView.onFocusChanged(TextView.java:9821) at android.view.View.handleFocusGainInternal(View.java:6631) at android.view.View.requestFocusNoSearch(View.java:10890) at android.view.View.requestFocus(View.java:10869) at android.view.View.requestFocus(View.java:10836) at android.view.View.requestFocus(View.java:10778) at com.example.zachmarcelo.softcash.RegisterActivity.registerUser(RegisterActivity.java:74) at com.example.zachmarcelo.softcash.RegisterActivity.onClick(RegisterActivity.java:143) at android.view.View.performClick(View.java:6291) at android.view.View$PerformClick.run(View.java:24931) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:101) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7425) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) and this is what is supposed to be happening: (works perfectly in name text but not in other edittexts) screenshot of mobile app any help will be appreciated :D A: My guess is that it has something to do with what you put into @style/TextLabel. When you have an error with password or email you request focus programmatically. Which is fine, however when that happens something in your style is looking for a color resource which doesn't exist. That's what's causing the error. A: The error seems to be for getColor() method of textview, your primary color has some problem, please check that.
{ "language": "en", "url": "https://stackoverflow.com/questions/52143542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex pattern to match & extract variables from math/algebraic expression I’m trying to write a regex/method that extracts Variables from an input String that represents “math/algebraic expression” and a special pattern that looks like this “PROPERTY(AnyOtherAplhaNumeric)” which can also be a variable. My definition of a variable: 1) Can contain alphanumeric values only 2) Must be at least 1 char or more 3) Cannot start with a digit , must start with [A-Za-z] 4) A variable for example “X”, can be surrounded by this string “PROPERTY(X)”, therefore the variable becomes “PROPERTY(X)” My current Method & Regex (works only in some cases): public Set<String> extractUniqueVarsFromExpression(String expression) { Set<String> varsSet = null; Pattern p = null; Matcher m = null; System.out.println(expression); if (expression != null) { varsSet = new java.util.LinkedHashSet<String>(); //"[A-Za-zPROPERTY(?)_][A-Za-z0-9PROPERTY(?)_]*||[A-Za-z_][A-Za-z0-9_]*" //"[[A-Za-z_][A-Za-z0-9_]*" p = Pattern.compile("[A-Za-zPROPERTY(?)_][A-Za-z0-9PROPERTY(?)_]*||[A-Za-z_][A-Za-z0-9_]*", Pattern.CASE_INSENSITIVE); m = p.matcher(expression); while (m.find()) { String group = m.group().trim(); //do not add duplicates if (!varsSet.contains(group)) { varsSet.add(group); System.out.println(" Variable : " + group); }//end if not duplicate }// end while } System.out.println(); return varsSet; } Examples/Cases: Ex #1: Input: [(ibdweight / ibdheight) * ibdheight] * 703 Output: Variable : PROPERTY(ibdweight) Variable : PROPERTY(ibdheight) Ex #2: Input: [ibdweight / ibdheight * ibdheight] * 703 Output: Variable : ibdweight Variable : ibdheight Ex #3: Input: [PROPERTY(ibdweight) / [PROPERTY(ibdheight) * PROPERTY(ibdheight)] * 703 Output: Variable : PROPERTY(ibdweight) Variable : PROPERTY(ibdheight) Ex #:4 These are the cases that don’t work (examples 4 to 6): The problem is the parenthesis are being picked up as variables: Input: ( Mass * ( Acceleration + whatever )) Output: Variable : ( Variable : Mass Variable : Acceleration Variable : whatever Variable : )) Ex #:5 The problem is the parenthesis are being picked up as variables: Input: ( Base * Height ) / 2 Output: Variable : ( Variable : Base Variable : Height Variable : ) Ex #:6 The problem is the parenthesis are being picked up as variables OR attached to a variable: Input: [((( var * var2 ) var3 ) + ( var1 / var4 ) var5) / var6 ] Output: Variable : ((( Variable : var Variable : var2 Variable : ) Variable : var3 Variable : ( Variable : var1 Variable : var4 Variable : var5) Variable : var6 A: The problem with your regular expression is that you have the both the parentheses and the word "PROPERTY" inside of the brackets. Brackets are for specifying a set of characters, not strings, any member of which will match. A simple (although probably not optimal) variation that should work for you is: (PROPERTY\([A-Za-z][A-Za-z0-9_]*\))|([A-Za-z][A-Za-z0-9_]*) A slightly better version would be: (PROPERTY\([A-Za-z]\w*\))|([A-Za-z]\w*) A: Part of the problem is the way that you are thinking about the regex. As an example: [A-Za-zPROPERTY(?)_] This is essentially a "character class" which is not behaving the way that you are expecting. It will match ANY single character in the input string that matches ANY of the characters in the class. It does not treat PROPERTY as a single entity, but rather as separate uppercase letters (which are already included with the A-Z, anyway. Also, having (?) in your character class is matching "(", which I am sure is not what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/11252091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use Case on join SQL query i have a query to select with case select so.name, rp.name, CASE WHEN sp.delivery_type = 'direct' THEN true ELSE false END as is_direct, CASE WHEN sp.origin ilike 'Return%' THEN true ELSE false END as is_from_return_doc, jsonb_agg( json_build_object( 'id', sm.id, 'product_id', pp.id, 'product_sku', pt.default_code, 'product_name', pt.name, 'image_url', CASE WHEN ir.store_fname IS NOT NULL THEN CONCAT('{}', ir.store_fname) ELSE '' END, 'quantity', sm.product_uom_qty, 'uom', json_build_object( 'id', sm_uom.id, 'name', sm_uom.name, 'factor', sm_uom.factor, 'barcode', piu.barcode ) ) ) as items from sale_order so JOIN res_partner rp on so.partner_id = rp.id JOIN stock_picking sp ON CASE WHEN sp.sale_id = so.id and sp.origin = so.name and sp.state in ('done') THEN sp.sale_id = so.id WHEN sp.sale_id = so.id and sp.origin ilike 'Return%' and sp.state not in ('cancel', 'done') THEN sp.sale_id = so.id END JOIN stock_move sm on sm.picking_id = sp.id JOIN product_product pp on sm.product_id = pp.id JOIN product_template pt on pp.product_tmpl_id = pt.id JOIN product_uom sm_uom ON sm.product_uom = sm_uom.id LEFT JOIN product_identity_uom piu ON piu.product_id = pt.id AND piu.uom_id = sm.product_uom LEFT JOIN ir_attachment ir ON ir.res_id = pt.id and ir.res_model = 'product.template' and ir.res_field = 'image' WHERE so.name = 'SO503251' GROUP BY so.id, rp.id, sp.id on this part, i want the last condition is replacing the first condition if the second condition is true, but it always goes to the first condition.. so if we found the "return" it will replace the first condition,.. i tried to make it nest condition case in case but didnt work.. please can someone help? CASE WHEN sp.sale_id = so.id and sp.origin = so.name and sp.state in ('done') THEN sp.sale_id = so.id WHEN sp.sale_id = so.id and sp.origin ilike 'Return%' and sp.state not in ('cancel', 'done') THEN sp.sale_id = so.id END thanks A: I speculate that you want logic something like this: ON sp.sale_id = so.id and (sp.origin = so.name and sp.state in ('done') or sp.origin ilike 'Return%' and sp.state not in ('cancel', 'done') )
{ "language": "en", "url": "https://stackoverflow.com/questions/65004511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Animating items in a ListView inside a stream builder I was working on a flutter project which involved searching items from a SQL database and then displaying them inside a StreamBuilder. I wanted to add an animation when new items are added by using a package called "flutter_staggered_animations" but since every time the search happens all the items inside my ListView are refreshed and the animation happens for every item, How can I make the animation happen only for the new results/items(that weren't found in the previous search)? I'm new to flutter. the code for the body is down below body: StreamBuilder( stream: _stream, builder: (BuildContext ctx, AsyncSnapshot snapshot){ if(snapshot.data == null){ return Container( child:Center(child: Text("Enter a search word")), ); } if(snapshot.data == "waiting"){ return Center( child: CircularProgressIndicator(), ); } return ListView.builder( itemCount: snapshot.data.length <= 20 ? snapshot.data.length : 20, itemBuilder: (BuildContext context,int index){ return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 375), child: SlideAnimation( verticalOffset: 50.0, child: FadeInAnimation( child: Container( color: Colors.grey[300], child: Padding( padding: const EdgeInsets.all(8.0), child: ListTile( // leading: snapshot.data.length!=2 ? null : CircleAvatar(), title: Text(snapshot.data[index]["word"]), subtitle: Text(snapshot.data[index]["definition"]), ), ), ), ), ), ); }, ); }, ),
{ "language": "en", "url": "https://stackoverflow.com/questions/65269822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JavaScript jQuery find value SyntaxError: missing : after property id I am getting the error Error: SyntaxError: missing : after property id on this line below, and I cannot work out why. I have a form with an ID of dform, I have a radio button with a name of del_standard_use_b_as_s and i'd like to get the value of it. var std_address_copy = $('#dform').find('input[name=del_standard_use_b_as_s]').val(); Am I missing something obvious here? A: If the previous line is $('#dform).validate({ then I guess the problems comes from the fact that validate should be passed options From the doc ( http://docs.jquery.com/Plugins/Validation/validate ), assuming your code is part of the submitHandler, something like : $(".selector").validate({ submitHandler: function(form) { var std_address_copy = $('#dform').find('input[name=del_standard_use_b_as_s]').val(); .... } }) Hope this will help
{ "language": "en", "url": "https://stackoverflow.com/questions/13193370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android crashes on start My app was working fine, until it crashed once and can't run again only on android. IOS is working fine. build doesn't catch any error, but when I start it on android studio I get these error log. enter image description here E/unknown:ReactNative: ReactInstanceManager.createReactContext: mJSIModulePackage not null E/AndroidRuntime: FATAL EXCEPTION: mqt_js Process: com.gamo, PID: 17096 java.lang.AssertionError: No source URL loaded, have you initialised the instance? at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:35) at com.facebook.react.modules.debug.SourceCodeModule.getTypedExportedConstants(SourceCodeModule.java:39) at com.facebook.fbreact.specs.NativeSourceCodeSpec.getConstants(NativeSourceCodeSpec.java:35) at com.facebook.react.bridge.JavaModuleWrapper.getConstants(JavaModuleWrapper.java:129) at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27) at android.os.Looper.loop(Looper.java:223) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226) at java.lang.Thread.run(Thread.java:923) I/Process: Sending signal. PID: 17096 SIG: 9 I already tried gradlew clean, cache clean, enable hermes = true
{ "language": "en", "url": "https://stackoverflow.com/questions/69825411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I get empty months while grouping records by last 12 month in EF Core 5 I have code snippet below for grouping records for last 12 months and it works properly but I just noticed that empty months is not included. Where did I go wrong? Thanks in advance public IQueryable<DashboardGrouping> DashboardStats() { var yearAgo = DateTime.Now.AddYears(-1); var date = new DateTime(yearAgo.Year, yearAgo.Month, 1); var items = context.Set<Transaction>() .Where(x => x.IsActive && x.CreatedAt.HasValue && x.CreatedAt.Value.Date >= date.Date && x.PaymentStatusId == PaymentStatus.Completed) .Include(x => x.Payment) .Include(x => x.Branch) .AsNoTracking() .Select(x => new { Year = x.CreatedAt.Value.Year, Month = x.CreatedAt.Value.Month, CashAmount = x.Payment.CashAmount, CardAmount = x.Payment.CardAmount, }) .GroupBy(x => new { Year = x.Year, Month = x.Month, }) .Select(x => new DashboardGrouping { Year = x.Key.Year, Month = x.Key.Month, TotalSale = x.Sum(s => s.CashAmount + s.CardAmount) }); return items; } A: You can do client-side postprocessing and enrich result with missing records. Helper function for generating months: static IEnumerable<DateTime> GetMonths(DateTime startDate, DateTime endDate) { startDate = new DateTime(startDate.Year, startDate.Month, 1); endDate = new DateTime(endDate.Year, endDate.Month, 1); while (startDate < endDate) { yield return startDate; startDate = startDate.AddMonths(1); } } Postprocessing: var currentDate = DateTime.Now; var yearAgo = currentDate.AddYears(-1); var months = GetMonths(yearAgo, currentDate); var stats = DashboardStats().ToList(); // left join months to actual data var query = from m in months join s in stats on new { m.Year, m.Month } equals new { s.Year, s.Month } into gj from s in gj.DefaultIfEmpty() select s ?? new DashboardGrouping { Year = m.Year, Month = m.Month, TotalSale = 0 }; var result = query.ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/70589893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UNION with different data types in db2 server I have built a query which contains UNION ALL, but the two parts of it have not the same data type. I mean, i have to display one column but the format of the two columns, from where i get the data have differences. So, if i get an example : select a,b from c union all select d,b from e a and d are numbers, but they have different format. It means that a's length is 15 and b's length is 13. There are no digits after the floating point. Using digits, varchar, integer and decimal didn't work. I always get the message : Data conversion or data mapping error. How can i convert these fields in the same format? A: I've no DB2 experience but can't you just cast 'a' & 'd' to the same types. That are large enough to handle both formats, obviously. A: I have used the cast function to convert the columns type into the same type(varchar with a large length).So i used union without problems. When i needed their original type, back again, i used the same cast function(this time i converted the values into float), and i got the result i wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/1472196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I retrieve links inside from a page and show on Rails page? I have been given ASP and HTML files which contain HTML and some JavaScript code. I have to write a Rails application which will retrieve links from those pages and show them in Rails views. I am stuck. Will Nokogiri help? A: Yes, it will. # open and read your HTML file as Nokogiri::HTML document doc = File.open("your_file.html") { |f| Nokogiri::HTML(f) } # collect all links that have not empty href attribute links = doc.css('a').map { |link| link['href'] }.reject { |link| link.blank? }
{ "language": "en", "url": "https://stackoverflow.com/questions/43223528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: KnockoutJS: Determining when changes to "ko.observableCollection" have finished rendering/updating the view I have an example in which I render a list of items using KnockoutJS. Every time a new item is added or removed to the ko.observableCollection a function is automatically triggered to reset all the item positions. In order to achieve this I subscribe to the ko.observableCollection to trigger the "reArrangeTiles" function: this.reArrangeTiles = function () { window.setTimeout(function () { self.$('.grid').each(function () { self.$('.tile[tileid=' + $(this).attr('tileid') + ']').animate($(this).position(), {duration: 500, queue: false}); }); }, 500); }; Each item in the ko.observableCollection is rendered twice, as "float:left" and "position:absolute". The "float:left" is invisible and its purpose is to mark the position where the "position:absolute" item needs to be moved to. The problem is that I need to wrap the re-arrange logic in a 500ms timeout because I need to wait for KnockoutJS to finish rendering the changes before I can obtain the updated positions. Does somebody know a better way to handle this than using a timeout? Thanks A: I think I figured this out. Using "afterAdd" and "beforeRemove" callbacks I can trigger the "reArrangeTiles" at the appropriate moment. Important note here is that when "beforeRemove" binding is used, the corresponding node needs to be explicitly removed. Once the node is removed I can invoke the "reArrangeTiles" function: this.hideTile = function (elem) { if (elem.nodeType === 1) { $(elem).fadeOut(function () { $(elem).remove(); self.reArrangeTiles(); }); } }; Updated example
{ "language": "en", "url": "https://stackoverflow.com/questions/20808589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Speeding up the code using numpy I'm new to python, and I have this code for calculating the potential inside a 1x1 box using fourier series, but a part of it is going way too slow (marked in the code below). If someone could help me with this, I suspect I could've done something with the numpy library, but I'm not that familiar with it. import matplotlib.pyplot as plt import pylab import sys from matplotlib import rc rc('text', usetex=False) rc('font', family = 'serif') #One of the boundary conditions for the potential. def func1(x,n): V_c = 1 V_0 = V_c * np.sin(n*np.pi*x) return V_0*np.sin(n*np.pi*x) #To calculate the potential inside a box: def v(x,y): n = 1; sum = 0; nmax = 20; while n < nmax: [C_n, err] = quad(func1, 0, 1, args=(n), ); sum = sum + 2*(C_n/np.sinh(np.pi*n)*np.sin(n*np.pi*x)*np.sinh(n*np.pi*y)); n = n + 1; return sum; def main(argv): x_axis = np.linspace(0,1,100) y_axis = np.linspace(0,1,100) V_0 = np.zeros(100) V_1 = np.zeros(100) n = 4; #Plotter for V0 = v_c * sin () x for i in range(100): V_0[i] = V_0_1(i/100, n) plt.plot(x_axis, V_0) plt.xlabel('x/L') plt.ylabel('V_0') plt.title('V_0(x) = sin(m*pi*x/L), n = 4') plt.show() #Plot for V_0 = V_c(1-(x-1/2)^4) for i in range(100): V_1[i] = V_0_2(i/100) plt.figure() plt.plot(x_axis, V_1) plt.xlabel('x/L') plt.ylabel('V_0') plt.title('V_0(x) = 1- (x/L - 1/2)^4)') #plt.legend() plt.show() #Plot V(x/L,y/L) on the boundary: V_0_Y = np.zeros(100) V_1_Y = np.zeros(100) V_X_0 = np.zeros(100) V_X_1 = np.zeros(100) for i in range(100): V_0_Y[i] = v(0, i/100) V_1_Y[i] = v(1, i/100) V_X_0[i] = v(i/100, 0) V_X_1[i] = v(i/100, 1) # V(x/L = 0, y/L): plt.figure() plt.plot(x_axis, V_0_Y) plt.title('V(x/L = 0, y/L)') plt.show() # V(x/L = 1, y/L): plt.figure() plt.plot(x_axis, V_1_Y) plt.title('V(x/L = 1, y/L)') plt.show() # V(x/L, y/L = 0): plt.figure() plt.plot(x_axis, V_X_0) plt.title('V(x/L, y/L = 0)') plt.show() # V(x/L, y/L = 1): plt.figure() plt.plot(x_axis, V_X_1) plt.title('V(x/L, y/L = 1)') plt.show() #Plot V(x,y) ####### # This is where the code is way too slow, it takes like 10 minutes when n in v(x,y) is 20. ####### V = np.zeros(10000).reshape((100,100)) for i in range(100): for j in range(100): V[i,j] = v(j/100, i/100) plt.figure() plt.contour(x_axis, y_axis, V, 50) plt.savefig('V_1') plt.show() if __name__ == "__main__": main(sys.argv[1:]) A: You can find how to use FFT/DFT in this document : Discretized continuous Fourier transform with numpy Also, regarding your V matrix, there are many ways to improve the execution speed. One is to make sure you use Python 3, or xrange() instead of range() if you a are still in Python 2.. I usually put these lines in my Python code, to allow it to run evenly wether I use Python 3. or 2.* # Don't want to generate huge lists in memory... use standard range for Python 3.* range = xrange if isinstance(range(2), list) else range Then, instead of re-computing j/100 and i/100, you can precompute these values and put them in an array; knowing that a division is much more costly than a multiplication ! Something like : ratios = np.arange(100) / 100 V = np.zeros(10000).reshape((100,100)) j = 0 while j < 100: i = 0 while i < 100: V[i,j] = v(values[j], values[i]) i += 1 j += 1 Well, anyway, this is rather cosmetic and will not save your life; and you still need to call the function v()... Then, you can use weave : http://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/weave.html Or write all your pure computation/loop code in C, compile it and generate a module which you can call from Python. A: You should look into numpy's broadcasting tricks and vectorization (several references, one of the first good links that pops up is from Matlab but it is just as applicable to numpy - can anyone recommend me a good numpy link in the comments that I might point other users to in the future?). What I saw in your code (once you remove all the unnecessary bits like plots and unused functions), is that you are essentially doing this: from __future__ import division from scipy.integrate import quad import numpy as np import matplotlib.pyplot as plt def func1(x,n): return 1*np.sin(n*np.pi*x)**2 def v(x,y): n = 1; sum = 0; nmax = 20; while n < nmax: [C_n, err] = quad(func1, 0, 1, args=(n), ); sum = sum + 2*(C_n/np.sinh(np.pi*n)*np.sin(n*np.pi*x)*np.sinh(n*np.pi*y)); n = n + 1; return sum; def main(): x_axis = np.linspace(0,1,100) y_axis = np.linspace(0,1,100) ####### # This is where the code is way too slow, it takes like 10 minutes when n in v(x,y) is 20. ####### V = np.zeros(10000).reshape((100,100)) for i in range(100): for j in range(100): V[i,j] = v(j/100, i/100) plt.figure() plt.contour(x_axis, y_axis, V, 50) plt.show() if __name__ == "__main__": main() If you look carefully (you could use a profiler too), you'll see that you're integrating your function func1 (which I'll rename into the integrand) about 20 times for each element in the 100x100 array V. However, the integrand doesn't change! So you can already bring it out of your loop. If you do that, and use broadcasting tricks, you could end up with something like this: import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt def integrand(x,n): return 1*np.sin(n*np.pi*x)**2 sine_order = np.arange(1,20).reshape(-1,1,1) # Make an array along the third dimension integration_results = np.empty_like(sine_order, dtype=np.float) for enu, order in enumerate(sine_order): integration_results[enu] = quad(integrand, 0, 1, args=(order,))[0] y,x = np.ogrid[0:1:.01, 0:1:.01] term = integration_results / np.sinh(np.pi * sine_order) * np.sin(sine_order * np.pi * x) * np.sinh(sine_order * np.pi * y) # This is the key: you have a 3D matrix here and with this summation, # you're basically squashing the entire 3D structure into a flat, 2D # representation. This 'squashing' is done by means of a sum. V = 2*np.sum(term, axis=0) x_axis = np.linspace(0,1,100) y_axis = np.linspace(0,1,100) plt.figure() plt.contour(x_axis, y_axis, V, 50) plt.show() which runs in less than a second on my system. Broadcasting becomes much more understandable if you take pen&paper and draw out the vectors that you are "broadcasting" as if you were constructing a building, from basic Tetris-blocks. These two versions are functionally the same, but one is completely vectorized, while the other uses python for-loops. As a new user to python and numpy, I definitely recommend reading through the broadcasting basics. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/26488550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cmake: boost dependencies and visual studio (or any platform with automatic link features) What is the recommended way to setup cmake boost dependencies with code that aims to be compiled with visual studio (or any other platform that features by default automatic linking on boost)? The problems comes at the link process, boost under visual studio automatically adds the library dependencies with the default naming convention, but you still have to manually add the LIBPATH, this under cmake is something like link_directories(${Boost_LIBRARY_DIRS}) but AFAIK using link_directories is discouraged. If I use target_link_libraries(foo ${Boost_LIBRARIES}) the problem is still there because this only adds additional absolute filenames and does not prevent the automatic linking process to add the relative libs and the linker misses to find them without the directory. So what is the best practise here, to disable the automatic link features or is there any other way? A: Disable (or don't enable - doesn't it require you to set a define?) the automatic linking.
{ "language": "en", "url": "https://stackoverflow.com/questions/26817921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: handle screen rotation with 3 fragments, every one with 3 different layouts I stuck in a little bit problem. I have situation like this: Login activity with one layout. Three Fragment every one with three different layouts, (Phone portrait, landscape, Tablet landscape) For better image, Fragments function is: login, register and confirmation code. What i want to achieve is, good screen rotate + after rotate open correct fragment with stored register data. I'm not sure if it will helpful but i use in project greenrobot event bus.What i need is suggestion how i could implement it correctly. Which is best approach etc. Thank you for your feedback! A: You should use quantifiers to load the great layout depending on your screen size and orientation. For example, activity_main.xml from layout-large-land and layout folders wont react the same. The first one will only be loaded if you are on a tablet and landscape oriented. The second one will be the default layout. You will need to use small, large, landscape (land) and portrait (default) quantifiers. About loading datas, you can use saveInstanceState bundle. Note that views with an id will automatically handle it.
{ "language": "en", "url": "https://stackoverflow.com/questions/38032760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AutoMapper and Windows Phone 7 Basics: * *Visual Studio 2010 *WP7 SDK 7.1 RC *AutoMapper added to project via NuGet *Ask for more! Problem: I'm getting the following error at runtime: Could not load type 'AutoMapper.Mapper' from assembly 'AutoMapper, Version=1.1.0.188, Culture=neutral, PublicKeyToken=BE96CD2C38EF1005'. There seems to be an open issue about this @ CodePlex, but i thought that i'd ask if anyone has found any solutions to this? As always, i'm more than happy to provide any additional info required! A: AutoMapper uses Castle Dynamic Proxy which requires Reflection.Emit which is not supported on the phone. If you want this you're going to need to look at building it all yourself. In terms of getting round the lack of reflection.Emit (if you really do need it) then you should look at using Mono.Cecil to provide this missing functionality. A: Seems that automapper is working on silverlight edition so possible WP7/WP8 compatibility coming soon. In the mean time there is a simple mapper library that you can use. It is very basic but probably meets most of your requirements for WP7 applications. // Configure LazyMapper Mapper.Create<SampleClass, SampleClassDto>(); // Perform mapping var dto = Mapper.Map<SampleClass, SampleClassDto>(new SampleClass { StringVal = "String1"}); Assert.AreEqual("String1",dto.StringVal); Download at http://lazycowprojects.tumblr.com/LazyMapper
{ "language": "en", "url": "https://stackoverflow.com/questions/7253995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error when accessing worklight server deployed on tomcat I deploy the war file and adapter file to the tomcat,everything is fine,but when I try access the worklight server,the request is [http://10.30.3.11:8080/nantian/apps/services/api/attendance/android/query] and the logcat appear this error [http://10.30.3.11:8080/nantian/apps/services/api/attendance/android/query]failure. state: 500, response: The server was unable to process the request from the application. Please try again later.[http://10.30.3.11:8080/nantian/apps/services/api/attendance/android/query]Cannot read property 'errors' of undefined and the tomcat appear the following error: java.lang.RuntimeException: Unique constrain: found 2 beans implementing inteface com.worklight.server.report.api.GadgetReportsService (in 4 spring application contexts). at com.worklight.server.bundle.api.ServiceManager.getServiceConsumer(ServiceManager.java:133) at com.worklight.core.bundle.CoreServiceManager.getGadgetsReportService(CoreServiceManager.java:47) at com.worklight.core.auth.impl.AuthenticationContext.logLoginActivity(AuthenticationContext.java:337) at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:495) at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:396) at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:373) at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:63) at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:162) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) I am sure that I just deploy one war file to the tomcat,but I have try deploying the war file again and again to test the app,Of course,undeploy the file before I deploy it.and the worklight server is 5.0.5,mysql 5.1.47,tomcat 7.0.37.Any help?thanks in advance. A: Is this an installation using IBM Installation Mananger? If you've used it to install Worklight on Tomcat then it has also deployed a worklight.war file during installation. Make sure you undeploy this .war file via the Tomcat Manager view (typically http://localhost:8080/manager). I would also go to the file system and make sure no other files remain (the .war file, worklight.home, ...). Next, deploy your own .war file (probably nantian.war or alike).
{ "language": "en", "url": "https://stackoverflow.com/questions/15893587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Store Boost Factor of Field in Index in lucene I am using lucene to search in the address book like product. I want to boost the search results according to some specific criteria. (e.g. Match in location field should have greater relevance than match in name of entity.) This is fixed criteria for my case. I am trying to store the boostfactor with Field by calling SetBoost() method while indexing. But then also result's score is not as expected. It's considering same boost value for every field. Can anybody suggest me where I am going wrong? Code I am using to build the index. Directory objIndexDirectory = FSDirectory.Open(new System.IO.DirectoryInfo(<PathOfIndexFolder>)); StandardAnalyzer objAnalyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); IndexWriter objWriter = new IndexWriter( objIndexDirectory, objAnalyzer, true, IndexWriter.MaxFieldLength.UNLIMITED); Document objDocument = new Document(); Field objName = new Field("Name", "John Doe", Field.Store.YES, Field.Index.ANALYZED); Field objLocation = new Field("Location", "NY", Field.Store.YES, Field.Index.NOT_ANALYZED); objLocation.SetBoost((2f); objDocument.Add(objName); objDocument.Add(objLocation); objWriter.AddDocument(objDocument); What I am trying to achieve is, Assuming there is three entries in index: * *John Doe, NY *John Foo, New Jercy *XYZ, NY In this case if the search query is "John NY", then result should have relevance like * *John Doe, NY *XYZ, NY *John Foo, New Jercy A: I can't figure out what you think is wrong with your approach, but here is the code I was using to test with: class Program { static void Main(string[] args) { RAMDirectory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer()); AddDocument(writer, "John Doe", "NY"); AddDocument(writer, "John Foo", "New Jersey"); AddDocument(writer, "XYZ", "NY"); writer.Commit(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("Name", "john")), BooleanClause.Occur.SHOULD); query.Add(new TermQuery(new Term("Location", "NY")), BooleanClause.Occur.SHOULD); IndexReader reader = writer.GetReader(); IndexSearcher searcher = new IndexSearcher(reader); var hits = searcher.Search(query, null, 10); for (int i = 0; i < hits.totalHits; i++) { Document doc = searcher.Doc(hits.scoreDocs[i].doc); var explain = searcher.Explain(query, hits.scoreDocs[i].doc); Console.WriteLine("{0} - {1} - {2}", hits.scoreDocs[i].score, doc.ToString(), explain.ToString()); } } private static void AddDocument(IndexWriter writer, string name, string address) { Document objDocument = new Document(); Field objName = new Field("Name", name, Field.Store.YES, Field.Index.ANALYZED); Field objLocation = new Field("Location", address, Field.Store.YES, Field.Index.NOT_ANALYZED); objLocation.SetBoost(2f); objDocument.Add(objName); objDocument.Add(objLocation); writer.AddDocument(objDocument); } } This code does return the results in the order you wish. In fact it returns them in that order for this set if you exclude the boost. I'm not an expert on Lucene scoring, but I believe this is because you are matching "NY" exactly for "XYZ, NY", and the "John" query is a partial match. You can read the details printed out via the Explain class. A: Have you tried MultiFieldQueryParser?
{ "language": "en", "url": "https://stackoverflow.com/questions/7304261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql query for joining three tables I have three tables Users ID || login || name || crypted_password || salt 2 || teacher1|| teacher1 || #@@EDGCH || SDWH@## Role(main) id||name 3 ||teacher Role_users id || role_id || user_id 2 || 3 || 2 now from these three tables i want to fetch crypted_password and salt value of user whose role=teacher. how can it be done!! A: You can use the join syntax to join tables according to the matching fields: SELECT crypted_password, salt FROM users JOIN role_users ON users.id = role_uses.user_id JOIN role ON role_users.role_id = role.id WHEN role.name = 'teacher' A: Join Like this SELECT U.* FROM USER U JOIN Role_Users RU ON RU.UserID = U.ID JOIN Role R ON R.ID = RU.Role_ID WHERE <Your Conditions here> A: select crypted_password,salt from Users U inner join Role_users RU on RU.user_id = U.ID inner join Role R on R.id = RU.role_id where R.name='teacher'
{ "language": "en", "url": "https://stackoverflow.com/questions/21398891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rewrite Rule Not Redirecting To The Specified File Recently I started working with .htaccess file to redirect API call to a specific file. However, even though my .htaccess file is working (tested it with just text on top of the file and I get "Internal Server Error") my rule is not working. Instead, Index.php is always read. The goal is, whenever the url ends with "myOwnAPI/" it takes you to the file "somefile.php". All files(index.php, somefile.php, .htaccess) leave in the same directory. The .htaccess file contains just one rule. Please help. httpd.conf file <Directory /> AllowOverride All Require all denied </Directory> AllowOverride All .htaccess file RewriteEngine on RewriteRule ^myOwnAPI/?$ somefile.php [NC,L] A: Every url start with a "/" so RewriteRule ^myOwnAPI/?$ somefile.php [NC,L] won't ever match. Change it to RewriteRule ^/myOwnAPI/? /somefile.php [NC,L] Moreover, please read the offical documentation https://httpd.apache.org/docs/2.4/rewrite/flags.html if you need to "pass" the parameters to the new url (flag QSA).
{ "language": "en", "url": "https://stackoverflow.com/questions/65899394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to provide collection name in nodejs/mongoose/ for $out I have a field called pin_count which has a count of another field called pins but due to broken logic the count of both fields mismatched, so I am writing migration script using migrate-mongo and below is what I did. But not sure why it's not working. I have tested below which is working fine: db.pins.aggregate([ { '$addFields': { 'pin_count': { '$size': '$pins'} }}, { "$out": "pins" } ]); But, the same in migrate-mongo()(https://www.npmjs.com/package/migrate-mongo) plugin isn't working. 'use strict'; const BPromise = require('bluebird'); const types = ['pins`]; module.exports = { up(db) { return BPromise.resolve(types).mapSeries(col => { return db.collection(col).aggregate([ { '$addFields': { 'pin_count': { '$size': '$pins'} }}, { "$out": col } ]); }); }, /** * No need to have down script since this is a correction of the data */ down: function (db) { } }; Document structure: {"_id" : ObjectId, "pins" : [ 'da', 'dal' ], "pin_count" : 4}
{ "language": "en", "url": "https://stackoverflow.com/questions/43733952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot get meteor.js to return mongo collection So I am trying to return a mongoDB database value to a template in my Meteor.js project. The code that I am using is below. Template.ResourceManager.helpers({ BoosterOneFuel : function(){ return resources.findOne({system : "booster1"}).fuel; } }); However, this always returns null. When I try to alert it, the alert also says that this value is null. Mongo can find it when I run this line in the console while running meteor mongo: db.Resources.findOne({system : "booster1"}).fuel; But meteor cannot. (This is on a localhost, so meteor mongo should affect meteor's database) I don't think its a problem with meteor loading before mongo does, because the following still doesn't work : if(resource.find({system : "booster1"})) alert(resources.findOne({system : "booster1"}).fuel); Anybody know whats going on here? Thanks in advance. A: Assuming the collection is actually called resources - i.e. you have something that looks like: resources = new Mongo.Collection('Resources'); Then it sounds like you just need to publish the documents to the client: server/publishers.js Meteor.publish('resources', function() { return resources.find(); }); client/subscriptions.js Meteor.subscribe('resources'); Of course the subscription could happen in your template or router instead of globally, but that's beyond the scope of this question. Also note you should add a guard to your helper. For example: Template.ResourceManager.helpers({ BoosterOneFuel : function() { var b1 = resources.findOne({system : "booster1"}); return b1 && b1.fuel; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/30090423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Spring MVC Frame work , How to iterate a list and create pins in bingmap? I'm using API version 8 and while running this code , I can able to get only one pin which has data in first object in the list. Here List has objects from object we have Latitude , Longitude , Title and Description. Iteration is done successfully but only first data is reflected in the BingMap. How can I get all the pins from the list and that reflected in BingMap. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script> <style> #myMap {; width: 800px; height: 600px; } #inputForm {; top: 200px; left: 250px; padding: 10px; background-color: white; border: 1px solid #000; border-radius: 10px; } </style> </head> <body> <div id="myMap" style=""></div> <script type='text/javascript'> var map, infobox, currentPushpin; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { credentials : 'bing map key', zoom : 0 }); document.getElementById('inputForm').style.display = ''; var lat = document.getElementById('lat').value; var lon = document.getElementById('lon').value; var center = new Microsoft.Maps.Location(lat, lon); //Create a pushpin. currentPushpin = new Microsoft.Maps.Pushpin(center); currentPushpin.metadata = { title : document.getElementById('title').value, description : document.getElementById('description').value }; //Add a click event to the pushpin. Microsoft.Maps.Events.addHandler(currentPushpin, 'click', pushpinClicked); //Add the pushpin to the map. map.entities.push(currentPushpin); } function pushpinClicked(e) { //Create an infobox that will render in the center of the map. infobox = new Microsoft.Maps.Infobox(e.target.getLocation(), { title : e.target.metadata.title, description : e.target.metadata.description }); //Assign the infobox to a map instance. infobox.setMap(map); } </script> <div id="inputForm" style="display: none;"> <TABLE> <c:forEach var="message" items="${list}"> <tr> <td><input id="lat" type="hidden" value="${message.lat}" /> <input id="lon" type="hidden" value="${message.lon}" /> <input id="title" type="hidden" value="${message.title}" /> <input id="description" type="hidden" value="${message.description}" /> </td> </tr> </c:forEach> </TABLE> </div> </body> </html> A: This isn't really a Bing Maps question, but more of a Spring MVC question. Looking at your HTML the first issue I see is that each item in your table has an ID assigned to them. ID's are meant to be unique in HTML, but with the code you have you will end up creating multiple elements with the same ID which is technically creating an invalid HTML and you will only be able to retrieve the last item by ID. Pulling your data from t a table like this likely isn't the best way to implement your application. There is likely some way to generate a JSON object using Spring MVC, however I'm not familiar with Spring MVC development. If you want to continue with the method you are using I would suggest changing the ID's to classes and then you will be able to retrieve the elements by class name. Here is an example worth trying. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script> <style> #myMap {; width: 800px; height: 600px; } #inputForm { padding: 10px; background-color: white; border: 1px solid #000; border-radius: 10px; } </style> </head> <body> <div id="myMap" style=""></div> <script type='text/javascript'> var map, infobox, currentPushpin; function GetMap() { map = new Microsoft.Maps.Map('#myMap', { credentials : 'bing map key', zoom : 0 }); //Create a reusable infobox infobox = new Microsoft.Maps.Infobox(map.getCenter(), {visible: false}); infobox.setMap(map); document.getElementById('inputForm').style.display = ''; var lats = document.getElementsByClassName('lat'); var lons = document.getElementsByClassName('lon'); var titles = document.getElementsByClassName('titles'); var descriptions = document.getElementsByClassName('description'); //The lats, lons, titles and descriptions values should be arrays of equal length. var loc, pin; for(var i = 0, len = lats.length; i < len; i++){ loc = new Microsoft.Maps.Location(parseFloat(lats[i].value), parseFloat(lons[i].value)); pin = pin.metadata = { title : titles[i].value, description : descriptions[i].value }; Microsoft.Maps.Events.addHandler(pin, 'click', pushpinClicked); map.entities.push(pin); } } function pushpinClicked(e) { //Create an infobox that will render in the center of the map. infobox.setOptions({ location: e.target.getLocation(), title : e.target.metadata.title, description : e.target.metadata.description, visible: true }); } </script> <div id="inputForm" style="display: none;"> <TABLE> <c:forEach var="message" items="${list}"> <tr> <td><input class="lat" type="hidden" value="${message.lat}" /> <input class="lon" type="hidden" value="${message.lon}" /> <input class="title" type="hidden" value="${message.title}" /> <input class="description" type="hidden" value="${message.description}" /> </td> </tr> </c:forEach> </TABLE> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/37813229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGL Red Book 8th - First Example gives black box (Ubuntu) After getting the first example program compiled from the 8th edition OpenGL Programming Guide after many alterations suggested by many sites, I am the proud owner of a black box - a vast improvement from the hours before, but it's embarrassing to admit that I've watch most of this with a debugger and unless something basic is wrong with the program, I have no clue where to look. Other OpenGL examples have run, but I'm trying to get the first example in the new book to run. My box: john@zerofluid:~/Downloads$ glxinfo | grep OpenGL OpenGL vendor string: NVIDIA Corporation OpenGL renderer string: GeForce GT 610/PCIe/SSE2 OpenGL version string: 4.3.0 NVIDIA 313.30 OpenGL shading language version string: 4.30 NVIDIA via Cg compiler OpenGL extensions: Linux zerofluid 3.8.0-26-generic #38-Ubuntu SMP Mon Jun 17 21:43:33 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux (latest 13.04 Ubuntu) I have a problem - it's way too much code to post here, but it is the first example of the book - as small as it gets and I have no idea of where the problem really is. It would be cool if someone actually wants to help - I'd feed it back to the author of the book. Yes, the LoadShader was found elsewhere and might be the problem, but it was supposed to be a solution. It's kind of hard to have any faith in the book when I can't get the first example to compile. It can be found here: https://github.com/kestess/opengl8thfirstexample.git A: it's way too much code to post here Not really. Try this: #include <GL/glew.h> #include <GL/freeglut.h> #include <vector> #include <iostream> struct Program { static GLuint Load( const char* vert, const char* geom, const char* frag ) { GLuint prog = glCreateProgram(); if( vert ) AttachShader( prog, GL_VERTEX_SHADER, vert ); if( geom ) AttachShader( prog, GL_GEOMETRY_SHADER, geom ); if( frag ) AttachShader( prog, GL_FRAGMENT_SHADER, frag ); glLinkProgram( prog ); CheckStatus( prog ); return prog; } private: static void CheckStatus( GLuint obj ) { GLint status = GL_FALSE, len = 10; if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status ); if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status ); if( status == GL_TRUE ) return; if( glIsShader(obj) ) glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len ); if( glIsProgram(obj) ) glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len ); std::vector< char > log( len, 'X' ); if( glIsShader(obj) ) glGetShaderInfoLog( obj, len, NULL, &log[0] ); if( glIsProgram(obj) ) glGetProgramInfoLog( obj, len, NULL, &log[0] ); std::cerr << &log[0] << std::endl; exit( -1 ); } static void AttachShader( GLuint program, GLenum type, const char* src ) { GLuint shader = glCreateShader( type ); glShaderSource( shader, 1, &src, NULL ); glCompileShader( shader ); CheckStatus( shader ); glAttachShader( program, shader ); glDeleteShader( shader ); } }; #define GLSL(version, shader) "#version " #version "\n" #shader const char* vert = GLSL ( 400 core, layout( location = 0 ) in vec4 vPosition; void main() { gl_Position = vPosition; } ); const char* frag = GLSL ( 400 core, out vec4 fColor; void main() { fColor = vec4( 0.0, 0.0, 1.0, 1.0 ); } ); enum VAO_IDs { Triangles, NumVAOs }; enum Buffer_IDs { ArrayBuffer, NumBuffers }; enum Attrib_IDs { vPosition = 0 }; GLuint VAOs[NumVAOs]; GLuint Buffers[NumBuffers]; const GLuint NumVertices = 6; void init(void) { glGenVertexArrays(NumVAOs, VAOs); glBindVertexArray(VAOs[Triangles]); GLfloat vertices[NumVertices][2] = { { -0.90, -0.90 }, // Triangle 1 { 0.85, -0.90 }, { -0.90, 0.85 }, { 0.90, -0.85 }, // Triangle 2 { 0.90, 0.90 }, { -0.85, 0.90 } }; glGenBuffers(NumBuffers, Buffers); glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); GLuint program = Program::Load( vert, NULL, frag ); glUseProgram(program); glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, (void*)(0) ); glEnableVertexAttribArray(vPosition); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(VAOs[Triangles]); glDrawArrays(GL_TRIANGLES, 0, NumVertices); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE ); glutInitWindowSize(512, 512); glutInitContextVersion(4, 0); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow(argv[0]); glewExperimental = GL_TRUE; if( GLEW_OK != glewInit() ) exit(EXIT_FAILURE); init(); glutDisplayFunc(display); glutMainLoop(); } No reason to request a 4.3 context if you're using #version 400 core.
{ "language": "en", "url": "https://stackoverflow.com/questions/17588737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to convert a WebView into an ImageView? i have a WebView of an html page which shows only one image http://www.google.fr/intl/en_com/images/srpr/logo1w.png webView = (WebView) findViewById(R.id.webView); webView.loadUrl("http://www.google.fr/intl/en_com/images/srpr/logo1w.png"); is there a simple way to turn it into an ImageView ? A: try this: webView.buildDrawingCache(); Bitmap bmap = imageView.getDrawingCache(); imageView.setImageBitmap(bmap); A: You can open an InputStream pointing to the image URL (using URLConnection), and create a Drawable from it using Drawable.createFromStream. You can then set the Drawable onto the ImageView. A: As per your above comment: ok you are right it must be easier getting the image directly... how do i do that ? Do i look in bitmap doc ?, i assume you want to load image from web and want to display the same in imageview, if this is the case then refer this to get exactly: How to display image from URL on Android A: Bitmap btmp = mwebview.getDrawingCache(true); this will return the Bitmap image in webview. And the bitmap can be set to image view by: imageView.setImageBitmap(bmap);
{ "language": "en", "url": "https://stackoverflow.com/questions/6747701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawing rectangle underneath PIXI.Text In a word game I am trying to draw score as white numbers above a blue (or red) rectangle: For example, in the above screenshot it is the number "13". Here is my entire class Score.js (with currently hardcoded WIDTH and HEIGHT): "use strict"; function Score(color) { PIXI.Container.call(this); this.interactive = false; this.buttonMode = false; this.visible = false; this.bgGraphics = new PIXI.Graphics(); this.bgGraphics.beginFill(color, 1); this.bgGraphics.drawRect(0, 0, Score.WIDTH, Score.HEIGHT); this.bgGraphics.endFill(); this.addChild(this.bgGraphics); this.text = new PIXI.Text('XXX', {font: '20px Arial', fill: 0xFFFFFF}); this.text.x = 1; this.text.y = 1; this.addChild(this.text); } Score.prototype = Object.create(PIXI.Container.prototype); Score.prototype.constructor = Score; Score.WIDTH = 36; Score.HEIGHT = 24; Score.prototype.setText = function(str) { this.text.text = str; } I wonder, how to modify my setText() function, so that a new rectangle is drawn on each call - as a bounding rectangle for the str argument? I have looked at the PIXI.Text.getBounds() method, but it returns a Matrix and not a Rectangle... A: I think you can just use this.text.width. This has historically had some bugs associated with it, but it should be working right in the latest version.
{ "language": "en", "url": "https://stackoverflow.com/questions/39055897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework SetInitializer and Seed Data Having difficulty figuring out why my database will not seed: Here is what I have in my Global.asax code: protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); Database.SetInitializer(new DataContextInitializer()); DataContext db = new DataContext(); db.Database.Initialize(true); WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true); } and here is the DataContextInitializer: public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext> { protected override void Seed(DataContext context) { if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true); WebSecurity.CreateUserAndAccount("admin", "12345"); } var roles = (SimpleRoleProvider)Roles.Provider; var membership = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("admin")) { roles.CreateRole("admin"); } if (membership.GetUser("admin", false) == null) { membership.CreateUserAndAccount("admin", "12345"); } if (!roles.GetRolesForUser("admin").Contains("admin")) { roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" }); } } } While debugging, the SqlException that I get is "There is already an object named ... in the database." Any idea why this would occur? A: These are the steps I took: * *Copied seed logic to the Migrations Configuration.cs file. *Excluded an old migration from the project *Within package console manager performed add-migration and gave it a name *Then ran update-database -verbose -force AFTER making sure that WebMatrix.WebData reference properties had 'CopyLocal = true' I hope this helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/27363174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JsDoc group multiple @typedef into one configuration file I have a project where I have to define multiple jsDoc's @typedef for describing multiple custom object types required by functions in the project. I'm wondering if I could group all these @typedef together into a single module/configuration file and reference them project-wide? Otherwise I would have to write these custom @typedef into multiple modules, and given that most of these have many properties this could create very big comment blocks that makes the modules ugly and difficult to read.
{ "language": "en", "url": "https://stackoverflow.com/questions/46158068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to run multiple methods parallely and get outputs from each of them in java I want to run three different methods in parallel to improve the performance in Java. Also I need to get the outputs from all the three of them. Below is the sample which I have tried. here, I'm not sure how to retrieve the returned string values. Please help me to add(concatenate all the three strings to total). import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class test { public static void main(String[] args) { String total = ""; Callable<String> callable1 = new Callable<String>() { @Override public String call() throws Exception { String t1 = ""; t1 = method1(); return t1; } }; Callable<String> callable2 = new Callable<String>() { @Override public String call() throws Exception { String t2 = method2(); return t2; } }; Callable<String> callable3 = new Callable<String>() { @Override public String call() throws Exception { String t3 = method3(); return t3; } }; List<Callable<String>> taskList = new ArrayList<Callable<String>>(); taskList.add(callable1); taskList.add(callable2); taskList.add(callable3); ExecutorService executor = Executors.newFixedThreadPool(3); try { executor.invokeAll(taskList); //total = ;(want to concatenate all the strings here). System.out.println(total); } catch (InterruptedException ie) { //do something if you care about interruption; } } public static String method1() { System.out.println("method1"); return "1"; } private static String method2() { System.out.println("method2"); return "2"; } private static String method3() { System.out.println("method3"); return "3"; } } A: As taskList is a List<Callable<String>>, executor.invokeAll(taskList) returns a List<Future<String>> containing a Future<String> corresponding to each task in taskList. You need to save that List<Future<String>> so that you can later get at the results of your tasks. Something like this: List<Future<String>> futureList = executor.invokeAll(tasklist); String result = futureList.get(0).get() + futureList.get(1).get() + futureList.get(2).get(); In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block. A: As you have very few number of task, you can create 3 CompletableFutures and stream over it and join it. CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> method1()); CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> method2()); CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> method3()); String concate = Stream.of(task1, task2, task3) .map(CompletableFuture::join) .reduce("", (s1, s2) -> s1 + s2); System.out.println(concate); A: Adding on top of @Govinda answer - You can create Stream of CompletableFutures by using the supplyAsync factory method and complete them by calling CompletableFuture::join and concat by calling Collectors.joining(). CompletableFuture<String> task1 = CompletableFuture.supplyAsync(Test::method1); CompletableFuture<String> task2 = CompletableFuture.supplyAsync(Test::method2); CompletableFuture<String> task3 = CompletableFuture.supplyAsync(Test::method3); String concat = Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining()); System.out.println(concat);
{ "language": "en", "url": "https://stackoverflow.com/questions/63433545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i add fabricjs-canvas objects in json format to a indexed array in php? I'm trying to make a database system to handle the saved fabricjs canvases. For every thing to work i need the canvas objects json=canvas.toDatalessJSON; // in javascript ...to be saved in php as .json file in a indexed array system that allows me to load and add more canvas objects or delete objects. The thing troubling me is how to actually structuring this. What i'm trying here is something like: ... The json structure i'm considering ... ["1"]{Object:.....} ["2"]{Object:.....} ["4"]{Object:.....} (["3"] deleted in this case) ... Trying to create in php ... $i="1"; $A=[]; $A[$i]=[]; array_push($A[$i],json_decode($json)); $newjson=json_encode($A); But this is obviously not the way to make it. Any ideas ? EDIT 1 Thank's for your answer @Michael. I ended up not using exactly what you propose. But i accept it as the answer that let my to a solution. In my solution i'm adding the index to the object, and unset the index when i'm going to use the object. Create: $dataA=array(); $dataB=json_decode($data,true); $dataB["index"]= $ThumbIndex; $dataA[]=&$dataB; $data=json_encode($dataA); file_put_contents($filename.'.json',$data); Add: $data0=file_get_contents($filename.'.json'); $dataA=json_decode($data0,true); $dataB=json_decode($data,true); $dataB["index"]= $ThumbIndex; $dataA[]=&$dataB; $data=json_encode($dataA); file_put_contents($filename.'.json',$data); A: Assuming you are trying to overwrite element "1" in your json object using php, try this: $newjson = json_decode($json, true); $newjson["1"] = Array(); $newjson = json_encode($newjson); If you want to add an element: $newjson = json_decode($json, true); $newjson[] = Array(); $newjson = json_encode($newjson);
{ "language": "en", "url": "https://stackoverflow.com/questions/39335362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Removing tuples that have the same pair of values from a list I want to remove all the tuples that have the same pair of values, e.g. [(1,1), (2,3), (2,2), (3,4)] I want [(2, 3), (3, 4)]. I am working in Haskell. This is what I tried: unique [] = [] unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[] And the output was: [(2,3)] I am confused on why (3, 4) did not appear. A: Because your else case says: unique [] = [] unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[] It thus says if fst x is not equal to snd x, then we return x : [] (or shorter [x]), and we are done. So it does not perform recursion on the rest of the list. We can solve this by adding recursion on the rest of the list, like: unique [] = [] unique (x:xs) = if fst x == snd x then unique xs else x : unique xs That being said, we can use a filter here, like: unique :: Eq a => [(a, a)] -> [(a, a)] unique = filter (\(x, y) -> x /= y) or even shorter: unique :: Eq a => [(a, a)] -> [(a, a)] unique = filter (uncurry (/=)) We thus retain all elements for which the first element x is not equal to the second element y.
{ "language": "en", "url": "https://stackoverflow.com/questions/54391239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: not a valid identifier - bash script error while execution I'm getting following error while I try to capture process ids in my shell script..... $bash ./restartjbossserver.sh ./restartjbossserver.sh: line 10: `i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}')': not a valid identifier And this is my script.... for i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}') do echo $i if [ $i != NULL ] then echo "Killing JBos Process.." kill -9 $i echo "Killed Joss Process..." fi done sleep 10s echo "Deleting JBoss Cache..." rm -rf /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/domain/tmp/* echo " Deleted JBoss Cache..." sleep 10s nohup /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/bin/domain.sh & >nohup.out A: The syntax for iterating over a list is for i in $( ... not for i=$( ... A: Have a look at the pkill and pgrep commands. You could just pkill jboss.
{ "language": "en", "url": "https://stackoverflow.com/questions/34065120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two function in a event on React-Native How to put two function in a event like onValueChange? I tried with onValueChange={(selected) => this.setState({selected}),this.state.eventOnChange}> A: What about: onValueChange={(selected) => { this.setState({selected}); this.state.eventOnChange(); }} A: Component.setState() is asynchronous and may be locked on the second call while it is still doing the first. Do the second call in a callback like this: onValueChange= { (selected) => { this.setState( {category:selected},() => {this.filter();} // Add Functions That's you want to call. ) } } A: Resolved with the following code: <TextInput style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1, }} onChangeText={(text) => this.setState({ text }, () => { this._onChangeText(); }) } autoCorrect={false} underlineColorAndroid='rgba(0,0,0,0)' value={this.state.text} /> Thanks to @pinewood. A: onValueChange={(itemValue, itemIndex) => this.setState({id: itemValue}),this.getOtherFunction }
{ "language": "en", "url": "https://stackoverflow.com/questions/36161344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why shell for expression cannot parse xargs parameter correctly I have a black list to save tag id list, e.g. 1-3,7-9, actually it represents 1,2,3,7,8,9. And could expand it by below shell for i in {1..3,7..9}; do for j in {$i}; do echo -n "$j,"; done; done 1,2,3,7,8,9 but first I should convert - to .. echo -n "1-3,7-9" | sed 's/-/../g' 1..3,7..9 then put it into for expression as a parameter echo -n "1-3,7-9" | sed 's/-/../g' | xargs -I @ for i in {@}; do for j in {$i}; do echo -n "$j,"; done; done zsh: parse error near `do' echo -n "1-3,7-9" | sed 's/-/../g' | xargs -I @ echo @ 1..3,7..9 but for expression cannot parse it correctly, why is so? A: Because you didn't do anything to stop the outermost shell from picking up the special keywords and characters ( do, for, $, etc ) that you mean to be run by xargs. xargs isn't a shell built-in; it gets the command line you want it to run for each element on stdin, from its arguments. just like any other program, if you want ; or any other sequence special to be bash in an argument, you need to somehow escape it. It seems like what you really want here, in my mind, is to invoke in a subshell a command ( your nested for loops ) for each input element. I've come up with this; it seems to to the job: echo -n "1-3,7-9" \ | sed 's/-/../g' \ | xargs -I @ \ bash -c "for i in {@}; do for j in {\$i}; do echo -n \"\$j,\"; done; done;" which gives: {1..3},{7..9}, A: Could use below shell to achieve this # Mac newline need special treatment echo "1-3,7-9" | sed -e 's/-/../g' -e $'s/,/\\\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash 1,2,3,7,8,9,% #Linux echo "1-3,7-9" | sed -e 's/-/../g' -e 's/,/\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash 1,2,3,7,8,9, but use this way is a little complicated maybe awk is more intuitive # awk echo "1-3,7-9,11,13-17" | awk '{n=split($0,a,","); for(i=1;i<=n;i++){m=split(a[i],a2,"-");for(j=a2[1];j<=a2[m];j++){print j}}}' | tr '\n' ',' 1,2,3,7,8,9,11,13,14,15,16,17,% A: echo -n "1-3,7-9" | perl -ne 's/-/../g;$,=",";print eval $_'
{ "language": "en", "url": "https://stackoverflow.com/questions/41294406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Exclude .csproj from VisualStudio 2012 .sln when using Mono Compiler I want to build my VisualStudio 2012 solution (.sln) with Mono, but it cannot compile projects that rely on VisualStudio-specific assemblies. E.g. xbuild ServerResource.sln ... HypervResourceControllerTest.cs(18,17): error CS0234: The type or namespace name `VisualStudio' does not exist in the namespace `Microsoft'. Are you missing an assembly reference? In this case, HypervResourceControllerTest.cs(18,17) is a reference to Visual Studio test tools: using Microsoft.VisualStudio.TestTools.UnitTesting; Since I don't need the testing environment to compile, can I tell the Mono compiler to bypass a specific project in a .sln? A: Create a new configuration, tell xbuild to use it: * *In Visual Studio, create a new configuration that excludes the projects you're not interested in. -(Build -> Configuration Manager..., select on the Active solution platform: drop down list) *Using the Configuration Manager, remove unwanted solutions from the configuration. *Next, close VisualStudio, which will save changes to the .sln and .csproj The .sln will record which projects are associated with the configuration. The .csproj will record the settings of the configuration, such as whether TRACE or DEBUG is defined. *Finally, when calling xbuild assign your configuration's name to the Configuration property. E.g. xbuild /p:Configuration="NoUnitTests" ServerResource.sln The above will build the projects associated with the NoUnitTests configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/18144563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is -c and nrow doing in this function? What is the purpose of -c and nrow in this function? bdf <- by(bdf, bdf$Serial_number, function(SN, k) { SN[-c(1:k, (nrow(SN)-k+1):nrow(SN)),] }, k = 10) by() splits the data frame bdf by the second argument Serial_number and applys the function function(SN, k) in the third argument. I don't understand the body of the function. A: c() creates a vector. - makes the numbers in the vector negative. The vector is in the "row" position of [, so it is omitting the rows from 1 to k, and from nrow(SN) - k + 1 to the end of the data frame. So it's chopping off the first k and last k - 1 rows of the data frame.
{ "language": "en", "url": "https://stackoverflow.com/questions/45306125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a dijit/Dialog for a specific HTML Div and use Div's elements as its content? Learning from http://dojotoolkit.org/reference-guide/1.9/dijit/Dialog.html, I know how to create dijit/Dialog widget programmatically and dynamically. But now I need to update the implementation of a form within our application which has many inputs. I want to create a dijit/Dialog for the specific DIV, and hope its div elements will be this dialog's elements. How is it possible? A: Please try the following code. This code, will remove your div node from it's parent. div will be moved into body tag. dojo.require("dijit.Dialog"); var myDialog=new dijit.Dialog( { title:"Dialog Title", content:dojo.byId("divNodeID") } ); myDialog.show(); Hope this helps you. Thanks! A: If you surround your with the HTML that will create a Dialog, it should work. For example, if your code is: <form> ... some HTML ... </form> then consider coding: <div data-dojo-type="dijit/Dialog" data-dojo-id="myDialog" title="MyTitle"> <form> ... some HTML ... </form> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/19760766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Rails gem for management of a "multi-visit pass" scenario? I'm a Rails noob. I'm looking to implement an application where users can purchase a multi-visit pass, then spend the credits week-by-week. For example, register and login, then purchase 10 visits at a gym - the system should list 10 remaining visits. Sign up to a class and 9 remaining visits are listed. When the credits are low, remind the user to top them up with another 10-visit pass, etc. I know I can use Devise and CanCan to manage the authentication and authorisation aspects. My question is whether there's already a gem to handle the management of the user's credits, or whether I'd need to write this from scratch. I've searched https://rubygems.org/gems/rails with no luck, but it's entirely possible I'm missing something obvious. A: I don't think there is a gem to do that, but it should be pretty simple to code: * *Add remaining_visits to your User model and table. *Do current_user.update(remaining_visits: current_user.remaining_visits+10) when a ticket is purchased. *Copy Devise sessions controller into app/controllers/devise/sessions_controller.rb. *Inside this controller, add this kind of code to create (where the user logs in): current_user.update(remaining_visits: current_user.remaining_visits-1). Note: Instead of copying Devise sessions controller you can just overwrite the create action.
{ "language": "en", "url": "https://stackoverflow.com/questions/28939773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Evaluate Matlab symbolic function I have a problem with symbolic functions. I am creating function of my own whose first argument is a string. Then I am converting that string to symbolic function: f = syms(func) Lets say my string is sin(x). So now I want to calculate it using subs. a = subs(f, 1) The result is sin(1) instead of number. For 0 it works and calculates correctly. What should I do to get the actual result, not only sin(1) or sin(2), etc.? A: You can use also use eval() to evaluate the function that you get by subs() function f=sin(x); a=eval(subs(f,1)); disp(a); a = 0.8415 A: syms x f = sin(x) ; then if you want to assign a value to x , e.g. pi/2 you can do the following: subs(f,x,pi/2) ans = 1 A: You can evaluate functions efficiently by using matlabFunction. syms s t x =[ 2 - 5*t - 2*s, 9*s + 12*t - 5, 7*s + 2*t - 1]; x=matlabFunction(x); then you can type x in the command window and make sure that the following appears: x x = @(s,t)[s.*-2.0-t.*5.0+2.0,s.*9.0+t.*1.2e1-5.0,s.*7.0+t.*2.0-1.0] you can see that your function is now defined by s and t. You can call this function by writing x(1,2) where s=1 and t=1. It should generate a value for you. Here are some things to consider: I don't know which is more accurate between this method and subs. The precision of different methods can vary. I don't know which would run faster if you were trying to generate enormous matrices. If you are not doing serious research or coding for speed then these things probably do not matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/20032441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }