_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d8901
train
Example of application.ini: resources.log.err.writerName = "Stream" resources.log.err.writerParams.stream = APPLICATION_PATH "/../data/logs/ERR.log" ;resources.log.stream.formatterParams.format = "%priority%:%message% %timestamp% %priorityName% %info% PHP_EOL" resources.log.err.filterName = "Priority" resources.log.err.filterParams.priority = 3 resources.log.err.filterParams.operator = "==" resources.log.warn.writerName = "Stream" resources.log.warn.writerParams.stream = APPLICATION_PATH "/../data/logs/WARN.log" ;resources.log.warn.formatterParams.format = "%priority%:%message%:%ip%:%userid% %timestamp% %priorityName% %info% PHP_EOL" resources.log.warn.filterName = "Priority" resources.log.warn.filterParams.priority = 4 resources.log.warn.filterParams.operator = "==" In bootstrap: protected function _initLog() { $options = $this->getOption('resources'); $partitionConfig = $this->getOption('log'); $logOptions = $options['log']; $logger = Zend_Log::factory($logOptions); $logger->addPriority('USERACTION', 8); $logger->addPriority('DBLOG', 9); Zend_Registry::set('logger', $logger); } Then in codes: $this->logger = Zend_Registry::get('logger'); $this->logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']); $this->logger->setEventItem('userid', $this->userId); Use this way: $this->logger->log('Test error', Zend_Log::WARN); Or this way: $this->logger->warn('Test error'); Or this way: $this->logger->log('Test error', 4); A: You can use filters to accomplish this. Just let higher priority events pass through the filters until you want to log them. http://framework.zend.com/manual/en/zend.log.filters.html What's wrong in your setup is that you are trying to use the same writer which you should not. Use the filters to choose the writers and associate certain log files with certain writers, as shown in the second part of the example. I think something like that should do the trick: resources.log.stream.writerName = "myDebugWriter" resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/debug.log" resources.log.stream.filterName = "Priority" resources.log.stream.filterParams.priority = Zend_Log::WARN resources.log.stream.writerName = "myInfoWriter" resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/info.log" resources.log.stream.filterName = "Priority" resources.log.stream.filterParams.priority = Zend_Log::INFO
unknown
d8902
train
UIView don't like "UILabel and UIImageView" which have highlighted state. You should do it by yourself in - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self.highlighted = !self.highlighted ; } Or add UITapGestureRecognizer or UILongPressGestureRecognizer(if you want detect long pressed gesture) to the view.
unknown
d8903
train
I've figured it out elsewhere on stackoverflow. It seems that my problem was not related to NelmioApiDocBundle, but to FOSRestBundle. I've had to change only one FOSRest setting in config.yml: fos_rest: routing_loader: include_format: false I've found the solution here
unknown
d8904
train
IEnumerable<Story> recentStories = (from s in stories orderby s.Date descending select s).Take(5).OrderBy(s => s.Title);
unknown
d8905
train
You can solve your problem just adding: workspaceRoot: '..', to your snowpack.config.js file. Basically it tells snowpack to process everything from the parent folder (..) through it's pipeline. It will pick up dependencies and process everything. In your case, you could import files from shared in app-1 by using relative paths, and without creating any symlinks: import something from '../shared/something'; You can find more about workspaceRoot property in snowpack's documentation. A: You should be able to specify a relative path to the folder in your mount object as another key: { "mount": { "../../shared": "/_dist_" } } this should serve your files from the shared directory from the /_dist_ folder.
unknown
d8906
train
Look at the 'asset' twig function : You can find it in \Symfony\Bundle\TwigBundle\Extensions\AssetsExtension public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null) { $url = $this->container->get('templating.helper.assets')->getUrl($path, $packageName, $version); if (!$absolute) { return $url; } return $this->ensureUrlIsAbsolute($url); } Instead of calling '{{asset}}' in your extension, just call the public function getAssetUrl()
unknown
d8907
train
There is no follow_redirect field on an adcreative, it's a flag you provide when creating the creative itself, but it isn't a property of the resulting creative
unknown
d8908
train
The reader monad is a set of rules we can apply to cleanly compose readers. You could use partial to make a reader, but it doesn't really give us a way to put them together. For example, say you wanted a reader that doubled the value it read. You might use partial to define it: (def doubler (partial * 2)) You might also want a reader that added one to whatever value it read: (def plus-oner (partial + 1)) Now, suppose you wanted to combine these guys in a single reader that adds their results. You'll probably end up with something like this: (defn super-reader [env] (let [x (doubler env) y (plus-oner env)] (+ x y))) Notice that you have to explicitly forward the environment to those readers. Total bummer, right? Using the rules provided by the reader monad, we can get much cleaner composition: (def super-reader (do-m reader-m [x doubler y plus-oner] (+ x y))) A: You can use partial to "do" the reader monad. Turn let into a do-reader by doing syntactic transformation on let with partial application of the environment on the right-hand side. (defmacro do-reader [bindings & body] (let [env (gensym 'env_) partial-env (fn [f] (list `(partial ~f ~env))) bindings* (mapv #(%1 %2) (cycle [identity partial-env]) bindings)] `(fn [~env] (let ~bindings* ~@body)))) Then do-reader is to the reader monad as let is to the identity monad (relationship discussed here). Indeed, since only the "do notation" application of the reader monad was used in Beyamor's answer to your reader monad in Clojure question, the same examples will work as is with m/domonad Reader replaced with do-reader as above. But, for the sake of variety I'll modify the first example to be just a bit more Clojurish with the environment map and take advantage of the fact that keywords can act as functions. (def sample-bindings {:count 3, :one 1, :b 2}) (def ask identity) (def calc-is-count-correct? (do-reader [binding-count :count bindings ask] (= binding-count (count bindings)))) (calc-is-count-correct? sample-bindings) ;=> true Second example (defn local [modify reader] (comp reader modify)) (def calc-content-len (do-reader [content ask] (count content))) (def calc-modified-content-len (local #(str "Prefix " %) calc-content-len)) (calc-content-len "12345") ;=> 5 (calc-modified-content-len "12345") ;=> 12 Note since we built on let, we still have destructing at our disposal. Silly example: (def example1 (do-reader [a :foo b :bar] (+ a b))) (example1 {:foo 2 :bar 40 :baz 800}) ;=> 42 (def example2 (do-reader [[a b] (juxt :foo :bar)] (+ a b))) (example2 {:foo 2 :bar 40 :baz 800}) ;=> 42 So, in Clojure, you can indeed get the functionality of the do notation of reader monad without introducing monads proper. Analagous to doing a ReaderT transform on the identity monad, we can do a syntactic transformation on let. As you surmised, one way to do so is with partial application of the environment. Perhaps more Clojurish would be to define a reader-> and reader->> to syntactically insert the environment as the second and last argument respectively. I'll leave those as an exercise for the reader for now. One take-away from this is that while types and type-classes in Haskell have a lot of benefits and the monad structure is a useful idea, not having the constraints of the type system in Clojure allows us to treat data and programs in the same way and do arbitrary transformations to our programs to implement syntax and control as we see fit.
unknown
d8909
train
1 - here to set the date from jDateChooser to string String dob=""+jDateChooser1.getDate(); 2 - to insert the date to database you should set the format first SimpleDateFormat Date_Format = new SimpleDateFormat("yyyy-MM-dd"); Date_Format.format(jDateChooser1.getDate())
unknown
d8910
train
Django's template language is (by design) pretty dumb/restricted. In his comment, Davind Wolever points at Accessing a dict by variable in Django templates?, where an answer suggests to make a custom template tag. I think that in your case, it is best to handle it in your view code. Instead of only passing along a player into your context, pass both the level ID and the level name. Possibly you can even directly pass the image url and the level name? Not constructing the URL in your template makes it more readable.
unknown
d8911
train
Use function substring_index. select substring_index(quot_number, '/', -1) from yourtable
unknown
d8912
train
Your code can be a little faster by caching the function and the button outside the interval (function() { const button = document.querySelector(".click-button"); const buttonClick = () => button.click(); if (button) setInterval(buttonClick, 5); })(); If the button does not exist at all, then the code above will not work. Then you do need the mutation oberver A: Instead of polling for the button, you could use a MutationObserver that will notify you when the button changes or is inserted into the document. Unless you can get to the event that triggers the button activation, this is probably the fastest you can do. Assuming that the button is inserted into a <div id="button-container"></div>: const callback = mutations => {mutations.forEach(m => m.addedNodes.forEach(node => node.tagName === 'BUTTON' && node.click()))} const observer = new MutationObserver(callback) const container = document.getElementById('button-container') observer.observe(container, {childList: true}) Have a look at this codepen Replacing the forEach() with a for will give you a few additional nanoseconds.
unknown
d8913
train
Here's how to do it with a batch file: @echo off set cnt=1 for /f %%f in ('dir /b "D:\Backup\Input_*.xls"') do set /a cnt+=1 if %cnt% lss 10 (move "E:\InputFolder\Input.xls" "D:\Backup\Input_0%cnt%.xls") else (move "E:\InputFolder\Input.xls" "D:\Backup\Input_%cnt%.xls") copy "E:\Template\Input.xls" "E:\InputFolder\Input.xls" You can have more control over your files' naming convention (not to mention deletion of old files) if you use a Script Task, though. A: can we use a 'File system task' instead. It helps us Renaming a file. You will have to use a 'For-Each loop Container' as well.
unknown
d8914
train
I'll go out on a limb and guess that your problem is that the C compiler complains that it doesn't know how to allocate memory for a struct dictionary_object when it compiles db_functions.c. Its confusion is understandable because the file you're asking it to compile doesn't tell it what struct dictionary_object is at all. You should move the definition of the struct to a header file that both of your .c files include. A: You need to define the structure contents and layout once in an include file. Also define the "extern" definitions for all functions and statics for the code there. In any file wanting to use those structs or definitions, include the header file (something like db_struct.h). db_struct.h: struct dictionary_obhect { char dictionary ... } extern struct dictionary_object dict_obj; extern int db_initialization(); db_struct.c: #include "db_struct.h" struct dictionary_object dict_obj; int db_initiatilization() { dict_obc.word_count = 0; } Note this is all pretty old-style C code. Modern C++ etc. have other means of doing similar things.
unknown
d8915
train
Get the returned data as "id" type first, then create your PKPass object by "initWithData" with your returned data. You don't need to convert it to NSData. Remember to import Passkit.
unknown
d8916
train
In case someone is wondering how can we integrate django_filters filter_class with api_views: @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def filter_data(request, format=None): qs = models.YourModal.objects.all() filtered_data = filters.YourFilter(request.GET, queryset=qs) filtered_qs = filtered_data.qs .... return response.Ok(yourData) A: Adding to @ChidG's answer. All you need to do is override the DjangoFilterBackend's filter_queryset method, which is the entry point for the filter, and pass it the instance of your APIView. The important point to note here is you must declare filter_fields or filter_class on the view in order to get the filter to work. Otherwise it just return your queryset unfiltered. If you're more curious about how this works, the class is located at django_filters.rest_framework.backends.py In this example, the url would look something like {base_url}/foo?is_active=true from django_filters.rest_framework import DjangoFilterBackend class FooFilter(DjangoFilterBackend): def filter_queryset(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) if filter_class: return filter_class(request.query_params, queryset=queryset, request=request).qs return queryset class Foo(APIView): permission_classes = (AllowAny,) filter_fields = ('name', 'is_active') def get(self, request, format=None): queryset = Foo.objects.all() ff = FooFilter() filtered_queryset = ff.filter_queryset(request, queryset, self) if filtered_queryset.exists(): serializer = FooSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response([], status=status.HTTP_200_OK) A: To use the functionality of DjangoFilterBackend, you could incorporate the filter_queryset method from GenericViewSet, which is the DRF class that inherits from APIView and leads to all specific 'generic' view classes in DRF. It looks like this: def filter_queryset(self, queryset): """ Given a queryset, filter it with whichever filter backend is in use. You are unlikely to want to override this method, although you may need to call it either from a list view, or from a custom `get_object` method if you want to apply the configured filtering backend to the default queryset. """ for backend in list(self.filter_backends): queryset = backend().filter_queryset(self.request, queryset, self) return queryset https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py A: Here If you are using APIView, There is nothing to do with filters.So you have to do like get_data = request.query_params #or request.GET check both Then Rental.objects.filter(city=get_data['city'], place=get_data['place'])
unknown
d8917
train
If you've been able to retrieve the data already, you should only need to update the DOM using $('#id').val(value). I did a bit of digging, and it looks like your API returns the title and authors like this, hence the use of json.items[0].volumeInfo in the new callback code. { "items": [{ "volumeInfo": { "title": "Example Title", "subtitle": "Example Subtitle", "authors": [ "Example Author" ] } }] } $(document).ready(function() { $('#submitCode').click(function() { var x; var isbn = $('#isbn').val(); var xmlhttp = new XMLHttpRequest(); var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn; xmlhttp.onreadystatechange = function() { /*<![CDATA[*/ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { x = JSON.parse(xmlhttp.responseText); callback(x); } /*]]>*/ }; xmlhttp.open("GET", url, true); xmlhttp.send(); function callback (json) { var book = json.items[0].volumeInfo $('#author').val(book.authors.join('; ')) $('#title').val(book.title) }; }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input id="isbn" type="text" value="1904764827"/>ISBN</label> <div class="input-field col s6 m6"> <input id="author" name="author" th:field="*{author}" type="text" class="validate" /> <label for="author">Author</label> </div> <div class="input-field col s6 m6"> <input id="title" name="title" th:field="*{title}" type="text" class="validate" /> <label for="title">Title</label> </div> <button id="submitCode">Submit</button>
unknown
d8918
train
Scripted fields in Kibana are powered by lucene expressions, which only support numeric operations right now. Support for things like string manipulation and date parsing will probably be added at some point, but I doubt scripts will even support executing aggregations. Scripted fields are primarily for converting a number before using it, or creating a synthetic field which is the combination of two or more other fields. Down the road they may even support things like extracting the day of the week from a date, or the portion of a string that matches a regular expression.
unknown
d8919
train
As of January 2013, there is no official way to delete temporary files, so imagemagic leaves you to do it yourself. I also use a cron job that runs every 20 minutes since the temporary files are 10+ GB in size. A: It means your ImageMagick installation is NOT functioning properly! The fact that it leaves magick-* files in tmp says that ImageMagick process died and that's why it didn't delete those files. You should configure memory limits etc. Refer http://www.imagemagick.org/script/resources.php A: I've had this problem for a period of time, my code issue was that I didn't use the destroy function: $im->destroy(); When calling the destroy function it will delete the temp files that are made under the /tmp directory. This is for PHP and maybe it will help someone. A: It is always better to use a task based approach and not to clog up the runtime with deleting stuff. just run the task once a day.
unknown
d8920
train
You need to add the libraries (jar files) to the project's build path in Eclipse. You can find these libraries in Maven Central here: Log4j Jackson A: You need to add the relevant Jar files to your projects classpath http://javahowto.blogspot.co.uk/2006/06/set-classpath-in-eclipse-and-netbeans.html A: You need to add the log4j jar to your classpath. Assuming that you're not using maven or gradle, you can download it from Apache's site. Then put it in some suitable shared location and add it to your project's classpath. I think it's about the 3rd or 4th item in the Project Properties dialog, iirc.
unknown
d8921
train
Set USER_AGENT = 'zara (+http://www.yourdomain.com)' in settings.py. Solves the issue. You could put your own user agent if you like also.
unknown
d8922
train
That is happening because test is a directory and mod_dir module that runs after mod_rewrite adds a trailing slash and does a 301 redirect. You can prevent it by adding this line on top of your .htaccess: DirectorySlash Off However keep in mind that it is considered a security risks as it can show directory listing. You can make this redirect in htaccess itself using this rule: # add a trailing slash to directories RewriteCond %{DOCUMENT_ROOT}/$1 -d RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]
unknown
d8923
train
local is a reserved keyword which is used extensively in many Bash completion packages, and generally in Bash code with functions. You really don't want to override it because that will break those packages. Call your alias something else. (Maybe also don't use an alias at all - shell functions are much more versatile - but that doesn't change the substance of your problem.) A: local is a shell builtin. You can see this from type local After your alias it has become a cd. The same type command will now give local is aliased to `cd /mnt/c/Users/NYCZE/OneDrive/' Now, line 295 in my /usr/share/bash-completion/bash_completion file is local cword words=() So, local is no longer behaving as expected by that file. The line in your file similarly uses local.
unknown
d8924
train
From the comments it appears you missed a step of the setup, namely as the instructions tell you to paste the response of curl to ~/.npmrc. The response should be pasted in the ~/.npmrc (in Windows %USERPROFILE%/.npmrc) file. As an alternative, on Linux and MacOS you can just pipe the output of curl to ~/.npmrc as follows: curl -u<USERNAME>:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da >> ~/.npmrc Using the >> operator will preserve the current content of ~/.npmrc and append the output of curl to the file (or create it if it's not there yet). If you want to overwrite the current ~/.npmrc file, just use the > operator instead. A: The Bintary 'Set Me Up' Instructions (referenced in step 1.3 of https://docs.daml.com/app-dev/bindings-js/getting-started.html) say to run a curl command and the to run npm config set @<SCOPE>:registry https://api.bintray.com/npm/digitalassetsdk/npm When I skip the npm config step I have no problems.
unknown
d8925
train
T-SQL has a function for that: DATALENGTH for all SQL Server versions. Example: DECLARE @lat DECIMAL(10, 7) = 3.14151415141514151415; SELECT @lat, DATALENGTH(@lat); Result: 3.1415142 and 5 (because DECIMAL(10,7) uses 5 bytes to be stored). Documentation: https://learn.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql?view=sql-server-ver15 For example, I have a table called Applications with these columns: (id VARCHAR(32), debug BIT, connectionString VARCHAR(2048), firebaseKey VARCHAR(4096)). As we know, VARCHAR doesn't allocate all the space (just what you need, so 'A' is 1 byte in VARCHAR). These queries: SELECT SUM(DATALENGTH(id)) AS idSize, SUM(DATALENGTH(debug)) AS debugSize, SUM(DATALENGTH(connectionString)) AS connectionStringSize, SUM(DATALENGTH(firebaseKey)) AS firebaseKeySize FROM Applications; SELECT SUM( DATALENGTH(id) + DATALENGTH(debug) + DATALENGTH(connectionString) + DATALENGTH(firebaseKey) ) AS totalSize FROM Applications; will return my data size (in my case, with my rows, is 8, 2, 366, 4698 (total: 5074). There are 2 rows in that table. Notice that this does NOT represent the total size of my database (there are pages, descriptors, indexes, etc. involved.)* MSSQL has internal stored procedures to tell you the exactly size of your database in disk: * *EXEC sp_spaceused; for all database; *EXEC sp_spaceused N'schema.TableName'; for a specific table; *EXEC sp_helpdb N'DatabaseName'; if you want details from each file. A: Your can use below query : SELECT * FROM sys.types result of above query is below : name system_type_id user_type_id schema_id principal_id max_length precision scale collation_name is_nullable is_user_defined is_assembly_type default_object_id rule_object_id is_table_type -------------------- -------------- ------------ --------- ------------ ---------- --------- ----- ----------------- ----------- --------------- ---------------- ----------------- -------------- ------------- image 34 34 4 NULL 16 0 0 NULL 1 0 0 0 0 0 text 35 35 4 NULL 16 0 0 Persian_100_CI_AI 1 0 0 0 0 0 uniqueidentifier 36 36 4 NULL 16 0 0 NULL 1 0 0 0 0 0 date 40 40 4 NULL 3 10 0 NULL 1 0 0 0 0 0 time 41 41 4 NULL 5 16 7 NULL 1 0 0 0 0 0 datetime2 42 42 4 NULL 8 27 7 NULL 1 0 0 0 0 0 datetimeoffset 43 43 4 NULL 10 34 7 NULL 1 0 0 0 0 0 tinyint 48 48 4 NULL 1 3 0 NULL 1 0 0 0 0 0 smallint 52 52 4 NULL 2 5 0 NULL 1 0 0 0 0 0 int 56 56 4 NULL 4 10 0 NULL 1 0 0 0 0 0 smalldatetime 58 58 4 NULL 4 16 0 NULL 1 0 0 0 0 0 real 59 59 4 NULL 4 24 0 NULL 1 0 0 0 0 0 money 60 60 4 NULL 8 19 4 NULL 1 0 0 0 0 0 datetime 61 61 4 NULL 8 23 3 NULL 1 0 0 0 0 0 float 62 62 4 NULL 8 53 0 NULL 1 0 0 0 0 0 sql_variant 98 98 4 NULL 8016 0 0 NULL 1 0 0 0 0 0 ntext 99 99 4 NULL 16 0 0 Persian_100_CI_AI 1 0 0 0 0 0 bit 104 104 4 NULL 1 1 0 NULL 1 0 0 0 0 0 decimal 106 106 4 NULL 17 38 38 NULL 1 0 0 0 0 0 numeric 108 108 4 NULL 17 38 38 NULL 1 0 0 0 0 0 smallmoney 122 122 4 NULL 4 10 4 NULL 1 0 0 0 0 0 bigint 127 127 4 NULL 8 19 0 NULL 1 0 0 0 0 0 hierarchyid 240 128 4 NULL 892 0 0 NULL 1 0 1 0 0 0 geometry 240 129 4 NULL -1 0 0 NULL 1 0 1 0 0 0 geography 240 130 4 NULL -1 0 0 NULL 1 0 1 0 0 0 varbinary 165 165 4 NULL 8000 0 0 NULL 1 0 0 0 0 0 varchar 167 167 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0 binary 173 173 4 NULL 8000 0 0 NULL 1 0 0 0 0 0 char 175 175 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0 timestamp 189 189 4 NULL 8 0 0 NULL 0 0 0 0 0 0 nvarchar 231 231 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0 nchar 239 239 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0 xml 241 241 4 NULL -1 0 0 NULL 1 0 0 0 0 0 sysname 231 256 4 NULL 256 0 0 Persian_100_CI_AI 0 0 0 0 0 0 CalculatedCreditInfo 243 257 9 NULL -1 0 0 NULL 0 1 0 0 0 1 udt_QoutaDetail 243 258 21 NULL -1 0 0 NULL 0 1 0 0 0 1 BeforeUpdate 243 259 22 NULL -1 0 0 NULL 0 1 0 0 0 1 udt_StoreInventory 243 260 26 NULL -1 0 0 NULL 0 1 0 0 0 1 udt_WKFHistory 243 261 32 NULL -1 0 0 NULL 0 1 0 0 0 1 IDTable 243 262 1 NULL -1 0 0 NULL you can use max_length for size of each data type. A: http://msdn.microsoft.com/en-us/library/ms187752.aspx Money : 8 bytes int : 4 bytes id - depends on what you mean. A: If the table specified in the where clause contains a nvarchar, this query will give you how many characters there are for that column correctly! This detects if the column is "wide" and essentially divides by 2. More broad than just nvarchar. SELECT c.name, (CASE WHEN LEFT(ts.name, 1) = 'n' AND ts.[precision] = 0 AND ts.[scale] = 0 THEN c.max_length / ts.[bytes] ELSE c.max_length END) AS [length] FROM sys.columns AS c INNER JOIN sys.tables AS t ON t.object_id = c.object_ID INNER JOIN ( SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes] FROM ( SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits] FROM sys.types AS iits ) AS its ) AS ts ON ts.user_type_id = c.user_type_id WHERE t.name LIKE 'tb_tablename' -- LIKE is case insensitive Of course, you can just divide max_length on sys.columns by 2 if you know the column is an nvarchar. This is more for discovering table schema in a way that seems better for if new sql data types are introduced in the future. And you so-choose to upgrade to it. Pretty small edge case. Please edit and correct this answer if you find an edge case where bytes and bits are incorrect. Details: -- ([bits] + 7) / 8 means round up -- -- Proof: -- o (1 bit + 7 = 8) / 8 = 1 byte used -- o ((8 + 8 + 1 = 17 bytes) + 7 = 24) / 8 = 3 byes used -- o ((8 + 8 + 7 = 23 bytes) + 7 = 30) / 8 = 3.75 = integer division removes decimal = 3 SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes] FROM ( SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits] FROM sys.types AS its ) AS ts If someone knows that SQL Server stores the bit and byte sizes for each data type. Or a better way to get sys.columns size, please leave a comment!
unknown
d8926
train
The simple way (this requires both files to be PHP files): <?php require_once "your_php_file_here.php"; // Change to your PHP file here ?> <script type='text/javascript'> var info = "<?php echo $info; ?>"; alert(info); </script> This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value. The (in my opinion) better way (the file can be HTML) using Ajax: <script type='text/javascript'> var info; var xhr = new XMLHttpRequest(); xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here xhr.onload = function() { if (xhr.status === 200) { info = xhr.responseText; alert(info); } else { alert('Request failed: ' + xhr.status); } }; xhr.send(); </script> This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page. For this to work, you need to change your PHP code to: $info = "A message"; if (true){ $info = 'Message to be passed'; } echo $info; I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.
unknown
d8927
train
you can submit your credentials using an ajax call, then inside your success method, you can check whether it's successful or not & show error if not ok. If it's ok, you can hide modal manually & redirect user to home page. A: You would need to setup a function manually as Laravel's documentation explains. You will also need a route and an ajax request to make the login. Custom Login route: Route::post('/login', 'LoginController@authenticate'); In your view you will first need to setup a meta tag with the csrf token to protect yourself from attacks: <meta name="csrf-token" content="{{ csrf_token() }}"> Then in your ajax you could do this: $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: 'POST', url: '/login', data: [email: '', password: ''], success: function(controllerResponse) { if (!controllerResponse) { // here show a hidden field inside your modal by setting his visibility } else { // controller return was true so you can redirect or do whatever you wish to do here } } }); Custom controller method could be something like this: public function authenticate(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { // Authentication passed... return true; } else { return false; } } *Important note: Please note that I haven't fully coded evrything since stackoverflow is about solving problems not coding for others, so you will need to figure out how to select form data with js, and create the error msg and show it when controller returns false. Also the controller is really basic, you can improve it with features such as controlling max-login attemps from a certain user, etc..* A: You can use session variable $_SESSION['error']. And write a if condition over your login form like if(isset($_SESSION['error']) echo "Your error message.") And just unset the session variable just after that
unknown
d8928
train
It appears like this is caused by a header/library disconnect on the systems I have. Compiling with the -save-temps flag, it appears GCC uses the system header for complex.h. This means the selected Xcode SDK's usr/include/complex.h on MacOS and /usr/include/complex.h on Linux. On MacOS, the CMPLX macro is only defined when using Clang. The Linux I have is RHEL 6 meaning the header is aimed at GCC 3 which did not have CMPLX. Based on the discussion on this bug report, it looks like making sure the macro is defined is not up to GCC. The short answer is: The compiler/platform combination doesn't support it. Use the native compiler or update the system.
unknown
d8929
train
Well, I tried it on Firefox, Chrome and IE and waited more than 1 minutes. It didn't disappear. Maybe there's a problem with your browser or it was a temporary bug.
unknown
d8930
train
“-UseBasicParsing” parameter worked like a charm for a unloginable account. I've used the following link for reference. https://powershell.org/forums/topic/powershell-scripts-with-task-scheduler-failing/
unknown
d8931
train
You can put each of SFMLwidgets and MapEditor in separate subdirs qmake project files. Shared configuration of the two subprojects can go into a pri file.
unknown
d8932
train
For storage, I recommend Internal Storage http://developer.android.com/guide/topics/data/data-storage.html#filesInternal And for downloading http://developer.android.com/reference/android/os/AsyncTask.html You can create a AsyncTask where you pass a ImageView, where you want to show the img, with the url as a tag. And check in the internal storage if you have that img already saved if not just download it.
unknown
d8933
train
The Internet Explorer box model bug. A: Double Margin Bug (< IE7) A: IE6 doesn't support min-height. You can use conditional comments to set height, which IE6 treats as a min-height. Or you can use the child selector in CSS, which IE6 can't read, to reinstate height: auto on everything but IE6. .myDiv { height: 100px; min-height: 100px; } .parentElement > .myDiv { height: auto; } Using techniques like this can be problematic, but all popular modern browsers work in such a way that it's a valid technique. A: Almost every HTML/CSS bug that you will encounter will be in Internet Explorer. IE6 has a lot of them, IE7 a bit fewer and IE8 subtantially fewer. Having a proper doctype is a must. Without it the page is rendered in quirks mode, and especially for IE that is bad. It renders the page more or less as IE5 would, with the box model bug and everything. Here are some common IE bugs: * *Making the content of each element at least one character high. (Can be fixed using overflow.) *Expanding each element to contain it's children even it it's floating elements. (Can be fixed using overflow.) *Elements that are not positioned but has layout gets a z-index, although they shouldn't. (Can be fixed by making it positioned and give it a specific z-index, and do the same for all elements on the same level that needs it.) *Margins are not collapsed correctly. (Use padding instead if possible.) *Vanishing floating elements. (Give them a specific size.) *lots more... (including suggestions for fixes) The most stable fix for most of the bugs is to rearrange the layout to avoid them, or to specify stricter styles (e.g. a specific size). A: Chalk another one up for IE6: DropDownList and DIV overlapping problem, with screen shots. The iframe fix is mentioned in the article. I'm not sure if there are CSS bugs that have consistent buggy behavior across all browsers. A: here a link that list all IE known bugs and how to fix it: PositionsEverything.net A: Rumor has it that IE8 will not allow you to center elements with text-align: center;, only the text inside elements themselves. Instead, you must use margin: 0 auto;. If this is in fact the case, nearly all of the interwebs will implode.
unknown
d8934
train
You could use a table function or a pipelined function Here's an example of a table function from: http://oracle-base.com/articles/misc/pipelined-table-functions.php CREATE TYPE t_tf_row AS OBJECT ( id NUMBER, description VARCHAR2(50) ); / CREATE TYPE t_tf_tab IS TABLE OF t_tf_row; / -- Build the table function itself. CREATE OR REPLACE FUNCTION get_tab_tf (p_rows IN NUMBER) RETURN t_tf_tab AS l_tab t_tf_tab := t_tf_tab(); BEGIN FOR i IN 1 .. p_rows LOOP l_tab.extend; l_tab(l_tab.last) := t_tf_row(i, 'Description for ' || i); END LOOP; RETURN l_tab; END; / -- Test it. SELECT * FROM TABLE(get_tab_tf(10)) ORDER BY id DESC; Here's an example of a pipelined function: CREATE OR REPLACE FUNCTION get_tab_ptf (p_rows IN NUMBER) RETURN t_tf_tab PIPELINED AS r t_tf_row%rowtype; BEGIN for z in (select id, desc from sometalbe) loop r.id := z.id; r.description := z.desc; PIPE ROW(r); END LOOP; RETURN; END; A: Would procedure like this meet your needs? create or replace procedure p_statement (cur in out sys_refcursor) is begin open cur for select 1 num from dual union select 2 num from dual; end; (I put there select from dual, instead you could replace it with your complex query and define variable to be fetch into accordingly) the actual call could be like this: declare mycur sys_refcursor; num number; begin p_statement(mycur); LOOP FETCH mycur INTO num; EXIT WHEN mycur%NOTFOUND; DBMS_OUTPUT.put_line(num); END LOOP; end;
unknown
d8935
train
With the error and code you gave me, that is what you are probably missing: prod = Product.new # This is a Product instance prod.categories << Category.new # This works prod = Product.where(name:'x') # This returns a query (ActiveRecord::Relation) prod.categories << Category.new # This doesn't work prod = Product.where(name:'x').first # This is a Product instance prod.categories << Category.new # This works A: When creating a new object (let's say Product), you can use the .build method to fill out those associations and call save! EDIT: here is a good read
unknown
d8936
train
I solved this by coding a helper tool which launches my main application.
unknown
d8937
train
You need to return a promise from every function that does something asynchronous. In your case, your one function returns undefined, while it would need to return the promise that you created for the "pass this to two" value after the timeout: function one (msg) { return $timeout(function () { //^^^^^^ console.log(msg); return "pass this to two"; }, 2000); } Btw, instead of using var deferred = $q.defer();, the chain is better written as: one("pass this to one") .then(two) .then(three);
unknown
d8938
train
the time of matrix multiplication depends on the matrix size and on the numbers in the matrix. Well, of course, you are multiplying integers of arbitrary size. CPUs have no support for multiplication of those, so it will be very slow, and become slower as the integers grow. The integers in the matrix can have hundreds of digits. I'd like to know if there is a way to avoid that problem. There are several ways: * *Avoid integers, use floating point numbers and handle the error however your project needs. This will greatly increase the speed and most importantly it won't depend on the size of the numbers anymore. The memory usage will also greatly decrease too. *Use a better algorithm. You already suggested this one, but this is one of the best ways to increase performance if the better algorithm gives you way better bounds. *Optimize it in a low-level systems language. This can give you some performance back, around an order of magnitude or so. Python is a very bad choice for high-performance computing unless you use specialized libraries that do the work for you like numpy. Ideally, you should be doing all 3 if you actually need the performance.
unknown
d8939
train
The string Replace function returns a new modified string, so you'd have to do something like: foreach (var key in dtParams.Keys.ToArray()) { dtParams[key] = dtParams[key].Replace("'", "''"); } EDIT: Addressed the collection is modified issue (which I didn't think would occur if you access a key that already exists...) A: when you use replace , it will return a new string instance , you need to assign the value in the dictionary after replace becaue string is immutable in nature A: You can't do this directly; you cannot modify a collection while you're enumerating it (also, avoid using ElementAt here; this is a LINQ to Objects extension method and is inefficient for iterating over an entire list). You'll have to make a copy of the keys and iterate over that: foreach(var key in dtParams.Keys.ToList()) // Calling ToList duplicates the list { dtParams[key] = dtParams[key].Replace("'", "''"); } A: A little lambda will go a long way. ;) I dropped this into LINQPad and tested it out for you. All the collections have .To[xxx] methods so you can do this quite easily in 1 line. var dtParams = new Dictionary<string, string>(); dtParams.Add("1", "'"); dtParams.Add("a", "a"); dtParams.Add("b", "b"); dtParams.Add("2", "'"); dtParams.Add("c", "c"); dtParams.Add("d", "d"); dtParams.Add("e", "e"); dtParams.Add("3", "'"); var stuff = dtParams.ToDictionary(o => o.Key, o => o.Value.Replace("'", "''")); stuff.Dump();
unknown
d8940
train
You will be able to iterate over the permutations of the list's ranges with for items in itertools.permutations(range(item) for item in a): items will contain the sequence with one item from each range. Note: The approach is very time and resource consuming. It might be good to consider if the concept your question is based on can be optimized.
unknown
d8941
train
The lower an Android API version becomes, the more devices it supports. Thus, if the desire is to increase the amount of supported devices, it is best to decrease the API version, so long as the functionality you have already created is not impeded. Here is data based on the number of devices that support each API as of January 8th, 2018: A: The Android version is not the only condition, maybe your application uses devices such as GPS, accelerometers, sensors, telephony, minimal screen resolution etc that not all Android devices have/support them. In general, more permissions declared in your app manifest means less compatible devices.
unknown
d8942
train
It is simple. just transpose array, sort it and transpose back again. board = [[" "," ","1"," "], [" "," ","1"," "], ["1","1"," "," "], ["1"," "," ","1"]] boardT=list((map(list, zip(*board)))) boardS=[sorted(L) for L in boardT] boardR=list((map(list, zip(*boardS)))) print(boardR) #ans=[[' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['1', ' ', '1', ' '], ['1', '1', '1', '1']]
unknown
d8943
train
just use the correct overload: @Html.ValidationMessageFor(model => model.YourProperty, "", new { @class = "a-class-if-you-want-one", id = "yourId" }) A: There is no overload that takes only the linq expression and an html attributes object. According to MSDN there is an overload that takes a linq expression, an errormessage (string) AND an html attributes object, like this: @Html.ValidationMessageFor(model => model.Title,"entry invalid",new{id="prjTitle"}) A: public static MvcHtmlString IDValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string id) { var validationString = Regex.Replace(htmlHelper.ValidationMessageFor(expression).ToString(), @"^data-valmsg-for=""*\""$", String.Format("data-valmsg-for=\"{0}\"", id)); return MvcHtmlString.Create(validationString); }
unknown
d8944
train
by splitting the screen into multiple parts, you can achieve that partially: split.screen(c(3,1)) A <- 4 barplot(A, col="green4") A: Are you looking to just expand the y axis. Look at ylim? A: What you might be looking for is to fix your aspect ratio. This can be achieved using asp: barplot(A, col = "green4", asp = 1) See also this post to R-help. On a more philosophical note, when the height of the bar changes, there is no change in surface area. barplot only draws a sequence of bars, where the x axis is an ordinal (ordered categorical) variable which makes it impossible to calculate a surface area. The height of the bar is the only changing variable. I would recommend drawing these kinds of timeseries using a simple line plot. So instead of: a = runif(100) b = 1:100 barplot(a) use: plot(b, a, type = "l") or switch to my favorite plotting package, ggplot2: require(ggplot2) theme_set(theme_bw()) qplot(b, a, geom = "line")
unknown
d8945
train
You can use foreach(): endforeach Block like this: <?php foreach ($myrows1 as $index=>$item1): ?> <h1> some html tags</h1> <?php if ($item1 === reset($myrows1)) {} ?> <h1> some html tags</h1> <?php endforeach; ?> for other php statements you can read this page.
unknown
d8946
train
So $your_object is already sorted by umeta_id and user_id fields? If not, you can use usort: function cmp1($a, $b) { return strcmp($a->umeta_id, $b->umeta_id); } function cmp2($a, $b) { return strcmp($a->user_id, $b->user_id); } usort($your_object, "cmp1"); usort($your_object, "cmp2"); Then simply: $str = ''; for($i=0;$i<count($your_object);$i+=2){ $str .= "<p>".$your_object[$i]->meta_value." "$your_object[$i+1]->meta_value."</p> "; } return $str; // this var contain all your data in string Hope this helps! A: This will generate the first-name and last-name pairs : $user_group = array(); ksort($user_group, SORT_NUMERIC); foreach ($users as $key => $item) { $name_meta = get_object_vars($item); foreach ($name_meta as $meta_in => $names) { if ($names == 'first_name') { $user_group[$item->user_id]['first_name'] = $name_meta['meta_value']; } if ($names == 'last_name') { $user_group[$item->user_id]['last_name'] = $name_meta['meta_value']; } } } Output : array(3) { [1]=> array(2) { ["first_name"]=> string(4) "John" ["last_name"]=> string(3) "Doe" } [2]=> array(2) { ["first_name"]=> string(4) "Jane" ["last_name"]=> string(5) "Smith" } [3]=> array(2) { ["first_name"]=> string(7) "William" ["last_name"]=> string(5) "Green" } } And to print the user name pairs : foreach ($user_group as $name) { echo "<p>" . $name['first_name'] . " " . $name['last_name'] . "</p>"; }
unknown
d8947
train
answer for number 2 : Setting height for TextField also has a side-effect that puts TextField into multiline mode (aka "textarea"). Multiline mode can also be achieved by calling setRows(int). The height value overrides the number of rows set by setRows(int). If you want to set height of single line TextField, call setRows(int) with value 0 after setting the height. Setting rows to 0 resets the side-effect. A: I cannot see any function setRow and setHeight doesnt allow to edit more lines. Only one line vertically i middle. Vaadin 7 A: for question 1, you should first setPrimaryStyleName and if you need other style, addStyleName
unknown
d8948
train
your report is somewhat confusing. As far as I understand you, your setup works as soon as you replace the XDebug-dll. Then your (primary) problem cannot be related to your settings, as far as you also adjusted zend_extension, of course. Though xdebug.remote_port=10000 seems odd. Std is 9000. If you use 9000, the you have to tell Eclipse in Window/Preferences/PHP/Debug/Debuggers to also listen to that port for XDebug. Best Raffael
unknown
d8949
train
It depends on what is in the resource fork. The use of resource forks has been discouraged, but there are few holdouts including alias files, custom icons (on files) and some legacy font files. You can verify if a file has a resource fork in the Terminal using "ls -l@". The resource forks are also exposed in the extended attribute APIs through the "com.apple.ResourceFork" attribute. If you want to just remove thumbnails, you could do that from the Finder's GetInfo panel. The extended attribute APIs, like removexattr(2), will let you programmatically remove the Resource Fork. If you're curious what's inside a resource fork you can use: "hexdump -C myfile/..namedfork/rsrc" Hope this helps -Don A: You ask - "is there any harm in deleting the resource forks?" Of course there is. Those are files that someone has constructed to be a certain way, and if you delete chunks from them, whatever program is using them is not going to be happy. You should only do so in certain situations where you know what you're getting into. For example, Text Clippings (what you get when you drag a chunk of selected text to the desktop) are stored entirely in the resource fork. The data fork is empty. This is annoying, but it's the way it is. If you delete the resource fork, there goes all your text. A better approach might be to contact the author of whatever software is still creating resource forks and try to convince them to abandon that practice, because you like having everything in data forks.
unknown
d8950
train
It isn't empty....you just don't have permission to view that folder on a device. Try it in a simulator and it will work for you since you have root access. A: There are two ways if you want to browse your device data (data/data) folder. * *You need to have a phone with root access in order to browse the data folder using ADM(Android Device Monitor). ADM location - (YOUR_SDK_PATH\Android\sdk\tools) *You need to be running ADB in root mode, do this by executing: adb root If you just want to see your DB & Tables then the esiest way is to use Stetho. Pretty cool tool for every Android developer who uses SQLite buit by Facobook developed. Steps to use the tool * *Add below dependeccy in your application`s gradle file (Module: app) 'compile 'com.facebook.stetho:stetho:1.4.2' *Add below lines of code in your Activity onCreate() method @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Stetho.initializeWithDefaults(this); setContentView(R.layout.activity_main); } Now, build your application & When the app is running, you can browse your app database, by opening chrome in the url: chrome://inspect/#devices Screenshots of the same are as below_ ChromeInspact Your DB Hope this will help all! :) A: It may be easier to store the database in a public folder during development. Or you can see this post : How to access data/data folder in Android device? A: Solving the issue using an emulator The folder /data can be empty because you are missing the proper permissions. To solve it, I had to execute the following commands. adb shell su Those commands starts a shell in the emulator and grant you root rights. The command adb is located in the folder platform-tools of the Android SDK, typically installed in ~/Library/Android/sdk/ on MacOS. chmod -R 777 /data Modify the permissions of the folder (and subfolders recursively) /data in order to make them appear in the tool Android Device Monitor. adb root Finally, this command restarts adb as root. Be careful, it only works on development builds (typically emulators builds). Afterwards, you can see the content of the folder /data and transfer the data located in. You can do it in console as well, using adb pull <remote> <locale>, such as: adb pull /data/data/<app name>/databases/<database> . A: In cmd GoTo: C:\Users\UserName\android-sdks\platform-tools Execute: adb root Done A: In addition to @Steven K's answers: If you want to gain access to your data without having to root your real device you need to run your app in an emulator with API 23 (or lower). It is a known problem that APIs above 23 can cause problems when deploying Android Device Monitor. A: If anyone is having the stated problem, follow below steps in terminal window: * *Navigate to /Users/Username/Library/Android/sdk/platform-tools *Execute ./adb root That's it. Problem solved. A: I had same problem with API_25, it didn't work for me. Configure an API_23 emulator, it will work on API_23. A: If you are on Windows follow these instructions step by step: * *Launch your app in android emulator. *Then open command prompt as an administrator and navigate to the sdk path for example cd C:\Android\sdk\platform-tools *Type adb root *Then type adb pull /data/data/ name-of-your-package /databases/name-of-your-database *You'll find your database located in the folder called platform-tools. Then you can install Sqlite Manager extension in Google Chrome via chrome webstore and use it to view and manage your exported database. In case you have a rooted phone you can follow the same instructions as above.
unknown
d8951
train
UPDATED You got a problem in your JSON: { "hero": { "name": "Hanzo", "role": "Offense", "abilities": { "primary": "left click", "secondary": "right click", "ultimate": "dragons" }, "strongAgainst": [ "Bastion", "Mercy" ], "weakAgainst": [ "Genji", "Tracer" ] }, "hero": { "name": "Torbjorn", "role": "Defense", "abilities": { "primary": "left click", "secondary": "right click", "ultimate": "lava bastard" }, "strongAgainst": [ "Lucio", "Mercy" ], "weak_against": [ "Widowmaker", "Junkrat" ] } } This is not sane. An object defining hero property twice. The full version should be: { "heroes" : [ { "name": "Hanzo", "role": "Offense", "abilities": { "primary": "left click", "secondary": "right click", "ultimate": "dragons" }, "strongAgainst": [ "Bastion", "Mercy" ], "weakAgainst": [ "Genji", "Tracer" ] }, { "name": "Torbjorn", "role": "Defense", "abilities": { "primary": "left click", "secondary": "right click", "ultimate": "lava bastard" }, "strongAgainst": [ "Lucio", "Mercy" ], "weak_against": [ "Widowmaker", "Junkrat" ] } ] } Full code (back to three POJOs): import com.google.gson.Gson; import java.util.List; public class Test { String json = "{\n" + " \"heroes\" : [\n" + " {\n" + " \"name\": \"Hanzo\",\n" + " \"role\": \"Offense\",\n" + " \"abilities\": {\n" + " \"primary\": \"left click\",\n" + " \"secondary\": \"right click\",\n" + " \"ultimate\": \"dragons\"\n" + " },\n" + " \"strongAgainst\": [\n" + " \"Bastion\",\n" + " \"Mercy\"\n" + " ],\n" + " \"weakAgainst\": [\n" + " \"Genji\",\n" + " \"Tracer\"\n" + " ]\n" + " },\n" + " {\n" + " \"name\": \"Torbjorn\",\n" + " \"role\": \"Defense\",\n" + " \"abilities\": {\n" + " \"primary\": \"left click\",\n" + " \"secondary\": \"right click\",\n" + " \"ultimate\": \"lava bastard\"\n" + " },\n" + " \"strongAgainst\": [\n" + " \"Lucio\",\n" + " \"Mercy\"\n" + " ],\n" + " \"weak_against\": [\n" + " \"Widowmaker\",\n" + " \"Junkrat\"\n" + " ]\n" + " }\n" + " ]\n" + "}"; static class Heroes { public List<Hero> heroes; } static class Hero { public String name; public String role; public Abilities abilities; public List<String> strongAgainst; public List<String> weakAgainst; } static class Abilities { public String primary; public String secondary; public String ultimate; } void go() { Gson gson = new Gson(); Heroes h = gson.fromJson(json, Heroes.class); System.out.println(h.heroes.size()); System.out.println(h.heroes.get(0).name); } public static void main(String[] args) { new Test().go(); } }
unknown
d8952
train
I was using PyCharm as my IDE and it was not showing module members correctly, hence I thought count is missing. Here is my solution for the above user.results.add_columns(Result.tag, db.func.count(Result.tag)).group_by(Result.tag).all()
unknown
d8953
train
Introduction I went ahead and created the following GUI. The GUI consists of a JFrame with one main JPanel. The JPanel uses a GridBagLayout and consists of a JLabel, JTextArea, JLabel, JTextArea. The GUI processes the sentence as it's typed by using a DocumentListener. The code in the DocumentListener is simple since I do the work of processing the sentence in a separate class. Here's the GUI after I've typed a few characters. A few more characters The final result Explanation When I create a Swing GUI, I use the model / view / controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time. I created one model class, one view class, and one controller class. The PangramModel model class produces a result String for any input sentence String. The PangramGUI view class creates the GUI. The SentenceDocumentListener controller class updates the result JTextArea. The most complicated code can be found in the model class. There are probably many ways to process a sentence String. This was the way I coded. Code Here's the complete runnable code. I made the classes inner classes so I could post this code as one block. import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class PangramGUI implements Runnable { public static void main(String[] args) { SwingUtilities.invokeLater(new PangramGUI()); } private JTextArea sentenceArea; private JTextArea resultArea; @Override public void run() { JFrame frame = new JFrame("Pangram Analysis"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(createMainPanel(), BorderLayout.CENTER); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } private JPanel createMainPanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.LINE_START; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(5, 5, 5, 5); gbc.weightx = 1.0; gbc.gridwidth = 1; gbc.gridx = 0; gbc.gridy = 0; JLabel label = new JLabel("Type the sentence to analyze"); panel.add(label, gbc); gbc.gridy++; sentenceArea = new JTextArea(3, 40); sentenceArea.setLineWrap(true); sentenceArea.setWrapStyleWord(true); sentenceArea.getDocument().addDocumentListener( new SentenceDocumentListener()); panel.add(sentenceArea, gbc); gbc.gridy++; label = new JLabel("Pangram result"); panel.add(label, gbc); gbc.gridy++; resultArea = new JTextArea(4, 40); resultArea.setEditable(false); resultArea.setLineWrap(true); resultArea.setWrapStyleWord(true); panel.add(resultArea, gbc); return panel; } public class SentenceDocumentListener implements DocumentListener { private PangramModel model; public SentenceDocumentListener() { this.model = new PangramModel(); } @Override public void insertUpdate(DocumentEvent event) { processSentence(sentenceArea.getText()); } @Override public void removeUpdate(DocumentEvent event) { processSentence(sentenceArea.getText()); } @Override public void changedUpdate(DocumentEvent event) { processSentence(sentenceArea.getText()); } private void processSentence(String text) { String result = model.processSentence(text); resultArea.setText(result); } } public class PangramModel { private String alphabet; public PangramModel() { this.alphabet = "abcdefghijklmnopqrstuvwxyz"; } public String processSentence(String sentence) { int[] count = new int[alphabet.length()]; for (int index = 0; index < sentence.length(); index++) { char c = Character.toLowerCase(sentence.charAt(index)); int charIndex = alphabet.indexOf(c); if (charIndex >= 0) { count[charIndex]++; } } if (isEmpty(count)) { return "Not a pangram"; } else { List<Character> missingCharacters = getUnusedCharacters(count); if (missingCharacters.size() <= 0) { return "A pangram"; } else { StringBuilder builder = new StringBuilder(); builder.append("Not a complete pangram"); builder.append(System.lineSeparator()); builder.append(System.lineSeparator()); builder.append("Missing characters: "); for (int index = 0; index < missingCharacters.size(); index++) { builder.append(missingCharacters.get(index)); if (index < (missingCharacters.size() - 1)) { builder.append(", "); } } return builder.toString(); } } } private boolean isEmpty(int[] count) { for (int index = 0; index < count.length; index++) { if (count[index] > 0) { return false; } } return true; } private List<Character> getUnusedCharacters(int[] count) { List<Character> output = new ArrayList<>(); for (int index = 0; index < count.length; index++) { if (count[index] <= 0) { output.add(alphabet.charAt(index)); } } return output; } } }
unknown
d8954
train
you can do posts = Post.objects.all().order_by('-date_posted') or in your models add a meta class class Meta: ordering = ['-date_posted']
unknown
d8955
train
In your auth.js when user signIn (callback after user signIn success) //In SignIn success callback. $state.go('dashboard');//for state $location.path("/dashboard");//for url dashboard Hope it helps A: You can use resolve to address this issue. When you are redirecting to "/" page. Just check in resolve section, whether the user is logged in or not. If the user is logged in, redirect to dashboard page. A: then it first shows sign in page then redirects to dashboard which I don't want.If I go from '/dashboard' to '/' then it should automatically go to dashboard page without going to sign in page.How do I achieve this Really depends on your code. I recommend having the login route / logic maintained by the backend (check credentials there, and send a redirect to /login if not logged in.) A: <!--HTML code--> <div ng-init="CheckIfLoggedIn()"> <form id="login-form"> .............. </form> </div> //in angular JS $scope.CheckIfLoggedIn = function(){ if (loggedinuser){ $location.path("/dashboard"); } };
unknown
d8956
train
I am able to make a backend service using NX@13, NestJS@8 and [email protected], In project.json of game-api , I added some commands like this "generate-migration": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "ts-node --project tsconfig.app.json ../../node_modules/.bin/typeorm migration:generate --pretty -f .env.local", "cwd": "apps/game-api" } }, Code repository: https://github.com/coinconket/conketkemon A: Adding "module": "CommonJS" to compilerOptions in tsconfig.app.json of the related nx app fixed the issue for me. A: Hope this is helpful for some people. For the latest nx@^14 , @nestjs/*@^9 and typeorm@~0.3: in your project.json. Note that "apps/<app-name>" can be applied to "libs/<lib-name>" as well "typeorm": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "ts-node --project tsconfig.json <path-to-node_modules>/typeorm/cli", "cwd": "apps/<app-name>" } }, "mig-gen": { "builder": "@nrwl/workspace:run-commands", "outputs": [], "options": { "command": "nx run <app-name>:typeorm migration:generate <path-to-migration>/{args.name} -d <path-to-typeorm-config>/typeorm.config.ts", "cwd": "apps/<app-name>" } }, In your typeorm.config.ts import { DataSource, DataSourceOptions } from 'typeorm'; import { config } from 'dotenv'; import { join } from 'path'; config({ path: '<path-to-env>/.env' }); const { DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_PORT, DB_NAME } = process.env; export default new DataSource({ type: DB_TYPE, host: DB_HOST, port: Number(DB_PORT), username: DB_USER, password: DB_PASS, database: DB_NAME, entities: [join(__dirname, '<path-to-entities>/*.entity.{ts,js}')], migrations: [join(__dirname, '<path-to-migration>/*{.ts,.js}')], synchronize: false, } as DataSourceOptions); in your <path-to-app>/tsconfig.json make sure inside compilerOptions{...}, property "emitDecoratorMetadata": true is set. Properties module,types and target may need to be set as well. See your <root-workspace>/tsconfig.base.json and documentation https://www.typescriptlang.org/tsconfig for reference Finally in your terminal, you can run the command like this to generate your migration file nx run <app-name>:mig-gen --name=whatever-makes-you-happy
unknown
d8957
train
I know what's wrong with the problem. The key is the step 4. in Adobe AIR SDK Upgrade Help. Copy the contents from the aot folder (AIRSDK_back_up\lib\aot) of the AIR SDK backup to the aot folder of the newly created AIR SDK (AIRSDK\lib\aot). Don't copy all contents from the aot folder, just copy strip from lib\aot\bin to the aot bin folder of the newly created AIR SDK 3.6 (AIRSDK\lib\aot\bin). Then, I restart the FB 4.7, the "hello world!" show as well.
unknown
d8958
train
When you do &genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc}); You're passing a reference to an array. So in sub genFile { my ( $outFileName, @skuArr ) = @_; You have to do : sub genFile { my ( $outFileName, $skuArr ) = @_; and then use @$skuArr. Have a look at references The modified genFile sub will be: sub genFile { my ( $outFileName, $skuArr ) = @_; my $output = new IO::File(">$outFileName"); my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2); #mpId is generated. &prepareMessage($writer, $mpId, @$skuArr); } And the other sub don't need to be modified. Or you can pass always skuArr by reference: &genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc}); ... sub genFile { my ( $outFileName, $skuArr ) = @_; ... &prepareMessage($writer, $mpId, $skuArr); } sub prepareMessage { my ( $writer, $mpId, $skuArr ) = @_; my $count = 1; print Dumper $skuArr; foreach my $sku ( @$skuArr ) { print "loop run" , $sku, "\n"; } }
unknown
d8959
train
If you are trying setPixel() method on the immutable bitmap. it will throw a IllegalStateException. first, create a mutable copy of your bitmap. and then you can change the color of the pixel in your bitmap. Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); int red = 255; //replace it with your color int green = 255; //replace it with your color int blue = 255; //replace it with your color int color = Color.argb(0xFF, red, green, blue); mutableBitmap.setPixel(indexI, indexJ, color); //now if you apply it to any image view to see change. imageView.setImageBitmap(mutableBitmap);
unknown
d8960
train
if you use Solrj JSONArray jArray = new JSONArray(); for (int i = 0; i < docList.size(); i++) { JSONObject json = new JSONObject(docList.get(i)); jArray.put(json); } > for (int i = 0; i < jArray.length(); i++) { JSONObject obj = objs.getJSONObject(i); obj.getString("a"));
unknown
d8961
train
When you use it like this router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true }); you are not passing query params to the page, you are only showing them in the address bar, I guess. How about something like this: router.push({ pathname '/items/[pageNumber]/', query: { param1: 'yes', }, }, { pathname: '/items/1/', query: { param1: 'yes', }, }); Don't forget to update query part for your case.
unknown
d8962
train
Why the loop? Just put the loop values in the Range statements: Dim rng As Range, cell As Range, copyToCell As Range Set rng = ThisWorkbook.Sheets("Sheet1").Range(Cells(9, "j"), Cells(23, "j")) Set copyToCell = ThisWorkbook.Sheets("Sheet2").Cells(3, "i") rng.Copy copyToCell End Sub HTH
unknown
d8963
train
I got an answer to this from another site: var parameters = new PresenceInfoResource(); parameters.userStatus = "Busy"; parameters.dndStatus = "TakeAllCalls"; var resp = await rc.Restapi().Account().Extension().Presence().Put(parameters); Console.WriteLine("User presence status: " + resp.userStatus); Console.WriteLine("User DND status: " + resp.dndStatus);
unknown
d8964
train
I was able to resolve my issue. I was supposed to be using Paramiko.Transport and then creating the SFTPClient with paramiko.SFTPClient.from_transport(t) instead of using open_sftp() from SSHClient(). The following code works: t = paramiko.Transport((host, 22)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) A: as i see it, with ssh=SSHClient() you create an SSHClient-Object, and then with sftp=ssh.open_sftp() you create an sftp-object. while you only want to use the sftp, you store the ssh in a local variable, which then gets gc'd, but, if the ssh is gc'd, the sftp magically stops working. don't know why, but try to store the ssh for the time your sftp lives. A: After reading your edit I think the problem is here stdin, stdout, stderr = self.sshConnections[host].exec_command(command) this line apparently disconnect the ftp thing EDITED
unknown
d8965
train
Ok this is much clearer after reading your comment and EDIT. So, correct me if I'm wrong. * *You want to be able to provide a version of your connector for each neo4j version *You use module to do so. What is still not clear to me, is that I cannot see the modules' part of your POM. You say that you want to use classifiers (so, of the same project) but maven modules are different projects...
unknown
d8966
train
You need Decoration for this. Here is the example: public class ItemOffsetDecoration extends RecyclerView.ItemDecoration { private int offset; public ItemOffsetDecoration(int offset) { this.offset = offset; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = offset; outRect.right = offset; outRect.bottom = offset; if(parent.getChildAdapterPosition(view) == 0) { outRect.top = offset; } } } And in your activity/fragment grid.setLayoutManager(new GridLayoutManager(this, 2)); grid.addItemDecoration(new ItemOffsetDecoration(1)); A: I think, that Jagadesh Seeram was talking about horizontal divider between items, but RecyclerView.ItemDecoration adds divider everywhere. If you don't use autoscroll to some item, you should write like this: public class ItemOffsetDecoration extends RecyclerView.ItemDecoration { private int offset; public ItemOffsetDecoration(int offset) { this.offset = offset; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int bottonIndex; if (parent.getAdapter().getItemCount() % 2 == 0){ bottonIndex = parent.getAdapter().getItemCount() - 2; } else { bottonIndex = parent.getAdapter().getItemCount() - 1; } if (parent.getChildAdapterPosition(view) < bottonIndex){ outRect.bottom = offset; } else { outRect.bottom = 0; } if(parent.getChildAdapterPosition(view) > 1 ) { outRect.top = offset; } else { outRect.top = 0; } if( (parent.getChildAdapterPosition(view) % 2 ) == 0) { outRect.right = offset; outRect.left = 0; } else { outRect.right = 0; outRect.left = offset; } }
unknown
d8967
train
Instead of returning true, try returning super.onKeyDown(keyCode, event) after finish(). You can try 1 more thing: specify android:noHistory="true" in the manifest for that activity. Specifying this attribute doesn't keep the activity on the Activity Stack. http://developer.android.com/guide/topics/manifest/activity-element.html#nohist A: Have you tried lauching B by calling startActivityForResult() in A? Do all your processing in B and then ensure you call finish on it and this should clear all data in it. Please let me know if it works. A: It's obvious. OnSaveState is called when finishing activity, and this activity is popped out of the stack. Best practice for you to clear the situation is to log all the lifecycle events in both activities, it will help to figure out where to put initializing your B activity. Yes, and one more thing try researching onNewIntent method in B activity i suppose it will be really helpfull A: As i stated in my last comment to the post, @Jianhong given me the correct answer (aslso if as a comment). As he don't copied the comment as answer in time, i add this answer and mark it as the ACCEPTED. Thanks @Jianhong! Answer: @Jianhong OMG! you completely right! i checked for this problem in past days but i couldn't find it as... i've not UPDATED from SVN. my coworker inserted lines of code that prefill fields by some static var!
unknown
d8968
train
I assume that your application will do specific things with data from specific bar-code scanners i.e. scanner1 is connected to cash register 1 and scanner2 to register 2 etc. Further I assume that you use some standard scanner hardware which identifies to a Linux system as an HID keyboard device. On modern Linux operating systems such as Raspbian USB devices are registered as device nodes in /dev/input/by-id. An example of a keyboard connected to my Pi is: /dev/input/by-id/usb-0130_0005-event-kbd. Linux HID device nodes allow you to directly read from them just like you would read from a file. This means that you can do something like the following, to make sure that your Java program reads from a particular barcode scanner only: DataInputStream in = new DataInputStream( new FileInputStream("/dev/input/by-id/usb-0130_0005-event-kbd")); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while((line = reader.readLine()) != null) { // evaluate the EAN code which is now in line } Assumption that your scanner like ours send a carriage return / line feed after each successfully scanned code. We use similar code in one of our applications to make sure, that our users not accidentally scan EAN codes in other fields such as names and description fields. In our application bar code scanners add items to an item list and keyboard input is exclusively used for other user input. On application startup in the main method we use code similar to this in order to make sure that keyboard and barcode scanners get distinguished. public static void main(String args[]) { String keyboardInput = args[0]; String barcodeInput = args[1]; // see code above how to read from the particular devices } As for application startup we use Linux command line tools to determine which device nodes refer to the barcode scanner and which to the keyboard. Basically a combination of lsusb and a set of Udev rules that get executed whenever a USB device is connected to the machine. However, this is out of the context of your question.
unknown
d8969
train
Is is possible to mix es6 on server-side and use es5 on client-side Yes you could mix both. But be aware that sharing code between both could be tricky. is all or nothing... all es6 on both server/client or vice versa? That's not the case here, but I would recommended to use on both sides es6 and convert to es5 for the browser, eg with Babel A: Is is possible to mix es6 on server-side and use es5 on client-side OR is all or nothing... all es6 on both server/client or vice versa? It's possible to mix entirely separate languages on the server and client, such as PHP or Java or Ruby or C# on the server and JavaScript on the client. So yes, it's just fine if you want to use ES2015 (aka "ES6") and later features in your server-side Node code and restrict yourself to ES5 and earlier features in your client-side browser code. You don't have to, though, and it's surprisingly hard once you get used to writing let and const and arrow functions to make yourself not write them in your client-side code by accident. So for that reason, you might consider using ES2015+ plus both server-side and client-side, and "transpiling" your client-side code from ES2015+ down to ES5 for use on older browsers. There are multiple transpilers, such as Babel. You can develop with an up-to-date browser such as Chrome or Firefox or Edge, and then have your build tool make the "production" build pass all the client-side code through Babel (perhaps with Webpack or Browserify or similar) for use on older browsers such as IE11.
unknown
d8970
train
There's no cost as far as I know, and these are two major benefits that I know of: * *If you use the same string in multiple layouts or classes, you can change it in strings.xml and it will be updated everywhere (you'll never forget to change it somewhere). *You can give people the strings.xml for translation, and create files like strings-es.xml (for Spanish) that Android will use for automatically displaying a translated version of your app based on the device's default language. I'm sure it affects compilation time but I think the SDK combines and optimizes all of your strings somewhere in the actual APK.
unknown
d8971
train
What about using the DataBound event handler to define check the dataSource binded and show or hide the grid. Here is an example of something similar, but in this case it shows a message when the grid is empty. http://blog.falafel.com/displaying-message-kendo-ui-grid-empty/ code example: @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>() .Name("grid") .Columns(columns => { columns.Bound(p => p.ProductName).Title("Product Name"); columns.Bound(p => p.UnitPrice).Title("Unit Price"); columns.Bound(p => p.UnitsInStock).Title("Units In Stock"); }) .Events(events => events.DataBound("onGridDataBound")) .DataSource(dataSource => dataSource .Ajax() .Read(read => read.Action("Products_Read", "Grid")) ) ) <script> function onGridDataBound(e){ var grid = e.sender; if (grid.dataSource.total() == 0 ){ //Hide grid $(grid).hide(); } else{ //Show grid $(grid).show(); } } </script>
unknown
d8972
train
Compilation of a Lisp file Take for example the compilation of a Lisp file. The Lisp compiler processes the top-level forms. These can be arbitrary Lisp forms, DEFUNs, DEFMACROS, DEFCLASS, function calls,... The whole story how the file compiler works is too complex to explain here, but a few things: * *the file compiler generates code for a (DEFUN foo () ) form. But it does not execute the defun form. Thus during compilation it is known that there is a function FOO, but the code of ˋFOOˋ is not available during the compilation. The compiler generates the code for the compiled file, but does not keep it in memory. You can't call such a function at compile time. *for macros this works slightly different: (DEFMACRO BAZ ...). The file compiler will not only compile the macro and note that it is there, but it will also make the macro available at compilation time. It is loaded into the compiler environment. Thus imagine the sequence of forms in a file: (defmacro baz ...) (defun foo () (baz ...)) This works because the file compiler knows the macro BAZ and when it compiles the code for FOO, then it can expand the macro form. Now let's look at the following example: (defun bar (form) ...) (defmacro baz (form) (bar form)) (defun foo () (baz ...)) Above will not work. Now the macro BAZ uses the function BAR by calling it. When the compiler tries to compile the function FOO, it can't expand the BAZ macro, because BAR can't be called, because the code of BAR is not loaded into the compile-time environment. There are two solutions to this: * *compile and load BAR earlier using a separate file. *Use EVAL-WHEN Example for EVAL-WHEN: (eval-when (:compile-toplevel :execute :load-toplevel) (defun bar (form) ...) ) (defmacro baz (form) (bar form)) (defun foo () (baz ...)) Now the EVAL-WHEN instructs the file compiler to actually run the DEFUN form during compilation. The effect of this is: the file compiler now knows the definition of BAR at compile time. Thus it is available later, when the file compiler need to call BAR during macro expansion of the usage of BAZ. One could use only :compile-toplevel, when the function would not be needed after the compilation of the file. If it is used later, then we need to make sure that it gets loaded. So EVAL-WHEN allows to specify if a particular piece of code should be run * *during compilation of a file *during loading of a file *during execution EVAL-WHEN is not used that often in user code. If you use it, then you should ask yourself if you really need it.
unknown
d8973
train
You'll need to check for readyState and the HTTP response status before replacing the text; if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("test").innerHTML=xmlhttp.responseText; } example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp Please let me know if it works. A: For browsers other than IE IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents). IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below. Normally you check the status of the request to see if it's been fully read or not before accessing the responseText. Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request. (The status will always be 0 for request not made via HTTP) The best I can offer is this: function loadXMLDoc(url) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { document.getElementById('test').innerHTML = xmlhttp.responseText; } xmlhttp.open( "GET", url ); xmlhttp.send(null); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open( "GET", url ); xmlhttp.send(null); document.getElementById('test').innerHTML = xmlhttp.responseText; } } For CHROME If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch. Otherwise, it will refuse file system ajax requests. (You will have to set this even if using a so-called "easier" library such as jQuery). Running AJAX apps on File System In General Not usually a good idea, a lot of caveats to this route. Typically local development is done with a web server installed to localhost on your development machine. A: Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest(); You have many other options for this. * *http://api.jquery.com/jQuery.ajax/ *http://www.w3schools.com/jquery/jquery_ref_ajax.asp *http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/ A: Firstly, you have to fight with Same Origin Policy. A simple working code for a synchronous request is following: var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.status == 200 && req.readyState == 4) { ... } req.open('GET', url, true); req.send(null); Note this is working for Firefox/Opera/Chrome. If IE, use: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); A: Try with jQuery. Download the last version here and write this code snippet: function loadXMLDoc(url) { $("#test").load(url); } It's much simpler and less error prone A: You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests. You don't need PHP, however you'll need apache or a similar web server.
unknown
d8974
train
A one liner you can use is -[UIView viewWithTag:], but this will likely loop internally as well. A faster approach for lots of views is to use an NSDictionary (NSNumber instances as keys plus views as values). Dictionaries use hashes internally so they're faster in most cases. A: Try this: [[self.view viewWithTag:someInteger] removeFromSuperview];
unknown
d8975
train
There are numerous options, such as: Flash Pro If your game has already been created in Flash Pro, you could simply target AIR for Android from Flash Pro's publish settings: ADT Command Line Packager Likewise, you could simply use the ADT command line packager to build your SWF to an Android distributable. Flash Builder Otherwise from Flash Builder, you can create a new ActionScript mobile project: Select Android, or other target platforms: Place code and packages relative to the src/ folder, same as you would relative to your FLA: Your entire Flash app could be published as a SWC, then instantiated from Flash Builder, or individual assets may be exported as SWCs: Likewise you can programmatically embed SWF assets in ActionScript classes using the embed metadata tag: [Embed(source="asset.swf", symbol="symbol")] private var SymbolClass:Class; var symbol:MovieClip = new SymbolClass();
unknown
d8976
train
You need a mutex. Essentially the only thing the GIL protects you from is accessing uninitialized memory. If something in Ruby could be well-defined without being atomic, you should not assume it is atomic. A simple example to show that your example ordering is possible. I get the "double set" message every time I run it: $global = nil $thread = nil threads = [] threads = Array.new(1000) do Thread.new do sleep 1 $thread ||= Thread.new do if $global warn "double set!" else $global = true end end end end threads.each(&:join)
unknown
d8977
train
Do you have a view named about in static_pages_controller's corresponding view folder? If so, rails assumes controller action just being empty and proceeds with render. To have test fail - rename or delete the view
unknown
d8978
train
Instead of using require_once I've use require...So as the code traversed it was creating AWS Class again and again. Code //s3 client require '../aws/aws-autoloader.php'; //use require_once $config = require('config.php'); //create s3 instance $S3 = S3Client::factory([ 'version' => 'latest', 'region' => 'REGION', 'credentials' => array( 'key' => $config['S3']['key'], 'secret' => $config['S3']['secret'] ) ]);
unknown
d8979
train
X sends a MapNotifyEvent (not to be confused with KeymapNotify) when the key mapping is changed (tested with xmodmap, but should work for other methods as well). I don't know if you can get at raw X events under Qt, but if you can, I think that's the event to look for.
unknown
d8980
train
How can I download the oldest file of an FTP server? Using WebRequestMethods.Ftp.ListDirectoryDetails This will issue an FTP LIST command with a request to get the details on the files in a single request. This does not make things easy though because you will have to parse those lines, and there is no standard format for them. Depending on the ftp server, it may return lines in a format like this: 08-10-11 12:02PM <DIR> Version2 06-25-09 02:41PM 144700153 image34.gif 06-25-09 02:51PM 144700153 updates.txt 11-04-10 02:45PM 144700214 digger.tif Or d--x--x--x 2 ftp ftp 4096 Mar 07 2002 bin -rw-r--r-- 1 ftp ftp 659450 Jun 15 05:07 TEST.TXT -rw-r--r-- 1 ftp ftp 101786380 Sep 08 2008 TEST03-05.TXT drwxrwxr-x 2 ftp ftp 4096 May 06 12:24 dropoff Or even another format. This blog post "Sample code for parsing FtpwebRequest response for ListDirectoryDetails" provides an example of handling several formats. If you know what the format is, just create a custom minimal line parser for it. Using WebRequestMethods.Ftp.ListDirectory with WebRequestMethods.Ftp.GetDateTimestamp This is easier, but the downside is that it requires you to submit several requests to find out the last modification dates for the directory entries. This will get you a list of file and directory entries with names only, that is easier to parse. public static IEnumerable<string> ListDirectory(string uri, NetworkCredential credentials) { var request = FtpWebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = credentials; using (var response = (FtpWebResponse)request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream, true)) { while (!reader.EndOfStream) yield return reader.ReadLine(); } } Then for each file you can get the last modification date by issuing a request per file: public static DateTime GetLastModified(string fileUri, NetworkCredential credentials) { // error checking omitted var request = FtpWebRequest.Create(fileUri); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; request.Credentials = credentials; using (var response = (FtpWebResponse)request.GetResponse()) return response.LastModified; } Now you can simply do the following to get a list of files with their last modification date. var credentials = new NetworkCredential("Igor", ""); var filesAndDates = ListDirectory("ftp://192.168.47.1/DocXML", credentials) .Select(fileName => new { FileName = fileName, LastModified = GetLastModified("ftp://192.168.47.1/DocXML/" + fileName, credentials) }) .ToList(); // find the oldest entry. var oldest = filesAndDates.OrderBy(x => x.LastModified).FirstOrDefault();
unknown
d8981
train
There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: http://code.google.com/p/seaside/issues/detail?id=48 This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not. Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't so bad. If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun. Edited to add: The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like: self requestContext response addCookie: aCookie This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled. A: I've just looked into this in depth, and the answer seems to be no. Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's stream but not the response itself). I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no. That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)
unknown
d8982
train
What database are you using? To copy from a single table into another table where a particular column's date is greater than now you could use this: SQL Server: INSERT INTO MyTempTable1 (Column1, Column2, Colu...) SELECT Column1, Column2, Colu... FROM _delTable1 WHERE MyDateColumn > GetDate(); TRUNCATE TABLE _delTable1; MySQL: INSERT INTO MyTempTable1 (Column1, Column2, Colu...) SELECT Column1, Column2, Colu... FROM _delTable1 WHERE MyDateColumn > CURRENT_TIMESTAMP(); TRUNCATE TABLE _delTable1; If you want to dynamically build the queries for each table that begins with _del then you could loop through the tables and build queries up and execute them - but it depends on what database you are using and even what version. Another option (depending on what you want to do) is to just delete the data older than today (now or the start of today). To get the start of today you could do this: SELECT DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), -1) If you want to use that just replace the GetDate() or CURRENT_TIMESTAMP() with it (in brackets).
unknown
d8983
train
According to a Frameworks Engineer on Developer Apple Forum: Animations and pan/zoom gesture do not work in widgets built with WidgetKits. Checkout https://developer.apple.com/videos/play/wwdc2020/10028/, where what works and doesn't. Throughout the WWDC20 Meet WidgetKit video mentioned above, Apple stresses that Widgets are not mini-apps, so they don't support gesture based views (like scroll views) or animations. Widgets are meant to only have glanceable information. From WWDC20 Meet WidgetKit Video Transcript: These widgets are not mini-apps. We do not support scrolling within the widget, interactive elements like switches and other system controls, nor videos or animated images.
unknown
d8984
train
The Hotspot JVM generates machine code for Java code (which doesn't support making syscalls). All code which makes syscalls is in a native method. So when Java wants to make a syscalls, you have to call some native code to do it for you. There are libraries you can use to wrap native calls. E.g. JNA and JNR-FFI. This allows you call c libraries without writhing native code.
unknown
d8985
train
buffer=malloc(255*sizeof(char)); gives you only 255 bytes. recv(socketname, buffer, 10000, 0); tries to read much more. That's why you get a segfault. Also, you do not know what you actualy download, so you'd be better off with memcpy to copy. An untested example: ssize_t received=0, current_received=0; char *reply, *buffer; reply=malloc(10000*sizeof(char)); buffer=malloc(255*sizeof(char)); while(received<10000) { current_received = recv(socketname, buffer, 255, 0); if(current_received <= 0) { //if we're done or we have an error. Think about some error handling. break; } //I have switched the following lines to make it a bit easier. //As an exercise try to avoid overflow if received=9999 and current_received=255 :) memcpy(reply + received, buffer, current_received); received += current_received; } If you're looking for a library that will do it for you, check this link. Keep in mind that using a library might be actually quite difficult if you want just a very simple example. A: But to jxh's point, you want to be using memcpy instead of strcat, and keeping any advancing pointer into your consolidated reply, incrementing by received each time.
unknown
d8986
train
Some of the docs explain how variables are created; the explanation as I understand it is that's just how the parser works: The local variable is created when the parser encounters the assignment, not when the assignment occurs: a = 0 if false # does not assign to a p local_variables # prints [:a] p a # prints nil You can see other examples of this: b = true if false # b is nil "test" || c = true # c is nil And others it doesn't get assigned: puts d if false # d generates a NameError
unknown
d8987
train
I made my own layout that does what I want, but it is quite limited at the moment. Comments and improvement suggestions are of course welcome. The activity: package se.fnord.xmms2.predicate; import se.fnord.android.layout.PredicateLayout; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.TextView; public class Predicate extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PredicateLayout l = new PredicateLayout(this); for (int i = 0; i < 10; i++) { TextView t = new TextView(this); t.setText("Hello"); t.setBackgroundColor(Color.RED); t.setSingleLine(true); l.addView(t, new PredicateLayout.LayoutParams(2, 0)); } setContentView(l); } } Or in an XML layout: <se.fnord.android.layout.PredicateLayout android:id="@+id/predicate_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" /> And the Layout: package se.fnord.android.layout; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * ViewGroup that arranges child views in a similar way to text, with them laid * out one line at a time and "wrapping" to the next line as needed. * * Code licensed under CC-by-SA * * @author Henrik Gustafsson * @see http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * @license http://creativecommons.org/licenses/by-sa/2.5/ * */ public class PredicateLayout extends ViewGroup { private int line_height; public PredicateLayout(Context context) { super(context); } public PredicateLayout(Context context, AttributeSet attrs){ super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert(MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec); // The next line is WRONG!!! Doesn't take into account requested MeasureSpec mode! int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); final int childw = child.getMeasuredWidth(); line_height = Math.max(line_height, child.getMeasuredHeight() + lp.height); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.width; } } this.line_height = line_height; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED){ height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST){ if (ypos + line_height < height){ height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected boolean checkLayoutParams(LayoutParams p) { return (p instanceof LayoutParams); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.width; } } } } With the result: A: There is a problem with the first Answer: child.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); In a ListView, for example, the list items are passed a heightMeasureSpec of 0 (UNSPECIFIED) and so, here, the MeasureSpec of size 0 (AT_MOST) is passed to all of the children. This means that the whole PredicateLayout is invisible (height 0). As a quick fix, I changed the child height MeasureSpec like this: int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } and then child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); which seems to work for me although does not handle EXACT mode which would be much more tricky. A: Since May 2016 there is new layout called FlexboxLayout from Google, which is highly configurable for purpose you want. FlexboxLayout is in Google GitHub repository at https://github.com/google/flexbox-layout at this moment. You can use it in your project by adding dependency to your build.gradle file: dependencies { implementation 'com.google.android.flexbox:flexbox:3.0.0' } More about FlexboxLayout usage and all the attributes you can find in repository readme or in Mark Allison articles here: https://blog.stylingandroid.com/flexboxlayout-part-1/ https://blog.stylingandroid.com/flexboxlayout-part2/ https://blog.stylingandroid.com/flexboxlayout-part-3/ A: I implemented something very similar to this, but using what I think is a little more standard way to handle spacing and padding. Please let me know what you guys think, and feel free to reuse without attribution: package com.asolutions.widget; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.asolutions.widget.R; public class RowLayout extends ViewGroup { public static final int DEFAULT_HORIZONTAL_SPACING = 5; public static final int DEFAULT_VERTICAL_SPACING = 5; private final int horizontalSpacing; private final int verticalSpacing; private List<RowMeasurement> currentRows = Collections.emptyList(); public RowLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.RowLayout); horizontalSpacing = styledAttributes.getDimensionPixelSize(R.styleable.RowLayout_android_horizontalSpacing, DEFAULT_HORIZONTAL_SPACING); verticalSpacing = styledAttributes.getDimensionPixelSize(R.styleable.RowLayout_android_verticalSpacing, DEFAULT_VERTICAL_SPACING); styledAttributes.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int maxInternalWidth = MeasureSpec.getSize(widthMeasureSpec) - getHorizontalPadding(); final int maxInternalHeight = MeasureSpec.getSize(heightMeasureSpec) - getVerticalPadding(); List<RowMeasurement> rows = new ArrayList<RowMeasurement>(); RowMeasurement currentRow = new RowMeasurement(maxInternalWidth, widthMode); rows.add(currentRow); for (View child : getLayoutChildren()) { LayoutParams childLayoutParams = child.getLayoutParams(); int childWidthSpec = createChildMeasureSpec(childLayoutParams.width, maxInternalWidth, widthMode); int childHeightSpec = createChildMeasureSpec(childLayoutParams.height, maxInternalHeight, heightMode); child.measure(childWidthSpec, childHeightSpec); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); if (currentRow.wouldExceedMax(childWidth)) { currentRow = new RowMeasurement(maxInternalWidth, widthMode); rows.add(currentRow); } currentRow.addChildDimensions(childWidth, childHeight); } int longestRowWidth = 0; int totalRowHeight = 0; for (int index = 0; index < rows.size(); index++) { RowMeasurement row = rows.get(index); totalRowHeight += row.getHeight(); if (index < rows.size() - 1) { totalRowHeight += verticalSpacing; } longestRowWidth = Math.max(longestRowWidth, row.getWidth()); } setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : longestRowWidth + getHorizontalPadding(), heightMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(heightMeasureSpec) : totalRowHeight + getVerticalPadding()); currentRows = Collections.unmodifiableList(rows); } private int createChildMeasureSpec(int childLayoutParam, int max, int parentMode) { int spec; if (childLayoutParam == LayoutParams.FILL_PARENT) { spec = MeasureSpec.makeMeasureSpec(max, MeasureSpec.EXACTLY); } else if (childLayoutParam == LayoutParams.WRAP_CONTENT) { spec = MeasureSpec.makeMeasureSpec(max, parentMode == MeasureSpec.UNSPECIFIED ? MeasureSpec.UNSPECIFIED : MeasureSpec.AT_MOST); } else { spec = MeasureSpec.makeMeasureSpec(childLayoutParam, MeasureSpec.EXACTLY); } return spec; } @Override protected void onLayout(boolean changed, int leftPosition, int topPosition, int rightPosition, int bottomPosition) { final int widthOffset = getMeasuredWidth() - getPaddingRight(); int x = getPaddingLeft(); int y = getPaddingTop(); Iterator<RowMeasurement> rowIterator = currentRows.iterator(); RowMeasurement currentRow = rowIterator.next(); for (View child : getLayoutChildren()) { final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (x + childWidth > widthOffset) { x = getPaddingLeft(); y += currentRow.height + verticalSpacing; if (rowIterator.hasNext()) { currentRow = rowIterator.next(); } } child.layout(x, y, x + childWidth, y + childHeight); x += childWidth + horizontalSpacing; } } private List<View> getLayoutChildren() { List<View> children = new ArrayList<View>(); for (int index = 0; index < getChildCount(); index++) { View child = getChildAt(index); if (child.getVisibility() != View.GONE) { children.add(child); } } return children; } protected int getVerticalPadding() { return getPaddingTop() + getPaddingBottom(); } protected int getHorizontalPadding() { return getPaddingLeft() + getPaddingRight(); } private final class RowMeasurement { private final int maxWidth; private final int widthMode; private int width; private int height; public RowMeasurement(int maxWidth, int widthMode) { this.maxWidth = maxWidth; this.widthMode = widthMode; } public int getHeight() { return height; } public int getWidth() { return width; } public boolean wouldExceedMax(int childWidth) { return widthMode == MeasureSpec.UNSPECIFIED ? false : getNewWidth(childWidth) > maxWidth; } public void addChildDimensions(int childWidth, int childHeight) { width = getNewWidth(childWidth); height = Math.max(height, childHeight); } private int getNewWidth(int childWidth) { return width == 0 ? childWidth : width + horizontalSpacing + childWidth; } } } This also requires an entry under /res/values/attrs.xml, which you can create if it's not already there. <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RowLayout"> <attr name="android:verticalSpacing" /> <attr name="android:horizontalSpacing" /> </declare-styleable> </resources> Usage in an xml layout looks like this: <?xml version="1.0" encoding="utf-8"?> <com.asolutions.widget.RowLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="10dp" android:horizontalSpacing="10dp" android:verticalSpacing="20dp"> <FrameLayout android:layout_width="30px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="60px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="70px" android:layout_height="20px" android:background="#F00"/> <FrameLayout android:layout_width="20px" android:layout_height="60px" android:background="#F00"/> <FrameLayout android:layout_width="10px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> </com.asolutions.widget.RowLayout> A: My slightly modified version based on posted here previously: * *It works in Eclipse layout editor *It centers all the items horizontally import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; public class FlowLayout extends ViewGroup { private int line_height; public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontal_spacing; public final int vertical_spacing; /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing, ViewGroup.LayoutParams viewGroupLayout) { super(viewGroupLayout); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing) { super(0, 0); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } } public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); line_height = Math.max(line_height, child.getMeasuredHeight() + lp.vertical_spacing); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.horizontal_spacing; } } this.line_height = line_height; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (ypos + line_height < height) { height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected android.view.ViewGroup.LayoutParams generateLayoutParams( android.view.ViewGroup.LayoutParams p) { return new LayoutParams(1, 1, p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int lastHorizontalSpacing = 0; int rowStartIdx = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { final int freeSpace = width - xpos + lastHorizontalSpacing; xpos = getPaddingLeft() + freeSpace / 2; for (int j = rowStartIdx; j < i; ++j) { final View drawChild = getChildAt(j); drawChild.layout(xpos, ypos, xpos + drawChild.getMeasuredWidth(), ypos + drawChild.getMeasuredHeight()); xpos += drawChild.getMeasuredWidth() + ((LayoutParams)drawChild.getLayoutParams()).horizontal_spacing; } lastHorizontalSpacing = 0; xpos = getPaddingLeft(); ypos += line_height; rowStartIdx = i; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.horizontal_spacing; lastHorizontalSpacing = lp.horizontal_spacing; } } if (rowStartIdx < count) { final int freeSpace = width - xpos + lastHorizontalSpacing; xpos = getPaddingLeft() + freeSpace / 2; for (int j = rowStartIdx; j < count; ++j) { final View drawChild = getChildAt(j); drawChild.layout(xpos, ypos, xpos + drawChild.getMeasuredWidth(), ypos + drawChild.getMeasuredHeight()); xpos += drawChild.getMeasuredWidth() + ((LayoutParams)drawChild.getLayoutParams()).horizontal_spacing; } } } } A: I have updated this sample to fix a bug, now, each line can have a different height ! import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * ViewGroup that arranges child views in a similar way to text, with them laid * out one line at a time and "wrapping" to the next line as needed. * * Code licensed under CC-by-SA * * @author Henrik Gustafsson * @see http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * @license http://creativecommons.org/licenses/by-sa/2.5/ * * Updated by Aurélien Guillard * Each line can have a different height * */ public class FlowLayout extends ViewGroup { public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontal_spacing; public final int vertical_spacing; /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing) { super(0, 0); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } } public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.horizontal_spacing; line_height = child.getMeasuredHeight() + lp.vertical_spacing; } } if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (ypos + line_height < height) { height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int lineHeight = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += lineHeight; } lineHeight = child.getMeasuredHeight() + lp.vertical_spacing; child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.horizontal_spacing; } } } } A: The android-flowlayout project by ApmeM support line breaks, too. A: Here is my simplified, code-only version: package com.superliminal.android.util; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * A view container with layout behavior like that of the Swing FlowLayout. * Originally from http://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/ itself derived from * http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * * @author Melinda Green */ public class FlowLayout extends ViewGroup { private final static int PAD_H = 2, PAD_V = 2; // Space between child views. private int mHeight; public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); else childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mHeight = 0; for(int i = 0; i < count; i++) { final View child = getChildAt(i); if(child.getVisibility() != GONE) { child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); mHeight = Math.max(mHeight, child.getMeasuredHeight() + PAD_V); if(xpos + childw > width) { xpos = getPaddingLeft(); ypos += mHeight; } xpos += childw + PAD_H; } } if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + mHeight; } else if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if(ypos + mHeight < height) { height = ypos + mHeight; } } height += 5; // Fudge to avoid clipping bottom of last row. setMeasuredDimension(width, height); } // end onMeasure() @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for(int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if(child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); if(xpos + childw > width) { xpos = getPaddingLeft(); ypos += mHeight; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + PAD_H; } } } // end onLayout() } A: Some of the different answers here would give me a ClassCastException in the Exclipse layout editor. In my case, I wanted to use ViewGroup.MarginLayoutParams rather than making my own. Either way, make sure to return the instance of LayoutParams that your custom layout class needs in generateLayoutParams. This is what mine looks like, just replace MarginLayoutParams with the one your ViewGroup needs: @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof MarginLayoutParams; } It looks like this method gets called to to assign a LayoutParams object for each child in the ViewGroup. A: LinearLayout row = new LinearLayout(this); //get the size of the screen Display display = getWindowManager().getDefaultDisplay(); this.screenWidth = display.getWidth(); // deprecated for(int i=0; i<this.users.length; i++) { row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); this.tag_button = new Button(this); this.tag_button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 70)); //get the size of the button text Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(tag_button.getTextSize()); mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL)); float size = mPaint.measureText(tag_button.getText().toString(), 0, tag_button.getText().toString().length()); size = size+28; this.totalTextWidth += size; if(totalTextWidth < screenWidth) { row.addView(tag_button); } else { this.tags.addView(row); row = new LinearLayout(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); row.addView(tag_button); this.totalTextWidth = size; } } A: I adapted some of the ode above and implemented a flow layout which centers all child views, horizontal and vertical. It fits my needs. public class CenteredFlowLayout extends ViewGroup { private int lineHeight; private int centricHeightPadding; private final int halfGap; public static final List<View> LINE_CHILDREN = new ArrayList<View>(); public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontalSpacing; public final int verticalSpacing; public LayoutParams(int horizontalSpacing, int verticalSpacing) { super(0, 0); this.horizontalSpacing = horizontalSpacing; this.verticalSpacing = verticalSpacing; } } public CenteredFlowLayout(Context context) { super(context); halfGap = getResources().getDimensionPixelSize(R.dimen.half_gap); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int maxHeight = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int lineHeight = 0; int xAxis = getPaddingLeft(); int yAxis = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final CentricFlowLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childMeasuredWidth = child.getMeasuredWidth(); lineHeight = Math.max(lineHeight, child.getMeasuredHeight() + lp.verticalSpacing); if (xAxis + childMeasuredWidth > width) { xAxis = getPaddingLeft(); yAxis += lineHeight; } else if (i + 1 == count) { yAxis += lineHeight; } xAxis += childMeasuredWidth + lp.horizontalSpacing; } } this.lineHeight = lineHeight; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = yAxis + lineHeight; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (yAxis + lineHeight < height) { height = yAxis + lineHeight; } } if (maxHeight == 0) { maxHeight = height + getPaddingTop(); } centricHeightPadding = (maxHeight - height) / 2; setMeasuredDimension(width, disableCenterVertical ? height + getPaddingTop() : maxHeight); } @Override protected CentricFlowLayout.LayoutParams generateDefaultLayoutParams() { return new CentricFlowLayout.LayoutParams(halfGap, halfGap); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int yAxis = centricHeightPadding + getPaddingTop() + getPaddingBottom(); View child; int measuredWidth; int lineWidth = getPaddingLeft() + getPaddingRight(); CentricFlowLayout.LayoutParams lp; int offset; LINE_CHILDREN.clear(); for (int i = 0; i < count; i++) { child = getChildAt(i); lp = (LayoutParams) child.getLayoutParams(); if (GONE != child.getVisibility()) { measuredWidth = child.getMeasuredWidth(); if (lineWidth + measuredWidth + lp.horizontalSpacing > width) { offset = (width - lineWidth) / 2; layoutHorizontalCentricLine(LINE_CHILDREN, offset, yAxis); lineWidth = getPaddingLeft() + getPaddingRight() + measuredWidth + lp.horizontalSpacing; yAxis += lineHeight; LINE_CHILDREN.clear(); LINE_CHILDREN.add(child); } else { lineWidth += measuredWidth + lp.horizontalSpacing; LINE_CHILDREN.add(child); } } } offset = (width - lineWidth) / 2; layoutHorizontalCentricLine(LINE_CHILDREN, offset, yAxis); } private void layoutHorizontalCentricLine(final List<View> children, final int offset, final int yAxis) { int xAxis = getPaddingLeft() + getPaddingRight() + offset; for (View child : children) { final int measuredWidth = child.getMeasuredWidth(); final int measuredHeight = child.getMeasuredHeight(); final CentricFlowLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.layout(xAxis, yAxis, xAxis + measuredWidth, yAxis + measuredHeight); xAxis += measuredWidth + lp.horizontalSpacing; } } } A: try : dependencies { implementation'com.google.android:flexbox:0.3.2' } A: Try setting both of lp's LayoutParams to be WRAP_CONTENT. Setting mlp to be WRAP_CONTENT, WRAP_CONTENT ensures that your TextView(s) t are just wide and tall enough enough to hold "Hello" or whatever String you put in them. I think l may not be aware of how wide your t's are. The setSingleLine(true) may be contributing too.
unknown
d8988
train
It turns out that I called an async void method, which made some strange unknown(by me) things happen. Here is the some conceptual code: [HttpPost] public async Task<JsonResult> Data() { await SomeTask(); return Json(new { message = "Testing" }); } private async Task SomeTask() { FireAndForget(); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } private async void FireAndForget() { await Task.Delay(TimeSpan.FromSeconds(100)).ConfigureAwait(false); } With above code, I thought the response would come 1 second after requesting. But it does not, not even 100 seconds after. In some cases I get a InvalidOperationException, in other cases I get nothing. If I change the async void to async Task, either ConfigureAwait(false) or not, every thing works: [HttpPost] public async Task<JsonResult> Data() { await SomeTask(); return Json(new { message = "Testing 4" }); } private async Task SomeTask() { FireAndForget(); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } private async Task FireAndForget() { await Task.Delay(TimeSpan.FromSeconds(100)).ConfigureAwait(false); } The reason responses are sent when web server shutting down in my production code, is because my FireAndForget() method there is an async loop reading network messages, and never returns untill the connection closed, and shutting down the web server closes the connection. It's still strange to me that I didn't get InvalidOperationException there though.
unknown
d8989
train
You can use the aspect-ration css property https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio .booking-calendar { width: 400px; display: flex; } .booking-calendar .react-calendar__tile { width: 100%; aspect-ratio: 1 / 1; margin: 10px; } .booking-calendar .react-calendar__tile--active abbr { outline: 2px solid #444444; box-sizing: border-box; width: 100%; height: 100%; border-radius: 40px; font-weight: 700; } .booking-calendar .react-calendar__month-view__days__day abbr { padding: 10px; border-radius: 40px; display: flex; justify-content: center; align-items: center; } <div class="booking-calendar"> <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;"> <abbr aria-label="July 11, 2022">11</abbr> </button> <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;"> <abbr aria-label="July 12, 2022">12</abbr> </button> <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;"> <abbr aria-label="July 13, 2022">13</abbr> </button> <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;"> <abbr aria-label="July 14, 2022">14</abbr> </button> </div> You will need to remove the flex inline style that collides with the aspect-ratio effect.
unknown
d8990
train
This should work for you then - for (int index = 0; index < carInfos.Count/6; index++) { int offest = index * 6; Cars.AllCars.Add(new CarModel{ Plate = carInfos[0 + offest].Value, Type = carInfos[1 + offest].Value, NetWorth = int.Parse(carInfos[3 + offest].Value, etc, etc.. }); } Since you have total of 7 items that's why (42/6) = 7 and item is at offset of multiple of 6 hence the logic for calculation of offset (offest = index * 6)
unknown
d8991
train
In panda we have groupby with cumcount df['C']=df.groupby('A').cumcount().gt(0).map({False:'New',True:'Update'})
unknown
d8992
train
I think a good idea would be to use an interface (List if element are ordered, or Set if elements are not ordered. You can use the implementation you prefer, for example: List<Card> deck = new ArrayList<Card>(); or Set<Card> deck = new HashSet<Card>(); A: If you really want to understand the nuances between the collection types, here goes. List isn't technically appropriate except when the game is Bohnanza (which, ahem, is one of the greatest card games of all time, but I'mma let me finish). List says, among other things, that one hand containing the Ace and King of Clubs, and another hand containing the King and Ace of Clubs, are fundamentally not the same hand. This is a much stronger dependence on order than simply "well, I want to remember the order that the user wants to see their cards in", which is a property that tons of non-List collections have, like LinkedHashSet and Guava's ImmutableSet. List also implies that there is some particular significance attached to the card that sits in index N. This is true of no card game I know. Set isn't generally appropriate for card games -- only the ones that use a single deck of completely unique cards. To allow duplicates but still have order-independent equality, the type to use is Guava's Multiset. For example HashMultiset or ImmutableMultiset. Note that most multiset implementations represent multiple "equal" cards by storing just the card and a count, so when iterating over them, duplicates of a card you have in your hand must always appear together. If it's important to let the user freely control the order of cards in her hand, you would need LinkedListMultiset. Now that lesson time is over.... well, let's be honest. Calling myHand.equals(yourHand), or using an entire hand as a key in a Map is not actually something you're ever going to do... so go ahead and use the ArrayList, you'll be fine. :-) A: Store them in an ArrayList. Cards in a hand are in a certain order, not in an unordered pile. This ordering is preserved in a List over a Set. ArrayList also gives you the opportunity to select a specific card by index, which will be helpful as you implement the game. Keep in mind that as long as you design your Hand class properly, you can always change this data structure easily at any point in the future. As long as you keep this in mind with any class you design, you can always change it if you realize you need something different. A: Well, a HashSet is faster(as far as I know), but if you want to make a card game, then maybe you will wish to sort the cards. That is why I would suggest using a List. If you are a beginner, then maybe the best thing would be to use an ArrayList. It's easy to use and understand. At least this is what I would do. If you want to learn more, I suggest reading about each one's unique properties so that you can decide for yourself. And yes, like greuze said before, you should use an interface for more flexibility. A: Firstly, use of Vector is discouraged in the latest versions of Java, so you can probably ignore that one. Secondly, as you'll know if you're read the Javadoc on those remaining classes, they all have advantages or disadvantages. Some have an order, some can take duplicate values, some cannot and so on. Therefore I think the best approach is to write some pseudo-code for your application which is not based on a specific class (just write things like 'add Card to Hand', 'remove card from Hand'). Once you have some of this pseudo code you will be able to see your requirements more clearly; will you want to keep the cards in the hand in a specific order? will you want to be able to retrieve cards from the hand by a key? Then, your choice will be clearer. A: Keeping the deck in a List makes sense as it does maintain order. I tend to default to using Lists.newArrayList() to create a List. Lists is part of Guava. I strongly recommend using and getting to know Guava since it has many useful offerings. It would make sense to be able to keep the hand in some data structure that could be sorted easily in order to make it easier to compare hands. OTOH, IIRC, gin rummy hands aren't all that large.
unknown
d8993
train
Create a separate table to store the count value. Create insert, update and delete triggers for table1, which calculates the new count and updates the count value. But do you really need to do this? Are you having performance problems with select count(*) from table1? You know, triggers will slow down all update, delete and inserts a bit. A: Just use a Select Count to the table ,even if you select just a column and count that for your rows or select the the whole table to count the complete table data...put your count expression after your update is done .
unknown
d8994
train
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
unknown
d8995
train
The first thing you do is already a mistake: Sorting. That'll make you report that [6, 5, 4, 3, 2, 1] has three such triples (same as the example) when in reality it doesn't have any. (Given that you pass two of five tests, I can imagine this is your only mistake. Maybe those tests are already sorted so you're not messing those up.)
unknown
d8996
train
Send your object in ireport using java program. Define a field with name of your instance and attribute. e.g. Suppose you send your class instance with grupoEstadistico, define a field in ireport with name "grupoEstadistico.tipoEntidad". and Drag a textfield in any band. RightClick->Edit Expression-> remove ${field}-> double click on your field->click apply It will add you attribute in *iReport *. now if you download your file as pdf format , it will show data what ever you send in this instance.
unknown
d8997
train
* *If you have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file and it's enable property value under <EmbeddedLDAP> is templated as {{embedded_ldap.enable}} (shown below), <EmbeddedLDAP> <Property name="enable">{{embedded_ldap.enable}}</Property> <Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property> <Property name="instanceId">default</Property> ..... </EmbeddedLDAP> you can use the following deployment.toml config [embedded_ldap] enable = false *If the <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file contains the EmbeddedLDAP config's enable property value as hardcoded to "true", you can change it to false and restat the server to change the config in embedded-ldap.xml. <EmbeddedLDAP> <Property name="enable">true</Property> <Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property> <Property name="instanceId">default</Property> ..... </EmbeddedLDAP> *If you don't have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file, the property value changes in embedded-ldap.xml won't be replaced once the server is restarted. A: In WSO2 Identity Server 5.10.0 the configurations are managed by a centralized toml file which is called as deployment.toml. We can add the following configuration to the deployment.toml file which is located in <IS_HOME>/repository/conf directory. [embedded_ldap] enable = false A: In WSO2 Identity Server 5.10.0 version the file embedded-ldap.xml.j2 doesn't come inside wso2is-5.10.0/repository/resources/conf/templates/repository/conf/identity so I needed to copy the file from this link: embedded-ldap.xml.j2 and put inside my configuration for docker container conf/is-as-km/repository/resources/conf/templates/repository/conf/identity docker-compose.yml ... volumes: - ./conf/is-as-km:/home/wso2carbon/wso2-config-volume ports: - "9444:9443" ... After that I put the property in deployment.toml: [embedded_ldap] enable = false And everything worked as shown in docker log: cup-is-as-km ... NFO {org.wso2.carbon.identity.oauth.uma...} - UMA Grant component activated successfully. cup-is-as-km ... INFO {org.wso2.carbon.ldap.server.DirectoryActivator} - Embedded LDAP is disabled. cup-is-as-km ... INFO {org.wso2.carbon.mex.internal.Of...} - Office365Support MexServiceComponent bundle activated successfully.. Based on the last answers and comments I reached the solution ;).
unknown
d8998
train
I get that error when the MySQL service isn't running. What OS are you on? I'm on Debian GNU/Linux, so I start the service with # service mysql start but other systems may use something different, like start or invoke-rc.d or something.
unknown
d8999
train
Just use two loops to iterate over the data: <?php $input = [1, 2, 3, 4]; foreach ($input as $left) { foreach ($input as $right) { if ($left < $right) { echo sprintf("%dx%d = %d\n", $left, $right, $left*$right); } } } For bigger data sets you might want to optimize it. Faster but harder to read: <?php $input = [1, 2, 3, 4]; foreach ($input as $key => $left) { foreach (array_slice($input, $key+1) as $right) { echo sprintf("%dx%d = %d\n", $left, $right, $left*$right); } } The output obviously is: 1x2 = 2 1x3 = 3 1x4 = 4 2x3 = 6 2x4 = 8 3x4 = 12
unknown
d9000
train
In our case, it was clear that there was a bug in the way Xcode was resolving dependencies to our target. Let's me start by saying, the solution was: import PassKit Now, before you raise that eyebrow, here is why this worked: * *We relied on a Swift framework that imports PassKit *We distributed the prebuilt binary to team members *The team observed the crash, just as OP mentioned it *Adding that import in the app target made Xcode embed the required swift libraries Note: Just linking PassKit in the GUI did absolutely nothing. A: Cracked it. Check if the framework you're trying to build or one of it's dependency framework uses any of the Swift standard libraries. If yes, create a NEW key in the build settings ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; A: I had this same error for a couple of weeks: dyld: Library not loaded: @rpath/libswiftContacts.dylib Basically I was able to run and test my app on device. Then about 2 weeks ago, I wasn't able to run the tests on device anymore. Tests were running fine on simulator. I can't think what changed. The error I saw was the one above. I searched Google for ages trying to find a solution, and tried many fixes unsuccessfully. The fix that finally worked was to delete the Derived Data. Once I did this, I was once again able to run the tests on my device. Fix that worked for me: * *Go to Xcode > Preferences > Locations > Derived Data (click on little arrow to open up the folder in finder) e.g. /Users/[username]/Library/Developer/Xcode/DerivedData *Delete the entire DerivedData folder *Clean/Build *Test on device - finally works again A: This error is caused due to invalid certification of Apple. Go to your keychain access. Under "Keychains" select "System" and under "Category" select "Certificates". Check whether the "Apple Worldwide Developer Relations Certification Authority" is valid or not. If not download that certificate from Apple site. It'll solve the problem. A: I know this is old question, but this is what helped me Speaking shortly: EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
unknown