source
sequence
text
stringlengths
99
98.5k
[ "ru.stackoverflow", "0000662218.txt" ]
Q: Как узнать название класса текущего элемента? в Android Studio У меня есть чужой код и разбираться со всем нет времени, да и по просту не хватит его. Слишком большой проект. Как мне узнать класс который отвечает за нажатие в приложении Button. Можно ли как - то сделать так, чтобы запустить приложение, нажать на кнопку, и в это время в Android Studio где - то укажется название класса или layout файла, или какую - нибудь отсылку на исходник..... P.S. Речь сейчас идет НЕ ПРО! Debug и BreakPoint. Потому что я не знаю куда BreakPoint ставить. А без BreakPoint Debug работать не будет. A: У кнопки должен быть указан id, попробуйте найти его упоминание в проекте
[ "stackoverflow", "0004990304.txt" ]
Q: String compare in iOS I want to find out whether a given NSString or CFStringRef contains a certain substring. How do I do that? A: Please read the NSString class reference. What you want is pathExtension.
[ "ethereum.stackexchange", "0000025043.txt" ]
Q: Basic question on distributed Smart contract Basic question on distributed Smart contract. Let us assume , I am writing a smart contract and deploying it in public network. My Contract Specification • My contract would allow anyone to register. • Fund 10 Ether to the contract • Contract will in turn return 12 Ether on Dec 31st 2017 Contract owner by mistake instead of capping it to Dec 31st , he mentioned Jan 31st in the contract. Scenario : • Owner A sits in USA, deploys the contract in public chain • User B from Australia funds 10 ether to the contract on August 31st, 2017 • User B now expects 12 Ether on Dec 31st but he never receives it . Question Even though the contract is distributed among all the nodes, 1. How would user B come to know what is written in the contract ( assuming B has zero coding knowledge) ? 2. If only User B is interested in this contract, who will verify this smart contract A: The smart contract once deployed on Ethereum is public and can be viewed. One would have to know what they're signing up for by reviewing the smart contract (There is no other way out).
[ "serverfault", "0000364517.txt" ]
Q: Multi Workstation DRBD Setup I'm considering setting up a way to automate data redundancy and synchronisation of multiple workstations at the office. The way our office is setup, nobody has a fixed desk and anyone can login and work on any workstation on the network. One way of doing this would be to have a NFS mounted /home filesystem. However, that would slow down file access as everything would need to be pulled off the network plus it creates a single point of failure. This is the general idea. [WS-A]--- (DRBD) ---[BACKUP]--- (DRBD) ---[WS-B/C/D/etc] The idea is for someone to work on WS-A and whatever file saved is automatically synchronised with another machine (backup). So, the data is now available on more than one machine. Ideally, the data should synchronise and propagate itself across all the workstations WS-B, WS-C, etc on the network. This propagation and synchronisation does not need to be instantaneous and can be asynchronous as long as the same user can log into any workstation at another time (but only one machine at a time) and find their latest files present. Also, if any workstation crashes, the setup will automatically recover and resync after the machine comes back onto the network, preventing split-brain problems. Would this even be possible with DRBD; and Are there any nightmare synchronisation issues that we might need to worry about? PS: We currently have a similar setup that uses glusterfs and it seems to work thus far, except that the performance drops when accessing a large git repository over it. A: Putting workstations into a DRBD cluster sounds like a terrible idea to me. I doubt that this will ever work reliable because now users can't restart their workstation anymore. Instead, make sure that your NFS server isn't a single point of failure anymore and setup a HA system at this point. Since this is not really easy, I just link to a tutorial for this.
[ "stackoverflow", "0026751134.txt" ]
Q: Function overriding without virtual and override I just have one basic question : public class virtualTest { public virtual void vTest() { Console.WriteLine("Base Class"); } } public class derivedVirtualTest : virtualTest { public override void vTest() { Console.WriteLine("Derived Class"); } } Here i have used function overriding with function vTest() But if i : public class virtualTest { public void vTest() { Console.WriteLine("Base Class"); } } public class derivedVirtualTest : virtualTest { public void vTest() { Console.WriteLine("Derived Class"); } } removes virtual and override keywords from respective places , then also code works. How can this be possible? Or then what is the use of override and virtual (entire function overriding) if code works fine without virtual and override??? EDIt: My Method through which i am calling above classes static void Main(string[] args) { derivedVirtualTest objderivedVirtualTest = new derivedVirtualTest(); objderivedVirtualTest.vTest(); virtualTest objvirtualTest = new virtualTest(); objvirtualTest.vTest(); Console.ReadLine(); } A: As qwr explained, the main difference in terms of OOP is polymorphism. It means that if you access the class which overrides the base member through a base type reference, the call you perform to the overriddable member is redirected to the override. In case of a class which shadows/hides the base member, the call is not redirected, and the base class' method is being executed. So, given: class Base { public virtual void OverrideMe() { Console.WriteLine("I'm the base"); } } class Derived : Base { public override void OverrideMe() { Console.WriteLine("I'm derived"); } } class Shadowing : Base { public void OverrideMe() { Console.WriteLine("I'm shadowing"); } } And using them this way: var instances = new Base[] {new Base(), new Derived(), new Shadowing()}; foreach (var instance in instances) { instance.OverrideMe(); } Will produce: I'm the base I'm derived I'm the base Additional difference is that in case of overriding you can evolve your base class, like changing the signature of the base member or removing it completely, without changing the hiding one. Which in some cases may suit needs exactly and in some - not so much. In case of overriding you must change the signature of overriding member as well, otherwise your code will fail to compile.
[ "stackoverflow", "0025271705.txt" ]
Q: Javascript Object Properties with condition How can I create object with properties in javascript ? Something like : function translate() { this.city = function () { if (language == "English") { return "City"; } else { return "Ville"; } } } When I try to use this : translate.city It return undefined... A: You need to create an instance of your object: var myTranslate = new translate(); var city = myTranslate.city(); Alternatively, you could do this: var translate = { city: function () { if (language == "English") { return "City"; } else { return "Ville"; } } }; var city = translate.city(); If you want to be able to access the city property without calling it as a function and you are using ES5 or higher, you can define a getter method: var translate = {}; Object.defineProperty(translate, "city", { get: function () { if (language == "English") { return "City"; } else { return "Ville"; } } }); console.log(translate.city); Or yet another way of defining a getter (also requires ES5): var translate = { get city() { if (language == "English") { return "City"; } else { return "Ville"; } } }; console.log(translate.city); And one more variation (provided by @vol7ron), which determines the city value when the object is created: function Translate() { this.city = (function () { if (typeof language !== 'undefined' && language == "English") { return "City"; } else { return "Ville"; } }()); } var translate = new Translate(); translate.city; // "Ville"
[ "stackoverflow", "0061847083.txt" ]
Q: How do I correct my Node connection to MySQL with the hostname? *** Edited the username from 'sabcozac@user' to 'sabcozac_user' My connection to my hosted MySQL database fails because the hostname is inserted even though I don't include it anywhere. I read through the response here regarding appending the hostname but I'm not sure how to resolve the issue. My db.js file doesn't contain the hostname but each time it gets inserted in my executable. I've provided both below and would appreciate any help anyone could offer please. db.js 'user strict'; const mysql = require('mysql'); const connection = mysql.createConnection({ host : 'cp14.domains.co.za', user : 'sabcozac_user', port : '3306', password : '************', database : 'sabcozac_fonebook' }); connection.connect(function(err) { if (err) throw err; }); module.exports = connection; I'm using a hosted database that is administered by PHPMyAdmin which doesn't allow me to add '@localhost' to the username. A: I retried the connection and it worked. I removed the other installation I had on the server (not the pre-installed PHPMyAdmin one) and this time the connection string didn't have the extra hostname in the user. Now I have a 'Packet out of order' problem but I'll come back with a new question if needed. Thanks all!
[ "stackoverflow", "0023225431.txt" ]
Q: How to return file object from assets in Android? I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content. What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path). A: You can straight way create a file using InputStream. AssetManager am = getAssets(); InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename); File file = createFileFromInputStream(inputStream); private File createFileFromInputStream(InputStream inputStream) { try{ File f = new File(my_file_name); OutputStream outputStream = new FileOutputStream(f); byte buffer[] = new byte[1024]; int length = 0; while((length=inputStream.read(buffer)) > 0) { outputStream.write(buffer,0,length); } outputStream.close(); inputStream.close(); return f; }catch (IOException e) { //Logging exception } return null; }
[ "stackoverflow", "0032545981.txt" ]
Q: Header wider than page I have set my header and footer width to 100% but somehow header is wider than page making a scroll bar appear at bottom, content and footer match page width, only header is wider maybe because i have used media query for drop down menu inside header. My code is * { margin: 0px; padding: 0px; font-family: Arial, Helvetica, Sans-serif; font-size: 12px; background-color: #EDEDED; } .headerMenu{ width: 100%; padding: 30px; background-color:#BF3B3D; } #wrapper { width:100%; background-color:#BF3B3D; } .logo img { position: absolute; top:0; float:left; background-image: url(../img/menu_bg.gif); width: 110px; height: 58px; } .search_box { top: 7px; float:left; color: #198C9E; background-color:#BF3B3D; position: absolute; margin-left: 155px; } @media screen and (max-width: 1280px) { .dd { background-color:#BF3B3D; position: absolute; right:0px; top:0; margin-right: 4%; } } @media screen and (min-width: 1280px) { .dd { background-color:#BF3B3D; position: absolute; right:0px; top:0; margin-right: 10%; } } @media screen and (min-width: 1920px) { .dd { background-color:#BF3B3D; position: absolute; right:0px; top:0; margin-right: 25%; } } Here dd is class for drop down menu. A: That's because you are applying a padding to your header. To change that behavior, use the box-sizing property. .headerMenu{ background-color:#BF3B3D; box-sizing: border-box; padding: 30px; width: 100%; }
[ "stackoverflow", "0046986114.txt" ]
Q: Grouping DataFrame to get max index I'm having a dataframe similar to something like this: Year class Sales 0 1980 1 1.10 1 1980 2 7.07 2 1980 3 8.00 3 1980 4 12.00 4 1981 1 11.20 5 1981 1 2.00 6 1981 3 4.00 7 1981 2 6.00 I want my data to be grouped such that I get the yearly max sales of class and get the class of that dataframe. what I need to do after this? data.groupby(['Year','class']).sum() Sales Year class 1980 1 1.10 2 7.07 3 8.00 4 12.00 1981 1 13.20 2 6.00 3 4.00 e.g. I want my output to be something like this: Sales Year class 1980 4 12.00 1981 1 13.20 I was able to get the correct output using loops but im trying to avoid that as it takes too much time. A: One approach would be that after you do your first groupby, you can do a second just on the Year (index level=0) to find the indices of the maximum sales: In [41]: d2 Out[41]: Sales Year class 1980 1 1.10 2 7.07 3 8.00 4 12.00 1981 1 13.20 2 6.00 3 4.00 In [42]: d2["Sales"].groupby(level=0).idxmax() Out[42]: Year 1980 (1980, 4) 1981 (1981, 1) Name: Sales, dtype: object In [43]: d2.loc[d2["Sales"].groupby(level=0).idxmax()] Out[43]: Sales Year class 1980 4 12.0 1981 1 13.2
[ "stackoverflow", "0028763256.txt" ]
Q: How to remove duplicate entries in postgresql table? I have a postgresql table without primary key. I want to remove all entries that have the same id, but retain the most recent one. The following statement almost works: DELETE FROM mytable USING mytable t WHERE mytable.id = t.id AND mytable.modification < t.modification; Problem: when two entries have the same modification timestamp (which is possible), both are retained. What would I have to change to just keep one of them, does not matter which one? I cannot change the condition to AND mytable.modification <= t.modification; as this would then remove all dublicates not retaining any entry. A: If you have rows that are complete duplicates (i.e., no way to distinguish one from the other), then you have two options. One is to use a built-in row identifier such as ctid: DELETE FROM mytable USING mytable t WHERE mytable.id = t.id AND (mytable.modification < t.modification OR mytable.modification = t.modification AND mytable.ctid < t.ctid); Or use a secondary table: create table tokeep as select distinct on (t.id) t.* from mytable order by t.id, t.modification; truncate table mytable; insert into mytable select * from tokeep;
[ "stackoverflow", "0058108271.txt" ]
Q: Download latest artifacts from app center / Hockey app using API (token) Recently the hockey moved to app center and i want to download the latest version of android and iOS version on the fly using the API. What I tried ? checked the official swagger api-specs 1. @GET("/v0.1/apps/{owner_name}/{app_name}/recent_releases") 2. @GET("/v0.1/apps/{owner_name}/{app_name}/builds/{build_id}/downloads/{download_type}") but the download url provided by the second url has a different host and it doesn't work. A: UPDATED The api's has been changed, and the new api we can use is @GET("/v0.1/public/sdk/apps/{app_secret}/releases/latest") fun latestRelease(@Header("X-API-Token") apiToken: String, @Path("app_secret") secret: String): Call<JsonObject> offical swagger api app_secret you can list your app secret using app list, use this command line. apiToken you can generate a token following these instructions
[ "stackoverflow", "0037698276.txt" ]
Q: UTF-8 text in HDInsight cluster with spark result encoding error 'ascii' codec can't encode characters in position: ordinal not in range(128) Trying to work with Hebrew characters UTF-8 TSV file in HDInsight cluster with spark on Linux and I get encoding error, any recommendations? There's my pyspark notebook code: from pyspark.sql import * # Create an RDD from sample data transactionsText = sc.textFile("/people.txt") header = transactionsText.first() # Create a schema for our data Entry = Row('id','name','age') # Parse the data and create a schema transactionsParts = transactionsText.filter(lambda x:x !=header) .map(lambda l: l.encode('utf-8').split("\t")) transactions = transactionsParts.map(lambda p: Entry(str(p[0]),str(p[1]),int(p[2]))) # Infer the schema and create a table transactionsTable = sqlContext.createDataFrame(transactions) # SQL can be run over DataFrames that have been registered as a table. results = sqlContext.sql("SELECT name FROM transactionsTempTable") # The results of SQL queries are RDDs and support all the normal RDD operations. names = results.map(lambda p: "name: " + p.name) for name in names.collect(): print(name) Error: 'ascii' codec can't encode characters in position 6-11: ordinal not in range(128) Traceback (most recent call last): UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-11: ordinal not in range(128) Hebrew Text file content: id name age 1 גיא 37 2 maor 32 3 danny 55 When I try English file it works fine: English Text file content: id name age 1 guy 37 2 maor 32 3 danny 55 Output: name: guy name: maor name: danny A: If you run the following code with the hebrew text: from pyspark.sql import * path = "/people.txt" transactionsText = sc.textFile(path) header = transactionsText.first() # Create a schema for our data Entry = Row('id','name','age') # Parse the data and create a schema transactionsParts = transactionsText.filter(lambda x:x !=header).map(lambda l: l.split("\t")) transactions = transactionsParts.map(lambda p: Entry(unicode(p[0]), unicode(p[1]), unicode(p[2]))) transactions.collect() you'll notice that you get the names as a list of unicode type: [Row(id=u'1', name=u'\u05d2\u05d9\u05d0', age=u'37'), Row(id=u'2', name=u'maor', age=u'32 '), Row(id=u'3', name=u'danny', age=u'55')] Now, we'll register a table with the transactions RDD: table_name = "transactionsTempTable" # Infer the schema and create a table transactionsDf = sqlContext.createDataFrame(transactions) transactionsDf.registerTempTable(table_name) # SQL can be run over DataFrames that have been registered as a table. results = sqlContext.sql("SELECT name FROM {}".format(table_name)) results.collect() You'll notice that all strings in the Pyspark DataFrame coming back from sqlContext.sql(... will be of Python unicode type: [Row(name=u'\u05d2\u05d9\u05d0'), Row(name=u'maor'), Row(name=u'danny')] Now running: %%sql SELECT * FROM transactionsTempTable Will get the expected result: name: גיא name: maor name: danny Do note that if you wanted to do some work on those names, you'd want to work with them as unicode strings. From this article: When you’re dealing with text manipulations (finding the number of characters in a string or cutting a string on word boundaries) you should be dealing with unicode strings as they abstract characters in a manner that’s appropriate for thinking of them as a sequence of letters that you will see on a page. When dealing with I/O, reading to and from the disk, printing to a terminal, sending something over a network link, etc, you should be dealing with byte str as those devices are going to need to deal with concrete implementations of what bytes represent your abstract characters.
[ "math.stackexchange", "0000508976.txt" ]
Q: Form a Parallelogram by 4 Points This is a question from my school. The following is the whole question. The vertices of a triangle $A$, $B$ and $C$ are given by the points $(-1, 0, 2)$, $(0, 1, 0)$, $(1, -1, 0)$ respectively. Find point $D$ so that the figure $ABCD$ forms a plane parallelogram. I have no idea with points in 3D. Would you mind helping me solve the question and explain to me in detailed. Thank you for your attention. A: There are three possible responses, depending on the choice of the first point in the next procedure: Let's say we choose point $A$ to start: choose one of the other points, $B$ or $C$. It doesn't matter as the result will be the same whatever is the choice. Let's say you choose point $B$. Then calculate: $V = B - A$. (With this $V$ must be parallel and same length as the "hidden" side of the parallelogram). Then add this vector $V$ to the other point ($C$ in this case). This will be the point $D$ you are looking for, so: $$ D = C + V = C + B - A\tag{1} $$ If you choose $C$ instead of $B$ you would have: \begin{alignat}{2} V &= C - A\\ D &= B + V &&{}= B + C - A \end{alignat} as you can see same result as in (1). You can repeat it starting with $B$ and $C$ points. So, you have three possible solutions: \begin{align} D_1 &= B + C - A\\ D_2 &= A + C - B\\ D_3 &= A + B - C \end{align}
[ "stackoverflow", "0008901651.txt" ]
Q: How to use NSHost to get the name behind a bunch of LAN ip addresses? I know how to get the name behind an ip address using the terminal and dig. I.e: dig @224.0.0.251 -p5353 -x 192.168.0.195 +short However, I don't want to use NSTask in my application. How can I use NSHost to get the name behind an ip address within a LAN? I tried this, but it always returns nil: NSHost *myHost = [NSHost hostWithAddress:@"192.168.0.195"]; NSLog(@"name: %@", [myHost name]); Thanks a lot! Edit: These methods/functions... +[NSHost hostWithAddress:] gethostbyaddr(3) - A BSD function ...seem to be the same as: dig -x 192.168.0.195 If I use that dig command in the terminal it says that no servers could be reached. (Yes I don't have a DNS server in my LAN), so no wonder I get back nil. It would be great if I could implement dig @224.0.0.251 -p5353 -x 192.168.0.195 +short (bonjour multicast lookup) in my app without having to use NSTask. :) A: It does not use NSHost, but uses the Bonjour-API and it seems to work as you want: #import <Cocoa/Cocoa.h> #import <dns_sd.h> #import <resolv.h> static void callback(DNSServiceRef serviceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context) { char result[1024] = {0}; dn_expand(rdata, rdata + rdlen, rdata, result, 1024); NSLog(@"Found: %s", result); } int main(int argc, char const *argv[]) { DNSServiceRef reverseLookupService = NULL; DNSServiceErrorType error = kDNSServiceErr_NoError; error = DNSServiceQueryRecord(&reverseLookupService, kDNSServiceFlagsForceMulticast, kDNSServiceInterfaceIndexAny, "5.1.168.192.in-addr.arpa.", kDNSServiceType_PTR, kDNSServiceClass_IN, callback, NULL); if (error != kDNSServiceErr_NoError) { NSLog(@"Error: %d", error); exit(1); } error = DNSServiceProcessResult(reverseLookupService); DNSServiceRefDeallocate(reverseLookupService); return 0; } The important part is using DNSServiceQueryRecord with kDNSServiceFlagsForceMulticast. Look at https://developer.apple.com/library/mac/#documentation/Networking/Reference/DNSServiceDiscovery_CRef/dns_sd_h/index.html#//apple_ref/c/func/DNSServiceQueryRecord for more info about this function. You'll have to convert the IP address to in-addr.arpa.-format yourself, but that is not hard (the octets are backwards with "in-addr.arpa." at the end. IPv6 is probably similar, but I have not tested it). It imports resolv.h (and you need to link it to libresolv), but only for dn_expand. The data passed to the callback is compressed, and dn_expand creates a human-readable representation.
[ "stackoverflow", "0026727770.txt" ]
Q: Hide form on submit - Django 1.6 I have this form on my Django 1.6 project: <form action="/proyecto/" method="POST" id="myform"> {% csrf_token %} <table> <span class="Separador_Modulo"></span> <span class="Sub-Titulo-Aplicacion">SiatPre</span> <tr> <td >Usuario: {{user}}</td> </tr> <tr><td> <span class="Sub-Titulo-Aplicacion">Tipo de Proyecto: </span> <input class="check-style" type="checkbox" name="curva" value="checkbox" >Petroleo</input> </td></tr> <tr><td> <input class="check-style" type="checkbox" name="curva" value="checkbox" >Gas</input> </td></tr> <tr><td> <span class="Sub-Titulo-Aplicacion">Proyecto: </span> <input class="check-style" type="checkbox" name="tipo" value="checkbox" >Nuevo</input> </td></tr> <tr><td> <input class="check-style" type="checkbox" name="tipo" value="checkbox" >Existente</input> </td></tr> <tr><td> <div class="Contenedor-Elemento-Formulario"> <span class="Sub-Titulo-Formulario"> Nombre Proyecto:</span> <input type="text" class="input-style" name="nombre_proyecto" style="width:96px;"/> </div> </td> </tr> <td><div > <div class="Principio-Boton"> </div> <input name="Aceptar" class="Boton" type="submit" value="Aceptar" onclick="myclick()"/> <div class="Final-Boton"></div> <div class="Principio-Boton"> </div> <input name="Cancelar" class="Boton" type="submit" value="Cancelar" /> <div class="Final-Boton"> </div> </div></td> </tr> </table> <table style="margin-bottom:45px; padding:15px 15px 15px 15px;"> <div>&nbsp;</div> <div>&nbsp;</div> <tr> <td colspan="4" align="center"> <div class="Principio-Boton"> </div> <a href="scppp/datos1.html"><input name="Datos" class="Boton" type="submit" value="Datos"/></a> <div class="Final-Boton"></div></td></tr> <tr> <td colspan="4" align="center"> <div class="Principio-Boton"> </div> <a href="scppp/libreriaPrePro1.html"><input name="Procesamiento" class="Boton" type="submit" value="Procesamiento"/></a> <div class="Final-Boton"></div></td></tr> <tr> <td colspan="4" align="center"> <div class="Principio-Boton"> </div> <a href="scppp/reporte1.html"><input name="Reporte" class="Boton" type="submit" value="Reporte"/></a> <div class="Final-Boton"></div></td></tr> </table> </form> This code is on my base.html file, however, this form is obviously inherited on other templates by block content tag. I need to hide specifically this form from other pages when user clicks <input name="Aceptar" class="Boton" type="submit" value="Aceptar" onclick="myclick()"/> not there is an onclick function I declared earlier on this html, the function being like this: <script>function myclick() {$('#myform').hide().fadeOut(2000); } </script> And on <form action="/proyecto/" method="POST" id="myform"> I reference the function by using an id (id="myform"), however, when I click on Aceptar, it does some hiding for a second or so, then when it loads a new template, by POST request to server, I still see this form there, no matter what. Is this the correct way to achieve what I'm looking for? Or maybe it has to do with POST requests to server? Any ideas? Thanks in advance! A: You have to pass a variable from views.py a = True when you need to display the form, and do the if condition in template, {% if a %} <form action="/proyecto/" method="POST" id="myform"> ................ </form> {% endif %}
[ "math.stackexchange", "0001193885.txt" ]
Q: Hot to prove this proposition? $n \in N$ is positive integer, and $64^n-7^n$ can be divisible by 57. Prove that $8^{2n+1}+7^{n+2}$ is also divisible by 57. A: HINT $$8^{2n+1}+7^{n+2} = 8\cdot 64^n + 49\cdot 7^n =8\cdot 64^n + (57-8)\cdot 7^n =\color{blue}{ 8(64^n-7^n) + 57\cdot 7^n} $$
[ "stackoverflow", "0024553853.txt" ]
Q: Change zIndex of Dojo Tooltip This question is similar to this one but I still cannot come up with a suitable solution. On my site I am trying to implement the dojo Tooltip (not dialog Box as in the link above; click here to see Tooltip documentation). I would like to be able to change the zIndex of the Tooltip to whatever I need. I can only seem to get Dojo to work if I use a CDN such as http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js or //cdnjs.cloudflare.com/ajax/libs/dojo/1.9.3/dojo.js, so trying to alter the javascript of the tooltip file for Tooltip.js did not seem to do anything. Note: Tooltip.js was included locally as: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"></script> <script src="dojo/Tooltip.js"></script> Using info from the link at the top of the page, I was able to come up with a hack solution. Assuming the default z-index for the Dojo tooltip is 1000, I changed the z-indices of all other divs (that were previously > 1000) to z-index < 1000. This solved the problem, and now the Dojo tooltip can be seen in front of these divs (previously was behind). Any suggestions on how to alter the zIndex property of the Dojo tooltip without altering Tooltip.js? A: I would recommend to override css rule according to your requirement. Like by default css rule on dijit tooltip is as follow: .dijitTooltip { position: absolute; z-index: 2000; // You can write your desired z-index display: block; left: 0; top: -10000px; overflow: visible; } Or you can try via JS dojo.query(".dijitTooltip:visible").style("z-index", 'You desired value'); // <1.6 //>1.7 require(["dojo/query","dojo/dom-style"],function(query, domStyle){ domStyle(query(".dijitTooltip:visible"), "z-index", "You desired value"); });
[ "ru.stackoverflow", "0000474438.txt" ]
Q: Утилита для работы с PostgreSQL Всем привет. Посоветуйте, пожалуйста, адекватную утилиту для работы с PostgreSQL, а то стандартный pgAdmin что-то не радует вовсе. Нужен удобный редактор запросов с функцией IntelliSense. Средства для администрирования БД (резервное копирование, возможность остановить, запустить сервер и т.д.). Просмотр схемы БД в виде диаграмм. ОС - Windows. A: EMS SQL Manager for PostgreSQL
[ "stackoverflow", "0018779322.txt" ]
Q: Disable New Line in Textarea when Pressed ENTER I am calling a function whenever someone press enter in the textarea. Now I want to disable new line or break when enter is pressed. So new line should work when shift+enter is pressed. In that case, the function should not be called. Here is jsfiddle demo: http://jsfiddle.net/bxAe2/14/ A: try this $("textarea").keydown(function(e){ // Enter was pressed without shift key if (e.keyCode == 13 && !e.shiftKey) { // prevent default behavior e.preventDefault(); } }); update your fiddle to $(".Post_Description_Text").keydown(function(e){ if (e.keyCode == 13 && !e.shiftKey) { // prevent default behavior e.preventDefault(); //alert("ok"); return false; } });
[ "stackoverflow", "0016071275.txt" ]
Q: How to display string inline? How to force in twitter bootstrap show text inline with overflow? For example in http://jsfiddle.net/nonamez/jJdX4/ overflow is working except the inline words. In my code nothing works. A: Use white-space and set it to nowrap which will make text go into one line until a break is reached. li {white-space:nowrap;} http://jsfiddle.net/jJdX4/1/
[ "stackoverflow", "0019636735.txt" ]
Q: grouping counted data by column name I have following table: QuranMaster 2.QuranPrayed I just wanted to have all the siparas and there count as result. Means expected result is as follows: Sipara1 3 Sipara2 2 .. .. .. Sipara1 is 3 because it has arrived 3 times in QuranPrayed. I made following query: select qm.sipara,COUNT(qp.Sipara) from QuranMaster qm,QuranPrayed qp where qp.sipara=qm.sipara group by qm.sipara This query works perfectly right when QuranPrayed has values. But when QuaranPrayed has no values, it does not shows me result. My expectation is: Sipara1 0 Sipara2 0 .. .. .. Please help me. A: You need to use a LEFT JOIN: SELECT qm.sipara, Prayed = COUNT(qp.Sipara) FROM QuranMaster qm LEFT JOIN QuranPrayed qp ON qp.sipara=qm.sipara GROUP BY qm.sipara; It is worth noting that the implicit join syntax you have used is over 20 years old and was replaced in ANSI 92 with explicit joins. This article by Aaron Bertrand raises some very valid reasons to switch to the newer syntax. Probably the most pertinant of which to you is the use of LEFT JOIN. previously in SQL-Server your query would have been: select qm.sipara,COUNT(qp.Sipara) from QuranMaster qm,QuranPrayed qp where qp.sipara=*qm.sipara group by qm.sipara However this is deprecated and you will likely get the following error: The query uses non-ANSI outer join operators ("*=" or "=*"). To run this query without modification, please set the compatibility level for current database to 80, using the SET COMPATIBILITY_LEVEL option of ALTER DATABASE. It is strongly recommended to rewrite the query using ANSI outer join operators (LEFT OUTER JOIN, RIGHT OUTER JOIN). In the future versions of SQL Server, non-ANSI join operators will not be supported even in backward-compatibility modes.
[ "stackoverflow", "0006041412.txt" ]
Q: jQuery val() not getting value Here is my code: jQuery('span.con').delegate('input#sdate', 'focus', function(e){ try { var oneDay = 24*60*60*1000; rangeConv = new AnyTime.Converter({format: '%m-%d-%Y %k:%i'}); fromDay = rangeConv.parse(jQuery(this).val()).getTime(); dayLater = new Date(fromDay+oneDay); dayLater.setHours(0,0,0,0); jQuery(this). AnyTime_picker({ askSecond: false, format: '%m-%d-%Y %k:%i' }); } catch(e){ alert(jQuery.error); jQuery.error = console.error; } //jQuery('span.con input#sdate').val(); alert(jQuery(this).val()); }); The alert() is showing a blank popup. Can some one guide me how can I get value of 'ITSELF' input box? Thanks in advance. A: In your code you have caught e but then tried to display something else. Do this instead: } catch(e){ alert(e.message); }
[ "mathoverflow", "0000258329.txt" ]
Q: Getting asymptotic behaviour of an integral? I am interested in the $\rho\sim0$ asymptotics of the following expression $$ \int_{1.1}^{\infty}\frac{\sin(k\rho)}{k^{1.9}\rho}\frac{1}{\log\frac{1}{k}}\,dk $$ any ideas of how to tackle this? A: the small-$\rho$ asymptotics of $$I(\rho)=-\int_{1.1}^{\infty}\frac{\sin(k\rho)}{\rho k^{1.9}\ln k}\,dk$$ is governed by the large-$k$ behavior of the integrand, which gives $I(\rho)\propto \rho^{1.9-2}$ up to a logarithmic factor, and a numerical evaluation supports the asymptotic $$I_{\rm asymp}(\rho)=-\rho^{-0.1}(3.5+0.126\ln\rho)$$ Log-linear plot of $-\rho^{0.1}I(\rho)$ (blue line) and $-\rho^{0.1}I_{\rm asymp}(\rho)$ (orange line) UPDATE, following Bazin's recent answer: I have some convergence issues with a numerical evaluation at much smaller $\rho$, but if I can trust the Mathematica output the curve does seem to level off towards an asymptote at zero, as derived by Bazin, possibly as $I(\rho)=-\text{constant}\times(\rho^{0.1}\log\rho)^{-1}$. A: Setting $t=\rho k$ the integral in question becomes $$ \int_{1.1\rho}^\infty\frac{\sin t}{\rho^{0.1}t^{1.9}\log (t/\rho)}\;dt. $$ Fix $\epsilon>0$. Then for $\rho\rightarrow 0$ we have $$ \int_{1.1\rho}^{\rho^{1/2}} \frac{\sin t}{t^{1.9}\log (t/\rho)}\;dt \ll \int_{1.1\rho}^{\rho^{1/2}} \frac{1}{t^{0.9}}\;dt \ll \rho^{1/20}, $$ $$ \int_{\rho^{1/2}}^\epsilon\frac{\sin t}{t^{1.9}\log (t/\rho)}\;dt \ll\frac{1}{\log\rho^{-1}}\int_{\rho^{1/2}}^\epsilon\frac{dt}{t^{0.9}}\ll\frac{\epsilon^{0.1}}{\log\rho^{-1}}, $$ and $$ \left|\int_{\epsilon^{-1}}^\infty\frac{\sin t}{t^{1.9}\log (t/\rho)}\;dt\right| \ll \int_{\epsilon^{-1}}^\infty\frac{1}{t^{1.9}\log \rho^{-1}}\;dt \ll\frac{\epsilon^{0.1}}{\log\rho^{-1}}. $$ Hence for $\rho<\epsilon^2$ the integral in question equals $$ \rho^{-0.1}\int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}\log(t/\rho)}\;dt + \mathcal{O}\left(\frac{\epsilon^{0.1}\rho^{-0.1}}{\log\rho^{-1}}\right). $$ Now $$ \int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}\log(t/\rho)}\;dt = \int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}(\log\rho^{-1} + \mathcal{O}(\log\epsilon^{-1}))}\;dt, $$ since in the range of integration we have $|\log t|\leq\log\epsilon^{-1}$. Putting $L=\log\rho^{-1}$ and $\alpha=\log\epsilon^{-1}$ we have for $\alpha<L/2$, i.e. $\rho<\epsilon^2$ $$ \left|\frac{1}{L}-\frac{1}{L+\alpha}\right| = \frac{|\alpha|}{L(L+\alpha)} \ll \frac{|\alpha|}{L^2}, $$ thus \begin{split} \int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}(L + \mathcal{O}(\alpha))}\;dt &= \int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}}\left(\frac{1}{L}+\mathcal{O}\left(\frac{\alpha}{L^2}\right)\right)\;dt\\ & = \frac{1}{L}\int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}}\;dt + \mathcal{O}\left(\frac{\alpha}{L^2}\int_\epsilon^{\epsilon^{-1}}\frac{|\sin t|}{t^{1.9}}\right). \end{split} In the error term we bound $|\sin t|$ by $\min(t, 1)$ and split the integral into the range $[\epsilon, 1]$ and $[1, \epsilon^{-1}]$. Doing so we find that the integral converges, hence the error term is $\mathcal{O}(\frac{\alpha}{L^2})$. In the main term we extend the integral to the range $(0,\infty)$. Doing so introduces an error $$ \frac{1}{L}\int_0^\epsilon\frac{\sin t}{t^{1.9}}\;dt \leq \frac{1}{L}\int_0^\epsilon\frac{1}{t^{0.9}}\;dt\ll\frac{\epsilon^{0.1}}{L} $$ and another one of size $$ \frac{1}{L}\int_{\epsilon^{-1}}^\infty\frac{\sin t}{t^{1.9}}\;dt \leq \frac{1}{L}\int_{\epsilon^{-1}}^\infty\frac{dt}{t^{1.9}} \ll \frac{\epsilon^{0.9}}{L}. $$ Together we obtain $$ \int_\epsilon^{\epsilon^{-1}}\frac{\sin t}{t^{1.9}\log(t/\rho)}\;dt = \frac{1}{L}\int_0^\infty\frac{\sin t}{t^{1.9}}\;dt + \mathcal{O}\left(\frac{\epsilon^{0.1}}{L}+\frac{\alpha}{L^2}\right). $$ Together with the bounds obtained before we get that the original integral equals $$ \frac{\rho^{-0.1}}{L}\int_0^\infty\frac{\sin t}{t^{1.9}}\;dt + \mathcal{O}\left(\frac{\rho^{-0.1}\epsilon^{0.1}}{L}+\frac{\rho^{-0.1}\alpha}{L^2}\right). $$ Putting $\epsilon=L^{10}$, i.e. $\alpha=10\log\log\rho^{-1}$, we get $$ \frac{\rho^{-0.1}}{L}\int_0^\infty\frac{\sin t}{t^{1.9}}\;dt + \mathcal{O}\left(\frac{\rho^{-0.1}\log\log\rho^{-1}}{(\log\rho^{-1})^2}\right). $$ The integral in the main term is positive, thus the main term is larger than the error term by a factor $\frac{\log\log\rho^{-1}}{\log\rho^{-1}}$, and we got an asymptotic formula. The main source of error is the approximation of the term $\log\rho^{-1}+t$ by $\log\rho^{-1}$. If you need better asymptotics, you would have to use the series expansion of $\frac{1}{1+x}$. In this way you would get an asymptotic series in $\frac{1}{L}$, but the computations would become rather long.
[ "stackoverflow", "0010123675.txt" ]
Q: CUDA: while loop index correctness This kernel is doing the right thing giving me the correct result. My problem is more in correctness of the while loop if I want to improve the performance. I tried several configuration of blocks and threads but if i'm going to change them, the while loop won't give me the correct result. The results i obtained changing the configuration of the kernel are that firstArray and secondArray won't be filled completely (they will have 0 inside the cells). Both arrays must be filled with the curValue obtained from the if loop. Any advice is welcomed :) Thank you in advance #define N 65536 __global__ void whileLoop(int* firstArray_device, int* secondArray_device) { int curValue = 0; int curIndex = 1; int i = (threadIdx.x)+2; while(i < N) { if (i % curIndex == 0) { curValue = curValue + curIndex; curIndex *= 2; } firstArray_device[i] = curValue; secondArray_device[i] = curValue; i += blockDim.x * gridDim.x; } } int main(){ firstArray_host[0] = 0; firstArray_host[1] = 1; secondArray_host[0] = 0; secondArray_host[1] = 1; // memory allocation + copy on GPU // definition number of blocks and threads dim3 dimBlock(1, 1); dim3 dimGrid(1, 1); whileLoop<<<dimGrid, dimBlock>>>(firstArray_device, secondArray_device); // copy back to CPU + free memory } A: You have a data dependency issue here which hinders you to do some meaningful optimization. The variables curValue and curIndex are changed within the while loop and feed forward into the next run. As soon as you try to optimize the loop you will find you in a situation where this variables have different states and the result is changed. I do not really know what you try to achieve, but try to make the while loop indepdent to the values of a former run of the loop to avoid the dependencies. Try to separate the data into threads and data chunks in a way that the indizes and values are calculated on the environment states like threadIdx, blockDim, gridDim... Also try to avoid conditional loops. It is better to use for loops with a constant number of runs. This is also easier to optimize.
[ "stackoverflow", "0032997791.txt" ]
Q: Quartz - Duplicate Jobs on 2 Apps, Potential Caching Issue Say I have some tomcat webapp with a quartz job that runs hourly, I've tested it fine on an environment that has one instance of this application running. No duplicate runs, all is as expected. Now I move this application out to a machine that has two environments running concurrently - DEV and QA. They run on separate JDKs, and have separate tomcat installations: /myapp/tomcatD and /myapp/tomcatQ. ps -ef ... admin 32089 1 2 10:14 pts/2 00:01:53 /myapp/java/jdk1.6.0_45_QA/jre/bin/java -Djava.util. ... admin 32296 1 99 11:44 pts/2 00:00:06 /myapp/java/jdk1.6.0_45_DEV/jre/bin/java -Djava. ... At first, I deploy the same build and scheduler.xml to just DEV. It works fine for weeks. Now I deploy to QA and notice that QA has duplicate runs of my scheduled jobs in its logs, and DEV's as well. I schedule DEV's jobs to run at: <value>30 0 * ? * *</value><!-- Every hour on :00 minute :30 second --> And QA's jobs to run at: <value>0 0 * ? * *</value><!-- Every hour on :00 minute --> I observe each log has one run on the XX:00:00 and XX:00:30. At first I am lead to believe that they are simply logging each other's jobs. However when I shut down DEV, I noticed that QA still runs a second instance of the job. I also tried restarting QA with dev still up and that did not work either - duplicate runs still happened. I also tried replacing DEV's scheduler.xml with one that has all jobs commented out. No success. What is going on behind the scenes in regard to Quartz? There must be some caching of these jobs that persists even when the applications are shut down or restarted. Moreover, is there some Quartz process outside of these applications that allows them to run eachother's jobs? A: Revisiting this with the solution in case it helps anyone - there was no issue with quartz, nothing funny going on with the xml. The only problem was someone copied + pasted the application directory in webapp to a different folder that nobody knew about. 2 apps were running simultaneously. tomcat webapps myapp examples some_devious_person_copied_myapp_here and it was running alongside the other one, causing duplicate instances of the jobs
[ "stackoverflow", "0039041653.txt" ]
Q: Autoloading class via PSR-0 I have the following directory structure oop - src - FetchTask.php - tests - FetchTaskTest.php - vendor - composer.json - composer.lock - phpunit.xml // FetchTask.php <?php namespace PHPUnitTuts; class FetchTask { } // FetchTaskTest.php <?php use PHPUnitTuts\FetchTask; class Fetch_Test extends AbstractTest { public function setUp() { $this->fetch = new FetchTask; } public function testStoresListOfAssets($value='') { $this->classHasStaticAttribute('paths', 'FetchTask'); } } // composer.json { "name": "raheel/code", "require-dev": { "phpunit/phpunit": "^5.5", "phpunit/php-code-coverage": "^4", "squizlabs/php_codesniffer": "2.*" }, "autoload": { "psr-0": { "PHPUnitTuts\\": "src/" } }, } // phpunit.xml <phpunit bootstrap="./vendor/autoload.php"> <testsuites> <testsuite name="oop"> <directory>./tests</directory> </testsuite> </testsuites> </phpunit> now when i am running $ vendor/bin/phpunit it says PHP Fatal error: Class 'PHPUnitTuts\FetchTask' not found in /home/raheel/code/oop/tests/FetchTaskTest.php on line 9 Please advice what i am doing wrong. Thanks A: You're mixing concepts of PSR-0 and PSR-4. To use PSR-0 Move src/FetchTask.php to src/PHPUnitTuts/FetchTask.php. To use PSR-4 Change "psr-0": { "PHPUnitTuts\\": "src/" } To "psr-4": { "PHPUnitTuts\\": "src" } Suggested Structure . ├── composer.json ├── phpunit.xml.dist ├── src │   └── FetchTask.php └── test └── FetchTaskTest.php composer.json { "name": "raheel/code", "require-dev": { "phpunit/phpunit": "^5.5", "phpunit/php-code-coverage": "^4", "squizlabs/php_codesniffer": "2.*" }, "autoload": { "psr-4": { "PHPUnitTuts\\": "src" } } } phpunit.xml.dist <phpunit bootstrap="vendor/autoload.php"> <testsuites> <testsuite name="oop"> <directory>test</directory> </testsuite> </testsuites> </phpunit> src/FetchTask.php <?php namespace PHPUnitTuts; class FetchTask extends \PHPUnit_Framework_TestCase { public static $paths = []; } test/FetchTaskTest.php <?php namespace PHPUnitTuts; class FetchTaskTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->fetch = new FetchTask(); } public function testStoresListOfAssets() { $this->assertClassHasStaticAttribute('paths', FetchTask::class); // or $this->assertClassHasStaticAttribute('paths', get_class($this->fetch)); // or $this->assertClassHasStaticAttribute('paths', 'PHPUnitTuts\\FetchTask'); } }
[ "stackoverflow", "0022943432.txt" ]
Q: JQuery doesn't work unless I refresh I'm trying to fadeIn a Circle in my Rails 4 app and it only works when I refresh the page. This is my JQuery so far $(document).ready(function() { $(".circle-div").hide().fadeIn(2000); }) I tried using doing $(document).ready(function() { location.reload($(".circle-div").hide().fadeIn(2000)); }) And it just reloads all my pages non stop. Help would be much appreciated. A: Give this a whirl: $(document).ready(function() { $(".circle-div").hide().delay(500).fadeIn(2000); });
[ "stackoverflow", "0032347347.txt" ]
Q: Bash - getting return code, stdout and stderr form piped invocations I made a simple logger which has method logMETHOD. It's job is to Put stderr and stdout to a variable log (and later to my global _LOG variable) Print stderr of invoked method on stderr and stdout on stdout so I can see it in a console. Return the return code of a invoked function. It's invocation looks like this: logMETHOD myMethod arg1 arg2 arg3 I figured out how to put standard and error output to both log variable and a console but I cannot get the right return code. My code so far: function logMETHOD { exec 5>&1 local log log="$($1 ${@:2} 2>&1 | tee /dev/fd/5)" local retVal=$? _LOG+=$log$'\n' return $retVal } Unfortunately the return code I get comes from (probably) assigning a value (or from tee maybe). BONUS QUESTION: Is there a possibility to achieve my goals without 2>&1 which connects stdout with stderr also for console? I tested solution with 'PIPESTATUS' but the code is still 0. function main { logMETHOD alwaysError } function logMETHOD { exec 5>&1 local log local retVal log="$( "$@" 2>&1 | tee /dev/fd/5 )" retVal=${PIPESTATUS[0]} echo "RETVAL: $retVal" echo "LOG: $log" _LOG+=$log$'\n' return $retVal } function alwaysError { return 1 } main $@ A: PIPESTATUS would be a good solution, but here it already holds the return value of the log=... assignment. If you want the return value of the "$@"... you have to write it like this: log="$( "$@" 2>&1 | tee /dev/fd/5; echo ${PIPESTATUS[0]}>/tmp/retval )" retVal=$(</tmp/retval) Assigning it to a variable would not work, because its scope would not extend to the calling shell, so you have to resort to using a tempfile. As for stderr, $() can only extract stdout, therefore you have to use a tempfile for that too, if you want to handle it separately. log="$( "$@" 2>/tmp/stderr | tee /dev/fd/5; echo ${PIPESTATUS[0]}>/tmp/retval )" stderr_log=$(</tmp/stderr) retVal=$(</tmp/retval) If you just want to spare the redirection: log="$( "$@" |& tee /dev/fd/5; echo ${PIPESTATUS[0]}>/tmp/retval )" From man bash: If |& is used, command's standard error, in addition to its standard output, is connected to command2's standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.
[ "superuser", "0001337381.txt" ]
Q: 3x 8GB RAM sticks installed but 1 stick is recognized as 512MB instead of 8GB I recently installed some new RAM, but I am not sure why one of the sticks is read as 512MB when it should be 8GB. I have tried reseating the RAM and resetting CMOS via battery and jumper but it still doesn't work. Is this because the RAM or mobo is faulty? I am running 64-bit Windows 10, using G.SKILL Ripjaws V Series RAM. A: Yes, this does probably mean "the RAM or mobo is faulty". Or maybe just incompatible. But the most likely cause is that the RAM is faulty. Don't use this computer for anything important, like loading an operating system that interacts with data that you deem important. A lot of software will randomize RAM locations due to some security benefit, so your impact may be random. Your computer might work just fine, once, or it might cause invisible errors that affect some data and cause more problems down the road. You've done well already (e.g., re-seating RAM). The next recommended step is to see if the RAM stick passes a memory test (ideally in another computer, as if the problem follows the RAM stick and not the motherboard, that helps to verify the likely conclusion that the issue is with the RAM stick). Note that although you've made great headway, and I'm saying the RAM stick is the most likely culprit, I wouldn't rule things out until confirming that problems follow the RAM stick, and not the motherboard. (And if the problem is with the motherboard, maybe the issue is outdated firmware which could be fixed with a firmware update.) So I would say that your troubleshooting efforts don't appear to be finalized quite yet.
[ "stats.stackexchange", "0000255352.txt" ]
Q: Famous historical example(s) of Type II error It's very easy to find famous examples of Type I errors in the histories of various fields. However, I'm struggling to find even one clear example of a Type II error. For my purposes, I'm specifically looking for an example that: can be easily described to an undergraduate class in a few minutes or less actually occurred (rather than being hypothetical) A: "The harm done by tests of significance" (pdf) relates 3 true stories in which not rejecting the null while it was actually false (so making a Type II error) has been interpreted as accepting the null and had lead to bad general interest decisions. Here is a brief summary of one of them: The practice of allowing right-turn-on-red (or RTOR) at signalized intersections started in California in 1937. To see weither this can be generalized to other state, a consultant did before–after study at 20 intersections for Virginia and concluded, quite correctly, that the change was not statistically significant. More published studies followed. An example: one study in 1977 found that there were 19 crashes involving right turning vehicles before and 24 after allowing RTOR and "conclude correctly that “this increase in accidents in not statistically significant, and therefore it cannot be said that this increase in RTOR accidents is attributable to RTOR”". Several small studies all pointing in the same direction get published but with statistically not significant results continued to accumulate all concluding that there was no significant difference in crashes. "After RTOR became nearly universally used in North America, several large data sets became available and the adverse effect of RTOR could be established." The author concludes: Researchers obtain real data which, while noisy, time and again point in a certain direction. However, instead of saying: “here is my estimate of the safety effect, here is its precision, and this is how what I found relates to previous findings”, the data is processed by NHST, and the researcher says, correctly but pointlessly: “I cannot be sure that the safety effect is not zero”.
[ "stackoverflow", "0032397623.txt" ]
Q: Remove navigation bar from WPF Pages application I have a WPF/XAML Window that navigates different Pages. The navigation is performed this way: MainFrame.Navigate(new LoginPage(this)); The problem is that, at the first navigation, a bar appears on top of the Window: How can I remove/hide it? A: Step 1. In your Frame Tag Add the Event ContentRendered. as <Frame Name="myFrame" ContentRendered="myFrame_ContentRendered" ></Frame> Step 2. In the ContentRendered event handler set the NavigationUIVisibility Hidden for each page instead on calling the same on all the pages as. private void myFrame_ContentRendered(object sender, EventArgs e) { myFrame.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Hidden; } or simply use : <Frame Source="YOURPAGE.xaml" NavigationUIVisibility="Hidden" />
[ "stackoverflow", "0014008127.txt" ]
Q: Gcode to tell a RepRap 3D printer he is in the middle of the heat bed? Is there a way to tell a RepRap 3D printer that he is in the middle of a heatbed using a specific gcode? A: You can set the coordinates to start at center (once you are already there) via G91: G91: Set to Relative Positioning Example: G91 All coordinates from now on are relative to the last position from http://reprap.org/wiki/G-code#M117:_Get_Zero_Position
[ "stackoverflow", "0051489869.txt" ]
Q: Program that multiplies all prime numbers under 10 by 1,2,3,4,5 I already wrote some code and would like to know how to make all the prime numbers under 10, (2,3,5,7) to be multiplied by the first 5 digits above 0, (1,2,3,4,5). Here n on the 5th line would be the prime numbers under 10. package sct; public class PrimeNumberMultiplicationTables { } public static void main(String[] args) { int n = ??? ; for(int i=1; i <= 5; i++) { System.out.println(n+" multiplied by "+i+" = "+n*i); } } } Thank you in advance to whoever finds this. A: Here it is in C#, you can convert it to java. class Program { static void Main(string[] args) { for (var i = 1; i <= 10; i++) { if (!IsPrime(i)) continue; for (var j = 1; j <= 5; j++) { var value = i * j; Console.WriteLine(i + " multiplied by " + j + " = " + value); } } Console.ReadLine(); } public static bool IsPrime(int candidate) { if ((candidate & 1) == 0) { return candidate == 2; } for (var i = 3; (i * i) <= candidate; i += 2) { if (candidate % i == 0) { return false; } } return candidate != 1; } } Adding Java Version: public class HelloWorld{ public static void main(String []args){ for (int i = 1; i <= 10; i++) { if (!IsPrime(i)) continue; for (int j = 1; j <= 5; j++) { int value = i * j; System.out.println(i + " multiplied by " + j + " = " + value); } } } public static boolean IsPrime(int candidate) { if ((candidate & 1) == 0) { return candidate == 2; } for (int i = 3; (i * i) <= candidate; i += 2) { if (candidate % i == 0) { return false; } } return candidate != 1; } }
[ "stackoverflow", "0047000415.txt" ]
Q: Tutorial On YouTube is using CInt While it does not exist Hello recently I decided to try to attempt to make something very small without using Unity. When I ran into a YouTube tutorial to change text into an integer for addition it said do Dim firstNum As Integer = CInt(txtAddVal1.Text) Dim secondNum As Integer = CInt(txtAddVal2.Text) I was able to change a bit of the code from my previous experience to int firstNumber = My problem here is that I don't know how to convert this CInt into a variable that actually exists now. I am using Windows App Forms (.NET). A: Code you have here is VB.NET not C#. CInt() from VB.NET can be replaced with (int)variable in C# int firstNum = (int)txtAddVal1.Text int secondNum = (int)txtAddVal2.Text Other options are int.Parse() and int.TryParse() https://www.dotnetperls.com/parse
[ "magento.stackexchange", "0000046864.txt" ]
Q: Retrieve Invoices of a Customer from SOAP API v2 WS-I salesOrderInvoiceList gives me a list of the invoices: object(stdClass)[5] public 'complexObjectArray' => array (size=9) 0 => object(stdClass)[6] public 'increment_id' => string '100000001' (length=9) public 'created_at' => string '2014-12-02 04:05:47' (length=19) public 'order_currency_code' => string 'AUD' (length=3) public 'order_id' => string '688' (length=3) public 'state' => string '2' (length=1) public 'grand_total' => string '70.0000' (length=7) public 'invoice_id' => string '448' (length=3) 1 => object(stdClass)[7] public 'increment_id' => string '100000002' (length=9) public 'created_at' => string '2014-12-02 04:08:49' (length=19) public 'order_currency_code' => string 'AUD' (length=3) public 'order_id' => string '687' (length=3) public 'state' => string '2' (length=1) public 'grand_total' => string '60.0000' (length=7) public 'invoice_id' => string '449' (length=3) Is there a way to retrieve invoices based on the customer ID and/or email? Do I need to create my own API? A: The Magento documentation on salesOrderInvoiceList states that you can apply "complex filters" Reading from the example, I think you can achieve this doing: $client = new SoapClient('http://magentohost/api/v2_soap/?wsdl'); $session = $client->login('apiUser', 'apiKey'); $complexFilter = array( 'complex_filter' => array( array( 'key' => 'customer_id', 'value' => array('key' => 'eq', 'value' => '1234') ) ) ); $result = $client->salesOrderInvoiceList($session, $complexFilter);
[ "stackoverflow", "0060290812.txt" ]
Q: Nativescript Vue Image stretch aspectFill not working I am working on a Nativescript-vue app, and am having a strange problem with the Image component not sizing correctly. I am trying to use stretch="aspectFill" to correctly size an image for a component. It works initially when live previewing in the ios simulator, but when you next render the component it reduces size to fit the space rather than aspectFill. My component code is below. <StackLayout> <Image :src="promo.image" stretch="aspectFill" height="200" /> <StackLayout class="promocontainer" row="1" padding="0"> <GridLayout columns="*,*" class="region"> <Label col="0" :text="promo.region" /> <Label col="1" :text="'$' + promo.price" textAlignment="right" /> </GridLayout> <Label :text="promo.inclusions_heading" class="heading" /> <Label :text="promo.heading" padding="10" textWrap="true" class="tagline" /> <Label :text="promo.introText" padding="10" textWrap="true" class="text" /> </StackLayout> </StackLayout> When you change the strech option, the live preview in ios show the intended behavior as shown below When interacting with the app, navigating away from this page and back, or previewing on a physical ios device, the image is show as below, instead of the intended aspect filled image as above. I am hoping someone has run into this before and might be able to assist with working out a solution. A: The component was being added to a ListView, which was causing the rendering issues above. I resolved this by instead wrapping the components in a ScrollView and StackLayout. This solved the stretch rendering issue straight away. Original code with stretch bug: <ListView for="promo in promos" @itemTap="onPromoTap"> <v-template> <PromoListItem :promo="promo" /> </v-template> </ListView> Solution: <ScrollView> <StackLayout> <PromoListItem margin="10" v-for="promo in promos" :key="promo.heading" :promo="promo" /> </StackLayout> </ScrollView> It looks like ListView calculates it's item sizing differently, and is not compatible with Image stretch, at least when there is other content involved.
[ "stackoverflow", "0050190666.txt" ]
Q: Apache FOP - The method getDefaultHandler() is undefined for the type Fop I have a requirement to convert XML to PDF document for that am using XSL - Apache FOP (Java). Am getting the below error The method getDefaultHandler() is undefined for the type Fop for the below line Result res = new SAXResult(fop.getDefaultHandler()); Please find my complete JAVA code. public static void main (String args[]) { // the XSL FO file File xsltfile = new File("sample2.xsl"); // the XML file from which we take the name StreamSource source = new StreamSource(new File("sample2.xml")); // creation of transform source StreamSource transformSource = new StreamSource(xsltfile); // create an instance of fop factory FopFactory fopFactory = FopFactory.newInstance(); // a user agent is needed for transformation FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // to store output ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Transformer xslfoTransformer; try { xslfoTransformer = getTransformer(transformSource); // Construct fop with desired output format Fop fop; try { fop = fopFactory.newFop (MimeConstants.MIME_PDF, foUserAgent, outStream); // Resulting SAX events (the generated FO) // must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing try { // everything will happen here.. xslfoTransformer.transform(source, res); // if you want to get the PDF bytes, use the following code //return outStream.toByteArray(); // if you want to save PDF file use the following code File pdffile = new File("Result.pdf"); OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); FileOutputStream str = new FileOutputStream(pdffile); str.write(outStream.toByteArray()); str.close(); out.close(); } catch (TransformerException e) { throw e; } } catch (FOPException e) { throw e; } } catch (TransformerConfigurationException e) { throw e; } catch (TransformerFactoryConfigurationError e) { throw e; } } private static Transformer getTransformer(StreamSource streamSource) { // setup the xslt transformer net.sf.saxon.TransformerFactoryImpl impl = new net.sf.saxon.TransformerFactoryImpl(); try { return impl.newTransformer(streamSource); } catch (TransformerConfigurationException e) { e.printStackTrace(); } return null; } Please find my dependencies: <!-- https://mvnrepository.com/artifact/fop/fop --> <dependency> <groupId>fop</groupId> <artifactId>fop</artifactId> <version>0.20.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/fop --> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>fop</artifactId> <version>2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.saxon/Saxon-HE --> <dependency> <groupId>net.sf.saxon</groupId> <artifactId>Saxon-HE</artifactId> <version>9.8.0-11</version> </dependency> A: You have both an old and a new version of fop in your dependencies. So your IDE or Java compiler must be picking up the old version, which does not have that method. Remove the old version from your dependencies.
[ "wordpress.stackexchange", "0000016782.txt" ]
Q: Widgets with groups / sub widgets? Widget in a widget? I tried to find anything about adding a widget within a widget area. That widget should be a widget group / sub widget area. I've found a plugin that does this: http://wordpress.org/extend/plugins/extensible-widgets/ http://jidd.jimisaacs.com/files/2010/02/wpew-screen-9.png What I really want is to dynamically create something like this without the help from plugins: http://www.gabfirethemes.com/demos/newspro/ Any bright ideas? A: if you take a look at Tabber Tabs Widget plugin does it you will see that it creates a widget and a new "sidebar", now if you place widgets in that sidebar they will show only where you place the plugins widget. and if you look at what Tabbed Widgets plugin does, it creates a widgets that pulls a list of all registered widgets in to a dropdown and lets you choose which ones you want. both seem like nice ways to achieve that , depends on what you need.
[ "stackoverflow", "0005829219.txt" ]
Q: How to insert and format values cell by cell in an XLSX file using openpyxl I am trying to write an XLSX file using the openpyxl module. I am using the append() method to insert the values row by row. But I want to insert the values cell by cell instead. I would also like to format the cell (font, colour, alignment etc). Please help me. A: You can set all that cell by cell (if that is what you need) using openpyxl. Here is a small example which sets the value, name (named_range) and some style of cells in a workbook: from openpyxl.workbook import Workbook wb = Workbook() dest_filename = r'empty_book.xlsx' ws = wb.worksheets[0] name = 'name' for col_idx in xrange(1, 101): col = get_column_letter(col_idx) for row in xrange(1, 1001): ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row) ws.cell('%s%s'%(col, row)).style.fill.fill_type = 'solid' ws.cell('%s%s'%(col, row)).style.fill.start_color.index = openpyxl.style.Color.DARKYELLOW wb.create_named_range(name+str(i), ws, '%s%s'%(col, row)) wb.save(filename = dest_filename) Look up the Style class in the openpyxl documentation to learn more about how to set individual formattings.
[ "stackoverflow", "0046203171.txt" ]
Q: Set icon onPress based on the state I'm trying to set the onPress to call a action to dispatch of an Icon, depending on a state in Redux. <MaterialIcons name="arrow-upward" size={30} style={mystyles1.myIcon} onPress = this.props.style.name === 'styleNormal' ? {() => this.props.changeStyleNew('styleNew')} : {()=>this.props.changeStyleNormal('styleNormal')} > </MaterialIcons> So if the this.props.style.name === 'styleNormal' the first function (changeStyleNew) should be passed, if not the second (changeStyleNormal). I'm not able to achieve this. I'm getting an error: TransformError C:/.../ExtComp02.js: JSX value should be either an expression or a quoted JSX text (94:19) How can I achieve this? Many thanks. A: You need to keep the expression inside curly brackets {} like this <MaterialIcons name="arrow-upward" size={30} style={mystyles1.myIcon} onPress = { this.props.style.name === 'styleNormal' ? () => this.props.changeStyleNew('styleNew') : ()=>this.props.changeStyleNormal('styleNormal') } > </MaterialIcons>
[ "stackoverflow", "0016765492.txt" ]
Q: DevExpress Pie Chart Legend Text (asp.net) I have just started using DevExpress Charting Components and I am trying out a Pie Chart. It works fine, but I have a problem and I can't find the answer anywhere even though it's probably quite simple. The Legend shows the percentages but I need it to show the "ArgumentDataMember" otherwise the legend is not really helpful. This is the short code: Series series1 = new Series("Series1", ViewType.Pie3D); chartControl.Series.Add(series1); series1.DataSource = dt; series1.ArgumentScaleType = ScaleType.Qualitative; series1.ArgumentDataMember = "CategoryName"; series1.ValueScaleType = ScaleType.Numerical; series1.ValueDataMembers.AddRange(new string[] { "Products" }); series1.LegendText = series1.ArgumentDataMember; chartControl.Legend.Visible = true; Obviously series1.LegendText = series1.ArgumentDataMember; didn't work. Does anybody know how to use the argument (data name) as legend text instead of the values? A: Series series1 = new Series("Series1", ViewType.Pie3D); chartControl.Series.Add(series1); series1.DataSource = dt; series1.ArgumentScaleType = ScaleType.Qualitative; series1.ArgumentDataMember = "CategoryName"; series1.ValueScaleType = ScaleType.Numerical; series1.ValueDataMembers.AddRange(new string[] { "Products" }); // series1.LegendText = series1.ArgumentDataMember; series1.PointOptions.PointView = PointView.Argument; //this is code that you want //if you only legend box change series1.LegendPointOptions.PointView = PointView.Argument; chartControl.Legend.Visible = true;
[ "stackoverflow", "0032739413.txt" ]
Q: Tooltip hide/show doesn't work in Bootstrap I use bootstrap 3 and have a button and input. I would like to show tooltip if button is disabled and hide tooltip if type of button is submit. In my snippet .tooltip('hide') method doesn't work and I don't know why. jsfiddle html <div class=" user-attributes"> <input type="text" name="attrName" /> <button type="submit" data-toggle="tooltip" title="Please select attribute name" class="btn btn-default disabled" name="addAttribute" >Add attribute</button> </div> javascript $('button[data-toggle="tooltip"]').tooltip({ animated: 'fade', placement: 'bottom', }); /* allow bootstrap tooltip for disabled buttons */ $('.user-attributes button[type="submit"]').css('pointer-events', 'auto'); $( ".user-attributes [name='attrName']" ).bind('input', function(){ var inputIsEmpty = $(this).val().length < 1; if (inputIsEmpty){ $('.user-attributes button[type="submit"]').addClass('disabled'); $('.user-attributes button[type="submit"]').removeAttr('type'); $('.user-attributes button[type="submit"]').css('pointer-events', 'auto'); $('button[data-toggle="tooltip"]').tooltip('show'); } else { $('.user-attributes button[type="submit"]').removeClass('disabled'); $('.user-attributes button[type="submit"]').removeAttr('style'); $('.user-attributes button[type="submit"]').attr('type', 'submit'); $('button[data-toggle="tooltip"]').tooltip('hide'); } }); A: .tooltip('destroy'); helped. jsfiddle
[ "rpg.stackexchange", "0000016949.txt" ]
Q: When should I separate encounters? I had a session this week involving a fairly large battle at sea. The encounter involved a couple of boarders while the enemy ship was still at quite a distance, and the larger group still on the ship. I modeled this as a single hard encounter (APL+3) which didn't work out well, as it was split up by a fair number of rounds which made it play out as two smaller encounters, the first of which was a pushover. How can I know when I should play something as two separate encounters instead of one? A: Well, the simplest answer is "if encounter 1's going to be done 3 or so combat rounds before encounter 2 starts." You can't always do this; smart tacticians will try to break up encounters for that exact reason, and that's part of the reward of being a smart tactician. We did this in our Jade Regent game recently; there was a hobgoblin keep with drawbridge, parapet with archers on it, and melee troops inside. So we dimension doored to the second floor, wall of iced the stairwell, and killed us some archers. Then the melee guys came busting through the ice but only after we'd killed the archers and had a round to buff and BS with each other. It would have been a very difficult encounter without the separation; with it, it was easy (though we did blow two 4th level spells on it). It can go the other way; dumb or unlucky players can end up "pulling" bunches of adjacent foes in a dungeon or whatnot. I consider this to be a feature of earlier D&D rather than the "set number of army points!" approach of some later editions . Sometimes you eat the bar, sometimes the bar eats you. All you can do is do best-guess planning of most likely outcome. It's OK for the PCs to rock a combat every once in a while, makes them feel all manly and stuff. Then you can really outclass them and see what happens (Last weekend I tossed 2 CR 12's and some trash mobs against a 6th level party to see what happened. Took like 4 hours but they won.).
[ "stackoverflow", "0020393409.txt" ]
Q: Advice written for method in spring AOP not go in infinite callbacks I am new to Spring AOP.Let me explain the question. I have class Circle public class Circle { private String name; public void setName(String name) { this.name = name; } public String getName() { System.out.println("Circle getName called"); return name; } } Now i have set advice getterAdvice() to call before getName() method from class Circle as show in following code. @Before("allGetters()") public void getterAdvice(JoinPoint joinPoint){ System.out.println("getter Advice is called"); ((Circle)joinPoint.getTarget()).getName(); } @Pointcut("execution(* com.example.Circle.get*(..))") void allGetters(){} Output when call getName: getter Advice is called Circle getName called Circle getName called Now i call getter method from Circle ie getName().It will first execute advice method and then getName() method.But i have called getName() again from advice. Still it is not again executing advice and not goes in to infinite calls.How Spring AOP acts with such a call?.Does advice executes only once for one method? The intent of this question is to only understand the execution flow and working of AOP in Spring 3.0. Your response will be greatly appreciated. A: I suggest a read of the AOP chapter, especially the section explaining proxies. In short spring uses proxies to apply AOP so methods going into the object will pass through the proxy and will be adviced. In your aspect you are doing a getTarget which returns the actual target (the unproxied object', the plain instance of your Circle object) and not the proxy.
[ "stackoverflow", "0043755609.txt" ]
Q: TensorFlow Estimator : model_fn has following not expected args: ['self'] I'm using TensorFlow (1.1) high-level API Estimators to create my neural net. But I'm using it into a class and I have to call an instance of my class to generate the model of the neural network. (Here self.a) class NeuralNetwork(object): def __init__(self): """ Create neural net """ regressor = tf.estimator.Estimator(model_fn=self.my_model_fn, model_dir="/tmp/data") // ... def my_model_fn(self, features, labels, mode): """ Generate neural net model """ self.a = a predictions = ... loss = ... train_op = ... return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, train_op=train_op) But I get the error : ValueError: model_fn [...] has following not expected args: ['self']. I tried to remove the self for the args of my model but got another error TypeError: … got multiple values for keyword argument. Is there any way to use these EstimatorSpec into a class ? A: It looks like the Estimator's argument checking is a bit overzealous. As a workaround, you can wrap the member-function model_fn in a lambda like so: import tensorflow as tf class ModelClass(object): def __init__(self): self._constant = 2. self.regressor = tf.estimator.Estimator( model_fn=lambda features, labels, mode: self._model_fn( features, labels, mode)) def _model_fn(self, features, labels, mode): loss = tf.constant(self._constant) train_op = tf.no_op() return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op) ModelClass() However, this is rather annoying. Would you mind filing a feature request on Github to relax this argument checking for member functions? Update: Should be fixed in TensorFlow 1.3+. Thanks, Yuan!
[ "ell.stackexchange", "0000221049.txt" ]
Q: Valency of being situated Being situated seems to need some kind of complement. According to Cambridge Dictionary, it may be used in the following ways: with in/on/near/... with an adverb with a to-infinitive However, it appears that in the following passage it is not used in any of the above-mentioned ways, and I cannot make sense of the sentence. Am I making a mistake here? [T]here is no privileged point where one can ground the entire enterprise, and from which one can build up everything else. However, I take it that all knowledge, about logic, as much as anything else, is situated. + A: Penelope Rush means that every new piece of information is learned and internalized in our minds in the context of old pieces of information. Her next sentence is something like "We are not, and could never be, tabulae rasa." Tabulae rasa means “blank slate”. In other words, it is not possible to learn something new without the new information being filtered and interpreted through our current opinions and understanding of the world. As Jason Bassford pointed out in his comment below, “situated” is an intransitive verb, and does not require a direct object, so the usage is correct.
[ "stackoverflow", "0056908484.txt" ]
Q: I can't get my javascript to toggle my login dropdown. Why is javascript not connecting to my html? I checked and rechecked my script link but it's not connecting to html. I must be doing something wrong but I don't see it. I'm trying to connect javascript to the Log in button, so it shows and hides the log in form. ''' <script type="text/javascript" src="/js/script.js"></script> function myFunction() { document.getElementsById("myDropdown").classList.toggle("show"); } window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown_content"); var i; for (i = 0; i < dropdowns.lenth; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } <div id="login"> <ul class="login_signup"> <li class="dropdown"> <button onclick="myFunction()" class="dropbtn"> Log in <span>▼</span> </button> <div id="myDropdown" class="dropdown_content"> <form> <fieldset id="inputs"> <input id="username" type="email" name="Email" placeholder="Your email address" required> <input id="password" type="password" name="Password" placeholder="Password" required> </fieldset> <fieldset id="actions"> <input type="submit" id="submit" value="Log in"> <label><input type="checkbox" checked="checked"> Keep me signed in</label> </fieldset> </form> </div> </li> <li id="signup"> <a href="">Sign up</a> </li> </ul> </div> I would like to connect this js to the login button in html. A: The function is getElementById() without the s in Elements, because there can be only one element with a given ID Also, you if you want to use relative paths you should remove the / from src="/js/script.js". / means start from the root path of your web server, and without it it means search the file starting from the file you are on right now. function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown_content"); var i; for (i = 0; i < dropdowns.lenth; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } <style> .dropdown_content { display: none; } .show { display: inherit !important; } </style> <div id="login"> <ul class="login_signup"> <li class="dropdown"> <button onclick="myFunction()" class="dropbtn"> Log in <span>▼</span> </button> <div id="myDropdown" class="dropdown_content"> <form> <fieldset id="inputs"> <input id="username" type="email" name="Email" placeholder="Your email address" required> <input id="password" type="password" name="Password" placeholder="Password" required> </fieldset> <fieldset id="actions"> <input type="submit" id="submit" value="Log in"> <label><input type="checkbox" checked="checked"> Keep me signed in</label> </fieldset> </form> </div> </li> <li id="signup"> <a href="">Sign up</a> </li> </ul> </div>
[ "stackoverflow", "0012867983.txt" ]
Q: How can I use jQuery to insert a new table row as the second row of a table? I have a table like this: <table id="myTable"> <tr> <td>Stuff</td> </tr> <tr> <td>Stuff</td> </tr> // etc. </table> I want to insert a new table row into the above table so it is the second row. I know that I can use prepend() to insert the row as the 1st row, but I can't figure out how to insert it as the second row. Here is what I am using: $.ajax({ type: "POST", url: 'get_new_table_row.php', success: function(data){ $('table#myTable').prepend(data); } }); return false; How can I modify this to make it insert the new row as the 2nd row in the table? A: You can use after method and :first selector: $('#myTable tr:first').after(data); or: $('#myTable tr').eq(0).after(data);
[ "stackoverflow", "0052050103.txt" ]
Q: Background Service don't work - Android I try to run a method in my service every two seconds, but when i start the services just run one time This is the relevant code: the start service: mViewHolder.mLinearLayoutContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent launchIntent = view.getContext().getPackageManager().getLaunchIntentForPackage(mListStorage.get(position).getAdrress()); mApkPackage = mListStorage.get(position).getAdrress(); Intent intent = new Intent(view.getContext(), KillerService.class); if(mApkPackage != null){ intent.putExtra("NAMEAPK", mApkPackage); view.getContext().startService(new Intent(view.getContext().getApplicationContext(), KillerService.class)); view.getContext().bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE); } if (launchIntent != null) { view.getContext().startActivity(launchIntent);//null pointer check in case package name was not found } } }); And this is from my Service class: @Override protected void onHandleIntent(@Nullable Intent intent) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //mAppsNames(); Log.d("SYSTEMRUNNIGKILLI", "matandoapps"); } }, 2000); } @Nullable @Override public IBinder onBind(Intent intent) { mApkName = intent.getStringExtra("NAMEAPK"); Log.d("HOLAXD", mApkName); return null; } @Override public void onCreate() { super.onCreate(); } The part of Log.d("SYSTEMRUNNIGKILLI", "matandoapps"); just run one time and not every 2 seconds. A: You are using wrong method to call code after every 2 seconds . Try to use this method new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() {} }, 0, 1000); //1000 miliseconds equal to 1 second
[ "stackoverflow", "0016872137.txt" ]
Q: NSDistributedNotificationCenter listen for undocumented Apple Notifications I am developing a Mac OS X app for a client which has a feature where it displays the current default Text-to-Speech voice, and they want this to change when the user changes that through System Preferences. I have done a little experimenting and found that the system post a notification through the NSDistributedNotificationCenter called "com.apple.speech.DefaultVoiceChangedNotification". Are there any rules against this with app on the Mac App store. Does this count as using an undocumented API. The alternative would be to poll for changes, yuk. A: It's not an API per se, just a notification you're listening for - I suppose the biggest risk you're taking is that it'll break with even a minor OS update. Unlikely that this will cause problems in the MAS approval process. No guarantees, though ;-)
[ "stackoverflow", "0025542863.txt" ]
Q: ef6 database migrations change table name I am using EF6 code first and database migrations to keep my new database up do date. I wanted to change the name of one of the database tables from "contacts" to "contact". So in EF I change the name of the class and in the customised DBContext class I rename Contacts to Contact so it is now showing; public DbSet<Contact> Contact { get; set; } However I run the database migrations with Update-Database -Verbose -Force and no change is made. To find out what is going on I put a new field in, and it tries to update the Contacts table rather than Contact which it needs to create. So how do I fix this? A: Try removing Pluralizing: protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); }
[ "math.stackexchange", "0003690589.txt" ]
Q: Riemann Integration vs Lebesgue Integration If a function is not Riemann integrable, what does it mean geometrically? Is it that we can't use integration to find out area under the curve? So basically when a function is Riemann integrable then it can tell us about area. I am asking this because I saw a function which is not Riemann integrable but Lebesgue integrable. What does it mean geometrically? A: Usually non-Riemann integrable functions are pathological functions like the Dirichlet function etc. But these are Lebesgue integrable. One of the main implications of a function being non-Riemann integrable is that it is not continuous enough to have a well-defined area under the curve. But the mathematical definition limits itself to the existence of a limiting sum only. In that sense, it is quite rigorous. I further quote from this article: We realize that both of them can help us to integrate functions. The difference is that the Riemann integral subdivides the domain of a function, while the Lebesgue integral subdivides the range of that function. The step function for Riemann integral has a constant value in each of the subintervals of the partition, while the simple function for Lebesgue integral provides finitely many measurable sets corresponding to each value of that function. The improvement from the Riemann integral to the Lebesgue integral is that the Lebesgue integral provides more generality than the Riemann integral does. From the reverse perspective, the Riemann integral can imply the Lebesgue integral. Hope this helps.
[ "stackoverflow", "0041646970.txt" ]
Q: How to use Translate behavior and .po file to change dynamic text Cakephp3? I'm using translate behavior in cakephp 3 using I18n table. Everything is working fine. But if I use .po file to translate static text the content coming from the database won't change. Can you please help me how to use both Translate behavior and .po file to change dynamic and static text. I used the following code for the translation: echo __($name); Thanks in advance A: I have resolved this using __d() function. This allows you to override the current domain for a single message lookup. Use __d(<your variable>, <domain>); For example echo __d($name, 'default'); default is your .po filename;
[ "stackoverflow", "0037837994.txt" ]
Q: Creating Package feed in Octopus Deploy I am new to using octopus deploy. I am publishing nuget packages from tfs build to local storage. Is there any way Octopus server can check regularly the publishing folder, and if new version/new file is found, it will deploy it to the deployment environment. PS:- I was thinking to create a package feed for local storage but couldn't find any link describing the same. Thanks in advance. :) A: Octopus can automatically trigger deployments when new packages are pushed to the built-in repository, but not to external repositories. Your options are: Enable Automatic Release Creation, and make sure your Project's Lifecycle automatically deploys to your first environment. You'll need to push your package to the built-in server rather than use the filesystem. You can do this fairly easily either with nuget.exe or octo.exe. As the last step of your build, manually create a Release using either the VSTS/TFS Extension, the Octopus REST API, or octo.exe. By default, this will use the newest package it can find (which should be the one you just packed). If your Lifecycle doesn't automatically deploy to an environment, you can deploy the Release the same way.
[ "stackoverflow", "0052200459.txt" ]
Q: Is there any way to get the class name of an old style (Borland Pascal) object instance in Delphi 7? I have a lot of descendant of my class: PMyAncestor =^TMyAncestor; TMyAncestor = object public constructor init; destructor done; virtual; // There are virtual methods as well end; PMyDescendant1 =^TMyDescendant1; TMyDescendant1 = object ( TMyAncestor ) end; PMyDescendant2 =^TMyDescendant2; TMyDescendant2 = object ( TMyAncestor ) end; PMyDescendant3 =^TMyDescendant3; TMyDescendant3 = object ( TMyDescendant2 ) end; procedure foo; var pMA1, pMA2, pMA3, pMA4 : PMyAncestor; s : string; begin pMA1 := new( PMyAncestor, init ); pMA2 := new( PMyDescendant1, init ); pMA3 := new( PMyDescendant2, init ); pMA4 := new( PMyDescendant3, init ); try s := some_magic( pMA1 ); // s := "TMyAncestor" s := some_magic( pMA2 ); // s := "TMyDescendant1" s := some_magic( pMA3 ); // s := "TMyDescendant2" s := some_magic( pMA4 ); // s := "TMyDescendant3" finally dispose( pMA4, done ); dispose( pMA3, done ); dispose( pMA2, done ); dispose( pMA1, done ); end; end; Is there any way to get the class name of its descendant instances? I don't want to create a virtual method for this reason (there are thousands of descendants). I know there is the typeOf(T) operator. But what is its return type? OK. Pointer. But what can I cast it for? The cast to PTypeInfo seems to be wrong. A: When I compile this code, and search for the names of your classes in the compiled executable, they are not found. From this I conclude that what you are trying to do is not possible. A: It is not possible to catch the old style object type names. Using TypeOf(), it is possible to test if the object is equal to a type: if TypeOf(pMA1^) = TypeOf(TMyAncestor) then ... It can also be used to build a lookup-table, in order to match with the actual type name. This can be a bit tedious if there are many object types to record in such a table. In a comment, it is said it would be used to catch memory leaks by logging the names during the base object initialization/finalization. Here is an example that does the logging, but instead of the type names, loggs the type names addresses. It also prints the base object name and address, which can be useful to pinpoint leaks. The object addresses are numbered in order of declaration, and it should be fairly straight forward to identify the leaking object with that knowledge. program Project121; {$APPTYPE CONSOLE} uses System.SysUtils; Type PMyAncestor =^TMyAncestor; TMyAncestor = object public constructor init; destructor done; virtual; // There are virtual methods as well end; PMyDescendant1 =^TMyDescendant1; TMyDescendant1 = object ( TMyAncestor ) end; PMyDescendant2 =^TMyDescendant2; TMyDescendant2 = object ( TMyAncestor ) end; PMyDescendant3 =^TMyDescendant3; TMyDescendant3 = object ( TMyDescendant2 ) end; constructor TMyAncestor.init; begin {$IFDEF DEBUG} WriteLn( IntToHex(Integer(TypeOf(Self))), ' Base class - TMyAncestor:', IntToHex(Integer(TypeOf(TMyAncestor)))); {$ENDIF} end; destructor TMyAncestor.done; begin {$IFDEF DEBUG} WriteLn(IntToHex(Integer(TypeOf(Self))),' Done.'); {$ENDIF} end; procedure foo; var pMA1, pMA2, pMA3, pMA4 : PMyAncestor; s : string; begin pMA1 := new( PMyAncestor, init ); pMA2 := new( PMyDescendant1, init ); pMA3 := new( PMyDescendant2, init ); pMA4 := new( PMyDescendant3, init ); try (* Do something *) finally dispose( pMA4, done ); dispose( pMA3, done ); dispose( pMA2, done ); dispose( pMA1, done ); end; end; begin foo; ReadLn; end. Outputs: 0041AD98 Base class - TMyAncestor:0041AD98 0041ADA8 Base class - TMyAncestor:0041AD98 0041ADB8 Base class - TMyAncestor:0041AD98 0041ADC8 Base class - TMyAncestor:0041AD98 0041ADC8 Done. 0041ADB8 Done. 0041ADA8 Done. 0041AD98 Done.
[ "meta.stackoverflow", "0000371762.txt" ]
Q: Disputed Close Vote Review Audit I came across (and failed) this as a Close Vote review audit today: ADB.exe is obsolete and has serious performance problems It looked very off-topic for "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself" reasons to me. Has a quick Google, and apparently posting here specifying the dubious audit is useful. Let me know if this helps, or if any further information is needed. A: Given that ADB is a tool for Android developers, why would you consider this to be off-topic? No code is necessary to replicate the issue that they're observing; if nothing else, installing ADB locally and executing it might be enough to replicate the issue. When it comes to questions seeking debugging help, you have to be certain that code is involved at some point. ADB is a tool which interacts with Android applications at a specific level, but it itself doesn't really touch code. Since I'm not 100% sure if you knew this or not, it would've been best to skip the review. Only review questions you're certain on. Skip the ones that you have any doubts on.
[ "math.stackexchange", "0001999061.txt" ]
Q: Proof of whether endpoints are local extrema Was wondering whether anyone would be able to prove the following statement if it is correct, or if not, then provide a counter example. Consider a differentiable function f on a finite closed interval [a, b]. The endpoints a and b are local extrema of the function. Thanks A: Let $f(x):=x^2\sin(1/x)$ if $x \ne 0$ and $f(0):=0$. Then $f$ is differentiable on $\mathbb R$ (prove this !), but in $0$ there is no local extremum.
[ "stackoverflow", "0002604715.txt" ]
Q: Add functions in gdb at runtime I'm trying to debug some STL based C++ code in gdb. The code has something like int myfunc() { std::map<int,int> m; ... } Now in gdb, inside myfunc using "print m" gives something very ugly. What I've seen recommended is compiling something like void printmap( std::map<int,int> m ) { for( std::map<int,int>::iterator it = ... ) { printf("%d : %d", it->first, it->second ); } } Then in gdb doing (gdb) call printmap( m ) This seems like a good way to handle the issue... but can I put printmap into a seperate object file (or even dynamic library) that I then load into gdb at runtime rather than compiling it into my binary - as recompiling the binary every time I want to look at another STL variable is not fun .. while compiling and loading a single .o file for the print routine may be acceptable. UPDATE: Prompted by Nikolais suggestion I'm looking at dlopen/dlsym. So I haven't yet got this working but it feels like I'm getting closer. In printit.cpp #include <stdio.h> extern "C" void printit() { printf("OMG Fuzzies"); } Compile to a .so using g++ -Wall -g -fPIC -c printit.cpp g++ -shared -Wl,-undefined,dynamic_lookup -o printit.so printit.o Start my test application and load the .so using dlopen ( 2 = RTLD_NOW ) then try to get the symbol for a debugging function using dlsym. (gdb) break main (gdb) run (gdb) print (void*) dlopen("printit.so", 2 ) $1 = (void *) 0x100270 (gdb) print (void*) dlsym( 0x100270, "_printit" ) $2 = (void *) 0x0 So close but for some reason I cant get that symbol... ( I cant even get it if I put the dlopen/dlsym calls in my executable) I'm guessing I'm either compiling the lib wrong or using dlsym incorrectly. If I can get the symbol I'm assuming I can call the function using something like (gdb) print (( void(*)() )(0x....))() I'm compiling this on OS X 10.4, which might be causing some of my .so woes... any pointers would be appreciated. Found out how to get all this working. Have posted as a solution below. A: So my solution is to load a shared object containing my debugging routines at run time, using dlopen. Turns out it is even simpler than I thought when you get all the compile flags right. On OS X this means you compile your application and debugging object like this: all : application.x debug_helper.so application.x : application.cpp g++ -g application.cpp -o application.x -fPIC debug_helper.so : debug_helper.o g++ -dynamiclib -o debug_helper.so debug_helper.o debug_helper.o : debug_helper.cpp g++ -Wall -g -fPIC -c debug_helper.cpp The -fPIC on the application is critical, as is the -dynamiclib (rather than trying the linux -shared flag ) An example debug_helper.cpp might look like this #include <map> #include <stdio.h> extern "C" void printMap( const std::map<int,int> &m ) { printf("Map of size %d\n", int(m.size()) ); for( std::map<int,int>::const_iterator it = m.begin(); it!=m.end(); ++it ) { printf("%d : %d \n", it->first, it->second ); } fflush(stdout); } Don't know why I chose to use stdio rather than iostream stuff... I guess you can use either. (just don't forget to flush the streams...) Now my application file looks like this: #include <map> int main() { std::map<int,int> m; m[1]=2; m[2]=5; m[3]=10; m[4]=17; } And heres an example debugging session (some output removed) Start the application and break at an interesting point (gdb) break main (gdb) run Reading symbols for shared libraries +++. done Breakpoint 1, main () at test.cpp:5 5 std::map<int,int> m; Load in the debug helper library (gdb) print (void*) dlopen("debug_helper.so",2) Reading symbols for shared libraries . done $1 = (void *) 0x100270 (gdb) n 6 m[1]=2; GDB is smart and catches all the new symbols for us so we dont need to use dlsym etc. We can just call the functions directly. (gdb) call printMap(m) Map of size 0 (gdb) n (gdb) n (gdb) n 9 m[4]=17; (gdb) call printMap(m) Map of size 3 1 : 2 2 : 5 3 : 10 Lets add some more info to printMap. First unload the library. (gdb) print (int) dlclose($1) $2 = 0 Edit the source to add in the sum of the entries. Recompile and then load the new library back into gdb (without restarting the executable or gdb ) (gdb) print (void*) dlopen("debug_helper.so",2) Reading symbols for shared libraries . done Use the modified function $3 = (void *) 0x100270 (gdb) call printMap(m) Map of size 3 1 : 2 2 : 5 3 : 10 SUM = 17 I think this does everything that I need.
[ "stackoverflow", "0005695634.txt" ]
Q: Confused about whether return false; is needed or not I'm very new to jQuery and I'm writing some validation logic on a form. With the help of this wonderful community I was able to understand how to post my forms with .ajax() and prevent a postback. I'm using the button.click() event to do this and I know when I need to keep the form from posting I have to put return false; and I understand why. For example: var name = $("input#name").val(); if (name == "") { $("label#lblName").css('color','red'); $("input#name").focus(); return false; } I understand why returning false is important in this case. But at the very end of my submit button click event there is also a return false, like so: $(function() { $("#submitbutton").click(function() { //validate and submit form return false; //WHY is this here? What purpose does it serve? }); }); The reason I ask is that I'm also writing a function to change the label colors back to white on .blur(). Like so: $(function() { $("input#name").blur(function() { var name = $("input#name").val(); if (name == '') { $("label#lblName").css('color','red'); } else { $("label#lblName").css('color',''); } //Do I need return false here? and why? }); }); Thank you! A: return false is used in jQuery event callbacks in order to stop event propagation, or event bubbling. If there is more than one callback in the event chain for this element, this means that none of the events past the one which returns false will be called. This is useful in situations such as the one you posted. A submit button, by default, has an attached event which will submit its containing form. When binding to this submit button's click event, using return false will prevent any previously-registered events from occurring — so your custom click event will be called and the form will not be submitted. For most situations, you don't need to include return false. It's only necessary if you think there might be another handler higher up in the event chain that could receive the event you're dealing with and somehow mix up your code. Extra information: jsFiddle demonstration event.stopPropagation() documentation
[ "stackoverflow", "0038985322.txt" ]
Q: Using Bootstrap Datetimepicker DOM object on multiple ng-views in AngularJS app I am trying to implement two ng-views on an angular app, each of them using a Bootstrap Datetimepicker (https://eonasdan.github.io/bootstrap-datetimepicker/) to select a date. For each view, I have a javascript $(document).ready function (outside of the angular controller, naturally) which configures the Datetimepicker: $(document).ready(function(){ $('#datetimepicker12').datetimepicker({ format: 'YYYY-MM-DD', inline: true, sideBySide: false, minDate: moment() }); var today = $('#datetimepicker12').data("DateTimePicker").getMoment(); $('#datetimepicker12').on('dp.change', function(e) { angular.element(document.getElementById('reservations')).scope().setDate(e.date); }); }); This code configures the DOM div with id #datetimepicker12 When I load the initial view, everything works as expected and the datetimepicker is properly configured and shown. But when I change the ng-view, naturally the $(document).ready is not called again, as it was already called before when first loading the app, and the datetimepicker object that should appear on the new ng-view is not configured once again. As a result, it is not shown any longer. Neither on the second nor first partial. It only appears again if I refresh the page. But then disappears if I change the partial inside the app. Is there a way around this? I thought a possibility would be to try to call a function outside the angular controller in order for it to be able to configure the object with the .datetimepicker() function. Any suggestions? Thanks! A: What actually solved my issue was creating an angular directive for the datetimepicker. With it, I was able to access the JQuery object I wanted and use the datetimepicker formatting functions. I applied the following directive: module.directive('datetimepicker', function() { return function(scope, element, attrs) { element.datetimepicker({ format: 'YYYY-MM-DD', inline: true, sideBySide: false, minDate: moment() }); var today = $('#datetimepicker12').data("DateTimePicker").getMoment(); element.on('dp.change', function(e) { angular.element(document.getElementById('reservations')).scope().setDate(e.date); }); } }); Then on the DOM element, I just added the 'datetimepicker' attribute to the div which held the datetimepicker.
[ "stackoverflow", "0032953749.txt" ]
Q: Operation on data frame in loop with changing dataframe names I have six data frames , z1, z2, ...z6. (read from six different sheets of a single excel file). I need to do subsetting on these data frames and build some models. The process is identical for each of them. I was hoping to do it in a loop but not able to find the right syntax. (I am trying to use paste and assign functions but it does not help). For example I want for (i in 1:6){ Z=subset(Zi,Zi$var1==1) } Zi should be Z1, Z2, Z3 exactly which are already defined. I can generate a variable through paste function which is Z1, Z2 in each iteration like temp=paste('Z',i,sep='') but I cannot use 'temp' in place of Zi in the above code. There is some discussion on other threads on similar problem but I am not able to find anything directly related there. If I am missing something, please point me to the right thread. A: We get the 'values' in a list using mget, loop over the list (lapply(..)) and subset` the rows based on the 'var1' column. lapply(mget(paste0('Z', 1:6)), subset, subset=var1==1)
[ "stackoverflow", "0048566158.txt" ]
Q: How to create text file using Groovy? I am trying to create a new text file using the below lines of Groovy code in Soap UI but I do not see the file is created import java.io.File def newFile = new File("C:/Users/ramus/Documents/Jars/test.txt") Could you please help me in understanding on what is wrong with the above lines of code? A: new File(path) means create pointer to file or directory with selected path. Using this pointer you can do anything what you want create, read, append etc. If you wish to only create file on drive you can do: def newFile = new File("C:/Users/ramus/Documents/Jars/test.txt") newFile.createNewFile() A: Just an addition to the accepted answer--if you want to create a file with content, you can do this: new File("C:/Users/ramus/Documents/Jars/test.txt").text = "Test text file content" This particular feature is one of my favorite parts of groovy, you can even append to a file with +=
[ "stackoverflow", "0028937106.txt" ]
Q: How to make custom dialog with rounded corners in android What I am trying to do: I am trying to make a custom dialog in android With rounded corners. What is happening: I am able to make custom dialog but it doesn't have rounded corners. I tried adding a selector but still I couldn't achieve rounded corners. Below is my code for the same: Java code: private void launchDismissDlg() { dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dlg_dismiss); dialog.setCanceledOnTouchOutside(true); Button btnReopenId = (Button) dialog.findViewById(R.id.btnReopenId); Button btnCancelId = (Button) dialog.findViewById(R.id.btnCancelId); btnReopenId.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); btnCancelId.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); dialog.setCanceledOnTouchOutside(false); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); dialog.show(); } xml code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" android:orientation="vertical" > <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:gravity="center" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="&quot;I WOULD LIKE TO DISMISS THE VENDOR&quot;" android:textColor="@color/col_dlg_blue_light" android:textSize="14sp" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="BECAUSE" android:textColor="@android:color/black" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btnReopenId" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/col_dlg_green_light" android:text="REOPEN" android:padding="5dp" android:textSize="14sp" android:textColor="@android:color/white" android:textStyle="bold" /> <Button android:id="@+id/btnCancelId" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/col_dlg_pink_light" android:text="CANCEL" android:padding="5dp" android:textSize="14sp" android:textColor="@android:color/white" android:textStyle="bold" /> </TableRow> </TableLayout> </LinearLayout> A: Create a xml in drawable , say dialog_bg.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/white"/> <corners android:radius="30dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape> set it as the background in your layout xml android:background="@drawable/dialog_bg" Set the background of the dialog's root view to transparent, because Android puts your dialog layout within a root view that hides the corners in your custom layout. dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); A: You need to do the following: Create a background with rounded corners for the Dialog's background: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="#fff" /> <corners android:bottomLeftRadius="8dp" android:bottomRightRadius="8dp" android:topLeftRadius="8dp" android:topRightRadius="8dp" /> </shape> Now in your Dialog's XML file in the root layout use that background with required margin: android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:background="@drawable/dialog_background" finally in the java part you need to do this: dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(layoutResId); View v = getWindow().getDecorView(); v.setBackgroundResource(android.R.color.transparent); This works perfectly for me. A: dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); this works for me
[ "stackoverflow", "0036407485.txt" ]
Q: What does "{ _ in }" mean in Swift? I found some code when I read a book about CoreData in Swift. I am confused about the meaning of the piece of code below. What's the meaning when declaring the closure like configurationBlock: NSFetchRequest -> () = { _ in }. especially the meaning of { _ in }. public static func fetchInContext(context: NSManagedObjectContext, @noescape configurationBlock: NSFetchRequest -> () = { _ in }) -> [Self] { let request = NSFetchRequest(entityName: Self.entityName) configurationBlock(request) guard let result = try! context.executeFetchRequest(request) as? [Self] else { fatalError("Fetched objects have wrong type") } return result } A: This is an empty closure that takes one parameter. In its fullest form, a closure looks like: { parameter: Type -> ReturnType in // Stuff it does } If ReturnType is void (no return), then it can be left out. If Type can be inferred, it can be left out. If parameter is unused, it can be replaced with _. And if there's no body, there's no body. So you wind up with just this when you're done: { _ in } In this specific case: configurationBlock: NSFetchRequest -> () = { _ in }) configurationBlock is a function that takes an NSFetchRequest and returns nothing, and its default value is a closure that does nothing. This lets you make configurationBlock optional without having to wrap it up in an Optional. (I go back and forth about which approach I like better, but both are fine.)
[ "stackoverflow", "0046178630.txt" ]
Q: FindBugs: How to avoid "Unwritten public field" warning when using JPA meta model? I've written quite a lot of DAO class and using the JPA criteria API and its meta model in them, like in this example: @Override public EntityA findByEntityB(EntityB entityB) { CriteriaBuilder builder = this.getCriteriaBuilder(); CriteriaQuery<EntityA> criteriaQuery = builder.createQuery(EntityA.class); Root<EntityA> root = criteriaQuery.from(EntityA.class); criteriaQuery.select(root); criteriaQuery.where(builder.and(builder.equal(root.get(EntityA_.entityB), entityB))); return this.findByCriteriaQuery(criteriaQuery); } While running static code analysis, FindBugs throws the following warning: UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD, Priorität: Normal Unwritten public or protected field: EntityA_.entityB No writes were seen to this public/protected field. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless. As I use the meta model classes in nearly all of my queries this warning is thrown very often. Is there any useful way to avoid these warnings? As we all know the meta model classes are just generated and their attributs are never written. I don't want to exclude the DAO classes from FindBugs sca as I want to check these to maybe find other possible bugs! A: Here are some ideas: Modify the generator to add a (redundant) setter. Implement a FindBugs filter (see http://findbugs.sourceforge.net/manual/filter.html) to exclude that specific bug in specific classes or packages. Or generally.
[ "stackoverflow", "0055174443.txt" ]
Q: Grouping consecutive words which contain B or I tags I have data looks: [[('Natural', 'JJ', 'B'), ('language', 'NN', 'I'), ('processing', 'NN', 'I'), ('is', 'VBZ', 'O'), ('one', 'CD', 'O'), ('of', 'IN', 'O'), ('the', 'DT', 'O'), ('important', 'JJ', 'O'), ('branch', 'NN', 'O'), ('of', 'IN', 'O'), ('CS', 'NNP', 'B'), ('.', '.', 'I')] ... ...]] I want to group the consecutive words which have tags B or I and ignore which have 'O' tags. The output keywords should look like: Natural language processing, CS, Machine learning, deep learning I did code as follows: data=[[('Natural', 'JJ', 'B'), ('language', 'NN', 'I'), ('processing', 'NN', 'I'), ('is', 'VBZ', 'O'), ('one', 'CD', 'O'), ('of', 'IN', 'O'), ('the', 'DT', 'O'), ('important', 'JJ', 'O'), ('branch', 'NN', 'O'), ('of', 'IN', 'O'), ('CS', 'NNP', 'B'), ('.', '.', 'I')], [('Machine', 'NN', 'B'), ('learning', 'NN', 'I'), (',', ',', 'I'), ('deep', 'JJ', 'I'), ('learning', 'NN', 'I'), ('are', 'VBP', 'O'), ('heavily', 'RB', 'O'), ('used', 'VBN', 'O'), ('in', 'IN', 'O'), ('natural', 'JJ', 'B'), ('language', 'NN', 'I'), ('processing', 'NN', 'I'), ('.', '.', 'I')], [('It', 'PRP', 'O'), ('is', 'VBZ', 'O'), ('too', 'RB', 'O'), ('cool', 'JJ', 'O'), ('.', '.', 'O')]] Key_words = [] index = 0 for sen in data: for i in range(len(sen)): while index < len(sen): I do not know what to do next. Could anyone please help me?. Thanks A: You should use itertools.groupby for a fairly compact solution: import itertools import string data = [[('Natural', 'JJ', 'B'), ('language', 'NN', 'I'), ('processing', 'NN', 'I'), ('is', 'VBZ', 'O'), ('one', 'CD', 'O'), ('of', 'IN', 'O'), ('the', 'DT', 'O'), ('important', 'JJ', 'O'), ('branch', 'NN', 'O'), ('of', 'IN', 'O'), ('CS', 'NNP', 'B'), ('.', '.', 'I')], [('Machine', 'NN', 'B'), ('learning', 'NN', 'I'), (',', ',', 'I'), ('deep', 'JJ', 'I'), ('learning', 'NN', 'I'), ('are', 'VBP', 'O'), ('heavily', 'RB', 'O'), ('used', 'VBN', 'O'), ('in', 'IN', 'O'), ('natural', 'JJ', 'B'), ('language', 'NN', 'I'), ('processing', 'NN', 'I'), ('.', '.', 'I')], [('It', 'PRP', 'O'), ('is', 'VBZ', 'O'), ('too', 'RB', 'O'), ('cool', 'JJ', 'O'), ('.', '.', 'O')]] punctuation = set(string.punctuation) keywords = [[' '.join(w[0] for w in g) for k, g in itertools.groupby(sen, key=lambda x: x[0] not in punctuation and x[2] != 'O') if k] for sen in data] print(keywords) # [['Natural language processing', 'CS'], # ['Machine learning', 'deep learning', 'natural language processing'], # []]
[ "stackoverflow", "0046169232.txt" ]
Q: How to Get all childrens Count in binary tree in php I have h that type table Now we want full binary tree And full Left and right chides count A: You will need to keep function in loop then run it , hope this helps you. Thanks
[ "stackoverflow", "0045714191.txt" ]
Q: Spring Boot BrokenPipe / Communications Exception i am facing Connection close Exception on my spring boot application. This is my db configuration: # For auto recconect it is necessary spring.datasource.tomcat.test-on-borrow = true spring.datasource.tomcat.test-while-idle= true spring.datasource.tomcat.test-on-return = true spring.datasource.tomcat.validationQuery=SELECT 1 spring.datasource.tomcat.time-between-eviction-runs-millis = 60000 spring.datasource.tomcat.min-evictable-idle-time-millis = 300000 spring.datasource.tomcat.min-idle = 10 spring.datasource.tomcat.max-idle = 100 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active = 100 Exceptions: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 66,612,631 milliseconds ago. The last packet sent successfully to the server was 66,612,631 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. java.net.SocketException: Broken pipe I have seen many topics about enabling autoReconnect but it is not recommended as far as i know. A: Well i changed default datasource provider to dbcp2, and fixed the bug. spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource # For auto recconect it is necessary spring.datasource.dbcp2.test-on-borrow = true spring.datasource.dbcp2.test-while-idle = true spring.datasource.dbcp2.test-on-return = true spring.datasource.dbcp2.validationQuery = SELECT 1 spring.datasource.dbcp2.time-between-eviction-runs-millis = 60000 spring.datasource.dbcp2.min-evictable-idle-time-millis = 300000 spring.datasource.dbcp2.min-idle = 10 spring.datasource.dbcp2.max-idle = 100
[ "stackoverflow", "0019046220.txt" ]
Q: How to execute a wordpress function inside custom PHP file Inside my active theme there is a user.php which serves this kind of url http://mysite.com/user/username. Inside user.php I echo a script tag with the following content $.ajax({ url: "' . get_theme_root_uri() . '/fray/userslogan.php", data: {"id": ' . $profile['id'] . ', "slogan": el.innerHTML}, type: "post", success: function(status) { alert(status); } }); I created a file userslogan.php and added it at the same level as user.php. Inside this file now all I want to do is <?php update_user_meta( $_POST['id'], 'slogan', $_POST['slogan'] ); echo 1; ?> but I get errors that functions that I call are undefined. So if I include some file that defines the update_user_meta function, then I will get another similar error and so on. What is the right way of executing code like this? A: You need to include wp-load.php to get access to the wordpress function in custom files. Suggestion: Don’t include wp-load, please. Use ajax in wordpress in proper way. You can refer this article. From above article Why this is wrong You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around in the installation. ALL the WordPress files could be moved about in this manner, are you going to search around for them? You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every page load. Once to produce the page, and then again to produce your generated javascript. You’re generating javascript on the fly. That’s simply crap for caching and speed and such. A: Try WP AJAX 1) http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) 2) http://codex.wordpress.org/AJAX_in_Plugins add_action( 'admin_footer', 'my_action_javascript' ); function my_action_javascript() { ?> <script type="text/javascript" > jQuery(document).ready(function($) { var data = { action: 'my_action', whatever: 1234 }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php $.post(ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); }); </script> <?php } add_action('wp_ajax_my_action', 'my_action_callback'); function my_action_callback() { global $wpdb; // this is how you get access to the database $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; die(); // this is required to return a proper result }
[ "stackoverflow", "0011549220.txt" ]
Q: Debugging layout xml file - file not loaded into system I'm having trouble getting my layout xml file loaded into the system. I need it loaded in adminhtml for a module I'm building, so here's the part of the config that matters: <adminhtml> <layout> <updates> <coupsmart_coupon> <file>coupsmart_coupon.xml</file> </coupsmart_coupon> </updates> </layout> </adminhtml> Now, the actual layout file, named coupsmart_coupon.xml file, is as follows: <layout> <coupsmart_coupon_adminhtml_coup_index> <update handle="coupsmart_coupon"/> <reference name="content"> <block type="coupsmart_coupon/adminhtml_forms" name="myform"/> </reference> </coupsmart_coupon_adminhtml_coup_index> </layout> Now, to debug this, I put an error in the layout xml file, such as leaving out a closing bracket (>), and I got no exceptions. So I checked the handles using $this->getLayout()->getUpdate()->getHandles() in my controller, and I got back coupsmart_coupon_adminhtml_coup_index as one of the handles, which is exactly what I named the handle in my layout xml file. Why else would this not be loading? Note: I have cleared cache and tried again. Still not working. I also do have logs on and exceptions on, so an exception should have shown in my logs. If any other code is needed let me know. A: Figured it out, because adminhtml.xml doesn't add to the DOM, and the xml file was actually located in etc/adminhtml.xml and not config.xml. When I moved the layout update to config, it looked as follows: <config> <adminhtml> <layout> <updates> <coupsmart_coupon> <file>coupsmart_coupon.xml</file> </coupsmart_coupon> </updates> </layout> </adminhtml> </config> And now it works. Thanks all for helping.
[ "stackoverflow", "0029354893.txt" ]
Q: How to add Scrollbars to Grid How does one add scrollbars to a grid? <Grid> <Menu Height="23" Name="menu1" VerticalAlignment="Top"> <MenuItem Header="File"> <MenuItem Command="ApplicationCommands.New" Header="New" /> <MenuItem Command="ApplicationCommands.Save" Header="Save" /> <MenuItem Command="ApplicationCommands.Open" Header="Open" /> <MenuItem Command="ApplicationCommands.Close" Header="Exit" /> </MenuItem> <MenuItem Header="Stuff"> <MenuItem Header="Properties" Command="Properties"/> <MenuItem Header="Tileset" Command="Replace"/> </MenuItem> </Menu> <Grid Margin="0,24,0,0"> <Canvas HorizontalAlignment="Stretch" Name="canvas1" VerticalAlignment="Stretch" MouseMove="MoveMouse" MouseDown="PressDownMouse" MouseUp="canvas2_MouseLeftButtonUp" MouseWheel="canvas1_MouseWheel"/> <Canvas HorizontalAlignment="Stretch" Name="canvas2" VerticalAlignment="Stretch" MouseMove="MoveMouse" MouseDown="PressDownMouse" MouseUp="canvas2_MouseLeftButtonUp" MouseWheel="canvas1_MouseWheel"/> <ListView HorizontalAlignment="Left" Name="listView1" Width="203" VerticalAlignment="Stretch" SelectionChanged="listView1_SelectionChanged"> </ListView> </Grid> </Grid> Two canvases may be too high or too wide. This is Tile Map Editor and I draw everything on canvas. In the ListView I have tiles to insert. A: Usually you can wrap the element with <ScrollViewer> or set ScrollViewer.HorizontalScrollBarVisibility and ScrollViewer.VerticalScrollBarVisibility inside the element's XAML. I like setting to Auto, so that they show up only when needed. Just try this to start: <ScrollViewer> <Grid> // some code </Grid> </ScrollViewer> EDIT for further help! Here's an example of a better layout, the listview is on the left followed by the two canvases. You may want to put these above each other or have a different layout, but this will show you how to do it: <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Menu Name="menu1" > <MenuItem Header="File"> <MenuItem Command="ApplicationCommands.New" Header="New" /> <MenuItem Command="ApplicationCommands.Save" Header="Save" /> <MenuItem Command="ApplicationCommands.Open" Header="Open" /> <MenuItem Command="ApplicationCommands.Close" Header="Exit" /> </MenuItem> <MenuItem Header="Stuff"> <MenuItem Header="Properties" Command="Properties"/> <MenuItem Header="Tileset" Command="Replace"/> </MenuItem> </Menu> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListView /> <Canvas Grid.Column="1"/> <Canvas Grid.Column="2"/> </Grid> </Grid>
[ "hinduism.stackexchange", "0000019564.txt" ]
Q: Incarnations of Vishnu after Kalki https://en.wikipedia.org/wiki/Kalki At the end of Kaliyug, the 10th and last incarnation of Vishnu is said to come as Kalki. Are there incarnations after Kalki, at the end of Dwapara yuga after this age? Do the incarnations "start over", or could they be expected to be completely new ones unlike the ones before? A: We know at least 7 incarnations of Vishnu after Kalki. Let me explain. Satya Yuga, Treta Yuga, Dwapara Yuga, and Kali Yuga together form one Mahayuga. And 1000 Mahayugas form a Kalpa. A Kalpa is also divided into 14 Manvantaras, each consisting of 71 Mahayugas. We are living in the 28th Mahayuga of the Vaivasvata Manvantara, which is the 7th Manvantara of the present Kalpa. Now as I discuss in this question, we don't have much information about the future Mahayugas of the Vaivasvata Manvantara. But we do have information about future Manvantaras: this chapter of the Srimad Bhagavatam lists seven incarnations of Vishnu who will occur in the remaining seven Manvantaras of the present Kalpa: O King, during the eighth manvantara, the great personalities Gālava, Dīptimān, Paraśurāma, Aśvatthāmā, Kṛpācārya, Ṛṣyaśṛṅga and our father, Vyāsadeva, the incarnation of Nārāyaṇa, will be the seven sages. For the present, they are all residing in their respective āśramas. In the eighth manvantara, the greatly powerful Personality of Godhead Sārvabhauma will take birth. His father will be Devaguhya, and His mother will be Sarasvatī. He will take the kingdom away from Purandara [Lord Indra] and give it to Bali Mahārāja. O King, the ninth Manu will be Dakṣa-sāvarṇi, who is born of Varuṇa. Among his sons will be Bhūtaketu, and Dīptaketu. In this ninth manvantara, the Pāras and Marīcigarbhas will be among the demigods. The king of heaven, Indra, will be named Adbhuta, and Dyutimān will be among the seven sages. Ṛṣabhadeva, a partial incarnation of the Supreme Personality of Godhead, will take birth from his father, Āyuṣmān, and his mother, Ambudhārā. He will enable the Indra named Adbhuta to enjoy the opulence of the three worlds. The son of Upaśloka known as Brahma-sāvarṇi will be the tenth Manu. Bhūriṣeṇa will be among his sons, and the brāhmaṇas headed by Haviṣmān will be the seven sages. Haviṣmān, Sukṛta, Satya, Jaya, Mūrti and others will be the seven sages, the Suvāsanas and Viruddhas will be among the demigods, and Śambhu will be their king, Indra. In the home of Viśvasraṣṭā, a plenary portion of the Supreme Personality of Godhead will appear from the womb of Viṣūcī as the incarnation known as Viṣvaksena. He will make friends with Śambhu. In the eleventh manvantara, the Manu will be Dharma-sāvarṇi, who will be extremely learned in spiritual knowledge. From him there will come ten sons, headed by Satyadharma. The Vihaṅgamas, Kāmagamas, Nirvāṇarucis and others will be the demigods. The king of the demigods, Indra, will be Vaidhṛta, and the seven sages will be headed by Aruṇa. The son of Āryaka known as Dharmasetu, a partial incarnation of the Supreme Personality of Godhead, will appear from the womb of Vaidhṛtā, the wife of Āryaka, and will rule the three worlds. O King, the twelfth Manu will be named Rudra-sāvarṇi. Devavān, Upadeva and Devaśreṣṭha will be among his sons. In this manvantara, the name of Indra will be Ṛtadhāmā, and the demigods will be headed by the Haritas. Among the sages will be Tapomūrti, Tapasvī and Āgnīdhraka. From the mother named Sunṛtā and the father named Satyasahā will come Svadhāmā, a partial incarnation of the Supreme Personality of Godhead. He will rule that manvantara. The thirteenth Manu will be named Deva-sāvarṇi, and he will be very advanced in spiritual knowledge. Among his sons will be Citrasena and Vicitra. In the thirteenth manvantara, the Sukarmās and Sutrāmas will be among the demigods, Divaspati will be the king of heaven, and Nirmoka and Tattvadarśa will be among the seven sages. The son of Devahotra known as Yogeśvara will appear as a partial incarnation of the Supreme Personality of Godhead. His mother’s name will be Bṛhatī. He will perform activities for the welfare of Divaspati. The name of the fourteenth Manu will be Indra-sāvarṇi. He will have sons like Uru, Gambhīra and Budha. The Pavitras and Cākṣuṣas will be among the demigods, and Śuci will be Indra, the king of heaven. Agni, Bāhu, Śuci, Śuddha, Māgadha and others of great austerity will be the seven sages. O King Parīkṣit, in the fourteenth manvantara the Supreme Personality of Godhead will appear from the womb of Vitānā, and His father’s name will be Satrāyaṇa. This incarnation will be celebrated as Bṛhadbhānu, and He will administer spiritual activities. So the seven known incarnations of Vishnu after Kalki are Sārvabhauma, Ṛṣabhadeva, Viṣvaksena, Dharmasetu, Svadhāmā, Yogeśvara, and Bṛhadbhānu. To answer your side question, some incarnations of Vishnu do recur. For instance I discuss in my question here how there have been three Vamana incarnations in the present Kalpa. And I discuss in my question here how Kalki came once before in the present Kalpa.
[ "electronics.stackexchange", "0000122322.txt" ]
Q: How does a "break" in the neutral wire enable it to reach the full line voltage? The answer to Is the neutral wire considered safe? states: When everything is working correctly, it should be at most a few volts from ground. However, and this is the big gotcha, if there is a break in the neutral line between where you are and where it is connected back to ground, it can be driven to the full line voltage. Basically in that case you are connected to the hot line via any appliances that happen to be on in that part of the circuit. Those can easily pass the few mA it takes to kill you. And something similar is stated in an answer to this question: A second problem with connecting the ground to the neutral happens if your neutral wire breaks between the outlet and your service entrance. If the neutral breaks, then plugged in devices will cause the neutral to approach the "hot" voltage. Given a ground to neutral connection, this will cause the chassis of your device to be at the "hot" voltage, which is very dangerous. Can someone shed light on this behavior? Specifically, how a break/disconnect in the neutral wire can suddenly cause it to have full voltage? A: Here is a simplified version of AC power lines: simulate this circuit – Schematic created using CircuitLab The two lines at lower right represent you holding the neutral. Since the neutral is connected to ground elsewhere, as you agree you only feel a small voltage. Note that the load is fairly low resistance, so it can produce a lot of power. Now let's break the neutral simulate this circuit Current will now flow through the upper hot wire, through the load, through you and then the ground in order to get back to the transformer neutral. And since the load has a low resistance, you are the big resistor in the circuit, and you will take most of the voltage. A: Consider this: simulate this circuit – Schematic created using CircuitLab With the neutral wire broken, the "Neutral" at the socket will be at 120VAC relative to ground. If another 1500W kettle was plugged in on the other side of the line, the voltage at the neutral would be around 0VAC relative to ground, however if a human were to contact the neutral wire and had a path to ground through their body, the voltage would not drop all that much and the person could be injured or killed. If a 60W incandescent bulb was connected between Hot2 and Neutral, it would glow very brightly and quickly burn out. That's why changes in brightness of incandescent bulbs can be seen as a canary-in-the-coalmine for a flaky neutral connection.
[ "stackoverflow", "0019438721.txt" ]
Q: Cannot load ado.net MySQL Under C#, framework 4.5. I installed Mysql connector 6.7.4. If I try to load dynamically the dll with DbProviderFactory fac = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); I get : Failed to find or load the registered .Net Framework Data Provider. I added in app.config the mysql (I even can list it with a GetFactoryClasses() !) I tried to put the MySQL assembly in GAC Nothing works :( A: There's a bug with the current provider. I had the same issue. You should use version 6.6.6, it worked for me. Here's a description for the bug register the provider in machine.config
[ "stackoverflow", "0044199280.txt" ]
Q: MySQL-Select start and end of week along with average of a column (week-by-week) I am trying to get average of a column player_count week-by-week over the past 6 weeks. But the problem is that I also want the start and the end of the week date which corresponds to a specific average. What I have tried: SELECT AVG(player_count) as average, updated_at, updated_at + INTERVAL WEEKDAY(updated_at) + 7 DAY as EndDate FROM `gtan_servers` WHERE server_short_name = 'FiveRP' GROUP BY WEEK(updated_at) ORDER BY updated_at DESC LIMIT 6 The updated_at column is intended to be taken as start of the week and EndDate is going to be taken as end of the week in which a specific average of the player count is provided. But this query is not working correctly regarding the week dates. I can fetch the average yes but the week dates are not being fetched correctly. Any help would be highly appreciated. A: You need an expression that truncates an arbitrary date to the first day of the week in which it occurs. That is, it returns 2017-05-21 (Sunday) if you give it 2017-05-24 This expression does that, assuming your weeks start on Sundays. Here's an explanation. FROM_DAYS(TO_DAYS(datestamp) -MOD(TO_DAYS(datestamp) -1, 7)) Then you need to use that as a GROUP BY expression and a WHERE expression. SELECT AVG(player_count) as average, FROM_DAYS(TO_DAYS(updated_at) -MOD(TO_DAYS(updated_at) -1, 7)) week_beginning, FROM_DAYS(TO_DAYS(updated_at) -MOD(TO_DAYS(updated_at) -1, 7)) + INTERVAL 6 DAY week_ending FROM `gtan_servers` WHERE server_short_name = 'FiveRP' AND updated_at >= FROM_DAYS(TO_DAYS(NOW()) -MOD(TO_DAYS(NOW()) -1, 7)) - INTERVAL 6 WEEK GROUP BY FROM_DAYS(TO_DAYS(updated_at) -MOD(TO_DAYS(updated_at) -1, 7)) ORDER BY 2 DESC LIMIT 6 The WHERE automatically filters out records from your table that are too old for your report. This query gets a little repetitive, but it works nicely. You could create a stored function like this: DELIMITER $$ DROP FUNCTION IF EXISTS TRUNC_SUNDAY$$ CREATE FUNCTION TRUNC_SUNDAY(datestamp DATETIME) RETURNS DATE DETERMINISTIC NO SQL COMMENT 'returns preceding Sunday' RETURN FROM_DAYS(TO_DAYS(datestamp) -MOD(TO_DAYS(datestamp) -1, 7))$$ DELIMITER ; Then your query becomes more readable: SELECT AVG(player_count) as average, TRUNC_SUNDAY(updated_at) week_beginning, TRUNC_SUNDAY(updated_at) + INTERVAL 6 DAY week_ending FROM `gtan_servers` WHERE server_short_name = 'FiveRP' AND updated_at >= TRUNC_SUNDAY(NOW()) - INTERVAL 6 WEEK GROUP BY TRUNC_SUNDAY(updated_at) ORDER BY TRUNC_SUNDAY(updated_at) DESC LIMIT 6 If your weeks start on Mondays change the -1 to a -2.
[ "serverfault", "0000300608.txt" ]
Q: Transparent Caching for HTTP I don't have a clue where to start on caching, and I'm already lost in googling it. I just want to run a server on an Ubuntu machine that will take a list of internet URLs, download a local copy of every page under that URL, and then configure my system so that when any process requests that URL (a browser, wget, apt-get, etc), it will be accessing the local copy without knowing it. And a second-priority requirement: allow processes on the local system to call by URL either the locally-cached version or the live-internet version. A: I think what you are looking for is Squid It is a Web-cache Proxy
[ "gis.stackexchange", "0000032089.txt" ]
Q: Negative values in ArcGIS API for Flex app? I have a contractor working for me on a Flex application. He retrieves recordset for a intersect query from the web service published in house. But he is getting some ids as negative random number instead of integer (generally 9-10 digits). He says it is at our end but when I query from REST service, I get everything fine. He is using the query to display results in app. I don't know his code in details because I have tasks to develop server side functionalities and have my plate full. The mapping service, in question, is a query layer and retrieving data from ORACLE database. Has anyone else noticed similar behavior? or any suggestion on this? A: Here are a few thoughts to help you move forward. 1. Prove once and for all to everyone that the problem is unquestionably server-side: If I were the Flex dev, I would use Fiddler (or any other traffic sniffer) and show you a screenshot proving the errant values are emitting from your service layer before they get into Flex. In other words, make them prove it. ( ..surely they've already done this, right? But if they haven't, they may very well prove to themselves that the problem occurs when the data hits Flex. I hope you're not in that situation. :/ ) 2A. Cast the id values as String, server-side: My recommendation? Just do this and be done with it. Assuming you prove Flex is the bad guy in #1, I'd cut to the chase and cast your id values to String server-side, like this guy, and this guy. If you do that, it eliminates every variety of "Flex-wierd-number-stuff". 2B. Configure return data types, client-side: ..alternatively, your Flex dev can "configure the return data type" for the id values, forcing the Flex client to receive them as String values. This saves you some trouble server-side, but personally, I'm not a big fan of this approach for the reason that if I have to delete/recreate my service connection in Flex, I have to remember all the specific return types I've configured. (And sometimes this is necessary if anything is refactored or heavily revised server-side.) But this is just personal preference based on my experiences. 2C. Implement a unique solution, client-side, to handle large integer values: This is an option, but it's not necessary to get where you want to be. Nevertheless your Flex dev could experiment with this so-called BigInt class (or anything else like it, plucked from the web). I rank this as option 2C because, well—you'd be involving a class someone created and put on their blog. :) Nothing wrong with that, but casting to String removes all guess-work. The truth is I love Flex for the stuff it does well, like rendering rich, visual content—and that's perfect for online maps. But I avoid doing serious arithmetic or buisness logic in Flex. Not to be pessimistic, but if you see clean data when you poll the service layer directly, I automatically suspect the issue begins when the data hits Flex. There's just no shortage of conversation about this and similar issues if you do some looking.. Best of luck. /E
[ "stackoverflow", "0044128811.txt" ]
Q: Magento 2 Add product to category (code) I want to create products by their code, and I want to add products to categories. How to add products to categories by code? I tried to add category to product \Magento\Catalog\Model\Product, but there no method setCategory or something like that. Then I tried to add products to category Magento\Catalog\Model\Category, and there no method addProduct or something like that. I saw function CategoryLinkManagementInterface -> assignProductToCategories( $product->getSku(), $product->getCategoryIds() //but there is not categories yet ) A: /** * @var \Magento\Catalog\Api\CategoryLinkManagementInterface */ protected $_categoryLinkManagement; $this->_categoryLinkManagement->assignProductToCategories($sku, $categoryIds); //where $sku is sku of product, and $categoryIds is array of real categories ids
[ "stackoverflow", "0020749915.txt" ]
Q: Making full year schedule of event using php date function I have an event having the following properties: id name weekday So, an event happens every week on that weekday. I wanted to create an array containing all the dates (Format: dd-mm-yyyy), when that event will take place two specific dates. I'm unable to figure out the appropriate logic/code. I implemented the following code: $day = date('d');//returns today's date in 2-digit format. $year = date('Y');//4-digit format of current year $month = date('m');//2-digit format of current month $cal = array(); $ttdayid = $weekday;//5 $tt = 0; $tt = abs($day-$ttdayid); $ttday = $date - $tt; while ($ttday>0) { if ($ttday<10) { $ttday = '0' . $ttday; } $arr = array( 'id' => $id, 'title' => $name, 'start' => $year . '-' . $month . '-' . $ttday ); array_push($cal, $arr); $ttday-= 7; } The above code works for the current month only before today. I'm unable to figure out how to extend it to show dates for previous and next months for the whole year. Also, how to included cases for leap years. A: Use the DateTime() object: $current = new DateTime(); // creates a date for "today" by default $end = new DateTime('yyyy-mm-dd'); // the ending date $interval = new DateInterval('P7D'); // 1 week while($current <= $end) { $cal[] = $current->format('Y-m-d'); $current = $current->add($interval); }
[ "scifi.stackexchange", "0000121772.txt" ]
Q: Why was Remus Lupin on the Hogwarts Express? In Harry Potter and the Prisoner of Azkaban, why does Remus Lupin take the train to Hogwarts? I do not recall any other instance of Professors taking the train. A basic search online yielded the following, unsatisfactory answers: He was exhausted from a recent transformation. I don't think that's it. He could Apparate, Floo, Portkey, all much faster and less exhaustive ways of travel. Dumbledore and the other Professors knew of his condition, and most were on good terms with him (seeing as several were also his professors when he was in school), it's likely they would have helped him with a quick, easy way to his new job without even his asking. He wanted to see Harry in a not-teacher/student setting first. Again, if this was such a big deal to him, he could have approached Harry a number of ways. In fact, Harry was staying at the Leaky Cauldron for quite some time. At any point, Remus could have casually met him there or in Diagon Alley. He was put there specifically to keep an eye on students because of the Dementors. Maybe? But if the school/Ministry wanted someone to watch the students around the Dementors, a lone, brand-new, tired-from-being-a-werewolf teacher doesn't seem like the best choice. Furthermore, we don't see any indication that any other teachers/adults were on the train (besides the conductor/train personnel). A: You say he could Apparate, but this is not necessarily less exhausting than the train. Remember that Hogwarts has an anti-Apparition jinx, so Apparition would still require a little, or maybe a lot, of walking over hard ground to get to Hogwarts, whereas on the train he could--and did--sleep almost the whole time. Could he use Floo powder? Doubtful. There was a lot of anti-werewolf prejudice at the time, and he was very poor, so it is unlikely that he had access to Floo Powder. Portkeys? They need Ministry help to set up, and this is too much trouble, as well as hard since he is a werewolf. So it is probable that he was just exhausted or had no other means of travel. Or, though this is unlikely, Dumbledore put him on the train knowing that he would meet Harry. I've found a quote from Slughorn's letter to Harry about the Slug Club. It proves that teachers do take the train, or at least some of them do, they just don't mix with students while on the train: Harry, I would be delighted if you would join me for a bit of lunch in compartment C. Sincerely, Professor H. E. F. Slughorn. A: Sirius Black had escaped and it was assumed he'd attack Harry. Lupin the defence Professor was on the train to protect the students, namely Harry so they all arrived safely at Hogwarts.
[ "opendata.stackexchange", "0000011054.txt" ]
Q: Resume Dataset Request Where can I find a dataset of resumes around 1000-2000 for machine learning project. Preferably good resumes of software engineers. I know this question has been asked before, but I believe there should be some dataset online hiding. P.S. Any chance of using a Python crawler to download resumes from indeed? Thank you, A: try Kaggle datasets: https://www.kaggle.com/datasets Also try the Fed's St. Louis website.
[ "stackoverflow", "0027823738.txt" ]
Q: Random multivariate normal distribution I've run into a problem where I have to be able to generate a set of randomly chosen numbers of a multivariate normal distribution with mean 0 and a given 3*3 variance-covariance matrix in Java. Is there an easy way as to do this? A: 1) Use a library implementation, as suggested by Dima. Or, if you really feel a burning need to do this yourself: 2) Assuming you want to generate normals with a mean vector M and variance/covariance matrix V, perform Cholesky Decomposition on V to come up with lower triangular matrix L such that V=LLt (where the superscript t indicates transpose). Generate a vector Z of three independent standard normals (using Random.nextGaussian() to get the individual elements). Then LZ + M will have the desired multivariate normal distribution.
[ "askubuntu", "0000797097.txt" ]
Q: How to copy or move a file from a folder to desktop? I am a beginner and I want to copy/move a file from a specific folder to the desktop. I use cp and mv for those tasks. But I want to copy/move to the desktop. Say I want to move file1 to Desktop, I use mv file1 _____ In _____, I used Desktop, but it renames the file to "Desktop". I used home/Desktop but it says no file/folder is found. A: Desktop is a directory in your user's home directory. If your language is English it is called Desktop. To copy some file there, you can run cp file ~/Desktop ~ stands for /home/<username> If your UI language is not English, it is called differently. You can do a copy without finding the correct name by cp file "$(xdg-user-dir DESKTOP)" You can get the name of the Desktop directory by xdg-user-dir DESKTOP You can use mv instead of cp if you want to move a file instead of copying. A: How these commands work depends on where you are in the filesystem. You can normally see where you are from your prompt: zanna@monster:~/Desktop$ That's my prompt when the current working directory is ~/Desktop, the handy shortcut for /home/zanna/Desktop If you're not sure where you are, you can type pwd and get the full absolute path zanna@monster:~/Desktop$ pwd /home/zanna/Desktop The first / is important - that's the root directory, and all full absolute paths will start with it You can use absolute or relative paths to do things with files. If you are in the directory where the file you want to move is, to move to your desktop, assuming your desktop directory is actually called Desktop (don't forget that Linux is case sensitive) mv file1 ~/Desktop because the current working directory is assumed. From anywhere in your filesystem you can do this: mv /path/to/file1 ~/Desktop but replace /path/to with the real path! for example, if the file is in you home Downloads folder do mv ~/Downloads/file1 ~/Desktop mv also renames files... if the target is a file that exists and isn't a directory, mv overwrites it with the contents of the first file, and renames to the target. If the file doesn't exist, then file1 is renamed as the target without overwriting anything, as you discovered. To copy a file instead of moving it, you can do exactly the same as above, with cp instead of mv. Only the behaviour is different in this case - the original file1 continues to exist in its previous location. To learn more, you can check man mv and man cp A nice option for learning - you can get mv and cp to tell you what they are doing by making them verbose: adding -v. Here I move the file chocolate from the current working directory ~/playground to my Desktop with the verbose option, and I get some output in the terminal: zanna@monster:~/playground$ mv -v chocolate ~/Desktop 'chocolate' -> '/home/zanna/Desktop/chocolate' A: You should use mv file1 ~/Desktop for moving and cp file1 ~/Desktop for copying to your Desktop directory.
[ "stackoverflow", "0058851504.txt" ]
Q: Scope resolution operator for returning a nested class type I know that the scope resolution operator :: is used to identify and disambiguate identifiers used in different scopes. In the example provided here C++ define class member struct and return it in a member function class UserInformation { public: userInfo getInfo(int userId); private: struct userInfo { int repu, quesCount, ansCount; }; userInfo infoStruct; int date; }; You can create a member function that returns a type of the nested class userInfo. UserInformation::UserInfo UserInformation::getInfo(int userId) <----- { Userinfo x; <----- infoStruct.repu = 1000; return infoStruct; } Why does the scope have to be stated twice in the function definition? UserInformation::UserInfo UserInformation::getInfo(int userId) It's an error if it's only stated once, but from my understanding, I thought that stating it once at the beginning, before the return value would put us in the correct scope already? In the function above, I added Userinfo x; to show that the nested class type can be declared and used without the scope resolution operator. Why is that allowed? A: The class scope is needed for the function return type because name lookup won't yet know of it. You can get around that requirement if you wish with C++11 trailing function return type. auto UserInformation::getInfo(int userId) -> UserInfo { ... } The class scope is not needed inside the member function body because there the class scope is then obviously known.
[ "stackoverflow", "0035014292.txt" ]
Q: Is it worth it to use policies instead of conditions everywhere (taking run time checking to compile time)? Let's imagine there is a condition in a program: void foo(bool condition) { .... a lot of work.... if (condition) something1; else something2; .... a lot of work.... } if at compile time, in each call of foo() we know we need something1 or something2, we can change program to this one: template <bool condition> void foo() { .... a lot of work.... SomePolicy<condition>::do_something(); .... a lot of work.... } template <bool Condition> class SomePolicy { public: static void do_something() { something1; } }; template <> class SomePolicy<false> { public: static void do_something() { something2; } }; So taking run time checking at compile time by calling foo<true> or foo<false>. Is this worthy to do everywhere and get rid of some conditions (probably will increase pipeline performance)? Is there any disadvantage of this besides a little ugly code? P.S. the problem is that we don't want to duplicate all foos code and call foo1 and foo2 in different places. A: Is this worthy to do everywhere and get rid of some conditions (probably will increase pipeline performance)? No, because pipeline stalls are not a bottleneck everywhere. It might be worth to do it in a hot spot where you have measured a bottleneck caused by a long dependency chain between instructions. A single branch in middle of "a lot of work" rarely has significant effect on performance. Is there any disadvantage of this besides a little ugly code? It limits the condition to be checked at compile time, instead of at run time. Programs that have variable input at run time are usually more versatile. As you pointed out in a comment, you can indeed reduce multiple runtime checks into one, using the described policy. But generating all your (apparently big, since they do lots of work) functions twice, everywhere can cause the executable size to grow significantly which is an undesirable side-effect. Also, it forces you to use a template, which forces the implementation to be in the header. If you do that all over your code, then most of your code will be implemented in headers, and that will cause massive recompilations, when the implementation is modified. Which is a problem in big projects.
[ "stackoverflow", "0055302136.txt" ]
Q: New-ADUser + OtherAttributes w/ Splatting for Readability foreach ($Person in $People) { $NewUserParams = @{ Name = $Person.Name Server = 'xxxx.com:389' Path = 'CN=Users,CN=addressBook,DC=xxxx,DC=com' Credential = $Credentials givenName = $Person.givenName otherAttributes = @{sn=$Person.sn} } New-ADUser @NewUserParams } I have many additional attributes (otherAttributes) that I would like to add that are available to me in the formart New-ADUser -Name XXX -OtherAttributes @{sn=xxx} . However, I am trying to using splatting to make the OtherAttributes more readable, along with other required parameters. I don't need to using splatting for the entire command, my goal was to break up otherAttributes so it wasn't a long string that wrapped. Ideas? A: The value of otherAttributes is just another hashtable, and can be wrapped like any other hashtable: $NewUserParams = @{ 'Name' = $Person.Name 'Server' = 'server.example.com:389' 'Path' = 'cn=Users,cn=addressBook,dc=example,dc=com' 'Credential' = $Credentials 'givenName' = $Person.givenName 'otherAttributes' = @{ 'sn' = $Person.sn } } Personally, I recommend putting the keys of the hashtables in quotes to avoid surprises, but at least in the above example that's not required. If the above doesn't work for you you need to provide more details about the code you're running and the error(s) you're getting. Displaying the content of the generated hashtable inside the loop usually helps troubleshooting problems with particular values.
[ "stackoverflow", "0053991977.txt" ]
Q: If a string is not matching one of 3 option in PHP This is the code I used to have to check if $A doesn't match $B if($A!=$B) { $set = array(); echo $val= str_replace('\\/', '/', json_encode($set)); //echo print_r($_SERVER); exit; } Now I need the opposite of this condition: ($A need to match one of these $B,$C or $D) A: A simple shortcut to seeing if a value matches one of multiple values you can put the values to be compared against ($B, $C, and $D) into an array and then use in_array() to see if the original value ($A) matches any of them. if (in_array($A, [$B, $C, $D])) { // ... } If you don't want it to match any of $B, $C, or $D just use !: if (!in_array($A, [$B, $C, $D])) { // ... }
[ "gis.stackexchange", "0000073837.txt" ]
Q: SLD layer style colour ranging from x -> y I am new to web mapping. I would like to create a SLD style that colours the points if they fall between certain numbers for example 0-500. I know I could manually create each colour for each value and assign it. However this is not practical when you reach high numbers of values that need colouring. One option is to group them into small groups of 10, but that still gives me 50 colours to do. I have a few hundred points, served from GeoServer via WMS, that rance from 0-500. How would I go about doing this with SLD? The image below shows an example of what I would expect in a desktop client. A: Or look at the interpolate function: http://docs.geoserver.org/latest/en/user/styling/sld-tipstricks/transformation-func.html#interpolate Mind, if you use it, GetLegendGraphics won't generate a nice legend for you (known limitation)
[ "drupal.stackexchange", "0000252415.txt" ]
Q: Apply Image styles for migrated images I've done a drupal migration from drupal 6 to drupal 8. While all files are migrated well, image styles are not applying on migrated images. Image styles are applied to the newly added images. I think I should have force drupal to generate image styles for migrated images, but I don't know how. any help one that is appreciated. PS. I read some information about Flushing image styles in drupal 7 but I couldn't find a proper way to use it in drupal 8 as a custom module. A: To solve the problem I used the code below to force Drupal to create the image styles for my nodes: if ($entity->hasField('field_image') && $entity->get('field_image')->getValue() != null) { $image = \Drupal::service('image.factory')->get($entity->get('field_image')->entity->getFileUri()); if ($image->isValid()) { $styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple(); $image_uri = $entity->get('field_image')->entity->getFileUri(); foreach ($styles as $style) { $destination = $style->buildUri($image_uri); $style->createDerivative($image_uri, $destination); } } } Here is the description, for each node ($entity variable) , first it checks if the node type has a field with machine name "field_image" and if this field has a value, then it checks if fileUri is a valid image, then if all conditions met, the code iterates on all image styles available and build that style for given image manually. This code can be used as a cron job function, so on every cron job image styles of given nodes are created.
[ "stackoverflow", "0050134925.txt" ]
Q: Angular Reactive Form manual validate gives ExpressionChangedAfterItHasBeenCheckedError I'm using Angular 5.0.0 and Material 5.2.2. This form has two sub questions in it. The user is submitting two times in one form. This has to stay this way because I present here a very stripped down version of my original form. After the first submit, in the second subquestion, I validate if there is minimum one checked checkbox. If not I do an this.choicesSecond.setErrors({'incorrect': true});. This disables the submit button in a correct way. But this gives an error: `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'. I think it has to do with with change detection. If I do an extra change detection with this.changeDetectorRef.detectChanges() then the error disappears but the submit button is not disabled anymore. What am I doing wrong? Template: <mat-card> <form *ngIf="myForm" [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" novalidate> <div *ngIf="!subQuestion"> <mat-card-header> <mat-card-title> <h3>Which fruit do you like most?</h3> </mat-card-title> </mat-card-header> <mat-card-content> <mat-radio-group formControlName="choiceFirst"> <div *ngFor="let fruit of fruits; let i=index" class="space"> <mat-radio-button [value]="fruit">{{fruit}}</mat-radio-button> </div> </mat-radio-group> </mat-card-content> </div> <div *ngIf="subQuestion"> <mat-card-header> <mat-card-title> <h3>Whichs fruits do you like?</h3> </mat-card-title> </mat-card-header> <mat-card-content> <div *ngFor="let choiceSecond of choicesSecond.controls; let i=index"> <mat-checkbox [formControl]="choiceSecond">{{fruits[i]}}</mat-checkbox> </div> </mat-card-content> </div> <mat-card-actions> <button mat-raised-button type="submit" [disabled]="!myForm.valid">Submit</button> </mat-card-actions> </form> </mat-card> Component: export class AppComponent { myForm: FormGroup; fruits: Array<string> = ["apple", "pear", "kiwi", "banana", "grape", "strawberry", "grapefruit", "melon", "mango", "plum"]; numChecked: number = 0; subQuestion: boolean = false; constructor(private formBuilder: FormBuilder, private changeDetectorRef: ChangeDetectorRef) { } ngOnInit() { this.myForm = this.formBuilder.group({ 'choiceFirst': [null, [Validators.required]], }); let choicesFormArray = this.fruits.map(fruit => { return this.formBuilder.control(false) }); this.myForm.setControl('choicesSecond', this.formBuilder.array(choicesFormArray)); this.onChangeAnswers(); } onChangeAnswers() { this.choicesSecond.valueChanges.subscribe(value => { let numChecked = value.filter(item => item).length; if (numChecked === 0 ) this.choicesSecond.setErrors({'incorrect': true}); }); } get choicesSecond(): FormArray { return this.myForm.get('choicesSecond') as FormArray; }; onSubmit(submit) { if (!this.subQuestion) { this.subQuestion = true; let numChecked = this.choicesSecond.controls.filter(item => item.value).length; if (numChecked === 0 ) this.choicesSecond.setErrors({'incorrect': true}); // this.changeDetectorRef.detectChanges() } console.log(submit); } } A: The issues comes from the this.choicesSecond.setErrors({'incorrect': true});, when you click submit you create the component and at the same time change its value. This fails in development mode because of the aditional check done by angular. Here is a good article about this error. For form validation you can use a custom validator, an example in this post : minLengthArray(min: number) { return (c: AbstractControl): {[key: string]: any} => { if (c.value.length >= min) return null; return { 'minLengthArray': {valid: false }}; } } And for steps, as you are using angular material you could use the mat-stepper.
[ "ethereum.stackexchange", "0000079260.txt" ]
Q: Logic help needed, how to transfer funds to the address who placed bets on winning team? This is a betting application and right now -> if I place bets on HOME, the amount gets stored but I want to transfer the amount only to the address who placed bets on winning team. I have developed code until getting the winner from oraclize but cant figure out how to transfer funds to the address who placed bets on winning team The issue-> How to check who has placed bets on the winning team and transfer funds Oraclize query gives back the result which is HOME or the winning team but how to track which address placed bets on winning team and transfer funds to the winner The workflow is like this 1) Solidity function expecting team number as argument which is being provided by the APP.JS file 2) The solidity function accepts the betting amount -> stores it and sends the request to oraclize to check for the winner 3) Oraclize provides callback providing us with the winning team 4) Now I want to transfer the funds only to the address who placed bets on the team which has won App.js var contract = web3.eth.contract(OraclizeContract.abi).at(OraclizeContract.address); var team = document.querySelector("#bet #team").value; if(team == "Home") { team = 1; } else { team = 2; } console.log(team) contract.deposit.sendTransaction(team, {value: web3.toWei(betAmount, 'ether'), gas: 3000000} ,function (error, result){ if(!error){ console.log(result);//transaction successful } else{ console.log(error);//transaction failed } }); Solidity code address public homeBet; address public awayBet; mapping (address => uint256) public amountStore; event LogDeposit(address sender, uint amount, string executed); function deposit(uint team) public payable returns(bool success) { if(team == 1) { homeBet = msg.sender; amountStore[msg.sender] += msg.value; emit LogDeposit(msg.sender, msg.value, "Executed deposit HOME"); oraclize_query("URL", "json(https://api.crowdscores.com/v1/matches/123945?api_key=).outcome.winner"); return true; } else if(team == 2) { awayBet = msg.sender; amountStore[msg.sender] += msg.value; emit LogDeposit(msg.sender, msg.value, "Executed deposit AWAY"); oraclize_query("URL", "json(https://api.crowdscores.com/v1/matches/123945?api_key=).outcome.winner"); return true; } } This is the callback i recieve from oraclize on this callback i get to know the winning team and want to transfer funds But the transfer is not working as expected Because i want 1) transfer only to the address who placed the bet on winning team I cannot figure out how to make it work function __callback(bytes32 id, string result, bytes proof) public { makePayment(result); } function makePayment(string result) public { if (result.toSlice().equals("home".toSlice())) --->> IF HOME HAS WON { < NEED LOGIC HELP > SEND MONEY TO ADDRESS WHO PLACED BETS ON HOME } else if(result.toSlice().equals("away".toSlice())) ----->> IF AWAY HAS WON { < NEED LOGIC HELP > SEND MONEY TO ADDRESS WHO PLACED BETS ON AWAY } } A: For that type of situations it is recommended to use a withdrawal pattern. You do not pay directly but instead you store the winning address, then the winner have to call a withdraw function and it will be able to retrieve the prize. function makePayment(string result) public { if (result.toSlice().equals("home".toSlice())) { winner = homeBet; } else if(result.toSlice().equals("away".toSlice())) { winner = awayBet; } } The withdrawal can be something like function withdraw() { require(msg.sender == winner, "Only winner can call withdraw"); msg.sender.transfer(<PRIZE AMOUNT>); // ** ISTANBUL FORK WARNING ** } Note: After the Istanbul fork using transfer is no longer the recommended solution to make ether transfers. But there is no better alternative, using call & value is dangerous if you are not careful with possible re-entrancy attacks.
[ "stackoverflow", "0012209661.txt" ]
Q: Unable to import sample project from sdk I want to study the sample code in android sdk which is cubelivewallpaper.. So i decided to import it. But it has a problem. i am not able to click finish because it is disabled.. here: and here is i am trying to import. Anyone can help me how to import sdk project wihout getting this error? Thank you.. A: To import sample project follow the following steps: Click on File ---> New ---> other, new project wizard will be opened. Now under android option click on the "android sample project" and press next. Select the build target e.g. android 4.1 and press next. Now you will get list of sample projects available. Select the one you want say "CubeLiveWallpaper" and press finish. You are done A: That project exists in the sample projects.(CubeLiveWallpaper) Try Creating a sample project. No need to import it.
[ "stackoverflow", "0049393537.txt" ]
Q: SSRS - Matrix Table Reading Previous Row Values I've been trying to read the previous row value(that displays hourly quantities) on the matrix table to compare it with current row value and highlight the background color to yellow if the difference between them is out of accepted tolerance range. The matrix table has a combination of grouping on column and row(for only hourly information) that is shown on the picture. Tried to use the custom code to achieve this, but I'm getting an incorrect result . I've attached the report design image, and result of that along with the custome code. Please help me to figure out what is wrong on the logic. Images: Result: Code: custom code written under report properties -> Code Public Shared previous as Object Public Shared current as Object = Nothing Public Shared Function GetCurrent(Item as Object) as Object previous=current current=Item return current End Function Public Shared Function GetPrevious() return previous End Function public Shared Function IsHourlyDiffAboveTolerance(previousValue as Integer, currentValue as Integer, variantPercent as Decimal, variantVolume as Decimal, sortOrder as Integer) As Object If previousValue = Nothing Then Return Nothing Else Dim diff as Integer diff = abs(currentValue - previousValue) Dim tolerance as decimal tolerance = 0.0 If variantPercent <> 0 Then tolerance = previousValue * (variantPercent/100) Else If variantVolume <> 0 Then tolerance = variantVolume End If If diff >= 0 And diff <= tolerance Then return Nothing Else return 1 End If End If End Function Caller Expression: =IIF( IsNothing(Code.IsHourlyDiffAboveTolerance(Code.GetPrevious(), Code.GetCurrent(Fields!ExpectedQty.Value), Fields!VariantPercent.Value, Fields!VariantVolume.Value, Fields!SortOrder.Value)), "No Color", "Yellow") Update: either variant volume or quantity can exist but not both. Thanks A: I would use the new analytical function LEAD() and LAG() for SQL Server 2012. These functions access data from a subsequent row (for lead) and previous row (for lag) in the same result set without the use of a self-join. To use these functions with a matrix, you'll probably need to use PARTITION BY in the clause for the grouping. Example SQL: USE AdventureWorks GO SELECT s.SalesOrderID , s.SalesOrderDetailID,s.OrderQty , LeadValue = LEAD(SalesOrderDetailID) OVER (ORDER BY SalesOrderDetailID) , LagValue = LAG(SalesOrderDetailID) OVER (ORDER BY SalesOrderDetailID) FROM Sales.SalesOrderDetail s WHERE SalesOrderID IN (43670, 43669, 43667, 43663) ORDER BY s.SalesOrderID , s.SalesOrderDetailID , s.OrderQty GO Reference Article
[ "stackoverflow", "0016459010.txt" ]
Q: How to check if "Java is outdated" bar is visible on Google Chrome? My website has a java applet that must run for complete functionallity. The problem is that some users have an outdated Java version, which makes Chrome show that annoying bar on top along with not running the applet at all. How can I check if the outdated bar is visible, so I can show an arrow pointing to the 'Run this time' button and make sure all users with an old Java version get to run the applet? Is this even possible? A: How can I check if the outdated bar is visible.. Probably by deploying the applet using the Deployment Toolkit Script & specifying a Java version of greater than or equal to 'latest know, secure (for the moment) Java'. Then it shouldn't appear at all. Update It's a 3D display of molecules with some extra info. It's essential as the website is pretty much about that only I think that seals it. Launch the applet using Java Web Start. Java Web Start (JWS) is the Oracle Corporation technology used to launch rich client (Swing, AWT, SWT) desktop applications directly from a network or internet link. It offers 'one click' installation for platforms that support Java. JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or Java version, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions.. That 'desktop integration' includes desktop shortcuts (like for Star Zoom Animation and JotPad below). Once the user is launching the app. from the desktop icon, we can be sure they won't be seeing any Chrome warning.
[ "stackoverflow", "0020173519.txt" ]
Q: Pygame level bitmask checking optimisation? Pygame offers a pretty neat bitmask colliding function for sprites, but it's really slow when you are comparing large images. I've got my level image, which worked fine when it was 400x240, but when I changed the resolution to (a lot) bigger, suddenly the game was unplayable, as it was so slow. I was curious if there was a way to somehow crop the bitmask of a sprite, so it does not have to do as many calculations. Or, an alternative would be to split the whole stage sprite into different 'panels', and have the collision check for the closest one (or four or two, if he is on the edge of the panels). But I have no idea how to split an image into several sprites. Also, if you have any other suggestions, they would be appreciated. I have seen the many places on the internet saying not to bother with bitmask level collision, because it is far too slow, and that I should use tile based collision instead. Although, I think bitmask would make it a lot more flexible, and it would give the opportunity for level destruction (like in the worms games), so I would prefer it if it was bitmask. I think I've explained it enough not not need to post my code, but please tell me it you really need it. Many thanks! A: Okay, I worked out a fix for it that actually wasn't any of these things... Basically, I realised that I was only colliding one pixel with the stage at a time, so I used the Mask.get_at() function. Kinda annoyed this didn't occur to me before. Although, I've heard that using this can be quite slow, so if somebody would be willing to offer a faster alternative of get_at() that'd be nice.
[ "stackoverflow", "0047960605.txt" ]
Q: Converting to binary truncates bits When trying to create a random 256 bit number the input gets truncated (Sometimes to 252 bits, others to 254). MacOS Sierra 10.12.6 python --version Python 2.7.13 :: Anaconda 4.4.0 (x86_64) Example: >>> private_key = binascii.hexlify(os.urandom(32)) >>> len(bin(int(private_key, 16))[2:]) 256 >>> private_key = binascii.hexlify(os.urandom(32)) >>> len(bin(int(private_key, 16))[2:]) 252 >>> private_key = binascii.hexlify(os.urandom(32)) >>> len(bin(int(private_key, 16))[2:]) 256 A: As @vaulath said in the comments, bin truncates to the shortest representation with no leading zeros. So if a number has 2 zeros at the beginning it would only have 254 bits. You can also see this very easily: >>> bin(int("001001", 2))[2:] '1001' >>> len("001001") 6 >>> len(bin(int("001001", 2))[2:]) 4 If you want the full 256 bits, you could to this: >>> len(format(0,"0256b")) 256
[ "mathoverflow", "0000019410.txt" ]
Q: Do Abel summation and zeta summation always coincide? This is a more focused version of Summation methods for divergent series. Let $a_n$ be a sequence of real numbers such that $\lim_{x \to 1^{-}} > \sum a_n x^n$ and $\lim_{s \to 0^{+}} > \sum a_n n^{-s}$ both exist. (In particular, we assume that both of the sums in question converge in the appropriate region.) Need the limits be equal? I've thought about this before, and am doing so again thanks to the linked question. Here are some things I've tried: It is true if $a_n$ is periodic with average $0$. If it is true for $a_n$, then it is true for the sequence $b_{kn+r}=a_n$, $b_m=0$ if $m \not \equiv r \mod k$. It is true for $a_n=1$ if $n$ is an even square, $-1$ if $n$ is an odd square and $0$ otherwise. I tried to prove in general that, if it is true for $a_n$ then it is true for $b_{n^2}=a_n$, $b_m=0$ for $m$ not a square, but couldn't. It appears to be true for $a_n = (-1)^n \log n$, although I didn't check all the details. I do not know any explicit sequence $a_n$ which obeys the hypotheses of the question and is not $(C, \alpha)$-summable for some $\alpha$. So it is possible that this is really a theorem about higher Cesaro summability. But I suspect such sequences do exist. A natural generalization is: Let $a_n$, $\lambda_n$ and $\mu_n$ be three sequences of real numbers, with $\lambda_n$ and $\mu_n$ approaching $\infty$. If $\lim_{s \to 0^{+}} \sum a_n e^{-\lambda_n s}$ and $\lim_{s \to 0^{+}} \sum a_n e^{-\mu_n s}$ both exist, need they be equal? As far as I can tell, Wiener's generalized Tauberian theorem does not apply. A: I'm very dubious, but I don't have handy a copy of G.H. Hardy, Divergent Series, 1949 — it's my primary reference for this type of question. As you've correctly pointed out, the generalized question is whether $$\lim_{s\to 0^+} \sum a_n e^{-\lambda_n s} = \lim_{s\to 0^+} \sum a_n e^{-\mu_n s}$$ for $\lambda_n,\mu_n$ both increasing to $\infty$. And for this the answer is a resounding "not always". Consider for example $e^{-\lambda_n s} = x^n$ and $e^{-\mu_n s} = x^{\lfloor 3n/2 \rfloor}$, for some changes of variables $x(s)$, and $a_n = (-1)^n$. Then the LHS is: $$ 1 - x + x^2 - x^3 + x^4 - \dots = \frac 1 {1+x} \to \frac12 $$ whereas the RHS is: $$ 1 - x + x^3 - x^4 + x^6 - \dots = \frac 1 {1 + x + x^2} \to \frac13 $$ In general, by "spacing" the alternating sequence $(-1)^n$ correctly, you can get its Abel-style summations to converge to any number in $[0,1]$. This is a more continuous version of "divergent series are not associative", just like "conditionally convergent series are not commutative". The point is that by twiddling the coefficients in $\lim \sum a_n e^{-\lambda_n s}$, you effectively twiddle the associatization. But it might just happen that the $x^n$ and the $n^{-s}$ spacings are both sufficiently regular that they give the same answer. Hardy [op. cit.] does provide a number of theorems about when these different summation methods agree, although his main focus in the book is when these different summation methods give the same answer. A: I think the answer is 'yes.' I don't have a suitably general reason why this is the case, although surely one exists and is in the literature somewhere. At any rate, for the problem at hand, we have for $s > 0$ $$\sum \frac{a_n}{n^s} = \frac{1}{\Gamma(s)}\int_0^\infty \sum a_n e^{-nt} t^{s-1} dt.$$ Edit: the interchange of limit and sum used here requires justification, and this is done below. Supposing that $\sum a_n x^n \rightarrow \sigma$, we may write $\sum a_n e^{-nt} = (\sigma + \epsilon(t))\cdot e^{-t}$ where $\epsilon(t) \rightarrow 0$ as $t \rightarrow 0$, and $\epsilon(t)$ is bounded for all t. In this case $$\sum \frac{a_n}{n^s} = \sigma + O\left(s\int_0^\infty \epsilon(t) e^{-t} t^{s-1} dt\right)$$ Showing that error term tends to $0$ is just a matter of epsilontics; for any $\epsilon > 0$, there is $\Delta$ so that $|\epsilon(t)| < \epsilon$ for $t < \Delta$. Hence $$\left|s\int_0^\infty \epsilon(t) e^{-t} t^{s-1} dt \right| < s\epsilon \int_0^\Delta t^{s-1} dt + s\int_\Delta^\infty e^{-t}t^{s-1}dt < \epsilon \Delta^s + s\int_\Delta^\infty e^{-t} t^{-1} dt.$$ Letting $s \rightarrow 0$, our error term is bounded by $\epsilon$, but $\epsilon$ of course is arbitrary. Edit: Justifying the interchange of limit and sum above is surprisingly difficult. We will require Lemma: If for fixed $\epsilon > 0$, the partial sums $D_{\epsilon}(N) = \sum_{n=1}^N a_n/n^\epsilon = O(1),$ then (a) $A(N) = \sum_{n \leq N} a_n = O(n^\epsilon)$, and (b) $\sum_{n \leq N} a_n e^{-nt} = O(t^{-\epsilon})$, where the O-constants depend on $\epsilon.$ This, with the hypothesis that $\sum a_n/n^s$ converges for all $s > 0$, imply the conclusions a) and b) for all positive $\epsilon$. To prove part a), note that $$\sum_{n \leq N} a_n = \sum_{n \leq N} a_n n^{-\epsilon}n^\epsilon = \sum_{n \leq N-1} D_{\epsilon}(n) (n^\epsilon - (n+1)^\epsilon) + D_\epsilon(N)N^\epsilon,$$ which is seen to be $O(N^\epsilon)$ upon taking absolute values inside the sum. To prove part b), note that $$t^\epsilon \sum_{n \leq N} a_n e^{-nt} = t^\epsilon \sum_{n=1}^{N-1} A(n)(e^{-nt} - e^{-(n+1)t}) + t^\epsilon A(N) e^{-Nt} = O \left( \sum_{n\leq N} (tn)^\epsilon e^{-nt}(1-e^{-t}) + (tN)^\epsilon e^{-Nt}\right).$$ Now, $(tN)^\epsilon e^{-Nt} = O(1)$, and $$\sum_{n\leq N} (tn)^\epsilon e^{-nt}(1-e^{-t}) = 2^\epsilon(1-e^{-t}) \sum_{n\leq N} (tn/2)^\epsilon e^{-nt/2} e^{-nt/2} = O\left(\frac{1-e^{-t}}{1-e^{-t/2}}\right) = O\left(\frac{1}{1+e^{t/2}}\right) = O(1),$$ and this proves b). We use this to justify interchanging sum and integral as follows: note that $$\sum_{n=1}^N \frac{a_n}{n^s} = \frac{1}{\Gamma(s)}\int_0^\infty \sum_{n=1}^N a_n e^{-nt} t^{s-1} dt,$$ and therefore $$\frac{1}{\Gamma(s)}\int_0^\infty \lim_{N\rightarrow\infty}\sum_{n=1}^N a_n e^{-nt} t^{s-1} dt = \frac{1}{\Gamma(s)}\int_0^1 \lim_{N\rightarrow\infty}\sum_{n=1}^N a_n e^{-nt} t^{s-1} dt + \frac{1}{\Gamma(s)}\int_1^\infty \lim_{N\rightarrow\infty}\sum_{n=1}^N a_n e^{-nt} t^{s-1} dt.$$ In the first integral, note that for $\epsilon < s$, $\sum_{n \leq N} a_n e^{-nt} t^{s-1} = O(t^{s-\epsilon -1})$ for all $N$. So by dominated convergence in the first integral, and uniform convergence of $e^t \sum_{n=1}^N a_n e^{-nt}$ for $t \geq 1$ in the second, this is limit is $$\lim_{N\rightarrow\infty}\frac{1}{\Gamma(s)}\int_0^1 \sum_{n=1}^N a_n e^{-nt} t^{s-1} dt + \lim_{N\rightarrow\infty}\frac{1}{\Gamma(s)}\int_1^\infty \sum_{n=1}^N a_n e^{-nt} t^{s-1} dt = \lim_{N\rightarrow\infty} \sum_{n=1}^N a_n \frac{1}{\Gamma(s)}\int_0^\infty e^{-nt}t^{s-1} dt.$$ This is just $\sum_{n=1}^\infty \frac{a_n}{n^s}$. Note then that we do not need to assume from the start that the infinite Dirichlet sum tends to anything as $s \rightarrow 0$; once it converges for each fixed $s$, that is implied by the behavior of the power series. A: G. H. Hardy, DIVERGENT SERIES, page 76... "It is easy to give examples of series summable $(A,\log n)$ but not summable $(A)$: we shall see, for example, that $\sum n^{-1-ci}$, where $c>0$, is such a series." Before that, on page 73, we see if a series is both summable $(A,\log n)$ and summable $(A)$, then the two sums are equal.
[ "stackoverflow", "0037872592.txt" ]
Q: How to add dynamic element jquery? I have this html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Agenda</title> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="css/agenda.css" rel="stylesheet"> <script type="text/javascript" src="js/jquery-3.0.0.min.js"></script> <script type="text/javascript" src=js/agenda.js></script> </head> <body> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtNombre" placeholder="Usuario" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtTelefono" placeholder="Telefono" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtDireccion" placeholder="Direccion" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtEmail" placeholder="Correo" required="" autofocus="" class="form-control" > </div> </div> <div class="row"> <div class="col-xs-12 col-md-3 col-md-offset-9 "> <img src="img/mas.png" class="agregar" id="btnAgregar" autofocus="" > </div> </div> </div> </body> </html> When user press "add" it must to add a new row with same date in the inputs, but add to every row the button for, edit the current row and delete it. so you can add N element and delete Row by Row (or edit it one by one). I am working with jquery A: Hi please check this link https://plnkr.co/edit/B2Nmf5wzKBqHypnLFc59 HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" /> <script data-require="jquery" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="script.js"></script> </head> <body> <div class="container"> <div class="row main" id="main"> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtNombre" placeholder="Usuario" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtTelefono" placeholder="Telefono" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtDireccion" placeholder="Direccion" required="" autofocus="" class="form-control" > </div> <div class="col-xs-12 col-md-3 "> <input type="text" id="txtEmail" placeholder="Correo" required="" autofocus="" class="form-control" > </div> </div> <div class="row buttonbox"> <div class="col-xs-12 col-md-3 col-md-offset-9 "> <button type="button" class="btn btn-success add" >ADD +</button> <button type="button" class="btn btn-danger remove" >DEL -</button> </div> </div> </div> </body> </html> and JS // Add your javascript here $(function(){ var i = 0; var last12 = $('.buttonbox').last(); $(document).on('click', '.add', function() { var clone = $('#main').clone(); clone.find("input").val(""); clone.attr("id", "main" + i++).insertBefore(last12); //clone.id = "main" + i; }); $(".remove").click(function(){ $('.main:last').remove(); }); }); you can clone the above div and add again
[ "stackoverflow", "0055133123.txt" ]
Q: Why can a Rcpp::Function be used as boost::function, and can it be introspected at runtime? I have a vector<boost::function<void(void)>> -- essentially, a vector of function-like objects. The vector contains some Rcpp::Function objects, as well as some boost::function<void(void)> objects. I have two questions about it. First off, I don’t really understand how this works, because as far as I can tell, Rcpp::Function isn’t a subclass of boost::function. How does the vector store these objects that don't have the same class? (Or do they share a class somehow?) Second, and more important, I would like to be able to introspect the objects at runtime. I want to iterate over the vector and return a Rcpp::List representation of it: any Rcpp::Function objects will be added to the List, and any boost::function objects will simply be represented with an arbitrary string, like "C++ function". In the example below, I have a C++ function test which takes an Rcpp::Function as input and adds to a vector. It also adds a boost::function<void(void)> to the vector. Then it iterates over the list, executing each function. The last part, which I haven't figured out, is how to build a List, where the item added to the list depends each item's type. Is this possible? library(Rcpp) cppFunction( includes = ' #include <boost/function.hpp> #include <boost/bind.hpp> #include <iostream> void cpp_message(std::string s) { std::cerr << s << "\\n"; } ', code = ' Rcpp::List test(Rcpp::Function r_fn) { std::vector<boost::function0<void> > fns; // Add a Rcpp::Function to the vector fns.push_back(r_fn); // Add a boost::function<void(void)> to the vector boost::function<void(void)> cpp_fn = boost::bind(&cpp_message, "bar"); fns.push_back(cpp_fn); // Execute the functions to demonstrate the vector works for (int i=0; i<fns.size(); i++) { fns[i](); } // Create the List Rcpp::List result; for (int i=0; i<fns.size(); i++) { // What I would like to do is something like: // if (fns[i] is a Rcpp::Function) { // result[i] = fns[i]; // } else { // result[i] = "C++ function"; // } } return result; } ', depends = "BH" ) test(function() message("foo")) #> foo #> bar #> list() (Note that the order of output lines can differ depending on how the environment buffers the output, so you may see it come out in a different order.) A: How does the vector store these objects that don't have the same class? Well, it is not the vector that stores such objects (directly), instead a newly created boost::function object inside the vector will store the instance. How would the this object do so? Some simple demo class illustrates how this could be implemented: // first need a generic template allowing the Demo<void(void)> syntax template <typename S> class Demo; // now specialising (otherwise, we'd need to instantiate Demo<void, void>) template <typename R, typename ... PP> class Demo<R(PP...)> { class Wrapper { public: virtual ~Wrapper() { } virtual R operator()(PP...) = 0; }; template <typename T> class SpecificWrapper : public Wrapper { T t; public: SpecificWrapper(T& t) : t(t) { }; virtual R operator()(PP...pp) { return t(pp...); } }; // the trick: pointer to POLYMORPHIC type! Wrapper* w; public: // be aware that this constructor deliberately is NOT explicit template <typename T> Demo(T& t) : w(new SpecificWrapper<T>(t)) { } R operator()(PP...pp) { return (*w)(pp...); } }; The non-explicit constructor allows to implicitly create a new Demo object: Rcpp::Function r; // simplified just for demo! std::vector<Demo<void(void)>> v; v.push_back(r); // implicit call to non-explicit constructor! equivalent to: v.push_back(Demo<void(void)>(r)); Be aware that the class is just minimally implemented (solely the copy constructor; move constructor and appropriate assignment operators might yet be added), as it only serves for demonstration purposes. I would like to be able to introspect the objects at runtime. You're looking for std::function::target: auto l = []() { std::cout << "demo" << std::endl; }; std::function<void(void)> f(l); auto* pl = f.target<decltype(l)>(); if(pl) (*pl)(); But that smells a bit of bad design, just like needing dynamic_cast (which Demo most likely would use on the wrapper pointer in its own variant of target). Why would you want to get this back? Wouldn't you rather just want to handle all functions alike, whether Rcpp or not?