source
sequence
text
stringlengths
99
98.5k
[ "serverfault", "0000162682.txt" ]
Q: Quagga keeps announcing down routes I have set up BGP on two routers using qugga. When I down the interface that holds the IP block that I am advertising zerba removes the route from its table but bgpd keeps advertising it. I can see that it is still advertised via the neighboring BGP tables as well as the show ip bgp nei 172.16.14.1 ad command from the router that is doing the advertising. This interface holds the full route that is being advertised so there is no aggregation. As anyone run into this before ... it seems to fundamentally break the main functionality of a routing protocol... Update: So in the router I have the following for a BGP table. so-rt1# show ip bgp BGP table version is 0, local router ID is 172.16.14.1 Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S Stale, R Removed Origin codes: i - IGP, e - EGP, ? - incomplete Network Next Hop Metric LocPrf Weight Path *> 0.0.0.0 12.12.12.12 200 0 5555 i * 15.15.15.0/24 172.16.14.2 0 100 0 i *> 0.0.0.0 0 32768 i Total number of prefixes 2 For the 15.15.15.0/24 network, which I announce, the directly connect route (the last entry) is the route that is preferred. If I shutdown the interface that holds 15.15.15.0/24 not only is the directly connected route not removed from the BGP table, it is still the preferred route. So after shutting down that interface, the BGP table stays exactly the same. Zebra is aware that the directly connected 15.15.15.0/24 route is no longer there. I see it with show ip route while the interface is up and the entry is gone when I shut it down. So the problem I think is that the BGP table is somehow not getting the updates I believe it should from zebra. A: If I understand the question correctly you have an IGP (or local) route to the network, and you annouce it over BGP. When the route vanishes in the IGP (or local) you want BGP to pull the route. If that is the case you are doing stuff wrong(TM), and Quagga will not let you easily do this. From the manual for the network command: BGP: network A.B.C.D/M This command adds the announcement network. router bgp 1 network 10.0.0.0/8 This configuration example says that network 10.0.0.0/8 will be announced to all neighbors. Some vendors' routers don't advertise routes if they aren't present in their IGP routing tables; bgp doesn't care about IGP routes when announcing its routes. This is due to the increased flapping you can easily get if you export IGP information in BGP. We have enough of a route churn on the internet allready, and it's considered bad practice to redistribute routing information from IGP into BGP. BGP is not an IGP, and don't abuse it as one ;) Also I can't really see any good cases for pulling the route from the Internet (it will cause flapping and you risk getting dampened for hours or days), unless you are ending up in a split-AS situation if this specific route is gone and want to protect yourself from the weird routing issues this can cause. (In this case, you should consider if you want the router to stay online at all. Split-AS situations are nasty!) The correct solution(TM) is to leave the route up and as stable as possible, regardless of what your IGP is doing. If you lose the connection to the network just drop the traffic locally. Make sure you don't loop it back to your transit provider if the IGP route to the network is down. The basic rule is "never change your BGP announcements unless it's something the whole Internet has to know about". That your IGP is flapping is not something the rest of the Internet cares about. Edit: From what I understand your network looks like this: Provider (AS 5555) --------------------- Provider (AS 5555) (12.12.12.12) | | eBGP |eBGP | | Router1---------15.15.15.0/24---------------Router2 172.16.14.1 172.16.14.2 | iBGP | -------------------------------------------- And your problem is that if you take down the interface on Router1 towards 15.15.15.0/24 you want it to stop announcing the network so you shift the data over to 172.16.14.2. This type of automatic changes to your peering policy is not something you usually do, and is as far as I know not something supported by Quagga. Instead you are expected to reroute the data over the IGP and keep your peerings static. If you were to do changes to your peerings you would change the MED (MULTI_EXIT_DISC) to steer the traffic to the right router. Note that if taking down 15.15.15.0/24 splits your AS you have additional failure modes, none of them good.
[ "stackoverflow", "0031578862.txt" ]
Q: Are register of Converters in BeanUtils thread-local? I have a web project where BeanUtils is used to manipulation beans. In my code, in order to make BeanUtils transfer string records into java.util.Date fields properly, a DateConverter is registered into ConvertUtils class like that: ConvertUtils.register(dateConverter, Date.class); Moreover, In my project, different date formats is needed in different Actions, So, I registered different converters in different actions like that: public void Action1(){ DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPatterns(dateFormats1); ConvertUtils.register(dtConverter, Date.class); ... BeanUtils.populate(myBean1, hashMap1); } public void Action2(){ DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPatterns(dateFormats2); ConvertUtils.register(dtConverter, Date.class); ... BeanUtils.populate(myBean2, hashMap2); } But later, I noticed that registered Converter with same target class (Date here) will replace each other. So if ConvertUtils.register operation is not thread local, problems caused by concurrence may happen here, even through my website haven`t met any yet. So, would converter registered in one thread replace converter registered in another thread? If so, is there any work around for my circumstance? A: Apache commons beanutils uses a ContextClassLoaderLocal to manage the framework's instances. The concept is similar to a ThreadLocal except that it binds an instance to a thread's context class loader. So when the threads that execute Action1 and Action2 share the same context class loader a change to the ConverterUtils in one action will affect the other. To be safe you can use an own instance of a BeanUtilsBean in each action, e.g. public void Action1(){ BeanUtilsBean beanUtils = new BeanUtilsBean(); ConvertUtilsBean convertUtils = beanUtils.getConvertUtils(); DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPatterns(dateFormats1); convertUtils.register(dtConverter, Date.class); ... beanUtils.populate(myBean1, hashMap1); } Of course it would be better to configure the BeanUtilsBean once in the constructor of your class and just use it.
[ "stackoverflow", "0024131182.txt" ]
Q: set variable variable as array key I'm not sure how to ask this question, but here goes: $id = 1; $age = 2; $sort = "id"; // or "age"; $arr = array($$sort => 'string'); // so that it becomes 1 => 'string' ^ what goes here? // instead of 'id' => string' Is this something that the & character is used for, "variable variables"? or maybe eval? A: on topic to your question. With the logic of PHP, the best way I can see this being done is to assign your variable variables outside the array definition: $id = 1; $age = 2; $sort = "id"; // or "age"; $Key = $$sort; $arr = array($Key => 'string'); print_r($arr); Which outputs: Array ( [1] => string ) Though, personally. I'd suggest avoiding this method. It would be best to define your keys explicitly, to assist with backtracing/debugging code. Last thing you want to do, is to be looking through a maze of variable-variables. Especially, if they are created on the fly Tinkering. I've got this; $arr[$$sort] = "Value"; print_r($arr); I've looked into the method to creating a function. I do not see a viable method to do this sucessfully. With the information i've provided (defining out of array definition), hopefully this will steer you in the right direction
[ "stackoverflow", "0041196803.txt" ]
Q: Why Eclipse+PyDev cannot import the module termcolor? Environments: Ubuntu v12.04 x64 + Eclipse Neon v4.6.0 x64 + PyDev v5.2.0 + Python v2.7.12 + termColor v1.1.0. In the terminal of Ubuntu, Python command line can import termcolor and output colorful characters using commands like "print colored('hello','red')". It shows termcolor can work properly. PyCharm community v2016.3 can import the module termcolor and work properly. However, Eclipse+PyDev give the error "ImportError: No module named termcolor". ("from termcolor import colored" has been written.) Can any expert give a solution to this problem? Thanks! Edit: the PYTHONPATH in the interpreter is: /home/usr/name/eclipseworkspace/pydevTest/src /home/usr/name/eclipseworkspace/pydevTest/src /home/usr/name/tools/eclipse-java-neon-R-linux-gtk-x86_64/plugins/org.python.pydev_5.2.0.201608171824/pysrc /usr/local/lib/python2.7 /usr/local/lib/python2.7/lib-dynload /usr/local/lib/python2.7/lib-old /usr/local/lib/python2.7/lib-tk /usr/local/lib/python2.7/plat-linux2 /usr/local/lib/python2.7/site-packages /usr/local/lib/python2.7/site-packages/xlrd-1.0.0-py2.7.egg /usr/local/lib/python2.7/site-packages/xlutils-2.0.0-py2.7.egg /usr/local/lib/python2.7/site-packages/xlwt-1.1.2-py2.7.egg /usr/local/lib/python27.zip and termcolor is: <module 'termcolor' from '/usr/local/lib/python2.7/dist-packages/termcolor.pyc' A: To help in giving you a solution, please add to your module: import sys print('\n'.join(sorted(sys.path))) import termcolor print(termcolor) Run it from PyDev and post the output here. Then, just run: import termcolor print(termcolor) from the console and also say what's the output you have.
[ "stackoverflow", "0061279514.txt" ]
Q: How do I split the data in the column while loading in neo4j using neo4j-admin import? I am trying to import 2 csv files where 1 has nodes and another has relationship. In relationship, I have a column where data needs to be splitted. I tried using --array-delimiter='|' but I get an error. I was hoping if someone could help me with this issue. node.csv identifier:ID,name:LABEL 1,apple 2,ball 3,cat rel.csv source_ids:START_ID,target_ids:END_ID,type:TYPE,data 1,2,connection, 2,3,relation,test1|test2 3,1,connection,test1 1,3,relation,test4|test3|tet6 If I use the command below, I get data with | in it. It will not split data field. neo4j-admin import --verbose --ignore-extra-columns=true --nodes C:/Users/Sam/Documents/node.csv --relationships C:/Users/Sam/Documents/rel.csv. I get result in a format of : { "data": "test4|test3|tet6" } What I want is : { "data": ["test4","test3","tet6"] } When I try: neo4j-admin import --verbose --ignore-extra-columns=true --array-delimiter= "|" --nodes C:/Users/Sam/Documents/node.csv --relationships C:/Users/Sam/Documents/rel.csv. I get an error: Invalid value for option '--array-delimiter': cannot convert '' to char (java.lang.Ill egalArgumentException: Unsupported character '') [picocli WARN] Could not format 'Maximum memory that neo4j-admin can use for various d ata structures and caching to improve performance. Values can be plain numbers, like 1 0000000 or e.g. 20G for 20 gigabyte, or even e.g. 70%.' (Underlying error: Conversion = '.'). Using raw String: '%n' format strings have not been replaced with newlines. Pl ease ensure to escape '%' characters with another '%'. [picocli WARN] Could not format 'Maximum memory that neo4j-admin can use for various d ata structures and caching to improve performance. Values can be plain numbers, like 1 0000000 or e.g. 20G for 20 gigabyte, or even e.g. 70%.' (Underlying error: Conversion = '.'). Using raw String: '%n' format strings have not been replaced with newlines. Pl ease ensure to escape '%' characters with another '%'. [picocli WARN] Could not format 'Maximum memory that neo4j-admin can use for various d ata structures and caching to improve performance. Values can be plain numbers, like 1 0000000 or e.g. 20G for 20 gigabyte, or even e.g. 70%.' (Underlying error: Conversion = '.'). Using raw String: '%n' format strings have not been replaced with newlines. Pl ease ensure to escape '%' characters with another '%'. Thanks, Sam A: To define an array type, append [] to the type. Example: source_ids:START_ID,target_ids:END_ID,type:TYPE,data:[] Refer documentation
[ "stackoverflow", "0058190064.txt" ]
Q: How to make a discord bot send a picture you sent to it via dm to a certain channel So I kept thinking about this piece of code. The logic behind it is "you send the bot a screenshot via DM (direct message) and the bot is supposed to take that picture and put it to a certain channel that exists in a certain server (probably with id). The problem starts when I tell it to send the file, it just stops without an error happening on the console, sometimes it shows the answer "you successfully sent a screenshot" sometimes it does not. It is clear to me that it has a problem to realize that I am sending a picture instead of plain text, I guess?. at this point, I am kinda stuck with not many options. (by the way, this block of code is attached on an "event") client.on("message", message => { message.author.send("Please send a screenshot"); const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {}); console.log(collector) collector.on('collect', message => { if (message.attachments.size > 0) { message.channel.send("You successfully sent a screenshot") console.log(`Collected ${message.content}`) client.channels.get(`628607857662623745`).send(message.content); } else if (message.attachments.size < 0) { message.channel.send("you did not"); } }) The bot is just required to send ONLY pictures you send it via DMs to a certain channel on discord. A: 1. You're collecting messages on the wrong channel Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {}); will collect on message.channel, which is the channel the initial 'trigger' message was sent in, not the DMChannel. To collect on the DMChannel, you would need to do something like that: if (initial_trigger) { message.author.createDM().then(dmc => { const collector = new Discord.MessageCollector( dmc, m => m.author.id === message.author.id, {} ); [...] }); } 2. You're sending back the wrong content client.channels.get(`628607857662623745`).send(message.content); will only send the message.content() which, when you send a file without any comment, is empty. To send the file back and not the content, you will need to use .sendFile() like so: console.log(`Collected ${message.attachments.size} screenshots`); client.channels .get(`628607857662623745`) .send({files:[message.attachments.first().url]});
[ "stackoverflow", "0060391735.txt" ]
Q: Broadcasting a list using sendBroadcast() I have a list which I am trying to broadcast with the use of intents. After following online tutorials, I was adviced to use Parcelable in order to send this data. However, I keep getting this error in logcat: Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable from this line of code bundle.putParcelable("data", (Parcelable)tweets); I do not know how to correct this. Where i am building the intent protected void onHandleWork(@NonNull Intent intent) { Log.d(TAG, "onHandleWork: "); List<tweet> tweets = new ArrayList(); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("HyjgZgfiqSODTdICZUXIHI8HK", "TlynMItosq99QxnLMLGxA6FElD3TAKx9UmBxva5oExg9Gz1mzV"); AccessToken accessToken = new AccessToken("2362719277-w5QlRNB2I7PXdMJuDXf5cc8FDT5H8X38ujxrtiT", "3v2Z2cqezaFrV6pFHu2yfPVFHZgMvLjMVKH4cUujI9kwI"); twitter.setOAuthAccessToken(accessToken); Query query = new Query("Twitch"); try { QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { String createdat = status.getCreatedAt().toString(); String text = status.getText(); String retweets = String.valueOf(status.getRetweetCount()); String favs = String.valueOf(status.getFavoriteCount()); String uri = status.getUser().getProfileImageURL(); tweet onetweet = new tweet(createdat,text,retweets,favs,uri); // Log.d(TAG, status.getText()); tweets.add(onetweet); } if (isStopped()) return; } catch (TwitterException e) { e.printStackTrace(); } sendToUI(tweets); } private void sendToUI(List tweets) { Intent intent = new Intent("tweet_result"); Bundle bundle = new Bundle(); bundle.putParcelable("data", tweets); intent.putExtras(bundle); sendBroadcast(intent); } My tweet POJO import android.os.Parcel; import android.os.Parcelable; public class tweet implements Parcelable { private String created_at; private String text; private String retweet_count; private String favorite_count; private String image_uri; public String getImage_uri() { return image_uri; } public String getCreated_at() { return created_at; } public String getText() { return text; } public String getRetweet_count() { return retweet_count; } public String getFavorite_count() { return favorite_count; } protected tweet(Parcel in) { created_at = in.readString(); text = in.readString(); retweet_count = in.readString(); favorite_count = in.readString(); image_uri = in.readString(); } public static final Creator<tweet> CREATOR = new Creator<tweet>() { @Override public tweet createFromParcel(Parcel in) { return new tweet(in); } @Override public tweet[] newArray(int size) { return new tweet[size]; } }; @Override public int describeContents() { return 0; } public tweet(String created_at, String text, String retweet_count, String favorite_count, String image_uri) { this.created_at = created_at; this.text = text; this.retweet_count = retweet_count; this.favorite_count = favorite_count; this.image_uri = image_uri; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(created_at); dest.writeString(text); dest.writeString(retweet_count); dest.writeString(favorite_count); dest.writeString(image_uri); } } A: Changing my sendToUI() to this has worked: private void sendToUI(List tweets) { Intent intent = new Intent("tweet_result"); //tweet_result is a string to identify this intent Bundle bundle = new Bundle(); bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) tweets); intent.putExtras(bundle); sendBroadcast(intent); }
[ "stackoverflow", "0048987662.txt" ]
Q: What does a comma after a variable name mean in python when used to create an animation? I was wondering if someone could explain to me what do the , commas do in the line P, = ax.plot([],[]) Q, = ax.plot([],[]) Qa, =ax.plot([],[]) When I use the code without these commas I get an error explaining to me that lists do not have the set_data attribute. I have been trying to decipher it all morning but so far have been unable to. The complete code is below. It is part of small program to run a brief animation. Thanks for all your help. from math import cos, sin , pi from matplotlib import pyplot as plt import numpy as np from matplotlib import animation as anim theta = np.linspace(0,2*pi, 100) #psi = pi/3 a = 2 b = 1 x = [] y = [] for angle in theta: x.append(a*cos(angle)) y.append(b*sin(angle)) fig = plt.figure(figsize=(8,8), dpi=80) plt.subplot(111) ax = plt.axes(xlim =(-2.5, 2.5), ylim = ( -2.5, 2.5)) plt.plot(x,y) P, = ax.plot([],[]) Q, = ax.plot([],[]) Qa, =ax.plot([],[]) #plt.plot([0,a*cos(psi)],[0,b*sin(psi)], label = "P") #plt.plot([0,a*cos(psi + pi/2)],[0,b*sin(psi + pi/2)], label = "Q") #plt.plot([0, a*cos(psi-pi/2)],[0,b*sin(psi- pi/2)], label = "Q'") plt.legend() def update(frame): psi = pi*frame/ 100 P.set_data([0,a*cos(psi)],[0,b*sin(psi)]) Q.set_data([0,a*cos(psi + pi/2)],[0,b*sin(psi + pi/2)]) Qa.set_data([0, a*cos(psi-pi/2)],[0,b*sin(psi- pi/2)]) return P, Q, Qa def init(): P.set_data([],[]) Q.set_data([],[]) Qa.set_data([],[]) return P, Q, Qa animation = anim.FuncAnimation(fig, update, interval=10, blit= False, init_func = init, frames=200) # animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40) plt.show() A: ax.plot() returns a tuple which contains only one element. If you assign it without the comma, you just assign the tuple. >>> t = (1,) >>> a = t >>> a (1,) But if you assign it with the comma, you unpack it. >>> t = (1,) >>> a, = t >>> a 1
[ "ru.stackoverflow", "0000411481.txt" ]
Q: Hibernate Entity many to one как использовать в сервлете? Использую Hibernate4, Spring mvc4, maven, tomcat7. Есть две таблицы: Категории и Проекты. Отношение Категории к Проектам = один-ко-многим, по ключу: ID_CATEGORY. Хочу показать список проектов, которые содержатся в конкретной Категории через @Controller, но не знаю, как их вызвать. Сейчас вывожу Проекты конкретной Категории в Контроллере таким образом: List<Project> projects = projectService.findAllProjects(idCategory); @Entity @Table(name="CATEGORIES", uniqueConstraints = {@UniqueConstraint(columnNames = "ID_CATEGORY")}) public class Category { public Category() { } public Category(int idCategory) { this.idCategory = idCategory; } @Id @Column(name = "ID_CATEGORY", unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private int idCategory; @Size(min=3, max=50) @Column(name = "NAME", nullable = false) private String name; @OneToMany(fetch = FetchType.LAZY) private List<Project> projects; public List<Project> getProjects() { return this.projects; } public void setProjects(List<Project> projects) { this.projects = projects; } public int getIdCategory() { return idCategory; } public void setIdCategory(int idCategory) { this.idCategory = idCategory; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Category)) return false; Category other = (Category) obj; if (idCategory != other.idCategory) return false; return true; } @Override public String toString() { return "Category [id=" + idCategory + ", name=" + name + "]"; } } @Entity @Table(name = "PROJECTS") public class Project { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_PROJECT") private int idProject; @NotNull @Column(name = "ID_CATEGORY") private String idCategory; @NotNull @Size(min = 3, max = 50) @Column(name = "NAME") private String name; @NotNull @Size(min = 15, max = 250) @Column(name = "SHORT_DESCRIPTION") private String shortDescription; @Size(min = 30, max = 500) @Column(name = "FULL_DESCRIPTION") private String fullDescription; @Column(name = "FOTO") private String foto; @Column(name = "LINK") private String link; @NotNull @Column(name = "HOW_MUCH_NEEDED") private int howMuchNeeded; @NotNull @Column(name = "HOW_MUCH_COLLECTED") private int howMuchCollected; @NotNull @Column(name = "HOW_MUCH_REMAINING") private int howMuchRemaining; @Temporal(TemporalType.DATE) @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate") @Column(name = "DATE_CLOSE") private LocalDate dateClose; @Column(name = "FAQ") private ArrayList<String> faq; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ID_CATEGORY", nullable = false, insertable = false, updatable = false) private Category category; public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public ArrayList<String> getFaq() { return faq; } public void setFaq(ArrayList<String> faq) { this.faq = faq; } public int getIdProject() { return idProject; } public void setIdProject(int idProject) { this.idProject = idProject; } public String getIdCategory() { return idCategory; } public void setIdCategory(String idCategory) { this.idCategory = idCategory; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } public String getFullDescription() { return fullDescription; } public void setFullDescription(String fullDescription) { this.fullDescription = fullDescription; } public String getFoto() { return foto; } public void setFoto(String foto) { this.foto = foto; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public int getHowMuchNeeded() { return howMuchNeeded; } public void setHowMuchNeeded(int howMuchNeeded) { this.howMuchNeeded = howMuchNeeded; } public int getHowMuchCollected() { return howMuchCollected; } public void setHowMuchCollected(int howMuchCollected) { this.howMuchCollected = howMuchCollected; } public int getHowMuchRemaining() { return howMuchRemaining; } public void setHowMuchRemaining(int howMuchRemaining) { this.howMuchRemaining = howMuchRemaining; } public LocalDate getDateClose() { return dateClose; } public void setDateClose(LocalDate dateClose) { this.dateClose = dateClose; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Project)) return false; Project other = (Project) obj; if (idProject != other.idProject) return false; return true; } @Override public String toString() { return "Project [idProject=" + idProject + "idCategory=" + idCategory + ", name=" + name + ", dateClose=" + dateClose + "]"; } } @Controller @RequestMapping("/") public class AppController { @Autowired CategoryService categoryService; @Autowired ProjectService projectService; @RequestMapping(value = { "/", "/categories" }, method = RequestMethod.GET) public String listCategories(ModelMap model) { List<Category> categories = categoryService.findAllCategories(); model.addAttribute("categories", categories); return "categories"; } @RequestMapping(value = { "/projects" }, method = RequestMethod.GET) public String listProjects(HttpServletRequest req, ModelMap model) { int idCategory = Integer.valueOf(req.getParameter("category")); List<Project> projects = projectService.findAllProjects(idCategory); model.addAttribute("projects", projects); model.addAttribute("category", idCategory); return "projects"; } A: скорее всего, необходимо указать какое поле мапить для связи. к примеру так: @OneToMany(fetch = FetchType.LAZY, mappedBy = "ID_CATEGORY") private List<Project> projects;
[ "genealogy.stackexchange", "0000017542.txt" ]
Q: Blank FAMC tags when exporting from ancestry.com, causing parentless children when imported to geneanet.org I have been exporting my personal family tree from ancestry.com via the built-in GEDCOM export feature. This tree has about 36,000 members. However, when I import the GEDCOM file to geneanet.org, I happened to find a set of siblings that were essentially 'floating' in the family tree, with no recorded parents according to the website. After further investigation in the initial GEDCOM file, I found that there were 67 total people with FAMC tags attributed to them, but with completely blank values. I have no idea what may have caused these issues, especially on such a small number of the total individuals, but I am curious if anyone has any experiences with this. It may also be important that all these individuals fell into one of 10 different families. An abbreviated (and name-changed) example below shows how the GEDCOM file looks like for one of these individuals. 0 @P1@ INDI 1 DEAT 2 DATE 17 Sept 1997 1 BIRT 2 DATE 15 Mar 1927 1 NAME John /Smith/ 1 SEX F 1 FAMC 0 (etc) A: A FAMC tag with no link is illegal in GEDCOM. Thus this is a bug with the GEDCOM export at Ancestry. If the tag is included, then it must point to the FAM record for the parents. If there are no parents, then the FAMC tag must not be included. Without seeing your GEDCOM file and comparing it to your family tree at Ancestry, it's impossible to tell what the cause is. Maybe there are siblings connected to the same parent but neither parent is defined. You can be a good citizen and report this problem to Ancestry so they can fix it. And you can tell Geneanet as well so they can give a message to warn the user that empty FAMC records were found.
[ "raspberrypi.stackexchange", "0000044433.txt" ]
Q: Does WiFi on the Pi 3 reduce the Ethernet bottleneck when using USB device? We all know that on Raspberry Pi 2 and previous models, the USB and Ethernet bandwidth is shared, so when we transfer data over Ethernet to a USB device and vice-versa we are limited by this fact. Since on the Raspberry pi 3 we have WiFi capabilities, can we use wlan0 to reserve all the bandwidth to USB ports? A: From the looks of it, yes. From the info I've read, the BCM43438 is connected to the SoC in two ways: The WiFi functionality uses the SDIO interface The Bluetooth functionality is connected via UART Based on this, we can safely say that it completely bypasses the USB interface so you can go ahead and use the USB ports to the fullest without affecting networking speed and vice versa. tl;dr: The WiFi/Bluetooth chip doesn't use USB. Source: Post by a Raspberry Pi engineer: (Link)
[ "aviation.stackexchange", "0000029625.txt" ]
Q: Is a recoil start (hand propping) allowed if it isn't mentioned in the aircraft manual? Is a recoil start (hand propping) allowed without it being referenced in the aircraft manual? In a Cessna 150, for example. A: You didn't say exactly what "allowed" means, e.g. do you mean approved by the manufacturer, or legal in a certain country? But if you're asking is it legal in the US (under FAA regulations), then the answer is yes. AOPA has a nice article on exactly this question, called Hand propping: A legal primer. It says: There is no specific FAA regulation that applies to hand propping an airplane, either to prohibit it or to direct how it is to be done But: The FAA contends that hand propping is a two-person operation and has expressed this view in the Airplane Flying Handbook (FAA-H-8083-3A) under the section titled “Hand propping.” Of course, this publication is not regulatory, but the NTSB was surely influenced by it in a 1983 legal decision. In that case, the FAA sought to suspend a pilot’s certificate for being careless or reckless when, while attempting to start a VariEze experimental aircraft, it “got away” and ran into a parked aircraft. The NTSB concluded that the pilot had violated 14 CFR 91.13 (careless and reckless operation): The board affirmed the administrative law judge’s finding that there had been a 91.10 (now 91.13) violation That means that hand propping itself isn't illegal, but doing it wrongly and against the FAA's general procedures could get you in trouble: There have been at least two previously issued NTSB (full board) decisions and one subsequent decision that refer to these generally accepted procedures and precautions for hand propping. The precedent has been set. So, hand proppers beware; if you fail to follow proper precautions and the airplane gets away, the FAA might pursue action against you for being careless or reckless.
[ "stackoverflow", "0038267202.txt" ]
Q: Merge Database Tables Based on 90 days with dplyr/R I have the following two database tables: **PLAN table**: customerID plantype purchasedate 1 A 7/16/2004 1 A 9/1/2005 2 B 12/3/2014 and: **EMAIL table** customerID emaildate openIND opendate 1 2/3/2005 1 2/4/2005 1 10/23/2005 0 NULL 2 1/2/2014 1 1/2/2014 2 1/10/2014 1 1/11/2014 What I'm trying to do is create a dataframe in R with dplyr that will calculate the percentage of emails opened for all customers 90 days or less before the purchase date (column C in the Plan table). I can do this in Excel with a ton of if-statements, vlookups, and manipulation. I've read many examples of using summarise() and group_by() on this very helpful site, but I'm having trouble actually implementing this in R as these examples are a bit too advanced for my current R skills. I am able to calculate lifetime percentage of emails opened with these aggregate functions with dplyr, but I'm struggling how to specify a 90-day range, compounded by the fact that 'purchasedate' is different for each row in the large dataset. My current successful code for the lifetime calculation is below: df2 <- select(PLAN,customerID,year) %>% filter(customerID %in% southeast_vector) %>% arrange(customerID, year) %>% left_join(EMAIL)%>% select(customerID, emaildate, year) %>% group_by(customerID, year) %>% summarise(lifetimeNumEmails = n(), lifetimeNumEmailsOpened = sum(openIND))%>% mutate(lifetimeEmailOpenPercentage = lifetimeNumEmailsOpened/lifetimeNumEmails) I would greatly appreciate any guidance you can provide for how to specify this 90-day range so that I can compute this calculation dynamically in R. Hopefully in addition to solving my question, this can help those making the initial transition from excel to R and dplyr in their efforts too. Thanks very much in advance. A: The 90 day condition could be implemented as dayLookup = 90 and filter(openIND ==1 & (purchasedate - opendate) >= dayLookup ) require(dplyr) planDF = read.table(text="customerID plantype purchasedate 1 A 7/16/2004 1 A 9/1/2005 2 B 12/3/2014",stringsAsFactors=FALSE,header=TRUE) planDF$purchasedate = as.Date(planDF$purchasedate ,format="%m/%d/%Y") planDF$year = year(planDF$purchasedate) emailDF = read.table(text="customerID emaildate openIND opendate 1 2/3/2005 1 2/4/2005 1 10/23/2005 0 NULL 2 1/2/2014 1 1/2/2014 2 1/10/2014 1 1/11/2014",stringsAsFactors=FALSE,header=TRUE) emailDF$emaildate = as.Date(emailDF$emaildate ,format="%m/%d/%Y") emailDF$opendate = as.Date(emailDF$opendate ,format="%m/%d/%Y") #southest_vector was not provided outputDF <- select(planDF,purchasedate,customerID,year) %>% #filter(customerID %in% southeast_vector) %>% arrange(customerID, year) %>% left_join(emailDF)%>% select(customerID,purchasedate,openIND,opendate, emaildate, year) %>% group_by(customerID, year) %>% filter(openIND ==1 & purchasedate - opendate >= dayLookup ) %>% summarise(lifetimeNumEmails_90d = n(),lifetimeNumEmailsOpened_90d = sum(openIND), lifetimeEmailOpenPercentage_90d = lifetimeNumEmailsOpened_90d/lifetimeNumEmails_90d) %>% as.data.frame() Please confirm if the output meets your requirements #Output: # customerID year lifetimeNumEmails_90d lifetimeNumEmailsOpened_90d lifetimeEmailOpenPercentage_90d # 1 1 2005 1 1 1 # 2 2 2014 2 2 1
[ "ru.stackoverflow", "0000464140.txt" ]
Q: Как сделать commit в свой репозиторий после клонирования чужого? Подскажите, как верно сделать: я клонирую удаленный репозиторий (шаблон сборки проекта), далее я работаю с ним, создавая новый проект, комичу изменения, но мне нужно комитить уже в свой репозиторий (своего проета), как это правильно сделать? A: коммиты с помощью команды git commit вы и делаете в свой локальный репозиторий, который находится в каталоге .git. более того: программа git не умеет делать коммиты куда-либо помимо вашего локального репозитория. да, произведённые в вашем локальном репозитории изменения вы можете впоследствии отправить в какой-нибудь другой репозиторий (в который у вас есть право записи). но это совсем другая история. A: Если вы клонировали с GitHub, BitBucket или другого подобного сервиса и теперь хотите получить свой удаленный репозиторий, то удобнее всего пойти таким путем. Нужно зарегистрироваться на сервисе. Создайте форк (fork) интересующего вас репозитория. Теперь у вас есть собственная копия удаленного репозитория, связанная с изначальной. Клонируйте эту копию. Теперь вы можете сохранять коммиты в свой локальный репозиторий, а потом пушить их в свой удаленный. Если вы захотите предложить свои изменения в изначальный репозиторий, для этого есть специальный инструмент под названием пулл-реквест или мерж-реквест (pull request, merge-request). Подробнее об этом: GitHub Flow GitLab Flow
[ "stackoverflow", "0032038690.txt" ]
Q: regex that checks if the string starts with two upper-case followed by numbers Hi Guys I need a regex that checks if the string starts with two upper-case followed by numbers: Example: DE123456789 Thanx a lot of. A: Literally: ^[A-Z]{2}\d+ ^ - start of the string [A-Z] - an upper case letter {2} - two of those \d - a digit + - one or more of those
[ "stackoverflow", "0051648724.txt" ]
Q: relative import in pycharm 2018 does not work like relative import in python 3.6 I have read endless discussions on relative import in python, I think that one of the reasons it is so confusing is that it changes fro one Python version to another (my version is 3.6). But here the culprit seems to be PyCharm (unless i'm mistaken..) and i wonder if anyone came across a solution to this issue. for a project with this layout: /project |-- __init__.py |---subfolder |-- __init__.py |-- AA.py |-- BB.py Let's imagine that AA.py contains some fuction myfunc inside the file BB.py if i write this import: from AA import myfunc Then python works perfectly, but PyCharm sees it as an error: So to make PyCharm happy i can add the . to the import and then the error is seemingly resolved: from .AA import myfunc But then python is not happy, giving me the error: ModuleNotFoundError: No module named '__main__.AA'; '__main__' is not a package So to conclude, I use the import that actually works (i.e. from AA import myfunc) but it would be great if i could make PyCharm agree to it somehow because then it offers features such as auto complete, go to definition and so on. not duplicates: I know it seems like this subject was discussed over and over but it also has many aspects. Here i'm talking about the pycharm aspect and therefore this topic is new as far as i know. How does PyCharm handle relative imports of modules? - is a user who didn't add the root project dir to PYTHONPATH Pycharm auto relative imports - is talking about auto-import feature that is not the case here Subpackages and relative imports in PyCharm - is talking about import issue in python 2.7 but in here i'm not having any issue to import Relative imports for the billionth time - offeres a great review of importing issues and also features a very detailed answer - none of it helps in my case because i don't have any import issue. not to mention that it is python 2.7 topic and not 3.x A: Mark subfolder as Source Root with right-click in the project tree -> Mark directory as ... -> Sources Root. PyCharm adds all Source Roots to PYTHONPATH by default so the issue should be resolved The problem is PyCharm doesn't know you are going to execute BB.py directly, e.g. let's say you have main.py in the root with from subfolder import BB. Calling python main.py will raise ModuleNotFoundError: No module named 'AA' (make sure to use Python 3 to avoid implicit relative imports from Python 2). Hope it makes sense and I didn't miss anything. A: You can get both python and pycharm to agree by using from subfolder.AA import myfunc However, according to here, from .AA import myfunc appears to be the correct syntax. But idk why it's not working.
[ "stackoverflow", "0058815243.txt" ]
Q: How to create a tuple of dictionaries in Python I have a problem in which I'm editing the value of one of the keys of a dictionary and then I want to store these dictionaries as entries of a tuple. But the problem is that the tuple seems to be adding dictionaries by reference. An example code is provided here: import numpy as np if __name__ == "__main__": dict_decision = {'policy': 'decision-rule', 'file': 'policy', 'nopts': 1, 'vect_td': 10} lifetime = 40; # years vect_td = np.arange(1,lifetime) tup_dict = () count = 0 for td in vect_td: dict_decision.update({'vect_td':int(td)}) #print(dict_decision) tup_dict = tup_dict + (dict_decision,) count = count + 1 At the end of the for-loop, the dictionary dict_decision, has the key vect_td = 39. When I check the tup_dict, all the dictionaries stored inside have vect_td = 39 where infact I want them to vary from 1 to 39. It seems to have passed the dictionary dict_decision by reference. What should I do to rectify the situation? A: This happens because when you call dict_decision.update(...), you update the same dict instance in every iteration of the loop. This means that your tuple does indeed contain a lot of references to the same dict. If you make a copy of the original dict before calling update on it, it will probably work better: for td in vect_td: td_dict = dict_decision.copy() td_dict.update({'vect_td': int(td)}) tup_dict = tup_dict + (td_dict,) count = count + 1 As suggested in the comment on your question, you probably also want a list instead of a tuple, so that you don't have to create new tuples for each iteration of the loop, but that is not strictly relevant to your question.
[ "stackoverflow", "0044457019.txt" ]
Q: Create own library of C functions I have been learning C for a couple weeks now (off and on). My primary use will be data analysis. I am surprised to find that simple functions are not available in the standard math.h library (e.g. average, mode, variance, etc.). Granted, these functions are simple enough to write, but doing so EVERY time they are needed is cumbersome. I could write my own header file (call it my_math.h) to store all of the non-standard functions, and include this file as needed. I have two questions: If I create a header file, how do I point my compiler to it? Obviously, I would not want to have to copy the .h file to each project's directory. Am I reinventing the wheel here? Is there a standard library that has all of these functions pre-built? A: The easiest way to do that is by using a Makefile which makes the link between your *.c and your *.h. You have to declare your functions' headers into the *.h. You can find some pieces of information here : Makefile include header .
[ "stackoverflow", "0050443538.txt" ]
Q: How the consecutive numbers can be replaced with the range of number and random number should be as it is? If there are numbers in which some are in sequence and some are random number, then how the consecutive numbers can be replaced with the range of number and random number should be as it is? for eg: 1,2,3,4,5,6, 458,243 output: 1-6,458,243 A: I have just solved this problem..Its super simple just some if-else condition, however, I don't think about efficient way, so please follow the solution and try to efficient it. public static void main(String[] args) { int [] numberList = {1,2,3,4,5,6,458,243}; int initialSequence = -1; int endSequence = -5; for (int num = 0; num<numberList.length;num++) { if(num<numberList.length-1) { if(initialSequence == -1 && numberList[num] == numberList[num+1]-1) { initialSequence = endSequence = numberList[num]; }else if(initialSequence == -1 && numberList[num] != numberList[num+1]-1){ System.out.print(numberList[num] + " "); }else if(initialSequence != -1 && numberList[num] == numberList[num+1]-1) { endSequence = numberList[num]; } else { System.out.print(initialSequence + "-" + (endSequence+1) + " "); initialSequence = -1; endSequence = -5; } }else { if(initialSequence == -1) System.out.print(numberList[num] + " "); else { System.out.print(initialSequence + "-" + (endSequence+1) + " "); } } } }
[ "scifi.stackexchange", "0000112264.txt" ]
Q: How did the Falcon end up on Jakku? What is the canon explanation for how: Han Solo "lost" the Falcon and it ended up on Jakku, abandoned in what looks like a junkyard. I don't recall the movie discussing this other than in a brief passing. It seems unlikely that a ship like that would end up sitting derelict on a no-name planet like it did and so I am curious what the canon explanation is. A: Novelization by Foster covers it. Someone stole it from Han, by the name of Ducain (no info on him yet). Impatiently, their captor gestured ever so slightly with the muzzle of his blaster. “Where’d you find this ship?” “Right here.” She saw no reason not to tell the truth. “I mean, down on the surface. Niima Outpost, to be specific.” Dropping his lower jaw to signify his disbelief, he stared back at her. “Jakku? That junkyard?” “Thank you!” Finn said. “Junkyard!” His original opinion confirmed, he shot Rey a look that was pure I-told-you-so. Looking away from them for the first time since they had emerged from below, their captor addressed his towering cohort. “Told ya we should’ve double-checked the Western Reaches! Just lucky we were in the general vicinity when the ship powered up and its beacon snapped on.” He turned back to Rey. She was trying to make sense of the mismatched pair standing before her and failing utterly. “Who had it?” he continued. “Ducain?” Again, she thought: no reason to prevaricate. “I stole it from a salvage dealer named Unkar Plutt.” Brows narrowed as the weathered visage wrinkled even more. “From who?” “Look.” Taking a chance, Rey lowered her hands so she could spread her arms wide. “I don’t know all the details for sure. I’m not privy to Plutt’s private accounting. But talk says that Plutt stole this ship from the Irving Boys, who stole it from Ducain.” “Who stole it from me!”
[ "stackoverflow", "0019465347.txt" ]
Q: Random number with equal total I have 4 number a,b,c,d : integers i need to have a random number between 2-7 assigned to each one but the total of all four numbers has to be 22 how can i do this? A: First of all I'm going to make it clear that as stated the question does not uniquely define the problem. You ask for random sampling, but do not specify the desired distribution of the samples. It's a common abuse of mathematical terminology to say random when you actually mean uniformly distributed. So I'm going to assume that's what you mean. Specifically that you want all possible distinct sets of 4 numbers to have equal probability of selection. The simplest and most efficient way to achieve this is as follows: Enumerate all such possible sets of 4 numbers. Count these sets of numbers, say N. To sample, choose random number, i say, from uniform distribution in range 0 to N-1. Return the i-th set of 4 numbers. The list of possible distinct sets is small. Off the top of my head I'd guess there are around 50 candidates. Generating the list of candidates is quite simple. Just run three nested for loops from 2 to 7. This gives you combinations of the first three numbers. Add them up, subtract from 22 and check if the final number is in range. Since you seem to like to see code, here's a simple demonstration: {$APPTYPE CONSOLE} uses System.Math, Generics.Collections; type TValue = record a, b, c, d: Integer; procedure Write; end; procedure TValue.Write; begin Writeln(a, ' ', b, ' ', c, ' ', d); end; var Combinations: TArray<TValue>; procedure InitialiseCombinations; var a, b, c, d: Integer; Value: TValue; List: TList<TValue>; begin List := TList<TValue>.Create; try for a := 2 to 7 do for b := 2 to 7 do for c := 2 to 7 do begin d := 22 - a - b - c; if InRange(d, 2, 7) then begin Value.a := a; Value.b := b; Value.c := c; Value.d := d; List.Add(Value); end; end; Combinations := List.ToArray; finally List.Free; end; end; function GetSample: TValue; begin Result := Combinations[Random(Length(Combinations))]; end; var i: Integer; begin Randomize; InitialiseCombinations; for i := 1 to 25 do GetSample.Write; Readln; end. It's clear from inspection that this algorithm samples from the available values uniformly. But what about the other proposed algorithms. We can perform a crude heuristic test by sampling repeatedly and counting how many times each possible sample is produced. Here it is: {$APPTYPE CONSOLE} uses System.SysUtils, System.Math, Generics.Collections; type TValue = record a, b, c, d: Integer; procedure Write; class operator Equal(const lhs, rhs: TValue): Boolean; end; procedure TValue.Write; begin Writeln(a, ' ', b, ' ', c, ' ', d); end; class operator TValue.Equal(const lhs, rhs: TValue): Boolean; begin Result := (lhs.a=rhs.a) and (lhs.b=rhs.b) and (lhs.c=rhs.c) and (lhs.d=rhs.d); end; var Combinations: TArray<TValue>; procedure InitialiseCombinations; var a, b, c, d: Integer; Value: TValue; List: TList<TValue>; begin List := TList<TValue>.Create; try for a := 2 to 7 do for b := 2 to 7 do for c := 2 to 7 do begin d := 22 - a - b - c; if InRange(d, 2, 7) then begin Value.a := a; Value.b := b; Value.c := c; Value.d := d; List.Add(Value); end; end; Combinations := List.ToArray; finally List.Free; end; end; function GetSampleHeffernan: TValue; begin Result := Combinations[Random(Length(Combinations))]; end; function GetSampleVanDien: TValue; const TOTAL = 22; VALUE_COUNT = 4; MIN_VALUE = 2; MAX_VALUE = 7; var Values: array[0..VALUE_COUNT-1] of Integer; Shortage: Integer; Candidates: TList<Integer>; ValueIndex: Integer; CandidateIndex: Integer; begin Assert(VALUE_COUNT * MAX_VALUE >= TOTAL, 'Total can never be reached!'); Assert(VALUE_COUNT * MIN_VALUE <= TOTAL, 'Total is always exceeded!'); Randomize; Candidates := TList<Integer>.Create; try for ValueIndex := 0 to VALUE_COUNT-1 do begin Values[ValueIndex] := MIN_VALUE; Candidates.Add(ValueIndex); end; Shortage := TOTAL - VALUE_COUNT * MIN_VALUE; while Shortage > 0 do begin CandidateIndex := Random(Candidates.Count); ValueIndex := Candidates[CandidateIndex]; Values[ValueIndex] := Values[ValueIndex] + 1; if Values[ValueIndex] = MAX_VALUE then Candidates.Remove(CandidateIndex); Shortage := Shortage - 1; end; finally Candidates.Free; end; Result.a := Values[0]; Result.b := Values[1]; Result.c := Values[2]; Result.d := Values[3]; end; function GetSampleLama: TValue; type TRandomValues = array[1..4] of Integer; var IntSum: Integer; Values: TRandomValues; begin // initialize a helper variable for calculating sum of the generated numbers IntSum := 0; // in the first step just generate a number in the range of 2 to 7 and store // it to the first integer element Values[1] := RandomRange(2, 7); // and increment the sum value IntSum := IntSum + Values[1]; // as the next step we need to generate number, but here we need also say in // which range by the following rules to ensure we ever reach 22 (consider, if // the 1st number was e.g. 3, then you can't generate the second number smaller // than 5 because then even if the next two numbers would be max, you would get // e.g. only 3 + 4 + 7 + 7 = 21, so just use this rule: // Values[1] Values[2] // 2 6..7 // 3 5..7 // 4 4..7 // 5 3..7 // 6..7 2..7 Values[2] := RandomRange(Max(2, 8 - Values[1]), 7); // and increment the sum value IntSum := IntSum + Values[2]; // if the third step we need to generate a value in the range of 15 to 20 since // the fourth number can be still in the range of 2 to 7 which means that the sum // after this step must be from 22-7 to 22-2 which is 15 to 20, so let's generate // a number which will fit into this sum Values[3] := RandomRange(Max(2, Min(7, 15 - IntSum)), Max(2, Min(7, 20 - IntSum))); // and for the last number let's just take 22 and subtract the sum of all previous // numbers Values[4] := 22 - (IntSum + Values[3]); Result.a := Values[1]; Result.b := Values[2]; Result.c := Values[3]; Result.d := Values[4]; end; function IndexOf(const Value: TValue): Integer; begin for Result := 0 to high(Combinations) do if Combinations[Result] = Value then exit; raise EAssertionFailed.Create('Invalid value'); end; procedure CheckCounts(const Name: string; const GetSample: TFunc<TValue>); const N = 1000000; var i: Integer; Counts: TArray<Integer>; Range: Integer; begin SetLength(Counts, Length(Combinations)); for i := 1 to N do inc(Counts[IndexOf(GetSample)]); Range := MaxIntValue(Counts) - MinIntValue(Counts); Writeln(Name); Writeln(StringOfChar('-', Length(Name))); Writeln(Format('Range = %d, N = %d', [Range, N])); Writeln; end; begin Randomize; InitialiseCombinations; CheckCounts('Heffernan', GetSampleHeffernan); //CheckCounts('Van Dien', GetSampleVanDien); CheckCounts('Lama', GetSampleLama); Readln; end. The output, from one particular run, is: Heffernan --------- Range = 620, N = 1000000 Lama ---- Range = 200192, N = 1000000 The Van Dien variant is commented out at the moment since it produces invalid values. OK, I debugged and fixed the Van Dien variant. The test and results now look like this: {$APPTYPE CONSOLE} uses System.SysUtils, System.Math, Generics.Collections; type TValue = record a, b, c, d: Integer; procedure Write; class operator Equal(const lhs, rhs: TValue): Boolean; end; procedure TValue.Write; begin Writeln(a, ' ', b, ' ', c, ' ', d); end; class operator TValue.Equal(const lhs, rhs: TValue): Boolean; begin Result := (lhs.a=rhs.a) and (lhs.b=rhs.b) and (lhs.c=rhs.c) and (lhs.d=rhs.d); end; var Combinations: TArray<TValue>; procedure InitialiseCombinations; var a, b, c, d: Integer; Value: TValue; List: TList<TValue>; begin List := TList<TValue>.Create; try for a := 2 to 7 do for b := 2 to 7 do for c := 2 to 7 do begin d := 22 - a - b - c; if InRange(d, 2, 7) then begin Value.a := a; Value.b := b; Value.c := c; Value.d := d; List.Add(Value); end; end; Combinations := List.ToArray; finally List.Free; end; end; function GetSampleHeffernan: TValue; begin Result := Combinations[Random(Length(Combinations))]; end; function GetSampleVanDien: TValue; const TOTAL = 22; VALUE_COUNT = 4; MIN_VALUE = 2; MAX_VALUE = 7; var Values: array[0..VALUE_COUNT-1] of Integer; Shortage: Integer; Candidates: TList<Integer>; ValueIndex: Integer; CandidateIndex: Integer; begin Assert(VALUE_COUNT * MAX_VALUE >= TOTAL, 'Total can never be reached!'); Assert(VALUE_COUNT * MIN_VALUE <= TOTAL, 'Total is always exceeded!'); Candidates := TList<Integer>.Create; try for ValueIndex := 0 to VALUE_COUNT-1 do begin Values[ValueIndex] := MIN_VALUE; Candidates.Add(ValueIndex); end; Shortage := TOTAL - VALUE_COUNT * MIN_VALUE; while Shortage > 0 do begin CandidateIndex := Random(Candidates.Count); ValueIndex := Candidates[CandidateIndex]; inc(Values[ValueIndex]); if Values[ValueIndex] = MAX_VALUE then Candidates.Delete(CandidateIndex); dec(Shortage); end; finally Candidates.Free; end; Result.a := Values[0]; Result.b := Values[1]; Result.c := Values[2]; Result.d := Values[3]; end; function GetSampleLama: TValue; type TRandomValues = array[1..4] of Integer; var IntSum: Integer; Values: TRandomValues; begin // initialize a helper variable for calculating sum of the generated numbers IntSum := 0; // in the first step just generate a number in the range of 2 to 7 and store // it to the first integer element Values[1] := RandomRange(2, 7); // and increment the sum value IntSum := IntSum + Values[1]; // as the next step we need to generate number, but here we need also say in // which range by the following rules to ensure we ever reach 22 (consider, if // the 1st number was e.g. 3, then you can't generate the second number smaller // than 5 because then even if the next two numbers would be max, you would get // e.g. only 3 + 4 + 7 + 7 = 21, so just use this rule: // Values[1] Values[2] // 2 6..7 // 3 5..7 // 4 4..7 // 5 3..7 // 6..7 2..7 Values[2] := RandomRange(Max(2, 8 - Values[1]), 7); // and increment the sum value IntSum := IntSum + Values[2]; // if the third step we need to generate a value in the range of 15 to 20 since // the fourth number can be still in the range of 2 to 7 which means that the sum // after this step must be from 22-7 to 22-2 which is 15 to 20, so let's generate // a number which will fit into this sum Values[3] := RandomRange(Max(2, Min(7, 15 - IntSum)), Max(2, Min(7, 20 - IntSum))); // and for the last number let's just take 22 and subtract the sum of all previous // numbers Values[4] := 22 - (IntSum + Values[3]); Result.a := Values[1]; Result.b := Values[2]; Result.c := Values[3]; Result.d := Values[4]; end; function IndexOf(const Value: TValue): Integer; begin for Result := 0 to high(Combinations) do if Combinations[Result] = Value then exit; raise EAssertionFailed.Create('Invalid value'); end; procedure CheckCounts(const Name: string; const GetSample: TFunc<TValue>); const N = 1000000; var i: Integer; Counts: TArray<Integer>; Range: Integer; begin SetLength(Counts, Length(Combinations)); for i := 1 to N do inc(Counts[IndexOf(GetSample)]); Range := MaxIntValue(Counts) - MinIntValue(Counts); Writeln(Name); Writeln(StringOfChar('-', Length(Name))); Writeln(Format('Range = %d, N = %d', [Range, N])); Writeln; end; begin Randomize; InitialiseCombinations; CheckCounts('Heffernan', GetSampleHeffernan); CheckCounts('Van Dien', GetSampleVanDien); CheckCounts('Lama', GetSampleLama); Readln; end. Heffernan --------- Range = 599, N = 1000000 Van Dien -------- Range = 19443, N = 1000000 Lama ---- Range = 199739, N = 1000000 And just to ram it home, here are some plots of empirical probability mass function of the various distributions: OK, now I fixed @TLama's code. It was using RandomRange incorrectly. The documentation states: RandomRange returns a random integer from the range that extends between AFrom and ATo (non-inclusive). The key is that the range is defined as a closed-open interval. The value returned is in the range [AFrom..ATo), or expressed with inequality signs, AFrom <= Value < ATo. But @TLama's code is written on the assumption that the interval is closed at both ends. So the code can readily be fixed by adding 1 to the second parameter of each call to RandomRange. When we do that the output looks like this: Heffernan --------- Range = 587, N = 1000000 Van Dien -------- Range = 19425, N = 1000000 Lama ---- Range = 79320, N = 1000000 And the empircal PMF plot becomes: The bottom line in all this is that sampling is difficult to get right if you care about the distribution.
[ "math.stackexchange", "0000134340.txt" ]
Q: Lebesgue decomposition theorem and fundamental theorem of calculus On page 42 of 'Evans-Gariepy, Measure theory and fine properties of functions' it's stated and proved this theorem: let $\mu$ and $\nu$ be Radon measures on $\mathbb{R}^n$. Then $\nu=\nu_{ac}+\nu_s$ where the first is absolutely continuous respect to $\mu$ and the second is singular respect $\mu$. Furthermore the derivative $D_{\mu}\nu=D_{\mu}\nu_{ac}$ and $D_{\mu}\nu_s=0 \; \mu-a.e$. Up to this everything is ok and proved, but then is stated a consequence not proved (because it seems obvious) but I don't understand: $\nu(A)=\int_{A}D_{\mu}\nu_{ac} d\mu+\nu_s(A)$. Why is there the term $\nu_s(A)$? I thought this: $\nu(A)=\int_{A}D_{\mu}\nu_{} d\mu =\int_{A}D_{\mu}\nu_{ac} d\mu+\int_{A}D_{\mu}\nu_{s}d\mu=\int_{A}D_{\mu}\nu_{ac} d\mu$ A: Think about $\nu_{ac}$ the Lebesgue measure and $\nu_s$ the counting measure. For the computation $\int_{A} d nu = \int_A d \nu_s + \int_A d \nu_s = \int_A D_\mu \nu_{ac} d \mu + \nu_s(A)$, but In general $$ \int_A d \nu_s \neq \int_A D_\mu \nu_{s} d \mu = 0.$$
[ "stackoverflow", "0027610965.txt" ]
Q: Trying to hide div class on screen size I'm trying to get an element to hide at 460px and below. I'm trying to hide the phone number & email at the very top in the header. [email protected] (909) 278-2644 I'm having trouble. Thank you for helping. http://www.superherodigital.com/locksmithsupplier/ I have this code in place but it is not working media="all" @media (max-width: 460px) #hide-none { display: none; } A: You need to have correct syntax and information. Use this and also when you are looking on mobile you need to make sure your meta tags are correct. @media (max-width: 460px){ #hide-none { display: none; } } Your view port is important for mobile devices. <meta name="viewport" content="width=device-width,initial-scale=1.0">
[ "stackoverflow", "0049279384.txt" ]
Q: Passing Relative Paths to Powershell shell.application Namespace I'm attempting to get the function from this page: https://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/ working using relative parameters. So I have this function: function Expand-ZIPFile($file, $destination) { Write-Host "Unzipping $file to $destination" -ForegroundColor Yellow $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($item in $zip.items()) { $shell.Namespace($destination).copyhere($item) } } And I attempt to call it like so: $zipPath = Resolve-Path ".\myZip.zip" $destinationPath = Resolve-Path ".\" Expand-ZIPFile -File $zipPath -Destination $destinationPath Output wise I see: Unzipping D:\test\myZip.zip to D:\test You cannot call a method on a null-valued expression. At D:\test\Unzip.ps1:14 char:22 + foreach($item in $zip.items()) + ~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull Which I'm assuming is because the namespace isn't being interpretted correctly because if I call: Expand-ZIPFile -File "D:\test\myZip.zip" -Destination "D:\test" This works fine, and I see: Unzipping D:\test\myZip.zip to D:\test in the console as well. How can I pass in the 'resolved' strings, as I can't see what's missing here. I have also tried wrapping the resolved strings in " to see if that made a difference ($zipPath = '"' + $zipPath + '"') but to no avail. A: I think your issue is coming from Resolve-Path. It is returning an object with a path property as supposed to a straight string. I would have thought that the console output for your write-host line would look weird as an indicator but it looks like it has a nice ToString() overload. You need to expand that property out. $zipPath = (Resolve-Path ".\myZip.zip").Path $destinationPath = (Resolve-Path ".\").Path Expand-ZIPFile -File $zipPath -Destination $destinationPath You can see the need for this when you output Resolve-Path to standard out. resolve-path .\sql.txt Path ---- C:\Users\myusername\sql.txt
[ "es.stackoverflow", "0000280424.txt" ]
Q: Consulta SQLITE Android Studio tengo una base de dato en sqlite en android studio, y al registrar un codigo "1", me guarda el codigo y la descripcion, pero al ingresar otro codigo "1" me dice que guarda los datos (pero no reescribe el codigo "1" solo dice que guardo) entonces necesito saber como puede mandar un TOAST que diga que ese codigo ya esta utilizado, aqui les dejo la clase de registrar. public void Registrar(View view){ AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1); SQLiteDatabase BaseDeDatos = admin.getWritableDatabase(); String codigo = et_codigo.getText().toString(); String descripcion = et_descripcion.getText().toString(); String cantidad = et_cantidad.getText().toString(); if(!codigo.isEmpty() && !descripcion.isEmpty() && !cantidad.isEmpty()){ ContentValues registro = new ContentValues(); registro.put("codigo", codigo); registro.put("descripcion", descripcion); registro.put("cantidad", cantidad); BaseDeDatos.insert("articulos", null, registro); BaseDeDatos.close(); et_codigo.setText(""); et_descripcion.setText(""); et_cantidad.setText(""); Toast.makeText(this,"Registro exitoso", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(this, "Debes llenar todos los campos", Toast.LENGTH_SHORT).show(); } } espero su ayuda! muchas gracias! A: Para comenzar no es una clase sino un método(de alguna clase),si he logrado entender lo que quieres es que necesitas saber si el numero: 1, ya existe en "articulos" tabla de la base de datos, entonces simplemente tienes que hacer un recorrido de la tabla para verificar y de tal modo poder mostrar en un Toast si ese dato ya existe o no. Llamamos a la funcion: verificarCodigo que nos devolvera un booleano true si existe y false si no existe. seria algo asi: public void Registrar(View view){ AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1); SQLiteDatabase BaseDeDatos = admin.getWritableDatabase(); String codigo = et_codigo.getText().toString(); String descripcion = et_descripcion.getText().toString(); String cantidad = et_cantidad.getText().toString(); if(!codigo.isEmpty() && !descripcion.isEmpty() && !cantidad.isEmpty()){ if(verificarCodigo(codigo)){ Toast.makeText(this,"el codigo: "+codigo +" Ya existe", Toast.LENGTH_SHORT).show(); }else{ ContentValues registro = new ContentValues(); registro.put("codigo", codigo); registro.put("descripcion", descripcion); registro.put("cantidad", cantidad); BaseDeDatos.insert("articulos", null, registro); BaseDeDatos.close(); et_codigo.setText(""); et_descripcion.setText(""); et_cantidad.setText(""); Toast.makeText(this,"Registro exitoso", Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(this, "Debes llenar todos los campos", Toast.LENGTH_SHORT).show(); } } public boolean verificarCodigo(String codigo){ AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1); SQLiteDatabase BaseDeDatoslectura = admin.getReadableDatabase();// leemos datos con: getReadableDatabase() Cursor c; boolean b=false; c= BaseDeDatoslectura.rawQuery("SELECT codigo FROM articulos",null); //hacemos el recorrido y preguntamos si existe un "1" en el campo codigo if (c.moveToFirst()){ do{ String buscar_codigo= c.getString(0); if(codigo.equal(buscar_codigo)){ b=true; } }while (c.moveToNext() && b==false); } return b; } Espero que sea lo que estés buscando.
[ "stackoverflow", "0009600016.txt" ]
Q: Filter order collection using custom field: Magento I added a custom field(sales_code) in order table(sales_flat_order) manually. Now I want to filter the order collection (in admin order gird page) using that custom field. But magento throws an error. My Code: $collection->addFieldToFilter('sales_code', '123456'); $collection->getSelect()->where('sales_code="123456"'); Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_code' in 'where clause' Is there any way to filter the collection using custom field in magento. A: To solve this problem I use the sales_flat_order_grid table instead of table sales_flat_order.
[ "stackoverflow", "0025849813.txt" ]
Q: How to set the path to a browser executable with python webbrowser I am trying to build a utility function to output beautiful soup code to a browser I have the following code: def bs4_to_browser(bs4Tag): import os import webbrowser html= str(bs4Tag) # html = '<html> ... generated html string ...</html>' path = os.path.abspath('temp.html') url = 'file://' + path with open(path, 'w') as f: f.write(html) webbrowser.open(url) return This works great and opens up the HTML in the default browser. However I would like to set the path to a portable firefox executable which is at: F:\FirefoxPortable\firefox.exe I am using win7. How to I set the path to the portable firefox executable? A: You could start your portable Firefox directly with the url as an argument instead. from subprocess import call call(["F:\\FirefoxPortable\\firefox.exe", "-new-tab", url])
[ "stackoverflow", "0014579051.txt" ]
Q: How to Create ASPX Pages in MVC 4 I used to develop with ColdFusion for a while, but then left the web development arena for a while. I'm back, now, and have been hired as an intermediate (right above entry)-level web developer. My workplace is using MVC 4, but is not using the Razor view engine. The two MVC 4 books that I've purchased (as well as the huge number of tutorials and blogs out there) only discuss using Razor- which I AM using in my self-study, but I need to understand how it works when NOT using the Razor engine. When using the ASPX view engine, how do you go about using it? Does it work like a normal ASPX page, where I place my ASP.NET controls on the page and then reference them with the code-behind in C#? Only, rather than using ASP.NET controls, I'm using HtmlHelper methods instead? Keep in mind, I'm not asking about the basic format of using <% %> instead of <@, because most of that was covered here: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx. I fail to understand how traffic will get routed to those ASPX pages through my basic HomeController (which just has a few ActionResult() methods, nothing large). I can elaborate more, if need be. A: All MVC view pages follow the same life cycle regardless of the view engine: Routing - The request is mapped to an action method (using request data like URL, querystring, session, etc) Controller - A controller is created for the matching action method. It's populated with all the environment, request, and session data Action - The matching action method is called Result - The ActionResult returned by the action method is executed. For a view result, this means: 1) The view engine locates a matching view name, 2) the matching view is instantiated with any model data returned by the action method, 3) the view is processed by the view engine. That means a WebForms view will be executed by the MVC WebForms view engine, not by the ASP.NET WebForms system. The view engine will perform some basic parsing to add the data from your model to your view (as specified with <%%>). Also, FYI you can even mix view engines in a single project (requires some setup).
[ "stackoverflow", "0019961884.txt" ]
Q: Android can only be built with make version 3.81 So if Android can be compiled with make v3.81 I installed it as /usr/bin/make-3.81 But make 4.0 is in my path as well under /usr/bin/make My question is if I execute $ make-3.81 clean && make-3.81 -j8 Is it safe and build like that, or will it try to call "make" from my PATH somewhere during build and run ito make v4.0? So in other words, should I make sure only "make" version 3.81 is in my PATH when building Android? A: As long as the makefiles are properly written and always uses the variable $(MAKE) anywhere they want to invoke make recursively, it will work fine. If someone has written poor makefiles and used the explicit command make, then it will break.
[ "mathoverflow", "0000146305.txt" ]
Q: a question about geometric quantization background I don't understand why for geometric description of a regular system, we take always the classical phase space as a symplectic manifold? A: What is the classical phase space (by phase space I'll, atleast in this post, mean classical phase space)? It is simply the cotangent bundle $\mathrm{T}^{*}(\mathscr{C})$ of the configuration space $\mathscr{C}$. "... in a lecture Thurston mentioned "Any manifold can be seen as the configuration space of some physical system." (cf. MO/16460)". It can be seen as the cotangent bundle because of the Poisson bracket - see the answer to the above linked question. Any cotangent bundle of a finite-dimensional smooth manifold (the configuration space, $\mathscr{C}$, is finite-dimensional and smooth) is a symplectic manifold. For a proof, see this essay, page $7$. Hence, the classical phase space $\mathrm{T}^{*}(\mathscr{C})$ is always a symplectic manifold.
[ "stackoverflow", "0035176542.txt" ]
Q: How can I resolve on state change into a controller on nested views I'm trying to perform a resolve on state change to get data I want to inject in a controller which uses "multiple" views. The reason for having nested views is because the template/app.html contains a <ion-side-menu>, and I want to resolve data inside the <side-menu-content>. CODE module configuration: $stateProvider.state('app', { url: '/app', abstract: true, templateUrl: 'template/app.html' }) .state('app.list', { url: '/list', views: { 'maincontainer@app': { controller: 'listctrl', templateUrl: 'template/list.html', resolve: { item: function(dataservice) { return dataservice.getItems(); } } } }, resolve: { auth: auth } }); controller: angular.module('controller', []).controller('listctrl', ['$scope', function($scope, items){ console.log(items); // prints undefined }]); PROBLEM The problem is that the resolved items is never injected into the controller, though the item function is resolved. I've been thinking about maybe having to store the data in local storage when resolved, and getting the items back again from the controller. I'd prefer if I didn't have to go that route (pun intended). A: You have to actually inject the items. angular.module('controller', []).controller('listctrl', ['$scope', "items", function($scope, items){ console.log(items); // prints undefined }]);
[ "ru.stackoverflow", "0000186655.txt" ]
Q: Ограничение движения мыши окном программы Как в Delphi 7 сделать, чтобы мышка не выходила за рамки нашей новой программы? A: Можно, есть такая функция ClipCursor. В делфи она тоже есть (вроде в файле windows.pas). Параметр - TRect - прямоугольник, в котором нужно держать курсор. Эту функцию настоятельно не рекомендуется использовать. Также не забывайте обновлять область по мере надобности и освобождать ее, когда программа завершится
[ "stackoverflow", "0050055092.txt" ]
Q: Swift Decodable issue - Trouble assigning value to an array I'm having trouble troubleshooting this error at self.tvShows = shows.data I get the error Cannot assign value of type 'RecentTvListDays' to type '[TvShowDetails]?' I've attached the JSON structure as an image at the bottom. Hope this is enough. class TvHomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { fileprivate let cellId = "cellId" var tvShows: [TvShowDetails]? = [] func fetchTvItems() { let jsonUrlString = "https://www.what-song.com/api/air-episodes" guard let url = URL(string: jsonUrlString) else {return} URLSession.shared.dataTask(with: url) { (data, response, err) in guard let data = data else {return} do { let shows = try JSONDecoder().decode(RecentTvListData.self, from: data) self.tvShows = shows.data DispatchQueue.main.async { self.collectionView?.reloadData() } } catch let jsonErr { print("Error serializing JSON", jsonErr) } }.resume() } } Model import UIKit struct RecentTvListData: Decodable { var data: RecentTvListDays } struct RecentTvListDays: Decodable { var RecentTvListByDay: [TvShowDetails] } struct TvShowDetails: Decodable { var _id: Int var name: String } A: It seems you're almost there, actually. I believe you simply need to change one line: self.tvShows = shows.data.RecentTvListByDay Like I mention in the comments, you're simply trying to set to a different type (like the error says, really). Side-note/tip: always start your variable- and property-names with lowercase. (Conforms to conventions and improves readability).
[ "stackoverflow", "0055218154.txt" ]
Q: Implementation of Isotropic squared exponential kernel with numpy I've come across a from scratch implementation for gaussian processes: http://krasserm.github.io/2018/03/19/gaussian-processes/ There, the isotropic squared exponential kernel is implemented in numpy. It looks like: The implementation is: def kernel(X1, X2, l=1.0, sigma_f=1.0): sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T) return sigma_f**2 * np.exp(-0.5 / l**2 * sqdist) consistent with the implementation of Nando de Freitas: https://www.cs.ubc.ca/~nando/540-2013/lectures/gp.py However, I am not quite sure how this implementation matches the provided formula, especially in the sqdist part. In my opinion, it is wrong but it works (and delivers the same results as scipy's cdist with squared euclidean distance). Why do I think it is wrong? If you multiply out the multiplication of the two matrices, you get which equals to either a scalar or a nxn matrix for a vector x_i, depending on whether you define x_i to be a column vector or not. The implementation however gives back a nx1 vector with the squared values. I hope that anyone can shed light on this. A: I found out: The implementation is correct. I just was not aware of the fuzzy notation (in my opinion) which is sometimes used in ML contexts. What is to be achieved is a distance matrix and each row vectors of matrix A are to be compared with the row vectors of matrix B to infer the covariance matrix, not (as I somehow guessed) the direct distance between two matrices/vectors.
[ "math.stackexchange", "0003769136.txt" ]
Q: Distribution of the ratio of two Normal variables Considering a sample of size $n$ from a $N(\mu,\sigma^2)$ distribution: $X_1, \ldots , X_n$, I need to find the ratio of \begin{equation} R = \frac{\tilde{\mu} - \mu}{\hat{\mu} -\mu}, \end{equation} where $\tilde{\mu} = X_1 $ one observation, and $\hat{\mu} = \bar{X}$, the sample mean. I know that $ \frac{\tilde{\mu} - \mu}{\sigma} \sim N(0,1)$, $ \frac{\sqrt{n}(\hat{\mu} - \mu)}{\sigma} \sim N(0,1)$, and the ratio of two normally distributed variables is Cauchy - for this to happen do we need for the variables to be independent? Also, there is a $\sqrt{n}$ coming in the picture when simplifying the ratio that I am not sure how to handle. A: For real $\alpha$ and $\beta>0$, suppose $\text{Cauchy}(\alpha,\beta)$ denotes the density $f(x)=\frac{\beta}{\pi((x-\alpha)^2+\beta^2)}\,,x\in \mathbb R$. It can be shown using a change of variables or otherwise that if $(X,Y)$ has a standard bivariate normal distribution with zero means, unit variances and correlation $\rho$, then $\frac{X}{Y}$ has a $\text{Cauchy}(\rho,\sqrt{1-\rho^2})$ distribution. Wikipedia states a more general result which agrees with this. It is clear that the distribution of $R$ is free of $\mu,\sigma$ because $$R=\frac{X_1-\mu}{\overline X-\mu}=\frac{(X_1-\mu)/\sigma}{(\overline X-\mu)/\sigma}=\frac{Y_1}{\overline Y}\,,$$ where $Y_i=(X_i-\mu)/\sigma$ are i.i.d standard normal for all $i=1,\ldots,n$. We can rewrite this as $$R=\sqrt n\left(\frac{Y_1}{\sqrt n \overline Y}\right)$$ Notice that \begin{align} \operatorname{Cov}(Y_1,\sqrt n\overline Y)&=\operatorname{Cov}\left(Y_1,\frac1{\sqrt n}\sum_{i=1}^n Y_i\right)& \\&=\frac1{\sqrt n}\sum_{i=1}^n\operatorname{Cov}(Y_1,Y_i) \\&=\frac1{\sqrt n}\operatorname{Var}(Y_1)=\frac1{\sqrt n} \end{align} Now as $\overline Y$ is a linear combination of independent normal variables, $(Y_1,\sqrt n\overline Y)$ is bivariate normal with zero means, unit variances and correlation $\frac1{\sqrt n}$. The ratio $\frac{Y_1}{\sqrt n \overline Y}$ therefore has a $\text{Cauchy}\left(\frac1{\sqrt n},\sqrt{\frac{n-1}n}\right)$ distribution, from which it follows that $$R\sim \text{Cauchy}(1,\sqrt{n-1})$$
[ "stackoverflow", "0000690176.txt" ]
Q: C/C++: Optimization of pointers to string constants Have a look at this code: #include <iostream> using namespace std; int main() { const char* str0 = "Watchmen"; const char* str1 = "Watchmen"; char* str2 = "Watchmen"; char* str3 = "Watchmen"; cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl; cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl; cerr << static_cast<void*>( str2 ) << endl; cerr << static_cast<void*>( str3 ) << endl; return 0; } Which produces an output like this: 0x443000 0x443000 0x443000 0x443000 This was on the g++ compiler running under Cygwin. The pointers all point to the same location even with no optimization turned on (-O0). Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on? A: It can't be relied on, it is an optimization which is not a part of any standard. I'd changed corresponding lines of your code to: const char* str0 = "Watchmen"; const char* str1 = "atchmen"; char* str2 = "tchmen"; char* str3 = "chmen"; The output for the -O0 optimization level is: 0x8048830 0x8048839 0x8048841 0x8048848 But for the -O1 it's: 0x80487c0 0x80487c1 0x80487c2 0x80487c3 As you can see GCC (v4.1.2) reused first string in all subsequent substrings. It's compiler choice how to arrange string constants in memory. A: It's an extremely easy optimization, probably so much so that most compiler writers don't even consider it much of an optimization at all. Setting the optimization flag to the lowest level doesn't mean "Be completely naive," after all. Compilers will vary in how aggressive they are at merging duplicate string literals. They might limit themselves to a single subroutine — put those four declarations in different functions instead of a single function, and you might see different results. Others might do an entire compilation unit. Others might rely on the linker to do further merging among multiple compilation units. You can't rely on this behavior, unless your particular compiler's documentation says you can. The language itself makes no demands in this regard. I'd be wary about relying on it in my own code, even if portability weren't a concern, because behavior is liable to change even between different versions of a single vendor's compiler. A: You surely should not rely on that behavior, but most compilers will do this. Any literal value ("Hello", 42, etc.) will be stored once, and any pointers to it will naturally resolve to that single reference. If you find that you need to rely on that, then be safe and recode as follows: char *watchmen = "Watchmen"; char *foo = watchmen; char *bar = watchmen;
[ "crypto.stackexchange", "0000061524.txt" ]
Q: Practical perfect security in bitwise XOR vs integer addition/subtraction cipher XOR already provides perfect security in theory but it's hard to apply it in practice due to strict requirements. I was thinking about whether simple addition/subtraction in integer format would not be more practical to use while also providing perfect secrecy. Ex: "9" will be the plaintext and "1" will be the secret key. In ASCII/UTF-8 they both occupy 1 byte of space, so qualified to xor-ing, so that is 8 bits. 9 = 00111001 1 = 00110001 First we would XOR like normally one would do, so: Encipher: 00111001 ⊕ 00110001 = 00001000 (obviously the output will be junk ciphertext, in this case the "Back Space" key in ASCII) Decipher: 00001000 ⊕ 00110001 = 00111001 Or we would use addition for encipher and subtraction for decipher in integer format: Encipher: 9 + 1 = 10 Decipher: 10 - 1 = 9 As you can see it's just as forwardly secure as XOR-ing, the 10 doesn't reveal anything about the 9, since the key and the plaintext can be both a gigantic positive and negative number who's sum is just happens to be 10, so it provides perfect secrecy. It's also easier to use, you don't have to convert to binary. But it has 1 special attribute that I think it makes it superior to XOR. Look at the binary value of 10, it's 0011000100110000, it's 2 bytes long. So using addition/subtraction instead of XOR also hides and obfuscates the length of the plaintext, doesn't it? Because if we use integers, we are not using a bitwise operation anymore. Instead the key can be any length, nobody can determine whether we have 9+1=10 or 1000000000+(-999999990)=10 or any other infinite number of combinations. It totally obfuscates the size of the data, there is no correlation between plaintext size and ciphertext size. And since it's not bitwise operation anymore, it doesn't have the "leakage" problem that XOR has, the key length can be any size, and it doesn't even have to be true random (I think, correct me if I am wrong), any pseudo-random and sufficiently complex integer can do it. So I think this makes it superior to XOR and other bitwise operators. Why isn't integer addition used in encryption algorithms? What do you think about this encryption method? Is it better and more practical than XOR? A: I started to write a long answer, but there are quite a few misunderstandings in the question, so I think a list is better suited: Encoding is different from encryption. If you encode something you will be left with as many possible values as when using binary. It doesn't matter if you encode ten as 00001010 or 00110001 00110000; Junk ciphertext: modern ciphertext is binary and - for a symmetric cipher - consists of random looking values. When you try to view it in any format it will look like "junk" but that's just because you're trying to give meaning to the random bits. Generally we want to be able to encrypt any data, regardless if it is text, an image etc. So binary data is the default input format for modern ciphers that run on computers. The problem with addition is that you would have to convert to numbers; computers however work on binary values. Even addition and multiplications are on machine words and are therefore modulo $2^{32}$ or $2^{64}$. It just takes you some work to get used to this. You have to use modular addition (or subtraction) to make addition secure. Otherwise the ciphertext values will be spread like a bell curve, which leaks information about the plaintext, especially when you look at the outer values such as zero or the maximum value within the ciphertext. This is similar to throwing two dice, where 2 and 12 is much less frequent than 7; if you throw 2 then both dice must have value 1. With modular addition the chance of a smaller number in the ciphertext is the same as with XOR when viewed in binary. With addition we humans automatically remove the zero digits from the left. You can do the same thing with the zero's after XOR. The only difference is if the input / output is treated as a number or not - but that's a choice you can make for both situations. Similarly, you can also left-pad small values with zero or one bits before XOR'ing them. That way you can encrypt with a larger key and XOR just like you do with a large number and modular addition. For a true one-time-pad - which is the name of the algorithm that you're trying to accomplish with XOR or modular addition - any value in the key stream needs to be fully random. If it isn't then you're dealing with a stream cipher. Stream ciphers can be computationally secure, but they are generally not perfectly secure. In general we try to keep the ciphertext as compact as possible. If you want to avoid leaking information about the plaintext size then you can first pad the message to a constant size. In that case you will only leak the information that the message is smaller than that size if you use a one-time-pad. So no, addition is not better than XOR. The advantages you list can be accomplished for XOR as well. Binary plaintext and ciphertext is a feature, not a drawback. A: Firstly, if you want the length of the plain text to be obfuscated, apply padding prior to encrypting the plain text. Secondly, while it is indeed possible to use other binary operations than XOR in an OTP scheme, to use addition over the natural numbers (as opposed to modular addition in a residue group) would also leak information. The Perfect Secrecy of a proper OTP, means that any given cipher text reveals no information about the plain text, save for the length. This is because, for any given cipher text and (optionally padded) plain text pair of the same length, there is always a key that would encrypt the plain text into the cipher text. With your scheme, the cipher text 0 would only be matched by the pair of the plain text 0 and key 0. The cipher text 1 would only be matched by either plain text 0 and key 1, or plain text 1 and key 0, etc. In a Cipher Text Only attack, the attacker would always know that the plain text has to be less than or equal to the cipher text, which reveals a non trivial amount of information.
[ "space.stackexchange", "0000042010.txt" ]
Q: Going to Eros; what to consider choosing between ion and chemical propulsion? When planning a mission to a close approach to the asteroid Eros and to remain nearby, what are the factors that one would need to consider when choosing between ion propulsion and chemical propulsion? A: This is going to depend very much on mission intent and time frame. If mission duration is in years and overall mass is small electric propulsion may work, and do so for lower overall mass. Especially if the mission on arrival requires large amounts of power so large solar cells are not wasted mass. If aim is to get there quickly and with a large payload (eg people) generally things tend to move towards conventional thermal rockets. This is especially the case with Eros if launch time can be carefully chosen such that bulk of DV happens deep in LEO when Eros is passing relatively close to earth, allowing cryogenic propellants and maximum benefit from the Oberth effect. For reference this handy table suggests Eros takes approximately the same amount of DV to reach as Moon or Mars, so rocket size/costs can be estimated by looking at those missions. Noting pre edit questions about mining, returning from Eros will involve similar amounts of DV, either from a rocket or rocket+heatshield for aerobreaking and need to either be mined in situ or lifted up from earth. This would make costs broadly comparable to the moon.
[ "stackoverflow", "0037382260.txt" ]
Q: Named key/value pairs in a Swift dictionaries Is there a way to have named key/value pairs in a Swift dictionaries? I'd rather use a name instead of an index number to refer to either the key or the value. Unfortunately, key/value pairs by name in Dictionary in Swift only discusses referring to the keys and values in a for-loop. I'd like to give the keys and values a name when I declare them in the typealias so they can always be referred to by their names. Please see the comment in the below code snippet to show what I mean: typealias CalendarRules = [EKCalendar : [String]] let calendarRules = buildCalendarRules() // builds the array. let firstCalendarRule = calendarRules.first print(firstCalendarRule.0) // I'd like to write: print(firstCalendarRule.cal) print(firstCalendarRule.1) // I'd like to write: print(firstCalendarRule.theString) A: This has nothing to do with dictionaries, except very indirectly; and your CalendarRules type alias is irrelevant. Your firstCalendarRule is not a dictionary; it is a tuple. You are free to name the members of a tuple: typealias Rule = (cal:String, string:String) let d = ["I am a calendar":"I am a string"] let firstRule : Rule = d.first! print(firstRule.cal) // I am a calendar
[ "stackoverflow", "0050980617.txt" ]
Q: Angular 5 event emitter triggered twice I am using angular 5. In which I am passing data from one component to another component using eventemitter. At first click event emitter is not subscribe the value in child component. On second click event emitter triggered twice. Header component.ts this.testservice.sendsearchdata.next( this.searchdataform.value) Search component.ts this.testservice.sendsearchdata.subscribe(value=>{ console.log( value) }) testservice.ts public testservice: EventEmitter<any> = new EventEmitter (): While passing reactive form data from header component to search component it's not triggered at first click. On next click it has triggered twice. A: I think you are incorrectly using EventEmitter. It's used when child component emitting events to parent component via @Output() property. In your case, component communication realized by using service. Try this way: @Injectable() export class MissionService { // Observable string sources private missionAnnouncedSource = new Subject<string>(); private missionConfirmedSource = new Subject<string>(); // Observable string streams missionAnnounced$ = this.missionAnnouncedSource.asObservable(); missionConfirmed$ = this.missionConfirmedSource.asObservable(); // Service message commands announceMission(mission: string) { this.missionAnnouncedSource.next(mission); } confirmMission(astronaut: string) { this.missionConfirmedSource.next(astronaut); } } Parent and children communicate via a service
[ "stackoverflow", "0033548123.txt" ]
Q: Latest jquery datepicker, change default date I know this question has been asked a lot, but I could find a solution that works for the latest version which by default shows current date on open. Any ideas how to change this to some static date (2011.09.21) ? I wrote this as a seperate script: <script> function(){ $(".single-product .i2").datepicker({ defaultDate: '2011/09/09' }); }; </script> But it still loads default date. A: Use the defaultDate parameter: $("#datepicker").datepicker({ defaultDate: '09/21/2011' }); jsFiddle example
[ "stackoverflow", "0014067877.txt" ]
Q: URL syntax for connecting with server from the client side I went around the Internet for this question and I just can't figure it out. I am developing a Java Application on Netbeans and I'm connecting to the H2 Database Engine through Netbeans IDE. I am not interested in using the console. The code to connect to H2 is as follows (from the client side): Connection connt = null; String url = "jdbc:h2:tcp://" + SERVER_IP + ":" + SERVER_PORT + "//C:/Databases/businessApp;"; connt = DriverManager.getConnection(url, "sa", ""); When the code reaches the .getConnection() method, it stays there and does nothing. I am almost sure that there is something wrong with the URL syntax. SERVER_IP and SERVER_PORT are defined earlier and are not null. A: I think the culpript is your final connection string which looks like "jdbc:h2:tcp://192.168.1.154:8080//C:/Databases/businessApp" and h2 apparently doesn't recognize UNC paths. The above under GNU/Linux instead would work because of the different convention used for paths: "jdbc:h2:tcp://192.168.1.154:8080/home/user/Databases/businessApp" The solution I found is to add a slash after the port number, your string would thus become: "jdbc:h2:tcp://192.168.1.154:8080/C:/Databases/businessApp" this works both in Linux and Windows
[ "stackoverflow", "0015137384.txt" ]
Q: Stop installation based on criteria I am trying to check if a computer has the VC++ redistributable installed and the best way I have found to check for it is by running the following code: bool CheckForVCRedist() { bool install = false; if (!install) install = 5 == MsiQueryProductState("{196BB40D-1578-3D01-B289-BEFC77A11A1E}"); if (!install) install = 5 == MsiQueryProductState("{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}"); if (!install) install = 5 == MsiQueryProductState("{C1A35166-4301-38E9-BA67-02823AD72A1B}"); if (!install) install = 5 == MsiQueryProductState("{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}"); if (!install) install = 5 == MsiQueryProductState("{1D8E6291-B0D5-35EC-8441-6616F567A0F7}"); if (!install) install = 5 == MsiQueryProductState("{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}"); return install; } [DllImport("msi.dll")] private static extern int MsiQueryProductState(string product); If any of the following are true, then my program will run correctly. I am trying to arrange it so that the installer stops based on the presence of the VC++ Redistributable. In the program installer cs file there is the following code: protected override void OnBeforeInstall(IDictionary savedState) { if (CheckForVCRedist()) { base.OnBeforeInstall(savedState); } else { throw new Exception("You are missing the VC ++ 2010 Redistributable. Please follow the link to get it:\nhttp://www.microsoft.com/en-us/download/details.aspx?id=5555"); } } This doesn't seem to work. Any advice? Edit: I don't have a custom action set up to run this as I thought overriding the method was the correct way to go... I now feel like that is wrong. Edit[2013-02-28 10:36]: The error is not being thrown in the installer, is there a better way to stop the installer form installing? A: You should create a CustomAction and then override Install. Then you can make the setup cancel by throwing InstallException public override void Install(System.Collections.IDictionary stateSaver) { if (CheckForExceptionalCondition()) throw new InstallException("Some message for user."); base.Install(savedState); } Then it shows a friendly message box during the installation and cancels the setup.
[ "blender.stackexchange", "0000131750.txt" ]
Q: Applied armature doesn't "stick" to mesh while not applied does and I think I need to apply According to a tutorial that shows how to export my NLA to Unity I need to apply all modifiers first. Though, I noticed that if I apply my armature to the mesh then the mesh stops following the armature. I also have a mask modifier on the mesh that maybe makes some fuss. But it doesn't seem to matter if I apply both modifiers in any other order. The mesh still does not follow the armature. I've appended the blend file in comments if someone could take a look. A: Don't apply the armature modifier.
[ "sharepoint.stackexchange", "0000219229.txt" ]
Q: SharePoint O365 Default Content Type Template Loads Automatically I am working with a Form library, that also has a requirement for users to create Word and Excel files. The library has been configured to allow for multiple content types, however, upon clicking +New, the default content type automatically loads. Users can briefly see the list of available content types, but are unable to select one. I have seen this question ask in the past, but no correct answer was ever given. I am hoping that someone has been able to figure this out. Thank you. A: I found a workaround. I really don't care if it's not "elegant": I just need it to work -which it does! How I did it: Ensure the custom content types are enabled in the list If you want to still include the Upload button, right click on it, chose Inspect element, copy the code for the button, then paste it into Notepad for later use Do the same for the +New button Click the FILES tab --> New Document dropdown, and open one of your custom content types custom content types Once the template loads, copy the URL Go back to Notepad, and in the button code, replace "Renderer.FunctionDispatcher.Execute(this,0,"itemClick",event,Renderer.FunctionDispatcher.GetObject(0))" -found in the onclick event- with the URL to the template that you just copied Repeat steps 4-6 for each additional custom content type Insert a CEWP, and hide the +New dropdown with CSS .ms-list-addnew-aligntop.ms-list-addnew {padding-bottom:0;} table#Hero-WPQ2 {display:none;} .ms-csrlistview-controldiv {padding-left:15px;} List item Insert another CEWP directly above the list In the CEWP, copy/paste the code for the button(s) you created in step 6 Copy/paste the code for the Upload button, from step 2
[ "stackoverflow", "0026481477.txt" ]
Q: Regular Expression to extract a number from inside a custom string I'm learning Regular Expressions. I'm trying to find the best way of writing an expression that extracts a number from within the parenthesis that follows the character R" so: Example 1: String("257*5.6+48.9/2*R(64)") reg ex would return the numeric value inside R() in this case 64. Example 2: String("sin(45)*55 + X^2+R(-64.525)") reg ex would return the numeric value inside R() in this case -64.525 My expression so far is: /R\(\-?\d+\.?\d+\)/g which returns R(number) taking into account possible decimal places and negative values. Is there a better regular expression to match(return) only the number from inside the parenthesis that follows the character R? Many thanks in advance for advice / help. D A: If you're using a regex engine other than JavaScript, you can use positive lookaround assertions: /(?<=R\()-?\d+\.?\d*(?=\))/g
[ "writers.stackexchange", "0000016941.txt" ]
Q: Should I use ellipses in narration? I want to indicate a dramatic pause in the narration of my fiction, but the rules I've read say that ellipses are reserved for "" quoted dialog. This would be the example I'm looking at: Normally he could tolerate it by spending his day in the far reaches of the forest or hiding in his office that he’d built in the mountains to the south, but now he had to... talk to people. People he loathed talking to. A: Ellipses are used differently in academic or non-fiction writing and narrative fiction. In academic non-fiction, ellipses indicate that the author has omitted part of the citation. In narrative fiction an ellipsis indicates a pause in spoken language. (I'll come back to that.) Other options for indicating pauses or breaks in spoken language in narrative fiction are the em-dash ("—"), but also colons and full stops. E.g. A speaker hesitates briefly, maybe because he is trying to think of the best word: That was...unfortunate. (This is very similar to a "voiced pause" filled with "err" or "hmm" or "um": That was, um, unfortunate.) A speaker is interrupted and does not finish his sentence: That was— A speaker pronounces each word separately (imagine him beating his fist on the table with every word): That. Was. Unacceptable! A speaker pronounces each syllable separately: The word is un-for-tu-nate, not unfornutate. A speaker makes a brief pause, emphasizing the first word: That, was unfortunate. And so on. Now, I said – and you read – that pauses are made in spoken language. Pauses in written language take the form of a line of whitespace between paragraphs or a chapter break, both of which often indicate that some time has passed: ... and went to bed. In the morning ... But spoken language must not necessarily be limited to dialoge enclosed in quotation marks. Some narrative fiction, for example, is written in a style mimicking spoken language, giving the impression that the narrator is not writing the tale, but verbally relating it to an audience. Often there is a framing narrative that explains who is telling the story to whom and under which circumstances, but often this is only implied within the narrative itself. Much of first person narration is of this type, where the narrator is not telling a tale with a detached, unemotional voice, but rather he or she is emotionally involved and sometimes even exclaims in surprise or – hesitates to continue (as I just did, with the en-dash, for effect). Here is a quick made up example, with two pauses in the narration (signified by an ellipsis and an en-dash, respectively): "Hey, Betty." Oh my God! Ben! "H-hey, B-Ben," I stammered. I felt...excited, I realized in surprise. Since when was I excited about – Ben? It is certainly not the best writing, but I am sure you have encountered similar pauses and breaks in your reading. They are especially common in first person Young Adult fiction. tl;dr Ellipses can appear in the narration outside of dialoge, if the narration is supposed to represent spoken language. In the example you give in your question, the ellipsis is perfectly fine, in my opinion, and gives the (short) text an appearance of being thought or said by a person (of whom we will learn more in the course of the book), instead of neutrally reporting events in the manner of a recording machine. I did not follow your link to check if you criticism would still stand with this information, because that was not part of your question and did not appear relevant to answering it.
[ "math.stackexchange", "0001991218.txt" ]
Q: Non Square Unitary Matrices In numerous sources online, I have found three claims Unitary matrices follow $U^* = U^{-1}$, where $^*$ is the conjugate transpose Unitary matrices can be non-square, as long as all columns and rows are orthonormal Non-square matrices do not have inverses These statements seem to form a contradiction, though I feel like it has something to do with complex numbers. Can anybody help clarify the statements above, and provide an example of a non-square unitary matrix? Correction After copious amounts of google searching, I forgot that the second statement was an assumption I made. I was under the impression that if non-square matrices have SVDs, then the left-singular-matrix and right-singular-matrix had to be non-square. I just realized that in those cases, they are actually square, and it is the diagonal matrix that is non-square. My bad. A: The first statement is certainly true since it is a possible definition of unitary matrices. In my opinion, it is not possible to define non-square unitary matrices because how would you define a unity matrix in the space $L(m,n)$, i.e. the space of linear maps from a $m$-dimensional to a $n$-dimensional vector space? Where did you get that claim from?
[ "superuser", "0000829329.txt" ]
Q: How do I add placeholder text in Word 2007? I'm working on a report but some data, which will be repeated throughout the document, are not yet ready. Is there any way to put a placeholder of some sort that will automatically adjust other than using find and replace? For example, in my document, I write that the current price of Item X is $100. This will appear several times in the same document. However, I might have to adjust the price later on. I can't use find and replace because Item Y and Item Z also cost $100 and their prices are independent of Item X. Is there a tool that will work for this purpose? I'm sorry if my explanation is hard to understand, English isn't my first language. A: Word has a provision for this, which is commonly used with templates to customize documents. You can create and use variables that you define and maintain in one place and use in other places. They are called fields (usually written as {fields} because the curely braces delimit them. The braces aren't actually characters, they must be created using Ctrl-F9 or Insert Field from the menu (in Word 2007, this is under Insert | Quick Parts). There is a collection of pre-defined fields and you can create you own. They can contain text, numbers, calculations, conditional tests, etc., so you can do some very powerful template and document automation with them. The built-in Word help contains a lot of documentation on how to use this feature. You also might find this online tutorial helpful.
[ "stackoverflow", "0018744086.txt" ]
Q: End Thread^ which isn't completed I have two threads within an event in my C++ GUI application (Visual Studio). The function has to run some code, but I want to end the thread when a specified time is elapsed. The thread I have made is: ThreadStart^ oThread = gcnew ThreadStart(this, &MyForm::ThreadMethod); Thread^ newThread = gcnew Thread(oThread); newThread->Start(); How can I end the thread? Because what I tried ends with an exception. A: If there is nothing preventing MyForm::ThreadMethod from tracking its own time spent, why not integrate the timing into your threaded work? void ThreadMethod { Int64 watchdog = 1000L * 5L * 60L; // 5 minutes System::Diagnostics::Stopwatch^ sw = System::Diagnostics::Stopwatch::StartNew(); while (sw->ElapsedMilliseconds < watchdog && otherCondition) { // do your work here } }
[ "stackoverflow", "0052983468.txt" ]
Q: How is the data of a numpy.array stored? This is my simple test code: data = np.arange(12, dtype='int32').reshape(2,2,3); so the data is: array([[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]], dtype=int32) but why does data.data[:48] look like this: '\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\x0b\x00\x00\x00' I mean why are '9','10' stored as '\t\x00\x00\x00' and '\n\x00\x00\x00'? A: \t is the tab character, of ASCII value 9. \n is the LF character, of ASCII value 10. \x00 is a NUL character, of ascii value 0. Thus, '\t\x00\x00\x00' represents a sequence of bytes [9, 0, 0, 0], which is a little-endian representation of a long integer 9. '\n\x00\x00\x00' represents a sequence of bytes [10, 0, 0, 0], which is a little-endian representation of a long integer 10.
[ "stackoverflow", "0035966933.txt" ]
Q: How do I install an APK without any internet connection? My phone's antenna died so it can't connect to the internet by cellular or wi-fi but I still want to use the phone for portable entertainment. I need a way to install an app strictly through the USB connection. Unfortunately, every article I've looked at for how to install APKs without Google Play tells me to start by getting a file manager from Google Play. A: You have two way can do that: Note: you have to connect phone with PC througth USB cable before. Copy any apk to phone from your PC/latop and open file browser in phone to open apk which you want to install Use can use ADB command line tool: Type command: adb install [apk_name_with_full_path] Ex: adb install C:\your_package.apk
[ "sharepoint.stackexchange", "0000092880.txt" ]
Q: Nesting double condition formulas I need to nest several formulas just like this one: =IF(Service="ACB",(IF([Fac/Fellow]="Faculty","002701284","")),""). So first condition is: =IF(Service="ACB",(IF([Fac/Fellow]="Faculty","002701284","")),"") Second condition is =If(Service="Surgery",(IF([Fac/Fellow]="Fellow",002701294,"")),"") Any ideas? I've nested 8 single condition formulas successfully but I can't figure out these double condition formulas. A: If you want to have only one calculated column where all the conditions, you must put next condition in statement else previous conditions. For you conditions example: IF(Service="ACB",(IF([Fac/Fellow]="Faculty","002701284","")),(IF(Service="Surgery",(IF([Fac/Fellow]="Fellow","002701294","")),"")))
[ "stackoverflow", "0047980911.txt" ]
Q: How to use a custom domain for a Cloud Function as a POST request I'm not very experienced with Node.js but learning quick all do quite good with javaScript. I'm using Cloud Functions to create an API for a project and trying to use a custom domain to reach this API. On my Firebase Hosting, I have connected a subdomain "api.mydomain.com". I have a function called "api" on my functions index.js using express: let express = require('express'); let app = express(); app.post('/endpoint/:userId', (req, res) => { ... EXECUTE CODE res.json(json); }); exports.api = functions.https.onRequest(app); In my firebase.json I have a rewrite as so: "rewrites": [ { "source": "/api/**", "function": "api" } So in theory if I make a POST request to https://api.mydomain/api/endpoint/userID should execute the function but instead I get: Cannot POST /api/endpoint/userID/ If I use the default firebase URL to access the function like https://us-central1-my-proyect.cloudfunctions.net/api it works fine. Do you have any Idea how to properly configure the custom domain to work with my function? Thanks a lot for any help! A: When you use an Express app as the target for an HTTPS function, the name of the function gets prepended to the path of the hosting URL, just like it does when you call the function direction. There are two ways to compensate for this: Put the prefix path in your route paths: app.post('/api/endpoint/:userId', (req, res) => { ... }) Create a second Express app that routes everything under /api, and send that to Cloud Functions: app.post('/endpoint/:userId', (req, res) => { ... }) const app2 = express() app2.use('/api', app) exports.api = functions.https.onRequest(app2) Either way, when you rewrite path /api/** to function api, your function will get invoked.
[ "stackoverflow", "0019637044.txt" ]
Q: Warning: Illegal string offset 'id' I have defined two variables as follows: $pic = get_tax_meta($books->term_id,'books_field_id', true); $imageurl = wp_get_attachment_image_src( $pic[id], 'list-thumb' ); print_r($pic) results in the following: Array ( [id] => 302 [src] => http://localhost/mysite/wp-content/uploads/2013/10/apic.jpg ) However, I get the following warning from $pic[id]: Warning: Illegal string offset 'id' Any idea what I'm doing wrong? A: This seems to have fixed the problem: $pic = get_tax_meta($books->term_id,'books_field_id', true); if (isset($pic['id'])) { $picid = $pic['id']; }; $imageurl = wp_get_attachment_image_src( $picid, 'list-thumb' );
[ "stackoverflow", "0052534459.txt" ]
Q: How do I get a list of possible windows service statuses? I'm working on a powershell script to uninstall windows service. I would like it to handle the most (if not all) possible scenarios. One thing I would like to check before I attempt to uninstall the service is service status. I was not able to find a complete list of possible statuses that a windows service can have. Apart from obvious ones (Stopped/Running/Stopping) are there any relevant statuses I should handle? A: You can get these by using the enum GetNames method on the System.ServiceProcess.ServiceControllerStatus type: [enum]::GetNames([System.ServiceProcess.ServiceControllerStatus]) Returns: Stopped StartPending StopPending Running ContinuePending PausePending Paused
[ "stackoverflow", "0050640161.txt" ]
Q: FLUTTER | Right Align not working Trying to right align a container with text view child, it has a row parent which is inside another column, tried number of solutions from Stack Overflow, didn't work. Code ///Transactions Heading new Column( children: <Widget>[ new Row( children: <Widget>[ new Container( alignment: Alignment.centerLeft, margin: new EdgeInsets.only(top: 20.0, left: 10.0), child: new Text( "Transactions", style: new TextStyle( color: primaryTextColor, fontSize: 25.0, fontWeight: FontWeight.w700, letterSpacing: 0.1, ), ), ), new Container( margin: new EdgeInsets.only(top: 25.0), child: new Text( currentGoalTransactions.length.toString() + " items", style: new TextStyle( color: darkHeadingsTextColor, fontSize: 15.0), ), ), ], ), ]); Want to align the 2 items text to the right Screenshot A: Use the mainAxisAlignment property in Row widget. new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, ... )
[ "stackoverflow", "0039438305.txt" ]
Q: angularJs , $http woocommercce set default param i learn about js and angularjs , and for test my knowledge i'm try to get data from woocommerce(wordpress) , so i find api reernce: https://woothemes.github.io/woocommerce-rest-api-docs/?shell#authentication-over-https curl https://example.com/wp-json/wc/v1/products \ -u consumer_key:consumer_secret code: myApp.controller('homeCtrl',['$scope','$http',function($scope,$http){ console.log('App Start') var secretKey = { consumer_key: 'ck_bc51576e596ae1fbf535f8a3d60b281541407006', consumer_secret: 'cs_44beee13f3eef60a9d5fb66142fc40a3ba1d2989' } $http({ method: 'GET', url:'https://www.ng-il.com/shop/wp-json/wc/v1/products', params: secretKey }).then(function(res){ console.log(res) }) }]); it work fine , my questions : 1)how i can set this params for all requests (angularJs)? 2)in js(no AngularJs) to pass paramters is only by var.send(params) ? 3)this is the way i need to pass counsumer_key&consumer_secret? or have other way? thank for all! A: To pass those parameters to all your requests, you can use interceptors : var myApp = angular.module('myApp', []); myApp.config(function ($httpProvider) { $httpProvider.interceptors.push(function ($q) { return { 'request': function (config) { config.params = { consumer_key: 'ck_bc51576e596ae1fbf535f8a3d60b281541407006', consumer_secret: 'cs_44beee13f3eef60a9d5fb66142fc40a3ba1d2989' }; return config; } } }); });
[ "stackoverflow", "0012317604.txt" ]
Q: Returning parameter in ABAP. How? I get used to JAVA, thus having problem to write this code in ABAP. I call a method with two parameters. It should return a number, so I can save it. What I want is int result = generate_num(40,5); int generate_num(int thisNum, int newDigit){ return thisNum * 10 + newDigit; } In ABAP I tried this so far. //Declared Method methods GENERATE_NUM importing !thisNum type I !NEWDIGIT type DIGIT_NUMBER_VALUE. //Calling Method CALL METHOD me->Generate_NUM EXPORTING thisNUm = 40 newDigit = 5. //Method itself METHOD GENERATE_NUM. DATA: newNum type i. If thisnum < 0. newNum = thisnum * 10 - newdigit. Else. newNum = thisnum * 10 + newdigit. ENDIF. RETURNING VALUE(newNum). ENDMETHOD. But I get lost in this code, have no idea how to return a value and how to save it in another variable. A: That's how you declare a method with a return parameter: METHODS generate_num IMPORTING thisNum TYPE i newdigit TYPE digit_number_value RETURNING value(result) TYPE i. Note that a method can only have one RETURNING parameter, and that parameter must always be passed by value. In the method implementation, you set the return value by modifying the local variable you declared as returning parameter: METHOD generate_num. IF thisnum < 0. result = thisnum * 10 - newdigit. ELSE. result = thisnum * 10 + newdigit. ENDIF. ENDMETHOD. The returned value will be whatever value result has when the method returns. Just like with EXPORTING parameters. When you call a method you can either use the classic CALL syntax which is more like the syntax seasoned ABAP developers are used to: DATA lv_foo TYPE i. " the variable you want to store the return value in CALL METHOD me->generate_num EXPORTING thisNUm = 40 newDigit = 5 RECEIVING result = lv_foo. or the functional syntax which is more like the Java syntax you might be used to: lv_foo = me->generate_num( thisNUm = 40 newDigit = 5). If the method doesn't just have importing parameters but also changing or exporting parameters, the syntax looks like this: lv_foo = me->generate_num( EXPORTING thisNUm = 40 newDigit = 5 CHANGING cv_bar = lv_bar ).
[ "ru.stackoverflow", "0000609339.txt" ]
Q: Алгоритм комбинаций Помогите с решением задачи. Есть строка: "abcd", нужно вывести все возможные комбинации с разделителем "_", на выходе должно получиться что-то вроде: a_b_c_d a_b_cd a_bc_d ab_c_d a_bcd ab_cd abc_d Upd: длина строки может быть разной, "abcd" - показана как пример. A: 4 символа - 3 промежутка, где знак подчеркивания или есть, или нет. Так что цикл от 0002 до 1112 и вставка подчерков в соответствии с маской. Если символов больше, то и ширина битовой маски соответственно больше. Добавление по подсказке Yaant: Если какие-то комбинации не нужны - её или их несложно пропустить. В приведённом примере это то, что соответствует полностью нулевой маске, т.е цикл нужно организовывать от 0012 до 1112.
[ "stackoverflow", "0059437083.txt" ]
Q: New Sklearn syntax How could I rewrite this code, so it would work with the sckit-learn 0.22 version? from sklearn.preprocessing import LabelEncoder, OneHotEncoderlabelencoder = LabelEncoder() x[:,0] = labelencoder.fit_transform(x[:,0]) onehotencoder = OneHotEncoder(categories = 0) x = onehotencoder.fit_transform(x).toarray() A: It would be better to know what problem you try to solve because it is not clear what your code was supposed to do. One thing is sure, you should not use a LabelEncoder to encode your data (i.e. X) and instead use directly the OneHotEncoder. So to one-hot encode a matrix of categories: import numpy as np from sklearn.preprocessing import OneHotEncoder X = np.array( [['a', 'b'], ['b', 'a']], dtype=object ) encoder = OneHotEncoder() X_trans = encoder.fit_transform(X) print(X_trans.A) and you will get: [[1. 0. 0. 1.] [0. 1. 1. 0.]] If you want to apply the encoder only on a subset of columns, then you need to use the ColumnTransformer import numpy as np from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder X = np.array( [['a', 'b', 1], ['b', 'a', 2]], dtype=object ) preprocessor = ColumnTransformer( [('cat-encoder', OneHotEncoder(), [0, 1])], remainder="passthrough" ) X_trans = preprocessor.fit_transform(X) print(X_trans) and you will get something like: [[1.0 0.0 0.0 1.0 1] [0.0 1.0 1.0 0.0 2]]
[ "math.stackexchange", "0000114081.txt" ]
Q: How many ways $12$ persons may be divided into three groups of $4$ persons each? How many ways $12$ persons may be divided into three groups of $4$ persons each? I think the answer should be $\frac{12!}{(4!)^3}$ but the suggested correct answer is $5775$, could anybody explain where I am going wrong? A: The answer is $\frac{12!}{(4!)^3\cdot3!}=5775$ because the $3!$ different orders of the three groups do not matter either, so your solution was almost correct. A: We can also organize the count in a different way. First line up the people, say in alphabetical order, or in student number order, or by height. The first person in the lineup chooses the $3$ people (from the remaining $11$) who will be on her team. Then the first person in the lineup who was not chosen chooses the $3$ people (from the remaining $7$) who will be on her team. The double-rejects make up the third team. The first person to choose has $\binom{11}{3}$ choices. For every choice she makes, the second person to choose has $\binom{7}{3}$ choices, for a total of $$\binom{11}{3}\binom{7}{3}.$$ Remark: The lineup is a device to avoid multiple-counting the divisions into teams. The alternate (and structurally nicer) strategy is to do deliberate multiple counting, and take care of that at the end by a suitable division.
[ "stackoverflow", "0002887643.txt" ]
Q: Mutate an object into an instance of one its subclasses Is it possible to mutate an object into an instance of a derived class of the initial's object class? Something like: class Base(): def __init__(self): self.a = 1 def mutate(self): self = Derived() class Derived(Base): def __init__(self): self.b = 2 But that doesn't work. >>> obj = Base() >>> obj.mutate() >>> obj.a 1 >>> obj.b AttributeError... If this isn't possible, how should I do otherwise? My problem is the following: My Base class is like a "summary", and the Derived class is the "whole thing". Of course getting the "whole thing" is a bit expensive so working on summaries as long as it is possible is the point of having these two classes. But you should be able to get it if you want, and then there's no point in having the summary anymore, so every reference to the summary should now be (or contain, at least) the whole thing. I guess I would have to create a class that can hold both, right? class Thing(): def __init__(self): self.summary = Summary() self.whole = None def get_whole_thing(self): self.whole = Whole() A: A general OOP approach would be to make the summary object be a Façade that Delegates the expensive operations to a (dynamically constructed) back-end object. You could even make it totally transparent so that callers of the object don't see that there is anything going on (well, not unless they start timing things of course). A: Responding to the original question as posed, changing the mutate method to: def mutate(self): self.__class__ = Derived will do exactly what was requested -- change self's class to be Derived instead of Base. This does not automatically execute Derived.__init__, but if that's desired it can be explicitly called (e.g. as self.__init__() as the second statement in the method). Whether this is a good approach for the OP's actual problem is a completely different question than the original question, which was Is it possible to mutate an object into an instance of a derived class of the initial's object class? The answer to this is "yes, it's possible" (and it's done the way I just showed). "Is it the best approach for my specific application problem" is a different question than "is it possible";-) A: I forgot to say that I also wanted to be able to create a "whole thing" from the start and not a summary if it wasn't needed. I've finally done it like that: class Thing(): def __init__(self, summary=False): if summary: self.summary = "summary" self._whole = None else: self._whole = "wholething" @property def whole(self): if self._whole: return self._whole else: self.__init__() return self._whole Works like a charm :)
[ "ru.stackoverflow", "0001171361.txt" ]
Q: регулярное выражение для добавления префиксов в классы верстки Всем привет! Необходимо в текстовом редакторе vscode с помощью регулярных выражений преобразовать строку вида: class="dab alfa beta gamma-new delta" в строку: class="pre-dab pre-alfa pre-beta pre-gamma-new pre-delta" Сам смог добиться только таких результатов: class="([^\s]+)(( [^\s]*)*)" заменяю строкой: class="pre-$1 pre-$2" Но результат не тот. Что я делаю не так? A: Используйте Найти: (?<=class="[^"]*?)[^\s"]+(?=[^"]*") Заменить: pre-$0 Подробности (?<=class="[^"]*?) - блок предварительного просмотра назад, требующий наличия подстроки class=", потом 0 и более символов, отличных от ", как можно меньше, сразу перед текущей позицией в строке [^\s"]+ - один и более символов, отличных от пробельных символов и двойной кавычки (?=[^"]*") - блок предварительного просмотра вперёд, требующий наличия 0 и более символов, отличных от ", а затем " сразу после текущей позиции в строке. $0 – обратная ссылка на целый текст совпадения.  Пример: Результат: class="pre-dab pre-alfa pre-beta pre-gamma-new pre-delta"
[ "stackoverflow", "0031099664.txt" ]
Q: Store and retrieve user favorites in mysql I have an android app that pulls information from mysql db and displays it in a list. Each list item has a favorite button that upon click updates the db with the username and with the list item. I can get all user favorites using relational and foreign key. What I am trying to achieve is when the user re-logs in to the App and scrolls for available items he can already see which items he marked as favorite without going to his favorites page. So for example when you are scrolling in your facebook page you can already see which posts you liked. How can I achieve that? First table |------------------|--------------|----|-------| | Column | Type |Null|Default |------------------|--------------|----|-------| | //**id**// | int(11) | No | | car_vendor | varchar(20) | No | | car_model | varchar(20) | No | | car_petro | varchar(10) | No | | car_transmition | varchar(10) | No | | car_hand | int(11) | No | | car_spedometer | varchar(7) | No | | car_engine_vol | varchar(4) | No | | car_category | int(11) | No | | car_post_date | date | No | second table |----------------|------------|----| | Column | Type |Null| Default |----------------|------------|----| | //**id**// | int(11) | No | | username | varchar(20)| No | | favorites_id | int(11) | No | <<< foreign key points to ID on first table A: You can ask the db for that information, the moment you get the list of all products you can do a LEFT JOIN, that can be used to connect a product, if liked, to the user. You can do something like this. SELECT CAR_VENDOR, A.CAR_MODEL, A.CAR_PETRO, A.CAR_TRANSMITION, A.CAR_HAND, A.CAR_SPEDOMETER, A.CAR_ENGINE_VOL, A.CAR_CATEGORY, A.CAR_POST_DATE, B.USERNAME FROM TABLE_ONE AS A LEFT JOIN TABLE_TWO AS B ON B.FAVORITES_ID = A.ID AND B.USERNAME = "actual user username" This query should do the work, I didn't test it but you can take as an idea where to start Only the object with the preference should have the username field filled EDIT ------------------------------------------------ Taking the case that the OP presented we have that: We have a single table that is a list of objects (cars) with their specific parameters (engine size, hand, model, category etc) We have a N to N table that can connect each product to one or more user and each user to one or more product We probably have a table of people (the "username" column of table two, that I wish to call "LIKES" should be a foreign key connected to the primary key in PEOPLE table) The behavior is simple, we want something social-like where a person can "upvote" a car, obviously we don't want multiple votes on the same car from the same person thus we have to disable the function in case he/she has already voted. We take in example a normal page in which a person has already voted some products and want to see the complete list. In this case we want to see: The COMPLETE list of item, no matter what. The items that have already got a vote from that particular user. One way to handle this is connecting CARS table with LIKES table (I leave the anagraphic of user outside to simplify). The way to do this is using a JOIN connecting the two tables on the id of the car. This SQL command will return a set of line that are the combination of each line inside the CARS followed by the relative username. This will lead to mutiple lines for the same CAR, one for each upvoting user, needing a business logic to handle the problem of showing the correct page. A step further in SQL logic is to use a LEFT JOIN. The LEFT JOIN will include ALL the record from the first table and will connect them with the matching line of the second one. Thus joining CARS with LIKE on car-id AND asking for the username that we want, will return the complete list of cars (all record from left) connected to (and only to) the records that match the username related condition. The example can be this: | CARS | | ID | MODEL | |------+---------------| | 1 + FORD | | 2 + OPEL | | 3 + FERRARI | | 4 + GM | |----------------------| | LIKES | | USERNAME | CAR_ID | |------------+---------| | KEVIN | 3 | | PAUL | 3 | |------------+---------| If I use a simple JOIN like this: SELECT ID, MODEL, USERNAME FROM CARS JOIN LIKES ON CAR_ID = ID It will return this: | ID | MODEL | USERNAME | | 3 | FERRARI | KEVIN | | 3 | FERRARI | PAUL | That is incomplete If I use something like this: SELECT ID, MODEL, USERNAME FROM CARS LEFT JOIN LIKES ON CAR_ID = ID I will have this: | ID | MODEL | USERNAME | | 1 | FORD | NULL | | 2 | OPEL | NULL | | 3 | FERRARI | KEVIN | | 3 | FERRARI | PAUL | | 4 | GM | NULL | That is still incorrect, even if better. The double record for the FERRARI will be removed adding a condition to the join: SELECT ID, MODEL, USERNAME FROM CARS LEFT JOIN LIKES ON CAR_ID = ID AND USERNAME = "KEVIN" This will return: | ID | MODEL | USERNAME | | 1 | FORD | NULL | | 2 | OPEL | NULL | | 3 | FERRARI | KEVIN | | 4 | GM | NULL | That is the correct list. Once I've got this list I need to show it to the user, checking if USERNAME is not NULL then DISABLE LIKE BUTTON (PSEUDOCODE) I hope this is useful to somebody
[ "stackoverflow", "0035491672.txt" ]
Q: MWS api Throtlling - Maximum request quota I don't understand something about mws throtlling. For example with this api: http://docs.developer.amazonservices.com/en_US/products/Products_GetMatchingProductForId.html The Max request quota is 20. So I understand that I can submit 20 different ids on each request. But in the table there written that 'Maximum: Five Id values'. So what the 20 represents? A: 20 represents the maximum about of requests you can make at a time. Each request can have a maximum of 5 Id values in the IdList. So, essentially you can submit requests for 100 (20 * 5) product Id's at a time. Then you have to wait until the quota is restored, which is 5 per second. You are also capped by an hourly request quota, in this case 18,000 requests per hour. Do some math to figure out how many requests you need to make and space those out so enough time is given for the restore to kick in.
[ "stackoverflow", "0029264153.txt" ]
Q: The remote certificate is invalid according to the validation procedure. WCF Error we have recently change one of our .asmx service to .svc the issue we are facing is we are unable to call the service from : 1. an application hosted on the same server as the .svc 2. an application hosted on different server then .svc it gives the following error: Same server error: "The remote certificate is invalid according to the validation procedure. " Different Server error: There was no endpoint listening at https://abc.svc that could accept the message. This is often caused by an incorrect address or SOAP action We tried putting the certificate in the Trusted root folder and here is the error: Same server error: "The remote certificate is invalid according to the validation procedure. " Different Server error: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail Here are config settings we have: Config details: Hosting Config Consumer config details [Different Server] A: we figured our the issue to be one of the SSL certificate on the Hosting server: We were calling the following website of the host: https://example.com/qwerty.svc the web-appPool example.com under IIS should have a SSL certificate binded to it, and the name of the certificate should be exactly same as example.com In our case the name was a mismatch, which was causing the above error.
[ "stackoverflow", "0017241180.txt" ]
Q: Oracle find dates same day different months i have a question, i would like to find all the records from a table that match the day and the year of a given date, in all the months, for example Given the date (mm/dd/yyyy) : '12/24/2010' Return all the records with the dates: '12/24/2010' '11/24/2010' '10/24/2010' '09/24/2010' '08/24/2010' '07/24/2010' '06/24/2010' '05/24/2010' '04/24/2010' '03/24/2010' '02/24/2010' '01/24/2010' Is there a way to do it in a single query? I would like to implement it in a function, but wouldn't like to use a loop (just for speed). Any help would be deeply appreciated!! :) A: Assuming that your columns are all defined as DATE, functionally, you could certainly do something like SELECT * FROM my_table WHERE to_char( date_column, 'DD-YYYY' ) = to_char( date '2010-12-24', 'DD-YYYY' ) You could potentially create a function-based index on to_char( date_column, 'DD-YYYY' ) to make the query more efficient.
[ "networkengineering.stackexchange", "0000044062.txt" ]
Q: One VLAN on two switches I'm trying to understand the specifics of trunking a VLAN on two switches. Say I have two switches, both hosting half of VLAN 3. Switch 1: Ports 0-5 on VLAN 3, Port 6 is Trunk Switch 2: Ports 0-5 on VLAN 3, Port 6 is Trunk Do the two switches know what the MAC addresses are of the devices connected to the other switch which are in the same VLAN, or do the switches just know that Port 6 is a VLAN 3 trunk and when they receive a broadcast frame, they just flood the frame to the trunk port with the VLAN tag and expect the switch on the other end to deal with it? A: When a frame enters a switch, the switch will take the source MAC address and update its MAC address table with the interface where the frame entered the switch. That interface can be an access or trunk interface. Broadcast or unknown unicast frames will be sent to all interfaces (except the one where the frame entered the switch), including access and trunk interfaces. Known unicast frames will be sent to the switch interface indicated in the switch MAC address table, whether an access or trunk interface.
[ "sound.stackexchange", "0000005906.txt" ]
Q: Mid/Side, is it magic? But how does it know its left from its right? I'm trying to wrap my head around MS recording. If I'm working without an MS encoder, I'm recording onto two channels. One channel takes the centre cardioid, the other takes the figure of eight. So, one channel records the mid, the other the sides. But where does left and right come into play? Is it in the magic of the 'matrixing'? If I record a motorcycle going from mic left to mic right, will the listener perceive the same left right transition? Someone, please explain. My brain is an idiot. A: Good question. I had a hard time myself when I started out. The technique is using the cardioid mic pointed at the source, which gives you a mono source sent to both speakers. This is the main signal. The side signal is a bidirectional (figure of 8) mic pointed at 90 degrees from the subject you're aiming at and so this records the ambient signal (or signal from the Side). The mid mic is played back mono. The side mic is duplicated, switched in polarity on one of the channels. They are panned left and right respectively. When you point your mic directly at the source, the null spot of the figure-8 mic is pointed directly at it as well so all you get is mono "in the center" signal. When the source moves a bit to your left, it comes in also to the left lobe of the figure-8 pickup pattern, and so that shows up via the matrix on the left side, thus creating a stereo image. It's basically that anything on your left enters into the figure-8 with positive polarity, thus being reinforced in the left speaker and cancelled out in the right speaker. When the source is on the right, the figure-8 mic is now negative in polarity, and thus the flipped phase channel is being reinforced in the right speaker and cancelled out in the left speaker because the left speaker is now negative and canceling with the mid mic and the right side (which is flipped to positive now) is being reinforced. I think if you drew a sketch or saw a picture of it at one of the sites the other guys sent a link to would work. There is a lot more detail to go into, having to do with phase, polarity of mics, etc. but that's the basics of what you need to know. A: Probably worth a search on here as there's a few posts regarding MS.. Also you might want to check out: http://www.wikirecording.org/Mid-Side_Microphone_Technique http://www.recording-microphones.co.uk/Mid-Side-stereo.shtml and http://www.bluecataudio.com/Vault/Doc/MidSideProcessing.pdf hope that helps!
[ "stackoverflow", "0036181851.txt" ]
Q: Deleting generalised strings from a text file I am trying to delete strings from a text file. The strings consist of different types of characters and are all different, but they all start with the same three letters and finish at the end of the line. So far I am using this code, which I know works when I want to delete all occurrences of a specific string: import sys import fileinput for i, line in enumerate(fileinput.input('duck_test.txt', inplace=1)): sys.stdout.write(line.replace('pep.*', '') I have tried to adapt it to delete a generalised string using '.*' but it doesn't work. Does anyone know where I am going wrong? Thanks. A: The following tested code will replace all strings that begin with the letters 'pep' and end with a newline in the file 'duck_test' with an empty string: import sys import fileinput import re for i, line in enumerate(fileinput.input('duck_test', inplace=1)): sys.stdout.write(re.sub(r'pep.*', '', line))
[ "stackoverflow", "0007031131.txt" ]
Q: jQuery alert message with user-defined persistance? I'd like to set up an alert message that appears at the top of my application on the first time a user accesses it, and persists until the user dismisses it. I'm kinda new to jQuery, but I'd like to use it for this. Does jQuery have some built in methods for this kind of thing? Ideally I'd like it to be an instant action, rather than a form variable. My app is a PHP based WordPress plugin. A: You can create a twitter-like alert by following the steps on these tutorials. CSS: #alert { overflow: hidden; z-index: 999; width: 100%; text-align: center; position: absolute; top: 0; left: 0; background-color: #fff; height: 0; color: #000; font: 20px/40px arial, sans-serif; opacity: .9; } jQuery Check if Use setTimeout to collapse the alert after 3 seconds Expand the alert to CSS line-height or 50px if line-height is not set If the user clicks alert before 3 seconds, collapse the alert early $(function () { var $alert = $('#alert'); if($alert.length) { var alerttimer = window.setTimeout(function () { $alert.trigger('click'); }, 3000); $alert.animate({height: $alert.css('line-height') || '50px'}, 200) .click(function () { window.clearTimeout(alerttimer); $alert.animate({height: '0'}, 200); }); } }); Put CSS and jQuery in an HTML page Some things to note: Line 1: Turn on session with PHP Line 13: There’s our alert CSS Line 30: If $_SESSION['alert'] exists (set in submit.php in step 2) Line 40: Use jQuery hosted by Google Line 42: There’s our alert jQuery <?php session_start(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Twitter-like alert message</title> <style type="text/css"> body { background-color: #ccc; color: #000; padding: 30px; } #alert { overflow: hidden; width: 100%; text-align: center; position: absolute; top: 0; left: 0; background-color: #fff; height: 0; color: #000; font: 20px/40px arial, sans-serif; opacity: .9; } </style> </head> <body> <?php if(!empty($_SESSION['display'])) { echo '<div id="alert">' . $_SESSION['display'] . '</div>'; unset($_SESSION['display']); } ?> <form method="post" action="submit.php"> <label for="message">Message</label> <input type="text" name="message"> <input type="submit" value="Alert me!"> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(function () { var $alert = $('#alert'); if($alert.length) { var alerttimer = window.setTimeout(function () { $alert.trigger('click'); }, 3000); $alert.animate({height: $alert.css('line-height') || '50px'}, 200) .click(function () { window.clearTimeout(alerttimer); $alert.animate({height: '0'}, 200); }); } }); </script> </body> </html> Use PHP to add the alert to the $_SESSION Save this file as submit.php <?php session_start(); $themessage = get_magic_quotes_gpc() ? stripslashes(trim($_POST['message'])) : trim($_POST['message']); $_SESSION['display'] = $themessage; header('Location: ' . $_SERVER['HTTP_REFERER']); exit; ?> It will create something similar to this http://www.youtube.com/watch?v=BbJeYdPRKXw&feature=player_embedded Comment below if you have any questions on the code, I guess this is all you need. Credits to: http://briancray.com/2009/05/06/twitter-style-alert-jquery-cs-php/ http://www.achari.in/create-twitter-alert-style-using-jquery-js-and-css
[ "boardgames.stackexchange", "0000007974.txt" ]
Q: Where to buy or how to cut blank hexes for own game prototype? Fellow board game player wants to test his game prototype, which uses a number of hex pieces (prefreably smaller than Catan or Eclipse ones). Is there a place to buy some blank ones? We could then use adhesive paper labels printed on inkjet printer. Or maybe there is a place to send full-hex graphic design and receive cutted pieces? Alternatively, do you have working DIY methods for cutting uniform hexes? A: Yes, you can buy blank hex pieces. Print&Play Productions offers cardboard hex tiles in several different sizes through Boards & Bits. Chipboard Shapes - Hex 1.19" [35 pcs] $2.00 Chipboard Shapes - Hex 1.5" [20 pcs] $2.00 Chipboard Shapes - Hex 2.2" [11 pcs] $2.00 Chipboard Shapes - Hex 2.6" [22 pcs] $3.00 Chipboard Shapes - Hex 3.9" [8 pcs] $3.00 You could also get wooden hexes from WoodNShop for $0.15-$0.42 each, or at a discount by the 100s. I am unsure if these would fit your purposes for tile laying, as I have heard complaints that the tile dimensions are not uniform enough for such a purpose. C/O HEXAGON 1/8 X 1 $0.15 C/O HEXAGON 1/8 X 2 $0.20 C/O HEXAGON 1/8 X 1 $0.32 C/O HEXAGON 1/8 X 1 $0.42 C/O HEXAGON 1/4 X 2 $0.20 There is also plastic tiles, if you are so inclined. With a little bit of work to remove the mesh backing, you could use actual hexagonal tiles from your local hardware store. I don't know of any board game manufacturer that creates hex tiles with custom graphics. Board game maufacturers are capable of creating protype board games, but my guess is the cost is prohibitive. If you want to cut your own uniform hex tiles, you are going to need a die cutter ($600), and a custom die. You probably don't even need hex tiles for testing purposes. If the hex tiles need not be rotated, then square tiles can be offset every other row for the same effect as a hex tile. If orientation is important, wooden tiles/disks can be substituted for hex tiles. A: Quilters and schools often use die-cutters to make shaped pieces. Hexagons are one of the standard die types, and are available in a variety of sizes. Many cut multiples at once, tho the standard sized template is a 5x8" block with 1 large, or 2, 4, or 6 hexagons of smaller sizes (3", 2", 1" face to face) Search for Hexagon die cut to find more variety than is worth listing here. Craft stores and school supply stores often also have them. To use them, however, you'll want a die-cutting press - itself a hundred dollar item. A: at the Wikipedia entry for hexagons(http://en.wikipedia.org/wiki/Hexagon) there is a really neat gif on how to draw a normal hexagon with a compass and a straight edge. Otherwise I've used TheGameCrafter.com in the past. They have a Hex playing cards. although that's probably larger then catan. (3.75in X 3.25in). and you can even get blanks there (if they have them in stock.)
[ "security.stackexchange", "0000154145.txt" ]
Q: When creating self signed certs, is the CA.crt supposed to be installed into client machine? I'm trying to work with OpenSSL C API, I'm relatively new to all this still, and I find a lot of mixed information out there, so I think it's wise to ask for ideas/opinions/clarification. Anyway, the client program requires a certificate or directory to be loaded which contains a "TrustStore". Is this just another meaning for the server's CA certificate itself in the case I'm creating my own SSL certificates for said server? And if so, will the intermediate CA work for this purpose in replacement of root CA? I think I'm on the right track. However, I just wanted some clarification so as to prevent myself making some real daft mistake, as I've heard some conflicting information in regards to this. Some say the client needs the root CA itself; other sources say they only install intermediate CA for security reasons, which seems logical. I'm generally a little confused as to how the chain of trust works in regards to a client connection though. I've actually only ever needed to generate a CSR and install a certificate on the web server, so the client side stuff is kinda new to me. This question was originally asked here on Stack Overflow, it was suggested that I ask the info-sec community. A: tl;dr If the cert contains some variation of CA:TRUE, it makes sense to distribute it, if it does not, then there is no benefit to distributing it. The chain of trust itself can be explained in terms of the certificate structure. If we start from your server's cert (i.e. the cert you would typically use for apache): you server cert is generated by a certificate authority, based on a CSR you provide. That CSR contains your public key, and some other information the CA may or may not be interested in using. the CA receives your CSR, and (generally), will create a signed certificate using an intermediate CA. Your certificate will have two public keys: one for the subject (which is the public key extracted from your CSR), and one for the issuing party, which is the CA's intermediate certificate. the CA's intermediate certificate is itself a signed certificate (with some special options), where the subject key will be the intermediate CA's public key (which is the same public key as is found in the Issuer Public Key of your server certificate). The signing (or issuing) key will be the CA's root certificate (alternatively, it will be another intermediate). the CA's root certificate is (generally) a self-signed certificate. In practice, this means that the Issuer and Subject keys are the same public key. You can see this by checking certificates in the wild, e.g.: $ openssl s_client -connect google.com:443 < /dev/null CONNECTED(00000003) depth=2 C = US, O = GeoTrust Inc., CN = GeoTrust Global CA verify return:1 depth=1 C = US, O = Google Inc, CN = Google Internet Authority G2 verify return:1 depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = *.google.com verify return:1 --- Certificate chain 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.google.com i:/C=US/O=Google Inc/CN=Google Internet Authority G2 1 s:/C=US/O=Google Inc/CN=Google Internet Authority G2 i:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA 2 s:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA i:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority The chain of trust this builds can be summarised as (I am starting from the 'bottom' - the Equifax cert): the root CA (Equifax) delegates day-to-day activities to an intermediate CA (GeoTrust) and signs a certificate representing this fact (i.e setting CA:TRUE, KeyUsage: keyCertSign). In other words, the root CA 'trusts' the intermediate to issue certificates on its behalf (hopefully after completing a series of mandatory validation steps). in this chain, the intermediate (Geotrust) has further delegated to a Google CA (CN=Google Internet Authority G2). the delegate (a.k.a the Google intermediate CA) then signs a CSR, which effectively is a document stating that for a given set of names (the CN, and possibly Subject Alternative Names), a private/public key pair is valid/trusted (the trust here coming from the fact they have validated the claim to speak for a given name - in this case, the Google CA has issued a certificate for *.google.com). Note that (root) CAs are generally self-signed - a CA is trusted generally because it abides by a set of processes and procedures that are felt to ensure it does not issue certificates to people who should not have them. Which is why I can't go out and get myself a certificate saying I am google. This is therefore a convention of sorts (albeit one backed by formal mechanisms), and if you start your own CA, distributing its root (and intermediate) certificates achieves exactly the same thing as distributing the certs of other CAs does: it makes certificates issued by that CA be accepted as valid (i.e. trustworthy) by the system. In more practical terms, the trust store (for openSSL) is pretty much a bunch of files with a specific naming convention. See https://www.openssl.org/docs/faq.html#USER5: When a certificate is verified its root CA must be "trusted" by OpenSSL this typically means that the CA certificate must be placed in a directory or file and the relevant program configured to read it That directory is /etc/ssl/certs (there are others, such as /etc/pki on RH-likes). https://superuser.com/questions/437330/how-do-you-add-a-certificate-authority-ca-to-ubuntu#719047 provides some further overview of how one adds a certificate to the store, as does https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate, The short version is that update-ca-certificates automates the process, and is the commonly used tool. The slightly longer version is that certificates need to be stored by hash (e.g. in files named based on the output of openssl x509 -hash -in cert.pem), so that openSSL can efficiently validate chains. See https://www.openssl.org/docs/man1.0.2/apps/c_rehash.html for some additional background. updated to respond to the questions in comments: The server certificate, in this discussion, is defined as trusted or not based on its chain of trust. If you think about how (e.g.) curl https://google.com works, it is a bit easier to understand: curl opens a TLS connection to google, which returns a certificate. curl looks at that 'end-user' certificate - i.e. the server's certificate, and looks specifically for the issuer. if the issuer is 'known' in the trust store, the remainder of the trust chain is validated (i.e. the server certificate issuer's certificate is checked, and if it has an issuer other than itself, that issuer is checked, etc). Only if the full trust chain can be validated is the certificate considered valid. However, it would absolutely impractical to distribute trust chains if end-user certificates needed to be included. I don't have any numbers on how many websites are out there, but based on the fact Alexa provide a top 1M, you would assume it is more than 1 million. Which is sort of the point of a chain of trust: you generally need to have the issuer certificates around, but you do not need the end certificates to be distributed, because they tell you who the issuer is. And you can verify they aren't lying, because you can check the issuers public key (and the chain of trust that establishes it is the proper key), and validate whether the end-user (i.e. server) certificate was really signed by the private counterpart of the issuer's public key. So no, you should not distribute the end-user certs, but only the chain of trust - or, in simpler terms: distribute all the certs you generate where the BasicConstraints (legitimately) say something at least CA:TRUE. Do not distribute anything that does not meet that condition, because it is a waste of your time and disk space - everything that does not say CA:TRUE can be validated against something that does.
[ "math.stackexchange", "0001501178.txt" ]
Q: Isometry: the dot product and derivative dot product. In the image below what is meant by the items within the squares: Box 1. Derivative f is the function from tangent plane p to to tangent plane f(p)? Box 2. What is the meant by dot product derivative f at f(p) versus the dot of v,w at p? in particular the f(p) and p. A: The notation $T_pM$ means "tangent space to the manifold $M$ at the point $p \in M$." Similarly, $T_{f(p)}N$ means "tangent space to the manifold $N$ at the point $f(p) \in N$." If $f \colon M \to N$ is a smooth map between smooth manifolds, then its derivative at $p \in M$ is a linear map $df_p \colon T_pM \to T_{f(p)}N$. A Riemannian metric on a manifold $M$ is a choice of (smoothly varying) inner product at each point of the manifold. In your situation, there are two Riemannian metrics in play: there is the metric $g$ on $M$, and also the metric $\overline{g}$ on $N$. The notation $\langle df_p(v), df_p(w) \rangle_{f(p)}$ means the inner product of the tangent vectors $df_p(v), df_p(w) \in T_{f(p)}N$ with respect to the Riemannian metric $\overline{g}$ at the point $f(p) \in N$. That is, the notation is really $$\overline{g}_p(df_p(v), df_p(w)) = \langle df_p(v), df_p(w) \rangle_{f(p)}$$ and $$g_p(v,w) = \langle v, w \rangle_p.$$ Saying that $f \colon (M, g) \to (N, \overline{g})$ is a local isometry means both that (1) $\overline{g}_{f(p)}(df_p(v), df_p(w)) = g_p(v,w)$ for all $p \in M$ and $v,w \in T_pM$, and also (2) $f$ is a diffeomorphism. Frankly, it will be very hard to learn any Riemannian geometry (as you seem to be doing) without a good understanding of smooth maps, their derivatives, and tangent spaces -- at the very least.
[ "stackoverflow", "0063750026.txt" ]
Q: Pointer array of strings size and address spacing do not match Sorry if this is a stupid question. I am trying to teach myself some programming and fell into a little confusion here. The code: #include <stdio.h> void main() { int i; char *array[5]={"Apples", "mangoes", "grapes", "bananas", "oranges"}; printf("THIS IS FROM THE ARRAY:\n"); for(i = 0; i < 5; i++) { printf("String=%s | ", array[i]); printf("Address of string literal = %i", array[i]); printf(" | Size = %u\n",sizeof(array[i])); } } produces the output: Output Image THIS IS FROM THE ARRAY: String=Apples | Address of string literal = 4210688 | Size = 8 String=mangoes | Address of string literal = 4210695 | Size = 8 String=grapes | Address of string literal = 4210703 | Size = 8 String=bananas | Address of string literal = 4210710 | Size = 8 String=oranges | Address of string literal = 4210718 | Size = 8 Why is the differences between the addresses not consistently 8 although the sizeof output says the size is eight? 4210688 4210695 (Difference is 7) 4210695 4210703 (Difference is 8) 4210703 4210710 (Difference is 7) 4210710 4210718 (Difference is 8) And if my suspicion is correct (that these are not the addresses of where the strings are in memory but just address of the pointers or something), how would I change my code to list the addresses of where the actual strings reside in memory? I am on a Windows 64 bit system using Code Blocks IDE, GNU GCC Compiler. If you need any more relevant info I will be happy to provide them. A: First, when printing addresses you should use the %p format specifier and cast the argument to void *. That being said, the addresses being printed are the addresses of where the strings are stored. If you look closely at the differences between the address of each pointer, you'll see that these differences exactly match the size of each string. String literals are typically stored in a read-only data segment, and in this case each of your strings happen to be consecutive in memory. If you were to print the address of each array element (each of which is a pointer) then you would see a difference of 8 between each of them.
[ "stackoverflow", "0052472976.txt" ]
Q: two column bipartite layout with igraph I'm trying to plot a bipartite graph, but with two columns; the function manual states that layout_as_bipartite() "Minimize[s] edge-crossings in a simple two-row (or column) layout for bipartite graphs." Trying with the example, I can only get two row graphs: library(igraph) library(dplyr) # Random bipartite graph inc <- matrix(sample(0:1, 50, replace = TRUE, prob=c(2,1)), 10, 5) g <- graph_from_incidence_matrix(inc) plot(g, layout = layout_as_bipartite, vertex.color=c("green","cyan")[V(g)$type+1]) # Two columns g %>% add_layout_(as_bipartite()) %>% plot() A: It appears that layout_as_bipartite only does rows, not columns, but it is easy to just modify the resulting layout. The layout is simply X-Y coordinates for the nodes, so to change from rows to columns, just switch X and Y. LO = layout_as_bipartite(g) LO = LO[,c(2,1)] plot(g, layout = LO, vertex.color=c("green","cyan")[V(g)$type+1])
[ "stackoverflow", "0061267108.txt" ]
Q: How to get the samAccountName from a csv file exported from Teams via powershell I have exported a CSV file from Microsoft Teams and got the data that I required after running this command: Import-Csv -Path "C:\TeamsUserActivity.csv" | Where-Object { $PSItem.DisplayName -notlike "*-*" } | Select-Object -Property DisplayName,'LastActivity (UTC Time)' | Sort-Object -Property 'LastActivity (UTC Time)' -Descending | Export-Csv -Path "C:\TeamsUsers.csv" This displays the following: DisplayName LastActivity (UTC Time) ----------- ----------------------- Tom Smith 2020-04-16T01:00:47Z Joe Bloggs 2020-04-16T01:00:47Z Harry Briggs 2020-04-16T01:00:47Z Jeff Kerry 2020-04-16T01:00:47Z Jane Briggs 2020-04-15T23:17:29Z Betty Smith 2020-04-06T02:56:51Z I need to remove the records under "LastActivity (UTC Time)" that are below the first date Anything below: 2020-04-16 Then run a Get-ADUser command on Active Directory to get the samAccountName for each record and put it into a third column. DisplayName LastActivity (UTC Time) UserID ----------- ----------------------- ------ Tom Smith 2020-04-16T01:00:47Z tsmith Joe Bloggs 2020-04-16T01:00:47Z jbloggs Harry Briggs 2020-04-16T01:00:47Z hbloggs Jeff Kerry 2020-04-16T01:00:47Z jkerry Been testing a whole bunch of methods to Get-ADUser from ActiveDirectory to return the samaccountname, it will only work for one record when I use static text Get-ADUser -filter { DisplayName -eq 'Tom Smith' } | Select samAccountName Not when I import the csv file and run a foreach loop for each row. The code I have tested, which I would think shuld return what I need is below: $in_file = "C:\PS\SessionData\sessionTMSct.csv" $out_file = "C:\PS\SessionData\sessionTMSctout.csv" $out_data = @() ForEach ($row in (Import-Csv $in_file)) { If ($row.DisplayName) { $out_data += Get-ADUser $row.DisplayName -Properties samAccountName } } $out_data | Select DisplayName,'LastActivity (UTC Time)',SamAccountName | Export-Csv -Path $out_file -NoTypeInformation Ends in the following error, pre row: Get-ADUser : The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:8 char:22 + $out_data += Get-ADUser $row.DisplayName -Properties samAccou ... + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Get-ADUser:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException A: You were nearly there. A custom field is what you need: Import-Csv -Path "C:\TeamsUserActivity.csv" | ` Where-Object { $PSItem.DisplayName -notlike "*-*" } | ` Select-Object -Property DisplayName,'LastActivity (UTC Time)',` @{l="samAccountName";e={$DN = $_.DisplayName; ` (Get-ADUser -filter {DisplayName -eq $DN}).samAccountName}} | ` Export-CSV -path "C:\ExportedTeamsUserActivity.csv"
[ "stackoverflow", "0003132249.txt" ]
Q: Need suggestions , making function to "put site offline" I am upto making a function for mine website's administrator to put it offline. But site must be some way accessible for administrators or mods. What way i should do it ? A: Somewhere in the includes: if($mainstance == 1){ if(strpos($_SERVER['REQUEST_URI'],'/admin/') === false) die("Site's down"); } This would make everything but the /admin/ directory inaccessible.
[ "stackoverflow", "0003244387.txt" ]
Q: Help needed to write SQL Query for SQL Logins I need to write SQL Query to Retrive the Following Settings of SQL Logins for SQL server 2005: 1.Enforce password policy 2.Enforce password expiration 3.User must change password at next login Thanx in advance. A: SELECT * FROM sys.sql_logins should give you the first two (is_policy_checked and is_expiration_checked columns) and you can use SELECT LOGINPROPERTY('sa', 'IsMustChange') to find if the user must change password at next login So putting it all into one query... SELECT name, is_policy_checked, is_expiration_checked, LOGINPROPERTY(name, 'IsMustChange') as is_must_change FROM sys.sql_logins
[ "stackoverflow", "0003546469.txt" ]
Q: Excel 2003 VBA fails to call SQL sproc with temporary tables I am trying to get resultset from SQL 2008 sproc into Excel 2003 using VBA. It worked for few sprocs but when I tried the one which uses temp table or table variable VBA fails with err 3704 "Operation is not allowed when the object is closed" on the following line: Sheet1.Range("A2").CopyFromRecordset rsMyDB If I comment out select into the temp table / table variable the very same VBA works just fine. The ADO I reference in the VBA module - "MS ActiveX Data Objects 2.8 Library" The SQL as follows: .Open "EXEC SprocWithTempTable '20100810', '20100811'" A: Add SET NOCOUNT ON at the beginning of the SQL proc and it should get through.
[ "math.stackexchange", "0003645342.txt" ]
Q: Zeroes of $2z^5-15z^2+z+2$ In preparation for qualifying exams I am working through old exams and came across the following question: Determine the number of roots, counted with multiplicity, of the equation $$2z^5-15z^2+z+2$$ inside the annulus $1\leq |z|\leq 2$. It seemed like a relatively straight forward application of Rouche's Theorem and was able to show there are two roots inside the unit disk, but when I was considering the boundary of $D(0,2)$, I couldn't seem to get a strict inequality in order to apply Rouche's Theorem. For example I chose $$f(z)=-15z^2+z+2$$ and $$g(z)=2z^5$$ but the best I could do was $|f(z)|\leq 64 =|g(z)|$ on $\partial D(0,2)$. Similar problems happened on different choices for $f$ and $g$. P.S. I am trying to use: If $|f|<|g|$ on $\partial D(0,r)$ then $|Z_{D(0,r)}(g-f)|=|Z_{D(0,r)}g|$ A: Rouche's theorem is typically about the interior of a region (although the conditions on the boundary prevent roots there too). In your case, you're interested in $|z|\leq 2$. So, let's take your splitting and use $|z|=2+\varepsilon$ for some $\varepsilon>0$. In this case, $$ |f(z)|\leq 15(2+\varepsilon)^2+(2+\varepsilon)+2=64+61\varepsilon+\varepsilon^2 $$ and $$ |g(z)|=2(2+\varepsilon)^5=64+160\varepsilon+160\varepsilon^2+80\varepsilon^3+20\varepsilon^4+2\varepsilon^5. $$ Therefore, on the circle of radius $2+\varepsilon$, $|f(z)|<|g(z)|$, so there are the same number of roots of both $f$ and $g$ in the open disk $B(0,2+\varepsilon)$. But, this is true fore every epsilon, so there can be no roots of $f$ outside the disk of radius $2$ (details hidden below). If there were a root of $f$ outside the disk of radius $2$, then let $r$ be the radius of this root. Consider two radii $2+\varepsilon_1<r<2+\varepsilon_2$. Applying Rouche's theorem to both of these values gives that $f$ has the same number of roots within disks of radius $2+\varepsilon_1$ and $2+\varepsilon_2$. This, however, is impossible since $f$ has a least one fewer root within the smaller disk whereas $g$ does not. For the disk of radius $1$, the $-15z^2$ should be a direct application of Rouche's theorem.
[ "stackoverflow", "0043760511.txt" ]
Q: language can not change in grocery crud I am using codeigniter with Grocery CRUD, I create a form with GC but the text in the required fields are in english and i want it in spanish. I read diferent documentation and I tray it but does not work. This is my controller $this->crud->set_table('test'); $this->crud->set_language('spanish'); $this->crud->set_subject('Test'); $this->crud->columns('id_test','test'); $this->crud->required_fields('test'); $output = $this->crud->render(); $data['contents'] = 'contents'; $data = array_merge($data, (array) $output); $this->load->view('template', $data); and in the view show like this The text in the required field Thanks in advance. A: After a month I solve the problem. I add a folder Spanish in system/language/ and inside a form_validation_lang.php. Although I change in application/conf/conf.php the default language for Spanish
[ "stackoverflow", "0008740254.txt" ]
Q: Sorting with DataView Hi All i got a problem with dataview that get data from datatabel (Col1 : ID,Col2: Time) and I'm sorting by Time in desc ... when the values for example {40.21,80.21,70.25,25.2} the dataview sorting them as I need but when one of values goes above 100 for example {40.21,80.21,100.25,25.2} the dataview always sort the highest number is the buttom, I don't know why .. This is a sample code Dim dt As New DataTable dt.Columns.Add("ID") dt.Columns.Add("Time") dt.Rows.Add(New String() {"1", "90.24"}) dt.Rows.Add(New String() {"2", "80.25"}) dt.Rows.Add(New String() {"3", "70.22"}) dt.Rows.Add(New String() {"4", "102.12"}) Dim dv As New DataView(dt) dv.Sort = "Time Desc" Thanks in advance ... A: You are sorting a String, so what have you expected? "10000" is lower than "2" because "1" is alphabetically lower than "2" just as "abbbb" would be lower than "b". You need to use the correct data-type(in this case i assume Double) to get the correct(numeric) sorting: Dim dt As New DataTable dt.Columns.Add("ID", GetType(Int32)) dt.Columns.Add("Time", GetType(Double)) dt.Rows.Add(1, 90.24) dt.Rows.Add(2, 80.25) dt.Rows.Add(3, 70.22) dt.Rows.Add(4, 102.12) Dim dv As New DataView(dt) dv.Sort = "Time Desc" Result: 4 102,12 1 90,24 2 80,25 3 70,22
[ "stackoverflow", "0006365326.txt" ]
Q: Formidable forms with WordPress being tripled I'm using the Formidable plugin to create forms in WordPress. However, when I insert the form onto a page, it is tripled - that is, three versions of the form appear, one after another. Has anyone had this problem? What could possibly be causing it? Could it be in my CSS or the form's CSS? Maybe in JavaScript? A: If it's not CSS as you say, use Firebug with Firefox, or in Chrome or Safari or IE8, use the developer tools to see what javascript is loading on your site, i.e., and what scripts, which are duplicates. Those tools will also show javascript errors in case some scripts - core WP scripts or plugin scripts - are colliding. If they're minified, look for a plugin that is doing that. If not, de-minify them: http://jsbeautifier.org/
[ "stackoverflow", "0014714360.txt" ]
Q: Implementing filters for ExtJS Tree grid with large amount of data I am working on a project which is using ExtJS 4.1 I need to implement a tree grid with filters. As per my understanding from reading various articles, blogs and SO posts, ExtJS does not provide filter mechanism with tree store and we need to write our own filtering mechanism. For filtering there are two approaches suggested: 1) Load the data into the tree grid and then show / hide the node based on filter conditions 2) Manipulate the store (copy the data and remove the record from the store) I tried first approach. It was working perfectly with the test data (around 30 nodes). But with the snapshot of production data, I was getting "Unresponsive Script" error in IE and FireFox. With Chrome it was working fine. Basically the production database has large amount of data, around 3500 records which form around 900 nodes in the tree grid. I suspect, once the tree store is populated, while rendering all 900 nodes into the tree grid, I get "Unresponsive Script" error. I am new to ExtJS and not sure what is the best way to tackle this problem. I would like to know, how does filtering works on grid. Can I replicate same filtering mechanism for Tree grid? Any suggestions to tackle this problem are welcome. A: I have found that loading child nodes on the expand events of each node is a decent way to minimize the dom interaction of the tree panel. That way when you filter, it's only going to need to filter the first level of the tree structure rather than the entire thing. I have it working in an access control management application right now that is handling about 350 resources in one tree panel and two others with about 75 nodes each that are linked together through events. There's no noticeable UI lag with that approach but I haven't scaled it up quite to your scale and it would depend greatly how many items were in the first level of your tree whether or not that could work for you.
[ "stackoverflow", "0055668190.txt" ]
Q: this.data.getUsers(...).subscribe is not a function fetching details from API and trying to list the same getting error while printing the list of users was able print with same code. following is my home.component.ts constructor(private formBuilder: FormBuilder, private data: DataService) { } ngOnInit() { this.data.getUsers().subscribe(data => { this.users = data console.log(this.users); } ); } following is my data services code getUsers() { return this.http.get('https://reqres.in/api/users'); } following is the html loop I am trying <ul *ngIf="users"> <li *ngFor="let user of users.data"> <img [src]="user.avatar"> <p>{{ user.first_name }} {{ user.last_name }}</p> </li> </ul> A: Re-Check this from your code Working Stackblitz component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'my-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { users; constructor(private data: DataService){} ngOnInit() { this.data.getUsers().subscribe(data => { this.users = data ; }) } } service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class DataService { constructor(private http: HttpClient) { } getUsers() { return this.http.get('https://reqres.in/api/users'); } } component.html <ul *ngIf="users"> <li *ngFor="let user of users.data"> <img [src]="user.avatar"> <p>{{ user.first_name }} {{ user.last_name }}</p> </li> </ul>
[ "stackoverflow", "0018389043.txt" ]
Q: Regular expression for x number of digits and only one hyphen? I made the following regex: (\d{5}|\d-\d{4}|\d{2}-\d{3}|\d{3}-\d{2}|\d{4}-\d) And it seems to work. That is, it will match a 5 digit number or a 5 digit number with only 1 hyphen in it, but the hyphen can not be the lead or the end. I would like a similar regex, but for a 25 digit number. If I use the same tactic as above, the regex will be very long. Can anyone suggest a simpler regex? Additional Notes: I'm putting this regex into an XML file which is to be consumed by an ASP.NET application. I don't have access to the .net backend code. But I suspect they would do something liek this: Match match = Regex.Match("Something goes here", "my regex", RegexOptions.None); A: You need to use a lookahead: ^(?:\d{25}|(?=\d+-\d+$)[\d\-]{26})$ Explanation: Either it's \d{25} from start to end, 25 digits. Or: it is 26 characters of [\d\-] (digits or hyphen) AND it matched \d+-\d+ - meaning it has exactly one hyphen in the middle. Working example with test cases A: You could use this regex: ^[0-9](?:(?=[0-9]*-[0-9]*$)[0-9-]{24}|[0-9]{23})[0-9]$ The lookahead makes sure there's only 1 dash and the character class makes sure there are 23 numbers between the first and the last. Might be made shorter though I think. EDIT: The a 'bit' shorter xP ^(?:[0-9]{25}|(?=[^-]+-[^-]+$)[0-9-]{26})$ A bit similar to Kobi's though, I admit.
[ "philosophy.stackexchange", "0000002775.txt" ]
Q: Is it possible to use intuitionistic logic in some everyday situations? Intuitionistic logic is the same as the usual boolean one apart from excluding the excluded middle, that is not(p) or p is not neccessarily true, so that boolean logic is a specialisation of the intuitionistic one. I take it evident that some parts of everyday reasoning uses classical boolean logic. Are there any everyday situations (i.e. not mathematical ones) in which intuitionistic logic is used? A: What does it mean to "use" logic? To reason in accordance with it? Is it evident we use classical logic? Is all our reasoning even formalisable as logical inference? Certainly not. Think about any reasoning that involves likely but uncertain events. This doesn't necessarily admit of an obvious translation into a simple logical framework. More esoterically, there are sentences which are "un-first-order-isable". That is, grammatical, meaningful English sentences that can't be formalised in a first-order logic. That is, you need to quantify over predicates to make them amenable to formalisation. The upshot of this is that it probably isn't possible to consistently use logic in everyday situations, whatever logic you use. So perhaps the question should really be: Can you replace classical logic in everyday reasoning with intuitionistic reasoning? Rephrasing: can every everyday use of classical logic be replaced with intuitionistic logic? And the answer there is: "of course not!". Think about all the times you do reason by using excluded middle. None of these inferences will work in intuitionistic logic.
[ "stackoverflow", "0008503436.txt" ]
Q: Can't add app to fanpage I have setup an App in dev. area. but I can't add it to a Fanpage where I'm admin. Normally there is this "View App Profil Page". This time it isn't. Any idea why it is like that? I'm admin from that page, but haven't made the page. Is that a problem? A: Try this link: http://www.facebook.com/dialog/pagetab?app_id=YOURAPPID&next=YOURDOMAIN The facebook documentation can be found here: http://developers.facebook.com/docs/appsonfacebook/pagetabs/
[ "stackoverflow", "0046172154.txt" ]
Q: db2,char for bit data,compare A field in java his type is GUID. In db2 his type is char for data type. I don't understand why (x'00345C9101600000018323B4F1311964BB' < x'00345C9101600000018323B4F1311964BB01') is false. is this not the comparation of Hexadecimal? Thanks for your help. A: Since the SQL data type is character, string comparison rules apply, so the shorter string is padded with spaces on the right. The ASCII code for the space character is x'20', which is greater than x'01'.
[ "stackoverflow", "0010288622.txt" ]
Q: I'd like to use jQuery to copy the file path in one input field and show it in a second field I'm using something like this but its not working for me. $(document).ready(function () { var content = $("#file_field").val(); $("input.browser_hidden").val( content ); }); Any suggestions? Even hard coding a value in the the second field isn't showing up. Here is the html I'm using: <div class="file_wrapper"> <input type="file" name="file_field" id="file_field"> <div class="file_wrapper_inner"> <input class="browser_hidden" value="something in here" type="text" /> <a class="button_browse" href="#">Browse</a> </div> </div> Basically what I'm trying to do is make the file input hidden (100% transparent) and when the input is clicked the file path is mirrored in the .browser_hidden input field. A: You cannot set a value in an <input type="file" /> with javascript. For security reasons. In case your 2nd field is not a file input, the code above still doesn't work for one reason - you are executing it only once, when the document is loaded. And at that moment the file input does not have a value. You should attach an onchange listener to the file input and then transfer the value. But I'm not sure if it is a good idea to do that. The value of the file input might not be consistent across browsers. For example in Firefox it contains the full path, while in Chrome it appears to contain only the filename (haven't checked if it is the case with js access). But anyway, the filename is available to the server side when submitting the form.
[ "stackoverflow", "0007315979.txt" ]
Q: Will FK validation in SQL Server always use the index specified in sys.foreign_keys? I can't find anything discussing the case where there are multiple possible indexes that could be used to backup a FK constraint. It seems from the test below that at FK creation time the FK gets bound to a specific index and this will always be used to validate the FK constraint irrespective of whether a new better index gets added later. Can any one point to any resources confirming or denying this? CREATE TABLE T1( T1_Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED NOT NULL, Filler CHAR(4000) NULL, ) INSERT INTO T1 VALUES (''); CREATE TABLE T2( T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id), Filler CHAR(4000) NULL, ) /*Execution Plan uses clustered index - There is no NCI*/ INSERT INTO T2 VALUES (1,1) ALTER TABLE T1 ADD CONSTRAINT UQ_T1 UNIQUE NONCLUSTERED(T1_Id) /*Execution Plan still use clustered index even after NCI created*/ INSERT INTO T2 VALUES (1,1) SELECT fk.name, ix.name, ix.type_desc FROM sys.foreign_keys fk JOIN sys.indexes ix ON ix.object_id = fk.referenced_object_id AND ix.index_id = fk.key_index_id WHERE fk.name = 'FK' ALTER TABLE T2 DROP CONSTRAINT FK ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK FOREIGN KEY(T1_Id) REFERENCES T1 (T1_Id) /*Now Execution Plan now uses non clustered index*/ INSERT INTO T2 VALUES (1,1) SELECT fk.name, ix.name, ix.type_desc FROM sys.foreign_keys fk JOIN sys.indexes ix ON ix.object_id = fk.referenced_object_id AND ix.index_id = fk.key_index_id WHERE fk.name = 'FK' DROP TABLE T2 DROP TABLE T1 A: Martin, I apologize that this isn't much of an answer, but since you made me curious as well, I did some digging. The information that I can share is: It is unlikely in current versions, including Denali, that an alternative would ever be considered in this situation.
[ "stackoverflow", "0019998454.txt" ]
Q: When to use: Java 8+ interface default method, vs. abstract method Java 8 allows for default implementation of methods in interfaces called Default Methods. I am confused between when would I use that sort of interface default method, instead of an abstract class (with abstract method(s)). So when should interface with default methods be used and when should an abstract class (with abstract method(s)) be used? Are the abstract classes still useful in that scenario? A: There's a lot more to abstract classes than default method implementations (such as private state), but as of Java 8, whenever you have the choice of either, you should go with the defender (aka. default) method in the interface. The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods. The good thing about this new feature is that, where before you were forced to use an abstract class for the convenience methods, thus constraining the implementor to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer. The original motivation to introduce default methods to Java 8 was the desire to extend the Collections Framework interfaces with lambda-oriented methods without breaking any existing implementations. Although this is more relevant to the authors of public libraries, you may find the same feature useful in your project as well. You've got one centralized place where to add new convenience and you don't have to rely on how the rest of the type hierarchy looks. A: There are a few technical differences. Abstract classes can still do more in comparison to Java 8 interfaces: Abstract class can have a constructor. Abstract classes are more structured and can hold a state. Conceptually, main purpose of defender methods is a backward compatibility after introduction of new features (as lambda-functions) in Java 8. A: This is being described in this article. Think about forEach of Collections. List<?> list = … list.forEach(…); The forEach isn’t declared by java.util.List nor the java.util.Collection interface yet. One obvious solution would be to just add the new method to the existing interface and provide the implementation where required in the JDK. However, once published, it is impossible to add methods to an interface without breaking the existing implementation. The benefit that default methods bring is that now it’s possible to add a new default method to the interface and it doesn’t break the implementations.
[ "gamedev.stackexchange", "0000034451.txt" ]
Q: android opengl-es spritesheet display number Whats the best way to display numbers on android with opengl using a spritesheet? I like to display the number "294" using the spritesheet: http://i.stack.imgur.com/wv5Zh.png A: I found what I was looking for. First I downloaded a game font: http://www.fontspace.com/triforce89/pipe-dream Second I found a tool which made me a spritesheet of a font: http://www.lmnopc.com/bitmapfontbuilder/ In my code then I just can write normal text and I can get the ascii codes of each character to calculate where its position on the generated spritesheet. Here is a fragment of my used code where I get the acsii codes of my "text": byte[] ascii = new byte[0]; try { ascii = text.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
[ "stackoverflow", "0048513017.txt" ]
Q: How do I get this math to calculate correctly I get this result: 8.01 - 8.0 #=> 0.009999999999999787 I want my answer to be 0.01. What can I do to fix this? How can I get this to happen? I guess this is float math. Is this due to floating point precision? A: You can use Ruby's arbitrary-precision decimal data type, BigDecimal: BigDecimal.new("8.01") - BigDecimal.new("8") # => 0.1e-1
[ "stackoverflow", "0012444015.txt" ]
Q: .focus(function) with Multiple chosen This question has been asked tons of times, however I don't see any answer for the 'multiple' variety: http://jsfiddle.net/queZ6/107/ When you tab INTO the box, i want to display an alert and capture the focus event. I'm basically wanting to change the highlighting for an element that surrounds each input, that follows along as you fill out the form. It's basically a signal to the user to easily see what field their on. I can't for the life of me figure out how to capture the focus event though tabbing into the box (or also clicking on it obviously). I dont see why this is difficult, considering you're typing INTO an input. Cant javascript see the newly created input (that youre typing into) and bind to that? JS is so confusing to me sometimes :S A: Update: While the old answer stated that you cannot bind into dynamically created elements(and this is still true to a degree), updates to the plugin in question have made this no longer a problem. While the plugin in question still has a problem of triggering the handler multiple times, in the case of an alert message being used, it is now possible to bind to those dynamically created elements thanks to the updates. All one must do in order to do this is bind, via .on(), to the chosen:showing_dropdown event on the original targeted select list. To solve the problem of the continuously created alert boxes, however, I decided to use underscore.js's .debounce() method, so it is only triggered once immediately every 1 second. The underscore library is by no means required, however you will need to have some sort of debounce function in order to get around that small quirk. var debouncedAlert = _.debounce(window.alert, 1000, true); $('#select').chosen(); $('#select').on('chosen:showing_dropdown', function(e){ e.preventDefault(); e.stopPropagation(); debouncedAlert('focused'); }); Working example: $(document).ready(function() { var debouncedAlert = _.debounce(window.alert, 1000, true); $('#select').chosen(); $('#select').on('chosen:showing_dropdown', function(e){ e.preventDefault(); e.stopPropagation(); debouncedAlert('focused'); }); $('button').click(function() { $('#select').trigger('chosen:open'); }); }); body { margin: 10px; } select { width: 200px; } <link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> <input type="text" value="Put your cursor here then Press Tab. Chosen will be focused!" style="width:100%"> <br> <select id="select" multiple> <option value="1">abc</option> <option value="2">def</option> <option value="3">ghi</option> </select> <br> <button>Press this button. Now chosen <b>will</b> be focused! :)</button> Old answer: No, it can't. Jquery's regular method of binding will not work with dynamically-created elements. In order to bind to those types of elements, you need .on(). $('.chzn-choices').focus(function(e){ e.preventDefault(); alert('focused!'); }); Would be changed to: $('#select_chzn').on('focus', '.chzn-choices', function(e){ e.preventDefault(); alert('focused!'); }); In this case, you are delegating the event to the container elemen, and then pointing it to your specific element. Working example
[ "stackoverflow", "0013207396.txt" ]
Q: Three Column Fixed-Width Web Layout and Quirky Refresh Behavior So I've been working on a basic site design for a client this evening (for reference:http://thomaswinchester.com/schaeferhvac/index.php) and I'm getting some odd results. The area of concern is a three-column content section in the middle of the page. When I initially uploaded the files to my server, the columns did not appear to work correctly. See the image below: So I thought it was just that the document was loading an old .css file or something, so I decided to hit ctrl+f5 to get an un-cached look. Everything seemed to work fine. See the image below: Which is exactly how I WANT it to look. So I made a couple back-end changes to the design and I hit refresh (f5) and the layout broke again. Then I hit ctrl+f5 and it was fixed. I have been continuing this pattern off and on for about 15 minutes now. My question is: why is this occurring? And which page is the "actual" page. For example, I visited the page from a laptop that had never been to the domain before, and it loaded the broken page. Sure enough, hitting ctrl+f5 fixed it! Then, hitting f5 broke it. At this point I should mention that I've tested this behavior with similar results in the latest versions of Chrome, FF, IE, Opera, and Safari for Windows (though Safari for Windows doesn't seem to have a ctrl+f5). I did some Googling and came upon a few leads: mostly explaining the difference between f5 and ctrl+f5. My biggest concern is that if it IS loading a cached file (even 20 minutes after the newest css files were uploaded), how can I stop that from happening in the future? Also, I won't post the code I'm using for the layout unless you specifically need it, because I'm not sure that's the issue. The page validates as XHTML Strict, but that doesn't mean I did everything right haha. If necessary, you can view the source code by clicking on the URL in the first paragraph. THANK YOU IN ADVANCE FOR ALL OF YOUR HELP!!! A: Yes this issue is must be about CSS caching. There are fews ways how to force browsers to load external files, they are all about making browsers think the file is updated: Add GET parameter to css file, such as time(), or something similar. <link rel="stylesheet" type="text/css" href="style.css?<?php echo time(); ?>" /> Add .htaccess directives to have additional headers for certain files (css files in example): <filesMatch "\.(css)$"> FileETag None <ifModule mod_headers.c> Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" </ifModule> </filesMatch>
[ "stackoverflow", "0038508008.txt" ]
Q: my sql statement for update doesnt work I am not able to execute an update statement. There seems to be some issue with my update statement. What I'm doing now is that I'm trying to update the duplicated email address and replace (update) with non-duplicated email. Therefore, in order to update, my SQL statement will check my database against the input and if ((firstname && lastname && dateofbirth) || (phoneNo && address) match what the user input, it will update the database; that is: update the duplicated email address with non-duplicated email, then remove all the duplicated email after the update has been executed. However, I'm not able to figure out what's wrong. Here is my update statement: try { System.out.println("it came here where filepart!=null"); DriverManager.registerDriver(new com.mysql.jdbc.Driver()); conn = DriverManager.getConnection(dbURL, dbUser, dbPass); // connects to the database conn = getConnection(); // constructs SQL statement stmt = conn.createStatement(); //sqll should be update String sql1 ="UPDATE registration SET emailAddress = ? where ((firstName = ? && lastName= ? && dateOfBirth= ?) || (phoneNo= ? && address= ?))" ; //Using a PreparedStatement to save the file PreparedStatement statement1 = conn.prepareStatement(sql1); System.out.println(firstName+"firstname"); statement1.setString(1, firstName); statement1.setString(2, lastName); statement1.setString(3, dateOfBirth); statement1.setString(4, phoneNo); statement1.setString(5, address); statement1.executeUpdate(); statement1.close(); String sql2="delete registration from registration inner join (select min(userId) as lastId, emailAddress from registration where emailAddress in ( select emailAddress from registration group by emailAddress having count(*) > 1) group by emailAddress) duplic on duplic.emailAddress = registration.emailAddress where registration.userId > duplic.lastId"; stmt.executeUpdate(sql2); //sends the statement to the database server // if (row > 0) { // getServletContext().getRequestDispatcher("/Message.jsp").include(request, response); // message = "You have successfully registered."; //} } catch (SQLException ex) { // message = "You have failed to registered. Please try again."; // ex.printStackTrace(); } finally { if (conn != null) { // closes the database connection try { conn.close(); } catch (SQLException ex) { // ex.printStackTrace(); //silent //message="You have failed to log in"; getServletContext().getRequestDispatcher("/FailedMsg.jsp").include(request, response); } } rs.close(); ps.close(); conn.close(); }} } A: Look at your sql string first: String sql1 ="UPDATE registration SET emailAddress = ? where ((firstName = ? && lastName= ? && dateOfBirth= ?) || (phoneNo= ? && address= ?))" ; In the above string you have 6 question marks (placeholders). But you are setting only the five of them and indeed in the wrong way. What you are doing is set firstname for emailAddress, lastname for firstName and so on. The first placeholder(?) is for emailAddress so you have to do as follows: statement1.setString(1, emailAddress); statement1.setString(2, firstName); statement1.setString(3, lastName); statement1.setString(4, dateOfBirth); statement1.setString(5, phoneNo); statement1.setString(6, address); Can this be a reason you cannot update correctly? You might also be getting some exception. You should look to the RAD console.
[ "math.stackexchange", "0002940412.txt" ]
Q: Quadratic variation and brackets, whats the difference? I am using Revous and Yor's book to learn about qudratic variations. For an arbitrary process this is defined via the following pointwise (in t) limit in probability $T^{\Delta _{n}}_{t} =\sum_{i=0}^{k-1}(X_{t_{i+1}}-X_{t_{i}})^2+(X_{t}-X_{t_{k}})^2$ But when when we define a similar concept for a local martingale we instead have that the random variables $\sup_{s\le t}\mid T^{\Delta _{n}}_{s}(M) - <M,M>_{s}\mid$ converging to zero in probablity. The latter looks stronger since it have to be uniform in the sequence of finite partitions. However is still looks like the same sum converges, just in a stronger sense. Yor do not however, call this the quadratic variation but he defines as the "increasing process of $M$". And furthermore for distinct local martingales he calls it the "bracket". Is this common pratice not to call this stronger limit the qudratic variation but something else? And if yes is there a particular reason for this? My own guess is that this might have something to do with the fact that this is only considered for martingales and not processes in general, making it a subclass of the more general quadratic varitaion. They do however use citation marks in connection to the following statement "Brownian motion is not a bounded martingale, nevertheless we have seen it has "qudratic variation" $t$". A: The usual notation for quadratic variation is $[\cdot]$. You may also define, for a local martingale $M$, a process that is sometimes called the conditional quadratic variation: $\langle M,M\rangle$ is the nondecreasing process such that $M^2-\langle M,M\rangle$ is a local martingale. Revuz and Yor are referring to this process as the "increasing process associated with $M$." And they're showing, in the same theorem (i.e., Theorem IV.1.8), that the "increasing process associated with $M$" is the same as the quadratic variation process. The quadratic variation process $[\cdot]$ and the bracket process $\langle\cdot\rangle$ are the same for continuous local martingales, so you don't have to worry about the distinction. But they may be different for discontinuous local martingales. See Angle bracket and sharp bracket for discontinuous processes