text
stringlengths
15
59.8k
meta
dict
Q: Unit Testing a Java Chat Application I have developed a basic Chat application in Java. It consists of a server and multiple client. The server continually monitors for incoming messages and broadcasts them to all the clients. The client is made up of a Swing GUI with a text area (for messages sent by the server and other clients), a text field (to send Text messages) and a button (SEND). The client also continually monitors for incoming messages from other clients (via the Server). This is achieved with Threads and Event Listeners and the application works as expected. But, how do I go about unit testing my chat application? As the methods involve establishing a connection with the server and sending/receiving messages from the server, I am not sure if these methods should be unit tested. As per my understanding, Unit Testing shouldn't be done for tasks like connecting to a database or network. The few test cases that I could come up with are: 1) The max limit of the text field 2) Client can connect to the Server 3) Server can connect to the Client 4) Client can send message 5) Client can receive message 6) Server can send message 7) Server can receive message 8) Server can accept connections from multiple clients But, since most of the above methods involve some kind of network communication, I cannot perform unit testing. How should I go about unit testing my chat application? A: You should test the server and client in isolation. The way to do this is to use mock objects to mock either the server (for testing the client) or the client (for testing the server). A mock server would have the same methods as the real server, but you can decide what they return, i.e. simulate a connection error, a timeout, etc. Because it is a mock, you have full control over the functioning and you don't have to worry about actual connection errors. For Java, look at the Mockito mocking framework. A: Unit tests should be focused on exercising public APIs of each class you have built. However, things get a little tricky when dealing with Swing. Consider swingUnit for unit testing Swing components. A: Chapter 7 of Beautiful Testing describes testing an XMPP chat client. I recommend reading the chapter. The conclusion is illustrative and may provide some pointers for your chat application: In our quest to create beautiful tests for checking XMPP protocol implementations, we started out by testing simple request-response protocols at the lowest level: the data sent of the network stream. After discovering that this form of testing does not really scale well, we abstracted out the protocol to a higher level, up to the point where the tests used only high-level data structures. By testing protocol behavior on a high level, we were able to write tests for more complex protocols without compromising the clarity of the tests. For the most complex protocols, writing scenarios helped to cover all of the possible situations that can arise in a protocol session. Finally, since XMPP is an open protocol with many different implementations, it's very important to test an XMPP application on the real network, to ensure interoperability with other implementations. By running small test programs regularly, we were able to test the system in its entirety, and check whether our implementation of the protocol plays together nicely with other entities on the network.
{ "language": "en", "url": "https://stackoverflow.com/questions/2714795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Webkit browsers renders multi-column layout contents wrong I have a two-column layout in a bootstrap modal. There should be a bootstrap dropdown button as the content. Firefox renders it correctly but webkit based browsers fail to display the button correctly. The button does not get hover or click events since its position is rendered wrong. The question is: Am I doing something wrong? And is there a way to avoid this problem? The jsfiddle is here: http://jsfiddle.net/cenap/mtpj8god/4/ Full screen: http://jsfiddle.net/cenap/mtpj8god/4/embedded/result/ .multicolumn-container { width: 250px; height: 300px; -webkit-column-count: 2; /* Chrome, Safari, Opera */ -moz-column-count: 2; /* Firefox */ column-count: 2; -webkit-column-rule: 1px outset #CCC; /* Chrome, Safari, Opera */ -moz-column-rule: 1px outset #CCC; /* Firefox */ column-rule: 1px outset #CCC; overflow: auto; } .box { display: inline-block; width: 100px; min-height: 60px; text-align: center; border: 3px solid #666; padding: 10px; margin: 10px; } .err { font-size: 8px; color: red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <div class="container"> <div class="hero-unit"> <h1>Multicolumn in Bootstrap modal</h1> <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span> </button> <h4 class="modal-title">Modal title</h4> <div class='btn-group'> <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'><span class='caret'></span> </button> <ul class='dropdown-menu' role='menu' aria-labelledby='dLabel'> <li><a href='#'>Some Action</a> </li> <li class='divider'></li> <li><a href='#'>Some Other Action</a> </li> </ul> </div> <--- This works but the ones in columns below do not render correctly in webkit. </div> <div class="modal-body"> <div class="multicolumn-container"> <div class="box">1 <div class='btn-group'> <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'><span class='caret'></span> </button> <ul class='dropdown-menu' role='menu' aria-labelledby='dLabel'> <li><a href='#'>Some Action</a> </li> <li class='divider'></li> <li><a href='#'>Some Other Action</a> </li> </ul> </div> <span class="err">This is rendered wrong in webkit browsers</span> </div> <div class="box">2 <div class='btn-group'> <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'><span class='caret'></span> </button> <ul class='dropdown-menu' role='menu' aria-labelledby='dLabel'> <li><a href='#'>Some Action</a> </li> <li class='divider'></li> <li><a href='#'>Some Other Action</a> </li> </ul> </div> <span class="err">This is rendered wrong in webkit browsers</span> </div> <div class="box">3</div> <div class="box">4</div> <div class="box">5</div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> A: its working fine on Mac OSX webkit browsers - Chrome 37+ and Safari 7+, as on Firefox 30+. Please specify the browser version. A: It seems like there is a bug in Webkit and columns have been disabled for printing by its developer (Dave Hyatt) because page breaking couldn't be implemented properly. So the WebKit implementation have CSS3 columns turned off, but Firefox renders them correctly. I’ve tried making columns work for printing in Chrome, but still getting better results from Firefox. Also there are some posts by Dave Hyatt and one of them stating that “Columns are using the new pagination model, but printing isn't using it yet.”(https://bugs.webkit.org/show_bug.cgi?id=45993) A: I know the question was asked over a year ago, but I found this worked for me. -webkit-perspective: 1; See http://jsfiddle.net/mtpj8god/6/ More about it (from http://caniuse.com/#search=column-count, in known issues): Chrome is reported to incorrectly calculate the container height, and often breaks on margins, padding, and can display 1px of the next column at the bottom of the previous column. Part of these issues can be solved by adding -webkit-perspective:1; to the column container. This creates a new stacking context for the container, and apparently causes chrome to (re)calculate column layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/26044969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Data available for all views in codeigniter I have a variable, contaning data that should be present in the entire site. Instead of passing this data to each view of each controller, I was wondering if there is a way to make this data available for every view in the site. Pd. Storing this data as a session variable / ci session cookie is not an option. Thanks so much. A: Set in application/config/autoload.php $autoload['libraries'] = array('config_loader'); Create application/libraries/Config_loader.php defined('BASEPATH') OR exit('No direct script access allowed.'); class Config_loader { protected $CI; public function __construct() { $this->CI =& get_instance(); //read manual: create libraries $dataX = array(); // set here all your vars to views $dataX['titlePage'] = 'my app title'; $dataX['urlAssets'] = base_url().'assets/'; $dataX['urlBootstrap'] = $dataX['urlAssets'].'bootstrap-3.3.5-dist/'; $this->CI->load->vars($dataX); } } on your views <title><?php echo $titlePage; ?></title> <!-- Bootstrap core CSS --> <link href="<?php echo $urlBootstrap; ?>css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap theme --> <link href="<?php echo $urlBootstrap; ?>css/bootstrap-theme.min.css" rel="stylesheet"> A: Create a MY_Controller.php file and save it inside the application/core folder. In it, something like: class MY_Controller extends CI_Controller { public $site_data; function __construct() { parent::__construct(); $this->site_data = array('key' => 'value'); } } Throughout your controllers, views, $this->site_datais now available. Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller. A: You need to extend CI_Controller to create a Base Controller: https://www.codeigniter.com/user_guide/general/core_classes.html core/MY_Controller.php <?php class MY_Controller extend CI_Controller { public function __construct() { parent::__construct(); //get your data $global_data = array('some_var'=>'some_data'); //Send the data into the current view //http://ellislab.com/codeigniter/user-guide/libraries/loader.html $this->load->vars($global_data); } } controllers/welcome.php class Welcome extend MY_Controller { public function index() { $this->load->view('welcome'); } } views/welcome.php var_dump($some_var); Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var') A: If this is not an Variable(value keep changing) then I would suggest to create a constant in the constant.php file under the config directory in the apps directory, if it's an variable keep changing then I would suggest to create a custom controller in the core folder (if not exist, go ahead an create folder "core") under apps folder. Need to do some changes in other controller as mentioned here : extend your new controller with the "CI_Controller" class. Example open-php-tag if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class LD_Controller extends CI_Controller { } close-php-tag Here LD_ is my custom keyword, if you want to change you can change it in config.php file under line# 112 as shown here : $config['subclass_prefix'] = 'LD_'; and extend this class in all your controllers as "class Mynewclass extends LD_Controller.. And in LD_controller you've to write the method in which you want to define the variable/array of values & call that array in all over the application as shown here : defining variable : var $data = array(); Method to get values from db through the Model class: function getbooks() { $books = $this->mybooks_model->getbooks(); //array of records $this->data = array('books'=>$books); } to call this variable in the views : print_r($this->data['books']);); you will get all the array values... here we've to make sure atleast one "$data" parameter needs to be passed if not no problem you can define this $data param into the view as shown here : $this->load->view('mybookstore',$data); then it works absolutely fine,,, love to share... have a fun working friends A: you can use $this->load->vars('varname', $data);[ or load data at 1st view only] onse and use in any loaded views after this A: Use sessions in your controllers $this->session->set_userdata('data'); then display them in your view $this->session->userdata('data'); Or include a page in base view file e.g index.php include "page.php"; then in page.php, add $this->session->userdata('data'); to any element or div then this will show on all your views A: I read all answers, but imho the best approch is via hook: * *Create hook, let's get new messages for example: class NewMessages { public function contact() { // Get CI instance CI_Base::get_instance(); $CI = &get_instance(); // <-- this is contoller in the matter of fact $CI->load->database(); // Is there new messages? $CI->db->where(array('new' => 1)); $r = $CI->db->count_all_results('utf_contact_requests'); $CI->load->vars(array('new_message' => $r)); } } *Attach it to some of the flow point, for example on 'post_controller_constructor'. This way, it will be loaded every time any of your controller is instantiated. $hook['post_controller_constructor'][] = array( 'class' => 'NewMessages', 'function' => 'contact', 'filename' => 'NewMessages.php', 'filepath' => 'hooks', 'params' => array(), ); *Now, we can access to our variable $new_message in every view or template. As easy as that :) A: You could override the view loader with a MY_loader. I use it on a legacy system to add csrf tokens to the page where some of the forms in views don't use the builtin form generator. This way you don't have to retrospectively change all your controllers to call MY_Controller from CI_Controller. Save the below as application/core/MY_Loader.php <?php class MY_Loader extends CI_Loader { /** * View Loader * * Overides the core view function to add csrf token hash into every page. * * @author Tony Dunlop * * @param string $view View name * @param array $vars An associative array of data * to be extracted for use in the view * @param bool $return Whether to return the view output * or leave it to the Output class * @return object|string */ public function view($view, $vars = array(), $return = FALSE) { $CI =& get_instance(); $vars['csrf_token'] = $CI->security->get_csrf_hash(); return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/16171046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Based on todays date, how to get the date of the penultimate working day? I try to figure out, how I can get the penultimate workingday from todays date. In my query, I would like to add an where clause where a specific date is <= today´s date minus 2 working days. Like: SELECT SalesAmount ,SalesDate FROM mytable t JOIN D_Calendar c ON t.Date = c.CAL_DATE WHERE SalesDate <= GETDATE()- 2 workingdays I have a calendar table with a column "isworkingDay" in my database and I think i have to use this but i don´t know how?! Structure of this table is like: CAL_DATE DayIsWorkDay 2022-07-28 1 2022-07-29 1 2022-07-30 0 2022-07-31 0 2022-08-01 1 One example: Today is Monday, August 01, 2022. So based on today, I need to get Thursday, July 28 2022. My desired result in the where clause should get me something like this: where SalesDate<= Getdate() minus 2 workingdays Thanks for your ideas! A: You could use something like this: SELECT t.SalesDate, PreviousWorkingDay = d.CAL_DATE FROM mytable t CROSS APPLY ( SELECT c.CAL_DATE FROM D_Calendar AS c WHERE c.CAL_DATE < t.SalesDate AND c.DayIsWorkDay = 1 ORDER BY c.CAL_DATE DESC OFFSET 1 ROWS FETCH NEXT 1 ROW ONLY ) AS d; It uses OFFSET 1 ROWS within the CROSS APPLY to get the penultimate working day A: This is how i implemented the idea from @SMor: SELECT SalesAmount ,SalesDate FROM mytable t JOIN D_Calendar c ON t.Date = c.CAL_DATE WHERE SalesDate <= (SELECT MIN(t1.CAL_DATE) as MinDate FROM (SELECT TOP 2 [CAL_DATE] FROM [DWH_PROD].[cbi].[D_Calendar] WHERE CAL_DAYISWORKDAY = 1 AND CAL_DATE < DATEADD(dd,0,DATEDIFF(dd,0,GETDATE())) ORDER BY CAL_DATE DESC ) t1) Thank you for your ideas and recommendations! A: You can use a ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) getting get the top 2 rows then take the row with number 2. Example: -- setup Declare @D_Calendar as Table (CAL_DATE date, DayIsWorkDay bit) insert into @D_Calendar values('2022-07-27', 1) insert into @D_Calendar values('2022-07-28', 1) insert into @D_Calendar values('2022-07-29', 1) insert into @D_Calendar values('2022-07-30', 0) insert into @D_Calendar values('2022-07-31', 0) insert into @D_Calendar values('2022-08-01', 1) Declare @RefDate DateTime = '2022-08-01 10:00' -- example query Select CAL_DATE From (Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE from @D_Calendar where DayIsWorkDay = 1 and CAL_DATE < Cast(@RefDate as Date)) as Data Where BusinessDaysBack = 2 From there you can plug that into your where clause to get : SELECT SalesAmount ,SalesDate FROM mytable t WHERE SalesDate <= (Select CAL_DATE From (Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE from D_Calendar where DayIsWorkDay = 1 and CAL_DATE < Cast(getdate() as Date)) as Data Where BusinessDaysBack = 2) Change the 2 to 3 to go three days back etc
{ "language": "en", "url": "https://stackoverflow.com/questions/73195169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using iText and C#, create named destinations at exact same page coordinate as each PDF bookmark I can iterate through all the bookmarks in my PDF file and create named destinations but positioned at the top of the same page as each bookmark and not at the same coordinates. The code below works but how do I set the named destination to also be at the exact same page coordinates as the bookmark (there can be a few bookmarks per page): string file = @"C:\MyDocs\MyDoc1.pdf"; string newFile = @"C:\MyDocs\MyDoc2.pdf"; PdfDocument pdf = new PdfDocument(new PdfReader(file), new PdfWriter(newFile)); // Get the bookmarks PdfOutline outlines = pdf.GetOutlines(false); List<PdfOutline> bookmarks = outlines.GetAllChildren().ToList<PdfOutline>(); PdfNameTree destsTree = pdf.GetCatalog().GetNameTree(PdfName.Dests); IDictionary<String, PdfObject> Tnames = destsTree.GetNames(); foreach (var item in bookmarks) { string title = item.GetTitle(); int pgn = pdf.GetPageNumber((PdfDictionary)item.GetDestination().GetDestinationPage(Tnames)); PdfPage pdfPage = pdf.GetPage(pgn); iText.Kernel.Geom.Rectangle pageRect = pdfPage.GetPageSize(); float getLeft = pageRect.GetLeft(); float getTop = pageRect.GetTop(); PdfExplicitDestination destObj = PdfExplicitDestination.CreateXYZ(pdfPage, getLeft, getTop, 1); pdf.AddNamedDestination(title, destObj.GetPdfObject()); } pdf.Close();
{ "language": "en", "url": "https://stackoverflow.com/questions/71704881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Groovy AST INSTRUCTION_SELECTION phase vs SEMANTIC_ANALYSIS This piece of code works in my visitor in the SEMANTIC_ANALYSIS phase but not in the INSTRUCTION_SELECTION phase. It looks like I am not able to use the constructor call. If I change the constructor instead to Arrays.asList() it seems to compile. Any help is appreciated val codeBlock = GeneralUtils.block() // Declare the futures list val arrayListNode = ClassHelper.make(ArrayList::class.java) val variable = "myVariable" val variableDeclaration = GeneralUtils.varX(variable, arrayListNode) val asListExpression = GeneralUtils.ctorX(arrayListNode) val variableStmt = GeneralUtils.declS(variableDeclaration, asListExpression) codeBlock.addStatement(variableStmt) // // Set the codeBlock back to the closure closure.code = codeBlock In the instruction selection phase, the error I get is java.lang.ArrayIndexOutOfBoundsException: size==0 at org.codehaus.groovy.classgen.asm.OperandStack.getTopOperand(OperandStack.java:672) at org.codehaus.groovy.classgen.asm.BinaryExpressionHelper.evaluateEqual(BinaryExpressionHelper.java:318) at org.codehaus.groovy.classgen.asm.sc.StaticTypesBinaryExpressionMultiTypeDispatcher.evaluateEqual(StaticTypesBinaryExpressionMultiTypeDispatcher.java:142) at org.codehaus.groovy.classgen.AsmClassGenerator.visitDeclarationExpression(AsmClassGenerator.java:637) at org.codehaus.groovy.ast.expr.DeclarationExpression.visit(DeclarationExpression.java:89) A: This code seemed to work. // Declare the futures list val arrayListNode = ClassHelper.make(ArrayList::class.java) val variable = "myVariable" val variableDeclaration = GeneralUtils.varX(variable, arrayListNode) val asListExpression = GeneralUtils.ctorX(arrayListNode) // Look for the arraylist constructor in the node val arrayNodeConstructorMethod = arrayListNode.getDeclaredConstructor(arrayOf()) asListExpression.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, arrayNodeConstructorMethod) val variableStmt = GeneralUtils.declS(variableDeclaration, asListExpression) codeBlock.addStatement(variableStmt) // // Set the codeBlock back to the closure closure.code = codeBlock
{ "language": "en", "url": "https://stackoverflow.com/questions/53879768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract a portion of a url I am trying to extract a portion of a URL using regex. An example of my url would be: http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food Using php, how could I extract the data in the q variable or the sourceid variable? A: Don't use a regex for this. Instead, use parse_url() and parse_str(). $params = array(); $url= "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food"; $url_query = parse_url($url, PHP_URL_QUERY); parse_str($url_query, $params); echo $params['q']; // Outputs food Demo A: A perfect tutorial for what you're trying to accomplish: $parts = parse_url('http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food'); parse_str($parts['query'], $query); echo $query['q'];
{ "language": "en", "url": "https://stackoverflow.com/questions/11420093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mixing words from wordlist and making new wordlist I am trying to do mixing of words from wordlist and creating newwordlist this is my wordlist Nice have fun its cool _ make quote backtick _ jobs public over what i am trying to do is mixing those words and want output like this. Nice make jobs _ have fun quote public _ its cool backtick over this is what i've tried with open('wordlist.txt') as f: wordlist= f.read().splitlines() newwordlist = [] for x in range(2): newx = wordlist[x] newwordlist.append(newx) A: You can just basically "transpose" them with zip: with open('wordlist.txt','r') as f: wordlist= list(zip(*[i.splitlines() for i in f.read().split('_')])) If there are no underlines: with open('wordlist.txt','r') as f: wordlist= list(zip(*[f.readlines()[i:i+3] for i in range(0,len(f.readlines()),3)])) And do new file: ... with open('wordlist2.txt','w') as f2: f2.write('_'.join(['\n'.join(i) for i in wordlist])) A: With underscores you could use the concept proposed by U9-Forward with open('wordlist.txt','r') as f: wordlist = list(zip(*[i.splitlines() for i in f.read().split('_\n')])) with open('newwordlist.txt','w') as f2: f2.write('\n_\n'.join(['\n'.join(i) for i in wordlist])) U9 was really close, just the newlines became issues If you have just have a list of words and no underscores, you could use random.shuffle. from random import shuffle with open('wordlist.txt', 'r') as f: words = f.read().splitlines() shuffle(words) # shuffles words randomly with open('newwordlist.txt', 'w') as f2: f2.write('\n'.join(words))
{ "language": "en", "url": "https://stackoverflow.com/questions/53115307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can I run a VBScript script from inside Visual Studio 2008? I'm writing pop-up's for a website (please don't get angry. It's an internal application that shows energy usage for different buildings and the specification is to alert the users every time they log on) and I have a VBScript script that will run at the end of the a Windows user's logon script. Is there a command to run the script from within Visual Studio rather than having to drop to Windows Explorer. It's only a tiny thing but if I don't ask I'll never know! I have VBScript script running at the end of some local builds and such but I'd like to be able to select the file, right-click, then run. But I don't seem to be able to. A: I don't believe so, but am hoping I am proved wrong. A: To do what you want you need to extend the Visual Studio development environment by using an add-in. I don't know if the add-in you need already exists, but it is possible to write your own. There is a list of popular add-ins here on Stack Overflow. A: Try running cscript //X yourvbscript.vbs - it'll promt you for the debugging application. Select Visual Studio if have it installed. Can do the same thing from VS but I don't remember at this moment ... A: You can create a macro that runs your script, either by invoking cscript/wscript or by using the scripting COM-component. You can then add the macro to the context menu. Another way is to add it as en external tool on the tool menu.
{ "language": "en", "url": "https://stackoverflow.com/questions/1255058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between User and System Installer of Visual Studio Code Visual Studio code offers User and System Installer but I have not found any description about the differences between these two options. Could someone please shed a light on this for me? A: User setup for Windows Announced last release, the user setup package for Windows is now available on stable. Installing the user setup does not require Administrator privileges as the location will be under your user Local AppData (LOCALAPPDATA) folder. User setup also provides a smoother background update experience. Download User Setup If you are a current user of the system-wide Windows setup, you will be prompted to install user setup, which we recommend using from now on. Don't worry, all your settings and extensions will be kept during the transition. During installation, you will also be prompted to uninstall the system-wide setup. Reference: https://code.visualstudio.com/updates/v1_26#_user-setup-for-windows A: I installed the user version side-by-side with the system version with no problems. The basic differences between the two is that the system version installs on the file system like every other app. The user install is basically a click-once (or web installer) version that installs in the User folder of the machine. The settings made to VS Code in the system version save for Everybody on the computer and the user version the settings are only for the user. I find that the behavior of the user version is a bit annoying for me because I have reasons to want to open multiple copies of VS Code at the same time and the user version only allows one instance. Otherwise, there's not really anything different between the two as far as I can tell. A: Many companies (like mine) dont allow Admin privileges, I think that's the main point so you can still install VSC with the user installer A: After user version of Visual Studio Code is downloaded, make cmd in the download folder and run a command below, replacing the correct version in the VS ode installation file name: runas /trustlevel:0x20000 ./VSCodeUserSetup-x64-1.74.3.exe start the command below in order to check which trust levels are supported: runas /showtrustlevels
{ "language": "en", "url": "https://stackoverflow.com/questions/51832451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "153" }
Q: Changing locale not working after `onResume` method? I have an app that is (more or less) translated in other languages. For this I used locale and for saving the language preferred by the user I used SharedPreferences. Using this I managed to load the prefered language on any/every activity inside the app. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pick); findViewById(R.id.flagcollection).setVisibility(View.GONE); findViewById(R.id.worldmapswitch) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (flagWorld) { // means true findViewById(R.id.flagcollection).setVisibility(View.GONE); flagWorld = false; } else { findViewById(R.id.flagcollection).setVisibility(View.VISIBLE); flagWorld = true; } } }); preferences = getSharedPreferences("settings_values", MODE_PRIVATE); String SavedLocaleLang = preferences.getString("LocalLang", null); Locale locale = new Locale(SavedLocaleLang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); .... The problem is that if for whatever reason I leave the app (not exiting/ending activity), after a while when I return to the app, it runs using the PHONE'S default language and not the saved value for locale. Then, after reading numerous posts regarding the miracles of onResume, combined with my java no-skills I tried this : @Override public void onResume(){ super.onResume(); // put your code here... preferences = getSharedPreferences("settings_values", MODE_PRIVATE); String SavedLocaleLang = preferences.getString("LocalLang", null); Locale locale = new Locale(SavedLocaleLang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); } I thought that I have solved my problem, but after testing the result in less than 1 hour I realized that I've done nothing (at least nothing good). Somewhere I'm doing something wrong. If anyone has the skills, the patience and much, much good will, PLEASE help me understand what and where I am doing wrong. Any help will be greatly appreciated! No sarcasm though, please. There I'm doing just fine :P THANK YOU !!! P.S. User "Cochi" requested the code for saving the locale in Prefereces ... so here you go : findViewById(R.id.flaghungary) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String localeHU = "hu"; SharedPreferences settings = getSharedPreferences("settings_values", MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString("LocalLang", localeHU); editor.apply(); Locale locale = new Locale("hu"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); setContentView(R.layout.activity_pick); Context context = getApplicationContext(); Toast.makeText(context, "Magyar nyelv kiválasztva", Toast.LENGTH_SHORT).show(); recreate(); } }); A: Try putting that code inside onCreate, before the setContentView : @Override protected void onCreate(@Nullable Bundle savedInstanceState) { String SavedLocaleLang = preferences.getString("LocalLang", null); Locale locale = new Locale(SavedLocaleLang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
{ "language": "en", "url": "https://stackoverflow.com/questions/42821852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to improve the binarization of Text document ( Fill missing pixels of alphabets, reduce noise etc) What (and how) can be done (like where exactly to plcae Erosion, Dialiation, Opening, Closing etc) so that the words are not cut / invisible in between (maybe some other binarization technique which works on most of the cases or some parameter tuning) I have this code to binarize / Threshold the image. It works fine on a wide range of images except a couple of things and the major problem being that it leads to loss of info due to some brightness and other factors. Some of the words are not readable or gets broken. Below is the code to threshold / Binarize along with some of the images. Also, here is the link to 200 sample and resulting images import cv2 import skimage.filters as filters def convert(path): img = cv2.imread(path) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) smooth = cv2.GaussianBlur(gray, (103,103), 0) division = cv2.divide(gray, smooth, scale=255) sharp = filters.unsharp_mask(division, radius=1.5, amount=5, multichannel=False, preserve_range=False) # High Radius increase the density or surrounding pixels making it dense sharp = (255*sharp).clip(0,255).astype(np.uint8) thresh = cv2.threshold(sharp, 0, 255, cv2.THRESH_OTSU )[1] return thresh A: You can test several types of histogram equalization techniques. I've scripted down two examples of histogram equalization with your above photo. You can than later keep preprocessing those raw results for better outcomes depending on your data variance. import cv2 import matplotlib.pyplot as plt # read a image using imread img = cv2.imread("test.png") img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # creating a Histograms Equalization equ = cv2.equalizeHist(img_gray) # clahe clahe = cv2.createCLAHE(clipLimit=10.0, tileGridSize=(100,100)) cl = clahe.apply(img_gray) # show image input vs output plt.figure(figsize=(10,10)) plt.imshow(img) plt.title("original image") plt.show() plt.figure(figsize=(10,10)) plt.imshow(equ, cmap='gray', vmin=0, vmax=255) plt.title("histogram equalization") plt.show() plt.figure(figsize=(10,10)) plt.imshow(cl, cmap='gray', vmin=0, vmax=255) plt.title("CLAHE") plt.show() The results are:
{ "language": "en", "url": "https://stackoverflow.com/questions/69003595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieving elements from a data.frame when the addressed column is misspelled I stumbled on some strange behavior of R when working with a data.frame called DS.inp. In this data.frame I have a column called "DATE_EGFR_CREAT". When I wanted to print the elements of this column in the console to see what data this column contained, I accidentally used a misspelled version of this column name: "DS.inp$DATE_EGFR". Still, R provided the results from "DATE_EGFR_CREAT" in the console. This was rather unexpected, as there is no column called "DATE_EGFR" in the data.frame DS.inp. The following code was used to verify whether the misspelled column was in my data.frame originally: > "DATE_EGFR" %in% names(DS.inp) FALSE Knowing what is causing this behavior in R might have a lot of impact on my work. Does someone know what is going on here?
{ "language": "en", "url": "https://stackoverflow.com/questions/64721585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where is encapsulated the operators between integers? I need to group some operators to be able to call them by index and to do that I need to know where they belong. When 1 + 1 is executed there is clearly an operator+(int, int) which must belong to a class that has some relation with ints -maybe a template parameter?- I tried accessing such function with functional header file included using int::operator+ with no luck. If something like [ the_class_i_need::operator+, the_class_i_need::operator-, ... ] could be achieved or something alike, that'd perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/43609500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filtering Pandas Dataframe by the ending of the string I have a data frame called df and in one column 'Properties' I have listed properties of some product. These properties are a single sentence. Some of them have the same ending i.e. stock. I was trying to do something like: df.loc[df['Properties'][-6:] == 'stock'] to filter this values but it was not working. I'd like to implement functionality where I can filter data frame by its last 5 characters. Do you have any ideas how to do this task? A: Try this: df = df[df['Properties'].str.endswith('stock')] If you want to try what you were trying, this would work: df = df[df['Properties'].str[-5:]=='stock']
{ "language": "en", "url": "https://stackoverflow.com/questions/62220132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to control order of replication? I have a huge master CouchDB database and slave read-only CouchDB database, that synchronizes with master database. Because rate of changes is quick, and channel between servers is slow and unstable, I want to set order/priority to define what documents come first. I need to ensure that the documents with highest priority are definitely of the latest version, and I can ignore documents in the end of list. SORTING, not FILTERING If it is not possible, what solution could be? Resource I have already looked at: http://wiki.apache.org/couchdb/Replication http://couchapp.org/page/index UPDATE: the master database is actually Node.js NPM registry, and order is list of Most Depended-upon Packages. I am trying to make proxy, because cloning 50G always fails after a while. But the fact is "we don't need 90% of those modules, but quick & reliable access to those we depend on." A: CouchDB, out of the box, does not provide you with any options to control the order of replication. I'm guessing you could piece something together if you keep documents with different priorities in different databases on the master, though. Then, you could replicate the high-priority master database into the slave database first, replicate lower-priority databases after that, etc. A: The short answer is no. The long answer is that CouchDB provides ACID guarantees at the individual document level only, by design. The replicator will update each document atomically when it replicates (as can anyone, the replicator is just using the public API) but does not guarantee ordering, this is mostly because it uses multiple http connections to improve throughput. You can configure that down to 1 if you like and you'll get better ordering, but it's not a panacea. After the bigcouch merge, all bets are off, there will be multiple sources and multiple targets with no imposed total order. A: You could set up filtered replication or named document replication: * *http://wiki.apache.org/couchdb/Replication#Filtered_Replication *http://wiki.apache.org/couchdb/Replication#Named_Document_Replication Both of these are alternatives to replicating an entire database. You could do the replication in smaller batch sizes, and order the batches to match your priorities.
{ "language": "en", "url": "https://stackoverflow.com/questions/15285520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: component moves to original position when window is resized I have a draggable JPanel that is added into a JFrame with the NetBeans IDE JFrame Form editor. When I run the program and drag the card somewhere other than the original position and resize the JFrame, the JPanel is returned to its original position. Before (When program first run): Moved Card: Resized Window: I'm at a loss to understand why this happens and how to prevent it. My Frame: package cards; import cards.cards.*; /** * * @author Nicki */ public class ImgTest extends javax.swing.JFrame { /** * Creates new form ImgTest */ public ImgTest() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { card2 = new cards.cards.Card(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Imgtest"); setMinimumSize(new java.awt.Dimension(250, 250)); setPreferredSize(new java.awt.Dimension(250, 250)); javax.swing.GroupLayout card2Layout = new javax.swing.GroupLayout(card2); card2.setLayout(card2Layout); card2Layout.setHorizontalGroup( card2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 71, Short.MAX_VALUE) ); card2Layout.setVerticalGroup( card2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(card2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(158, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(card2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(133, Short.MAX_VALUE)) ); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]){ /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ImgTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ImgTest().setVisible(true); } }); } // Variables declaration - do not modify private cards.cards.Card card2; // End of variables declaration } My card panel: package cards.cards; import cards.images.CardImageProvider; import java.awt.Canvas; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.JPanel; /** * * @author Nicki */ public class Card extends JPanel { private Image cardImg; private Cards card; private volatile int draggedAtX, draggedAtY; public Card(Cards c) { this.setSize(71, 96); card = c; cardImg = CardImageProvider.getCardImage(c); addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ draggedAtX = e.getX(); draggedAtY = e.getY(); } }); addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e){ setLocation(e.getX() - draggedAtX + getLocation().x, e.getY() - draggedAtY + getLocation().y); repaint(); } }); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } public Card(){ this(Unknown.UNKNOWN); } @Override public void paintComponent(Graphics g) { this.setSize(71, 96); g.drawImage(cardImg, 0, 0, this); } public void setCard(Cards c) { card = c; cardImg = CardImageProvider.getCardImage(c); repaint(); } public Cards getCard() { return card; } } I would like to know how to prevent the card moving back to its first position. Thanks in advance. A: By defaults an IDE will use a layout manager to position components on the frame. When you drag the panel you are manually setting the location of the panel and overriding the location determined by the layout manager. However, when you resize the frame the layout manager code is again executed and the panel is set back to its original position. You need to change your code so that the parent panel of the panel you drag uses a "null layout". However, when you do this you are now responsible for setting the size and location of the panel.
{ "language": "en", "url": "https://stackoverflow.com/questions/20940913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MATLAB insert character separated with space from GUI I need to input characters from a GUI but they need to be separated by spaces. Every time a new character is added, it should be appended to the existing array. For example: * *user enters 'a', the content of array is 'a' *if user enters 'b' next, the content of array is 'a b' Edit 1 These lines of code should be inside the pushbutton1_callback function, so whenever the user presses the button, a new character should be added to static text; separated by a space. Edit 2 My only line of code in here is: letter = get(handles.edit1, 'string') A: Without details I can provide a conceptual solution. Initialize the variable that holds the text to: txt = ''; Then the callback will do: txt = strtrim(sprintf('%s %s',txt, get(handleToTextBox,'String'))); A: letter = get(handles.edit1, 'string'); global txt; txt=[txt letter]; txt=[txt ' ']; set(handles.text1, 'string', txt); That's how I solved it.
{ "language": "en", "url": "https://stackoverflow.com/questions/16719389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How would I write this as another form of PHP Hey I had a question I can not figure out how to write this code: <div><?=$rs['username']." ~ ".$rs["webcam_status"]?></div> When I have my code already set up as only 1 php markup, the code: <?php echo" <!-- header --> "; include "../../access/$template/header.php"; echo " <!-- content --> <div><?=$rs['username']." ~ ".$rs["webcam_status"]?></div> <!-- content --> <!--footer--> "; include "../../access/$template/footer.php"; echo " "; ?> I know how to write it differently, does anybody know how to write it that way? A: You can't cause PHP to output PHP and then parse that PHP and execute it. Add your data via string concatenation instead. Better yet: Geek echo statements to a minimum, and drop out of PHP mode with <? when you are just outputting static data. A: <?php echo" <!-- header --> "; include "../../access/$template/header.php"; echo " <!-- content --> <div>".$rs['username']." ~ ".$rs["webcam_status"]."</div> <!-- content --> <!--footer--> "; include "../../access/$template/footer.php"; echo " "; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/18687510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Remove all CSS Stylesheets from a page I want to show a page without any css applied. Is it somehow possible to add a jquery switch inside the page to disable all stylesheets? Reason: I want to show a client the importance of Design by giving him the opportunity to disable the css styles of his site. It is way more convincing when he can trigger it on his own :) A: If you want it to fire after a click: $(".element").click(function(){ $("link[rel='stylesheet']").remove(); }); or at the beginning: $(document).ready(function(){ $("link[rel='stylesheet']").remove(); }); A: Try this: $('link[rel="stylesheet"]').remove(); This will remove all stylesheets (all the styles applies due to those stylesheets) from the page. A: Just spent few mintues to draft one (function(f,a,s,x){ x=$(a);x.map(function(i,o){o=$(o);o.data(s+s,o.attr(s));o.removeAttr(s)}); $(s+',link[rel='+s+'sheet]').appendTo(f); setTimeout(function(){ $(a,f).appendTo('head'); x.map(function(i,o){o=$(o);o.attr(s,o.data(s+s))}) },999); })($('<i>'),'*','style'); A: Disable all StyleSheetList.prototype.forEach=Array.prototype.forEach; // *Note document.styleSheets.forEach((ss)=>ss.disabled=true); or (Disable All) for(styleSheet of document.styleSheets){ styleSheet.disabled=true; } or (Remove all) StyleSheetList.prototype.forEach=Array.prototype.forEach; document.styleSheets.forEach((ss)=>ss.ownerNode.parentNode.removeChild(ss.ownerNode)); or (Remove all) for(styleSheet of document.styleSheets){ styleSheet.ownerNode.parentNode.removeChild(styleSheet.ownerNode); } *Note: If you don't want to change the prototype, you can invoke it like this: Array.prototype.forEach.apply(document.styleSheets,[(ss)=>ss.disabled=true]) A: Try this $('link[rel="stylesheet"]').remove(); A: Place this on document ready: $('link[rel=stylesheet]').remove(); Or bind it to a button. A: A rough, dirty and brute approach: document.querySelector("head").remove(); A bookmarklet version of the same code that you can paste as the URL of a bookmark. You can also paste it into the address bar (for security reasons, when you paste the text, chrome/firefox remove the javascript: bit at the beginning so you'll need to type that by hand): javascript:(function(){document.querySelector("head").remove();})() A: Use below code to remove all kinds of styles, inline, internal, external. let elements=document.querySelectorAll("*"); elements.forEach(el=>{ if(el.tagName==="LINK" || el.tagName==="STYLE") el.remove(); else el.removeAttribute("style"); }); Thank me later! ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/14629593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: gurobipy.GurobiError: Element 302194 of a double array is Nan or Inf I am trying to solve an ILP that optimises a problem on graphs using Gurobi. Unfortunately, I get the following error when creating the problem: gurobipy.GurobiError: Element 302194 of a double array is Nan or Inf. The error is thrown when setting the objective. m.setObjective(quicksum([G.G.nodes[node]['prize'] * node_var for node, node_var in nodes.items()]) - quicksum([mod_var * mod[1][1] for mod, mod_var in modules.items()]), GRB.MAXIMIZE) All my variables are initialised and have a finite value. I don't understand which double array is being referenced. I have not found a solution online. Can anyone help me? A: It's difficult to debug inside a Python generator expression. Try debugging by rewriting as loops, like the following: obj = 0 for node, node_var in nodes.items(): # print(f"node={node}, prize={G.G.nodes[node]['prize']}, node_var={node_var}") obj += G.G.nodes[node]['prize'] * node_var for mod, mod_var in modules.items(): # print(f"mod_var={mod_var}, mod={mod[1][1]}") obj -= mod_var * mod[1][1] m.setObjective(obj, GRB.MAXIMIZE) Since I can't test this code, it's possible there may be errors, but this should give you some ideas how to debug your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/71586022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In Javascript selenium webdriver how to use if statement to check if web element actual exists? I would like to write a loop (if there is another solution even better) where i check if a given element exists. I have select list with huge amounts of options, when i select item various new items appear. They constist of constant elements with assigned values E.g product exmaple : -product -something something There is a limited number element like procduct exmaple with the same first semi row names like product. I would like to write a loop that checks if product exmaple is existing or not and get something something element I try if use asserts in if loop, i try to get to made findElement to boolean value but i don't know what to do 2
{ "language": "en", "url": "https://stackoverflow.com/questions/74449675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change the IP address of all sites in IIS6 using powershell 1.0? Using Powershell 1.0 under Windows Server 2003 with IIS 6. I have about 200 sites that I would like to change the IP address for (as listed in the website properties on the "website" tab in the "Web site identification" section "IP address" field. I found this code: $site = [adsi]"IIS://localhost/w3svc/$siteid" $site.ServerBindings.Insert($site.ServerBindings.Count, ":80:$hostheader") $site.SetInfo() How can I do something like this but: * *Loop through all the sites in IIS *Not insert a host header value, but change an existing one. A: The following PowerShell script should help: $oldIp = "172.16.3.214" $newIp = "172.16.3.215" # Get all objects at IIS://Localhost/W3SVC $iisObjects = new-object ` System.DirectoryServices.DirectoryEntry("IIS://Localhost/W3SVC") foreach($site in $iisObjects.psbase.Children) { # Is object a website? if($site.psbase.SchemaClassName -eq "IIsWebServer") { $siteID = $site.psbase.Name # Grab bindings and cast to array $bindings = [array]$site.psbase.Properties["ServerBindings"].Value $hasChanged = $false $c = 0 foreach($binding in $bindings) { # Only change if IP address is one we're interested in if($binding.IndexOf($oldIp) -gt -1) { $newBinding = $binding.Replace($oldIp, $newIp) Write-Output "$siteID: $binding -> $newBinding" $bindings[$c] = $newBinding $hasChanged = $true } $c++ } if($hasChanged) { # Only update if something changed $site.psbase.Properties["ServerBindings"].Value = $bindings # Comment out this line to simulate updates. $site.psbase.CommitChanges() Write-Output "Committed change for $siteID" Write-Output "=========================" } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/1635882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: AttributeError: 'DataFrame' object has no attribute 'droplevel' in pandas I am getting a strange (to my understanding) message when I try to drop a level from a multi-indexed pandas dataframe. For a reproducible example: toy.to_json() '{"["ISRG","EPS_diluted"]":{"2004-12-31":0.33,"2005-01-28":0.33,"2005-03-31":0.25,"2005-04-01":0.25,"2005-04-29":0.25},"["DHR","EPS_diluted"]":{"2004-12-31":0.67,"2005-01-28":0.67,"2005-03-31":0.67,"2005-04-01":0.58,"2005-04-29":0.58},"["BDX","EPS_diluted"]":{"2004-12-31":0.75,"2005-01-28":0.75,"2005-03-31":0.72,"2005-04-01":0.72,"2005-04-29":0.72},"["SYK","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BSX","EPS_diluted"]":{"2004-12-31":0.35,"2005-01-28":0.35,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BAX","EPS_diluted"]":{"2004-12-31":0.18,"2005-01-28":0.18,"2005-03-31":0.36,"2005-04-01":0.36,"2005-04-29":0.36},"["EW","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.5,"2005-04-01":0.5,"2005-04-29":0.5},"["MDT","EPS_diluted"]":{"2004-12-31":0.44,"2005-01-28":0.45,"2005-03-31":0.45,"2005-04-01":0.45,"2005-04-29":0.16},"["ABT","EPS_diluted"]":{"2004-12-31":0.63,"2005-01-28":0.63,"2005-03-31":0.53,"2005-04-01":0.53,"2005-04-29":0.53}}' toy.droplevel(level = 1, axis = 1) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-33-982eee5ba162> in <module>() ----> 1 toy.droplevel(level = 1, axis = 1) C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\core\generic.py in __getattr__(self, name) 4370 if self._info_axis._can_hold_identifiers_and_holds_name(name): 4371 return self[name] -> 4372 return object.__getattribute__(self, name) 4373 4374 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'droplevel' A: Problem is the use of an older pandas version, because if you check DataFrame.droplevel: New in version 0.24.0. The solution is to use MultiIndex.droplevel: toy.columns = toy.columns.droplevel(level = 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/56144794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: built in __dict__ is returning names of attributes with class names as prefix class Enrollment(object): def __init__(self,enrollmentId=None, enrollmentReference=None): self.enrollmentId = enrollmentId self.enrollmentReference = enrollmentReference @property def enrollmentId(self): return self.__enrollmentId @enrollmentId.setter def enrollmentId(self, enrollmentId): self.__enrollmentId = enrollmentId @property def enrollmentReference(self): return self.__enrollmentReference @enrollmentReference.setter def enrollmentReference(self, enrollmentReference): self.__enrollmentReference = enrollmentReference If i now try to print the attributes of the above class: print(Enrollment().__dict__) It prints the attributes prefixed with class name as below: {'_Enrollment__enrollmentId': None, '_Enrollment__enrollmentReference': None} Note: If I remove object as the super class, all works well and it prints the attributes correctly as below: {'enrollmentId': None, 'enrollmentReference': None} I have been been wrapping my head around this for 2 days now with no luck. Not able to understand why the class name is prefixed to attributes. I need to serialize the Enrollment object to JSON. A: In a class definition, Python transforms __x into _classname__x. This is called name mangling. Its purpose is to support class local references so that subclasses don't unintentionally break the internal logic of the parent class. A: Cause This is due to Python's name mangling of class attribute names that start with __ and are suffixed with at most a single _. This suggests a stricter privacy for these attributes. Note: This is still a heuristic and shouldn't be counted on for access prevention. From the docs: Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. class A: def __foo_(self): pass print(vars(A)) outputs {'__module__': '__main__', '_A__foo_': <function A.__foo_ at 0x1118c2488>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} Notice that __foo_ has been mangled into _A__foo_. Uses Why might this be useful? Well the example from the docs is pretty compelling: Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example: class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) tldr Read the docs on name mangling.
{ "language": "en", "url": "https://stackoverflow.com/questions/49081980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel: groupBy to nested json I have an end point the current response is as below, when we query with groupBy() it returns only one row, but how to get an nested json with hidden grouped values. //controller public function products() { $get_products = Product::groupBy('name') ->get(); $data = [ 'data' => $get_products ]; return Response::json( $data_with_status = array_merge($this->respondSuccess('query successfull'), $data) ); } //json response { "status_code": 200, "status_message": "query successfull", "data": [ { "id": 1, "name": "onion", "proportion": "500 gm", "mrp": "25", "price": "22", "status": "1" } ] } The expected result is as below, is there a query to achieve this, { "status_code": 200, "status_message": "query successfull", "data": [ { "id": 1, "name": "onion", "proportion": { "0": "500 gm", "1": "1 kg", } "mrp": "25", "price": "22", "status": "1" }, { "id": 2, "name": "tomato", "proportion": "500 gm" "mrp": "20", "price": "15", "status": "1" } ] } The Database schema is as below Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('proportion'); $table->string('mrp'); $table->string('price'); $table->enum('status', ['available','unavailable']); $table->timestamps(); $table->softDeletes(); }); Sample data to group By from products table id name proportion mrp price status 1 onion 500 gm 25 22 1 2 onion 1 kg 50 44 1 3 tomato 500 gm 20 15 1 if product name is same meaning if a product have multiple proportion i want to group the products and merge the proportions in a json as shown in the above expected json result. thank you A: Use group_cancat() - $get_products = Product::select('id','name','mrp','price','status',DB::raw('group_concat(proportion)')) ->groupBy('name')->get();
{ "language": "en", "url": "https://stackoverflow.com/questions/48387159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The wiki editor generates a link "Template:Multiple Image" (to a page that does not exist) when I try to use the multiple image template I am editing a wiki and I want to insert multiple images thanks to the {{multiple image}} template. Here is my code: {{multiple image | footer = foo | image1 = foo1.png | caption1 = foo 1 | image2 = foo2.jpg | caption2 = foo 2 }} However this code generates a link Template:Multiple Image to a page that does not exist. I obviously read the wiki documentation and looked for an answer on the web and on stackoverflow but I could find nothing about this bug. What am I doing wrong ?
{ "language": "en", "url": "https://stackoverflow.com/questions/38570430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gives me this error in gplus-api using JS Hello i just started learning gplus-api signin using javascript but i came across a error that says this Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null'). This is my code i have referred to this site but didn;t help me! https://developers.google.com/+/web/signin/javascript-flow My code <!DOCTYPE HTML> <html> <head></head> <body> <script src="https://apis.google.com/js/client:platform.js" async defer></script> <meta name="google-signin-clientid" content="MY_CLIENT_ID.apps.googleusercontent.com"> <meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" /> <meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" /> <meta name="google-signin-cookiepolicy" content="single_host_origin" /> <script type="text/javascript"> (function(){ var po = document.createElement('script'); po.type = "text/javascript"; po.async = true; po.src = "https://apis.google.com/js/client:plusone.js"; var s = document.getElementByTagName('script'); s.parentNode.insertBefore(po,s); }); function render() { // Additional params including the callback, the rest of the params will // come from the page-level configuration. var additionalParams = { 'callback': signinCallback }; // Attach a click listener to a button to trigger the flow. var signinButton = document.getElementById('signinButton'); signinButton.addEventListener('click', function() { gapi.auth.signIn(additionalParams); // Will use page level configuration }); } function signinCallback(authResult) { if (authResult['status']['signed_in']) { // Update the app to reflect a signed in user // Hide the sign-in button now that the user is authorized, for example: document.getElementById('signinButton').setAttribute('style', 'display: none'); } else { // Update the app to reflect a signed out user // Possible error values: // "user_signed_out" - User is signed-out // "access_denied" - User denied access to your app // "immediate_failed" - Could not automatically log in the user console.log('Sign-in state: ' + authResult['error']); } } </script> <button id="signinButton">Sign in with Google</button> </body> </html> my js origin is http://localhost:8080, also when i try to load this url it gives me 404 error please help to solve me this error! A: You must run a web server (even locally) when working with Google+ Sign in. A simple example is to run Python with your port set to 8080: python -m SimpleHTTPServer 8080 You can also configure / run Apache or another server for local testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/28092471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can I register for WNS in Windows Developer Center I want to know how to enable Windows Notification Services for UWP apps. A: The steps to enable WNS for your UWP app have changed, but the documentation has not yet been updated. To enable WNS: * *Register for a developer account at developer.microsoft.com *Create a new app - you can do this through Visual Studio by right clicking your UWP app > Store > Associate app with store *In Microsoft Developer Center, select your app and go to App Management > WNS/MPNS. Follow the link to Live Services Site *Here you can find your app secret and Package SID required to enable WNS
{ "language": "en", "url": "https://stackoverflow.com/questions/45476218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to join/merge two generators output using python I have two generators g1 and g2 for line in g1: print line[0] [a, a, a] [b, b, b] [c, c, c] for line1 in g2: print line1[0] [1, 1, 1] [2, 2, 2] [3, 3, 3] for line in itertools.chain(g1, g2): print line[0] [a, a, a] [b, b, b] [c, c, c] [1, 1, 1] [2, 2, 2] [3, 3, 3] How do I get the output like: [a, a, a],[1, 1, 1] [b, b, b],[2, 2, 2] [c, c, c],[3, 3, 3] or [a, a, a, 1, 1, 1] [b, b, b, 2, 2, 2] [c, c, c, 3, 3, 3] Thank You for Your help. A: You can use itertools.izip for example g1=([s]*3 for s in string.ascii_lowercase) g2=([s]*3 for s in string.ascii_uppercase) g=itertools.izip(g1,g2) This will ensure the resultant is also a generator. If you prefer to use the second here is how you can do it g1=([s]*3 for s in string.ascii_lowercase) g2=([s]*3 for s in string.ascii_uppercase) g=(x+y for x,y in itertools.izip(g1,g2)) A: You can get pairs of things (your first request) using zip(g1, g2). You can join them (your second request) by doing [a + b for a, b in zip(g1, g2)]. Almost equivalently, you can use map. Use map(None, g1, g2) to produce a list of pairs, and map(lambda x, y: x + y, g1, g2) to join the pairs together. In your examples, your generators are producing a list or tuple each time, of which you're only interested in the first element. I'd just generate the thing you need, or preprocess them before zipping or mapping them. For example: g1 = (g[0] for g in g1) g2 = (g[0] for g in g2) Alternatively, you can apply [0] in the map. Here's the two cases: map(lambda x, y: (x[0], y[0]), g1, g2) map(lambda x, y: x[0] + y[0], g1, g2) A: Let's say you have g1 and g2 : g1 = [ [['a', 'a', 'a'], ['e', 'e'], ['f', 'g']], [['b', 'b', 'b'], ['e', 'e'], ['f', 'g']], [['c', 'c', 'c'], ['e', 'e'], ['f', 'g']], ] g2 = [ [[1, 1, 1], ['t', 'q'], ['h', 't']], [[2, 2, 2], ['r', 'a'], ['l', 'o']], [[3, 3, 3], ['x', 'w'], ['z', 'p']], ] To get that : [a, a, a],[1, 1, 1] [b, b, b],[2, 2, 2] [c, c, c],[3, 3, 3] You can do that : result1 = map(lambda a, b: (a[0], b[0]) , g1, g2) # Which is like this : [(['a', 'a', 'a'], [1, 1, 1]), (['b', 'b', 'b'], [2, 2, 2]), (['c', 'c', 'c'], [3, 3, 3])] And for the second : [a, a, a, 1, 1, 1] [b, b, b, 2, 2, 2] [c, c, c, 3, 3, 3] result2 = map(lambda a, b: a[0]+b[0] , g1, g2) # Which is like that : [['a', 'a', 'a', 1, 1, 1], ['b', 'b', 'b', 2, 2, 2], ['c', 'c', 'c', 3, 3, 3]] A: first case: use for x, y in zip(g1, g2): print(x[0], y[0]) second case: use for x, y in zip(g1, g2): print(x[0] + y[0]) You can of course use itertools.izip for the generator version. You get the generator automatically if you use zip in Python 3 and greater.
{ "language": "en", "url": "https://stackoverflow.com/questions/8553349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: graphQl - return all in db I'm really new to graphQL I have a simple graphQL schema here const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID } = graphql const books = [ { name: "book 1", genre: "book-1", id: "1" }, { name: "book 2", genre: "book-2", id: "2" }, { name: "book 3", genre: "book-3", id: "3" } ] const BookType = new GraphQLObjectType({ name: 'Book', fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, genre: { type: GraphQLString } }) }) const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { book: { type: BookType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return _.find(books, { id: args.id }) } } } }) module.exports = new GraphQLSchema({ query: RootQuery }) I can return one book using the id const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { book: { type: BookType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return _.find(books, { id: args.id }) } } } }) How would I return all the books, I was thinking something like: const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { book: { type: BookType, args: {}, resolve(parent, args) { return _.find(books, {}) } } } }) A: const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { book: { type: BookType, args: { displayall: { type: GraphQLID } }, resolve(parent, args) { return _.find(books, { displayall: args.displayall }) } } books:{ type: new GraphQLList(BookType), resolve(parent, args) { return books } } } })
{ "language": "en", "url": "https://stackoverflow.com/questions/57737181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Enforce order of discord.js slash commands (using rest api) I am creating slash commands (without the slash builder), and when loading the slash commands, the order of which the options can be choosen from can be varied. I want the user to have to specify the options in a set order, because each option depends on it. I have figured out that if I set the option to required, it enforces the order by which its set in the configuration. this.options = [{ name: "first option", description: "first argument", type: 3, choices: [{ // ... }], required: true }, { name: "second option", description: "second argument", type: 3, choices: [{ // ... }], required: true } ] The code above would set the order of the options from 1 to 2 and so on. this.options = [{ name: "first option", description: "first argument", type: 3, choices: [{ // ... }], required: false }, { name: "second option", description: "second argument", type: 3, choices: [{ // ... }], required: false } ] Now, the order can be choosen freely however the user wants to. Can I enforce the order even tho the options are not required?
{ "language": "en", "url": "https://stackoverflow.com/questions/75524159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a hash map in java script and send the hash map to java action class I have text boxes like which will have some values and i would like to create a hash map with no duplicates and send that hash map to action class. <input type="text" name="test1" value="test" /> <input type="text" name="test2" value="test2" /> Like the above there will be N number of text boxes and create a hash map key as name of the text box and value as the value of the text box would some one help me as how to do this please.
{ "language": "en", "url": "https://stackoverflow.com/questions/32943869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Losing data in dictionary I have 2 lists that I am merging together like this, is there a way to merge without losing data because I have duplicates in the code? new = dict(zip(sortedPrimes, a)) both sortedPrimes and 'a' are lists with 1062 elements when I use len(). However when I zip them together like this when I print len(new) I get 336. This hasn't happened before, where is the data going? Rest of the code: def rwh_primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] numbers = rwh_primes(10000) a = [x for x in numbers if x > 1000] final = [] sortedPrimes = [] for x in a: sortedPrimes.append(''.join(sorted(str(x)))) lisp = [x for n, x in enumerate(sortedPrimes) if x in sortedPrimes[:n]] new = dict(zip(sortedPrimes, a)) A: print(len(set(sortedPrimes))) # Count of unique keys: 336 Dictionaries hash values to keys. Those key aren't duplicated. There's 336 unique items in sortedPrimes so there's 336 keys in new A: You have a situation where one key is mapping to multiple values. In that case, one reasonable data structure is a dict of lists: import collections d = collections.defaultdict(list) for v1, v2 in zip(sortedPrimes, a): d[v1].append(v2) for k in sorted(d): print k, d[k] # Output 0013 [3001] 0014 [4001] 0017 [7001] 0019 [1009, 9001] 0023 [2003] 0034 [4003] 0035 [5003] 0047 [4007] 0059 [5009] 0067 [6007] 0079 [9007] 0089 [8009] 0112 [1021, 1201, 2011] 0113 [1013, 1031, 1103, 1301, 3011] 0115 [1051, 5011, 5101] etc. for all 336 keys ...
{ "language": "en", "url": "https://stackoverflow.com/questions/44713108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strategies for multithreaded singleton object in Rails I have a compelling use case where notifications happen in realtime at the server level. I would like to push these events out over a websocket using Rails' ActionCable. How Can I reliably maintain a long-lived singleton object to react to and push server-level events? * *I prototyped a Rails app using an object instantiated from a file in /app/lib that mixes in the Singleton module. Even with class caching, this was instantiated multiple times and occasionally garbage collected despite open sockets. *Marking the event producer's initialize method private and writing a class-level instance method that checks Thread.main[:event_provider] for an instance works 95% in development, but I worry about what I don't know that I don't know about production. Very occasionally I get exceptions like "Expected x_y.rb to define constant XY" exceptions, which make me think there's a problem to this approach. *The production server will ultimately serve a very small number of clients in an environment that demands 100% uptime. I can choose a server stack that makes sense. I'm hoping someone with knowledge of Rack and/or ActionCable can comment on reliable ways to serve events to a Rails application from within the server. A: As of now, the strategy I am undertaking is to instantiate a singleton object early in the boot process and then use it to maintain threads. Threadsafe practices are obviously needed for this. The file application.rb defines MyApp::Application. At this point I declare an accessor my_thing_manager, require my_thing_manager and set self.my_thing_manager = MyThingManager.instance. class MyThingManager def instance return Thread.main[:thing_manager] unless Thread.main[:thing_manager].nil? Thread.main[:thing_manager] = self.new end private def initialize end end This approach works in a single multithreaded process but does not work in a clustered production environment. For my requirements that is completely acceptable. For a multi-process app, one could utilize hooks in e.g. Puma after_worker_fork or Unicorn's after_fork to manage a subscription to something like Redis pubsub. This will be a requirement for an upcoming project so I expect to develop this strategy further.
{ "language": "en", "url": "https://stackoverflow.com/questions/56766811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Illegal instance declaration / Overlapping instances Given class X and Y, what's the most idiomatic approach to creating instances of each other's class? e.g. - instance (X a) => Y a where ... instance (Y a) => X a where ... I'd like to avoid extensions. Also, I am aware that this could cause some nasty infinite recursion, so I'm open to a completely different approach to accomplish the same thing and stay relatively DRY. Below gives some context as to the exact problem I am having - data Dealer = Dealer Hand data Player = Player Hand Cash class HasPoints a where getPoints :: a -> Int class (HasPoints a) => CardPlayer a where getHand :: a -> Hand viewHand :: a -> TurnIsComplete -> Hand hasBlackjack :: a -> Bool hasBlackjack player = getPoints player == 21 && (length . getCards . getHand) player == 2 busts :: a -> Bool busts player = getPoints player > 21 I'd like to do this - instance (CardPlayer a) => HasPoints a where getPoints = getPoints . getHand But it seems I must do this - instance HasPoints Dealer where getPoints = getPoints . getHand instance HasPoints Player where getPoints = getPoints . getHand EDIT Seems my favorite approach is to keep the HasPoints typeclass and implement CardPlayer as data instead. data CardPlayer = Dealer Hand | Player Hand Cash instance HasPoints CardPlayer where getPoints = getPoints . getHand getCash :: CardPlayer -> Maybe Cash getHand :: CardPlayer -> Hand viewHand :: CardPlayer -> TurnIsComplete -> Hand hasBlackjack :: CardPlayer -> Bool busts :: CardPlayer -> Bool -- I wanted HasPoints to be polymorphic -- so it could handle Card, Hand, and CardPlayer instance HasPoints Hand where getPoints Hand { getCards = [] } = 0 getPoints hand = if base > 21 && numAces > 0 then maximum $ filter (<=21) possibleScores else base where base = sum $ map getPoints $ getCards hand numAces = length $ filter ((Ace==) . rank) $ getCards hand possibleScores = map ((base-) . (*10)) [1..numAces] instance HasPoints Card where -- You get the point A: Given class X and Y, what's the most idiomatic approach to creating instances of each other's class? The most idiomatic approach, given your example code, is to not use type classes in the first place when they're not doing anything useful. Consider the types of the class functions: class HasPoints a where getPoints :: a -> Int class (HasPoints a) => CardPlayer a where getHand :: a -> Hand viewHand :: a -> TurnIsComplete -> Hand hasBlackjack :: a -> Bool busts :: a -> Bool What do they have in common? They all take exactly one value of the class parameter type as their first argument, so given such a value we can apply each function to it and get all the same information without needing to bother with a class constraint. So if you want a nice, idiomatic DRY approach, consider this: data CardPlayer a = CardPlayer { playerPoints :: Int , hand :: Hand , viewHand :: TurnIsComplete -> Hand , hasBlackjack :: Bool , busts :: Bool , player :: a } data Dealer = Dealer data Player = Player Cash In this version, the types CardPlayer Player and CardPlayer Dealer are equivalent to the Player and Dealer types you had. The player record field here is used to get the data specialized to the kind of player, and functions that would have been polymorphic with a class constraint in yours can simply operate on values of type CardPlayer a. Though perhaps it would make more sense for hasBlackjack and busts to be regular functions (like your default implementations), unless you really need to model players who are immune to the standard rules of Blackjack. From this version, you can now define a HasPoints class alone if you have very different types that should be instances of it, though I'm skeptical of the utility of that, or you can apply the same transformation to get another layer: data HasPoints a = HasPoints { points :: Int , pointOwner :: a } However, this approach quickly becomes unwieldy the further you nest specializations like this. I would suggest droping HasPoints entirely. It only has one function, which just extracts an Int, so any code that handles HasPoints instances generically might as well just use Ints and be done with it. A: In general, it's impossible to declare all instances of a class to also be instances of another class without making type checking undecidable. So your proposed definition will only work with UndecidableInstances enabled: {-# LANGUAGE FlexibleInstances, UndecidableInstances #-} instance (CardPlayer a) => HasPoints a where getPoints = getPoints . getHand Although it's possible to go that route, I'd suggest refactoring the code as follows instead: data Hand = ... handPoints :: Hand -> Int handPoints = ... data Dealer = Dealer Hand data Player = Player Hand Cash class CardPlayer a where getHand :: a -> Hand ... instance CardPlayer Dealer where ... instance CardPlayer Player where ... playerPoints :: (CardPlayer a) => a -> Int playerPoints = handPoints . getHand
{ "language": "en", "url": "https://stackoverflow.com/questions/16161384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why should cocos2d-iphone users avoid using the @2x file extension? Cocos2d-iphone uses the -hd extension for Retina images (and other assets). The cocos2d Retina guide speaks only vaguely of "some incompatibilities" regarding @2x: Apple uses the ”@2x” suffix, but cocos2d doesn't use that extension because of some incompatibilities. Instead, cocos2d has its own suffix: ”-hd”. WARNING: It is NOT recommend to use the ”@2x” suffix. Apple treats those images in a special way which might cause bugs in your cocos2d application. Great. I feel well informed. Through a 2-year old bug report regarding @2x I got the link to a forum thread that supposedly explains the issues with @2x. However, it does not. The only hints I found in there is that there are iOS (4.0/4.1) bugs regarding @2x which I suppose are no longer relevant. It's possible that I might have missed some crucial aspect (there was some talk about caching or repeat loading issues) - the thread is very long after all. I'd like to know what specific issues might a cocos2d developer encounter if (s)he is using the @2x suffix for images instead of -hd? Please give concrete examples of things that might go or actually will be wrong. A: It seems as if this has a historic background. What makes using -hd graphics still worthwhile is that loading them doesn't rely on Apple functionality but is rather done in framework code. So -hd can be loaded for iPads in iPhone Simulator mode and make use of the higher resolution pictures in 2x mode. Other than that I couldn't find any more reasons to not use @2x when I was looking into this a week ago. In case you want all the details it is probably best to drop riq an email. A: This seems to be the main reason from this link: http://www.cocos2d-iphone.org/forum/topic/12026 Specifically this post by riq: I don't know if initWithContentsOfFile was fixed, but in 4.0 it was broken and it wasn't working with @2x, ~iphone extensions. imageNamed caches all the loaded files so it consumes much more memory than initWithContentsOfFile Also the @2x extension does something (I don't know exactly what) but it doesn't work OK with cocos2d. Another good point: Back when the iPhone 4 was just released with the retina display, I am sure some users of Cocos2D were using an older version of it so when the user was using the retina display on a version of Cocos2D that didn't support it, things were twice as large as they should've been. Again this is now fixed to most unless you are using a VERY early version of Cocos2D. Overview, so it seems that the main issue was with initWithContentsOfFile from iOS 4 but they have fixed this since because I use that exact API with Cocos2D 2.0-rc2 in my app and I do not have any issues whatsoever. I use all Apple specified extensions for images and everything works jolly good! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/10960875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Getting required width of an overflowing span in JS <div id="wrapper" style="width:50px; overflow:hidden;"> <span id="innerPart" style="white-space: nowrap; width: auto;">Lorem ipsum...</span> </div> Hello interwebs, I'm trying to get the width the innerPart would require to be fully displayed via JS. Tried using document.getElementById("innerPart").width; but it is just returning null A: Use document.getElementById("innerPart").offsetWidth See this answer If you wanted the width property it's off the style property. E.g. document.getElementById("innerPart").style.width The difference being that offsetWidth is a computed property, it takes into account borders and padding whereas width doesn't. You may find that width is null and I'm assuming that is true if the width hasn't been specifically set by you.
{ "language": "en", "url": "https://stackoverflow.com/questions/25648836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView Transparent BackGround I got this code : UIViewController *nextQuestionView = [[QuizzQuestionViewController alloc]init]; nextQuestionView.view.backgroundColor=[UIColor colorWithRed:0.44 green:0.44 blue:0.41 alpha:1]; [self.navigationController pushViewController:nextQuestionView animated:YES]; NSLog(@"gotonextQuestion"); [nextQuestionView newQuestion]; [nextQuestionView release]; And i want to remove the black corner. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/5939582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Correct way to pause a Python program I've been using the input function as a way to pause my scripts: print("something") wait = input("Press Enter to continue.") print("something") Is there a formal way to do this? A: I have had a similar question and I was using signal: import signal def signal_handler(signal_number, frame): print "Proceed ..." signal.signal(signal.SIGINT, signal_handler) signal.pause() So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running. A: print ("This is how you pause") input() A: I use the following for Python 2 and Python 3 to pause code execution until user presses Enter import six if six.PY2: raw_input("Press the <Enter> key to continue...") else: input("Press the <Enter> key to continue...") A: As pointed out by mhawke and steveha's comments, the best answer to this exact question would be: Python 3.x: input('Press <ENTER> to continue') Python 2.x: raw_input('Press <ENTER> to continue') For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on Python 2.x) to prompt the user, rather than a time delay. Fast readers won't want to wait for a delay, slow readers might want more time on the delay, someone might be interrupted while reading it and want a lot more time, etc. Also, if someone uses the program a lot, he/she may become used to how it works and not need to even read the long text. It's just friendlier to let the user control how long the block of text is displayed for reading. Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :) A: Very simple: raw_input("Press Enter to continue ...") print("Doing something...") A: For Windows only, use: import os os.system("pause") A: By this method, you can resume your program just by pressing any specified key you've specified that: import keyboard while True: key = keyboard.read_key() if key == 'space': # You can put any key you like instead of 'space' break The same method, but in another way: import keyboard while True: if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space' break Note: you can install the keyboard module simply by writing this in you shell or cmd: pip install keyboard A: cross-platform way; works everywhere import os, sys if sys.platform == 'win32': os.system('pause') else: input('Press any key to continue...') A: It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds. import time print("something") time.sleep(5.5) # Pause 5.5 seconds print("something") A: So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program, def pause(): programPause = raw_input("Press the <ENTER> key to continue...") and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this: import os import system def pause(): programPause = raw_input("Press the <ENTER> key to continue...") print("Think about what you ate for dinner last night...") pause() Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean. NOTE: For Python 3, you will need to use input as opposed to raw_input A: I work with non-programmers who like a simple solution: import code code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals()) This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output: Paused. Press ^D (Ctrl+D) to continue. >>> The Python Debugger is also a good way to pause. import pdb pdb.set_trace() # Python 2 or breakpoint() # Python 3 A: I assume you want to pause without input. Use: time.sleep(seconds) A: I think I like this solution: import getpass getpass.getpass("Press Enter to Continue") It hides whatever the user types in, which helps clarify that input is not used here. But be mindful on the OS X platform. It displays a key which may be confusing. Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background? A: user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke). By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer. import readchar readchar.readkey() A: I think that the best way to stop the execution is the time.sleep() function. If you need to suspend the execution only in certain cases you can simply implement an if statement like this: if somethinghappen: time.sleep(seconds) You can leave the else branch empty. A: For cross Python 2/3 compatibility, you can use input via the six library: import six six.moves.input( 'Press the <ENTER> key to continue...' )
{ "language": "en", "url": "https://stackoverflow.com/questions/11552320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "214" }
Q: Flutter : /opt/..../FETCH_HEAD exists in filesystem Arch While I'm updating and installing some packages on Arch Linux: sudo pacman -Syu && sudo pacman -S --needed \ webkit2gtk \ base-devel \ curl \ wget \... I got following error: error: failed to commit transaction (conflicting files) flutter: /opt/flutter/.git/FETCH_HEAD exists in filesystem Errors occurred, no packages were upgraded. A: Fixed with sudo rm -rf /opt/flutter/.git/FETCH_HEAD
{ "language": "en", "url": "https://stackoverflow.com/questions/72149226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Run a function in a seperate python thread (Python 3.8.3) I am using two python threads right now, one that has a while True loop import threading def threadOne(): while True: do(thing) print('loop ended!') t1=threading.Thread(threadOne) t1.start() And another that checks for a ctrl+r input. When recieved, I need the second thread to tell the first thread to break from the while loop. Is there a way to do this? Note that I cannot change the loop to 'while Break == False' as do(thing) waits for user input, but i need this to be interrupted. A: The recommended way is to use threading.event (You can combine this with event.wait if you want to sleep in that thread too however as you are waiting for a user event, probably dont need that). import threading e = threading.Event() def thread_one(): while True: if e.is_set(): break print("do something") print('loop ended!') t1=threading.Thread(target=thread_one) t1.start() # and in other thread: import time time.sleep(0.0001) # just to show thread_one keeps printing # do something for little bit and then it break e.set() EDIT: To interrupt the thread while it's waiting for user input you can send SIGINT to that thread and and it will raise KeyboardInterrupt which you can then handle. Unfortunate limitation of python, including python3, is that signals to all threads are handled in the main thread so you need to wait for the user input in the main thread: import threading import sys import os import signal import time def thread_one(): time.sleep(10) os.kill(os.getpid(), signal.SIGINT) t1=threading.Thread(target=thread_one) t1.start() while True: try: print("waiting: ") sys.stdin.readline() except KeyboardInterrupt: break print("loop ended")
{ "language": "en", "url": "https://stackoverflow.com/questions/63293718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SEO Friendly URLs Rewrite Using Htaccess And Mod_Rewrite I have used below RewriteRule in .htacces file then it is working as /page/NDT:REBGEARPOSGM-8630342 <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^page/([A-Za-z0-9\-:]+$)$ page.php?partid=$1 </IfModule> But I want work as /page/NDT:REBGEARPOSGM-8630342.html. For this I have used below RewriteRule and it is giving error 404 . <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^page/([A-Za-z0-9\-:]+$)\.html page.php?partid=$1 </IfModule> Any one please assist where I did wrong or any other way to do this. Thanks in advance. A: You have a misplaced $ anchor in your regex. Use this rule: <IfModule mod_rewrite.c> Options -MultiViews RewriteEngine on RewriteRule ^page/([a-z0-9:-]+)\.html$ page.php?partid=$1 [L,QSA,NC] </IfModule>
{ "language": "en", "url": "https://stackoverflow.com/questions/27501225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Operands could not be broadcast together with shapes data = pd.read_csv('./Book1.csv') # Read the edgelist of the Wiki Talk network G = nx.from_pandas_edgelist(data, data.columns[0], data.columns[1]) G = G.subgraph(max(nx.connected_components(G), key=len)) ic_seed_set = np.random.choice(G.nodes(), ic_seed_set_size) Determine the model parameter ic_threshold = 0.4 g = Graph([[u,v] for (u,v) in G.edges]) def IC(g,S,ic_threshold,ic_num_steps): """ Input: graph object, set of seed nodes, propagation probability and the number of Monte-Carlo simulations Output: average number of nodes influenced by the seed nodes """ # Loop over the Monte-Carlo Simulations spread = [] for i in range(ic_num_steps): # Simulate propagation process new_active, A = S[:], S[:] for i in range(len(new_active)) : # For each newly active node, find its neighbors that become activated new_ones = [] for node in new_active: # Determine neighbors that become infected np.random.seed(i) success = np.random.uniform(0,1,len(g.neighbors(node,mode="out"))) < ic_threshold new_ones += list(np.extract(success, g.neighbors(node,mode="out"))) new_active = list(set(new_ones) - set(A)) # Add newly activated nodes to the set of activated nodes A = A + new_active spread.append(len(A)) return(np.mean(spread)) modelpropagation =IC(g,ic_seed_set,ic_threshold,ic_num_steps) i expected list of integer but in this line >>> A = A + new_active <ipython-input-24-fc67faf2ae99> in IC(g, S, ic_threshold, ic_num_steps) 61 62 # Add newly activated nodes to the set of activated nodes ---> 63 A = A + new_active 64 65 spread.append(len(A)) ValueError: operands could not be broadcast together with shapes (5,) (492,)
{ "language": "en", "url": "https://stackoverflow.com/questions/74900584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reorder x-axis with heatmap in R I am used to using ggplot2, so I have only used fct_inorder() to reorder my axes. It should be Gate 0 - 3 then Full. How do you do this with a base function like heatmap? df and code below. Thank you! Wizard_heatmap <- structure(list(Response = c("LIZARD", "LIZARD", "LIZARD", "NR", "NR", "WAITER", "WEEKEND", "WHALE", "WHEELCHAIR", "WHIP", "WHISKEY", "WHISTLE", "WHISTLE", "WHISTLE", "WIND", "WINDMILL", "WINDOW", "WINDOW", "WINTER", "WISDOM", "WISDOM", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WOMEN", "WOOD", "WOODCHIP"), Target = c("WIZARD","WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD", "WIZARD"), Gate = c("Full", "Gate 2", "Gate 3", "Gate 0", "Gate 1", "Gate 0", "Gate 1", "Gate 0", "Gate 0", "Gate 0", "Gate 1", "Gate 0", "Gate 1", "Gate 2", "Gate 0", "Gate 0", "Gate 0", "Gate 1", "Gate 0", "Gate 1", "Gate 2", "Full", "Gate 1", "Gate 2", "Gate 3", "Gate 0", "Gate 0", "Gate 0"), n = c(1, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 7, 1, 15, 1, 12, 14, 1, 1, 1)), row.names = c(NA, -28L), class = c("tbl_df", "tbl", "data.frame")) heatmap(with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate))))) A: I wonder if, given your data, you are not interested in the dendrogram and are just looking for a standard heatmap? If do, then perhaps using ggplot would give you the control you need? m <- with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate)))) for(i in seq(nrow(Wizard_heatmap))) { m[Wizard_heatmap$Response[i], Wizard_heatmap$Gate[i]] <- Wizard_heatmap$n[i] } df <- setNames(as.data.frame(as.table(m)), c("Response", "Gate", "n")) library(ggplot2) ggplot(df, aes(Gate, Response, fill = n)) + geom_tile(color = "gray") + theme_minimal() + scale_fill_gradientn(colours = c("red4", "red", "orange", "yellow", "white"))
{ "language": "en", "url": "https://stackoverflow.com/questions/71579107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to compile xf86drm.h example On this page https://raw.githubusercontent.com/dvdhrm/docs/master/drm-howto/modeset.c someone has published an example on how to properly use the drm api. I downloaded the source file compiled it with gcc -I/usr/include/drm/ modeset.h -o modeset, marked it as executeable chmod +x modeset and launched it ./modeset Output: michael@lord:~/Documents/cpp/modeset$ ./modeset ./modeset: line 1: $'gpchC014\310\b\032\231\253\267+\277\331\022\225I\021': command not found ./modeset: line 17: syntax error near unexpected token `$'\375?\250\001\177\001\001'' ./modeset: line 17: `ø?¨ ø?¨ ø?¨ø?¨0ø?¨2ø?¨4ø?¨6ø?¨8ø?¨9ø?¨:ø?¨;ø?¨<ø?¨=ø?¨>ø?¨Pø?¨Rø?¨Tø?¨Vø?¨Xø?¨Zø?¨\ø?¨^ø?¨`ø?¨bø?¨dø?¨fø?¨hø?¨jø?¨lø?¨nø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ø?¨ ø?¨¢ø?¨¤ø?¨¦ø?¨¨ø?¨ªø?¨¬ø?¨®ø?¨°ø?¨±ø?¨²ø?¨³ø?¨´ø?¨µø?¨¶ø?¨·ø?¨¸ø?¨¹ø?¨ºø?¨»ø?¨¼ø?¨½ø?¨¾ø?¨¿ø?¨ðø?¨òø?¨ôø?¨öø?¨øø?¨úø?¨üø?¨þø?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨Aù?¨Cù?¨Eù?¨Gù?¨Iù?¨Kù?¨Mù?¨Où?¨aù?¨cù?¨eù?¨gù?¨iù?¨kù?¨mù?¨où?¨qù?¨sù?¨uù?¨wù?¨yù?¨{ù?¨}ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨ù?¨Áù?¨Ãù?¨Åù?¨Çù?¨Éù?¨Ëù?¨Íù?¨Ïù?¨Ñù?¨Óù?¨Õù?¨×ù?¨Ùù?¨Ûù?¨Ýù?¨ßù?¨ñù?¨óù?¨õù?¨÷ù?¨ùù?¨ûù?¨ýù?¨ÿù?¨ú?¨ú?¨ú?¨ú?¨ ú?¨ ú?¨ú?¨1ú?¨3ú?¨5ú?¨7ú?¨9ú?¨;ú?¨=ú?¨?ú?¨Qú?¨Sú?¨Uú?¨Wú?¨Yú?¨[ú?¨]ú?¨_ú?¨qú?¨sú?¨uú?¨wú?¨yú?¨{ú?¨}ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨ú?¨¡ú?¨¢ú?¨£ú?¨¤ú?¨¦ú?¨¨ú?¨ªú?¨¬ú?¨®ú?¨Àú?¨Âú?¨Äú?¨Æú?¨Èú?¨Êú?¨Ìú?¨Îú?¨ðú?¨òú?¨ôú?¨öú?¨øú?¨úú?¨üú?¨þú?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨ û?¨"û?¨$û?¨&û?¨(û?¨*û?¨,û?¨.û?¨Pû?¨Rû?¨Tû?¨Vû?¨Xû?¨Zû?¨\û?¨^û?¨`û?¨bû?¨dû?¨fû?¨hû?¨jû?¨lû?¨nû?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨û?¨Ðû?¨Òû?¨Ôû?¨Öû?¨Øû?¨Úû?¨Üû?¨Þû?¨àû?¨âû?¨äû?¨æû?¨èû?¨êû?¨ìû?¨îû?¨ðû?¨òû?¨ôû?¨öû?¨øû?¨úû?¨üû?¨þû?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨Pü?¨Rü?¨Tü?¨Vü?¨Xü?¨Zü?¨\ü?¨^ü?¨pü?¨rü?¨tü?¨vü?¨xü?¨zü?¨|ü?¨~ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨ü?¨°ü?¨²ü?¨´ü?¨¶ü?¨¸ü?¨ºü?¨¼ü?¨½ü?¨¾ü?¨¿ü?¨Ðü?¨Ñü?¨Òü?¨Óü?¨Ôü?¨Õü?¨Öü?¨×ü?¨Øü?¨Ùü?¨Úü?¨Ûü?¨Üü?¨Ýü?¨Þü?¨ßü?¨àü?¨áü?¨âü?¨ãü?¨äü?¨æü?¨èü?¨éü?¨ëü?¨ìü?¨íü?¨îü?¨ïü?¨ ý?¨"ý?¨$ý?¨%ý?¨&ý?¨'ý?¨(ý?¨)ý?¨*ý?¨+ý?¨,ý?¨-ý?¨.ý?¨/ý?¨@ý?¨Aý?¨Bý?¨Dý?¨Fý?¨Gý?¨Hý?¨Iý?¨Jý?¨Lý?¨Ný?¨pý?¨rý?¨tý?¨vý?¨xý?¨yý?¨zý?¨{ý?¨|ý?¨~ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨ý?¨¡ý?¨£ý?¨¥ý?¨§ý?¨©ý?¨«ý?¨¬ý?¨­ý?¨®ý?¨Àý?¨Âý?¨Äý?¨Æý?¨Èý?¨Êý?¨Ìý?¨Îý?¨ðý?¨òý?¨ôý?¨öý?¨÷ý?¨øý?¨ùý?¨úý?¨ûý?¨üý?¨ýý?¨ÿý?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨þ?¨?¨þ?¨þ?¨þ?¨ þ?¨"þ?¨#þ?¨$þ?¨%þ?¨&þ?¨(þ?¨*þ?¨+þ?¨,þ?¨-þ?¨.þ?¨/þ?¨@þ?¨Aþ?¨Bþ?¨Cþ?¨Eþ?¨ß@¨@¨@¨@¨@¨@¨@¨@¨@¨@¨Þ@¨ @¨Gþ?¨Hþ?¨Jþ?¨Lþ?¨Nþ?¨`þ?¨bþ?¨dþ?¨fþ?¨hþ?¨jþ?¨lþ?¨nþ?¨ þ?¨¢þ?¨¤þ?¨¦þ?¨¨þ?¨ªþ?¨¬þ?¨­þ?¨®þ?¨¯þ?¨' ^[[?1;2c^[[?1;2c I do not understand this low level framebuffer example so I am a bit lost right now. The web is also not revealing any docs. Some basic hints about what's happening here would be enough. I am also using xorg server. A: The file you are invoking seems not to be a valid ELF executable, bash tries to process it as a bash script and fails. You can check for sure by using file command, e.g. file modeset. Check for the errors during your GCC build. Note that you try to compile modeset.h, not modeset.c.
{ "language": "en", "url": "https://stackoverflow.com/questions/52806194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set-up a favicon? I am trying to do a very simple preliminary exercise to setting up a website which is creating a favicon. This is the code I am using: <!DOCTYPE html > <html lang="en-US"> <head profile="http://www.w3.org/2005/10/profile"> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> </html> But it is not working - can anyone please assist? I've saved the file favicon.ico on the same level as my html file (on a subdirectory). Many thanks A: With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming. You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device. You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time). One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) : <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png"> <link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192"> <link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160"> <link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="mstile-144x144.png"> <meta name="msapplication-config" content="browserconfig.xml"> In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines: <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="/manifest.json"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> A: Below given some information about fav Icon What Is FavIcon?  FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure. How It Works ?  Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference. <link rel="icon" href="favicon.ico" type="image/ico"/> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"  Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.  We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages A: you could take a look at the w3 how to, i think you will find it helpful your link tag attribute should be rel="icon" A: I use this on my site and it works great. <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"/> A: There is a very simple method to set a favicon, which had been around for a long time AFAIK. Place the favicon.ico file in the default location. i.e http://www.yoursite.com/favicon.ico This works in almost every browser without a <link> tag. However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag A: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en-US"> <head profile="http://www.w3.org/2005/10/profile"> <link rel="icon" type="image/png" href="http://example.com/myicon.png"> </head> <body> ... </body> </html> rel="shortcut icon" should be rel="icon" Source: W3C A: From experience of my favicon.ico not appearing, I am sharing my experience. You can't get it to show until you put your website on a host, therefore, try put it on a localhost using XAMPP - http://www.apachefriends.org/en/xampp.html. This is how the favicon appears and like others recommended, change: rel="shortcut icon" to rel="icon" Also this way .png favicons can be used for slickness. A: <head> <link rel="shortcut icon" href="favicon.ico"> </head> A: In my site, I use this: <!-- for FF, Chrome, Opera --> <link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32"> <!-- for IE --> <link rel="icon" type="image/x-icon" href="/assets/favicons/favicon.ico" > <link rel="shortcut icon" type="image/x-icon" href="/assets/favicons/favicon.ico"/> To simplify your life, use this favicons generator http://realfavicongenerator.net A: This method is recommended <link rel="icon" type="image/png" href="/somewhere/myicon.png" /> A: Try put this in the head of the document: <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/> A: I use this https://realfavicongenerator.net/ to generate all the possible favicons scenarios and it is free.
{ "language": "en", "url": "https://stackoverflow.com/questions/18301745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "84" }
Q: Google Sheets SUMIFS where multiple criteria is returning 0 I am struggling to workout the correct Google Sheets formula to achieve the following. In the sheet Profile below, column Purchased_Classes, I want to SUMIF the Qty in sheet Purchased_Completed, Where the Email matches and Item contains the text "Class" I have tried this but the results is returning 0 Here is a link to a sample google sheet. ={"Purchased_Classes";ARRAYFORMULA(IF(ISBLANK(A2:A),"",SUMIFS(Purchases_Completed!H2:H,Purchases_Completed!B2:B,A2:A,ISNUMBER(SEARCH("Class",Purchases_Completed!C2:C)), TRUE)))} . Profile Purchases_Completed A: You could try and create an empty sheet with the following formula: =QUERY(Purchases_Completed!A2:H, "SELECT B, SUM(H) WHERE C LIKE '%Class%' GROUP BY B LABEL B 'Email', SUM(H) 'Purchased_Classes'") This formula uses QUERY and it calculates the sum of your items which contain the 'Class' keyword for each user. Here is the result using the query: You can learn more about the Google Query Language here.
{ "language": "en", "url": "https://stackoverflow.com/questions/59169310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to properly manage objects when using StreamWriter/Reader with TcpClient? I'm developing software that communicates with external hardware via ethernet (TCP), and I'm experiencing difficulties regarding the object management (StreamWriter/-Reader and TcpClient). There will be frequent/continual communication between the computer and the hardware, which includes various commands. My questions are: * *When using TcpClient - does the connection/stream close or otherwise "reset" upon creating a new instance of TcpClient, for use in various classes - communicating with the same device? Or does it not matter unless I explicitly say .Close()? *How do I use StreamWriter/-Reader properly when two whole classes use both objects? Global declaration, or declarations for every method? *How does StreamReader.ReadLine() work? I have a peculiar case where it returns an "old" message, rather than the slightly newer it should. How can I properly use StreamReader such that each command will get their respective replies?
{ "language": "en", "url": "https://stackoverflow.com/questions/49176783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display more than 5 messages in TileUpdater I use in my application ScheduledTileNotifications and push 10 until 20 messages in the TileUpdateManager. But on the metro there are only 5 messages active. What can I do to display more than 5 notifications in the metro-Tile? string tileXmlString = "<tile>" + "<visual>" + "<binding template='TileWideSmallImageAndText03' branding='name'>" + "<image id='1' src='ms-appx:///Assets/icons/cube_for_kachel.png'/>" + "<text id='1'>" + longSubject + "\n" + message.title + "</text>" + "</binding>" + "<binding template='TileSquareText04' branding='name'>" + "<text id='1'>" + shortSubject + "\n" + message.title + "</text>" + "</binding>" + "</visual>" + "</tile>"; XmlDocument tileXml = new XmlDocument(); tileXml.LoadXml(tileXmlString); ScheduledTileNotification sceduleNotification = new ScheduledTileNotification(tileXml, DateTime.Now.AddSeconds(15)); TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); TileUpdateManager.CreateTileUpdaterForApplication().AddToSchedule(sceduleNotification); When I set the EnableNotificationQueue to true, five of my notification run in a circle. When I set it to false, my notification don´t run in a circle. But I have 10 until 20 Notifications, which should run in a circle. Do you think it is possible. When I use the AddToSchedule method an push 10 Notifications, each notification will show for one time. A: The problem is related to the use of the EnableNotificationQueue method. In fact, as you can read at http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.notifications.tileupdater.enablenotificationqueue: When queuing is enabled, a maximum of five tile notifications can automatically cycle on the tile. Try to pass false to this method. According to the documentation, you can schedule up to 4096 notifications. Reref to http://hansstan.wordpress.com/2012/09/02/windows-8-advanced-tile-badge-topics/ for a working example.
{ "language": "en", "url": "https://stackoverflow.com/questions/13064620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: prevent jsTree from expanding the nodes after you select them programmatically Is there a way to select a node without expanding nodes? Every time I call the method to select a node, it will call the changed.jstree event and expand the nodes. I want to select a node without expanding the nodes. $('#jstree').jstree(true).select_node('info'); $('#jstree').on("changed.jstree", function (e, data) { }); UPDATE: I also tried the below method to select a node and it still expanded the nodes: $('#jstree').jstree().select_node('info', false,true) A: I figured it out. You call the below method to check the default options and the boolean below to true to set the prevent_open. $('#jstree').on('ready.jstree', function (e, data) { data.instance.select_node(['info'], false, true); }); //$('#jstree').jstree().select_node('info', false,true)
{ "language": "en", "url": "https://stackoverflow.com/questions/66571352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to paste source code to vim without error format? When I copy a python code, and paste to vim. the indents are all error. but I paste into emacs or gedit, it is right. that is difficult to describle, let's see the screenshot. Notice:the blue and yellow line is just use the "indent guides plugin". This is the source code example: import threading import time class timer(threading.Thread): #The timer class is derived from the class threading.Thread def __init__(self, num, interval): threading.Thread.__init__(self) self.thread_num = num self.interval = interval self.thread_stop = False def run(self): #Overwrite run() method, put what you want the thread do here while not self.thread_stop: print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime()) time.sleep(self.interval) def stop(self): self.thread_stop = True def test(): thread1 = timer(1, 1) thread2 = timer(2, 2) thread1.start() thread2.start() time.sleep(10) thread1.stop() thread2.stop() return if __name__ == '__main__': test() A: Automatic indenting kicked in. The easiest way to disable it is: :set paste :help paste 'paste' boolean (default off) global {not in Vi} Put Vim in Paste mode. This is useful if you want to cut or copy some text from one window and paste it in Vim. This will avoid unexpected effects. Setting this option is useful when using Vim in a terminal, where Vim cannot distinguish between typed text and pasted text. In the GUI, Vim knows about pasting and will mostly do the right thing without 'paste' being set. The same is true for a terminal where Vim handles the mouse clicks itself. A: Karoly's answer is correct regarding the paste option. You can then add a mapping in your .vimrc to quickly enable/disable 'paste' option: For example, I use set pastetoggle=<F10> A: You can also let vim handle the situation automatically for you. With the following in your ~\.vimrc let &t_SI .= "\<Esc>[?2004h" let &t_EI .= "\<Esc>[?2004l" inoremap <special> <expr> <Esc>[200~ XTermPasteBegin() function! XTermPasteBegin() set pastetoggle=<Esc>[201~ set paste return "" endfunction you can paste freely without worrying about the auto-indentions. If you work in tmux, then you have to write instead the following function! WrapForTmux(s) if !exists('$TMUX') return a:s endif let tmux_start = "\<Esc>Ptmux;" let tmux_end = "\<Esc>\\" return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end endfunction let &t_SI .= WrapForTmux("\<Esc>[?2004h") let &t_EI .= WrapForTmux("\<Esc>[?2004l") function! XTermPasteBegin() set pastetoggle=<Esc>[201~ set paste return "" endfunction inoremap <special> <expr> <Esc>[200~ XTermPasteBegin() The source is Coderwall if you would like to read more.
{ "language": "en", "url": "https://stackoverflow.com/questions/9822618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: What's the best way to manage multiple dependent projects in Git or Mercurial? I have a dozen Java projects that depend on each other, and I frequently make changes that cross-cut all of them. However, many of the projects are libraries that could be used independently of each other as well. Right now I use mercurial subrepos, which works well except that very few third-party tools support it - it's hard to set up code review tools, continuous integration, etc. What's the best way to address this situation? Split everything into separate projects and build separate JARs? Migrate to git and use git subrepositories? Check everything in to a single repo and accept that I have to check out everything to use anything? Something else? A: I would say the best way to do it would be to cut your dependencies so that they can reference as external jars. This way when you make potentially breaking changes you don't necessarily have to fix the affected areas straight away. Since they depend on a previously built jar it allows you to properly isolate your coding. If you use something like Maven to manage your dependencies you will also benefit from the ability to more easily keep track of the different versions of your jars. A: If the subprojects are sufficiently autonomous, I would advise setting them up as separate maven projects with separate VCS repos. This will give you the modularity you need paired with a working dependency management.
{ "language": "en", "url": "https://stackoverflow.com/questions/8713521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Programmatically determine human readable color (e.g. Red, Green, etc..) of an image I'm trying to come up with a script that will programmatically run through an image and tell me it's primary color(s). Currently the script gets the RGB value of each pixel. Compares them against predefined rules and attempts to count up the number of pixels of each colour. My problem is the script is a little hit and miss. Does anyone know of a better way of doing this (maybe using a different colour coding system that's easier to translate to english) or an existing set of rules defining colours via their RGB? <?php $file = "8629.jpg"; $colors = array("Red" => array("rel" => true, "r" => 0.65, "g" => 0.09, "b" => 0.25, "var" => 0.3), "Blue" => array("rel" => true, "r" => 0.21, "g" => 0.32, "b" => 0.46, "var" => 0.3), "Green" => array("rel" => true, "r" => 0, "g" => 0.67,"b" => 0.33, "var" => 0.3), "Black" => array("rel" => false, "r" => 0, "g" => 0,"b" => 0, "var" => 30), "White" => array("rel" => false, "r" => 255, "g" => 255,"b" => 255, "var" => 30)); $total = 0; $im = imagecreatefromjpeg($file); $size = getimagesize($file); if (!$im) { exit("No image found."); } for ($x = 1; $x <= $size[0]; $x++) { for($y = 1; $y <= $size[1]; $y++) { $rgb = imagecolorat($im, $x, $y); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $colorTotal = $r + $g + $b; $rRatio = $r > 0 ? $r / $colorTotal : 0; $gRatio = $g > 0 ? $g / $colorTotal : 0; $bRatio = $b > 0 ? $b / $colorTotal : 0; foreach($colors as $key => $color) { if ($color["rel"]) { if ((($color["r"] - $color["var"]) <= $rRatio && $rRatio <= ($color["r"] + $color["var"])) && (($color["g"] - $color["var"]) <= $gRatio && $gRatio <= ($color["g"] + $color["var"])) && (($color["b"] - $color["var"]) <= $bRatio && $bRatio <= ($color["b"] + $color["var"]))) { $colourCount[$key]++; $total++; } } else { if ((($color["r"] - $color["var"]) <= $r && $r <= ($color["r"] + $color["var"])) && (($color["g"] - $color["var"]) <= $g && $g <= ($color["g"] + $color["var"])) && (($color["b"] - $color["var"]) <= $b && $b <= ($color["b"] + $color["var"]))) { $colourCount[$key]++; $total++; } } } } } var_dump($colourCount); foreach($colourCount as $key => $color) { $colourPrecent[$key] = $color / $total; } arsort($colourPrecent); var_dump($colourPrecent); foreach($colourPrecent as $key => $color) { if ($prevVal) { if ($color < ($prevVal - 0.1)) { break; } } $primary[] = $key; $prevVal = $color; } echo("The primary colours in this image are " . implode(" and ", $primary)); ?> A: Solution was to convert the RGB to HSL as suggested by Herbert. Function for converting to human still needs a little tweaking / finishing off but here it is: function hslToHuman($h, $s, $l) { $colors = array(); // Gray if ($s <= 10 && (9 <= $l && $l <= 90)) { $colors[] = "gray"; } $l_var = $s / 16; // White $white_limit = 93; if (($white_limit + $l_var) <= $l && $l <= 100) { $colors[] = "white"; } // Black $black_limit = 9; if (0 <= $l && $l <= ($black_limit - $l_var)) { $colors[] = "black"; } // If we have colorless colors stop here if (sizeof($colors) > 0) { return $colors; } // Red if (($h <= 8 || $h >= 346)) { $colors[] = "red"; } // Orange && Brown // TODO // Yellow if (40 <= $h && $h <= 65) { $colors[] = "yellow"; } // Green if (65 <= $h && $h <= 170) { $colors[] = "green"; } // Blue if (165 <= $h && $h <= 260) { $colors[] = "blue"; } // Pink && Purple // TODO return $colors; } A: Alright so you've got a graphics library, there must be an average thingy in there, you average your picture, take any pixel and tadaam you're done ? And the simplest solution found on here is : resize to 1x1px, get colorat : Get image color After that it's pretty easy, find somewhere a detailed list of rgb to human readable (for example html colors), encode that as an array and use it in your script -> round() your r,g,b, vals to the precision of your data and retrieve the color. You should determine what color granularity you want and go from there -> find your set of named colors (I think all 8bit colors have a name somewhere) and then reduce your rgb information to that - either by reducing color information of the image before reading it (faster) or by reducing color information at read time (more flexible in terms of color list. Basic example of some rgb-human readable resources : http://www.w3schools.com/html/html_colornames.asp Others : http://chir.ag/projects/name-that-color/#2B7C97 http://r0k.us/graphics/SIHwheel.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7501737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Get Login Token from WebSite via an API im trying to create a LoginActivity in Android. I use the standard LoginActivity template provided by Android Studio. What i wana do is give the user a nice LoginActivity, and when the login is successful an Activity with WebView showing the WebSite should be shown. Now i have an Asynchron Task where all the "magic" seems to happen. public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { private final String mEmail; private final String mPassword; UserLoginTask(String email, String password) { mEmail = email; mPassword = password; } @Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. try { // Simulate network access. Thread.sleep(2000); } catch (InterruptedException e) { return false; } for (String credential : DUMMY_CREDENTIALS) { String[] pieces = credential.split(":"); if (pieces[0].equals(mEmail)) { // Account exists, return true if the password matches. return pieces[1].equals(mPassword); } } // TODO: register the new account here. return false; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } Here the username and password is simply compered to values of an Array. My first Problem is, everything i change of that Task, like adding a simple Toast, leads my App to crash... This is my first time implementing a login, but am i right that my login algorihm has to be insige that task? Thats my naxt Question, how do i make a request, using an empty login-token for my r and call the function getLoginToken? The API from this Site gives me this RequestLink: www.pentle.com/api.php?c=json&r={"request":"getLoginToken","validation":{"type":"token","client":"YOUR_APP","token":"","token_id":0,"user_id":0}}&username=YOUR_USERNAME&password=YOUR_PASSWORD The request will return a json object like this: { "token_id":0, "user_id":0, "token":"THE_TOKEN" } I tried this Solution but it didnt Work. When i try to use the HttpClient it has a line going through it (struck through / crossed out?). And my App crashes... Maybe somebody can shed some light on how to use an Asynchron Task, and how to make a login possible with the RequestLink. It is realy important for me that this is working! EDIT: Thanks to @danny my code looks like this now: package com.pentle.pentle2; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.app.LoaderManager.LoaderCallbacks; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import java.util.ArrayList; import java.util.List; /** * A login screen that offers login via email/password. */ public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> { public String test = ""; /** * A dummy authentication store containing known user names and passwords. * TODO: remove after connecting to a real authentication system. */ private static final String[] DUMMY_CREDENTIALS = new String[]{ "foo@example.com:hello", "bar@example.com:world" }; /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // UI references. private AutoCompleteTextView mEmailView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. mEmailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); } private void populateAutoComplete() { getLoaderManager().initLoader(0, null, this); } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ public void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. mEmailView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (TextUtils.isEmpty(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for empty Username if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); mAuthTask = new UserLoginTask(email, password); mAuthTask.execute((Void) null); } } private boolean isEmailValid(String email) { //TODO: Replace this with your own logic return email.contains("@"); } private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 4; } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses. ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[]{ContactsContract.CommonDataKinds.Email .CONTENT_ITEM_TYPE}, // Show primary email addresses first. Note that there won't be // a primary email address if the user hasn't specified one. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { List<String> emails = new ArrayList<String>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { emails.add(cursor.getString(ProfileQuery.ADDRESS)); cursor.moveToNext(); } addEmailsToAutoComplete(emails); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { } private interface ProfileQuery { String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY, }; int ADDRESS = 0; int IS_PRIMARY = 1; } private void addEmailsToAutoComplete(List<String> emailAddressCollection) { //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection); mEmailView.setAdapter(adapter); } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { private final String mEmail; private final String mPassword; UserLoginTask(String email, String password) { mEmail = email; mPassword = password; test = "1"; } @Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. String response; HttpClient Client = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { test = "2"; HttpPost postMethod = new HttpPost("www.pentle.com/api.php?c=json&r={request:getLoginToken,validation:type:token,client:Pentle_Android,token:,token_id:0,user_id:0}}&username="+mEmail+"&password=" + mPassword); //_email and _password are String values from TextView: test = "3"; //postMethod.setEntity(new StringEntity("&username="+mEmail+"&password=" + mPassword)); test = "4"; postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded"); //here is the reponse, you can check it: response = Client.execute(postMethod, responseHandler); } catch(Exception ex) { //Login to server failed... ex.printStackTrace(); } /*try { // Simulate network access. Thread.sleep(2000); } catch (InterruptedException e) { return false; } for (String credential : DUMMY_CREDENTIALS) { String[] pieces = credential.split(":"); if (pieces[0].equals(mEmail)) { // Account exists, return true if the password matches. return pieces[1].equals(mPassword); } }*/ // TODO: register the new account here. return false; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); Toast.makeText(getApplicationContext(), test, Toast.LENGTH_SHORT).show(); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } } Later it should return if the user wasnt foud, the user was found but the pw was incorrect, or if the login was successful. In case of it beeing successful an Activity with a WebView shoul be displayed. Right now it fails at HttpPost postMethod = new HttpPost("www.pentle.com/api.php?c=json&r={request:getLoginToken,validation:type:token,client:Pentle_Android,token:,token_id:0,user_id:0}}&username="+mEmail+"&password=" + mPassword);. Does it becasue im trying to run it in Background? The String test is displayed in a Toast in PostExecute to see where ist stops. Did i use the API Request right? A: @Denis Pramme Please try this code and let me know: public class LoginActivity extends Activity { ..... private void SignInMethod() { new Thread(new Runnable() { public void run() { try { HttpPost postMethod = new HttpPost("*URL TO YOUR API SERVER*" + "Authenticate"); //_email and _password are String values from TextView: postMethod.setEntity(new StringEntity("grant_type=password&username=" + _email + "&password=" + _password)); postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded"); //here is the reponse, you can check it: response = httpClient.execute(postMethod, resonseHandler); } catch(Exception ex) { //Login to server failed... ex.printStackTrace(); } } }).start(); } } A: @DennisPramme, ok please change the line: String response = httpClient.execute(postMethod, resonseHandler); TO this line: (it will show status returned from server): HttpResponse responseFromServer = httpClient.execute(postMethod); int status = responseFromServer.getStatusLine().getStatusCode();
{ "language": "en", "url": "https://stackoverflow.com/questions/29914863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bootstrap radio button and label in different lines when label is too long For some reason, Bootstrap is placing my label in a different line than the radio button (codepen) when the label is sufficiently large: Without Bootstrap, the exact same code works as expected, with the label next to the radio button: * { font-family: helvetica, arial, sans-serif } input[type="radio"] { margin: 6px; padding: 6px; } .choices { border: 1px solid skyblue; padding: 6px; width: 600px; border-radius: 8px; } .choice { line-height: 24px; margin: 4px; display: inline-block; } <div class="choices"> <div class="choice"> <input type="radio" name="answer" id="radio2" value="2"> <label for="radio2">Fusce euismod augue at diam semper congue.</label> </div> <div class="choice"> <input type="radio" name="answer" id="radio3" value="3"> <label for="radio3">Nullam nec ullamcorper justo, at lobortis libero. Praesent congue erat nibh, non tincidunt nisi tempor in. Nam eu mi sed nisl commodo dignissim sed non urna.</label> </div> <div class="choice4"> <input type="radio" name="answer" id="radio4" value="4"> <label for="radio4">Integer at convallis lorem.</label> </div> </div> How do I fix with CSS rules? I tried using Bootstrap's .form-horizontal and .form-inline classes, but that didn't work. I cannot put the radio button inside the label. Although this will fix the way it is displayed, it breaks some very delicate Javascript somewhere else in the page A: well I fixed this with just float .choices input[type="radio"]{ float:left; } * { font-family: helvetica, arial, sans-serif } input[type="radio"] { margin: 6px; padding: 6px; } .choices { border: 1px solid skyblue; padding: 6px; width: 600px; border-radius: 8px; } .choice { line-height: 24px; margin: 4px; display: inline-block; } .choices input[type="radio"]{ float:left; } .choices .choice4{ margin: 4px; } <div class="choices"> <div class="choice"> <input type="radio" name="answer" id="radio2" value="2"> <label for="radio2">Fusce euismod augue at diam semper congue.</label> </div> <div class="choice"> <input type="radio" name="answer" id="radio3" value="3"> <label for="radio3">Nullam nec ullamcorper justo, at lobortis libero. Praesent congue erat nibh, non tincidunt nisi tempor in. Nam eu mi sed nisl commodo dignissim sed non urna.</label> </div> <div class="choice4"> <input type="radio" name="answer" id="radio4" value="4"> <label for="radio4">Integer at convallis lorem.</label> </div> </div> A: Add the .row class to your div. See the example below. * { font-family: helvetica, arial, sans-serif } input[type="radio"] { margin: 6px; padding: 6px; } .choices { border: 1px solid skyblue; padding: 6px; width: 600px; border-radius: 8px; } .choice { line-height: 24px; margin: 4px; display: inline-block; } <div class="choices"> <div class="choice"> <input type="radio" name="answer" id="radio2" value="2"> <label for="radio2">Fusce euismod augue at diam semper congue.</label> </div> <div class="choice row"> <label for="radio3"><input type="radio" name="answer" id="radio3" value="3"> Nullam nec ullamcorper justo, at lobortis libero. Praesent congue erat nibh, non tincidunt nisi tempor in. Nam eu mi sed nisl commodo dignissim sed non urna.</label> </div> <div class="choice4"> <input type="radio" name="answer" id="radio4" value="4"> <label for="radio4">Integer at convallis lorem.</label> </div> </div> * { font-family: helvetica, arial, sans-serif } input[type="radio"] { margin: 6px; padding: 6px; } .choices { border: 1px solid skyblue; padding: 6px; width: 600px; border-radius: 8px; } .choice { line-height: 24px; margin: 4px; display: inline-block; } <div class="choices"> <div class="choice"> <input type="radio" name="answer" id="radio2" value="2"> <label for="radio2">Fusce euismod augue at diam semper congue.</label> </div> <div class="choice"> <input type="radio" name="answer" id="radio3" value="3"> <label for="radio3">Nullam nec ullamcorper justo, at lobortis libero. Praesent congue erat nibh, non tincidunt nisi tempor in. Nam eu mi sed nisl commodo dignissim sed non urna.</label> </div> <div class="choice4"> <input type="radio" name="answer" id="radio4" value="4"> <label for="radio4">Integer at convallis lorem.</label> </div> </div> * { font-family: helvetica, arial, sans-serif } input[type="radio"] { margin: 6px; padding: 6px; } .choices { border: 1px solid skyblue; padding: 6px; width: 600px; border-radius: 8px; } .choice { line-height: 24px; margin: 4px; display: inline-block; } <div class="choices"> <div class="choice"> <input type="radio" name="answer" id="radio2" value="2"> <label for="radio2">Fusce euismod augue at diam semper congue.</label> </div> <div class="choice"> <input type="radio" name="answer" id="radio3" value="3"> <label for="radio3">Nullam nec ullamcorper justo, at lobortis libero. Praesent congue erat nibh, non tincidunt nisi tempor in. Nam eu mi sed nisl commodo dignissim sed non urna.</label> </div> <div class="choice4"> <input type="radio" name="answer" id="radio4" value="4"> <label for="radio4">Integer at convallis lorem.</label> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/45178425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: An HTTP POST, authenticated with the key Android I had to do HTTP POST, authenticated with the key. I had the key with me and also url. But am getting 400 response code i.e, bad request error. My code is: Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("sixxxxxxxx","xxxxxxxxxTGh7fYbA:xxxxxxoRtGnOIb_vno1wQ".toCharArray()); } }); I found this is for username and password. But i want to authenticate with specific key only How to do this? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7725053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Optimizing partial computation in Haskell I'm curious how to optimize this code : fun n = (sum l, f $ f0 l, g $ g0 l) where l = map h [1..n] Assuming that f, f0, g, g0, and h are all costly, but the creation and storage of l is extremely expensive. As written, l is stored until the returned tuple is fully evaluated or garbage collected. Instead, length l, f0 l, and g0 l should all be executed whenever any one of them is executed, but f and g should be delayed. It appears this behavior could be fixed by writing : fun n = a `seq` b `seq` c `seq` (a, f b, g c) where l = map h [1..n] a = sum l b = inline f0 $ l c = inline g0 $ l Or the very similar : fun n = (a,b,c) `deepSeq` (a, f b, g c) where ... We could perhaps specify a bunch of internal types to achieve the same effects as well, which looks painful. Are there any other options? Also, I'm obviously hoping with my inlines that the compiler fuses sum, f0, and g0 into a single loop that constructs and consumes l term by term. I could make this explicit through manual inlining, but that'd suck. Are there ways to explicitly prevent the list l from ever being created and/or compel inlining? Pragmas that produce warnings or errors if inlining or fusion fail during compilation perhaps? As an aside, I'm curious about why seq, inline, lazy, etc. are all defined to by let x = x in x in the Prelude. Is this simply to give them a definition for the compiler to override? A: If you want to be sure, the only way is to do it yourself. For any given compiler version, you can try out several source-formulations and check the generated core/assembly/llvm byte-code/whatever whether it does what you want. But that could break with each new compiler version. If you write fun n = a `seq` b `seq` c `seq` (a, f b, g c) where l = map h [1..n] a = sum l b = inline f0 $ l c = inline g0 $ l or the deepseq version thereof, the compiler might be able to merge the computations of a, b and c to be performed in parallel (not in the concurrency sense) during a single traversal of l, but for the time being, I'm rather convinced that GHC doesn't, and I'd be surprised if JHC or UHC did. And for that the structure of computing b and c needs to be simple enough. The only way to obtain the desired result portably across compilers and compiler versions is to do it yourself. For the next few years, at least. Depending on f0 and g0, it might be as simple as doing a strict left fold with appropriate accumulator type and combining function, like the famous average data P = P {-# UNPACK #-} !Int {-# UNPACK #-} !Double average :: [Double] -> Double average = ratio . foldl' count (P 0 0) where ratio (P n s) = s / fromIntegral n count (P n s) x = P (n+1) (s+x) but if the structure of f0 and/or g0 doesn't fit, say one's a left fold and the other a right fold, it may be impossible to do the computation in one traversal. In such cases, the choice is between recreating l and storing l. Storing l is easy to achieve with explicit sharing (where l = map h [1..n]), but recreating it may be difficult to achieve if the compiler does some common subexpression elimination (unfortunately, GHC does have a tendency to share lists of that form, even though it does little CSE). For GHC, the flags fno-cse and -fno-full-laziness can help avoiding unwanted sharing.
{ "language": "en", "url": "https://stackoverflow.com/questions/10266954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Perforce Change List too Big In Perforce, I have created a change list that has over 200,000 files (by doing a rename on a directory). This change list is now too big to submit or revert. When I try, I get an error saying that the operation took too long. I am now stuck with this change list that has my original directory in marked for delete state and a new directory that hasn't been submitted. Is there a way undo this change list? A: You can revert the files a few at a time. As a test, you could run p4 revert //path/to/some/file and verify that it's able to revert that file. Once you know that's working, you just need a way to automate the process. You could script something up that starts in the root directory and runs through all directories breadth-first, running p4 revert //path/to/folder/* at each folder (I think you could also use client paths). A: You can revert via the command line using the p4 tool. I do not think you can revert the files from the UI. The associated documentation shows various examples of how revert all or specific files (see the Examples section): http://www.perforce.com/perforce/r12.1/manuals/cmdref/revert.html
{ "language": "en", "url": "https://stackoverflow.com/questions/22975758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android : Get the list of images to download added in the separate folder of Firebase console from a FireBase Storage API I have an list of images with separate folder that is directly uploaded in the Fire-base console. I want to download that images into the app to display it in the grid using an storage API. I looked into this https://firebase.google.com/docs/storage/android/download-files but this is only for the single image to download and have to specified an name for that. Basically I want to get all the images with multiple categories that is stored in the separate folder in the console. A: In order to download a image from Firebase Storage, you first need to have the corresponding url of the image. To download a image, it requires more steps: * *Upload the image to Firebase Storage. *Save the corresponding url to Firebase Database while uploading. *Attach a listener on the folder you have saved the image. *Display the image. Let's say your Firebase Storage structure looks something like this: Storage-root | --- Photos | --- FolderNo1 | | | --- image1.jpg | | | --- image2.jpg | --- FolderNo2 | --- image3.jpg | --- image3.jpg The coresponding database structure of your Firebase database that stores the urls of the images should look like this: Firebase-root | --- Photos | --- FolderNo1 | | | --- imageName1: imageUrl1 | | | --- imageName2: imageUrl2 | --- FolderNo2 | --- imageName3: imageUrl3 | --- imageName4: imageUrl4 The folder names in the Firebase database can be simple names (but be sure when uploading to check the names for uniqueness) or can be random unique ids, in which case i recomand you using the push() method. If you are saving the images through Firebase Console, you cannot get the image url, that's why you should do this programmatically. Firestore documentation shows how to download just a single image because even if you download a single image or more images, the code is almost the same. If you want to get all urls from a single folder, please use the following code: DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference folderRef = rootRef.child("Photos").child("FolderNo1"); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<String> list = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String imageName = ds.getKey(); String imageUrl = ds.getValue(String.class); list.add(imageUrl); } Log.d("TAG", list); } @Override public void onCancelled(DatabaseError databaseError) {} }; folderRef.addListenerForSingleValueEvent(eventListener); If you want to get all urls from all folders, please use the following code: DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference photosRef = rootRef.child("Photos"); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<String> list = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String imageName = ds.getKey(); String imageUrl = ds.getValue(String.class); list.add(imageUrl); } Log.d("TAG", list); } @Override public void onCancelled(DatabaseError databaseError) {} }; photosRef.addListenerForSingleValueEvent(eventListener); In both cases, as you probably see, you get a List of urls. Having this list, you can now download the desired images according to Firebase Storage Office Documentation but instead of using one url as mentioned there, you need to use a List of urls. A: you need to save path and image name in realtime database at upload images time in firebase database than you will get all images showing in below image
{ "language": "en", "url": "https://stackoverflow.com/questions/47261549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How should I implement a map of string to method in Java? I have a list of XML tags and a method for each of them inside my class, getting that tag as an argument and doing its work. So all the methods get the same input and I want to loop through the list of tags, calling appropriate method each time. In Python I've made it with a hash of strings (names of tags) to lambdas (self.methodName()) and I want to translate it to Java. Now in Java, I can't (?) make such a hash and even can't use strings (tag names) in a switch statement (with each branch calling a certain method). The possibility of using 10 or so subsequent ifs seems horribly ugly and I'm looking for a better way to code that. A: Map string to a class instance by instantiating classes and saving them (probably in a hash). All the classes must implement the same interface of course. You'll find that if you code this way a better structure starts to emerge from your code--for instance you might find that where before you might have used 2, 3 or 10 similar methods to do slightly different things, now the fact that you can pass data into your constructor allows you to do it all with one or two different classes instead. This interface and the classes that implement it (for me at least) nearly always evolve into a full-featured set of classes that I needed all along but might not have recognized otherwise. Somehow I never seem to regret writing code the "Hard" way, but nearly always regret when I choose the easier path. A: I'd go with what Bill K suggested in regards to implementing the same interface. But if you have the issue of wanting to call methods with different names you could try using reflection and do something like this: Method method = Foo.class.getDeclaredMethod("methodName", parametersTypes); // Get the method you want to call Foo foo = new Foo(); method.invoke(foo, args); // invoke the method retrieved on the object 'foo' with the given arguments A: What do people think of this? public static enum Tags { TAG1, TAG2, TAG3 } public class Stuff { ... switch (Tags.valueOf(str)) { case TAG1: handleTag1(); break; case TAG2: handleTag2(); break; case TAG3: handleTag3(); break; } } The upside is that this is concise and efficient (at least in this case). The downside is that it is not so good with mixed case tags and tags with Java non-identifier characters in them; e.g. "-". (You either have to abuse accepted Java style conventions for the enum member identifiers, or you have to add an explicit String-to-enum conversion method to the enum declaration.) Using a switch statement for dispatching is evil in some peoples' book. But in this case, you need to compare what you are gaining with what you are loosing. And I'd be surprised if polymorphic dispatching would give a significant advantage over a switch statement in terms of extensibility and maintainability. A: you can invoke the method using reflection: Class.getMethod therefore you don't need a switch or a set of ifs. A: Here is an example of the proposal of Bill K (if I understood it right) public class Example { static interface TagHandler { void handle(String tag); } static final Map<String, Example.TagHandler> tagHandlers = new HashMap<String, Example.TagHandler>() { { put("tag_1", new Example.TagHandler() { public void handle(String tag) { System.out.println("Handling tag_1: " + tag); } }); put("tag_2", new Example.TagHandler() { public void handle(String tag) { System.out.println("Handling tag_2: " + tag); } }); } }; public static void main(String[] args) { String[] tags = { "tag_1", "tag_2", "tag_1" }; for (String tag : tags) { tagHandlers.get(tag).handle(tag); } } } A: An indirect answer: XML typically represents data, not instructions. So it is probably more useful to map parser handling onto fields. This is what JAXB does. I suggest using JAXB or similar. Unless you have a huge amount to do, I would strongly advise against reflection in a statically typed language. A string of } else if (tag.equals("blah")) { (or with interning, } else if (tag == "blah") { isn't going to kill you. You can even map strings onto their enum namesakes, but that is a little reflectiony. Switch-on-string should be with us in JDK7.
{ "language": "en", "url": "https://stackoverflow.com/questions/2060619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: connecting to cassandra using hector PasswordAuthenticator issue I am using Cassandra 1.2.3 and I made following change in cassandra config to enable user/password - authenticator: org.apache.cassandra.auth.PasswordAuthenticator I am able to access the existing keyspace using cassandra-cli. But having issues with querying using hector - (adding credentials at HFactory.getOrCreateCluster did help in moving forward but now i get same error while running queries against the keyspace) Map<String, String> AccessMap = new HashMap<String, String>(); AccessMap.put("username", "cassandra"); AccessMap.put("password", "cassandra"); cluster = HFactory.getOrCreateCluster(clusterName, new CassandraHostConfigurator(hostport), AccessMap); ConfigurableConsistencyLevel ccl = new ConfigurableConsistencyLevel(); ccl.setDefaultReadConsistencyLevel(HConsistencyLevel.ONE); keyspace = HFactory.createKeyspace(keyspaceName, cluster, new AllOneConsistencyLevelPolicy(), FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE, AccessMap); exception thrown when running QueryResult> result = sliceQuery .execute(); - Caused by: me.prettyprint.hector.api.exceptions.HInvalidRequestException: InvalidRequestException(why:You have not logged in) Without credentials being added SliceQuery was working fine. A: I was using hector 1.1.4 but it is taken care in hector 1.1.5.
{ "language": "en", "url": "https://stackoverflow.com/questions/18139626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble with Flex error handling The following flex file gives output that does not exit with a nonzero status when it encounters an error, like trying to write to /dev/full: WS [ \t]+ %option noyywrap %{ #include <stdio.h> #include <stdlib.h> int output(const char *); %} newline (\r|\n|\r\n|\n\r) %% #[^\r\n]*/{newline} {}; [^#]+ { output(yytext); } <<EOF>> { output(yytext); return 0; } %% int main (void) { while (yylex()) ; return errno; } int output(const char *string) { int error; if (fputs(string, stdout) == EOF ){ error = errno; fprintf(stderr, "Output error: %s\n", strerror(error)); exit(errno); } return 0; } How do I fix this? A: The problem was that I was not flushing stdout. Due to buffering, the printf succeeded, but the fflush failed.
{ "language": "en", "url": "https://stackoverflow.com/questions/20448634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In MVP is onClick responsibility of View or Presenter? In the MVP pattern who is responsible to handle clicks on the UI? E.g. the non-MVP approach would be something like: counterButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { totalClicks++; counterTextView.setText("Total clicks so far: "+totalClicks); } }); Using MVP is the onClick the responsibility of the Presenter? Or the View can handle that? Can someone please clarify this? A: In MVP, it is the responsibility of the View to know how to capture the click, not to decide what to do on it. As soon as the View captures the click, it must call the relevant method in the Presenter to act upon it: ------------------- View -------------------- button1.setOnClickListener(new OnClickListener({ presenter.doWhenButton1isClicked(); })); ------------------ Presenter ---------------- public void doWhenButton1isClicked(){ // do whatever business requires } I have a series of articles on architectural patterns in android, part 3 of which is about MVP. You might find it helpful. A: OnClick should call a Presenter method. You should do your business in presenter and if you need to update the ui you should define a method in your View and call it from presenter. You need a method for your View ex: public void showCounterCount(final int totalClicks){ counterTextView.setText("Total clicks so far: "+totalClicks); } Also you need a method and a variable in your Presenter: int totalClicks = 0; public void onCounterButtonClicked(){ totalClicks++; mView.showCounterCount(totalClicks); } And refactor your code like this: counterButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPresenter.onCounterButtonClicked(); } }); For more complex and clean architecture you can do your use case business in interactors. (In your example incrementing a counter value is a use-case for your application) You can define an interactor and increment your counter value there. CounterInteractor: public CounterInteractor{ public int incrementCounter(int currentCounter){ return currentCounter+1; } } And refactor your presenter like below: int totalClicks = 0; CounterInteractor mCounterInteractor = new CounterInteractor(); public void onCounterButtonClicked(){ totalClicks = mCounterInteractor.incrementCounter(totalClicks); mView.showCounterCount(totalClicks); } With this approach you separate your business logic totally from presenters and re use your use-case concepts without duplicating code in presenters. This is more clean approach. You can also check this git repo for different MVP Approaches. https://github.com/googlesamples/android-architecture/tree/todo-mvp-clean/ Good luck. Edit: Here's my lightweight wikipedia client project source: https://github.com/savepopulation/wikilight I'm trying to implement MVP. (MVP + Dagger2 + RxJava)
{ "language": "en", "url": "https://stackoverflow.com/questions/38360478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Convert base 64 string into image return nil in swift let str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8Q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ItpyeV9M0xcXen2s72ejlpN5HhOy55zn9qlYNKstRtfFuoyxWLIweAaI07RbC1FrJFGd8nck+1Nkq0LlrZHmddGjnvLlnlmmi/UTuAY8YC/2jmrF8H+tYrLo7U9K1jqdNH8G4Mse9Qd4J9Ae/FU3W7mX+aeExDLtfgj25/wCq17qWo3epX5S4kwsbYUINo7+tKWJSdszPkSUqNx6p1p0oGuLrT5pNamiDSNLIp2jPGFH5qD636i1EJpslnEsNtNbh2C8eYjt9/X8VRtGuZLeCaCMLsdTkEf8AkKtmqXMt50JFLPtLC6RAcdgI24p0caTGTyOWxGmatJdNvlZ5GChRlv8AitldPahpr6V8pNbzNNJwpznBrUPTLFmIbnArZvSgDzDcMheQPxTmqQqDtls0rQb8XNsrwl/EfC49amdTE2n3U+mSO0TIDzjndjj/ADilXmoXdnp0FxaymKSEhkZRyDnFMW00urXi3d/IZZZXUMx+pAP/ADSLp2jTXaNHSHw21d7/AKG0w3Vw0skCCGVgOR9T7VbACrELnZjAz6itPfBCeS36o6j6cVt1lDAkkatyVOQeK25vbAyey118U+0UcjNGp0O8HjNe3hTgEU0HJNJLHdTUKaof8QHvjFNmdQ2AtIJJpGMvg1JA886lSMAU0ZGI8oGaQyKWxisDCcqKCU6FeNcA4UVl5g3Mkh49jSfEb6UgIpkAIyDQAuM5zjOPrSsj3pib+mPJxSAzEd6CD//Z" let dataDecoded : Data = Data(base64Encoded: str, options: .ignoreUnknownCharacters)! let decodedimage = UIImage.init(data: dataDecoded) decodedImage is nil If I put this base 64 string into this link, I get my required image. A: The problem is that the string you pass to Data(base64Encoded: is not actually base64encoded, it contains some more plaintext in the front. You need to remove that and only pass the actual base64 encoded image, like so: let str = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQ..." let dataDecoded : Data = Data(base64Encoded: str)! let decodedimage = UIImage.init(data: dataDecoded) Alternatively you can programatically split the original data at the , and take the second part as the actual data input. At that point you can remove the options: .ignoreUnknownCharacters as well since now there should not be any non-base64 chars left - and if there are you should fix the data instead of the code. Final note: depending on where you get the data from it might be a good idea to not force-unwrap anything and instead deal with a broken / missing image by e.g. displaying a placeholder image.
{ "language": "en", "url": "https://stackoverflow.com/questions/65231859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert a div css line to django template line for this particular line? I want to convert a particular template line containing and inline css into django template line which will show the static files too. The template line is <div class="single-welcome-slides bg-img bg-overlay jarallax" style="background-image: url(img/bg-img/1.jpg);"> What will be the django static template line to load the image? A: Maybe You can try something like this <div class="single-welcome-slides bg-img bg-overlay jarallax" style="background-image: url({% static 'img/bg-img/1.jpg' %});" /> Happy Coding!
{ "language": "en", "url": "https://stackoverflow.com/questions/63390297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php program works locally but not on server I have this code running locally smoothly. The program only looks for a file and write data on it. When I try to run the same program on a server, it just does nothing... This is the complete code: <?php $myFile = "Current_User.txt"; //$produto = "sapato1"; //$produto = $produto.";"; $i = 0; $produto = $_POST["produtoID"]; $produto = $produto.";"; //$produto = $_POST["produtoID"]; $fh = fopen($myFile, 'r'); $line_of_text = fgets($fh); $str = $line_of_text; $str = str_replace("\n", "", $str); $str = $str."_Cesto.txt"; fclose($fh); $fh2 = fopen($str, "r")or die("can't open file"); while (($line_of_text = fgets($fh2))) { $i++; $line_of_text = str_replace("\n", "", $line_of_text); $line_of_text = str_replace("\r", "", $line_of_text); if($produto == $line_of_text){ break; } } fclose($fh2); $dados = file($str); if($i == 1){ unset($dados[$i - 1]); } else{ unset($dados[$i - 2]); } file_put_contents($str,$dados); ?> A: Following code is facing the same problem so permissions could be the reason or elsewise change the method to GET it will be working. <?php $url = "http://sea-summit.com/T_webservice/get_appointments_by_id.php"; $data = array('user_id'=> 1); $options = array( 'http' => array( 'method' => 'POST', 'content' => json_encode( $data ), 'header'=> "Content-Type: application/json\r\n" . "Accept: application/json\r\n" )); $context = stream_context_create( $options ); $result = file_get_contents( $url, false, $context ); $response = json_decode( $result ); var_dump($response); ?> A: you forgot to upload Current_User.txt A: Did you check the write permission of your Current_User.txt file? What File System are you using on your Server? If you have access: Check your PHP error_log on the Server to get more valueable answers, or change the error_reportings.
{ "language": "en", "url": "https://stackoverflow.com/questions/13904771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Javascript variable scope, how to pass variable values to outer functions? How can I get the variable to be equal to what is defined in the if statement? My first alert evaluates correctly but then loses scope. I need to take action outside of the $.get function. function emailCheck() { var emailExists; var emailEntry = $("#email").val(); $.getJSON('http://localhost:8080/ShoppingCart/ajax.do', function(responseJson) { $.each(responseJson, function(index, item) { if(emailEntry == item.email) { //Set to true when a match is found emailExists = true; return false; } }); //alerts to true alert(emailExists + " in get"); }); //Need emailExists to be true here when match is found but it's undefined?? alert(emailExists + "end email check"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28919764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: select items from one table with sum of records matching HAVING in subquery I have a table of cities with, among other things, population, latitude and longitude. I also have a table of airports with various info including latitude and longitude. A query like this roughly obtains the population of all towns within 100 km of a given latitude and longitude: SELECT SUM(cty_population) as cty_population_total FROM (SELECT cty_population, ( 6371 * acos ( cos ( radians(37.61899948) ) * cos( radians( cty_latitude ) ) * cos( radians( cty_longitude ) - radians(-122.37500000) ) + sin ( radians(37.61899948) ) * sin( radians( cty_latitude ) ) ) ) AS cty_distance FROM cities HAVING cty_distance < 100) cty_population_alias This will give a result like this: cty_population_total 6541221 In the above query, 37.61899948 is the latitude and -122.37500000 is the longitude. My question is: can I select an arbitrary number of airports from the airports table, pass their longitudes and latitudes into this subquery in place of the above numbers, and find the city population within 100 km of each airport. Ideally I would have results like this: airport_name airport_pop Boston Logan 6654901 London Heathrow 11345690 ...etc. I could do this with scripting, but I am wondering if it can be done with SQL alone? The database engine is MySQL. A: You have a very procedural way of thinking this which would not work well in SQL. You can think of it as joining the city with all its nearby airports. The following may work: SELECT a.name, SUM(c.cty_population) FROM cities c JOIN airports a ON ( 6371 * acos ( cos ( radians(a.latitude) ) * cos( radians( c.cty_latitude ) ) * cos( radians( c.cty_longitude ) - radians(a.longitude) ) + sin ( radians(a.latitude) ) * sin( radians( c.cty_latitude ) ) ) < 100 WHERE (filter airports or something else here) GROUP BY a.airport_id, a.name Also, I suggest you migrate to MySQL 5.7 which includes spatial functions and data types built in.
{ "language": "en", "url": "https://stackoverflow.com/questions/39406920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Charts set default date range I've created a dashboard with the Google Charts API that has a DateRangeFilter and a ComboChart with a data point for every Monday over 3 months. It contains an actual series (which can be null) as a bar graph, and a goal series that always has data associated with it. Ideally, I would like to set the DateRangeFilter to show just the current and previous week, as well as 2 weeks ahead, but still allow me to manipulate the range filter to show additional data. So far I've tried setting hAxis.viewWindow.max and hAxis.viewWindow.min to the correct dates, but this just crops the graph, and won't let me go back to the points that get cropped out. Dashboard setup: var rangeFitter = new google.visualization.ControlWrapper({ 'controlType': 'DateRangeFilter', 'containerId': 'filter_div', 'options': { 'filterColumnLabel': 'Closed Date' } }); var lineChart = new google.visualization.ChartWrapper({ 'chartType': 'ComboChart', 'containerId': 'chart_div', 'options': { animation: { duration: 500, startup: true, easing: 'out' }, hAxis: { gridlines: { count: 4, units: { days: { format: ['MMYY'] } } }, //this crops the graph :c viewWindow: { min: new Date(2016, 0, 11), max: new Date(2016, 2, 7) } }, 'height': 300, tooltip: { isHtml: true, trigger: 'selection' }, seriesType: 'bars', series: { 0: { targetAxisIndex: 0 }, 1: { type: 'line', pointSize: 5 } } } }); dashboard.bind(rangeFilter, lineChart); A: Never mind, I figured it out. I was searching for something within the chart options, but it turns out the DateRangeFilter control has a "state" parameter. Here it is implemented in my example var rangeFliter = new google.visualization.ControlWrapper({ 'controlType': 'DateRangeFilter', 'containerId': 'filter_div', 'options': { 'filterColumnLabel': 'Closed Date' }, //this will set the default range based on the values you provide 'state': {'lowValue': new Date(2016, 0, 11), 'highValue': new Date(2016, 1, 1)} });
{ "language": "en", "url": "https://stackoverflow.com/questions/34816271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying multiple Text Files on screen in Unity This code successfully reads in one text file and allows it to then be displayed as a GUI Label. I was wondering how I would do this for multiple text files? I wouldn't want them together just as individual Labels, I was thinking possibly Arrays or Lists but I wouldn't be sure. Thank you for you help using UnityEngine; using System.Collections; using System.IO; public class OnClick : MonoBehaviour { public StreamReader reader = null; public FileInfo theSourceFile = null; public void Start() { theSourceFile = new FileInfo(Application.dataPath + "/puzzles.txt"); if (theSourceFile != null && theSourceFile.Exists) reader = theSourceFile.OpenText(); if (reader == null) { Debug.Log("puzzles.txt not found or not readable"); } else { while ((txt = reader.ReadLine()) != null) { Debug.Log("-->" + txt); completeText += txt + "\n"; } } } public void OnGUI() { if (Input.GetKey(KeyCode.Tab)) { GUI.contentColor = Color.red; GUI.Label(new Rect(1000, 50, 400, 400), completeText); } } A: In the class, add a list of strings: private List<string> _allFiles = new List<string>(); Separate Start() to another method and call that for each of your files. At the end of each process, add the completeText variable to that list as shown below: public void Start() { theSourceFile = new FileInfo(Application.dataPath + "/puzzles.txt"); ProcessFile(theSourceFile); // set theSourceFile to another file // call ProcessFile(theSourceFile) again } private void ProcessFile(FileInfo file) { if (file != null && file.Exists) reader = file.OpenText(); if (reader == null) { Debug.Log("puzzles.txt not found or not readable"); } else { while ((txt = reader.ReadLine()) != null) { Debug.Log("-->" + txt); completeText += txt + "\n"; } _allFiles.Add(completeText); } } Finally, in your OnGui() method, add a loop around the GUI.Label call. int i = 1; foreach(var file in _allFiles) { GUI.Label(new Rect(1000, 50 + (i * 400), 400, 400), file); i++; } This assumes that you want the labels to appear vertically, and with no gap between them.
{ "language": "en", "url": "https://stackoverflow.com/questions/32374373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pd.scatter_matrix not working on pandas version 1.4.2 Here is my code: import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split fruits = pd.read_table('readonly/fruit_data_with_colors.txt') from matplotlib import cm X = fruits[['height', 'width', 'mass', 'color_score']] y = fruits['fruit_label'] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) cmap = cm.get_cmap('gnuplot') scatter = pd.scatter_matrix(X_train, c= y_train, marker = 'o', s=40, hist_kwds={'bins':15}, figsize=(9,9), cmap=cmap) My education had pandas version '0.19.2' and pd.scatter_matrix works fine. But I got the error message below when I run it on my Jupyter Notebook with pandas '1.4.2.'. AttributeError: module 'pandas' has no attribute 'scatter_matrix' How can I make it run on my Jupyter Notebook? A: I guess it has now changed to pandas.plotting.scatter_matrix Have a look at the document below. https://pandas.pydata.org/docs/reference/api/pandas.plotting.scatter_matrix.html
{ "language": "en", "url": "https://stackoverflow.com/questions/73299300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facing GCC installation issue while setting up airflow on hadoop cluster I have set up a three nodes Hadoop cluster for dev environment wherein one act as a master node and other being as a datanodes. cluster has been set up with below configurations/version: Operating System: Red Hat Enterprise Linux Server 7.7 python 3.7.3 anaconda 2 spark 2.45 I would like to install and configure airflow with mysql as a backend database on this hadoop cluster set up. I thought of asking something else regarding configuring MySQL as a backend database but receiving an error while running pip on master node itself. pip install apache-airflow Error Message: Running setup.py install for setproctitle ... error ERROR: Complete output from command /root/anaconda2/bin/python -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-TUrT4x/setproctitle/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-GdyZzq/install-record.txt --single-version-externally-managed --compile: ERROR: running install running build running build_ext building 'setproctitle' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src gcc -pthread -B /root/anaconda2/compiler_compat -Wl,--sysroot=/ -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DHAVE_SYS_PRCTL_H=1 -DSPT_VERSION=1.1.10 -I/root/anaconda2/include/python2.7 -c src/setproctitle.c -o build/temp.linux-x86_64-2.7/src/setproctitle.o unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command "/root/anaconda2/bin/python -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-TUrT4x/setproctitle/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-GdyZzq/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-TUrT4x/setproctitle/ when I typed which gcc, I get this. which gcc /usr/bin/which: no gcc in (/home/xyz/anaconda2/envs/python3.7.2/bin:/home/xyz/anaconda2/bin:/home/xyz/spark-2.4.5-bin-hadoop2.7/bin:/usr/local/bin:/usr/bin:/usr/local/sbin: /usr/sbin:/home/xyz/jdk1.8.0_241/bin:/home/xyz/hadoop-2.7.7/bin:/home/xyz/.local/bin:/home/xyz/bin) 'xyz' is user name I am looking for some help to solve above issue and suggestion regarding airflow for the above mentioned configurations. A: gcc is a pre-requisite for Apache Airflow and it looks like it is not installed. You can install it using this command, sudo yum install gcc gcc-c++ -y You might need these development packages as well, sudo yum install libffi-devel mariadb-devel cyrus-sasl-devel -y
{ "language": "en", "url": "https://stackoverflow.com/questions/60926009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: my VPCis out of ips, how can I connect my EKS cluster to new VPC My VPC is out of IPs and we need more IPs. how Can I connect my EKS cluster to new VPC?
{ "language": "en", "url": "https://stackoverflow.com/questions/71039333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Localize "CHOOSE AN ITEM" text on PickerFlyoutBase of ComboBox in WP8.1 How do I localize the PickerFlyoutBase.Title of a ComboBox in the Resources.resw language resource file in WP 8.1? <ComboBox x:Uid="myUid" PlaceholderText="Some Text" PickerFlyoutBase.Title="Changed Text"> <ComboBoxItem Content="a"/> </ComboBox> PickerFlyoutBase.Title is the text to replace the CHOOSE AN ITEM text on the flyout. A: I had real trouble with this and finally with some support which led me in the right direction I managed to get the syntax correct, this is entered in the Name column of the Resources.resw file. myUid.[using:Windows.UI.Xaml.Controls.Primitives]PickerFlyoutBase.Title
{ "language": "en", "url": "https://stackoverflow.com/questions/33370258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django buggy template tag - 'NoneType' object has no attribute 'source' Wondering what is causing this? Had me stumped for some time, everything checks out in console when running in pieces as a side note: the template is using the same object in other places and displaying values - the object in template is also the same one loaded in the console below error 'NoneType' object has no attribute 'source' template {% form_transaction prop %} console value of prop >>> prop = VacationHome.objects.get(pk=1) >>> prop <VacationHome: Samantha Dunn's vacation home at Close to Disney> >>> prop.sell 0 >>> prop.rent 1 >>> count = 0 >>> string = '' >>> type = [] >>> num = 0 >>> for tr in TRANSACTION_MODEL: ... if getattr(prop, tr, False): ... type.append(count+1) ... cur_count = count+1 ... string += '<li><label for="id_transaction_%s"><input type="checkbox" name="transaction" value="%s" id="id_transaction_%s" />%s</label></li>' % (count, cur_count, count, TRANSACTION_TITLE[count][1]) ... num += 1 ... count += 1 ... >>> string '<li><label for="id_transaction_1"><input type="checkbox" name="transaction" value="2" id="id_transaction_1" />Rental</label></li>' DEFINITIONS TRANSACTION_TITLE = ( (1, 'Purchase'), (2, 'Rental'), (3, 'Exchange'), ) TRANSACTION_MODEL = ['sell', 'rent', 'exchange'] template tag @register.tag def prop_form_transaction(parser, token): try: tag_name, prop = token.split_contents() count = 0 string = '' type = [] num = 0 for tr in TRANSACTION_MODEL: if getattr(prop, tr, False): type.append(count+1) cur_count = count+1 string += '<li><label for="id_transaction_%s"><input type="checkbox" name="transaction" value="%s" id="id_transaction_%s" />%s</label></li>' % (count, cur_count, count, TRANSACTION_TITLE[count][1]) num += 1 count += 1 if num: if num > 1: return string else: return '<input type="hidden" name="transaction" value="'#+str(type[0])+'" />' except ValueError: raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0] views def property_list_city(request, type, city): city = str(city).replace('-', ' ') if type == 'timeshare': timeshares = Timeshare.objects.filter(resort__city__icontains=city).filter(available__icontains=True) resorts = Resort.objects.filter(city__icontains=city) objects = chain(timeshares, resorts) elif type == 'vacation_home': objects = VacationHome.objects.filter(city__icontains=city) else: objects = False context = { #line 265 'properties' : objects, 'title' : city, 'type' : type, } return render_to_response('properties/properties_list.html', context_instance=RequestContext(request, context)) traceback Environment: Request Method: GET Request URL: http://localhost:8000/properties/single/vacation_home/1/ Django Version: 1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.humanize', 'properties', 'config', 'sorl.thumbnail', 'haystack', 'south', 'debug_toolbar'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/alvin/workspace/timeshare/properties/views.py" in property_single 272. return property_single_context(request, type, property) File "/home/alvin/workspace/timeshare/properties/views.py" in property_single_context 265. return render_to_response('properties/single.html', context, context_instance=RequestContext(request)) File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string 103. t = get_template(template_name) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template 82. template = get_template_from_string(source, origin, template_name) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template_from_string 90. return Template(source, origin, name) File "/usr/local/lib/python2.6/dist-packages/django_debug_toolbar-0.8.1.alpha-py2.6.egg/debug_toolbar/panels/template.py" in new_template_init 28. old_template_init(self, template_string, origin, name) File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in __init__ 168. self.nodelist = compile_string(template_string, origin) File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in compile_string 189. return parser.parse() File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse 285. compiled_result = compile_func(self, token) File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in do_extends 169. nodelist = parser.parse() File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse 285. compiled_result = compile_func(self, token) File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in do_block 147. nodelist = parser.parse(('endblock', 'endblock %s' % block_name)) File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse 289. self.extend_nodelist(nodelist, compiled_result, token) File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in extend_nodelist 56. node.source = token.source Exception Type: AttributeError at /properties/single/vacation_home/1/ Exception Value: 'NoneType' object has no attribute 'source' Any ideas for where to look in debugging this are welcomed - big huge thanks in advance if you happen to know what is causing the error A: I've run into this a few times and it's always been the same thing (for me at least). If the template tag function doesn't return anything this error pops up. class MyTag(template.Node): def __init__(self, name): self.name=name def render(self, context): context[self.name]='czarchaic' #return an empty string since we've only modified the context return '' @register.tag def my_tag(parser, token): bits=token.split_contents() if len(bits)==2: return MyTag(bits[1]) #return an empty string if all test fail return '' EDIT Looking at your code it would appear that if num were still 0 at the if num: check this tag would not return anything, resulting in this error. A: Line 265 (or 272) of your source views.py is sending an object that is a 'NoneType' which deeper code is trying to get the 'source' attribute from. In other words, you're sending a blank (NoneType) object to the template engine, so look at your code above these lines and see which objects don't have a value when you send them away.
{ "language": "en", "url": "https://stackoverflow.com/questions/1879614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I create a dictionary that indexes the location of certain keys? I have a class that inherits the dict object. my_subclassed_dict = SubclassedDictionary({ "id": {"value1": 144 "value2": "steve", "more" {"id": 114} }, "attributes": "random" }) On initialization of SubclassedDictionary, I would like paths generated which match a certain condition. Hypothetically, if I was to make this condition, 'index all numbers above 100' This could perhaps then access my_subclassed_dict.get_paths(), which would then return some kind of structure resembling this: [ ['id', 'value1'], ['id', 'more', 'id',] ] In short, how can I subclass dict which generates paths for keys matching a certain condition, on instantiation? EDIT Since someone asked for an example implementation. However the problem with this is that it doesn't handle nested dictionaries. class SubclassedDictionary(dict): paths = [] def __init__(self, *args, **kwargs): self.update(*args, **kwargs) # use the free update to set keys def update(self, *args, **kwargs): temp = args[0] for key, value in temp.items(): if isinstance(value, int): if value > 100: self.paths.append(key) super(SubclassedDictionary, self).update(*args, **kwargs) dictionary = { "value1": 333, "v2": 99, "v2": 129, "v3": 30, "nested": { "nested_value" 1000 } } new_dict = SubclassedDictionary(dictionary) print(new_dict.paths) # outputs: ['v2','value1'] If it did work as intended. print(new_dict.paths) Would output [ ['v2'], ['value1'], ['nested', 'nested_value'] ] A: From what I understand, you want a dictionary that is capable of returning the keys of dictionaries within dictionaries if the value the key's are associated with match a certain condition. class SubclassedDictionary(dict): def __init__(self, new_dict, condition=None, *args, **kwargs): super(SubclassedDictionary, self).__init__(new_dict, *args, **kwargs) self.paths = [] self.get_paths(condition) def _get_paths_recursive(self, condition, iterable, parent_path=[]): path = [] for key, value in iterable.iteritems(): # If we find an iterable, recursively obtain new paths. if isinstance(value, (dict, list, set, tuple)): # Make sure to remember where we have been (parent_path + [key]) recursed_path = self._get_paths_recursive(condition, value, parent_path + [key]) if recursed_path: self.paths.append(parent_path + recursed_path) elif condition(value) is True: self.paths.append(parent_path + [key]) def get_paths(self, condition=None): # Condition MUST be a function that returns a bool! self.paths = [] if condition is not None: return self._get_paths_recursive(condition, self) def my_condition(value): try: return int(value) > 100 except ValueError: return False my_dict = SubclassedDictionary({"id": {"value1": 144, "value2": "steve", "more": {"id": 114}}, "attributes": "random"}, condition=my_condition) print my_dict.paths # Returns [['id', 'value1'], ['id', 'more', 'id']] There's a few benefits to this implementation. One is that you can change your condition whenever you want. In your question it sounded like this may be a feature that you were interested in. If you want a different condition you can easily write a new function and pass it into the constructor of the class, or simply call get_paths() with your new condition. When developing a recursive algorithm there are 3 things you should take into account. 1) What is my stopping condition? In this case your literal condition is not actually your stopping condition. The recursion stops when there are no longer elements to iterate through. 2) Create a non-recursive function This is important for two reasons (I'll get to the second later). The first reason is that it is a safe way to encapsulate functionality that you don't want consumers to use. In this case the _get_paths_recursive() has extra parameters that if a consumer got a hold of could ruin your paths attribute. 3) Do as much error handling before recursion (Second reason behind two functions) The other benefit to a second function is that you can do non-recursive operations. More often than not, when you are writing a recursive algorithm you are going to have to do something before you start recursing. In this case I make sure the condition parameter is valid (I could add more checking to make sure its a function that returns a bool, and accepts one parameter). I also reset the paths attribute so you don't end up with a crazy amount of paths if get_paths() is called more than once. A: The minimal change is something like: class SubclassedDictionary(dict): def __init__(self, *args, **kwargs): self.paths = [] # note instance, not class, attribute self.update(*args, **kwargs) # use the free update to set keys def update(self, *args, **kwargs): temp = args[0] for key, value in temp.items(): if isinstance(value, int): if value > 100: self.paths.append([key]) # note adding a list to the list # recursively handle nested dictionaries elif isinstance(value, dict): for path in SubclassedDictionary(value).paths: self.paths.append([key]+path) super(SubclassedDictionary, self).update(*args, **kwargs) Which gives the output you're looking for: >>> SubclassedDictionary(dictionary).paths [['v2'], ['value1'], ['nested', 'nested_value']] However, a neater method might be to make paths a method, and create nested SubclassedDictionary instances instead of dictionaries, which also allows you to specify the rule when calling rather than hard-coding it. For example: class SubclassedDictionary(dict): def __init__(self, *args, **kwargs): self.update(*args, **kwargs) # use the free update to set keys def update(self, *args, **kwargs): temp = args[0] for key, value in temp.items(): if isinstance(value, dict): temp[key] = SubclassedDictionary(value) super(SubclassedDictionary, self).update(*args, **kwargs) def paths(self, rule): matching_paths = [] for key, value in self.items(): if isinstance(value, SubclassedDictionary): for path in value.paths(rule): matching_paths.append([key]+path) elif rule(value): matching_paths.append([key]) return matching_paths In use, to get the paths of all integers larger than 100: >>> SubclassedDictionary(dictionary).paths(lambda val: isinstance(val, int) and val > 100) [['v2'], ['value1'], ['nested', 'nested_value']] One downside is that this recreates the path list every time it's called. It's worth noting that you don't currently handle the kwargs correctly (so neither does my code!); have a look at e.g. Overriding dict.update() method in subclass to prevent overwriting dict keys where I've provided an answer that shows how to implement an interface that matches the basic dict's. Another issue that your current code has is that it doesn't deal with keys subsequently being removed from the dictionary; my first snippet doesn't either, but as the second rebuilds the path list each time it's not a problem there.
{ "language": "en", "url": "https://stackoverflow.com/questions/30488061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Multiprocessing speed issue I have a nested for loop of the form while x<lat2[0]: while y>lat3[1]: if (is_inside_nepal([x,y])): print("inside") else: print("not") y = y - (1/150.0) y = lat2[1] x = x + (1/150.0) #here lat2[0] represents a large number Now this normally takes around 50s for executing. And I have changed this loop to a multiprocessing code. def v1find_coordinates(q): while not(q.empty()): x1 = q.get() x2 = x1 + incfactor while x1<x2: def func(x1): while y>lat3[1]: if (is_inside([x1,y])): print x1,y,"inside" else: print x1,y,"not inside" y = y - (1/150.0) func(x1) y = lat2[1] x1 = x1 + (1/150.0) incfactor = 0.7 xvalues = drange(x,lat2[0],incfactor) #this drange function is to get list with increment factor as decimal cores = mp.cpu_count() q = Queue() for i in xvalues: q.put(i) for i in range(0,cores): p = Process(target = v1find_coordinates,args=(q,) ) p.start() p.Daemon = True processes.append(p) for i in processes: print ("now joining") i.join() This multiprocessing code also takes around 50s execution time. This means there is no difference of time between the two. I also have tried using pools. I have also managed the chunk size. I have googled and searched through other stackoverflow. But can't find any satisfying answer. The only answer I could find was time was taken in process management to make both the result same. If this is the reason then how can I get the multiprocessing work to obtain faster results? Will implementing in C from Python give faster results? I am not expecting drastic results but by common sense one can tell that running on 4 cores should be a lot faster than running in 1 core. But I am getting similar results. Any kind of help would be appreciated. A: You seem to be using a thread Queue (from Queue import Queue). This does not work as expected as Process uses fork() and it clones the entire Queue into each worker Process Use: from multiprocessing import Queue
{ "language": "en", "url": "https://stackoverflow.com/questions/38147699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: background image doesn't show <div id="home"> <div class="landing-text"> <h1 class="display-2"> One Piece MMO</h1> <button type="button" class="btn btn-primary btn-lg">Watch Trailer</button> <button type="button" class="btn btn-primary btn-lg">Download Game</button> </div> </div> #home{ background: url(images/bg.png) no-repeat fixed center; display: table; height: 100%; position: relative; width: 100%; background-size: cover; } why i can't see the background image? can't figure out the problem....tried "background-image: url("image/bg.png") and "background: url("images/bg.png") A: If your CSS code is inline with the HTML, make sure it's enclosed in <style> tags: <div id="home"> <div class="landing-text"> <h1 class="display-2"> One Piece MMO</h1> <button type="button" class="btn btn-primary btn-lg">Watch Trailer</button> <button type="button" class="btn btn-primary btn-lg">Download Game</button> </div> </div> <style type="text/css"> #home { background: url(images/bg.png) no-repeat fixed center; display: table; height: 100%; position: relative; width: 100%; background-size: cover; } </style> A: Your code is actually correct, which leads me to believe it could have something to do with the path to the image you want to display. I changed the url to a universal one leading to random cat image and it worked. That or enclose your image path between quotes, as in url("images/bg.png"). JS Fiddle Check your image path! <div id="home"> <div class="landing-text"> <h1 class="display-2"> One Piece MMO</h1> <button type="button" class="btn btn-primary btn-lg">Watch Trailer</button> <button type="button" class="btn btn-primary btn-lg">Download Game</button> </div> </div> #home { background: url(http://www.catster.com/wp-content/uploads/2015/06/google-cat-search-2014-_0.jpg) no-repeat fixed center; display: table; height: 100%; position: relative; width: 100%; background-size: cover; } A: You can run it. <div id="home"> <div class="landing-text"> <h1 class="display-2"> One Piece MMO</h1> <button type="button" class="btn btn-primary btn-lg">Watch Trailer</button> <button type="button" class="btn btn-primary btn-lg">Download Game</button> </div> </div> <style> #home { background: url(https://image.freepik.com/free-vector/happy-childrens-day-design_23-2147705019.jpg) no-repeat fixed center; display: table; height: 100%; position: relative; width: 100%; background-size: cover; } <style>
{ "language": "en", "url": "https://stackoverflow.com/questions/49638017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to upload a file through Apollo Server v4 and graphql-upload? im using Apollo server v4 with expressjs and NEXTJS for my Frontend. What I want is to create a Mutation like uploadFile using upload-graphql to upload a file to my Backend Server. upload type export interface Upload { filename: string; mimetype: string; encoding: string; createReadStream: () => Stream; } my mutation: @Mutation(() => Boolean) async uploadFile( @Arg("picture", () => GraphQLUpload) { createReadStream, filename }: Upload ): Promise<boolean> { return new Promise(async (resolve, reject) => createReadStream() .pipe(createWriteStream(__dirname + `/../../../images/${filename}`)) .on("finish", () => resolve(true)) .on("error", () => reject(false)) ); } } but the problem is, whenever I upload something like a photo, I get ApolloError: Argument Validation Error . I think, there is no way to upload through new Version of Apollo server (v4) yet, but if anyone knows about it, please help me ! my dependencies "dependencies":{ "@apollo/server": "^4.3.1", "express": "^4.18.2", "graphql": "^16.6.0", "graphql-fields": "^2.0.3", "graphql-middleware": "^6.1.33", "graphql-scalars": "^1.20.1", "graphql-shield": "^7.6.5", "graphql-upload": "14", "type-graphql": "2.0.0-beta.1", }, I tried to upload a file on my frontend nextjs - apollo-upload-client. and front-end upload Scenario It's just a hobby project, and I know there are alternatives to kind of use other approach to upload files => like extra endpoint api or using like s3, but I want to get my files uploaded through graphql.
{ "language": "en", "url": "https://stackoverflow.com/questions/75250427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Google Cloud Build keep docker images between steps by default? Does Google Cloud Build keep docker images between build steps by default? In their docs they say built images are discarded after every step but I've seen examples in which build steps use images produced in previous build ones! so, are built images discarded on completion of every step or saved somewhere for coming steps? Here's my cloudbuild.yaml. steps: - name: gcr.io/cloud-builders/docker args: - build - '-t' - '${_ARTIFACT_REPO}' - . - name: gcr.io/cloud-builders/docker args: - push - '${_ARTIFACT_REPO}' - name: gcr.io/google.com/cloudsdktool/cloud-sdk args: - run - deploy - my-service - '--image' - '${_ARTIFACT_REPO}' - '--region' - us-central1 - '--allow-unauthenticated' entrypoint: gcloud A: Yes, Cloud Build keep images between steps. You can imagine Cloud Build like a simple VM or your local computer so when you build an image it is stored in local (like when you run docker build -t TAG .) All the steps run in the same instance so you can re-use built images in previous steps in other steps. Your sample steps do not show this but the following do: steps: - name: 'gcr.io/cloud-builders/docker' args: - build - -t - MY_TAG - . - name: 'gcr.io/cloud-builders/docker' args: - run - MY_TAG - COMMAND - ARG As well use the previous built image as part of an step: steps: - name: 'gcr.io/cloud-builders/docker' args: - build - -t - MY_TAG - . - name: 'MY_TAG' args: - COMMAND - ARG All the images built are available in your workspace until the build is done (success or fail). P.D. The reason I asked where did you read that the images are discarded after every step is because I've not read that in the docs unless I missed something, so if you have the link to that please share it with us.
{ "language": "en", "url": "https://stackoverflow.com/questions/71185816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing values with $_SESSION I have a problem while passing a value of an element via $_SESSION <?php session_start(); ?> <?php echo "<table>"; $con = mysql_connect("localhost","root","") or die ("problem"); mysql_query("SET NAMES 'utf8'", $con); mysql_select_db("dedomena"); $query = mysql_query("SELECT * FROM posts"); $i = 1; while($query_row = mysql_fetch_assoc($query)) { echo "<tr><td onclick='myFunction($i)'><a href='page.php'>".$query_row['title']."</a></td><td>$i</td>"; $i = $i + 1; }; echo "</table>"; ?> <script> function myFunction($i) { alert(x); <?php $_SESSION["id"] = $i; ?> } </script> The code on page2.php is <?php session_start(); ?> <?php echo $_SESSION["id"]; ?> When I click on an element on the first page I get the right id But when I try to pass the values to the second page it only shows me the number 10! Note: the number 10 is obviously because of the $i + 1 loop but how do I fix that? A: <script> function myFunction($i) { alert(x); <?php $_SESSION["id"] = $i; ?> } </script> You are trying to include php code in javascript thinking you will change php global variable at client end when a click event happens. This is not the right way. Sessions are for saving session variables. You are using sessions for passing GET params to server. Session variables can't be updated from client end since they are not exposed to client. Sessions in PHP : The contents of the SESSION superglobal cannot be changed. This lives on the server and the client has no way to access this. However, a session id is passed to the client so that when the client contacts the server the server knows which session to use. This value could be changed which would allow a user to use someone else's session. A: As brute_force already mentioned, the problem is <?php $_SESSION["id"] = $i; ?> This code is executed server-side, before the page is sent to the user. That's the difference between PHP and javascript: javascript is executed at runtime, while the page is loaded, but the PHP in the page is executed in order to load the page, so the SESSION["id"] is set to 10 in your while-loop, and then, in the mentioned piece of code, put into the SESSION variable. In order to get the variable in the session at runtime, you must create a request to a PHP script on the server, which in turn puts it in the SESSION. Have a look at (jQuery) ajax, that's the easiest solution in this case. A: but what you are trying to do? php is server side language and javascript is client side. you must do a ajax call to pass the value ID. A: You can not execute server side codes on client through JS . Coming to your problem you can send it to php via string query ** BEST SOLUTION FOR THIS PROBLEM IS STRING QUERY** while($query_row = mysql_fetch_assoc($query)) { echo "<tr><td><a href='page.php?id='.$i>".$query_row['title']."</a></td><td>$i</td>"; $i = $i + 1; } page2.php <?php id=$_REQUEST['id']; echo $id; ?> Or if rigid to session use ajax. A cheat solution with iframe(without ajax) is below <?php echo "<table>"; $con = mysql_connect("localhost","root","") or die ("problem"); mysql_query("SET NAMES 'utf8'", $con); mysql_select_db("dedomena"); $query = mysql_query("SELECT * FROM posts"); $i = 1; while($query_row = mysql_fetch_assoc($query)) { echo "<tr><td onclick='myFunction(i)'><a href='page.php'>".$query_row['title']."</a></td><td>$i</td>"; $i = $i + 1; } echo "</table>"; ?> function myFunction(i) { alert(i); var html=''; html +='<div id="fakeDiv">'; html +='<form action="setSession.php" method="post" id="fakefrm" target="ifk">'; html +='<input type="hidden" name="jsvar" id="jsvar" value="'+val+'"/>'; html +='</form>'; html +='</div>'; html +='<iframe name='ifk'style='display:none;></iframe>'; var c=document.createElement('div'); document.body.innerHTML += html; document.getElementById('fakefrm').submit(); document.body.removeChild(document.getElementById('fakeDiv')); } setSession.php <?php session_start(); $_SESSION['id']=$_POST['jsvar']; ?> Add setSession.php in your project.. NOTE - In fact , if i see this answer in quick , i caste downvote this , but this answer is an instant relief for a guy who is unaware the name "ajax"
{ "language": "en", "url": "https://stackoverflow.com/questions/32921774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Which of the growth rates log(log *n) and log*(log n) is faster? As n gets large, of the two functions log*(log n) and log(log* n) will will be faster? Here, the log* function is the iterated logarithm, defined here: I suspect these are the same, just written differently, but is there any difference between them? A: log* n is the iterated logarithm, which for large n is defined as log* n = 1 + log*(log n) Therefore, log*(log n) = (log* n) - 1, since log* is the number of times you need to apply log to the value before it reaches some fixed constant (usually 1). Doing another log first just removes one step from the process. Therefore, log(log* n) will be much smaller than log* (log n) = log* n - 1 since log x < x - 1 for any reasonably large x. Another, more intuitive way to see this: the log* function is significantly better at compressing large numbers than the log function is. Therefore, if you wanted to take a large number and make it smaller, you'd get way more efficiency by computing log* n first to contract n as much as you can, then use log on that (log (log* n)) to pull down what's left. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/19172489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Grouping of images using KMean I want to apply kmeans clustering on the data that i have obtained. Here,I am attaching a link. Please check. http://arxiv.org/ftp/arxiv/papers/0910/0910.1849.pdf From the algorithm provided in this link,I have done till 4th point of 3.2 ie of Block Truncation algorithm. I am not knowing how to proceed further. Please help.The code till where I have implemented is given below.Its in java. import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import java.util.ArrayList; public class BlockTruncation{ public static void main(String[] args) throws IOException { BufferedImage bufImgs = ImageIO.read(new File("C://Users/Chandni/chandni's pics/2013-04-06-1449.jpg")); ArrayList<Integer> RH=new ArrayList<Integer>(); ArrayList<Integer> RL=new ArrayList<Integer>(); ArrayList<Integer> GH=new ArrayList<Integer>(); ArrayList<Integer> GL=new ArrayList<Integer>(); ArrayList<Integer> BH=new ArrayList<Integer>(); ArrayList<Integer> BL=new ArrayList<Integer>(); /* ArrayList RL[]=new int[15]; int GH[]=new int[15]; int GL[]=new int[15]; int BH[]=new int[15]; int BL[]=new int[15];*/ int red[]=new int[(bufImgs.getWidth()* bufImgs.getHeight())]; int green[]=new int[(bufImgs.getWidth()* bufImgs.getHeight())]; int blue[]=new int[(bufImgs.getWidth()* bufImgs.getHeight())]; int c=0; for(int r=0;r<bufImgs.getWidth();r++) { for(int s=0;s<bufImgs.getHeight();s++) { int color = bufImgs.getRGB(r, s); red[c]=(color>>16) & 0xFF; green[c]=(color>>8) & 0xFF; blue[c]=color & 0xFF; c++; } } double mean_pix[]=new double[3]; mean_pix[0]=mean_no(red); mean_pix[1]=mean_no(green); mean_pix[2]=mean_no(blue); for(int k=0;k<mean_pix.length;k++) { System.out.println(mean_pix[k]); } for(int p=0;p<red.length;p++) { if(red[p]<mean_pix[0]) { /*for(int q=0;q<RL.length;q++) { RL[q]=red[p]; }*/ RL.add(red[p]); } else { /* for(int q=0;q<RL.length;q++) { RH[q]=red[p]; }*/ RH.add(red[p]); } } System.out.println("RH :"); { for(int g:RH) { System.out.println(g); } } System.out.println("RL :"); { for(int g:RL) { System.out.println(g); } } } static double mean_no(int[] col) { double sum=0; for(int rgb:col) { sum+=rgb; } return (sum/col.length); } } A: You need to read more literature. In particular on: * *Color Moments *k-means clustering Without reading this literature, you will not be able to understand the article you linked.
{ "language": "en", "url": "https://stackoverflow.com/questions/19744278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract array column by selecting one field of struct-array column in PySpark I have a dataframe df containing a struct-array column properties (array column whose elements are struct fields having keys x and y) and I want to create a new array column by extracting the x values from column properties. A sample input dataframe would be something like this import pyspark.sql.functions as F from pyspark.sql.types import * data = [ (1, [{'x':11, 'y':'str1a'}, ]), (2, [{'x':21, 'y':'str2a'}, {'x':22, 'y':0.22, 'z':'str2b'}, ]), ] my_schema = StructType([ StructField('id', LongType()), StructField('properties', ArrayType( StructType([ StructField('x', LongType()), StructField('y', StringType()), ]) ) ), ]) df = spark.createDataFrame(data, schema=my_schema) df.show() # +---+--------------------+ # | id| properties| # +---+--------------------+ # | 1| [[11, str1a]]| # | 2|[[21, str2a], [22...| # +---+--------------------+ df.printSchema() # root # |-- id: long (nullable = true) # |-- properties: array (nullable = true) # | |-- element: struct (containsNull = true) # | | |-- x: long (nullable = true) # | | |-- y: string (nullable = true) On the other hand, the desired output df_new should look like df_new.show() # +---+--------------------+--------+ # | id| properties|x_values| # +---+--------------------+--------+ # | 1| [[11, str1a]]| [11]| # | 2|[[21, str2a], [22...|[21, 22]| # +---+--------------------+--------+ df_new.printSchema() # root # |-- id: long (nullable = true) # |-- properties: array (nullable = true) # | |-- element: struct (containsNull = true) # | | |-- x: long (nullable = true) # | | |-- y: string (nullable = true) # |-- x_values: array (nullable = true) # | |-- element: long (containsNull = true) Does anybody know a solution for such task? Ideally, I am looking for a solution which operates row-by-row without relying on F.explode. In fact in my actual database I have not identified an equivalent to id column yet, and after calling F.explode I would not be sure of how to coalesce back together the exploded values. A: Try using properties.x then all values are extracted from the properties array. Example: df.withColumn("x_values",col("properties.x")).show(10,False) #or by using higher order functions df.withColumn("x_values",expr("transform(properties,p -> p.x)")).show(10,False) #+---+-------------------------+--------+ #|id |properties |x_values| #+---+-------------------------+--------+ #|1 |[[11, str1a]] |[11] | #|2 |[[21, str2a], [22, 0.22]]|[21, 22]| #+---+-------------------------+--------+
{ "language": "en", "url": "https://stackoverflow.com/questions/70262490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MS Word Macros 2003 - 2007 I work in a remote region with limited resources and technical expertise as a Project Manager and a new project I just got handed was the testing of MS Word 2003 macros on a MS Word 2007 platform. The Macros were initially developed by Corel a few years ago when we migrated they migrated that specific division from WordPerfect to MS Office 2003. I have a test workstation with Office 2007 installed and followed the steps required to get the Macros work to no avail. Any tips and recommendations would be appreciated. I do have experience in VBA and XML coding but the VBA was about 10 years ago and I haven't looked at XML code in at least 4 years. If I can sollicit some high level suggestions, if coding needs to changed or updated, I can try to figure it out or contract it out but just want to make sure that I have exhausted all other options prior opting for that route. Thanks A: I doubt you will get any useful answers in this forum, which concerns itself with programming questions. But you might want to try this discussion group, which seems to be just what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: grunt assemble - page.json data not showing in layout template So I know this seems really silly, but I just can't get page data to display in my layout using grunt-assemble. I can get the page data to display in the page.hbs, and that to appear in the layout, but just can't get the page.json to appear in the layout.hbs Here are the relevant bits, if you need anything more, let me know. layouts/default.hbs <!DOCTYPE html> <html lang="en"> <head> <!-- I've tried all of these and none work --> <!-- <title>{{ data.title }}</title> --> <!-- <title>{{ config.title }}</title> --> <!-- <title>{{ this.title }}</title> --> <!-- <title>{{ this.page.title }}</title> --> <!-- <title>{{ page.title }}</title> --> <title>{{ title }}</title> </head> <body> <!-- Page Output --> {{> body }} </body> </html> data/home.json { "title": "Home Page", "body": "this is test text", "id": "home-page" } pages/home.hbs <section id="{{ home.id }}"> <h1>Hello World - {{ home.body }}</h1> </section> assembled output <!DOCTYPE html> <html lang="en"> <head> <!-- <title></title> --> <!-- <title></title> --> <!-- <title></title> --> <!-- <title></title> --> <!-- <title></title> --> <title></title> </head> <body> <title></title> <!-- Page Output --> <section id="home-page"> <h1>Hello World - this is test text</h1> </section> </body> </html> If you need anymore info, please let me know. I'm sure it's something super simple. A: So the solution was two things * *upgrade handlebars to v0.4.41 (I was on 0.4.0) *use {{ page.title }}
{ "language": "en", "url": "https://stackoverflow.com/questions/25395809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parse and Stringify JSON in PHP 4 Possible Duplicate: php4 with json data Is there a library or class that provides parsing (JSON to PHP primitives/arrays) and stringifying (PHP primitives/arrays to JSON) for PHP 4? A: This also looks like it may be a viable option http://willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/
{ "language": "en", "url": "https://stackoverflow.com/questions/3486226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: querySelectorAll vs getElementsByClassName When I looping through a nodelist obtained by querySelectorAll and add a new class for each one,it takes much less time(3ms) than which obtained by getElementsByClassName(100ms).Why? var container = document.getElementById('box-container'); var button = document.getElementById('button'); for (var i = 0; i < 3000; i++) { var div = document.createElement('div'); div.classList.add('box'); div.index = i; container.appendChild(div); } button.addEventListener('click', function() { var box1 = container.getElementsByClassName('box'); for (var i = 1;i < box1.length; i+=2){ box1[i].classList.toggle('gray'); }; var box2 = container.querySelectorAll('.box'); for (var i = 1;i < box2.length; i+=2){ box2[i-1].classList.toggle('gray'); }; }); A: The difference is the type of list you are running on. box1 is a NodeList (a.k.a a live node list) which is updated when the DOM changes. box2 is an array, which is a non-live list - so changing the DOM doesn't affect it. What happens when you iterate on box1 is that on every class toggle, the box1 list is updated, which causes the overhead. Here's a test you can easily run: var container = document.getElementById('box-container'); var button = document.getElementById('button'); for (var i = 0; i < 6000; i++) { // added 3000 more to challenge modern browsers... var div = document.createElement('div'); div.classList.add('box'); div.index = i; container.appendChild(div); } button.addEventListener('click', function () { var box1 = container.getElementsByClassName('box'); for (var i = 1; i < box1.length; i += 2) { box1[i].classList.toggle('gray'); } var deadBox1 = []; for (i = 0; i < box1.length; i++) { deadBox1[i] = box1[i]; } for (var i = 1; i < deadBox1.length; i += 2) { deadBox1[i].classList.toggle('gray'); } var box2 = container.querySelectorAll('.box'); for (i = 1; i < box2.length; i += 2) { box2[i - 1].classList.toggle('gray'); } }); Now run the chrome performance (or timeline) tool. You can see the diff here:
{ "language": "en", "url": "https://stackoverflow.com/questions/44320620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding pixel position public static void sample(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); int value[][] = new int[width][height]; int valueR[][] = new int[width][height]; int valueG[][] = new int[width][height]; int valueB[][] = new int[width][height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { int pixel = image.getRGB(i, j); value[i][j] = pixel; Color c = new Color(pixel); valueR[i][j]= c.getRed(); valueG[i][j] = c.getGreen(); valueB[i][j] = c.getBlue(); System.out.println("Red value = "+valueR[i][j]); System.out.println("Green value ="+valueG[i][j]); System.out.println("Blue value"+valueB[i][j]); } } } The above code is to store RGB values and pixel color values of an image in an array separately. public static BigInteger modPow(BigInteger a1, BigInteger e, BigInteger n) { BigInteger r = 1; for (int i = e.bitLength() - 1; i >= 0; i--) { r = (r.multiply(r)).mod(n); if (e.testBit(i)) { r = (r.multiply(a1)).mod(n); } } System.out.println("C value = " + r); int lng = 3; BigInteger bi = BigInteger.valueOf(lng); BigInteger a = r.divide(bi); BigInteger b = r.mod(bi); System.out.println("pixel position a = " + a); System.out.println("modulus value b = " + b); return r; } In the above code am finding pixel position where i need to embed the secret bit.so i need to go to that specific pixel to embed the message.But in the previous code am storing pixel color in array value[][].i need to search through the array value[][] to get the pixel position which i got in last code. Note: a1 is the position of current bit of information file to embed {e,n} is public key My question is how to find the pixel positions? A: To find the position of a pixel is a simple concept with a complex execution. I've written some code here that takes a BufferedImage and searches through it for a pixel of a specific color. import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import java.io.IOException; public class pixelSearch { public static void main(String[] args) { //I don't know where you're getting your image but i'll get one from file File image = new File("image.bmp"); try { BufferedImage imageToSearch = ImageIO.read(image); Color colorToFind = new Color(255,255,255); //define color to search for with RGB vals 255,255,255 //for more information on constructing colors look here: http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html int[] pixelCoordinates = pSearch( colorToFind, imageToSearch ); //search for the pixel System.out.println("Found pixel at (" + pixelCoordinates[0] + "," + pixelCoordinates[1] + ")."); //display coordinates } catch (IOException e) { System.out.println(e.toString()); } } private static int[] pSearch ( Color c, BufferedImage pic ){ int cVal = c.getRGB(); //get integer value of color we are trying to find int x1 = 0; int y1 = 0; int x2 = pic.getWidth(); int y2 = pic.getHeight(); int[] XArray = new int[x2-x1+1]; //create an array to hold all X coordinates in image int iterator = 0; while (iterator <= x2) { XArray[iterator] = x1 + iterator; iterator++; } int [] YArray = new int[y2-y1+1]; //create an array to hold all Y coordinates in image iterator = 0; while (iterator <= y2) { YArray[iterator] = y1 + iterator; iterator++; } //next we iterate throug all the possible coordinates to check each pixel for (int yVal : YArray) { for (int xVal : XArray) { int color = pic.getRGB(xVal, yVal); //get the color of pixel at coords (xVal, yVal) if (color == cVal) { //if the color is equal to the one we inputted to the function int[] cPos = {xVal, yVal}; //store the coordinates return cPos; //return the coordinates } } } int[] returnVal = {-1,-1}; //if we didn't find it return -1, -1 return returnVal; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/15553122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode 10 loses support for Subversion. Is there any free alternative? Relese Notes So in the release note, Apple says that they have removed support for Subversion but I want to know there is any free alternative to use subversion tool freely. I already heard about Versions, SmartSVN, and Xversion etc but this tools are not free.
{ "language": "en", "url": "https://stackoverflow.com/questions/52478825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to limit width of Text in SwiftUI I was trying to make a speech bubble like so: Text("Hello my name is Johnny Miller and I am new here") .foregroundColor(.white) .padding() .background(.blue) .cornerRadius(25) However I thought the speech bubble looked way wider than it needed to be. Therefore I tried to limit how far out the bubble can stretch before it goes to a new line. The easiest way which came to mind was this: Text("Hello my name is Johnny Miller and I am new here") .foregroundColor(.white) .padding() .background(.blue) .cornerRadius(25) .frame(maxWidth: 300) // << Limits how wide it can stretch This worked for long messages but when the text was small such as "Hello," the frame would stay at 300pts and refused to resize to its ideal width. I tried using .fixedSize() but this would cause truncation when the text was long. I couldn't find a way to cap the width of the text and still have it be its ideal size. If someone could propose a solution I would be extremely grateful. In short: The text frame should never cross 300pts in width but it can be as tall as it wants. Thanks in advance! Edit These are the things I've tried so far: Text("Hello") .foregroundColor(.white) .padding() .background(.blue) .cornerRadius(25) .frame(maxWidth: 300) .lineLimit(nil) which causes the "Hello" bubble to have a frame of 300 (I've provided an image above) and I've tried: Text("Hello my name is Johnny Miller and I am new here") .foregroundColor(.white) .padding() .background(.blue) .cornerRadius(25) .frame(maxWidth: 300) .lineLimit(nil) .fixedSize() which gave me:
{ "language": "en", "url": "https://stackoverflow.com/questions/65651326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Opengl hide parts of the screen (code snippet. I know it's ugly but i wanted to make it work before making it better so please don't pay too much attention to the structure) I modified slightly the glfw example present in the documentation to have a triangle that rotates when pressing the right arrow key and draws a circle described by the position of one of his vertices (the blue one in this case). I clear the GL_COLOR_BUFFER_BIT only when initializing the window to avoid having to store all the coordinates that will be needed to draw the line (they would be hundreds of thousands in the final program), that means that on the screen every time i press the right arrow a "copy" of the triangle is draws rotated by 12 degrees and a line is drawn that connects the old blue angle position to the new one. The problem now is that i would want to be able to press the escape key GLFW_KEY_ESCAPE and "delete" the triangles while keeping the lines drawn. I tried using a z-buffer to hide the triangles behind a black rectangle but only the last line drawn is visualized (i think this is because opengl doesn't know the z of the previous lines since i don't store them). Is there a way to do what i want without having to store all the point coordinates and then clearing the whole screen and redrawing only the lines? If this is the case, what would be the best way to store them? Here is part of the code i have so far. bool check = 0; Vertex blue = {0.f, 0.6f, 0.5f}; Vertex green = {0.6f,-0.4f, 0.5f}; Vertex red = {-0.6f, -0.4f, 0.5f}; Vertex line = {0.f, 0.6f, 0.f}; Vertex line2 = {0.f, 0.6f, 0.f}; static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) check = !check; if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS) { line.x = line2.x; line.y = line2.y; rotation -= 12; rad = DegToRad(-12); double x = line.x*cos(rad) - line.y * sin(rad); double y = line.y * cos(rad) + line.x * sin(rad); line2.x = x; line2.y = y; } int main(void) { GLFWwindow *window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(1280, 720, "Example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glClear(GL_COLOR_BUFFER_BIT); while (!glfwWindowShouldClose(window)) { glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); float ratio; int width, height; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(rotation, 0.f, 0.f, 1.f); glBegin(GL_TRIANGLES); glColor3f(1.f, 0.f, 0.f); glVertex3f(red.x, red.y, red.z); glColor3f(0.f, 1.f, 0.f); glVertex3f(green.x, green.y, green.z); glColor3f(0.f, 0.f, 1.f); glVertex3f(blue.x, blue.y, blue.z); glEnd(); glLoadIdentity(); glLineWidth(1.0); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(line.x, line.y, line.z); glVertex3f(line2.x, line2.y, line2.z); glEnd(); if (check){ //hide the triangles but not the lines } glEnd(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } A: I clear the GL_COLOR_BUFFER_BIT only when initializing the window That's your problem right there. It's idiomatic in OpenGL to always start with a clear operation of the main framebuffer color bits. That is, because you don't know the state of your window main framebuffer when the operating system is asking for a redraw. For all you know it could have been all replaced with cat pictures in the background without your program knowing it. Seriously: If you have a cat video running and the OS felt the need to rearrange your window's main framebuffer memory this is what you might end up with. Is there a way to do what i want without having to store all the point coordinates and then clearing the whole screen and redrawing only the lines? For all intents and purposes: No. In theory one could come up with a contraption made out of a convoluted series of stencil buffer operations to implement that, but this would be barking up a very wrong tree. Here's something for you to try out: Draw a bunch of triangles like you do, then resize your window down so there nothing remains, then resize it back to its original size… you see where the problem? There's a way to address this particular problem, but that's not what you should do here. The correct thing is to redraw everything. If you feel that that's to slow you have to optimize your drawing process. On current generation hardware it's possible to churn out on the order of 100 million triangles per second.
{ "language": "en", "url": "https://stackoverflow.com/questions/42949571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Springboot REST API returning 404 when deployed in Jboss EAP.7.1.0 I have created a simple Springboot REST api, which is working fine when deployed in Tomacat container but returning 404 message when deployed in Jboss EAP 7.1.0. Need help to resolve this problem. Below are the classes i wrote along with pom.xml and application.properties SpringRestApiApplication.java package com.test.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringRestApiApplication{ public static void main(String[] args) { SpringApplication.run(SpringRestApiApplication.class, args); } } RestExample.java package com.test.spring.web.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/test") public class RestExample { @GetMapping(value = "/hello") public String HelloWorldAPI() { return "Hello World!"; } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>SpringRestAPI</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>SpringRestAPI</name> <description>Rest API Test Example</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <finalName>rest-api</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> application.properties server.servlet-path=/* A: You are using 7.1.0 right. Remove this and try server.servlet-path=/*
{ "language": "en", "url": "https://stackoverflow.com/questions/68325751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to execute an unordered SQL script I have a SQL script but there is an issue with the order of the statements in the script e.g. INSERT INTO PERMISSIONS_FOR_ROLE (ROLE_ID, PERMISSION_ID) VALUES (3, 8); INSERT INTO permissions (id, name) VALUES (8, 'update'); The order of occurrence in the script should have been reverse! And this results in a error because the foreign key with id 8 is not yet inserted when the first statement executes leading to: [Code: -177, SQL State: 23503] integrity constraint violation: foreign key no parent; PERMISSIONS_FOR_ROLE_PERM_FK table: PERMISSIONS_FOR_ROLE value: 8 statements used to create the relationships are as below create table PERMISSIONS ( ID bigint not null, NAME varchar(255), primary key (ID) ); create table PERMISSIONS_FOR_ROLE ( ROLE_ID bigint not null, PERMISSION_ID bigint not null, primary key (ROLE_ID, PERMISSION_ID) ); alter table PERMISSIONS_FOR_ROLE add constraint permissions_for_role_perm_fk foreign key (PERMISSION_ID) references PERMISSIONS; Any suggestions on how to execute such a script ? I tried manually changing the order and the script executes properly but is there any other way to do it as its run as part of a ANT build target. A: For mass inserts with very large scripts that are out of order, you can disable referential integrity checks with: SET DATABASE REFERENTIAL INTEGRITY FALSE see http://hsqldb.org/doc/2.0/guide/management-chapt.html#mtc_sql_settings on how to check for possible violations after the insert.
{ "language": "en", "url": "https://stackoverflow.com/questions/67015606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# - reading from binary log file that is updated every 6 seconds with 12k of data I have a binary log file with streaming data from a sensor (Int16). Every 6 seconds, 6000 samples of type Int16 are added, until the sensor is disconnected. I need to poll this file on regular intervals, continuing from last position read. Is it better to a) keep a filestream and binary reader open and instantiated between readings b) instantiate filestream and binary reader each time I need to read (and keep an external variable to track the last position read) c) something better? EDIT: Some great suggestions so far, need to add that the "server" app is supplied by an outside source vendor and cannot be modified. A: If it's always adding the same amount of data, it may make sense to reopen it. You might want to find out the length before you open it, and then round down to the whole number of "sample sets" available, just in case you catch it while it's still writing the data. That may mean you read less than you could read (if the write finishes between you checking the length and starting the read) but you'll catch up next time. You'll need to make sure you use appropriate sharing options so that the writer can still write while you're reading though. (The writer will probably have to have been written with this in mind too.) A: Can you use MemoryMappedFiles? If you can, mapping the file in memory and sharing it between processes you will be able to read the data by simply incrementing the offset for your pointer each time. If you combine it with an event you can signal your reader when he can go in an read the information. There will be no need to block anything as the reader will always read "old" data which has already been written. A: I would recommend using pipes, they act just like files, except stream data directly between applications, even if the apps run on different PCs (though this is really only an option if you are able to change both applications). Check it out under the "System.IO.Pipes" namespace. P.S. You would use a "named" pipe for this (pipes are supported in 'c' as well, so basically any half decent programming language should be able to implement them) A: I think that (a) is the best because: * *Current Position will be incremented as you read and you don't need to worry about to store it somewhere; *You don't need to open it and seek required position (it shouldn't be much slower to reopen but keeping it open gives OS some hints for optimization I believe) each time you poll it; *Other solutions I can think out requires PInvokes to system interprocess synchronisation primitives. And they won't be faster than file operations already in framework. You just need to set proper FileShare flags: Just for example: Server: using(var writer = new BinaryWriter(new FileStream(@"D:\testlog.log", FileMode.Append, FileAccess.Write, FileShare.Read))) { int n; while(Int32.TryParse(Console.ReadLine(), out n)) { writer.Write(n); writer.Flush(); // write cached bytes to file } } Client: using (var reader = new BinaryReader(new FileStream(@"D:\testlog.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { string s; while (Console.ReadLine() != "exit") { // allocate buffer for new ints Int32[] buffer = new Int32[(reader.BaseStream.Length - reader.BaseStream.Position) / sizeof(Int32)]; Console.WriteLine("Stream length: {0}", reader.BaseStream.Length); Console.Write("Ints read: "); for (int i = 0; i < buffer.Length; i++) { buffer[i] = reader.ReadInt32(); Console.Write((i == 0 ? "" : ", ") + buffer[i].ToString()); } Console.WriteLine(); } } A: you could also stream the data into a database, rather than a file as another alternative, then you wouldn't have to worry about file locking. but if you're stuck with the file method, you may want to close the file each time you read data from it; it depends alot on how complicated the process writing to the file is going to be, and whether it can detect a file locking operation and respond appropriately without crashing horribly.
{ "language": "en", "url": "https://stackoverflow.com/questions/1170538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Docker and localhost seem not to connect as should So Im new to Docker and wanted to start a docker container with a apache system on it that should just show one simple "hello world" php-file. I followed a youtube tutorial for that. Now I could set up the container and I could run the image, I also connected the port of the container with the port outside, but it seems like its not working. My http://localhost:80 (<- I connected Port 80 to port 80 in the container) and nothing happened. Is it possible, that my firewall is killing the connection? Here is the dockerfile and my php file: PHP <? php echo "Hello World"; Dockerfile FROM php:7.0-apache COPY src/ /var/www/html EXPOSE 80 The tutorial is this one: https://www.youtube.com/watch?v=YFl2mCHdv24 Unfortunately my knowledge is so limited, that I have not even an idea where to search for the probelm. Edit: After building my container I used docker run -p 80:80 <name of container> Thanks for taking your time A: You have to run the image with the -p option like: docker run -p 80:80 <image name> Expose is only working for internal docker image communication. -p then maps the host port to the container port: -p <host_port>:<container_port>
{ "language": "en", "url": "https://stackoverflow.com/questions/50188086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kubernetes pod readiness probe failed I have a kubernetes cluster running with minikube in my local. I am trying to train a model with KubeFlow's TFJob operator which implements TensorFlow's distributed training strategies. The YAML for the TFJob looks like this apiVersion: kubeflow.org/v1 kind: TFJob metadata: name: tf-job-cifar namespace: kubeflow spec: tfReplicaSpecs: Worker: replicas: 2 restartPolicy: Never template: metadata: annotations: kubectl.kubernetes.io/default-container: tensorflow spec: containers: - name: tensorflow imagePullPolicy: IfNotPresent image: tf-dist-cifar10:1.0 livenessProbe: exec: command: - cat - /tmp/healthy initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: exec: command: - cat - /tmp/healthy initialDelaySeconds: 10 periodSeconds: 5 When I deploy this YAML using kubectl create -f <file-name>.yaml. The pods thus created for the job fails with error: Readiness probe failed: Get "http://172.17.0.31:15021/healthz/ready": dial tcp 172.17.0.31:15021: connect: connection refused The error after few minutes changes to: Readiness probe failed: Get "http://172.17.0.31:15021/healthz/ready": context deadline exceeded (Client.Timeout exceeded while awaiting headers) Where could possibly the error be?
{ "language": "en", "url": "https://stackoverflow.com/questions/70529033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issues with font/text-color in css I keep having issues with the text-color rule in css whereas I'll have a code like this: #horizontal > ul > li > a:hover { background-color: rgb(255,101,101); text-color: black; And the background color will change, but the text remains blue. A: The colour property in CSS is 'color' not 'text-color'. A: Use color: black; "text-color" is not a function. A: Use color #horizontal > ul > li > a:hover { background-color: rgb(255,101,101); color: black;
{ "language": "en", "url": "https://stackoverflow.com/questions/37976418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Authenticating gcloud SDK in Cloud Run with user credentials I'm currently working on a project that will automatically set up a new Firebase/Gcloud project. It relies heavily on the Firebase CLI and gcloud SDK with user credentials for several mandatory steps. I am now trying to move this project to a Docker container on Cloud Run. I have been able to authenticate the Firebase CLI with user credentials using their built-in token-based CI command. I would like to ask if it's possible to authenticate the gcloud SDK using a similar method. Why service accounts probably won't work I realize that service-to-service programs like this should be authenticated with service accounts. In my case, however, the flow of the program goes like this: * *Use Firebase CLI to create a new gcloud/firebase project *Use gcloud SDK to add IAM-bindings, enable APIs, billing, etc. for the new project I am unable to use a service account to authenticate the requests in step 2 as the project has only just been created and I therefore haven't yet had the opportunity to give any service accounts permission to edit it or download the key-files. This is why I'd like to authenticate with a token representing user credentials. By default, the Cloud Run environment actually has access to a service account for the project hosting the container. Since this service account doesn't have permission to edit the newly created project, using it for authenticating is pointless. Ideas so far * *gcloud auth login --no-launch-browser - Requires user interaction and the key that is provided seems to be unique per login session *Since the Firebase CLI is authenticated with user credentials, maybe there's a way to use that to authenticate the gcloud SDK? *Would it be possible to let a service account inherit all permissions from a user? I have seen a couple of examples of this, but they only work on a per-project level. I realize how unseemly this solution would be. *The gcloud SDK seems to save user credentials in the /root/.config/gcloud folder. I went against all sensible logic and copied this folder over when setting up my Docker-container. This actually works, when I run it on a local Docker container, but when I run it on Cloud Run, the default service account seems to override all other credentials. A local Docker container can access the copied configurations, but even though the files are copied successfully, the gcloud SDK doesn't seem to recognize them. EDIT: My intentions are to allow less tech-savvy colleges to create a new Firebase project with a large set of pre-defined settings via the click of a button. This includes the following steps: * *Set up a new Firebase project (which automatically sets up a new Google Cloud project) *Enable billing *Set user IAM roles and upgrade/download service accounts *Add Google Analytics *Add Cloud storage *Create new Cloud storage bucket *Add Firestore Native mode *Copy pre-defined cloud functions and security roles and deploy them to the cloud The created Google Cloud project must be a part of our Google Cloud organization. The owner of the project is not important as I manually set IAM roles after creation. All of the above steps work on my local system and when I use idea #4, they also work on a generic docker container outside of Cloud Run. The problems I'm dealing with is authenticating the request for step #2 and step #3. As both of these requests deal with the newly created project, the default service identity for Cloud Run can't have the required roles to authenticate these requests at this time. This is why I am looking for a way to authenticate via the same user credentials used in step #1 by the Firebase CLI, as those credentials will have owner privileges by default. A: I'm not sure that what you want to achieve is possible. And even if a hack is possible, you don't know if a day it will be broken because of version update or API change. In addition, using a personal account into an app running on a VM is not a good idea. The log will trace you as user and not the app identity (the service account). What are your personal actions (on your computer and your access to the Cloud) and the app actions (those perform on behalf of you)? If your concern is about the deployment, you can have a look to terraform or you can even script you own deployment. I'm not sure to have caught all your blockers and problems, tell us more, maybe there is good workaround!!
{ "language": "en", "url": "https://stackoverflow.com/questions/60968104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }