_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d18201
test
The question basically drill downs to when should I make a method static. The answer is simple- when your method has a very specific task and does not change the state of the object. Something like a utility method, say add(int a, int b) which simply returns a+b. If I need to store the value a+b for later use for the object, static method is strictly no-no (you will not be able to store a non static variable in a static method). But if we are dealing with some action which is independent of state of the object, static is the answer. Why are we giving preference to static if it is independent of state of object? * *Memory- static method will only have one copy, irrespective of the actual number of object. *Availability- Method is available even if you don't have single object Ofcourse the downside is that we are keeping a copy of method even if we do not use it at all (if it was non-static and no object was created, we would have saved this space). But this is of lower weight than the advantages mentioned above. As the method we are discussing here (makeText), does not need to maintain a state for later use, the best way to go is static method. --Edit-- The answer mentioned above is more generic as to when we should use static and when non-static, let me get specific to Toast class. Toast class gives us 2 ways to create a Toast object (Refer http://developer.android.com/reference/android/widget/Toast.html) * *makeText(Context context, CharSequence text, int duration) which returns a Toast object which the values assigned. *Normal way, use new Toast(context) to create an object, then set values as required. If you use method 1, you are saying something like Toast.makeText(context, text, duration).show(); and we are done. I use this method all the time. Method 2 is used only for a specific case, from http://developer.android.com/guide/topics/ui/notifiers/toasts.html Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast. @CFlex, If I got your question properly, I guess you just want to know why we have Toast.makeText(context, text, duration) returning a Toast object, when the same thing could have been done by a constructor. Whenever I look at something like ClassName.getObject returning object of class, I think about singleton pattern. Well, in this case we are not exactly talking about singleton, I would like to assume that makeText returns same object always (to save creation of N objects), otherwise it is just a fancy thing developed by Android team. A: One rule: Ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static. Remember that objects live in memory and they are created for certain jobs. Static methods are available for all the objects in a class and it is not necessary to create an object to use them. So there is no reason to create an object Toast to be able to access the method makeText, when you can access it as a static method (more elegant and compact) A: As far as I know: That's because we don't wish to hold an instance of the object toast, which would require an amount of memory persistently used until cleaned by the GarbageCollector. And that it always have access to being displayed, so it is not required by your application to have any set of permissions.
unknown
d18202
test
In this answer I assume that your direct parent is always in a row above your own as it is what your expected output and your diagramm suggests. With this hypothesis, we can, for each row, take the closest row with a level below the row : import pandas as pd data={"Symbol":["A", "A01", "A01B", "A01B 1/00", "A01B 1/02", "A01B 1/022", "B"], "level":[2,4,5,7,8,9,2]} df=pd.DataFrame(data=data) df['Parent'] = '' for index, row in df.iterrows(): # We look at the potential parents potential_parents = df.loc[df.index.isin([x for x in range(index)]) & (df['level'] < row['level']), 'Symbol'] # And we take the last one as our parent if len(potential_parents) == 0: df.loc[index, 'Parent'] = '' else: df.loc[index, 'Parent'] = potential_parents.iloc[-1] Output : Symbol level Parent 0 A 2 1 A01 4 A 2 A01B 5 A01 3 A01B 1/00 7 A01B 4 A01B 1/02 8 A01B 1/00 5 A01B 1/022 9 A01B 1/02 6 B 2 A: Here's another method. GetParent() returns a function that keeps track of the most recent symbol for each level and returns the parent of the current level. Using it in pandas.apply() creates a column with the parent symbols. def GetParent(): # 0 1 2 3 4 5 6 7 8 9 10 hierarchy = [0, 0, 0, 0, 2, 4, 0, 5, 7, 8, 9] parent = [' ']*11 def func(row): #print(row) symbol,level = row[['SYMBOL', 'level']] parent_level = hierarchy[level] parent_symbol = parent[parent_level] parent[level] = symbol return pd.Series([parent_symbol], index=['parent']) return func # create a column with the parents parents = df.apply(GetParent(), axis=1) df = pd.concat([df, parents], axis=1) df Output: SYMBOL level na ao parent 0 A 2 True False 1 A01 4 True False A 2 A01B 5 True False A01 3 A01B 1/00 7 False False A01B 4 A01B 1/02 8 False False A01B 1/00 5 A01B 1/022 9 False False A01B 1/02 6 A01B 1/024 9 False False A01B 1/02 7 A01B 1/026 9 False False A01B 1/02 8 A01B 1/028 9 False False A01B 1/02 9 A01B 1/04 9 False False A01B 1/02 10 A01B 1/06 8 False False A01B 1/00 11 A01B 1/065 9 False False A01B 1/06 12 A01B 1/08 9 False False A01B 1/06 ...
unknown
d18203
test
With your current code, you are trying to filter patterns with patterns. Using the WHERE Clause with variables would be the best approach. Match the pattern first and then filter on the desired property. You could use the following Query to match users based on their postcode: MATCH (p:Person)-[:HasPostcode]->(pc:Postcode) WHERE pc.value='LA2 0RN' RETURN p, pc If you want to use an OR condition and find matches for Postcode or Name: MATCH (f)<-[:HAS_FIRST_NAME]-(p:Person)-[:HasPostcode]->(pc) WHERE pc.value='LA2 0RN' OR f.value='Jerry' OR f.value='Tom' RETURN f, p, pc
unknown
d18204
test
I think you need an architect to re-design your solution to lift in the cloud. It is good time to check whether you want to move to managed products or would prefer just the same in the cloud. Talking about the products: * *Rabbit QM should be replaced with Pub/Sub, which fits pretty good. If you would like to keep using RabbitMQ here. PubSub should be the best choice if you want to move most of your solution to the Google Cloud, and in the long term could bring more benefits in the Gooogle Cloud ecosystem. *Dataflow is a good batch processor. Here is an example of PubSub - Dataflow: Quickstart: stream processing with Dataflow. There are Google-Provided batch templates or you can create one: traditional or Flex. Don't rush and pick a solution. It is well worth to check all your business and technical requirements and explore the benefits of each product (managed or not) of the Google Cloud. The more detailed your requirements are, the best you can design your solution. A: Google Cloud offers, today, only one workflow manager named Cloud Composer (based on Apache Airflow project) (I don't take into account the AI Platform workflow manager (AI Pipeline)). This managed solution allow you to perform the same things than you do today with Celery * *An event occur *A Cloud Function is called to process the event *The Cloud Function trigger a DAG (Diagram Acyclic Graph - a workflow in Airflow) *A step in the DAG runs a lot of sub process (Cloud Function/Cloud Run/anything else) wait the end, and continue to the next step... 2 warnings: * *Composer is expensive (about $400 per month, for the minimal config) *DAG are acyclic. no loops are authorized Note: A new workflow product should come on GCP. No ETA for now, and at the beginning the parallelism want be managed. IMO, this solution is the right one for you, but not for short term, maybe in 12 months About the MQTT queue, you can use PubSub, very efficient and affordable. Alternative You can build your own system following this process * *An event occur *A Cloud Function is called to process the event *The cloud function create as many PubSub message as batched are required. *For each message generated, you write an entry into Firestore with the initial event, and the messageId *The generated messages are consumed (by Cloud Function, Cloud Run or anything else) and at the end of the process, the Firestore entry is updated saying that the sub process has been completed *You plug a Cloud Function on Firestore event On Write. The function checks if all the subprocess for an initial event are completed. If so, go to the next step... We have implemented a similar workflow in my company. But it's not easy to maintain and to debug when a problem occur. Else, it works great.
unknown
d18205
test
Final version developed through comments: DECLARE @sql AS NVARCHAR(MAX) DECLARE @cols AS NVARCHAR(MAX) SELECT @cols= ISNULL(@cols + ',','') + QUOTENAME(case when breakname like 'Perfect%' then 'Perfect' else breakname end) FROM (select * from breaks where breakname not like 'Perfect - 90') a group by id, breakname order by id SET @sql = N'SELECT seller, saledate, ' + @cols + ' FROM (select seller, saledate, case when breakname like ''Perfect%'' then ''Perfect'' else breakname end breakname from test inner join breaks on case when breakcode = 8 then 1 else breakcode end = id) derived PIVOT(count(breakname) FOR derived.breakname IN (' + @cols + ')) AS PVTTable ORDER BY seller, saledate' EXEC sp_executesql @sql SQL Fiddle
unknown
d18206
test
Audio/Video has been restricted from autoplaying. They can play only with user interaction. Also please keep the format of the audio file as ogg instead of m4a as you have specified the type as audio/ogg. Change from voice/Story 2_A.m4a to voice/something.ogg
unknown
d18207
test
I could get it to work by changing maskContentUnits back to its default value of userSpaceOnUse but that doesn't feel right because of the static dimensions i would have to assign to the mask shape. It would be much better if the rect in my mask would scale to each object the mask gets applied to. So, if anyone has a better solution, I would be very thankful... #my-defs { position: absolute; top: -1000px; left: -1000px; } #my-svg { width: 200px; height: 3em; } #my-svg rect { width: 100%; height: 80%; } <svg id="my-defs"> <defs> <pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4"> <path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" /> </pattern> <mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="userSpaceOnUse"> <rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="9000" height="9000" /> </mask> </defs> </svg> <svg id="my-svg"> <rect fill="steelblue" mask="url(#diagonal-hatch-mask)" /> </svg>
unknown
d18208
test
You could do something like this (I'm using lsqlite3 so adjust accordingly): db = sqlite3.open(':memory:') db:execute [[ create table xxx(xxx); insert into xxx values('one'); insert into xxx values('two'); insert into xxx values('three'); ]] sql = [[select last_insert_rowid() as num;]] for ans in db:nrows(sql) do print(ans.num) end
unknown
d18209
test
Try with: $i = 0; // init $i $x = 'icon'.($i+1); If you want to regularly increment $i variable: $x = 'icon'.(++$i); A: try this : $temp = $i+1; $x = 'icon'.$temp; You are getting wrong answer because of "Operator Precedence", Ref this link : http://php.net/manual/en/language.operators.precedence.php Here see the line : left + - . arithmetic and string . has more Precedence than +, So your expression will be like : $x = ('icon'.$i)+1; To solve it either use the method i mentioned above or hsz answer ie : $x = 'icon'.($i+1); A: Operator Precedence explains why this is happening. You can use brackets: $x = 'icon'.($i+1); This should do the job. My test: $i = 18; $x = 'icon'.($i+1); var_dump($x); --> string(6) "icon19"
unknown
d18210
test
Try this format <a href="link_to_target" target="_blank"><img src='image_src' border="0"/></a> It is up to you if you want to define the target attribute in <a> tag. A: // JavaScript Document // // Type the number of images you are rotating. var numberOfImagesToRotate = 3; // Edit the destination URl here var linkUrl = 'example.html'; // HTML-partials var imgFirstPart = '<img src="domain/rotatingimages'; var imgLastPart = '.gif" height="250" width="388" border="0">'; var anchorFirstPart = '<a href="'; var anchorSecondPart = '">'; var anchorLastPart = '</a>'; function printImage() { var r = Math.ceil(Math.random() * numberOfImagesToRotate); document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart); }
unknown
d18211
test
You're telling the browser to wait for the load-event, this (from the aforementioned MDN-docs): ...fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. Hence, don't use onload if you don't need to wait for the DOM to be ready. <link href="default.css" type="text/css" rel="stylesheet" id="dynamic_stylesheet" /> <script> if (window.localStorage['webpage_style']) { var styleLink = document.getElementById("dynamic_stylesheet"); styleLink.href = window.localStorage['webpage_style']; } </script> Or if that still introduces a flash you could write the style link conditionally in JS. <script> if (window.localStorage['webpage_style']) { document.write("<link href=\""+window.localStorage['webpage_style']+"\" type=\"text/css\" rel=\"stylesheet\" />"); } else { document.write("<link href=\"default.css\" type=\"text/css\" rel=\"stylesheet\" />"); } </script> <noscript> <link href="default.css" type="text/css" rel="stylesheet" /> </noscript>
unknown
d18212
test
I guess SAML assertion may not contain the all audience urls. In Trusted IDP UI, you can configure identity provider audiences. If you have defined them, those urls must be in the assertion. Also.. value that is defined by "OAuth2 Token Endpoint Name:" must be also as an audience url in assertion.
unknown
d18213
test
One way is to read a well known site content with URL connection. If you can read it, then it means you have an Internet connection. Other is to connect to your radio station site: this has double requirement: you have Internet connection AND the radio station site is up. Maybe both of them will block you, if you read too often! There is android buggy API to read the network state and suck, but if you connect to WIFI , then you will have the Connected state from API even if your WAN cable pulled out...
unknown
d18214
test
Something like this, though with mutiple authors it remains a question which author you order by: var sorted = from book in b let firstAuthor = book.BookAuthors.First() let lastName = firstAuthor.LastName order book by lastName select book Alternatively you could apply some logic (if you had it)... var sorted = from book in b let author = book.BookAuthors.FirstOrDefault(a=>a.Primary) ?? book.BookAuthors.FirstOrDefault(a=>a.Editor) ?? book.BookAuthors.First() let lastName = author.LastName order book by lastName select book
unknown
d18215
test
This worked shader.uniforms[ "tDiffuse" ].value = panoTexture;
unknown
d18216
test
This should do it. Use the .indexOf() on an array of the good values and check if the value is in the array. To ensure that the handler fires at page load trigger the change event with .change().: $(document).ready(function() { $('#dropdown').on('change', function() { if ( ['field2', 'field3'].indexOf( this.value ) > -1 ) { $("#image").show(); } else { $("#image").hide(); } }) .change(); }); $(document).ready(function() { $('#dropdown').on('change', function() { if ( ['field2', 'field3'].indexOf( this.value ) > -1 ) { $("#image").show(); } else { $("#image").hide(); } }) .change(); }); #image img { padding-left: 60px; position:absolute; padding-top: -10px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="dropdown" name="dropdown"> <option value="field1" selected="selected">None</option> <option value="field2">field2</option> <option value="field3">field3</option> </select> <div id="image"> <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQijmYaWonPS_ckwz9WLIrMpDPWCQDOTe8D7O_RIjEVcyMKr7NwZQ" alt="some image" /> </div> Update Note: For the purpose of continuity, it is good practice to retain the original question and include any new updates. When the question is drastically different, it's advisable to create a new question. $(document).ready(function() { $('#dropdown').on('change', function() { $('#image,#image1').hide(); if ( this.value === 'field2') { $("#image").show(); } else if(this.value === 'field3') { $("#image1").show(); } else { $("#image").hide(); $("#image1").hide(); } }) .change(); }); #imagex img { padding-left:554px; position:absolute; padding-top: 774px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="dropdown" name="dropdown"> <option value="field1" selected="selected">None</option> <option value="field2">field2</option> <option value="field3">field3</option> </select> <span id="image">#image</span> <span id="image1">#image1</span>
unknown
d18217
test
Agree this is a bug, which I see you've submitted. A temporary workaround is to specify the filename option: devtools::source_gist("524eade46135f6348140", filename = "ggplot_smooth_func.R")
unknown
d18218
test
The "function" is a reserved word, and in object notation may require quotes, Netbeans is expecting () after the Function key word. A: As Bodman Said, function is a reserved word so you need to quote that. But you may also need to quote all the hash keys for netbeans to interpret them correctly for example: $.get("/adminc/utilsAjax.php", { "function": "orderIsOpenOrClosed", "orderID": orderID, "rand": randn }, function(data){ // fun body }); A: You have missed a { after function(data)
unknown
d18219
test
Mark your superclass as abstract, because it clearly is supposed to be.
unknown
d18220
test
I could not fix this issue. It was looping through upgrades and downgrades, so after much frustration I tried Ruby 2.6 that Redmine 4.2 claimed to be compatible, which still had issues. I downgraded to Ruby 2.3 and it worked, then I migrated my database according to the redmine.org documentation and almost everything is functional, and I got a feedback that it is much faster. According to my experience, you will have your Redmine database still working so don't worry that it s the same version.
unknown
d18221
test
So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all? It doesn't make any sense to have a factory with specific methods. If your client code has to decide which specific method should it use, why wouldn't it call the specific car's constructor directly? In your example, factory methods would merely be wrappers over specific constructors. On the other hand having a single factory method that is called with an enum gives your client a chance to decide dynamically which car should it create, the decision could for example be based on a database query. There are some possible ways around your current approach. One option would be to have a hierarchy of classes that represent constructor parameters. You don't even need the enum then because the parameter type is enough to infer which specific car should be created: public abstract class CarCreationParams { } public class FordCreationParams : CarCreationParams { public Engine engine; } ... public class CarFactory { public Car GetCar( CarCreationParams parms ) { if ( parms is FordCreationParams ) return new Ford( ((FordCreationParams)parms).engine ); ... Another option would be to think whether you really need your Fords to be created with external engines (aggregation) or rather they own their engines (composition). In the latter case, you would expose parameterless constructors to your specific car types: public class Ford : Car { public Engine engine; // car is composed of multiple parts, including the engine public Ford() { this.engine = new FordEngine(); } which makes the implementation of the factory much easier. A: No that is not a good example of factor pattern. Rather if your Car class is dependent on different types of Components you can have factories for those too. E.G For Car and Engine you can have like: public interface ICar { IEngine Engine { get; set; } } public class Mustang : ICar { private IEngine _engine = EngineFactory.GetEngine(EngineType.Mustang); public IEngine Engine { get { return _engine; } set { _engine = value; } } } public class CarFactory { public ICar GetCar(CarType carType) { switch (carType) { case CarType.Ford: return new Mustang(); } } } Similarly for Engine public interface IEngine { } public class MustangEngine : IEngine { } public class EngineFactory { public static IEngine GetEngine(EngineType engine) { switch (engine) { case EngineType.Mustang: return new MustangEngine(); } } } A: In case you need different parameters for object creation(batteries for Tesla or Engine for Ford) you can choose between different solutions: - pass all of these parameters while creating a factory - it will be specific factory for all types of car with such available details; class SpecificCarFactory { public SpecificCarFactory(IList<Battery> batteries, IList<Engine> engines) { //save batteries etc into local properties } public Car GetCar(CarType carType) { switch(carType) { case CarType.Ford: return new Mustang(_engines.First()); } } } * *encapsulate parameters into class object and get them from factory method parameter; class CarFactory { public Car GetCar(CarDetail carDetail) //where CarDetails encapsulates all the possible car details { switch(carDetail.type) { case CarType.Ford: return new Mustang(carDetail.Engine);//just an example } } } A: Yes, It is factory pattern. factory pattern says to create factories of Object but let subclass decide the way to instantiate the object . This is true in your case your deciding based on type of Enum
unknown
d18222
test
That is... odd. I can't repro it here, so I'm guessing it is something specific to Blazor. I've checked what the code does in the "regular" frameworks, and at least for me it seems to do the right things - using UnaryValueTaskAsync<Customer, Customer>() and UnaryValueTaskAsync<Empty, CustomerResultSet>(), which is what I would expect. I've improved the exception handling in that code path, to at least give us a clue what it is trying to do, so my suggestion is: * *update to protobuf-net.Grpc version >= 1.0.119 (I'll get it deployed as soon as CI finishes) *retry, and let me know exactly what it says now Alternatively, if you have a minimal repro including the blazor bits on, say, a GitHub repo, I can happily take a look there. (tip: I try to keep an eye on both Stack Overflow and GitHub, but GitHub is probably more appropriate for this kind of question - I'd happily say that this is a bug, so: https://github.com/protobuf-net/protobuf-net.Grpc/issues) A: I was having a similar problem. System.InvalidOperationException: Error obtaining client-helper 'UnaryValueTaskAsync' (from: 'System.Guid', to: 'Test.DTO.OpResult'): Invalid generic arguments My entire ServiceContract on that service stopped working. This happened after I added ValueTask ChangeCompany(Guid companyGuid); I changed it to ValueTask ChangeCompany(string companyGuid); And that got it working again. The error was a bit confusing since i wasn't using ChangeCompany, but like a said, not calls were working.
unknown
d18223
test
Set the primarykey after you load from the database. I don't think dataadapters set the primarykey.
unknown
d18224
test
The SoapFault you're facing is not due to the parameters but due to the fact that the SoapAction address is not reachable from your network or is simply invalid. * *You should first check the url in <soap:address location="{url}" /> in the WSDL and ensure that it is reachable, *You should then use a WSDL to php generator that will ease you the task of sending the request. Indeed you won't have to wonder about soap as you'll only deal with objects or at least you'll know exactly how to send the parameters. I can only advise you to try the PackageGenerator as it's mine but you can find other project of this type out there
unknown
d18225
test
Sub SearchReport() Dim p As Integer p = 25 Report FileSystem.getFolder(HostFolder), p End Sub
unknown
d18226
test
Why do you need TimeoutCountSequenceSizeReleaseStrategy; your sequences are finite; just use the default SimpleSequenceSizeReleaseStrategy. However the TimeoutCountSequenceSizeReleaseStrategy should release based on the sequence size anyway. But, it's not really suitable for your use case because you can be left with a partial group in the store.
unknown
d18227
test
One option would be to map a condition, i.e. PSF != 1 on the shape aes and set your desired shape using scale_shape_manual: library(ggplot2) ggplot(data = block.data, aes(x = PSF, y = CC, group = 1)) + geom_line() + geom_point(aes(shape = PSF != 1), size = 3) + scale_shape_manual(values = c(17, 16)) + theme_bw() + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black") ) + scale_x_continuous(breaks = seq(0, 2, .2)) + scale_y_continuous(breaks = seq(0.08, 23, .01)) + guides(shape = "none")
unknown
d18228
test
The function addItemsToMyArray() has correctly been set up to return the array to the main PHP code but you forgot to catch that return value and put it in a variable. One way to write this code and make the difference easier to see could be like this: function addItemsToMyArray($tmpArray) { $tmpArray[] = 'apple'; $tmpArray[] = 'banana'; $tmpArray[] = 'coconut'; return $tmpArray; } $myArray = array(); $myArray = addItemsToMyArray($myArray); echo count($myArray); /* Gives 3 */ The variable used inside the function is a different variable than the $myArray variable outside of the function. A: Unless you specify otherwise, function/method arguments are pass-by-value, meaning you get a copy of them inside the function. If you want the function to change the variable that was passed to it, you need to pass-by-reference. As described here: By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition: Note the ampersand before $array in the doc page for sorting functions like asort() and ksort(): bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
unknown
d18229
test
WebAudio should be able to start audio very precisely using start(time), down to the nearest sample time. If it doesn't, it's because the audio data from decodeAudioData doesn't contain the data you expected, or it's a bug in your browser. A: Looks like when you call keyPressed, you want to trigger both songs to start playing. One immediately, and the other in 7.5 seconds. * *The function to play the songs is soundObj.play and it needs to take an additional argument, which is the audioContext time to play the song. Something like: soundObj.play = function(volumeVal, pitchVal, startTime) {...} *The function keyPressed() block should look something like this: harp1.play(.5, 2, 0); harp2.start(1, 1, audioContext.currentTime + 7.5); audioContext.resume(); audioContext.resume() starts the actual audio (or rather starts the audio graph timing so it does things you've scheduled)
unknown
d18230
test
A few things: * *Use the grid array to store the on\off blocks of the screen. It only gets read when the screen is resized and needs a full redraw *When a new rectangle is turned on, draw the rectangle directly in the event handler and update the grid array. There is no need to redraw the entire screen here. *In the resize event, reset the screen mode to the new size then redraw the entire screen using the grid array. This is the only time you need to do a full redraw. Here is the updated code: import pygame #from grid import Grid #from pincel import Pincel #from debugger import Debugger #from display import Display from pygame.locals import * pygame.init() #pygame.mixer_music.load("musica/musica1.wav") #pygame.mixer_music.play(-1) width = 1000 height = 1000 screen = pygame.display.set_mode((width, height), pygame.RESIZABLE) pygame.display.set_caption("SquareDraw") #Grid Creator numberOfRows = 250 numberOfColumns = 250 #grid = Grid(numberOfRows, numberOfColumns) grid = [[0 for x in range(numberOfRows)] for y in range(numberOfColumns)] # use array for grid: 0=white, 1=black # Medidas basicX = width / numberOfColumns basicY = height / numberOfRows #Tool Creator #pincel = Pincel(2) #xx running = 1 #Initial values #grid.equipTool(pincel) #xx clicking = 0 def drawScreen(screen, grid, basicX, basicY): # draw rectangles from grid array for i in range(numberOfColumns): for j in range(numberOfRows): if grid[i][j]: #print('yes') #print(i, j) pygame.draw.rect(screen, (0, 0, 0), (j * basicX, i * basicY, basicX, basicY)) screen.fill((255, 255, 255)) # start screen while running: events = pygame.event.get() for event in events: if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): running = 0 if event.type == pygame.MOUSEBUTTONDOWN or clicking: # mouse button down clicking = 1 x, y = pygame.mouse.get_pos() #Debugger.printArray2D(grid.board) #print('') xInGrid = int(x / basicX) yInGrid = int(y / basicY) grid[yInGrid][xInGrid] = 1 # save this point = 1, for screen redraw (if resize) pygame.draw.rect(screen, (0, 0, 0), (xInGrid * basicX, yInGrid * basicY, basicX, basicY)) # draw rectangle #grid.ferramenta.draw(grid.board, xInGrid, yInGrid) #Debugger.printArray2D(grid.board) #print('') pygame.display.flip() # update screen if event.type == pygame.MOUSEBUTTONUP: clicking = 0 if event.type == pygame.VIDEORESIZE: # screen resized, must adjust grid height, width width = event.w height = event.h basicX = width / numberOfColumns basicY = height / numberOfRows #print(width, height) screen = pygame.display.set_mode((width, height), pygame.RESIZABLE) # reset screen with new height, width screen.fill((255, 255, 255)) # clear screen drawScreen(screen, grid, basicX, basicY) # redraw rectangles pygame.display.flip() # update screen pygame.quit()
unknown
d18231
test
str.replace(/(?<=\d),(?=\d)/g, '') (?<=\d): lookbehind - a digit (?=\d) : lookahead - a digit
unknown
d18232
test
You have set the class on the element instead of the id. But that is irrelevant anyway because you do not need to any of this for a single file component; just do this instead (as you did for App.vue): <template> <div class="intro" style="text-align:center;"> <h1>{{ message }}</h1> </div> </template> <script> export default { data() { return { message: 'My first VueJS Task' } } } </script> Constructing a Vue component manually with new Vue() is only necessary for the root component instance.
unknown
d18233
test
Fixed fiddle Check the DOM in your browser console you can see that the input is already inside the div, you should just adjust CSS, check example bellow. Hope this helps. var vertical_slider = document.createElement('div'); vertical_slider.id = 'vertical_slider'; var osa_y_panorama = 0.6; var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)"; range_pitch.style.oTransform = "rotate(90deg)"; range_pitch.style.msTransform = "rotate(90deg)"; range_pitch.style.transform = "rotate(90deg)"; range_pitch.min = "0"; range_pitch.max = "218"; range_pitch.step = "0.6"; range_pitch.defaultValue = osa_y_panorama; vertical_slider.appendChild( range_pitch ); document.body.appendChild( vertical_slider ); #vertical_slider { float: left; width: 40px; height: 218px; border: 1px solid blue; } input{ position: relative; top:93px; right: 83px; width:200px; } A: The problem come from your css rotation to the input, if you check the DOM, your element is inside but the rotation make it look outside. You can use this css to hot fix it : input { position: relative; right: 70px; top: 100px; }
unknown
d18234
test
Answering my own question. You have to manually specify the --sources for what CocoaPods will validate the spec against. pod spec lint MYPODNAME --verbose --sources=git@<DOMAIN>:<REPO>.git
unknown
d18235
test
Note that jstatd in CentOS 7 is now part of the package java-1.8.0-openjdk-devel. To install it: yum install java-1.8.0-openjdk-devel
unknown
d18236
test
Try this one: db.collection.aggregate([ { $sort: { id: 1, item_id: 1, last_update: -1 } }, { $group: { _id: { id: "$id", item_id: "$item_id" }, last_update: { $max: "$last_update" }, quantity: { $first: "$quantity" }, } }, { $project: { last_update: 1, quantity: 1, id: "$_id.id", item_id: "$_id.item_id", _id: 0 } } ]) Note, make proper $sort, otherwise $frist will return wrong value.
unknown
d18237
test
If you need any price information you could use chainlink oracle. Here is official docs for evm data feeds; https://docs.chain.link/docs/using-chainlink-reference-contracts/ . For a simple implementation example you can take a look at freeCodeCamp.org 's 32-hour course/lesson4 on youtube. Also you can take a look at uniswap API ; https://docs.uniswap.org/protocol/V2/reference/API/entities A: If you want it to be compatible across multiple chains and multiple DEXs, the easiest way I could think of is to call the router by using the method getAmountsOut. router.methods.getAmountsOut(amountIn, [inAddress, outAddress]).call() amountIn would be 1 * Math.pow(10, inAddress token decimals) inAddress is WBTC address outAddress is USDC address The output will be: 100000000,22397189858 Output[0] is amount in. Output[1] is amount out. You then have to divide that by (1 * Math.pow(10, out address decimal), where you will get WBTCprice: 22397.189858 The only caveat of doing this method is that you need to know the stable pair that exist on that dex. Some dex may use WBTC/USDT, some may use WBTC/USDC.
unknown
d18238
test
This is frequently a problem with beginners when they fail to validate the JS written. Whatever editor you use, try using a JS validator to validate whether JS has been written correctly. In this case, I believe you forgot to use a bracket after completing your getJSON function. $.getJSON( 'http://api.fixer.io/latest', function(data) { // Check money.js has finished loading: if ( typeof fx !== "undefined" && fx.rates ) { fx.rates = data.rates; fx.base = data.base; } else { // If not, apply to fxSetup global: var fxSetup = { rates : data.rates, base : data.base } } ); //This bracket is missing in your code For JS validation, use http://www.jslint.com/ A: I finally find the answer and it was very simple: I didn't specify what currency I wanted to convert in NZD: $('#bid_jpy').keyup(function(){ var nzd = fx.convert(this.value, {from: "JPY", to: "NZD"}); $('#bid_nzd').val(accounting.formatNumber(nzd, { precision : 0, thousand : "" })); });
unknown
d18239
test
Here's an answer addressing iterkeys vs. viewkeys here: https://stackoverflow.com/a/10190228/344143 Summary (with a little backstory): view* methods are a live view into the data (that will update as it updates), whereas iter* and just-plain * are more like snapshots. The linked answerer suggests that while the view*-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*/* under Python 2. My take: if you want a live view and you're under Python 2, use view*; if you just want to whip through the set of keys/values/items once, use iter*; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *. Let the performance slide until you pick it up in an inner loop.
unknown
d18240
test
It looks like ld is having trouble creating an executable file due to permission problems. Try building the program in a folder that you are sure that you own (like C:\Users\yourusername) or try adjusting the permissions for the folder you are building in.
unknown
d18241
test
I just briefly looked at the Github project you referenced, and I wanted to throw in my $0.02, for whatever it's worth - Breeze.js is responsible for taking care of client side caching for you. The idea is to not have to worry about what the back-end is doing and simply make a logical decision on the client on whether to proceed and hit the server for data again. If you don't need to refresh the data, then never hit the server, just return from Breeze's cache. The project you are referencing seems to do both - server side and client-side caching. The decision of caching on the server is one not to be taken lightly, but this project seems to handle it pretty well. The problem is that you are trying to mix two libraries which, at best, conflict in the area of what their concerns are. There may be a way to marry the two up, but at what cost? Why would you need to cache on the server that which is already cached on the client? Why cache on the client if you plan to cache the exact same data on the server? The only reason I can think of is for paging of data (looking at a subset of the whole) and wanting to see the next data set without having to hit the server again. In that case, your query to the server should not match the original anyway and therefore one would expect that you need to customize the two solutions to do what you are asking for. In general that project seems to ignore queryString parameters, from what I can tell, to support JSONP so you should have no problem coming up with a custom solution, if you still think that is necessary.
unknown
d18242
test
I would recommend not using DOM to parse HTML, as it has problems with invalid HTML. INstead use regular expression I use this class: <?php /** * Class to return HTML elements from a HTML document * @version 0.3.1 */ class HTMLQuery { protected $selfClosingTags = array( 'area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta', 'param' ); private $html; function __construct( $html = false ) { if( $html !== false ) $this->load( $html ); } /** * Load a HTML string */ public function load( $html ) { $this->html = $html; } /** * Returns elements from the HTML */ public function getElements( $element, $attribute_match = false, $value_match = false ) { if( in_array( $element, $this->selfClosingTags ) ) preg_match_all( "/<$element *(.*)*\/>/isU", $this->html, $matches ); else preg_match_all( "/<$element(.*)>(.*)<\/$element>/isU", $this->html, $matches ); if( $matches ) { #Create an array of matched elements with attributes and content foreach( $matches[0] as $key => $el ) { $current_el = array( 'name' => $element ); $attributes = $this->parseAttributes( $matches[1][$key] ); if( $attributes ) $current_el['attributes'] = $attributes; if( $matches[2][$key] ) $current_el['content'] = $matches[2][$key]; $elements[] = $current_el; } #Return only elements with a specific attribute and or value if specified if( $attribute_match != false && $elements ) { foreach( $elements as $el_key => $current_el ) { if( $current_el['attributes'] ) { foreach( $current_el['attributes'] as $att_name => $att_value ) { $keep = false; if( $att_name == $attribute_match ) { $keep = true; if( $value_match == false ) break; } if( $value_match && ( $att_value == $value_match ) ) { $keep = true; break; } elseif( $value_match && ( $att_value != $value_match ) ) $keep = false; } if( $keep == false ) unset( $elements[$el_key] ); } else unset( $elements[$el_key] ); } } } if( $elements ) return array_values( $elements ); else return array(); } /** * Return an associateive array of all the form inputs */ public function getFormValues() { $inputs = $this->getElements( 'input' ); $textareas = $this->getElements( 'textarea' ); $buttons = $this->getElements( 'button' ); $elements = array_merge( $inputs, $textareas, $buttons ); if( $elements ) { foreach( $elements as $current_el ) { $attribute_name = mb_strtolower( $current_el['attributes']['name'] ); if( in_array( $current_el['name'], array( 'input', 'button' ) ) ) { if( isset( $current_el['attributes']['name'] ) && isset( $current_el['attributes']['value'] ) ) $form_values[$attribute_name] = $current_el['attributes']['value']; } else { if( isset( $current_el['attributes']['name'] ) && isset( $current_el['content'] ) ) $form_values[$attribute_name] = $current_el['content']; } } } return $form_values; } /** * Parses attributes into an array */ private function parseAttributes( $str ) { $str = trim( rtrim( trim( $str ), '/' ) ); if( $str ) { preg_match_all( "/([^ =]+)\s*=\s*[\"'“”]{0,1}([^\"'“”]*)[\"'“”]{0,1}/i", $str, $matches ); if( $matches[1] ) { foreach( $matches[1] as $key => $att ) { $attribute_name = mb_strtolower( $att ); $attributes[$attribute_name] = $matches[2][$key]; } } } return $attributes; } } ?> Usage is: $c = new HTMLQuery(); $x = $c->getElements( 'tr' ); print_r( $x );
unknown
d18243
test
Here's a slight modification of your code that might help you. The main points: * *You can use getline() instead of fscanf(). fscanf() can be used to read line-by-line, but it needs an explicit check for the end of line condition. getline() does this automatically. *As kaylum pointed out, it's necessary to rewind() the file pointer back to the beginning of the file after counting the number of lines. #include <omp.h> #include <stdio.h> #include <stdlib.h> void countAnagrams(char* fileName); void main () { char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"}; countAnagrams(fileNames[0]); countAnagrams(fileNames[1]); countAnagrams(fileNames[2]); countAnagrams(fileNames[3]); } void countAnagrams(char* fileName) { int anagramCount = 0; int ch, lines = 0; //Count number of lines in file FILE *myfile = fopen(fileName, "r"); do { ch = fgetc(myfile); if (ch == '\n') lines++; } while (ch != EOF); rewind(myfile); char *contents[lines]; int i = 0; size_t len = 0; for(i = 0; i < lines; i++) { contents[i] = NULL; len = 0; getline(&contents[i], &len, myfile); } fclose(myfile); printf("%.12s\n",fileName); printf("number of lines: %d\n", lines); printf("first thing: %s\n", contents[0]); printf("last thing: %s\n", contents[lines-1]); } A: I think that the problem is char contents[lines] and then fscanf(myfile,"%s",contents[i]) and the printf-s after. contents[i] is char type, and you want to read an array of chars into one char. contents needs to be declared as char* contents[lines] to be able to read a char array into contents[i].
unknown
d18244
test
You sign with your private key. Signature is proof of origin, it proves that you were in possession of the private key therefore the data must be from you, and the data was not altered. You encrypt with the destination public key. This is to ensure that only the destination can decrypt it. As you see, the signature and encryption serve different purposes. A: Signing is putting your signature on a letter, and encrypting is putting the letter in an envelope. The envelope keeps other people from reading the letter. The signature proves that you wrote the letter. Additionally, you sign and then encrypt, in that order, because if you instead put the letter in the envelope first, and then sign the envelope, this doesn't really prove that you wrote letter. You could argue in front of a judge that you didn't get to see the letter before the envelope was sealed. Finally, you should not use the same key for both signing and encrypting. There are cryptographic reasons, but another, simpler reason is that the key that you use for encrypting can be held in escrow by other people (for example, the company you work for) to have access to the contents of all of your envelopes if needed, but the key you use for signing should only be given to people you would trust to legally sign in your place, as if a power of attorney.
unknown
d18245
test
This might be the complete solution as you are looking for. This code is from the udacity computer science course (CS101) It uses simulated webpages using method get_page(url): Run in your computer once and read the code It also try to remove duplicate urls def get_page(url): # This is a simulated get_page procedure so that you can test your # code on two pages "http://xkcd.com/353" and "http://xkcd.com/554". # A procedure which actually grabs a page from the web will be # introduced in unit 4. try: if url == "http://xkcd.com/353": return '<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Python</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s">\t<ul> <li><a href="http://xkcd.com/554"">Archive</a><br /></li>\t <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> <br />XKCD updates every Monday, Wednesday, and Friday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"><h1>Python</h1><br/><br /><div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/352/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/354/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul></div><br/><br/><img src="http://imgs.xkcd.com/comics/python.png" title="I wrote 20 short programs in Python yesterday. It was wonderful. Perl, Im leaving you." alt="Python" /><br/><br/><div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/352/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/354/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul></div><h3>Permanent link to this comic: http://xkcd.com/353/</h3><h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/python.png</h3><div id="transcript" style="display: none">[[ Guy 1 is talking to Guy 2, who is floating in the sky ]]Guy 1: You39;re flying! How?Guy 2: Python!Guy 2: I learned it last night! Everything is so simple!Guy 2: Hello world is just 39;print &quot;Hello, World!&quot; 39;Guy 1: I dunno... Dynamic typing? Whitespace?Guy 2: Come join us! Programming is fun again! It39;s a whole new world up here!Guy 1: But how are you flying?Guy 2: I just typed 39;import antigravity39;Guy 1: That39;s it?Guy 2: ...I also sampled everything in the medicine cabinet for comparison.Guy 2: But i think this is the python.{{ I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I39;m leaving you. }}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br />Search comic titles and transcripts:<br /><script type="text/javascript" src="//www.google.com/jsapi"></script><script type="text/javascript"> google.load(\"search\", \"1\"); google.setOnLoadCallback(function() { google.search.CustomSearchControl.attachAutoCompletion( \"012652707207066138651:zudjtuwe28q\", document.getElementById(\"q\"), \"cse-search-box\"); });</script><form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div></form><script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script><a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a><br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://www.boltcity.com/copper/">Copper</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://achewood.com/">Achewood</a>, <a href="http://wondermark.com/">Wondermark</a>, <a href="http://thisisindexed.com/">Indexed</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>.<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you\"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body></html> ' elif url == "http://xkcd.com/554": return '<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xkcd: Not Enough Work</title> <link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/c40a9f8.css" media="screen" title="Default" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="http://imgs.xkcd.com/s/ecbbecc.css" media="screen" title="Default" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/atom.xml" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/rss.xml" /> <link rel="icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> <link rel="shortcut icon" href="http://imgs.xkcd.com/s/919f273.ico" type="image/x-icon" /> </head> <body> <div id="container"> <div id="topContainer"> <div id="topLeft" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <ul> <li><a href="/archive/">Archive</a><br /></li> <li><a href="http://blag.xkcd.com/">News/Blag</a><br /></li> <li><a href="http://store.xkcd.com/">Store</a><br /></li> <li><a href="/about/">About</a><br /></li> <li><a href="http://forums.xkcd.com/">Forums</a><br /></li> </ul> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="topRight" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <div id="topRightContainer"> <div id="logo"> <a href="/"><img src="http://imgs.xkcd.com/s/9be30a7.png" alt="xkcd.com logo" height="83" width="185"/></a> <h2><br />A webcomic of romance,<br/> sarcasm, math, and language.</h2> <div class="clearleft"></div> XKCD updates every Monday, Wednesday, and Friday. <br /> Blag: Remember geohashing? <a href="http://blog.xkcd.com/2012/02/27/geohashing-2/">Something pretty cool</a> happened Sunday. </div> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> <div id="contentContainer"> <div id="middleContent" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <h1>Not Enough Work</h1><br/> <br /> <div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/553/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_t">Random</a></li> <li><a href="/555/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul> </div> <br/> <br/> <img src="http://imgs.xkcd.com/comics/not_enough_work.png" title="It39;s even harder if you39;re an asshole who pronounces &lt;&gt; brackets." alt="Not Enough Work" /><br/> <br/> <div class="menuCont"> <ul> <li><a href="/1/">|&lt;</a></li> <li><a href="/553/" accesskey="p">&lt; Prev</a></li> <li><a href="http://dynamic.xkcd.com/random/comic/" id="rnd_btn_b">Random</a></li> <li><a href="/555/" accesskey="n">Next &gt;</a></li> <li><a href="/">&gt;|</a></li> </ul> </div> <h3>Permanent link to this comic: http://xkcd.com/554/</h3> <h3>Image URL (for hotlinking/embedding): http://imgs.xkcd.com/comics/not_enough_work.png</h3> <div id="transcript" style="display: none">Narration: Signs your coders don39;t have enough work to do: [[A man sitting at his workstation; a female co-worker behind him]] Man: I39;m almost up to my old typing speed in dvorak [[Two men standing by a server rack]] Man 1: Our servers now support gopher. Man 1: Just in case. [[A woman standing near her workstation speaking to a male co-worker]] Woman: Our pages are now HTML, XHTML-STRICT, and haiku-compliant Man: Haiku? Woman: &lt;div class=&quot;main&quot;&gt; Woman: &lt;span id=&quot;marquee&quot;&gt; Woman: Blog!&lt; span&gt;&lt; div&gt; [[A woman sitting at her workstation]] Woman: Hey! Have you guys seen this webcomic? {{title text: It39;s even harder if you39;re an asshole who pronounces &lt;&gt; brackets.}}</div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> <div id="middleFooter" class="dialog"> <div class="hd"><div class="c"></div></div> <div class="bd"> <div class="c"> <div class="s"> <img src="http://imgs.xkcd.com/s/a899e84.jpg" width="520" height="100" alt="Selected Comics" usemap=" comicmap" /> <map name="comicmap"> <area shape="rect" coords="0,0,100,100" href="/150/" alt="Grownups" /> <area shape="rect" coords="104,0,204,100" href="/730/" alt="Circuit Diagram" /> <area shape="rect" coords="208,0,308,100" href="/162/" alt="Angular Momentum" /> <area shape="rect" coords="312,0,412,100" href="/688/" alt="Self-Description" /> <area shape="rect" coords="416,0,520,100" href="/556/" alt="Alternative Energy Revolution" /> </map><br/><br /> Search comic titles and transcripts:<br /> <script type="text/javascript" src="//www.google.com/jsapi"></script> <script type="text/javascript"> google.load("search", "1"); google.search.CustomSearchControl.attachAutoCompletion( "012652707207066138651:zudjtuwe28q", document.getElementById("q"), "cse-search-box"); }); </script> <form action="//www.google.com/cse" id="cse-search-box"> <div> <input type="hidden" name="cx" value="012652707207066138651:zudjtuwe28q" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="31" /> <input type="submit" name="sa" value="Search" /> </div> </form> <script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script> <a href="/rss.xml">RSS Feed</a> - <a href="/atom.xml">Atom Feed</a> <br /> <br/> <div id="comicLinks"> Comics I enjoy:<br/> <a href="http://threewordphrase.com/">Three Word Phrase</a>, <a href="http://oglaf.com/">Oglaf</a> (nsfw), <a href="http://www.smbc-comics.com/">SMBC</a>, <a href="http://www.qwantz.com">Dinosaur Comics</a>, <a href="http://www.asofterworld.com">A Softer World</a>, <a href="http://buttersafe.com/">Buttersafe</a>, <a href="http://pbfcomics.com/">Perry Bible Fellowship</a>, <a href="http://questionablecontent.net/">Questionable Content</a>, <a href="http://www.buttercupfestival.com/buttercupfestival.htm">Buttercup Festival</a> </div> <br/> Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors).<br/> <br/> <h4>We did not invent the algorithm. The algorithm consistently finds Jesus. The algorithm killed Jeeves. <br />The algorithm is banned in China. The algorithm is from Jersey. The algorithm constantly finds Jesus.<br />This is not the algorithm. This is close.</h4><br/> <div class="line"></div> <br/> <div id="licenseText"> <!-- <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/"><img alt="Creative Commons License" style="border:none" src="http://imgs.xkcd.com/static/somerights20.png" /></a><br/> --> This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>. <!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns "><Work rdf:about=""><dc:creator>Randall Munroe</dc:creator><dcterms:rightsHolder>Randall Munroe</dcterms:rightsHolder><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:source rdf:resource="http://www.xkcd.com/"/><license rdf:resource="http://creativecommons.org/licenses/by-nc/2.5/" /></Work><License rdf:about="http://creativecommons.org/licenses/by-nc/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction" /><permits rdf:resource="http://web.resource.org/cc/Distribution" /><requires rdf:resource="http://web.resource.org/cc/Notice" /><requires rdf:resource="http://web.resource.org/cc/Attribution" /><prohibits rdf:resource="http://web.resource.org/cc/CommercialUse" /><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" /></License></rdf:RDF> --> <br/> This means you"re free to copy and share these comics (but not to sell them). <a href="/license.html">More details</a>.<br/> </div> </div> </div> </div> <div class="ft"><div class="c"></div></div> </div> </div> </div> </body> </html> ' except: return "" return "" def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None, 0 start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote def union(p,q): for e in q: if e not in p: p.append(e) def get_all_links(page): links = [] while True: url,endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links def crawl_web(seed): tocrawl = [seed] crawled = [] while tocrawl: page = tocrawl.pop() if page not in crawled: union(tocrawl, get_all_links(get_page(page))) crawled.append(page) return crawled print crawl_web('http://xkcd.com/353') A: Do you want to extract urls from a html file? Then this is what you need: http://youtu.be/MagGZY7wHfU?t=1m54s Its a great course by the way. Maybe you are interested. A: To parse html file you should use XML parsing library. See: https://docs.python.org/2/library/xml.html
unknown
d18246
test
Apperently, there's always nuances that you miss sometimes and browsers keep extensive data of the pages you browser. I've just cleared all of my browsers caches and now everything works perfectly!.. So if you encounter something similar, be sure to clear your browser cache.
unknown
d18247
test
The problem is that u are using a version of the engines that don't use generics but using generics in the handler Try with this: var engine = new FileHelperEngine<MyClass>(); engine.Options.IgnoreFirstLines = 1; engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue; engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
unknown
d18248
test
The PrimaryKeyConstraint object you're using as constraint= argument is not bound to any table and would seem to produce nothing when rendered, as seen in ON CONFLICT (). Instead pass the primary key(s) of your table as the conflict_target and Postgresql will perform unique index inference: upsert_statement = insert_statement.on_conflict_do_update( constraint=idTagTable.primary_key, set_={"updatedon": insert_statement.excluded.updateon, "category":insert_statement.excluded.category} )
unknown
d18249
test
Try File.seek and File.rawRead. They work like their C counterparts, but rawRead determines the read count from the size of the output buffer you hand it.
unknown
d18250
test
I think the real problem is that you are confused about number representations and text renderings of numbers. Here are some key facts that you need to understand: * *The byte type is the set of integral values from -128 to +127. *All integral types use the same representation (2's complement). The difference between the different types is their ranges. *When you "see" a number, what you are seeing is a rendering of the number into a sequence of characters. There are MANY possible renderings; e.g. the number represented in memory as 00101010 (42) can be rendered as "42" or "+42" or "0x2a" or ... "forty two". *The default format for rendering a byte, short, int and long is the same; i.e. an optional minus sign followed by 1 or more decimal digits (with no zero padding). If you want to see your numbers formatted differently, then you need to do the formatting explicitly; e.g. using String.format(...). So to pull this together, if you want the bytes to look like 0x00 and 0x01 when you output or display them, you need to format them appropriately as you output / display them. In your example code, I doubt that there is anything wrong with the numbers themselves, or with the loop you are using to populate the array. A: You are confusing the string representation of the value with the value itself. A value can be represented as binary, decimal, or hex, but it is still the same value. If you want to use your integer to initialise a byte array, you just need to cast your integer value to a byte value as follows: arr[i] = (byte) i; A: new byte[]{0x00} is actually equivalent to new byte[]{0} The 0x00 notation is just an alternative way to write integer constants, and if the integer constant is in the range -128 to 127, then it can be used as a byte. If you have an existing integer variable that you want to use, and its value is in the range -128 to 127, then you just have to cast it: int i = 1; new byte[]{(byte)i}; A: You want new byte[]{(byte)i} How you print this array is another matter. Look up printf in the API reference. A: I would just like to note that 0 is NOT the same thing as 0x00. If i were to use: ColorChooserOutputText.append(Integer.toHexString(list[i].getRed())); ColorChooserOutputText.append(Integer.toHexString(list[i].getGreen())); ColorChooserOutputText.append(Integer.toHexString(list[i].getBlue())); and wanted to return the color, Purple it would return: ff0cc Which would be fine if I were just using Java. But if you are going between Java and something that had format specific needs ff0cc would not produce purple.. ff00cc is actually purple. //Declare some variables. Color HexColor = JButton1.getBackground(); String MyRValue = null; String MyGValue = null; String MyBValue = null; //Get Hex Value MyRValue = Integer.toHexString(HexColor.getRed()); MyGValue = Integer.toHexString(HexColor.getGreen()); MyBValue = Integer.toHexString(HexColor.getBlue()); //Make sure to keep both 0's MyRValue = ("00"+MyRValue).substring(MyRValue.length()); MyGValue = ("00"+MyGValue).substring(MyGValue.length()); MyBValue = ("00"+MyBValue).substring(MyBValue.length()); //Format your HexColor to #00ff00, #000000, #ff00ee JTextArea1.append("#"); JTextArea1.append(MyRValue+MyGValue+MyBValue); JTextArea1.append(", "); A: String.Format ("%02x") is your friend :) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html http://www.xinotes.org/notes/note/1195/
unknown
d18251
test
bower will download the entire package using Git. Your package must be publically available at a Git endpoint (e.g., GitHub). Remember to push your Git tags! This means that bower will actually download the entire repository/release for you to use in your ASP project. I've tested this with bootstrap and jQuery. These repositories can contain many many files so including them into the .csproj file will clutter your project file and may not be ideal. This can be compared to using nuget packages where we are only referencing external packages in the packages.config file but we do not include the dll and other assemblies into the project. This leads me to think that bower_components should indeed not be included in the project; this makes no difference to usage as you can still reference the packages and use the files.
unknown
d18252
test
Well you can 3 options: * *Create a layout with UIIImageViews and UITextView *Use HTML and UIWebView *NSAttributedString and draw it on a view with CoreText A: That's almost certainly laid out in an UIWebView, with the styling on the image set to "float: left" with margin settings that hold the text off from the edge of it but let it wrap around it. Here's a little tutorial about it: http://www.tizag.com/cssT/float.php Note that this is about the HTML and CSS content to feed the UIWebView, not anything iOS-ish. A: You arrange UIImageViews and UITextViews in the way you want them by setting their frames. Then assign images to the imageViews and text to the textViews.
unknown
d18253
test
css cant affect anything before it, it can only affect stuff after the targeted element change like below #menu-open + #logo { color: #ccc; font-style: italic; } #menu-open:checked + #logo { color: #f00; font-style: normal; } <input type="checkbox" id="menu-open"> <div id="logo" class="logoib"> my logo here </div> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> A: You could use pure JS, JQuery or CSS. Here is a pure JS solution. If you want to set it also on load, you could call myFunction when the DOM is ready. function myFunction() { var cb = document.getElementById('menu-open'); var logo = document.getElementById('logo'); if (cb.checked) { logo.setAttribute("class", "newClass"); } else { logo.removeAttribute("class"); } } #menu-open:checked~.logoib { -webkit-filter: invert(100%); filter: invert(100%); } .newClass { color: red; } <div id="logo" class="logoib">Logo </div> <input type="checkbox" id="menu-open" onchange="myFunction()"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label>
unknown
d18254
test
Just for testing i have replicated, and it works fine as expected A: Actually you can't do that by overlaying the dialog, you'll need to rely in DAM Metadata Schemas to achieve that - https://experienceleague.adobe.com/docs/experience-manager-64/assets/administer/metadata-schemas.html?lang=en From there, and if you want to persist these definitions in your code baseline, you can refer to the location where it gets stored - /conf/global/settings/dam/adminui-extension/metadataschema Hope it helps
unknown
d18255
test
InstanceProfileCredentialsProvider retrieves credentials as needed; a client using it should never see a credentials timeout exception. This implies that either (1) you are explicitly setting instance profile credentials on the client that is timing out, or (2) there is something else in the provider chain that is providing limited-time credentials. Or, I suppose, you might be using an extremely old version of the SDK. I don't know at what point they added automatic refresh; according to git blame, the fetcher variable was last changed 13 months ago. But I've been using instance credentials with long-running processes for much longer than that. A: This article may help you. If you really need to get a new credentials, the following example shows pseudocode for how to use temporary security credentials if you're using an AWS SDK: assumeRoleResult = AssumeRole(role-arn); tempCredentials = new SessionAWSCredentials( assumeRoleResult.AccessKeyId, assumeRoleResult.SecretAccessKey, assumeRoleResult.SessionToken); s3Request = CreateAmazonS3Client(tempCredentials); Read further info about temporary credentials in this docs.
unknown
d18256
test
This should work (you'll need to add the error handling back in): lines = enumerate(open('orders.txt')) for i, line in lines: print i, line i = int(input(">")) open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))
unknown
d18257
test
A=A20)*(E:E=*"N/A"*)) VBA: "=SUMPRODUCT((C[-5]=RC[-5])*(C[-1]=""N/A""))" (It actually shows the text "N/A" - it's not returning an error) Column G - Lookup Dollar Amount from Column P: =LOOKUP(A20,O:O,P:P) VBA: "=LOOKUP(RC[-6],C[8],C[9])" Column K - Determine if Column E begins with a 5: =IF(LEFT(C20,1)="5","Yes","No") VBA: "=IF(LEFT(RC[-8],1)=""5"",""Yes"",""No"")" Column M - (Count occurances in column A) * (Count Column F > 1) * (Dollar amount in D > 0)): =SUMPRODUCT((A:A=A20)*(F:F>1)*(D:D>0)) VBA: "=SUMPRODUCT((C[-12]=RC[-12])*(C[-7]>1)*(C[-9]>0))" Column N - Assigns color value for each conditional and applies to Column N: =IF(AND((F20>1),(M20=1),(G20>0)),"Yellow",IF(AND((F20>1),(M20=1),(G20=0)),"Red",IF(AND((F20>1),(M20>1),(G20>0)),"Blue",IF(AND((K20="Yes"),(G20>0)),"Blue",IF(AND((K20="No"),(G20>0)),"Red",IF(G20<0,"Orange",IF(G20=0,"Red","Next"))))))) VBA: "=IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]>0)),""Yellow""," & _ "IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]=0)),""Red""," & _ "IF(AND((RC[-8]>1),(RC[-1]>1),(RC[-7]>0)),""Blue""," & _ "IF(AND((RC[-3]=""Yes""),(RC[-7]>0)),""Blue""," & _ "IF(AND((RC[-3]=""No""),(RC[-7]>0)),""Red""," & _ "IF(RC[-7]<0,""Orange""," & _ "IF(RC[-7]=0,""Red"",""Next"")))))))" Then for applying highlighting, I have: Columns("A:E").Select Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=ISNUMBER(SEARCH(""Blue"",$N1))=TRUE" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .Color = 15773696 End With I know there's a way to string it all together... I'm just not sure how. There don't even have to be multiple columns... That's just how I knew how to get it to work. A: You're on the right track with your VBA, but you're trying to use formula syntax in VBA code, and that's not going to work. Change this: "=IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]>0)),""Yellow""," & _ "IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]=0)),""Red""," & _ "IF(AND((RC[-8]>1),(RC[-1]>1),(RC[-7]>0)),""Blue""," & _ "IF(AND((RC[-3]=""Yes""),(RC[-7]>0)),""Blue""," & _ "IF(AND((RC[-3]=""No""),(RC[-7]>0)),""Red""," & _ "IF(RC[-7]<0,""Orange""," & _ "IF(RC[-7]=0,""Red"",""Next"")))))))" To this: Dim cel as range offset(row,col) set cel = ActiveCell if cel.offset(0,-8) > 1 and cel.offset(0,-1) = 1 and cel.offset(0,-7) > 0 then cel.interior.color = vbYellow elseif cel.offset(0,-8) > 1 and cel.offset(0,-1) = 1 and cel.offset(0,-7) = 0 then cel.interior.color = vbRed elseif cel.offset(0,-8) > 1 and cel.offset(0,-1) > 1 and cel.offset(0,-7) > 0 then cel.interior.color = vbBlue elseif ucase(cel.offset(0,-3)) = "YES" and cel.offset(0,-7) > 0 then cel.interior.color = vbBlue elseif ucase(cel.offset(0,-3)) = "NO" and cel.offset(0,-7) > 0 then cel.interior.color = vbRed elseif cel.offset(0,-7) < 0 then cel.interior.color = vbOrange elseif cel.offset(0,-7) = 0 then cel.interior.color = vb.Red End If Note: * *vbOrange may not be a predefined color. You may have to specify the RGB you want to get there. This was done to get you going. *set cel = ActiveCell is most likely not what you really want, but you didn't specify any code around it, so you'll have to figure out how to assign this properly yourself. *Using this code, I think you should be able to eliminate the use of multiple columns now that you have the proper syntax for VBA instead of a formula.
unknown
d18258
test
QProcess is derived from QIODevice, so I would say calling close() should close the file handle and solve you problem. A: I cannot see the issue, however one thing that concerns me is a possible invocation overlap in getMemoryUsage() where it's invoked before the previous run has finished. How about restructuring this so that a new QProcess object is used within getMemoryUsage() (on the stack, not new'd), rather than being an instance variable of the top-level class? This would ensure clean-up (with the QProcess object going out-of-scope) and would avoid any possible invocation overlap. Alternatively, rather than invoking /usr/bin/free as a process and parsing its output, why not read /proc/meminfo directly yourself? This will be much more efficient. A: First I had the same situation with you. I got the same results. I think that QProcess can not handle opened pipes correctly. Then, instead of QProcess, I have decided to use popen() + QFile(). class UsageStatistics : public QObject { Q_OBJECT public: UsageStatistics(){ timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(getMemoryUsage())); timer->start(1000); // one second } virtual ~UsageStatistics() {} private: QFile freePipe; FILE *in; public slots: void getMemoryUsage() { if(!(in = popen("/usr/bin/free", "r"))){ qDebug() << "UsageStatistics::getMemoryUsage() <<" << "Can not execute free command."; return; } freePipe.open(in, QIODevice::ReadOnly); connect(&freePipe, SIGNAL(readyRead()), this, SLOT(parseResult()) ); // OR waitForReadyRead() and parse here. } void parseResult(){ // Parse your stuff freePipe.close(); pclose(in); // You can also use exit code by diving by 256. } } A: tl;dr: This occurs because your application wants to use more resources than allowed by the system-wide resource limitations. You might be able to solve it by using the command specified in [2] if you have a huge application, but it is probably caused by a programming error. Long: I just solved a similar problem myself. I use a QThread for the logging of exit codes of QProcesses. The QThread uses curl to connect to a FTP server uploads the log. Since I am testing the software I didn't connect the FTP server and curl_easy_perform apparently waits for a connection. As such, my resource limit was reached and I got this error. After a while my program starts complaining, which was the main indicator to figure out what was going wrong. [..] QProcessPrivate::createPipe: Cannot create pipe 0x7fbda8002f28: Too many open files QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb0003128: Too many open files QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb4003128: Too many open files QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb4003128: Too many open files [...] curl_easy_perform() failed for curl_easy_perform() failed for disk.log [...] I've tested this by connecting the machine to the FTP server after this error transpired. That solved my problem. Read: [1] https://linux.die.net/man/3/ulimit [2] https://ss64.com/bash/ulimit.html [3] https://bbs.archlinux.org/viewtopic.php?id=234915
unknown
d18259
test
Just add .Where(i => i.Extension.Equals(".finfo", StringComparison.InvariantCultureIgnoreCase)) to the enumerable. Or better, use the other overload of EnumerateFiles: foreach (FileInfo filemove in finfo.Directory.EnumerateFiles("*.finfo")) { Also, note that MoveTo only works on the same logical drive. If that's not enough for you, you will need to add your own copy+delete method for moving files accross drives.
unknown
d18260
test
I don't think this will work in Javascript since objects are written like JSON and thus properties will be undefined or null but not throw an error. The solution will be writing a native getter/setter. var obj = { vars: {}, set: function(index, value) { obj.vars[index] = value; }, get: function(index) { if (typeof(vars[index]) == "undefined") { throw "Undefined property " + index; } return vars[index]; } }; A: There is no reliable getter/setters in javascript right now. You have to check it manually. Here's a way to do that: if (!('key' in object)) { // throw exception }
unknown
d18261
test
If you want it to fire after a click: $(".element").click(function(){ $("link[rel='stylesheet']").remove(); }); or at the beginning: $(document).ready(function(){ $("link[rel='stylesheet']").remove(); }); A: Try this: $('link[rel="stylesheet"]').remove(); This will remove all stylesheets (all the styles applies due to those stylesheets) from the page. A: Just spent few mintues to draft one (function(f,a,s,x){ x=$(a);x.map(function(i,o){o=$(o);o.data(s+s,o.attr(s));o.removeAttr(s)}); $(s+',link[rel='+s+'sheet]').appendTo(f); setTimeout(function(){ $(a,f).appendTo('head'); x.map(function(i,o){o=$(o);o.attr(s,o.data(s+s))}) },999); })($('<i>'),'*','style'); A: Disable all StyleSheetList.prototype.forEach=Array.prototype.forEach; // *Note document.styleSheets.forEach((ss)=>ss.disabled=true); or (Disable All) for(styleSheet of document.styleSheets){ styleSheet.disabled=true; } or (Remove all) StyleSheetList.prototype.forEach=Array.prototype.forEach; document.styleSheets.forEach((ss)=>ss.ownerNode.parentNode.removeChild(ss.ownerNode)); or (Remove all) for(styleSheet of document.styleSheets){ styleSheet.ownerNode.parentNode.removeChild(styleSheet.ownerNode); } *Note: If you don't want to change the prototype, you can invoke it like this: Array.prototype.forEach.apply(document.styleSheets,[(ss)=>ss.disabled=true]) A: Try this $('link[rel="stylesheet"]').remove(); A: Place this on document ready: $('link[rel=stylesheet]').remove(); Or bind it to a button. A: A rough, dirty and brute approach: document.querySelector("head").remove(); A bookmarklet version of the same code that you can paste as the URL of a bookmark. You can also paste it into the address bar (for security reasons, when you paste the text, chrome/firefox remove the javascript: bit at the beginning so you'll need to type that by hand): javascript:(function(){document.querySelector("head").remove();})() A: Use below code to remove all kinds of styles, inline, internal, external. let elements=document.querySelectorAll("*"); elements.forEach(el=>{ if(el.tagName==="LINK" || el.tagName==="STYLE") el.remove(); else el.removeAttribute("style"); }); Thank me later! ;)
unknown
d18262
test
Use Choose or IIF function Select Choose([p3]+1 , '' ,'p3') From yourtable Select IIF([p3]=0 , '' ,'p3') From yourtable for older versions use CASE statement Select Case when [p3] = 0 then '' else 'p3' End From yourtable A: select case when p3 = 1 then 'p3' else '' end from yourTable
unknown
d18263
test
Can a stack allocated buffer be accessed through C++? Yes. From the type-system perspective there is no difference between statically allocated, stack allocated, or heap allocated: the C signature only takes pointer and size, and cares little where that pointer points to. Is this safe? Most likely. As long as the C function is correctly written and respects the bounds of the buffer, this will be safe. If it doesn't, well, that's a bug. One could argue that it's better to have a heap-allocated buffer, but honestly once one starts writing out of bounds, overwriting arbitrary stack bytes or overwriting arbitrary heap bytes are both bad, and have undefined behavior. For extra security, you could use a heap allocated nested between 2 guard pages. Using OS specific facilities, you could allocate 3 contiguous OS pages (typically 4KB each on x86), then mark the first and last as read-only and put your buffer in the middle one. Then any (close) write before or after the buffer would be caught by the OS. Larger jumps, though, wouldn't... so it's a lot of effort for a mitigation. Is your code safe? You most likely need to know how many bytes were written, so using a null pointer is strange. I'd expect to see: let mut written: size_t = 0; let written_size = &mut written as *mut _; And yes, that's once again a pointer to a stack variable, just like you would in C. A note on style. Your Rust code is unusual in that you use fully typed variables and full paths, a more idiomatic style would be: // Result is implicitly in scope. pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> Result<(), &str) { let mut buffer = [0u8; MAX_BYTES_TRANSPORT]; let mut written: size_t = 0; let written_size = &mut written as *mut _; // Safety: // <enumerate preconditions to safely call the function here, and why they are met> let result = unsafe { openvpn_client_receive_just( buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client) }; translate_openvpn_error(result)?; let buffer = &buffer[0..written]; f(buffer); Ok(()) } I did annotate the type for written, to help along inference, but strictly speaking it should not be necessary. Also, I like to preface every unsafe call I make with the list of pre-conditions that make it safe, and for each why they are met. It helps me audit my unsafe code later on.
unknown
d18264
test
Create a javascript file deleteUni.js (or whatever you want to call it) and add this to your template script(src="/Scripts/deleteUni.js") //content of name.js $(function(){ var isButtonDisabled = false; $('#buttonId').click(function($event){ //this part handles multiple button clicks by the user, trust me on this one, it's really important to have it if (isButtonDisabled){ return $event.preventDefault(); } isButtonDisabled = true; var formData = $('#formId').serialize(); //serialize form to a variable $.post( "/overview/delete-uni",formData) .success(function(response){ //handle response }) .fail(function(error){ //handle error }) .always(function(){ //always execute . . . isButtonDisabled = false; }); return $event.preventDefault(); }) });
unknown
d18265
test
Your code needs to run in a new thread. Look into the System.Threading namespace for instructions and examples of how to create a new thread. Essentially, you create the thread Here is an example from one of my old test programs. Thread thdOneOfTwo = new Thread(new ParameterizedThreadStart(TextLogsWorkout.DoThreadTask)); In the above example, TextLogsWorkout.DoThreadTask is a static method on class TextLogsWorkout, which happens also to contain the above statement. You have the option of giving each thread a name, and of using a WaitHandle that it can signal when it has completed its assignment. Both are optional, but you must execute the Start method on the instance. Be aware that you are entering the world of multi-threaded programming, where many hazards await the unwary. If you aren't already, I suggest you read up on mutexes, wait handles, and the intrinsic lock () block. Of the three, lock() is the simplest way that a single application can synchronize access to a property. Of the other two, WaitHandles and Mutexes are about equal in complexity. However, while a WaitHandle can synchronize activities within a process, a Mutex is a filesystem object, and, as such, can synchronize activities between multiple processes. In that regard, be aware that if a mutex has a name, as it must if it is to synchronize more than one process, that name must begin with "\?\GLOBALROOT", unless all of them run in the same session. Failure to do this bit me really hard a few years ago.
unknown
d18266
test
Full disclosure: I love the googleVis package. I see the same behavior you do, even after updating to the latest version of googleVis (not yet on CRAN). I don't know if this is a bug or not; the googleVis documentation for gvisLineChart mentions continuous data, but nothing I tried allows me to plot the X axis as numerical. You can get clues as to what's happening when you change aspects of your code in generating googleVis charts and graphs if you right-click on the web page that gets displayed with the plot, and choose "View Page Source." This page is where the magic happens, and is the HTML output from the googleVis package. The problematic line in this case is the one that reads "data.addColumn('string','val1'); In this line, the word 'string' should be 'number', and the val1 values should not be in quotes in the data section. You can get the results you want, though, by using gvisScatterChart instead: library(googleVis) df=data.frame(val1=c(10,13,100), val2=c(23,12,32)) Line <- gvisScatterChart(df, options=list(lineWidth=2, pointSize=0)) plot(Line)
unknown
d18267
test
if (document.getElementById('name').value != "" && document.getElementById('company').value != "" && document.getElementById('email').value != ""){ document.getElementById('hiddenpdf').style.display = 'block'; }else{ document.getElementById('hiddenpdf').style.display = 'none'; } Hope this helps. You have a syntax error in your code. Above solution checks with "and" logic and will only execute 'block' statement if all three conditions are met otherwise it will move over to else statement.
unknown
d18268
test
On the rails db MySql console, I used: SHOW CREATE TABLE dogs; To find out that the charset for the table was latin1. I just added a migration with this query: ALTER TABLE dogs CONVERT TO CHARACTER SET utf8mb4; And it started to work fine.
unknown
d18269
test
Avahi does not currently support sleep proxy, as either a client or server. So this will not work. Currently you require some Apple device for a sleep proxy such as Airport, Time Capsule, Apple TV, etc. I hope to add support for Sleep Proxy into Avahi
unknown
d18270
test
First, don't use :units as the association name, it "has one unit" no "units", Rails convention over configuration expects the association to be singular. Then you should be able to do some_emp.unit.name. Or you can use method delegation: class Emp < ApplicationRecord has_one :unit delegate :name, to: :unit end And now you can do some_emp.name.
unknown
d18271
test
this issue arise with mysql database setup. please follow below listed link to sorted out that issue.. https://docs.wso2.org/display/EMM100/General+Server+Configurations there are few mistakes on documentation. On step 6, type exit; and Step 9. add given config values within <datasources> </datasources> A: Please check using MySQL console whether the admin has permission to access EMM_DB. Meanwhile you can try WSO2 EMM 1.1.0 http://wso2.com/products/enterprise-mobility-manager/
unknown
d18272
test
I finally found out what was wrong! The answer is so retarded that I didn't belive it would work but it did. Simply add this at the page beginning (before <html> tag): <!DOCTYPE html> Yep, Internet Explorer... Otherwise the :hover works only on <a> and <button> tags. A: Not sure if this answers your question but the code below works for me (IE10, Win7 on Virtual Machine) Another option is to use Javascript. <html> <head> <style> .block-active { background-color: #0f0; margin: 0px 0px 0.5% 0.5%; height: 50px; opacity:0.5; width: auto; padding: 1.7% 1.8% 1.7% 1.8%; transition:opacity 0.5s; position:relative; } .block-active:hover { opacity:1; } </style> </head> <body> <div class="block-active"></div> </body> </htm>
unknown
d18273
test
The way I'm handling this is to first use the Web Essentials 2017 extension. This installs the Bundler & Minifier tool, which then adds a bundleconfig.json file to your project. Right-click on this file, go to the Bundler & Minifier menu item and you will see an option in there to Convert To Gulp. Selecting convert to gulp will create the necessary gulpfile.js and also install the npm packages required for using Gulp. Wait for all of the npm packages to install and you can then right click on gulpfile.js, select Task Runner Explorer and you should be ready to set up Gulp-based tasks. If you see gulpfile.js failed to load message, npm packages may still be installing (check the progress bar on the VS 2017 status bar). Hit the Refresh icon in Task Runner Explorer when all packages are installed and the error should vanish. There's probably a more manual way to add Gulp support but I find this more automated method ensures all the tooling is wired up to work properly and I don't miss anything. I gleaned all this information from the awesome Microsoft Docs site, specifically this page on Bundling & Minification. There's also a Using Gulp section in there that may provide additional details for your situation. https://learn.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification A: Microsoft have now added documentation on how to get gulp running: https://learn.microsoft.com/en-us/aspnet/core/client-side/using-gulp Make sure you update Visual Studio 2017 to the latest version as it now comes shipped with Node.js, NPM and Gulp (you don't need to pick "Node.js support" when installing Visual Studio for this to work). Create an npm Configuration File (package.json) in your project folder and edit it to reference gulp: { "version": "1.0.0", "name": "example", "private": true, "devDependencies": { "gulp": "3.9.1" }, "scripts": { "gulp": "gulp" } } In the project folder, create a Gulp Configuration File (gulpfile.js) to define the automated process. Add the following to the post-build event command line for each project requiring gulp support: cd $(ProjectDir) call dotnet restore npm run gulp To run the tasks in Visual Studio 2017, open the Task Runner Explorer (View > Other Windows > Task Runner Explorer). Then on the build server just install Node.js and ensure the path to node is added to the environmental path variable then when the build server builds the project gulp will run too! A: I found the solution here. More information on that part of VS from Mads himself. You have to force Visual Studio run with your Node.js version: Go to Tools > Options in Visual Studio 2017 Go to Projects and Solutions > External Web Tools Add the following path: C:\Program Files\nodejs
unknown
d18274
test
If you add a --pidfile arg to the start command sudo /finance/finance-env/bin/uwsgi --ini-paste-logged /finance/corefinance/production.ini --pidfile=/tmp/finance.pid You can stop it with the following command sudo /finance/finance-env/bin/uwsgi --stop /tmp/finance.pid Also you can restart it with the following command sudo /finance/finance-env/bin/uwsgi --reload /tmp/finance.pid A: You can kill uwsgi process using standard Linux commands: killall uwsgi or # ps ax|grep uwsgi 12345 # kill -s QUIT 12345 The latter command allows you to do a graceful reload or immediately kill the whole stack depending on the signal you send. The method you're using, however, is not normally used in production: normally you tell the OS to start your app on startup and to restart it if it crashes. Otherwise you're guaranteed a surprise one day at a least convenient time :) Uwsgi docs have examples of start scripts/jobs for Upstart/Systemd. Also make sure you don't really run uwsgi as root - that sudo in the command makes me cringe, but I hope you have uid/gid options in your production.ini so Uwsgi changes the effective user on startup. Running a webserver as root is never a good idea.
unknown
d18275
test
>>> import json >>> data = ''' { ... "items":[ ... { ... "item":0 ... }, ... { ... "item":1 ... }, ... { ... "item":2 ... }, ... { ... "item":3 ... } ... ] ... }''' >>> print(json.dumps({a:[{b:1+c[b]for b in c}for c in d]for a,d in json.loads(data).items()},indent=4)) { "items": [ { "item": 1 }, { "item": 2 }, { "item": 3 }, { "item": 4 } ] }
unknown
d18276
test
More Slightly modified for those who do not like VBA to have to make up explicit variables and then waste time transfer data to them.. Let With. do the job Function LoadFileStr$(FN$) With CreateObject("Scripting.FileSystemObject") LoadFileStr = .OpenTextFile(FN, 1).readall End With End Function A: brettdj's answer, slightly adjusted Public Function readFileContents(ByVal fullFilename As String) As String Dim objFSO As Object Dim objTF As Object Dim strIn As String Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile(fullFilename, 1) strIn = objTF.readall objTF.Close readFileContents = strIn End Function A: To read line by line: Public Sub loadFromFile(fullFilename As String) Dim FileNum As Integer Dim DataLine As String FileNum = FreeFile() Open fullFilename For Input As #FileNum While Not EOF(FileNum) Line Input #FileNum, DataLine Debug.Print DataLine Wend End Sub A: Rather than loop cell by cell, you can read the entire file into a variant array, then dump it in a single shot. Change the path from C:\temp\test.txt to suit. Sub Qantas_Delay() Dim objFSO As Object Dim objTF As Object Dim strIn 'As String Dim X Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile("C:\temp\test.txt", 1) strIn = objTF.readall X = Split(strIn, vbNewLine) [h12].Resize(UBound(X) + 1, 1) = Application.Transpose(X) objTF.Close End Sub A: The following code will loop through each line in the text document and print these from range H12 and downward in the UI-sheet. Sub ImportFromText() Open "C:\tester.txt" For Input As #1 r = 0 Do Until EOF(1) Line Input #1, Data Worksheets("UI").Range("H12").Offset(r, 0) = Data r = r + 1 Loop Close #1 End Sub A: Sub LoadFile() ' load entire file to string ' from Siddharth Rout ' http://stackoverflow.com/questions/20128115/ Dim MyData As String Open "C:\MyFile" For Binary As #1 MyData = Space$(LOF(1)) ' sets buffer to Length Of File Get #1, , MyData ' fits exactly Close #1 End Sub A: I think an easier alternative is Data > From Text and you can specify how often the data is refreshed in the Properties. A: Fidel's answer, over Brettdj's answer, adjusted for ASCII or Unicode and without magical numbers: Public Function readFileContents(ByVal fullFilename As String, ByVal asASCII As Boolean) As String Dim objFSO As Object Dim objTF As Object Dim strIn As String Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile(fullFilename, IOMode:=ForReading, format:=IIf(asASCII, TristateFalse, TristateTrue)) strIn = objTF.ReadAll objTF.Close readFileContents = strIn End Function
unknown
d18277
test
You can use the error style class to mark the entry as having error. The following is a minimal example that checks if an entry has a valid hex digit and updates the entry style: /* main.c * * Compile: cc -ggdb main.c -o main $(pkg-config --cflags --libs gtk+-3.0) -o main * Run: ./main * * Author: Mohammed Sadiq <www.sadiqpk.org> * * SPDX-License-Identifier: LGPL-2.1-or-later OR CC0-1.0 */ #include <gtk/gtk.h> static void entry_changed_cb (GtkEntry *entry) { GtkStyleContext *style; const char *text; gboolean empty; g_assert (GTK_IS_ENTRY (entry)); style = gtk_widget_get_style_context (GTK_WIDGET (entry)); text = gtk_entry_get_text (entry); empty = !*text; /* Loop until we reach an invalid hex digit or the end of the string */ while (g_ascii_isxdigit (*text)) text++; if (empty || *text) gtk_style_context_add_class (style, "error"); else gtk_style_context_remove_class (style, "error"); } static void app_activated_cb (GtkApplication *app) { GtkWindow *window; GtkWidget *entry; window = GTK_WINDOW (gtk_application_window_new (app)); entry = gtk_entry_new (); gtk_widget_set_halign (entry, GTK_ALIGN_CENTER); gtk_widget_set_valign (entry, GTK_ALIGN_CENTER); gtk_widget_show (entry); gtk_container_add (GTK_CONTAINER (window), entry); g_signal_connect_object (entry, "changed", G_CALLBACK (entry_changed_cb), app, G_CONNECT_AFTER); entry_changed_cb (GTK_ENTRY (entry)); gtk_window_present (window); } int main (int argc, char *argv[]) { g_autoptr(GtkApplication) app = gtk_application_new (NULL, 0); g_signal_connect (app, "activate", G_CALLBACK (app_activated_cb), NULL); return g_application_run (G_APPLICATION (app), argc, argv); }
unknown
d18278
test
Because of the implementation of the fling Method in the ScrollView - it is sufficient to override the findFocus(), so that it will return this to prevent the focus from jumping around when scrolling. @Override public View findFocus() { return this; } A: It's not scrolling that randomly focuses the EditText. It's when the scrollview handles a fling event. If you overwrite the fling method the won't be any random focus changes. Then if you want the fling functionality back you'll need to write your own fling method. There's code here you can copy from: Smooth scrolling in Android
unknown
d18279
test
You can do this: private final List<Button> mButtons = new ArrayList<>(); // somewhere in your code mButtons.add(mButton1); mButtons.add(mButton2); mButtons.add(mButton3); mButton1.setOnClickListener(mClickListener); mButton2.setOnClickListener(mClickListener); mButton3.setOnClickListener(mClickListener); private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View v) { for (Button button : mButtons) { if (button == v) { // set selected background } else { // set not selected backround } } } }; If you define a stateful drawable for your buttons, then you can simply change the onclick to this: private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View v) { for (Button button : mButtons) { button.setSelected(v == button); } } }; A: For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button. For example button_selector.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/your_image1" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/your_image2" /> <!-- focused --> android:drawable="@drawable/your_image3" <!-- default --> </selector> then just apply it as : <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawable="@drawable/button_selector.xml" /> A: "Pressed", "selected", "disabled" and such are View states. As such they're supposed to be handled automatically by Android and not by your click listeners. This is achieved using SateLists, which control the look your Views sould have depending on which state(s) they're in. So you can easily set subject_button as the unpressed state, clicked_subject as the pressed state, and let Android take care of actually switching between them. Full explanation: https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList A: I solved it by instead of changing only the background color on clicking the button, I also change the textColor, then I can check the textColor with if (((Button) v).getCurrentTextColor() == Color.WHITE)
unknown
d18280
test
Try to use "Accept", "application/json" in your params (use both). I have to use x-api-key when connecting with my company's webserver, but I'm not sure if you'll need it. A: --> Use https instead of http in android , Postman seems fine with the http, but OkHttp needed https. I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .
unknown
d18281
test
Your log say that your application don't have the right to write in his current emplacement. Your should check the right on your file can you post the output of a ls -al in your app's folder ?
unknown
d18282
test
You can't import "NgModule" as it is a decorator and not a module.
unknown
d18283
test
The docs on the registry report that the digest contains the image manifest, and the manifest is made up of the tag amongst other things.
unknown
d18284
test
My suggestion: session.findById("wnd[0]").sendVKey 83 myPosition = session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position do if session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010/ctxtMAPL-MATNR[2,0]").Text = "" then exit do myPosition = myPosition + 1 session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position = myPosition loop msgbox myPosition Regards, ScriptMan A: Just to go to the end max_scrollbar = session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Maximum ' Get the maximum scrollbar value session.findById("wnd[1]/usr/tblSAPLCZDITCTRL_4010").verticalScrollbar.Position = max_scrollbar ' Go to the end
unknown
d18285
test
You seem to be using a thread Queue (from Queue import Queue). This does not work as expected as Process uses fork() and it clones the entire Queue into each worker Process Use: from multiprocessing import Queue
unknown
d18286
test
I'd actually do something like this (I'm assuming you cant use reversed()). This uses slicing notation to reverse a list. def reverse(s): return s[::-1] I'm also assuming you need to wrap this in a function, you could just use the index notation on its own. EDIT: Here is a bit of an explanation of the [::-1] operation: Slicing notation is of the format [start_point:end_point:step] The start_point is not specified, this becomes the length of the list so the operation starts at the end. The end_point is also not specified, this becomes -1 so the operation will end at the start. The step is -1, so it will iterate backwards in steps of 1 (i.e. every element of the list). This will create a shallow copy of your original list. This means the list you pass into reverse(s) will remain the same. Example for clarification: >>> x = [1, 2, 3] >>> y = x[::-1] >>> x [1, 2, 3] >>> y [3, 2, 1] A: parameter passed to function is of type list. def reverse(s): return s[::-1]
unknown
d18287
test
Based on Determining free memory on Linux, Free memory = free + buffers + cache. Following example includes values derived from node os methods for comparison (which are useless) var spawn = require("child_process").spawn; var prc = spawn("free", []); var os = require("os"); prc.stdout.setEncoding("utf8"); prc.stdout.on("data", function (data) { var lines = data.toString().split(/\n/g), line = lines[1].split(/\s+/), total = parseInt(line[1], 10), free = parseInt(line[3], 10), buffers = parseInt(line[5], 10), cached = parseInt(line[6], 10), actualFree = free + buffers + cached, memory = { total: total, used: parseInt(line[2], 10), free: free, shared: parseInt(line[4], 10), buffers: buffers, cached: cached, actualFree: actualFree, percentUsed: parseFloat(((1 - (actualFree / total)) * 100).toFixed(2)), comparePercentUsed: ((1 - (os.freemem() / os.totalmem())) * 100).toFixed(2) }; console.log("memory", memory); }); prc.on("error", function (error) { console.log("[ERROR] Free memory process", error); }); Thanks to leorex. Check for process.platform === "linux" A: From reading the documentation, I am afraid that you do not have any native solution. However, you can always call 'free' from command line directly. I put together the following code based on Is it possible to execute an external program from within node.js? var spawn = require('child_process').spawn; var prc = spawn('free', []); prc.stdout.setEncoding('utf8'); prc.stdout.on('data', function (data) { var str = data.toString() var lines = str.split(/\n/g); for(var i = 0; i < lines.length; i++) { lines[i] = lines[i].split(/\s+/); } console.log('your real memory usage is', lines[2][3]); }); prc.on('close', function (code) { console.log('process exit code ' + code); });
unknown
d18288
test
In python there are multiple ways to format strings. using %s inside a string and then a % after the string followed by a tuple (or a single value), allows you to create a new string: x = 5 y = 8 'my favourite number is %s, but I hate the number %s' % (x, y) results in: 'my favourite number is 5, but I hate the number 8' I think they call it C-type string formatting. For more information, you can check out this page. In my opinion, it is easier to format string using f'strings, or .format(). Check out this page too
unknown
d18289
test
You can do it like so. * *use groupingBy and create a Map<String, List<String>> *if the string starts with "el" group using the els key *otherwise, use the others key List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el"); Map<String, List<String>> map = elements.stream().collect( Collectors.groupingBy(str -> str.startsWith("el") ? "els" : "others")); map.entrySet().forEach(System.out::println); prints els=[el2, el3] others=[e1, 4 el, 5 el] A: Since you have a threshold condition which determine if an item will go to group A, otherwise B, I suggest using partitioningBy for this. For example: List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el"); //create the partition map Map<Boolean,List<String>> partitionMap = elements.stream() .collect(Collectors.partitioningBy(s-> s.startsWith("el"))); //getting the partitions List<String> startsWithEl = partitionMap.get(true); List<String> notStartingWilEl = partitionMap.get(false); Now each list will hold its partition .
unknown
d18290
test
Just going with your constraints taken at face value, have you considered something like the following... I woudln't recommend this approach, but if nothing else about your situation can be changed, this might work for you... Considering the following requirements * *Single-line operations *Detect failed line *Be able to restart on-or-around failed line (+/- 1, etc). Public Sub RunCode(Optional ByVal StartLine As Integer = 0) On Error GoTo Handle If StartLine > 0 Then If StartLine = 10 Then GoTo 10 If StartLine = 20 Then GoTo 20 If StartLine = 30 Then GoTo 30 If StartLine = 40 Then GoTo 40 End If 10: Debug.Print "10" 20: Debug.Print "20" 30: Err.Raise -1, "Jones" 40: Debug.Print "40" Exit Sub Handle: Debug.Print "Handle [" & Erl & "]: " & Error End Sub The trick used is the Erl statement from VBA... It's generally not used, because it requires the explicit line numbers, seen above... But, since you ALREADY effectively numbered you lines, it would seem like a better option than what you're currently doing. Second, if you NEED to restart AT or around the line that failed, you need a goto label anyway... That is, you would have to have a third line on each clause the way you're doing it, so you can do a GoTo to it. That is the only way to restart in the middle of your control structure, as you have it. By combining the line numbering as the labels, you effectively reduce this, hopefully making your life easier in the mid-term (not the long term, since numbering your lines is inherently problematic). The Erl will give you the line that failed, which can be stored somewhere like either a return value or a Global (or wherever you can store and retrieve it). What you have left is the requirement to restart at the given line. Unfortunately, to the best of my knowledge, you can't simply do GoTo StartLine, as would be the easiest, so, as you see, each line is enumerated twice (but, you already had that, right?).. The function, via Optional parameter, can be effectively re-entered at any given point. This, then, is the most straight-forward way to accomplish your three goals. With that said, you could consider some other options... For example, you could wrap your call to DoCmd.OpenQuery "...", acViewNormal, acEdit in some function, and attempt to apply some retry-logic on the same... That is, Public Function RetryMyQuery(ByVal Query As String) As Boolean Const MaxRetries As Long = 5 DoRetry: On Error Goto QueryFailed Dim FailureCount as Long DoCmd.OpenQuery Query, acViewNormal, acEdit RetryMyQuery = True Exit Function QueryFailed: FailureCount = FailureCount + 1 If FailureCount >= MaxRetries Then Exit Function If MsgBox("Query Failed [" & Query & "]: " & Err.Description, vbRetryCancel, "Query Failed") = vbRetry Then Resume DoRetry End Function Each line in the main function would simply call this function with the query name: If Not RetryMyQuery("SP_export_sumary") Then MyErrorLine = 19 What this is doing is attempting to retry each operation up to 5 times (configurable), with a message box between each retry to force the user to interact. They can double-check the connection, re-open anything as needed, and try again, or, simply cancel the operation. The stub function encapsulates the retries and returns True on success, so in the main loop, you can still detect the error, and even record the line that failed, if desired. However, again, if you NEED to re-enter the control logic at any given point, you likely need something like solution #1. Other alternatives to this would be to put the list of operations in some kind of String Array and loop through them, and then you're not re-entering hard-coded logic lines, you just start at an arbitrary point in the list. It depends on your needs. Hopefully something in this would be of assistance. It is not always possible to change a lot of the control structures on existing code, and while I wouldn't ever set out and design something like the first example, if you merely need to modify what's there, a down-and-dirty way is sometimes the best. Just remember, maintaining line numbers is terrible. BASIC (Before VB or VBA, or even QuickBasic) had line numbers and always had this problem. They aren't used any more for a reason. It should be considered a last resort, but, if it gets things up and going, I've done worse. NOTE: It may also be helpful to point out that GoTo Labels are only scoped to the current function. Pre-pending the name of the function (Export_to_sp_Err:) only results in more characters being typed, and never being able to remember what the handler is named by the time you get to the end of a long function. Just a tip! A: The classic way of doing this is to avoid the very limited old scool way of dealing with errors and instead implement a Tryxxx function. The Role of the TryXXX function is to return True of False to indicate the success or fail of an action. One of the parameters (usually the last) is declared as ByRef so that the result of the action can be passed back via the parameter. I'd also restructure how you provide the strings for the queries so that you separate them from the code that does the querying XXXQuery is the name of the query for which you have the sequence of query statments. SOmething along these lines Public Sub DoXXXQuery(ByRef ipQuerySeq As Collection) Dim myItem As Variant For Each myItem In ipQuerySeq Dim myResult as Variant 'as an example If Not TryDoQuery(myItem, acviewnormal, acedit, myresult) Then MsgBox "Query execution stopped unexpectedly at '" & myItem & "'" 'put code here for action after failure End If Next End Sub ' ipViewNormal, ipEdit, and opResult are variants as the OP ' doesn't provide enough information to define more appropriately Public Function TryDoQuery(ByVal ipCommand As String, ByVal ipViewNormal, ByVal ipEdit, ByVal opResult As Variant) As Boolean TryDoQuery = False On Error Resume Next DoCmd.OpenQuery ipCommand, ipViewNormal, ipEdit If Err.Number <> 0 Then Err.Clear Exit Function End If err.clear opResult = ????? ' its not clear what the result of the query is TryDoQuery = True End Function Public Function GetXXXQuerySeq() As Collection Dim myC As Collection Set myC = New Collection With myC .Add "6-delete_C", acviewnormal, acedit .Add "6-rename_B_to_C" .Add "6-rename_A_to_B" .Add "6-rename_Active_to_A" .Add "6- export_to_Sp" .Add "6- move_A_to_backup" .Add "6-delete_A" .Add "upload_size_tracker_to_SP_new" .Add "Clear_old_for_current_SP" .Add "3_open_op" .Add "export change log to new sp" .Add "clear_sp_table_size" .Add "count_local_std_res" .Add "count_local_res" .Add "count_sp_std_res" .Add "count_sp_ol_res" .Add "count_sp_backup_ol_result" .Add "count_audit_log" .Add "count_row_tracker" .Add "SP_export_sumary" End With Set GetXXXQuerySeq = myC End Function
unknown
d18291
test
As I looked at your source code, I guess you should somehow add the .cbp-af-header-shrink class back to the header, when you click the green button.
unknown
d18292
test
startService() does not use a ServiceConnection. bindService() does. A: Intent intent = new Intent(CallAlert.class.getName()); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); A: The onServiceConnected isn't called. For binding with the service you need to call bindService(). It provide the persistence connection, and after connection establishment onServiceConnected() is called. Second point:- If you are using AIDL IPC mechanism then I think you need the communication between 2 diff processes/Application. Here you need to have same copy of .aidl file in both service and Activity side in same PACKAGE. Then you need to modify little bit in your Activity side.. you can find here http://www.zestofandroid.blogspot.com/
unknown
d18293
test
I think is better like this: var mobileController = TextEditingController(); getMobile() async { Future notificatinstatus = SharedPrefrence().getUserMobile(); notificatinstatus.then((data) async { var mobile_no=data; setState(() { if(mobile_no.isNotEmpty){ mobileController.text = mobile_no; } }); }); } @override void initState() { super.initState(); getMobile(); }
unknown
d18294
test
Regex: (Product)\s*(\d+)\s*Pc[.s]?\s*(\d+) Replacement string: $1 $2 Price $3 DEMO $string = <<<EOT Name xxx Product 1 Pc 100 Name Pci Product2Pc.200 Name Pcx Product 3 Pcs300 EOT; $pattern = "~(Product)\s*(\d+)\s*Pc[.s]?\s*(\d+)~"; echo preg_replace($pattern, "$1 $2 Price $3", $string); Output: Name xxx Product 1 Price 100 Name Pci Product 2 Price 200 Name Pcx Product 3 Price 300 A: The reason your attempt is not working is because you are removing things that you don't want to. You could use the following regular expression. $title = <<<DATA Name xxx Product 1 Pc 100 Name Pci Product2Pc.200 Name Pcx Product 3 Pcs300 DATA; $title = preg_replace('/Product\K\s*(\d+)\D+(\d+)/', ' $1 Price $2', $title); echo $title; Output: Name xxx Product 1 Price 100 Name Pci Product 2 Price 200 Name Pcx Product 3 Price 300
unknown
d18295
test
db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } }, {$match:{_id:"tel_aviv"}}) matching at the end did the trick.
unknown
d18296
test
Put this in your page: <script type="text/javascript"> window.onload = function() { counter = 0; document.body.onclick = function() { counter++; if(counter == 1) { document.getElementById('btn').click(); } else if(counter == 2) { location.replace('http://www.google.com'); } }; document.getElementById('btn').onclick = function(e) { e.stopPropogation(); alert('Link has been clicked!'); }; } </script> Sorry, I am unable to create a fiddle for this, as jsfiddle prevents iframe page redirects out of its domain.
unknown
d18297
test
Using new Integer() will guarantee that you have a new Integer object reference. Using the value directly will not guarantee that, since auto boxing int to Integer may not do that object instantiation. I would say that you will only need new Integer(1) in really strange edge cases, so most of the time I would say you never need to do new Integer... Also please bear in mind that auto boxing / unboxing may produce some errors in some edge cases. Integer x = null; int y = x; // Null Pointer Exception Long iterations where auto(un)boxing is happening may have a performance cost that an untrained eye might not notice A: Use autoboxing as a default pattern - it's been about forever and makes life ever-so-slightly easier. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, .. While there are slight difference with new Integer (see other answers/comments/links), I generally do not consider using new Integer a good approach and strictly avoid it.
unknown
d18298
test
There's nothing about your existing function that prevents it from being used on an n-dimensional array. In fact, the function you show here, gives exactly the desired output using the provided input. <?php function array_chunk_vertical($data, $columns = 2) { $n = count($data) ; $per_column = floor($n / $columns) ; $rest = $n % $columns ; // The map $per_columns = array( ) ; for ( $i = 0 ; $i < $columns ; $i++ ) { $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ; } $tabular = array( ) ; foreach ( $per_columns as $rows ) { for ( $i = 0 ; $i < $rows ; $i++ ) { $tabular[$i][ ] = array_shift($data) ; } } return $tabular ; } $cars = [ [ 'make' => 'Alfa Romeo', 'id' => 2 ], [ 'make' => 'Aston Martin', 'id' => 3 ], [ 'make' => 'Audi', 'id' => 4 ], [ 'make' => 'BMW', 'id' => 8 ], [ 'make' => 'Caterham', 'id' => 9 ], ]; echo '<table>'; foreach(array_chunk_vertical($cars) as $row) { echo '<tr>'; foreach($row as $car) { echo '<td><input type="checkbox" value="', $car['id'], '" />', $car['make'], '</td>'; } echo '</tr>'; } echo '</table>'; A: In that case you should add your data into a new one dimension array.Try something like the following $a = array(0 => array( 'make' => 'Alfa Romeo', 'id' => 2 ), 1 => array( 'make' => 'Aston Martin', 'id' => 3 ), 2 => array( 'make' => 'Audi', 'id' => 4 ), 3 => array( 'make' => 'BMW', 'id' => 8 ), 4 => array( 'make' => 'Caterham', 'id' => 9 ) ); $b=array(); foreach ($a as $v) { $b[]=$v['make']; } sort($b); print_r($b); Then you can use your working function passing the new array as the parameter. A: try this,add up som condtions to display in your two column <?php $sort=Array ( 0 => Array ( 'make' => 'Alfa Romeo' ,'id' => 2 ), 1 => Array ( 'make' => 'Aston Martin' ,'id' => 3 ) , 2 => Array ( 'make' => 'Audi' ,'id' => 4 ), 3 => Array ( 'make' => 'Caterham' ,'id' => 8 ), 4 => Array ( 'make' => 'BMW' , 'id' => 9 ) ); print_r($sort); sort($sort); echo ' <br/>'; print_r($sort); ?>
unknown
d18299
test
If you're curious about this sort of stuff you should play around with Chrome Developer Tools, the Firefox Firebug Addon or the Safari's 'Developer' menu. They're really great at giving you an insight as to what is going on in a webpage As to "how did they build this" there's many, many different technologies being used up and down the web application stack. Keep in mind the servers storing, caching and fetching all this data are just as much a part of the web application as the frontend. But I imagine your question is asking how "how did they get this webpage to do all this interactive stuff". Basically it looks like it's all traditional HTML/CSS--no "HTML5" canvas shenanigans or Flash. The interactivity comes from their custom Javascript code. I tried to figure out if they're using some popular 3rd party Javascript Framework (like jQuery or Prototype) but they are importing so many scripts it's hard to follow. Interestingly enough jQuery and $ are not defined variables on the Evernote page, so it looks like they're not using jQuery at the least. They have clearly written a lot of Javascript to get this thing up and running so it's not that big of a stretch to imagine they they would just decide to keep all their code in-house. FYI: The three columns are just absolutely positioned and sized <div>s. <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 0px; top: 0px; bottom: 0px; width: 220px; ">...</div> <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 220px; top: 0px; bottom: 0px; width: 360px; ">...</div> <div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 580px; top: 0px; right: 0px; bottom: 0px; ">...</div> The scrolling that you see in those columns is done in child <div>s. A: webapps like this are usually built with a javascript framework such as backbone, angularjs, ember, etc. here is a reference site which lists them: http://todomvc.com/ Its hard to see what js framework they are using if any but there are using jQuery 1.8 They are using http://icanhazjs.com/ which is a javascript client side template library. They are using http://requirejs.org/ A: Well, at the very basic evernote has accomplished its note app workflow using custom javascript, although there are lot of others frameworks they have used for backend work. One way is to see it using Chrome web Inspector nad if on Firefox ,then they have upgraded there web inspector and its much cooler now, but if you prefer the much popular firebug, it will do. For detailed info, on what are the resources they have used to build, on way is to track it using a web analyzer tool like www.buitwith.com here, is the link for the homepage of the evernote site , searched over Builtwith.com : http://builtwith.com/?https%3a%2f%2fwww.evernote.com However the app, that is built upon comprises a lot of custom code. Hard to specify the exact usage, but if we check the code, it doesn't show any of specific use of AngularJS , they do use requireJS for loading modules. As your question is front-end specific, it can be done using HTML5, with some javascript or if you prefer a framework to ease the process, then checkout this link from JQueryUI. https://jqueryui.com/resizable/ They are still the kings of UI development, if AngularJS and ReactJS are not mentioned to be overwhelmed. And also , if you try to do it using plain vanilla JavaScript, that will give you an edge to the learning curve a loads. A: They use Angular.js, HTML5, CSS3, custom Javascript, and JQuery (and lots of other stuff as others have noted). From: http://evernote.com/careers/job.php?job=om2qXfwv
unknown
d18300
test
You would need to create a custom dimension in Google Analytics, retrieve the cookie value and pass it to the GA code (how exactly would depend on the version of the GA code that you use, as they have recently shifted from the analytics.js library to gtag.js).
unknown