_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d11001
Use regex with character class ([\\w.]+) If you just want to contain single . then use (\\w+\\.\\w+) In case you want multiple . which is not adjacent then use (\\w+(?:\\.\\w+)+) A: To validate a string that contains exactly one dot and at least two letters around use match for \w+\.\w+ which in Java is denoted as \\w+\\.\\w+ A: This regex works: [\w\[.\]\\]+ Tested for following combinations: foo.com foo.co.in foo... ..foo A: I understand your question like, you need a regex to match a word which has a single dot in-between the word (not first or last). Then below regex will satisfy your need. ^\\w+\\.\\w+$
d11002
You can unpack the generator expression using the splat operator: print (biggest_number(*a)) Although I think you actually want to use a container such as tuple or list since you can only consume the gen. exp. once so that the next call to max after the print gives you an error: a = [int(x) for x in input().split()] Or: a = tuple(int(x) for x in input().split()) However, you still need to unpack since your function does not take the iterables directly. A: you can try with raw_input() instead of input().
d11003
You didn't show any effort on the implementation but this should solve your problem. awk -F"\t" 'NR==FNR{a[$1]=$2;next} {for(k in a) gsub(k,a[k])}1' <(paste search replace) text create a lookup table, do the replacement based on lookup. A: There may be a better way to do this, but if you would like to use AWK, you can asssign a variable for each file you read, build some arrays with the find and replace string, and then loop through each find/replace value: awk ' file == 1 { source[++s] = $0 } file == 2 { replace[++r] = $0 } file == 3 { for (i = 1; i < s; i++) { gsub (source[i], replace[i], $0) } print } ' file=1 match_file \ file=2 replace_file \ file=3 original_file I don't claim this is the most efficient way to do it, but I think it will do what you describe. A: Here is one approach of solving this using awk: #!/usr/bin/awk -f FILENAME == ARGV[1] { m[FNR]=$0 } # Store the match word in an array FILENAME == ARGV[2] { r[FNR]=$0 } # Store the replacement word in a second array FILENAME == ARGV[3] { for (i in m) gsub(m[i],r[i]); print } # Do the replacement for every line in file3 Run it like this: ./script.awk match_file replace_file original_file A: This is the output the first three codes.This is the output the first two codes. Perhaps the encoding? a_demand▒_de_montreraa_demand▒_de_montreria_demand▒_de_montrersa_demand▒_de_montrersa_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montrerea_demand▒_de_montrerua_demand▒_de_montrerra_demand▒_de_montrer a_demand▒_de_montrerua_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrerma_demand▒_de_montrerpa_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerda_demand▒_de_montrer a_demand▒_de_montreraa_demand▒_de_montrerda_demand▒_de_montreraa_demand▒_de_montrerpa_demand▒_de_montrerta_demand▒_de_montreraa_demand▒_de_montrerta_deman d▒_de_montreria_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer a_demand▒_de_montrerAa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreraa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreria_demand▒_de_montrerma_demand▒_de_montreria_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrer,a_demand▒_de_montrer a_demand▒_de_montrerca_demand▒_de_montrerha_demand▒_de_montreraa_demand▒_de_montrerca_demand▒_de_montrerua_demand▒_de_montrerna_demand▒ I tried this.. BEGIN { while ((getline ln1 < mt) > 0) { source[++s] = ln1; } while ((getline ln2 < rp) > 0) { replace[++r] = ln2; } } { for ( i = 1; i < s; i++) gsub (source[i], replace[i], $0) print; } A: With GNU awk for ARGIND (with other awks just add FNR==1{ARGIND++}): $ cat tst.awk ARGIND==1 { a[FNR] = $0; next } ARGIND==2 { map[a[FNR]] = $0; next } { for (m in map) { gsub(m,map[m]) } print } $ awk -f tst.awk match.txt replace.txt original.txt A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos... A ce jour, je suis totalement satisfaite A ce moment-là aux grandes_vacances on m'a_demandé_de_montrer le bon. A chacun son choix A chaque fois c'est moi qui dois les recontacter. A eux de_faire leurs avis.... A l'achat, le vendeur m'a_montré comment rabattre le siège arrière, mais quand il l'a_remis en place, ce n'était pas bien_posé. A l'arrière_du_véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle_essence. A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ... A la limite, chacun son garagiste. Like all other solutions posted so far, the above will behave undesirably if you have regexp metachars in your match file or regexp capture group identifiers in your replace file. If that can happen use index() and substr() instead of gsub().
d11004
You can use subquery, because your query is not identical. Here DQL: Doctrine Query Language some example. And here is pseudocode, I do not know if it will work at once. $q = Doctrine_Query::create() ->from('Product p') ->select('id, sum(id) as sumEntries') ->addSelect('(SELECT id, name) // and else fields that you need FROM Product a WHERE ( a.store_id = '.$store_id.' AND a.collection = '.$this->product->getCollection().' AND a.id<>= '.$this->product_id.' ) OFFSET '.rand(0, $productsCount - 1).') // I am not sure in this line as resultSubquery') ->where('p.store_id = ?', $store_id) ->andWhere('p.collection = ?', $this->product->getCollection()) ->andWhere('p.image_path IS NOT NULL') $result = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //This greatly speeds up query You get an array in $result. Do var_dump() and check its contents. I'm not sure that this code will work at once, but I advise you to move in this direction. p.s: I recommend you this interesting presentation about Doctrine query optimization: Doctrine 1.2 Optimization
d11005
const input = [ { 'Product': 'P1', 'Price': 150, 'Location': 1, }, { 'Product': 'P1', 'Price': 100, 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, }, { 'Product': 'P2', 'Price': 10, 'Location': 1, }, { 'Product': 'P2', 'Price': 130, 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, } ] const output = [] input.forEach(item => { const index = output.findIndex(o => o.Product === item.Product && o.Location === item.Location); if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); console.log(output); Without arrow function input.forEach(function(item) { const index = output.findIndex(function(o) { return o.Product === item.Product && o.Location === item.Location}); if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); A: You can use reduce() to do that, obj = [ { 'Product': 'P1', 'Price': 250, // price is the sum of both similar in location and product 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, // same product but different location }, { 'Product': 'P2', 'Price': 140, //sum of same 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, }, ] res = obj.reduce((prev, curr) => { index = prev.findIndex(item => item.Product=== curr.Product && item.Location === curr.Location); if(index > -1) { prev[index].Price += curr.Price; } else { prev.push(curr); } return prev; }, []); console.log(res); A: Modifying @William's answer (Accepted) for my use case as it was to be run on the platform which was not supporting ES6 features (findIndex and arrow function), this can be done without findIndex as below; var input = [{ 'Product': 'P1', 'Price': 150, 'Location': 1, }, { 'Product': 'P1', 'Price': 100, 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, }, { 'Product': 'P2', 'Price': 10, 'Location': 1, }, { 'Product': 'P2', 'Price': 130, 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, } ] var output = [] input.forEach(function(item) { var index = output.indexOf(output.filter(function(o) { return o.Product === item.Product && o.Location === item.Location })[0]); // note the [0] index here if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); console.log(output);
d11006
The v parameter sent in that web request is just used as a way to help the browser know when to request a new resource--commonly called "cache busting." The number that MVC puts in the bundle links will change any time the files used in the bundle are changed, but the server doesn't even pay any attention to the parameter at all when the actual request is made. Because of this, the auditing software sees a pattern that indicates it can send "anything" to the server, and it never gets checked to see if it is valid. In some cases, this can be indicative that their sql injection "got through," but in this case it's a false positive. The bundling framework doesn't touch SQL at all, so there's absolutely no way that this represents a SQL injection vulnerability. For more information, see the "Bundle Caching" section of this article.
d11007
Do you really do data mining (as in: classification, clustering, anomaly detection), or is "data mining" for you any reporting on the data? In the latter case, all the "modern data mining tools" will disappoint you, because they serve a different purpose. Have you used the indexing functionality of Postgres well? Your scenario sounds as if selection and aggregation are most of the work, and SQL databases are excellent for this - if well designed. For example, materialized views and triggers can be used to process data into a scheme more usable for your reporting. A: There are a thousand ways to approach this issue but I think that the path of least resistance for you would be postgres replication. Check out this Postgres replication tutorial for a quick, proof-of-concept. (There are many hits when you Google for postgres replication and that link is just one of them.) Here is a link documenting streaming replication from the PostgreSQL site's wiki. I am suggesting this because it meets all of your criteria and also stays withing the bounds of the technology you're familiar with. The only learning curve would be the replication part. Replication solves your issue because it would create a second database which would effectively become your "read-only" db which would be updated via the replication process. You would keep the schema the same but your indexing could be altered and reports/dashboards customized. This is the database you would query. Your main database would be your transactional database which serves the users and the replicated database would serve the stakeholders. This is a wide topic, so please do your diligence and research it. But it's also something that can work for you and can be quickly turned around. A: If you really want try Data Mining with PostgreSQL there are some tools which can be used. * *The very simple way is KNIME. It is easy to install. It has full featured Data Mining tools. You can access your data directly from database, process and save it back to database. *Hardcore way is MADLib. It installs Data Mining functions in Python and C directly in Postgres so you can mine with SQL queries. Both projects are stable enough to try it. A: For reporting, we use non-transactional (read only) database. We don't care about normalization. If I were you, I would use another database for reporting. I will desing the tables following OLAP principals, (star schema, snow flake), and use an ETL tool to dump the data periodically (may be weekly) to the read only database to start creating reports. Reports are used for decision support, so they don't have to be in realtime, and usually don't have to be current. In other words it is acceptable to create report up to last week or last month.
d11008
It's hard to see without getting a look on the complete code. But every time your JS runs, you wrap every h2 element with a span. And then for every br-tag that is inside a h2-tag, it adds spans before and after. A more robust way to do this would be to have the captions already in place and and with the correct CSS. But the captions are hidden (display:none;). Then you can load your data in to them and just do $(".caption").show(); on completion/success of your ajax callback. Good luck :)
d11009
Using the comments from @Asperi and @jnpdx, I was able to come up with a more powerful solution than I needed: class ScrollToModel: ObservableObject { enum Action { case end case top } @Published var direction: Action? = nil } struct HigherView: View { @StateObject var vm = ScrollToModel() var numAbstractedViewsToMake: Int var body: some View { VStack { HStack { Button(action: { vm.direction = .top }) { // < here Image(systemName: "arrow.up.to.line") .padding(.horizontal) } Button(action: { vm.direction = .end }) { // << here Image(systemName: "arrow.down.to.line") .padding(.horizontal) } } Divider() HStack { ForEach(0..<numAbstractedViewsToMake, id: \.self) { _ in ScrollToModelView(vm: vm) } } } } } struct AbstractedView: View { @ObservedObject var vm: ScrollToModel let items = (0..<200).map { $0 } // this is his demo var body: some View { VStack { ScrollViewReader { sp in ScrollView { LazyVStack { // this bit can be changed accordingly ForEach(items, id: \.self) { item in VStack(alignment: .leading) { Text("Item \(item)").id(item) Divider() }.frame(maxWidth: .infinity).padding(.horizontal) } }.onReceive(vm.$direction) { action in guard !items.isEmpty else { return } withAnimation { switch action { case .top: sp.scrollTo(items.first!, anchor: .top) case .end: sp.scrollTo(items.last!, anchor: .bottom) default: return } } } } } } } } Thank you both!
d11010
Use bootstrap's responsive-table. Wrap your <table> with this. <div class="table-responsive fix-table-height"> // your table here </div> Then add the class fix-table-height on the wrapper so you could define the height of the wrapper. In your case you want 200px;. So you can do this : .fix-table-height{ max-height:200px; } This is the output jsFiddle A: You'll need to change your table's body and rows display to block. Do something like this: table.jSpeeds tr:hover, table.jSpeeds tr td:hover{ cursor:pointer; } table.table-fixed thead { width: 100%; } table.table-fixed tbody { height: 230px; overflow-y: auto; } table.table-fixed tbody, table.table-fixed tr { display: block; width: 100%; } table.table-fixed th, table.table-fixed td { width: 300px; } EDIT Since I was challenged to give a robust solution, here is comes: table.jSpeeds tr:hover, table.jSpeeds tr td:hover{ cursor:pointer; } table.table-fixed thead { width: 100%; } table.table-fixed tbody { height: 230px; overflow-y: auto; } table.table-fixed tbody, table.table-fixed tr { display: block; width: 100%; } table.table-fixed th, table.table-fixed td { display: block; float: left; width: 50%; } Gist Link A: just adjust your css to this: tbody { display: block; overflow: auto; height: 230px; } tbody tr { display: table; width: 100%; table-layout: fixed; }
d11011
Your le_maxpage is a class level variable. When you pass the argument to __init__, you're creating an instance level variable start_urls. You used start_urls in le_maxpage, so for the le_maxpage variable to work, there needs to be a class level variable named start_urls. To fix this issue, you need to move your class level variables to instance level, that is to define them inside the __init__ block. A: Following masnun's answer, I managed to fix this. I list the updated code below for the sake of completeness. import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class NumberOfPagesSpider(CrawlSpider): name = "number_of_pages" allowed_domains = ["funda.nl"] def __init__(self, place='amsterdam'): self.start_urls = ["http://www.funda.nl/koop/%s/" % place] self.le_maxpage = LinkExtractor(allow=r'%s+p\d+' % self.start_urls[0]) rules = (Rule(self.le_maxpage, ),) def parse(self, response): links = self.le_maxpage.extract_links(response) max_page_number = 0 # Initialize the maximum page number for link in links: if link.url.count('/') == 6 and link.url.endswith('/'): # Select only pages with a link depth of 3 page_number = int(link.url.split("/")[-2].strip('p')) # For example, get the number 10 out of the string 'http://www.funda.nl/koop/amsterdam/p10/' if page_number > max_page_number: max_page_number = page_number # Update the maximum page number if the current value is larger than its previous value filename = "max_pages.txt" # File name with as prefix the place name with open(filename,'wb') as f: f.write('max_page_number = %s' % max_page_number) # Write the maximum page number to a text file Note that the Rule does not even need a callback because parse is always called.
d11012
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> Does that mean that there's no way to do the same as the first application? I mean there's no Hibernate OGM provider that I can just put in the place of HibernateJpaVendorAdapter in order to make the application running on Neo4j rather than SQL Server? Thanks in advance. PS: I checked out Spring Data but found another difference in defining entities (@NodeEntity, @GraphId, @RelatedTo, etc.). I'm asked not to touch the application code. A: Here is the below Java configuration class(Note I'm using spring boot, you could modify according you your requirement) @Configuration @EnableJpaRepositories(basePackages = { "com.kp.swasthik.mongo.dao" }, entityManagerFactoryRef = "mongoEntityManager", transactionManagerRef = "mongoTransactionManager") public class MongDbConfig { @Bean(name = "mongoEntityManager") public LocalContainerEntityManagerFactoryBean mongoEntityManager() throws Throwable { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("javax.persistence.transactionType", "resource_local"); properties.put("hibernate.ogm.datastore.provider","mongodb"); properties.put("hibernate.ogm.datastore.host","localhost"); properties.put("hibernate.ogm.datastore.port","27017"); properties.put("hibernate.ogm.datastore.database", "kpdb"); properties.put("hibernate.ogm.datastore.create_database", "true"); LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setPackagesToScan("com.kp.swasthik.mongo.domain"); entityManager.setPersistenceUnitName("mongoPersistenceUnit"); entityManager.setJpaPropertyMap(properties); entityManager.setPersistenceProviderClass(HibernateOgmPersistence.class); return entityManager; } @Bean(name = "mongoTransactionManager") public PlatformTransactionManager transactionManager() throws Throwable { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(mongoEntityManager().getObject()); return transactionManager; } } Regarding your Second question on @NodeEntity @GraphId etc. Similar to hibernate OGM sprig provides jpa implementation for no sql using spring-data for number of nosql datastores such as redis, mongodb,cassandra, hbase, couchdb, solr, elasticsearch etc. @NodeEnity and @GraphId is used in neo4j A: I add Java Config for Neo4j with OGM Hibernate @Configuration @EnableTransactionManagement @JpaPackagesToScan(Entity.class) public class RepositoryConfig { /** * Neo4J OGM EntityManager config */ @Bean public LocalContainerEntityManagerFactoryBean entityManager(JpaPackagesToScanHolder holder) throws Throwable { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("javax.persistence.transactionType", "JTA"); properties.put("hibernate.ogm.datastore.provider", "neo4j_embedded"); properties.put("hibernate.ogm.datastore.database", "my-db"); properties.put("hibernate.ogm.neo4j.database_path", "/mnt/graph.db"); properties.put("hibernate.dialect", "org.hibernate.ogm.datastore.neo4j.Neo4jDialect"); LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setPackagesToScan(holder.toStringArray()); entityManager.setPersistenceUnitName("my-pu"); entityManager.setJpaPropertyMap(properties); entityManager.setPersistenceProviderClass(HibernateOgmPersistence.class); return entityManager; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) throws Throwable { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } } And added to the pom (for Java 7 project) <dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-neo4j</artifactId> <version>4.1.0.Final</version> </dependency>
d11013
Simplest thing would be to have a thread work through a whole subnet and exit when it finds a host. UNTESTED from Queue import Queue import time import socket #wraps system ping command def ping(i, q): """Pings address""" while True: subnet = q.get() # each IP addresse in subnet for ip in (subnet=str(x) for x in range(1,254)): #print "Thread %s: Pinging %s" % (i, ip) result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #Avoid flooding the network with ping requests time.sleep(3) if result == 0: try: hostname=socket.gethostbyaddr(ip) print "%s (%s): alive" % (ip,hostname[0] except: print "%s: alive"%ip break q.task_done() num_threads = 100 queue = Queue() #Put all possible subnets on wireless network into a queue for i in range(1,255): queue.put('128.119.%s.'%i) #Spawn thread pool for i in range(num_threads): worker = Thread(target=ping, args=(i, queue)) worker.setDaemon(True) worker.start() #Wait until worker threads are done to exit queue.join() A: Since you know how many threads you got in the beginning of the run, you could periodically check the current number of threads running to see if nowThreadCount < startThreadCount. If it's true terminate the current thread. PS: Easiest way would be to just clear the queue object too, but I can't find that in the docs.
d11014
Specifying dtype argument when creating an array avoids the unintentional creation of object arrays from jagged matrices, without writing any additional code. np.array([[1, 2], [3, 4]], dtype=int) # okay np.array([[1, 2], [3]], dtype=int) # ValueError np.array([[1, "b"]], dtype=int) # ValueError (Regarding the last one, np.array([1, "b"]) would silently convert "1" to a string if the data type was not set.) A: There's Python saying that it's easier to ask forgiveness than permission. So there might be less overhead if you just call np.array and then check for object dtype. One other thing that you need to watch out for is when it throws an error. For example: In [273]: np.array((np.zeros((2,3)), np.ones((2,4)))) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-273-70f6273e3371> in <module>() ----> 1 np.array((np.zeros((2,3)), np.ones((2,4)))) ValueError: could not broadcast input array from shape (2,3) into shape (2) If the non-uniformity is in the first dimension, it produces an object dtype array, e.g. np.array((np.zeros((2,3)), np.ones((1,4)))). But when it's at a deeper level it appears to allocate the result array, and then has problems copying one or more of the component arrays to it. This is a tricky case to diagnose. Or consider: In [277]: np.array([[1,2,3],[4,5,'6']]) Out[277]: array([['1', '2', '3'], ['4', '5', '6']], dtype='<U21') The last element in the nested list forces the string dtype. And if that last element is some other PYthon object, we may be a object dtype: In [279]: np.array([[1,2,3],[4,5,{}]]) Out[279]: array([[1, 2, 3], [4, 5, {}]], dtype=object) But if the object is a list, we get a variant on the broadcasting error: In [280]: np.array([[1,2,3],[4,5,['6']]]) ValueError: setting an array element with a sequence But if you do want to check first, np.stack might a good model. With axis=0 it behaves much like np.array if given arrays or lists.
d11015
If I'm understanding what you're trying to do correctly, I'd remove the sizeof and just check if the first character in the string is \0; #define EMPTY_OR(x, y) ( #x[0] ? (x+0) : (y) ) A: Here's a solution adapted from this article and without Boost that works on anything that I can think of that you can pass: #define CAT(a, b) CAT_(a, b) #define CAT_(a, b) a##b #define IF(cond, t, f) CAT(IF_, cond)(t, f) #define IF_1(t, f) t #define IF_0(t, f) f #define COMMA(x) , #define ARG3(a, b, c, ...) c #define HAS_COMMA(x) ARG3(x, 1, 0,) #define EMPTY(x) EMPTY_(HAS_COMMA(COMMA x ())) #define EMPTY_(x) HAS_COMMA(CAT(EMPTY_, x)) #define EMPTY_1 , #define EMPTY_OR(x, y) IF(EMPTY(x), y, x) #define TEST(x, y) EMPTY_OR(y, x) #include <iostream> using namespace std; int main() { int t = TEST(1==, ) 1; int f = TEST(1==, 0==) 1; cout << "t: " << t << endl; cout << "f: " << f << endl; return 0; }
d11016
* *RFC2616 calls it an Exchange. *Wireshark and HTTPNetworkSniffer call it a Request/Response. *Fiddler calls it a Session. *Charles calls it a Sequence. *HTTP Scoop calls it a Conversation. *Other vocabulary includes: Message, Transaction, Communication. I would go for Exchange or RequestResponse. I also went to name it Operation in my code as I would queue Operations, flush Operations, pause or resume Operations. A: The spec calls them "exchanges" (or "request/response exchanges"). Per section 1.4, "Overall Operation": In HTTP/1.0, most implementations used a new connection for each request/response exchange. In HTTP/1.1, a connection may be used for one or more request/response exchanges […] A: Exchanges is nice name, also we can use Connection, Communication or session A: Payload In my project, I needed a name so that I can differentiate between models (Database) and HTTP interaction objects, so I am using payload, like: * *ProductPayload, ProductModel *CartPayload, CartModel *OrderPayload, OrderModel A: Transaction, yes, or "A singe HTTP Request consists of one HTTP Request message and one HTTP Response message."
d11017
As you say, adding .all() gives the result, so you need to add that to your dynamic lookup: field_value = getattr(self, field).all()
d11018
You've used double quotes inside your XPath query. Switching these for single quotes allows sheets to parse the formula correctly: =IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//*[@id='content-body']/header/div[2]/div[1]/div[1]/div/h1") But this still results in an error: Error Imported XML content cannot be parsed. You haven't been very specific but you can get the H1 content from the page in your code with this: =IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//h1") This may well break for other pages, though.
d11019
Some other interesting usages in the documentation. Reuseable A use case for query() is when you have a collection of DataFrame objects that have a subset of column names (or index levels/names) in common. You can pass the same query to both frames without having to specify which frame you’re interested in querying -- (Source) Example: dfA = pd.DataFrame([[1,2,3], [4,5,6]], columns=["X", "Y", "Z"]) dfB = pd.DataFrame([[1,3,3], [4,1,6]], columns=["X", "Y", "Z"]) q = "(X > 3) & (Y < 10)" print(dfA.query(q)) print(dfB.query(q)) X Y Z 1 4 5 6 X Y Z 1 4 1 6 More flexible syntax df.query('a < b and b < c') # understand a bit more English Support in operator and not in (alternative to isin) df.query('a in [3, 4, 5]') # select rows whose value of column a is in [2, 3, 4] Special usage of == and != (similar to in/not in) df.query('a == [1, 3, 5]') # select whose value of column a is in [1, 3, 5] # equivalent to df.query('a in [1, 3, 5]') A: Consider the following sample DF: In [307]: df Out[307]: sex age name 0 M 40 Max 1 F 35 Anna 2 M 29 Joe 3 F 18 Maria 4 F 23 Natalie There are quite a few good reasons to prefer .query() method. * *it might be much shorter and cleaner compared to boolean indexing: In [308]: df.query("20 <= age <= 30 and sex=='F'") Out[308]: sex age name 4 F 23 Natalie In [309]: df[(df['age']>=20) & (df['age']<=30) & (df['sex']=='F')] Out[309]: sex age name 4 F 23 Natalie *you can prepare conditions (queries) programmatically: In [315]: conditions = {'name':'Joe', 'sex':'M'} In [316]: q = ' and '.join(['{}=="{}"'.format(k,v) for k,v in conditions.items()]) In [317]: q Out[317]: 'name=="Joe" and sex=="M"' In [318]: df.query(q) Out[318]: sex age name 2 M 29 Joe PS there are also some disadvantages: * *we can't use .query() method for columns containing spaces or columns that consist only from digits *not all functions can be applied or in some cases we have to use engine='python' instead of default engine='numexpr' (which is faster) NOTE: Jeff (one of the main Pandas contributors and a member of Pandas core team) once said: Note that in reality .query is just a nice-to-have interface, in fact it has very specific guarantees, meaning its meant to parse like a query language, and not a fully general interface.
d11020
You have understood Python generics wrong. A Generic, say Generic[T], makes the TypeVar T act as whatever you provide the instance with. I found this page to be very useful with learning Generics. A: typing.Generic is specifically for type annotations; Python provides no runtime concept equivalent to either: * *Template classes, or *Function overloads by parameter count/type The latter has extremely limited support from functools.singledispatch, but it only handles the type of one argument, and the runtime type-checking is fairly slow. That said, you don't need a template-based class or a polymorphic inheritance hierarchy here; Python is perfectly happy to call draw on anything that provides a method of that actual name. The code you're writing here can just do: a = A(5) b = B('Hello') a.draw() b.draw() with no use of G needed.
d11021
If your plugin needs the dictionary object, it has to ask for it: class MyPlugin { /** * @var Dictionary */ private $dictionary; private function __construct(Dictionary $dictionary) { $this->dictionary = $dictionary; } You now have loosely coupled your plugin with the Dictionary, the plugin class is not responsible any longer to create the Dictionary for itself, because it's injected. It takes what it needs. So how would that work? The plugin needs to be created somewhere, so this needs a factory. The factory build method knows what your plugin needs: class MyPluginFactory { public static function build($pluginName) { $plugin = NULL; switch($pluginName) { case 'MyPlugin': $dictionary = new Dictionary(); $plugin = new MyPlugin($dictionary); } return $plugin; } } As this is wordpress we know that the bootstrapping of the plugin is done by including the plugin file. So at it's beginning, the plugin needs to be created. As includes are done in the global scope we want to preserve the plugin object in memory but without being available as a global variable probably. This does not prevent you from creating more than one plugin instance, but it will ensure that when wordpress initializes your plugin (loads your plugin), it will make only use of that single instance. This can be done by making the plugin factory some additional function: class MyPluginFactory { ... public static $plugins; public static function bootstrap($pluginName) { $plugin = self::build($pluginName); self::$plugins[] = $plugin; return $plugin; } Take care here, that the only usage of the static class member variable is only to ensure that the plugin stays in memory. It technically is a global variable we normally want to prevent, however, the instance needs to be stored somewhere, so here it is (I changed this to public because it is a global variable and it shouldn't be shy about it. Having a public can help in some circumstances in which private or protected are too restrictive. Also it shouldn't be a problem. If it is a problem, there is another problem that should be fixed first). This basically decouples your plugin code from wordpress itself. You might want to also create a class that offers and interface to any wordpress function you're making use of, so you're not bound to these functions directly and your plugin code stays clean and loosely coupled to wordpress itself. class WordpressSystem { public function registerFilter($name, $plugin, $methodName) { ... do what this needs with WP, e.g. call the global wordpress function to register a filter. } ... } Then add it as a dependency again if your plugin needs the WordpressSystem to perform tasks (which normally is the case): class MyPlugin { ... public function __construct(WordpressSystem $wp, Dictionary $dictionary) ... So to finally wrap this up, only the plugin php file is needed: <?php /* * MyPlugin * * Copyright 2010 by hakre <hakre.wordpress.com>, some rights reserved. * * Wordpress Plugin Header: * * Plugin Name: My Plugin * Plugin URI: http://hakre.wordpress.com/plugins/my-plugin/ * Description: Yet another wordpress plugin, but this time mine * Version: 1.2-beta-2 * Stable tag: 1.1 * Min WP Version: 2.9 * Author: hakre * Author URI: http://hakre.wordpress.com/ * Donate link: http://www.prisonradio.org/donate.htm * Tags: my * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ Namespace MyPlugin; # if your file is named 'MyPlugin.php' this will be 'MyPlugin'. return PluginFactory::bootstrap(basename($plugin, '.php')); class PluginFactory { private static $plugins; public static function bootstrap($pluginName) { $plugin = self::build($pluginName); self::$plugins[] = $plugin; return $plugin; } public static function build($pluginName) { $plugin = NULL; switch($pluginName) { case 'MyPlugin': # Make your plugin work with different Wordpress Implementations. $system = new System\Wordpress3(); $dictionary = new Dictionary(); $plugin = new Plugin($system, $dictionary); } return $plugin; } } class Plugin { /** * @var System */ private $system; /** * @var Dictionary */ private $dictionary; private function __construct(System $system, Dictionary $dictionary) { $this->system = $system; $this->dictionary = $dictionary; } ... The bootstrap method can also take care of registering an autoloader or do the requires. Hope this is useful.
d11022
In PassConfig you specified the prefix to be "mybatis.key" and the String as key According to this, in application.properties your property is expected to be mybatis.key.key (prefix.variablename) in setKey you specified the @Value to take mybatiskey from application.properties property names should be consistent. It is null because most probably you don't have the propery mybatis.key.key in your application.properties file.
d11023
With -Xmx you only specify the Java heap size - there is a lot of other memory that the JVM uses (like stack, native memory for the JVM, direct buffers, etc.). In our experience the correct size for total usage of the JVM is 1.5 to 2 times the heap size but this depends heavily on your use case (for example some applications using direct buffers may have 32GB of RAM using only 1GB of heap). So run your app with more limits, check the actual usage and then define that + 5% as a container limit. You should also adapt your request to at least 1Gi with -Xms512m.
d11024
I did not see any harm in using two v-for (one for the object keys and another for the array elements) as far as it is all dynamic. You can give a try to this solution by using of Object.keys() : new Vue({ el: '#app', data: { tabs: { first: [{ name: 'tab1' }, { name: 'tab2' }], second: [{ name: 'tab3' }], } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div id="tabs"> <div v-for="tab in Object.keys(tabs)" :key="tab" :id="tab"> <a v-for="tab in tabs[tab]">{{ tab.name }}</a> </div> </div> </div> A: There's no problem using more than one v-for loops. And there's no problem using nested v-for loops. The problem I see with your current code is that it's not scalable. You're hard-coding the exact values of your tabs in <template />(e.g: first, second). The main idea here is to loop through tabs and, inside each tab, to loop through each contents, without the <template> needing to know what the tab is or how many there are. So that when you change your tabs to, say... { tab1: [{ name: 'intro'}], tab2: [{ name: 'tab2-1' }, { name: 'tab2-2' }], tab3: [{ name: 'tab3' }] } template still works, without needing any change. To achieve this type of flexibility, you need to use a nested v-for loop: <div id="tabs"> <div v-for="(items, name) in tabs" :key="name" :id="name"> <a v-for="(item, key) in items" :key="key" v-text="item.name"></a> </div> </div> Demo: new Vue({ el: '#app', data: () => ({ tabs: { tab1: [{ name: 'intro' }], tab2: [{ name: 'tab2-1' }, { name: 'tab2-2' }], tab3: [{ name: 'tab3' }] } }) }) #tabs a { padding: 3px 7px } <script src="https://v2.vuejs.org/js/vue.min.js"></script> <div id="app"> <div id="tabs"> <div v-for="(links, name) in tabs" :key="name" :id="name"> <a v-for="(link, key) in links" :key="key" :href="`#${link.name}`" v-text="link.name"></a> </div> </div> </div> But I'd take it one step further and change the tabs to be an array: data: () => ({ tabs: [ [{ name: 'intro'}], [{ name: 'tab1' }, { name: 'tab2' }], [{ name: 'tab3' }] ] }) And use :id="'tab-' + name" on tab divs if you really need those unique ids. (Hint: you don't). It makes more sense to me. A: You could add a computed property being the .concat from both and loop for it export default { data() { tabs: { first: [{ name: 'tab1' }, { name: 'tab2' }], second: [{ name: 'tab3' }], } }, computed: { tabsCombined () { return this.tabs.first.concat(this.tabs.second) } }, template: ` <div id="tabs"> <div v-for='category in tabsCombined' :id='category' :key='category'> <template v-for="tab in tabs.test"> <a v-if='tab.category === category>{{ tab.name }}</a> </template> </div> </div> ` }
d11025
Actually your example's output is almost correct. It starts with 0 and you need 1, so this should work: colors = red blue orange green yellow li for color, i in colors &:nth-of-type({i + 1}n) background-color: color
d11026
This is probably a bug (and not the only one with this autoplay policy...). When you set the muted attribute through Element.setAttribute(), the policy is not unleashed like it should be. To workaround that, set the IDL attribute through the Element's property: function render() { const video = document.createElement('video'); video.muted = true; video.autoplay = true; video.loop = true; video.setAttribute('playsinline', true); const source = document.createElement('source'); source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4'); video.appendChild(source); document.body.appendChild(video); } render(); As a fiddle since StackSnippets requiring a click event form the parent page are anyway always allowed to autoplay ;-). A: Async, Await, & IIFE After finding this article a couple of months ago, I still couldn't get a consistent autoplay behavior, muted or otherwise. So the only thing I hadn't tried is packing the async function in an IIFE (Immediately Invoked Function Expression). In the demo: * *It is dynamically inserted into the DOM with .insertAdjacentHTML() *It should autoplay *It should be unmuted *All of the above should happen without user interaction. Demo var clip = document.getElementById('clip'); (function() { playMedia(); })(); async function playMedia() { try { await stamp(); await clip.play(); } catch (err) { } } function stamp() { document.body.insertAdjacentHTML('beforeend', `<video id='clip' poster='https://image.ibb.co/iD44vf/e2517.jpg' src='https://storage04.dropshots.com/photos8000/photos/1381926/20181019/182332.mp4' width='100%' autoplay loop playsinline></video>`); }
d11027
You could do it with a circular list. Like so: (defun sin-mac (x series n plus-minus) (cond ((zerop series) 0) (t (funcall (car plus-minus) (/ (power x n) (factorial n)) (sin-mac x (1- series) (+ n 2) (cdr plus-minus)))))) (sin-mac x series 1 '#0=(+ - . #0#)) Or even better, wrap up the initial arguments using labels: (defun sin-mac (x series) (labels ((recur (series n plus-minus) (cond ((zerop series) 0) (t (funcall (car plus-minus) (/ (power x n) (factorial n)) (recur (1- series) (+ n 2) (cdr plus-minus))))))) (recur series 1 '#0=(+ - . #0#)))) A: If the function is a symbol, this is easy: (defun next-function (function) (ecase function (+ '-) (- '+))) (defun sinMac (x series n plusminus) (cond ((= series 0) 0) (t (funcall plusminus (/ (power x n) (factorial n)) (sinMac x (- series 1) (+ n 2) (next-function plusminus)))))) A: I would not swap the function but just the sign. Using a loop for this also seems clearer to me (and is most likely more efficient, although there is still plenty of opportunity for optimization): (defun maclaurin-sinus (x n) "Calculates the sinus of x by the Maclaurin series of n elements." (loop :for i :below n :for sign := 1 :then (- sign) :sum (let ((f (1+ (* 2 i)))) (* sign (/ (expt x f) (factorial f)))))) A few optimizations make this about 10 times faster (tested with n = 5): (defun maclaurin-sinus-optimized (x n) "Calculates the sinus of x by the Maclaurin series of n elements." (declare (integer n)) (loop :repeat n :for j :from 0 :by 2 :for k :from 1 :by 2 :for sign := 1 :then (- sign) :for e := x :then (* e x x) :for f := 1 :then (* f j k) :sum (/ e f sign)))
d11028
It seems your intention is to randomly pick numbers between 1 and 75 without repeating a number. This is most easily done by inverting the problem to randomly ordering the numbers 1-75 then iterating through them: List<Integer> nums = new ArrayList<Integer>(75); for (int i = 1; i < 75; i++) nums.add(i); Collections.shuffle(nums); Now they are in random order, just use them one by one: for (Integer i : nums) { // use i }
d11029
OK, problem sorted. It turns out that the error message actually referred to an XML file referenced by the solution (containing some deployment files). This XML had somehow become corrupted which does fit the message '.', hexadecimal value 0x00. After removing this feature (which didn't need deploying anyway) the problem disappeared so the world can go on being a happy place again (or at least my manager is!) A: I just ran into this after downloading an msbuild file from the internet. Opening the newly downloaded file in a hex editor showed me what the problem was pretty quickly. The file was downloaded with 2 byte characters, and every other byte was a 0. I think Notepad++ said the encoding was UCS-2. In any case, the fix was pretty simple. Notepad++ has an Encoding menu option that I used to rewrite the file as UTF-8. Changing the file back to UTF-8 immediately fixed the problem. Hope this helps people in the future. --Addendum - I might have tried to muck with the file using PowerShell before its encoding changed.
d11030
Your database has int field it will truncate the characters and only consider the numbers that's why you are getting 23 as return id. A: You are quoting the number in your query, so MySQL must convert it from a string to a number. When it does that, it is using only the numeric part of the string. I don't think the behavior is completely appropriate ( "23abcd".ToInt() should be NULL, I think), but that's what it does. A: As Fakhruddin said that int field truncates the value of characters. That's right. But you can prevent wrong values from being inserted in the first place by setting the STRICT_ALL_TABLES mode mysql> SET sql_mode = 'STRICT_ALL_TABLES'; One more thing is that you need to store your id as character strings(VARCHAR) if they contain letters.
d11031
I believe both the methods have its own importance. * *Parcelable is a good choice. But using parcelable you will have to write code for serialization yourself. This method is not encouraged when you are having large number of data members in your class, whose object you want to send. *On the other hand serialization is for sure bulky operation but I think easy to implement. You will have to make your class implements serializable. But still there is one more option, which you can use. You can make your object static and access it from other Activity. if object is not a lot bulky, then this is also good choice. A: If performance is important, then you really should go with Parcelable. JSON will be relatively slow because it is less efficient than Parcelable which was specifically implemented in Android for improving performance when packaging data for Inter-Process Communication.
d11032
You are right about not being able to define a schema for headers. Unfortunately, API Blueprint doesn't support it yet. Until something like that is supported, you can use the literal value for the header like the following: + Headers X-Auth-Token: 2e5db4a3-c80f-4cfe-ad35-7e781928f7a2 API Blueprint also does not support any Traits currently. I am afraid you might have been confused by reading other feature requests.
d11033
You could do something like this: import React from "react"; import ReactDOM from "react-dom"; const resultsContent = (searchValue) => { const Content = (props) => <h1>{searchValue}</h1>; return Content; }; const Content = resultsContent("a"); const rootElement = document.getElementById("root"); ReactDOM.render(<Content />, rootElement); **Also check if you import your ResultsContent with a default import not named import: import ResultsContent from './your-path-to-the-file';**
d11034
I found the work around for this. I was using WAS 8.5 which provides its own JDK which supports JPA 2.0 . @Table.indexes() method was introduced in JPA 2.1 . Solution for this 1)Upgrade WAS to 9 2)Instead of using @Table annotation try using xml mapping . I used ClassName.hbm.xml.
d11035
Ah, look at this: E/AndroidRuntime(589): Caused by: java.lang.NullPointerException 10-06 19:23:12.927: E/AndroidRuntime(589): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 10-06 19:23:12.927: E/AndroidRuntime(589): at org.json.JSONTokener.nextValue(JSONTokener.java:94) 10-06 19:23:12.927: E/AndroidRuntime(589): at org.json.JSONObject.(JSONObject.java:154) 10-06 19:23:12.927: E/AndroidRuntime(589): at org.json.JSONObject.(JSONObject.java:171) 10-06 19:23:12.927: E/AndroidRuntime(589): at com.fansheroid.facts.chicks.MainActivity.getTumblrs(MainActivity.java:156) 10-06 19:23:12.927: E/AndroidRuntime(589): at com.fansheroid.facts.chicks.MainActivity.onCreate(MainActivity.java:62) It basically says the JSON parser fails: you're probably passing NULL on line 156 of MainActivity.java. You should check the value at that line and see if your device upgrade hasn't somehow wiped out a value or failed to retrieve a value correctly. A: try { responseBody = client.execute(get, responseHandler); } catch (Exception ex) { ex.printStackTrace(); } That section of code is where your response is failing. You assign null to responsebody, chances are that your call there is failing so that responsebody is still null when it hits line 156. Try looking in your debug output for the ex.printStackTrace(); output to see what is going on. A: Solved the problem by using HttpResponse and HttpEntity instead of ResponseHandler, and this solved the problem.
d11036
Why not just do this? .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } &--big { padding: 2.5em; } &--big &__value { font-size: 3em; } } A: You can split up the modifiers in a different structure, but nested within the .card selector, like this: .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } &--big { padding: 2.5em; } &--big &__value { padding: 2.5em; } } Which will in turn produce this: .card { padding: 2em; } .card__value { font-size: 1.5em; color: #000; } .card--big { padding: 2.5em; } .card--big .card__value { padding: 2.5em; } I think this is an almost perfect way, although its not perfectly nested I hope this was a help! A: I just found a much better way to achieve this with sass, by using a variable to store the value of the parent selector you can use it at any level of nesting! For example here I am storing the .card selector in the $this variable, and reusing it like this #{$this} So this code .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } $this: &; &--big { padding: 2.5em; #{$this}__value { font-size: 3em; } } } will compile to .card { padding: 2em; } .card__value { font-size: 1.5em; color: #000; } .card--big { padding: 2.5em; } .card--big .card__value { font-size: 3em; } This answer was inspired by this article on css-tricks. Thanks to Sergey Kovalenko A: There is another pattern you could use here. This will: - separate actual card modifier from its elements' modifiers - will keep the modified styles within the same elements' selector so you don't need to scroll your code up and down to see what is being modified - will prevent more specific rules from appearing above less specific rules, if that's your thing Here's an example: // scss .card { $component: &; padding: 2em; &--big { padding: 2.5em; } &__value { font-size: 1.5em; color: #000; #{$component}--big & { font-size: 3em; } } } /* css */ .card { padding: 2em; } .card--big { padding: 2.5em; } .card__value { font-size: 1.5em; color: #000; } .card--big .card__value { font-size: 3em; } A: You can do this by adding ONE character, no variables or mixins are needed. &--big { becomes &--big & {: .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } &--big & { padding: 2.5em; &__value { // Is this going to work? (yes!) font-size: 3em; } } } A: Going through the same issue I've build a library called Superbem which is basically a set of SCSS mixins that help you write BEM declarative way. Take a look: @include block(card) { padding: 2em; @include element(value) { font-size: 1.5em; color: #000; } @include modifier(big) { padding: 2.5em; @include element(value) { font-size: 3em; } } } Gives you: .card, .card--big { padding: 2em; } .card__value { font-size: 1.5em; color: #000; } .card--big { padding: 2.5em; } .card--big .card__value { font-size: 3em; } Hope you'll find this useful! A: Your solution looks quite fine but you may also try @at-root. A: .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } &--big { padding: 2.5em; &__value { // Is this going to work? font-size: 3em; } } } You can achieve the result You wanted by the following : .card { padding: 2em; &__value { font-size: 1.5em; color: #000; } &--big { padding: 2.5em; .card { &__value { // this would work font-size: 3em; } } } }
d11037
I feel dumb, I just had to remove the period in the other answer and add another character class. '(\\[tvrnafb\\]|[^\\'])'
d11038
Try this..selector name is mistake.it should be #pop_up $(document).on("rightclick", "div", function() { alert("hello"); $('#pop_up').css('display','block'); return false; }); DEMO A: Your code is working fine. Just change from $('#popup').css('display','inline-block'); to $('#pop_up').css('display','inline-block'); A: you have wrong id Its pop_up and not popup
d11039
After sleeping on it, I figured it out. I changed RxTextView.textChanges to RxTextView.textChangeEvents. This allowed me to query the CharSequence's text value (using text() method provided by textChangeEvents) even if it's empty. Due to some other changes (not really relevant to what I was asking in this question) I was also able to reduce some of the conditional code too. I'm just putting that out there in case someone comes across this and is curious about these changes. The takeaway is that you can get that empty emission using RxTextView.textChangeEvents. Here is my new Observer: val systemIdDisposable = RxTextView.textChangeEvents(binding.etSystemId) .skipInitialValue() .map { charSeq -> viewModel.isSystemIdValid(charSeq.text().toString()) } .subscribe { binding.systemIdTextInputLayout.error = viewModel.authErrors.value?.systemId } And here is my validation code from the ViewModel: fun isSystemIdValid(systemId: String?): Boolean { val auth = _authErrors.value return if (systemId != null && systemId.isNotEmpty()) { auth?.systemId = null _authErrors.value = auth true } else { auth?.systemId = getApplication<Application>().resources.getString(R.string.field_empty_error) _authErrors.value = auth false } } Lastly, if anyone is curious about how I'm using my LiveData / MutableLiveData objects; I create a private MutableLiveData object and only expose an immutable LiveData object that returns the values of the first object. I do this for better encapsulation / data hiding. Here is an example: private val _authErrors: MutableLiveData<AuthErrorFields> by lazy { MutableLiveData<AuthErrorFields>() } val authErrors: LiveData<AuthErrorFields> get() { return _authErrors } Hope this helps someone!
d11040
According to the ASCII table for the char variable 'e' it seems that corresponds to 65. Lowercase 'e' is 65 HEX. In decimal that would be 101. When you increment it, you get 66 HEX, or 102 decimal. A: Adding to dasblinkenlights's answer...The byte code will give you a clear idea of what is happening behind the scenes : public static void main(java.lang.String...); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS Code: stack=2, locals=2, args_size=1 0: bipush 101 // push decimal value of 'e' 2: istore_1 3: iload_1 4: iconst_1 5: iadd // add 1 to 101 ==> 102 6: i2c // convert 102 to char ==> f 7: istore_1 // store it in the var myLetter 8: return
d11041
Simply don't mention the columns you have no data for. INSERT INTO ('no_data','stuff') VALUES ('','foobar'); becomes INSERT INTO ('stuff') VALUES ('foobar'); Syntax in mysql It's a good rule of thumb to actually log the error when debugging (mysql_error) A good code highliter could help aswell. You are using a column named date. this is however a reserved word used by mysql. change it to date. Or even better change it to a name that tells me more about it. What kind of date? start? end? birthday? ... A: Use this INSERT INTO sickness_details (pnid, dFullName, dposition, dhospital, date) SELECT '$pnid', admins.FullName, admins.position, admins.hospital, NOW() FROM admins WHERE admins.Nid = '$Nid';
d11042
The problem is your approach of solving this. See you are inheriting your image from selenium/standalone-chrome which is supposed to run a Selenium browser. Now is this image you are adding your tests and specifying the CMD to run the tests. When you build and launch this image, you don't get any browser because the CMD has been overridden by you to run the test. When we build in docker we keep dependent services in different containers. It is preferred to run 1 service/process per container in most case. In your case when the test is run the browser server process is missing, so that is the reason for connection refused. So you need to be running two containers here. One for selenium/standalone-chrome and one for your test. Also your image should inherit from node: and not from selenium chrome image. You should not have node -v and npm -v commands also while building images. They create extra layers in your final image FROM node:7 USER root # installing node RUN apt-get update && apt-get install -y curl # Installing Yarn RUN npm install -g -y yarn ENV PATH $PATH:/usr/local/bin/yarn #copying files WORKDIR /app COPY . . # debug #installing yarn RUN yarn install RUN yarn CMD yarn test Now you need to create a docker-compose file to run a composition which has both your test and chrome version: '3' services: chrome: image: selenium/standalone-chrome tests: build: . depends_on: - chrome Install docker-compose and run docker-compose up command to run the above composition. Also in your tests make sure to use the URL as http://chrome:4444/wd/hub and use the Remote webdriver and not the local driver. A: i used a selenium/node-chrome image, but what resolved it was making sure my chromedriver + selenium server + nightwatch were set to the latest versions in my package.json
d11043
Open User Accounts by clicking the Start button , clicking Control Panel, clicking User Accounts and Family Safety (or clicking User Accounts, if you are connected to a network domain), and then click User Accounts. In the left pane, click References. Click the password that you want to remove, and then click Remove.
d11044
Well t is a date, so of course it doesn't contain any time data. You have to use datetime.timetuple(datetime.now()) to have those fields populated. A: I have tried this in my console and get the following results: from datetime import datetime, date date.timetuple(datetime.now()) >>> time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1) datetime.timetuple(datetime.now()) >>> time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=13, tm_min=23, tm_sec=34, tm_wday=1, tm_yday=165, tm_isdst=-1) A: >>> from datetime import datetime >>> datetime.timetuple(datetime.now()) time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=18, tm_min=25, tm_sec=20, tm_wday=1, tm_yday=165, tm_isdst=-1) >>> from datetime import date >>> date.timetuple(datetime.now()) time.struct_time(tm_year=2011, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=165, tm_isdst=-1) this is my result. A: this should work: t = datetime.timetuple(datetime.now())
d11045
Use metadata with a key of X-Goog-Api-Key. See this other answer. If you have API restrictions, you may need additional headers. For example, an iOS example mentioned a bundle id restriction.
d11046
I think Item renderers are your best option, you can use a canvas as your renderer and do whatever to it based on the data of that cell.
d11047
This happens when you try to submit to a domain different than your AMP site. You need to whitelist your AMP domain on your server to enable CORS or contact Administrator if it's a shared hosting for your AMP domain to be whitelisted for CORS. Read further about CORS on AMP. Also check out specs on CORS Whitelisting.
d11048
.removeClass and .addClass are jQuery functions. You need to use .classList.add and .classList.remove // Plus/Minus Toggle function toggle_plus(id) { var f = document.getElementById(id); if (f.classList.contains("showplus")) { f.classList.remove("showplus"); f.classList.add("showminus"); } else { f.classList.remove("showminus"); f.classList.add("showplus"); } } // Toggle to show and hide content below the link function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') { e.style.display = 'none'; } else { e.style.display = 'block'; } } .showminus:before { content: '-'; } .showplus:before { content: '+'; } <div class="teamdetail"> <a href="javascript:void(0)" onclick="toggle_visibility('team4'); toggle_plus('team4Plus');">More Details [<span id="team4Plus" class="showplus"></span>]</a> </div> <div id="team4" class="teamtxt"> Text Goes Here </div> A: In addition to Dave's answer (I don't have enough rep to comment :/), toggle is your friend. // Plus/Minus Toggle function toggle_plus(id) { var f = document.getElementById(id); f.classList.toggle("showplus"); f.classList.toggle("showminus"); } Will do the same. Also, the Chrome inspector console is your friend - it would've been throwing up errors to you. https://developers.google.com/web/tools/chrome-devtools/console/
d11049
You could build your own dependency injection module. Using NodeJs it's fairly simple to do. This one for instance.
d11050
Have a look at these for some pointers: MySQL Group By with top N number of each kind http://explainextended.com/2009/03/06/advanced-row-sampling/ A: This is what i ended up using. recent_video_viewers is the name of the view I made so i didn't have to do any joins SELECT id, MAX(date), user_id, img_key, random_key FROM recent_video_viewers WHERE video_id = '$vr[id]' AND img_key != '' GROUP BY user_id ORDER BY MAX(date) DESC LIMIT 18 I'm not sure if this is the best way to do this but it works. A: Here is a query that works. It assume that you need logs only for a given video id (@video_id): SELECT log_date, user_id, name_display FROM ( SELECT MAX(l.date) AS log_date, user_id FROM log_views AS l WHERE (l.video_id=@video_id) GROUP BY user_id ORDER BY log_date DESC LIMIT 18 ) AS top INNER JOIN users AS u ON (u.user_key=top.user_id)
d11051
Try to change your HttpGet with HttpPost since your rest service answer to a POST request.
d11052
Action has to be dispatched like below. Let me know if it works const mapDispatchToProps = (dispatch) => { return { onClearCart: () => (dispatch(clearCart())) } };
d11053
Not sure what exactly you are trying to achieve, but you can change your RelativeLayout height to android:layout_height="match_parent" Also have a look at docs for android:fitsSystemWindows="true". Hope this helps.
d11054
Your problem is right here: var words = <%= submission.content %>.split(' '); That will dump your submission.content value into your JavaScript without any quoting so you'll end up saying things like: var words = blah blah blah.split(' '); and that's not valid JavaScript. You need to quote that string and properly escape it: // You may or may not want submission.content HTML encoded so // you might want submission.content.html_safe instead. var words = '<%=j submission.content %>'.split(' '); Or better, just do it all in Ruby rather than sending a bunch of throw-away text to the browser: <script type="text/javascript"> var wordCount = <% @folder.submissions.map { |s| submission.content.split.length }.sum %> console.log(wordCount); </script> That assumes that your JavaScript .split(' ') is really intended to split on /\s+/ rather than just single spaces of course.
d11055
If you run import urllib2 url = 'https://www.5giay.vn/' urllib2.urlopen(url, timeout=1.0) wait for a few seconds, and then use C-c to interrupt the program, you'll see File "/usr/lib/python2.7/ssl.py", line 260, in read return self._sslobj.read(len) KeyboardInterrupt This shows that the program is hanging on self._sslobj.read(len). SSL timeouts raise socket.timeout. You can control the delay before socket.timeout is raised by calling socket.setdefaulttimeout(1.0). For example, import urllib2 import socket socket.setdefaulttimeout(1.0) url = 'https://www.5giay.vn/' try: urllib2.urlopen(url, timeout=1.0) except IOError as err: print('timeout') % time script.py timeout real 0m3.629s user 0m0.020s sys 0m0.024s Note that the requests module succeeds here although urllib2 did not: import requests r = requests.get('https://www.5giay.vn/') How to enforce a timeout on the entire function call: socket.setdefaulttimeout only affects how long Python waits before an exception is raised if the server has not issued a response. Neither it nor urlopen(..., timeout=...) enforce a time limit on the entire function call. To do that, you could use eventlets, as shown here. If you don't want to install eventlets, you could use multiprocessing from the standard library; though this solution will not scale as well as an asynchronous solution such as the one eventlets provides. import urllib2 import socket import multiprocessing as mp def timeout(t, cmd, *args, **kwds): pool = mp.Pool(processes=1) result = pool.apply_async(cmd, args=args, kwds=kwds) try: retval = result.get(timeout=t) except mp.TimeoutError as err: pool.terminate() pool.join() raise else: return retval def open(url): response = urllib2.urlopen(url) print(response) url = 'https://www.5giay.vn/' try: timeout(5, open, url) except mp.TimeoutError as err: print('timeout') Running this will either succeed or timeout in about 5 seconds of wall clock time.
d11056
file management is not a normal process. I strongly advise you to use the branch flow. For your example, use develop branch(DevParam) for an all your developers and master branch for a prod Try to use the follows advice. The developers are coding in the dev branch. Each developer working only this branch. You should create the build configuration with the trigger to your dev branch. After each new commit, the configuration will be triggered. If you decided that the code in the dev branch is ready to production, you just merged all to the master. And now you can also trigger the same configuration only for a master branch. For more information about gitflow-workflow read this
d11057
Have a look at the plugins provided by e(fx)clipse: http://www.efxclipse.org/
d11058
do u mean this? <div ng-repeat="item in items | filter1 | filter2"> more info here http://docs.angularjs.org/guide/dev_guide.templates.filters.using_filters EDIT: now i got that u didnt wrote filters but scope function, u need something like this myModule.filter('iif', function () { return function (input, trueValue, falseValue) { return input ? trueValue : falseValue; }; }); my use is class="{{ catalogItem.IS_FINAL | iif : 'IsFinalCatalogItem' : '' }}" should look like this myModule.filter('prodClassIsALine', function() { return function(item) { return item.level_type=='line'; }; }); p.s. in angular 1.2 they added the standard iif syntax
d11059
If you know what cell it is, then you could do something like this; TableCell tc = GridView1.Cells[indexOfCell]; // where GridView1 is the id of your GridView and indexOfCell is your index foreach ( Control c in tc.Controls ){ if ( c is YourControlTypeThatYouKnow ){ YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow)c; } } If you don't know what cell it is exactly, then you can always loop through each cell. I am sure there is a better way in Linq. With Linq (I think this should work) var controls = GridView1.Cells[indexOfCell].Cast<Control>(); YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow) controls.Where( x => x is YourControlTypeThatYouKnow).FirstOrDefault(); A: On ItemDataBound event handler of GridView, access the table-cell as follows. Within the cell, Controls collection provides you access to ASP control embedded in the cell TableCell cell = e.Item.Cells[0]; if (cell.Controls.Count > 0) { cell.Controls[0].Visible = false; } A: I have had the same problem. Add a command name to your field like CommandName="ProjectClick". Then add a rowcommand and in the row command do this: if (e.CommandName.Equals("ProjectClick")) { } or you can use the text: if (e.CommandName.Equals("")) { if (((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text.Equals("Projects")) { } }
d11060
To acces path to the desktop use: Environment.GetFolderPath(Environment.SpecialFolder.Desktop) A: After you've obtained the desktop location (as Garath has pointed out in his answer), check out File.Move in the System.IO namespace. e.g File.Move(path, path2); http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx
d11061
Make form with display: inline-block: .container form, /* added */ .container ul{ display: inline-block; /* fixed */ }
d11062
It doesn't matter The compiler will convert statements like that to (what it thinks, and often is) their most efficient form. I'd recommend you write statements like this in the same way as the rest of your code base in order to keep consistency. If you are just doing your own thing on a personal project you can either do what you prefer or what is common for your particular language. A: It does not matter, the performance is the same. In 1978 when C was invented these would map to different PDP-11 instructions, resulting in faster performance of ++ and +=. These days, however, the operations are optimized into the same exact sequences of instructions.
d11063
I usually get this error when all I am doing is swapping view in xml layout. It is a ecllipse bug(sometimes) when and as a result your resource is not synced with the adt builder. When I get his error first thing I do is close ecllipse, end process adb.exe from task manager(windows) and then start ecllipse again. If this doesnot help then Android tools -> fix project properties and project -> clean. A: android.widget.RadioGroup cannot be cast to android.widget.Button * *Your XML contains a RadioGroup item *Your Fragment class is getting that item with findViewById and tries to cast it as a Button. Like that for instance: Button btn = (Button) getView().findViewById(r.id.myRadioButton); You'll need to either change your XML to make that a element or to change your fragment to get a RadioGroup variable: RadioGroup grp = (RadioGroup) getView().findViewById(r.id.myRadioButton); A: The problem is that you are trying to cast a RadioGroup to a Button, which you can't do. This is happening in MainActivity. Post the code for MainActivity if you can't find the problem. A: As I suspected, I don't see any invalid casting going on. My guess is that you're receiving this error because there is some disconnect between what has been deployed and what you've got built in your IDE. R.java is probably stale. You need to clean (remove bin, gen, lib, obj directories) and rebuild your project. Here's a similar post where this same thing happened: Android ClassCastException for RadioGroup into RadioButton Their issue was resolved by shutting down the emulator and restarting the IDE. A: this is simple one! I had came across this once. It seems quite baffling & frustrating at first, but the only thing you need to do is help eclipse get aware of the fact that the position and layout of a few (or all) components have been modified/altered. And this you are supposed to achieve by building the work space from scratch. For that all you need to do is close and restart eclipse. That'll do.
d11064
Rather than calling the raise_exception outside the class, calling it from within the run method for the thread will work. Ex. def run(self): if count>3: self.raise_exception()
d11065
You are only asking for messages the user sent. You need to also get messages that the user received. $user = auth()->user()->id; $messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get(); $receivedMessages= Message::where('sender_id', recipient_id)->where('recipient_id', $user)->get();
d11066
For me this template is deploying fine using the SAM cli. May you try to update your SAM cli? And also check if you have permissions to create Eventbridge events?
d11067
Commented code: /* a = ptr to sub-array */ /* 0 = starting index */ /* m = mid point index */ /* n = ending index */ /* left half indices = 0 to m-1 */ /* right half indices = m to n */ void merge (int *a, int n, int m) { int i, j, k; int *x = malloc(n * sizeof (int)); /* allocate temp array */ for (i = 0, j = m, k = 0; k < n; k++) { x[k] = j == n ? a[i++] /* if end of right, copy left */ : i == m ? a[j++] /* if end of left, copy right */ : a[j] < a[i] ? a[j++] /* if right < left, copy right */ : a[i++]; /* else (left <= right), copy left */ } for (i = 0; i < n; i++) { /* copy x[] back into a[] */ a[i] = x[i]; } free(x); /* free temp array */ } /* a = ptr to sub-array */ /* n = size == ending index of sub-array */ void merge_sort (int *a, int n) { if (n < 2) /* if < 2 elements nothing to do */ return; int m = n / 2; /* m = mid point index */ merge_sort(a, m); /* sort a[0] to a[m-1] */ merge_sort(a + m, n - m); /* sort a[m] to a[n-1] */ merge(a, n, m); /* merge the two halves */ }
d11068
I think you can get around this by rewriting things slightly: foreach (QueryOver subQuery in subQueries) { query.Where( Restrictions.EqProperty( Projections.Property<Customer>(c => c.CustomerID), Projections.SubQuery(subQuery.DetachedCriteria))); } I don't know enough about your subqueries to say, but you might be able to use a List<QueryOver<Customer>> instead. The issue is that .WithSubquery...In requires a QueryOver<U> where your list is the non-generic base type (QueryOver). A: I've managed to solve this with a little refactoring. Andrew's response gave me the idea to use .Where() (instead of .WithSubquery) and then use a Conjunction for the sub queries. The refactored code looks like this: Conjunction conj = new Conjunction(); conj.Add(Subqueries.WhereProperty<Customer>(x => x.CustomerID).In(QueryOver.Of<Customer>()...)); conj.Add(Subqueries.WhereProperty<Customer>(x => x.CustomerID).In(QueryOver.Of<AttributeValue>()...)); conj.Add(Subqueries.WhereProperty<Customer>(x => x.CustomerID).In(QueryOver.Of<CustomerListEntry>()...)); ISession session = sf.OpenSession(); using (var tran = session.BeginTransaction()) { var query = session.QueryOver<Customer>() .Where(conj) .Select(Projections.RowCount()) .FutureValue<int>() .Value; tran.Commit(); } I can now programatically build up and selectively apply the subqueries.
d11069
Some minimal information available with me is posted below. I don't know much of Java. But as far as 'C' is concerned, you can use the getsockopt function to get the buffer sizes (send buffer and recv buffer) of the socket. It appears getsockname helps you in getting the ip & port to which the socket is bound to. A: In c in the function accept: csock = accept(sock, (struct sockaddr*)&csin, &recsize); * *sock is the socket server(int) *csock is the socket client (int) *recsize is the size *csin is a struct with client's details * *csin.sin_addr is the client's address *csin.sin_port is the client's port From a socket ID try this: #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> f() { int s; struct sockaddr_in sa; int sa_len; . . . /* We must put the length in a variable. */ sa_len = sizeof(sa); /* Ask getsockname to fill in this socket's local */ /* address. */ if (getsockname(s, &sa, &sa_len) == -1) { perror("getsockname() failed"); return -1; } /* Print it. The IP address is often zero beacuase */ /* sockets are seldom bound to a specific local */ /* interface. */ printf("Local IP address is: %s\n", inet_ntoa(sa.sin_add r)); printf("Local port is: %d\n", (int) ntohs(sa.sin_port)); . . . }
d11070
You can do it like this: * *Just create the separate web-service on server side which have parameter as app version. *Set the global variable on server side which holds the latest version of the app. *Now, from your application, when app will be launched, then call this service with the parameter of api version used in the app. (this api version will be static, because you have done the code for same. And when you will update your app then you will change the api code yourself. Hope you understand). *Check the api version on server side, and if app api using latest version then return TRUE. And if api on app using lower version then return FALSE. *Now, in application, if web-service returns the FALSE then just inform the user by ALERT that, he is using the lower version of the api and download latest app to use the latest api. Hope, you got an idea of what to do. Cheers.
d11071
One solution could be to just append the file to the second file. You should consider using variables for the file paths instead of copy-paste. Also, the name of the files is a bit confusing. output5.close() output6.close() with open(r"E:\test2\output5.txt", 'a') as output5: with open(r"E:\test2\output6.txt", "r") as output6: output5.write(output6.read()) Relevant question about appending files Here is a explanation of how you can use the with statement Also, instead of writing the content directly to the files in the if statement, why not just store it into strings? Then in the end you could write it to a file. If you try to read from a file, before closing it, the text won't show up. You can try the snippet below. output5 = open(r"Test", "w") output5.write("Foo") output6 = open(r"Test", "r") print(output6.read())
d11072
If you create the data as an array in your controller, then pass it back with json_encode() and render the output on the client-side, I think it is more what you are looking for. I excluded the Model, because it doesn't need to change, and the unchanged part of your jquery is omitted before/after the ... Javascript: ... function load_data(query) { $.ajax({ url:"<?php echo base_url(); ?>ajaxsearch/fetch", method:"POST", data:{query:query}, success:function(json){ handleOutput(json); } }); } function handleOutput(json) { var output = '<div class="table-responsive"><table class="table table-striped"><tr><th scope="row" >Channel Number</th><th scope="row">Channel Name</th></tr>'; if (json.length == 0) { // if no data is returned output += '<tr><td colspan="5">No Data Found</td</tr>'; } else { // if data isn't returned json.forEach(function(row) { output += '<tr><td>'+row['nr']+'</td><td>'+row['naam']+'</td></tr>'; } } output += '</table></div>'; $('#result').html(output); } ... Controller: class Ajaxsearch extends CI_Controller { function index() { $this->load->view('ajaxsearch'); } function fetch() { $query = ''; $this->load->model('ajaxsearch_model'); if($this->input->post('query')) { $query = $this->input->post('query'); } $data = $this->ajaxsearch_model->fetch_data($query); $retval = array(); if($data->num_rows() > 0) { $retval[] = array( "nr" => $row->nr, "naam" => $row->naam ); } return json_encode($retval); } } Note: I condensed your code a bit. Hopefully, it is still easily read/understandable.
d11073
Set its background to light red. This is what Adium does when you go over the message length limit in a Twitter tab. The specific color Adium uses is: * *Hue: 0.983 *Saturation: 0.43 *Brightness: 0.99 *Alpha: 1.0 as a calibrated (Generic RGB) color. A: What about shaking the text field while making it slightly red? It may or may not work well in practice, but its used in the login field for both MobileMe and user switching on OS X. A: I like the Windows solution and implemented a small tooltip popup myself. I don't think that just changing colors doesn't will work. A textual explaination is often required too. Unfortunately MacOSX removed the balloon tips from old MacOS.
d11074
When I had this problem, i solved it by switching the order of the libraries. <script src="/bower_components/angular/angular.min.js"></script> ... <script src="/bower_components/jasmine/lib/jasmine-core/jasmine.js"></script> <script src="/bower_components/jasmine/lib/jasmine-core/jasmine-html.js"></script> <script src="/bower_components/jasmine/lib/jasmine-core/boot.js"></script> <script src="/bower_components/angular-mocks/angular-mocks.js"></script> ... then the tests e.g. <script src="/js/lib/sync/test/local-test.js"></script> Also I import all of them at the end of the <body>.
d11075
Sorry if I am late to the party. This works for me: services.AddMvc(options => { options.OutputFormatters.RemoveType(typeof(JsonOutputFormatter)); options.InputFormatters.RemoveType(typeof(JsonInputFormatter)); options.ReturnHttpNotAcceptable = true; }) .AddXmlSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); A: Use MVC input and output formatters: services.AddMvc(configure => { // remove JSON formatter var outputFormatters = configure.OutputFormatters; var jsonOutputFormatter = outputFormatters.First(f => f is JsonOutputFormatter); outputFormatters.Remove(jsonOutputFormatter); var inputFormatters = configure.InputFormatters; var jsonInputFormatter = inputFormatters.First(f => f is JsonInputFormatter); inputFormatters.Remove(jsonInputFormatter); }).AddXmlSerializerFormatters()
d11076
wxWidgets doesn't support overlapping child controls, so you would need to use a different top level window for your floating control, typically a wxPopupWindow -- then you could either draw your text in it or make wxStaticText its child.
d11077
One way of doing it is by including your site on the Enterprise Mode Site List so it will open in IE11 automatically: The steps and the details can be found in this blog post by the Microsoft Edge team: http://blogs.windows.com/msedgedev/2015/08/26/how-microsoft-edge-and-internet-explorer-11-on-windows-10-work-better-together-in-the-enterprise/
d11078
A slightly different perspective on the great answer by Josh C: as it happens both the client authentication and the grant credentials can be expressed as JWTs but the semantics behind them are different. It is about separation of concerns: clients authenticate with a credential that identifies them i.e. they are the so-called subject whereas they use grants that were issued to them i.e. they are the so-called audience. Or as version 12 of the draft spec (https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-bearer-12) says: *The JWT MUST contain a "sub" (subject) claim identifying the principal that is the subject of the JWT. Two cases need to be differentiated: A. For the authorization grant, the subject typically identifies an authorized accessor for which the access token is being requested (i.e., the resource owner or an authorized delegate), but in some cases, may be a pseudonymous identifier or other value denoting an anonymous user. B. For client authentication, the subject MUST be the "client_id" of the OAuth client. A: Probably very little. The way a client is identified and the way auth grants are requested are two different notions in OAuth, so the questions address those notions separately: * *Can a client authenticate with an authorization server using a JWT? Yes. *Can a client make a grant request using a JWT? Yes. The spec seems to hint that the separation is simply a design decision, deferring to policy makers to find what scenarios are valuable to them: The use of a security token for client authentication is orthogonal to and separable from using a security token as an authorization grant. They can be used either in combination or separately. Client authentication using a JWT is nothing more than an alternative way for a client to authenticate to the token endpoint and must be used in conjunction with some grant type to form a complete and meaningful protocol request. JWT authorization grants may be used with or without client authentication or identification. Whether or not client authentication is needed in conjunction with a JWT authorization grant, as well as the supported types of client authentication, are policy decisions at the discretion of the authorization server. One concrete possibility: The separation could allow for an authorization server to set up different policies along client types. For example, in the case of a public client (like a mobile app), the server should not accept the client creds grant type. Instead, the server could accept the JWT grant type for public clients and issue a token of lesser privilege. Other than that, I would suppose that the design simply offers a degree of freedom for clients and servers to pivot around--keep this part of the existing handshake the same while migrating this part--as the need arises.
d11079
Put a $ at the end of your pattern: -match ".vhdx?$" $ in a Regex pattern represents the end of the string. So, the above will only match .vhdx? if it is at the end. See a demonstration below: PS > 'foo.vhd' -match ".vhdx?$" True PS > 'foo.vhdx' -match ".vhdx?$" True PS > 'foo.vhdxxxx' -match ".vhdx?$" False PS > Also, the . character has a special meaning in a Regex pattern: it tells PowerShell to match any character except a newline. So, you could experience behavior such as: PS > 'foo.xvhd' -match ".vhdx?$" True PS > If this is undesirable, you can add a \ before the . PS > 'foo.xvhd' -match "\.vhdx?$" False PS > This tells PowerShell to match a literal period instead. A: If you only want to check extension, then you can just use Extension property instead of Name: $NEWEST_VHD = Get-ChildItem -Path $vhdSourceDir | Where-Object Extension -in '.vhd','.vhdx' A: Mostly just an FYI but there is no need for a regex solution for this particular issue. You could just use a simple filter. $NEWEST_VHD = Get-ChildItem -Path $vhdSourceDir -Filter ".vhd?" Not perfect but if you dont have files called ".vhdz" then you would be safe. Again, this is not meant as an answer but just useful to know. Reminder that ? in this case optionally matches a single character but it not regex just a basic file system wildcard. Depending on how many files you have here you could argue that this would be more efficient since you will get all the files you need off the get go instead of filtering after the fact.
d11080
In your first code, when you use Object.assign, the parameters past the first have their getters invoked: Object.assign( {}, { get foo() { console.log('getter invoked'); } } ); So, your get maxRowLength is running immediately, before you're even declaring the m array - and when the getter is invoked, it calls this.max, and at that point, this is the second argument you're passing to Object.assign, which is that object - which doesn't have a .map method, resulting in the error. Here's another more minimal example of your code to show what's going on: const objectToAssign = { max() { // `this` is the object here console.log(this === objectToAssign); }, get maxRowLength() { return this.max(); }, }; Object.assign(Array.prototype, objectToAssign); A: Yesterday when I was reading the book JavaScript: The Definitive Guide, 7th Edition, I suddenly came across a listing of code in that book (Section 14.1: Property Attributes) that happened to be dedicated exactly to my original problem, so I think maybe I should list it here for future reference or maybe someone may need it: /***************************************************************** * Object.assignDescriptors() * ***************************************************************** * * • copies property descriptors from sources into the target * instead of just copying property values. * * • copies all own properties (both enumerable and non-enumerable). * • copies getters from sources and overwrites setters in the target * rather than invoking those getters/setters. * * • propagates any TypeErrors thrown by `Object.defineProperty()`: * • if the target is sealed or frozen or * • if any of the source properties try to change an existing * non-configurable property on the target. */ Object.defineProperty(Object, "assignDescriptors", { // match the attributes of `Object.assign()` writable : true, enumerable : false, configurable: true, // value of the `assignDescriptors` property. value: function(target, ...sources) { for(let source of sources) { // copy properties for(let name of Object.getOwnPropertyNames(source)) { let desc = Object.getOwnPropertyDescriptor(source, name); Object.defineProperty(target, name, desc); } // copy symbols for(let symbol of Object.getOwnPropertySymbols(source)) { let desc = Object.getOwnPropertyDescriptor(source, symbol); Object.defineProperty(target, symbol, desc); } } return target; } }); // a counter let counter = { _c: 0, get count() { return ++this._c; } // ⭐ getter }; // ---------------------------------------------------------- // ☢️ Alert: // Don't use Object.assign with sources that have getters, // the inner states of the sources may change❗❗❗ // ---------------------------------------------------------- // copy the property values (with getter) let iDontCount = Object.assign({}, counter); // ☢️ `counter.count` gets INVOKED❗❗❗ counter._c === 1 (polluted)❗❗❗ // copy the property descriptors let iCanCount = Object.assignDescriptors({}, counter); [ counter._c, // 1 (☢️ polluted by Object.assign❗) // ⭐ `iDontCount.count` is a "data" property Object.getOwnPropertyDescriptor(iDontCount, 'count'), // { // value: 1, <---- ⭐ data property // writable: true, enumerable: true, configurable: true // } iDontCount.count, // 1: just a data property, iDontCount.count, // 1: it won't count. // ⭐ `iCanCount.count` is an "accessor" property (getter) Object.getOwnPropertyDescriptor(iCanCount, 'count'), // { // get: [Function: get count], <---- ⭐ accessor property // set: undefined, // enumerable: true, // configurable: true // } // ☢️ although it can count, it doesn't count from 1❗ iCanCount.count, // 2: it's a getter method alright, but its "count" iCanCount.count, // 3: has been polluted by Object.assgin() ☢️ ].forEach(x => console.log(x))
d11081
The error message "The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page." would point to a data related problem: I would assume on the server, there is some data that is larger than the target column allows, but this is not there in your development environment. E. g. a string of length 23 and your column crFlgActive has an SSIS DT_STR data type of length 20. One way to find the data causing problems would be to configure the destination component to redirect records causing problems instead of failing. The redirection could be to a table, or maybe even just a CSV or Excel file.
d11082
If you're not planning to change the contents of PROPERTYOPTIONS at runtime, you can mark it as immutable (as const) and define a type alias for it using typeof: export const PROPERTYOPTIONS = [ { value: 'tag', label: 'Tag' }, { value: 'composition', label: 'Composition' }, { value: 'solvent', label: 'Solvent' }, { value: 'allergen', label: 'Allergen' }, { value: 'category', label: 'Category' }, { value: 'other', label: 'Other' }, ] as const type PropertyOptions = typeof PROPERTYOPTIONS type PropertyOption = PropertyOption[number] interface CreatePropertyModalState { // if the type should be exactly one of the options type: PropertyOption, // if you want to combine an allowed value with an arbitrary label type: { value: PropertyOption['value'], label: string }, } A: You can use a generic identity function to constrain the type of the array, and then typeof with an indexed access type to extract the type you want. function checkArray<T extends string>(arr: {value: T, label: string}[]) { return arr; } export const PROPERTY_OPTIONS = checkArray([ { value: "tag", label: "Tag" }, { value: "composition", label: "Composition" }, { value: "solvent", label: "Solvent" }, { value: "allergen", label: "Allergen" }, { value: "category", label: "Category" }, { value: "other", label: "Other" }, ]); type PropertyOption = typeof PROPERTY_OPTIONS[number] // type PropertyOption = { // value: "tag" | "composition" | "solvent" | "allergen" | "category" | "other"; // label: string; // } interface CreatePropertyModalState { type: PropertyOption } Playground Link
d11083
You can of course update the whole transparent EF with the FF pattern using the UPDATE BINARY command. Depending on on the size of the file and the supported data field length of your card / reader you may have to send more than one command and specify the offset from where on to update. If the transparent EF is larger than 32 KByte, you have to use the UPDATE BINARY with odd INS code and give the offset and data to update in their respective data object. If your card supports the ERASE BINARY command, you could use that instead. Have a look here for a description of the BINARY commands.
d11084
The .nextLine() is getting the '\n' character trailing the integer. Fix this by adding keyboard.nextLine() after the .nextInt(). As follows: Scanner keyboard = new Scanner(System.in); // prompt the user input for a number int a = keyboard.nextInt(); // prompt the user input for a string keyboard.nextLine(); // This captures the '\n' character trailing the integer String str = keyboard.nextLine();
d11085
Database database database. Make sure you can add more db servers without lots of pain. Adding app servers is usually fairly straightforward, but DB replication/clustering can get tricky. A: It depends. It depends on how your application is used. You cannot tell until you know how many users will do concurrent requests. Most of the time it will be your database, depending on how many requests per second it can manage. So if you know your application patterns (read intensive or write intensive) you can design it for easier scaling. Would it be enough to just do replication? A: Your problem from day 1 will be the time taken for the client to download the content from your server. CDN's, minification and combining assets should be a primary concern. (Un)fortunatly, unless you go Google, you won't become big enough to require multiple application, database servers (no offence). A: A couple suggestions: 1) Since you said read write intensive you need to decide how you will be structuring your database to be more read or write friendly. What will be happening most often. If it is reads then indexes are your friend. If it is writes then be careful of going index crazy. 2) On the client side be careful of writing to the live DOM too often. If you need to do do a lot of loads of say table rows, load them into a parent element in memory and then load that parent element into the DOM all at once. A: You may take a look at http://ilian.i-n-i.org/tag/cache/ there are three articles about caching and how it will help your website. As for the scales well... are you sure that your application needs it? Do not get me wring, it is awesome to have multiple database servers, CDN, load balancers etc. but do you really need it? If you are starting a new project you should focus on providing a stable features more than optimizing it for a million hits per day cause you are probably not going to make them(at least in the beginning). Start with caching, it is easy to implement and effective if it is correctly used. When your visitors get so much that you reach the bottle necks think for them then but not earlier. The above does not mean that you should write the slowest code that is possible. It only means that the need for extreme scalability comes when you have working application and that if you waste 1 year and a ton gold to build it probably you will miss the moment.
d11086
The suitable representation depends on what operations is desired on the sparse array. The general approach is to store the locations of non-zero items and their values in a data structure. One option is to use a hash table. enum {NumDimensons = 4}; struct ArrayLocation { int16_t location[NumDimensions]; }; typedef uint8_t ArrayValue; // Hash Table with key as ArrayLocation and value as ArrayValue With hash table operations like get() and put() are straightforward, but iteration is not. If iteration is important, one option is to use a binary search tree.
d11087
I finally used the event : SOLine_UOM_FieldUpdated. Everything works perfectly, including the webservices protected void SOLine_UOM_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e) { var row = (SOLine)e.Row; row.CuryUnitPrice=tmp; }
d11088
I don't think its possible to do what I asked at this point, but if you keep it local, you can do something similar and have more flexibility. The best thing to do is load the contents you need inside the local page. In my case, I need the whole site, including all things in the head, so I used an iframe. Keep in mind that the iframe won't be able to access the window above due to different domains, so what I did was setup an onload event in the local page to check the iframe changes. When it had the URL I was looking for, I would handle differently and load a different page in the local app. Here is an example. I am using jQuery with this and setup so that the URL's to check for are /app/LOCALPAGEPATH. So if the URL found is /app/index.html it would go to index.html. $('iframe').load(function(){ var url = $(this).get(0).contentWindow.location.href; var appIndex = url.indexOf('/app/'); if (appIndex > -1) { var appURL = url.substr(appIndex+5); window.location.href = appURL; } }); A: You can make your close button execute window.history.go(-(window.history.length - 1)); That should go back to the local index.html as it was the first page it loaded.
d11089
You can do this with cucumber's Before and After hooks. Just disable VCR using something like this: Before('@live') do VCR.eject_cassette VCR.turn_off! end This may be dependent on exactly how you are integrating VCR with your cucumber tests though.
d11090
You have to use event delegation using jQuery's on() method. From its documentation: When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector. In your case, you'll need to delegate the .btn click event to an ancestor which exists prior to that element being dynamically added to the page: $('body').on('click', '.btn', function() { var number1 = $('#s2').val(); alert(number1); }); The closer you get to the .btn element, the better, so unless your document's body is the nearest non-dynamic ancestor then you'll want to change this to something a bit closer. Edit: Further question in comments: can I get the ID of each button To get the id of each button, simply use this.id: $('body').on('click', '.btn', function() { var id = this.id; alert(id); }); Edit 2: Further question in comments So as I said,ID are numbers.So if i click button1 then it will print s1 in the inputfield.Can you please tell me how to do? As your input has an id of "number", you can simply use jQuery's .val() method to set the value of the input to the id of the clicked button: $('body').on('click', '.btn', function(){ $('#number').val(this.id); }); Working JSFiddle demo. A: $(document).on('click', '.btn', function(){ alert($(this).val()); }); Should work. The "on" is a way of working with dynamically placed elements. A: Put value attribute in button input <button type="button" class="btn" value="test2" >test</button> <button type="button" class="btn" value="test1" id="s1">test</button> <button type="button" class="btn" value="test" id="s2">test</button> And then use script $('.btn').on('click', function() { var number = $('#s2').val();//get value }); A: If you want to get the id of the clicked button you should use attr: $('.btn').click(function(){ var number1 = $('#s2').attr('id'); alert(number1); });
d11091
Try the below code. $email_config = Array( 'protocol' => 'smtp', 'smtp_host' => 'bh-24.webhostbox.net', 'smtp_port' => '465', 'smtp_user' => 'feedback@domain.com', 'smtp_pass' => '12feedback34', 'mailtype' => 'html', 'starttls' => true, 'newline' => "\r\n" ); $this->load->library('email', $email_config); $this->email->from($to, 'FEEDBACK'); $this->email->to('feedback@domain.com'); $this->email->subject($sub); $this->email->message($msg); $this->email->send();
d11092
You have to use syscall #12 to read a character. See the MARS syscall sheet for further details. Here goes an example that reads a character from console and prints the next ASCII code char loop: li $v0, 12 syscall # Read Character addiu $a0, $v0, 1 # $a0 gets the next char li $v0, 11 syscall # Write Character b loop nop
d11093
(I'm assuming you want to emulate the behavior of the ctrl+c keystroke in a terminal window. If you really mean to send an ETX to the target process, this answer isn't going to help you.) The ctrl+c keyboard combination doesn't send an ETX to the standard input of the program. This can easily be verified as regular keyboard input can be ignored by a running program, but ctrl+c (usually) immediately takes effect. For instance, even programs that completely ignore the standard input (such as int main() { while (1); }) can be stopped by pressing ctrl+c. This works because terminals catch the ctrl+c key combination and deliver a SIGINT signal to the process instead. Therefore, writing an ETX to the standard input of a program has no effect, because the keystroke is caught by the terminal and the resulting character isn't delivered to the running program's standard input. You can send SIGINT signals to processes represented by a NSTask by using the -[NSTask interrupt] method. [task interrupt]; Otherwise, you can also send arbitrary signals to processes by using the kill function (which, mind you, doesn't necessarily kills programs). #include <signal.h> kill(task.processIdentifier, SIGINT);
d11094
Apparently, the action that hides behind your IDE's "reset commit" isn't git reset --mixed, and it resulted in files being deleted from your disk. As said in the comments : you can use the reflog to find past commits. * *run git reflog to spot the sha for commit A (the faulty commit with the 121MB file) *use whatever action you see fit to get files back from that commit : * *git reset A *git checkout A -- file1 file2 *git restore -s A -W -- . or git restore -s A -W -- file1 file2 *...
d11095
The direct answer is the application appear twice because Android Market and Android OS view two different packages as two different applications. The code can be same, but if the packages are different the applications are completely different Android Market identifies applications by their package name. I suspect this is because the OS tracks programs by package...makes sense that you wouldn't want two packages with the exact same name installed, how would the OS know which one to call? Therefore, if you install a package with the same name as a package that's already installed the OS will view it as a package upgrade and let the new program access the old user data. You state that the packages share the same ID, I assume this is user ID. This enables you to share data between the packages. More information is here: http://developer.android.com/guide/topics/security/security.html#userid Recommendation: Release a small upgrade to your old package providing whatever glue is needed to let it share it's data with your new package. Then release your new package with the code to import the user data from the old package (need same UserId and signature). The transition would be seamless to the user (no manual backup and import). A: The application signature must be the same. If you imported the project in another Eclipse, build it and upload it to market you will see 2 separate apps.
d11096
If I correctly understood what disappears (I assume you meant list rows on vertical scrolling), then yes it is due to List reuse/cache optimisation issue. The following approach should work (tested with Xcode 11.2 / iOS 13.2) struct ItemView: View { var body: some View { VStack { Text("Tag list:") ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(0...8, id: \.self) { _ in TagView().padding() } } }.id(UUID().uuidString) // << here is a fix ! } } }
d11097
Something like this: require(sqldf) C <- sqldf('select A.log, A.P1, A.P2, A.P3, A.P4, A.P5, A.Method, A.Round, "A.#TSamples", "A.#Samples0", "A.#Samples1", B.FP, B.TN, B.TP, B.FN, A.Time, A.Det_Time from A inner join B on (A.log = B.log and A.P1 = B.P1 and A.P2 = B.P2 and A.P3 = B.P3 and A.P4 = B.P4 and A.P5 = B.P5 and and A.Method = B.Method and A.Round = B.Round) ') C <- rbind(A,C) C <- C[!duplicated(C[c("log", "P1", "P2", "P3", "P4", "P5", "Method", "Round", "#TSamples", "#Samples0", "#Samples1", "Time", "Det_Time")]),]
d11098
The Computational Model Library contains models from a variety of ABM modeling toolkits, including Repast Simphony. These come up if you search using "Repast" as a keyword. Repast Simphony also comes with demonstration models (included in the macOS and Windows distributions or available here as a standalone download), but those are more geared towards showing examples of how Repast Simphony features can be incorporated into user models. Have you looked at those?
d11099
Assuming you define div and span tags as “illegal” as per your comment, the following regex will match x sentences before and y sentences after the sentence conatining $word, as long as those sentences do not contain the “illegal” tags: '(?:(?<=[.!?]|^)(?:(?<!<div|<\/div|<span|<\/span)>|[^>.!?])+[.!?]+){0,x}[^.!?]*'.$word.'[^.!?]*[.!?]+(?:(?:<(?!\/?div|\/?span)|[^<.!?])*[.!?]+){0,y}' Split up and explained (quotes and string concatenation operator removed, comments and line breaks added for better reading): // 0 TO X LEADING SENTENCES (?: ---------------------------------// do not create a capture group (?<=[.!?]|^) ----------------------// match only after sentence end or start of string (?: -------------------------------// do not create a capture group (?<!<div|<\/div|<span|<\/span)> -// match “>” only if not preceded by span or div tags |[^>.!?] ------------------------// or any any other, non punctuation character )+ --------------------------------// one or more times [.!?]+ ----------------------------// followed by one or more punctuation characters ){0,x} ------------------------------// the whole sentence repeated 0 to x times // MIDDLE SENTENCE WITH KEYWORD [^.!?]* -----------------------------// match 0 or more non-punctuation characters $word -------------------------------// match string value of $word [^.!?]* -----------------------------// match 0 or more non-punctuation characters [.!?]+ ------------------------------// followed by one or more punctuation characters // 0 TO Y TRAILING SENTENCES (?: ---------------------------------// do not create a capture group <(?!<\/?div|\/?span) --------------// match “<” not followed by a “div” or “span” tag |[^<.!?] --------------------------// or any non-punctuation character that is not “<” )* --------------------------------// zero or more times [.!?]+ ----------------------------// followed by one or more punctuation characters ){0,y} ------------------------------// the whole sentence repeated 0 to y times Note the lookbehind assertion used for matching sentences before $word will only match opening and closing tags without attributes, and has to match both the opening and closing tag variants literally, as lookbehind assertions cannot be of variable length. There are other limitations and gotchas: * *notably that the regex will return an “illegal” tag if it is located inside the sentence containing $word *and that “inside” a sentence literally means “following the closing punctuation of the preceding sentence”, which, although formally correct, might not be what is expected. All of this goes to highlight the limitations of a regex based approach to the problem. In this light, you might think that switching to a more programatic approach (like parsing all sentences into an array irrespective of tags, then scanning for “illegal” tags and trimming or rejecting the array accordingly, which would allow for a more flexible tag matching regex) would work better, and you would be right, were it not for the underlying difficulty of matching a natural language construct like a sentence with a regex with any degree of accuracy. I’ll leave you to ponder what the “sentence splitting” regex used in this question and answer would do to the following: “T.J. Hooker was plaid (sic.) by W. Shatner of Starship Enterprise (!) fame” It’s not pretty. And neither is the result.
d11100
When RoofClass constructor creates an instance of AClass, it passes a pointer to itself, with uninitialized members a_class and b_class. AClass constructor then copies those values and returns. When RoofClass constructor sets a_class to point to the newly constructed object, the pointers inside AClass are still pointing to nothing. You probably want BaseClass to store a pointer to RoofClass instead: class BaseClass { public: BaseClass(RoofClass* roof_class) { r_class = roof_class; } RoofClass* r_class; }; class AClass : public BaseClass { public: AClass(RoofClass* roof_class) : BaseClass(roof_class) {} void Afunction(); int Aint = 1; // access class B as r_class->b_class }; A: I actually solved the question. It is like this: In its constructor, the RoofClass creates a and b objects, in order. It first initializes a object by going into its constructor (which actually is the constructor of BaseClass due to inheritance) and setting a's a and b objects to roof's a and b. But the problem is that, roof's b is not constructed yet. That is why, a's b is initialized to a value of 00000000. When the RoofClass goes to b object's constructor for initialization, this time both roof's a and b are in place so that b's a and b's b are properly initialized. That is why, b can have a proper a but not vice versa. The solution is introducing an InitPointer function to the base class, which acts after the roof objects constructs all a and b objects. This way, InitPointer sets pointers of a and b objects to already constructed a and b objects. Here is the working code: #include <iostream> using namespace std; class AClass; class BClass; class RoofClass { public: RoofClass(); AClass* a_class; BClass* b_class; }; class BaseClass { public: BaseClass() {} void InitPointer(RoofClass* roof_class) { a_class = roof_class->a_class; b_class = roof_class->b_class; } AClass* a_class; BClass* b_class; }; class AClass : public BaseClass { public: AClass() : BaseClass() {} void Afunction(); int Aint = 1; }; class BClass : public BaseClass { public: BClass() : BaseClass() {} void Bfunction(); int Bint = 2; }; void AClass::Afunction() { cout << b_class->Bint << endl; } void BClass::Bfunction() { cout << a_class->Aint << endl; } RoofClass::RoofClass() { a_class = new AClass(); b_class = new BClass(); a_class->InitPointer(this); b_class->InitPointer(this); } int main(int argc, char **argv) { RoofClass roof_class; cout << "b calls a" << endl; roof_class.b_class->Bfunction(); cout << "a calls b" << endl; roof_class.a_class->Afunction(); } Thanks for the all discussion!