INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How do I use try() to load an image thumbnail in Rails Syntax question! How do I use try() with an image thumbnail? I am using Carrierwave and MiniMagick to manage image uploads in my Rails app. Each uploaded image also gets a :med_thumb thumbnail. I use this code to display an Avatar image when it is available -- <%= link_to image_tag(user.avatar.try(:image)), user %> How do I try() the :med_thumb of the image instead? I've attempted these lines without success: <%= link_to image_tag(user.avatar.try(:med_thumb)), user %> <%= link_to image_tag(user.avatar.try(:image, :med_thumb)), user %> <%= link_to image_tag(user.avatar.try(image(:med_thumb))), user %> Thanks in advance!
I discovered I can chain the try() function and use that to get to the image thumbnail. This line worked -- <%= link_to image_tag(user.avatar.try(:image).try(:med_thumb)), user %>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "ruby on rails, carrierwave" }
Changing dashboardHeader font color in shiny and keep logo I have the following code for mi UI: header <- dashboardHeader() anchor <- tags$a(href=' tags$img(src='logo12.png', height='40', width='40'), 'MiWaterNet') #anchor$children[[2]]$children <-tags$div( # tags$head(tags$style(HTML("h1 { color: red}"))),class='name') header$children[[2]]$children <- tags$div( tags$head(tags$style(HTML(".name {background-color: transparent}"))), anchor, class = 'name') dashboardPage( title="CFRE MiWaterNet", skin="black", header, dashboardSidebar(disable = T), dashboardBody() which gives this as a result: resulting image I want to be able to change the font (MiWaterNet) to yellow while keeping the logo as is. I have checked other questions, but those answers won't really fit with the way I structured the code.
Just add style as shown below: header <- dashboardHeader() anchor <- tags$a(href=' tags$img(src='YBS.png', height='40', width='40'), 'MiWaterNet', style = "color:red;") #anchor$children[[2]]$children <-tags$div( # tags$head(tags$style(HTML("h1 { color: red}"))),class='name') header$children[[2]]$children <- tags$div( tags$head(tags$style(HTML(".name {background-color: transparent}"))), anchor, class = 'name') ui <- dashboardPage( title="CFRE MiWaterNet", skin="black", header, dashboardSidebar(disable = T), dashboardBody() ) server <- function(input, output, session) {} shinyApp(ui = ui, server = server) ![output](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css, shiny, shinydashboard" }
Is it possible to get around PHP session checks? I've got a user login field that sets the session after they're validated on the login page: $_SESSION['user'] = $user; $_SESSION['id'] = $id; And on this PHP page I only want logged in users to access I have at the top: <?php session_start(); if (!isset($_SESSION['id']) && !isset($_SESSION['user'])) { header('Location: to home page--'); exit(); <-- Added thanks to comments } ?> Is this enough to keep user who have not logged in off the page? It's redirecting me back to the home page when I'm not logged in, but could people get around it? Edit: I've added the `exit();` now.
Users can bypass the HTTP `Location` header. Add a `die();` (Which is equivalent to `exit();`) right after to prevent any other content from being sent to the browser. if (!isset($_SESSION['id']) && !isset($_SESSION['user'])){ header('Location: to home page--'); die(); } * * * Other than that, note that a user can change the `PHPSESSID` cookie. If they find the id of an active session with the variables in question set, they will gain access to the page.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php" }
Problems calling a Function - "not defined" as the topics asks: How do you import/reference another already written (exterior) program within a main program? if I have a file named Squares.py with this inside of it: def squares(x): for i in x: return i*i squares(x) ...how do I tell an umbrella program to reference it? Do I use an import command at the top of the overhead program? How would I write it?
You won't be able to `import Squares` because `x` isn't defined on the last line def squares(x): for i in x: return i*i squares([23]) You need to fix that problem first The function itself probably doesn't do what you want. Is `x` supposed to be a `list` or an `int` or something else? Supposing you fix those problems, you should isolate the bottom part with a test def squares(x): for i in x: return i*i if __name__ == "__main__": squares([23]) This will prevent `squares` being called implicitly when you import the module You'll then be able to simply use: import Squares result = Squares.square([23]) or from Squares import square result = square([23])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Is there a purpose for this slapping at the top of reps? This question led me to this video, apparently of Dejan "STIPKE" Stipic, doing various feats of bodyweight strength. In the pull-ups, dips, and squats, there's a fellow beside him who gives a light slap to the limb in action at the top of the motion. You can see it being done with some of the other background athletes as well. Is this a standard thing to do when spotting someone in bodyweight movements? Does this do something physical like help the muscle to relax (seems unlikely to me, since they only seem to be tapping one side) or is this just a way to let the person know they've hit full extension (possibly hard to tell on multiple reps due to muscle engorgement causing numbness)?
They are acting as counters for competition. The person beside them is a judge, and the tap is to let them know that they completed a successful repetition, usually accompanied by a verbal count of the reps. There are some types of slaps that are used in boxing and other similar training, to get the muscles used to impact and the pain sensation so that it can be ignored, but this is just a "hey, that's one" type of tap.
stackexchange-fitness
{ "answer_score": 5, "question_score": 5, "tags": "bodyweight exercises" }
How to say “dudes rock” in Latin? I want to translate "dudes rock" into Latin. Google Translate and working with synonyms got me to _viri sunt prodigiosus_ (“men are amazing” more or less?). But I'm wondering if there’s an idiom or expression that would translate more felicitously. “Men can be charming in their simplicity” (i.e. doing something possibly juvenile yet wholesome) is maybe close to the sense of the expression.
The adjective _prodigiosus_ means "unnatural, strange, wonderful, marvellous, prodigious". Not a perfect fit, but certainly an option if you like the tone. If you want to use that, it should be in the plural form _prodigiosi_ instead. Google Translate is horrible with Latin and is not to be trusted. A nice simple option would be to say: _**Valent viri**_ , "men are strong". While the literal meaning is different, I think that the Latin _valere_ corresponds pretty well to the English "to rock" in this sense. Something related that might be worth considering is the famous hexameter verse: > _Sunt pueri pueri, pueri puerilia tractant._ > Boys are boys, boys do boyish things. This is a nice way to refer to juvenile behavior in men. I think this works best with the word "boy" instead of "man", not only because that is the original phrasing.
stackexchange-latin
{ "answer_score": 3, "question_score": 1, "tags": "english to latin translation, idiom" }
how to get rid of bullet in haml ul so here's an ul in haml that I have .content .testing .testing-ul2 %ul %li a b c .testing-ul2 %ul %li d e f • a b c • d e f how do i get rid of the bullet points in sass?
Valid CSS is not valid SASS, it's valid SCSS. For valid SASS, you need to get rid of the curly braces and the semicolons. Here's what you want: .content .testing ul list-style: none
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, sass, haml" }
Run a program using NVIDIA dedicated GPU only when plugged into power Under 3d Settings in NVIDIA's control panel, it allows me to choose whether specific programs always start using the integrated graphics on my CPU or the dedicated GTX 960M. Can I create a condition where the program opens with my GPU when my laptop is plugged into AC by default, and the same program opens with integrated graphics when it is on battery power by default?
Unfortunately, the requested configuration is unsupported. The only company that allows such setup options would be AMD's Enduro implementation which allows GPU selection based on power supply.
stackexchange-superuser
{ "answer_score": 2, "question_score": 3, "tags": "windows, laptop, battery, nvidia graphics card, switchable graphics" }
semi automatic prizing system UX/UI Am working on a project where system determines certain number of winners based on their scores. They are marked by system as gold, silver and bronze. The admin must be able to manually select winners after certain numbers of winners that system has picked. So, I was thinking to generate users list and implement following method * provide 3 check box for making it gold, silver or bronze against each user * provide dropdown gold, silver and bronze to select against each user list. Both methods works, but I am hesitant to use both methods. Can anyone suggest any better UX for making such semi automate process? Or least, which is the best practice out of the two methods I have specified? Tnx
When you select one and only on out of three options you should use radio buttons. You see all the options at once (apart from a dropdown) and you can select only one item (apart from a checkbox). !mockup download bmml source - Wireframes created with Balsamiq Mockups
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "multi selection, choices" }
Why when I install my apps APK on Physical Android Device says App Not Installed Attention great developers. I have hit a snag. I have built this application in flutter and has been in development for over a year. When I run the command flutter build apk the apk file is built and located in the Outputs file within the build. When I transfer the apk to my device and install it gives a App not installed. How can I debug this or has anyone had this issue and knows how to solve it. I am worried that it might have something to do with my flutter_google_maps pacakge. Anyone help and guidance is much appreciated. I will attach a screen shot of the error. Cheers![enter image description here](
After another day of debugging I have found the issue. The problem was the assets folder with the images. Once I removed all images not being used the apk install worked. Hopefully this helps others. Cheers Everyone for the contributions
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, flutter, apk" }
Connect to OracleDriver I have this code : Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "user", "password"); What configurations do i need to make in my system/administrative tools for this to connect to my database ? I have Oracle 11g installed and running in my system.
First of all you must add `ojdbc6.jar` to library folder and try again to connect to database,I think your url is false.oracle connection url is like that `jdbc:oracle:thin:@" your ip ":1521:`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "java, oracle, jdbc" }
How can I split the arrow in the following diagram? I got a help on drawing this diagram from here \documentclass{article} \usepackage{tikz} \usetikzlibrary{cd} \begin{document} \[\begin{tikzcd} & P \ar[dl, dashed, "\tilde{f}" '] \ar[d, "f"] \\ A \ar[r,twoheadrightarrow,"g" '] & B \arrow[r, twoheadrightarrow] & 0 \end{tikzcd}\] \end{document} But how can I split the arrow as shown below: ?![enter image description here](
![enter image description here]( That is your third very similar question ... so I estimate that it is time, that you read documentation for the `tikz-cd`package and make yourself more familiar with this package ;-). You need to insert new row between existed: **Edit:** Considered is @campa's comment: \documentclass[border=3mm, varwidth]{standalone} %\documentclass{article} \usepackage{tikz-cd} \usepackage{mathtools} \begin{document} \[ \begin{tikzcd} & F(S)\mathrlap{{}= P\oplus K} \ar[ddl, dashed, "\tilde{f}" '] \ar[d,"\pi"] \\ & P \ar[d,"F'"] \\ % <--- M \ar[r,"\varphi" '] & B \ar[r] & 0 \end{tikzcd} \] \end{document}
stackexchange-tex
{ "answer_score": 5, "question_score": 2, "tags": "tikz arrows, arrows, tikz cd, commutative diagrams" }
CodeIgniter: Anchor or a href? Whats difference in using `anchor` in CodeIgniter instead of using traditional html `a href` tag? Should I use anchor in Views or HTML a href? Thanks
I honestly feel like there is minimal difference. I personally use html anchor because it uses more html. If you want to add context path inside a view, just do this: <a href="<?=site_url('path/name');?>">anchor</a> However, one of the advantages of using codeigniter anchor is that, if you want to build contents dynamically: for($i = 0; $i < $count; $i++) { $anchors[] = anchor('path/name', 'anchor'); } is easier than for($i = 0; $i < $count; $i++) { $anchors[] = '<a href="'.site_url('path/name').'">anchor</a>'; } Do you see the difference? :)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "codeigniter" }
If $f(x+y)=f(x)\cdot f(y)$, then $f(x)=e^{ax}$ I'm trying to prove this question: > Let $f:\mathbb R\to \mathbb R$ a function such that $f(x+y)=f(x)\cdot f(y)$, $f(0)=1$ and $f'(0)=a$. Show that $f(x)=e^{ax}$, for every $x\in \mathbb R$. First of all I'm trying to prove that this function is positive, but even that it's difficult to me, I know that this function is never zero, because if there is $y \in \mathbb R$ such that $f(y)=0$, then $f(x-y+y)=f(x-y)\cdot f(y)=0$, then $f(x)=0$ for every $x\in \mathbb R$. I need help to prove the positivity and hints to follow from that point. Thanks a lot in advance.
for positivity: $f(x) = f(\frac{x}{2} +\frac{x}{2})=f^2(\frac{x}{2})\geq 0$ hint for the problem: take $g(x) =\ln f(x)$ then $g(x+y) =g(x) +g(y)$ so $g(x) =ax$
stackexchange-math
{ "answer_score": 5, "question_score": 5, "tags": "real analysis" }
why the scala programe created by singleton object doesnt require a static main method? I am new to scala ,and worked with java previosly.On studying i found that we can create a singleton object like given below object Hello{ def main(a:Array[String]){ println("hello user") } } **If Scala uses JVM then why the scala programe created by singleton object doesnt require a static main method?** I know its a very basic question but i am a beginner. and also if anybody can suggest me some docs online to study scala. Thanks in advance.
Methods of singleton objects get translated into static methods (among other stuff)strong text. So you actually do have the equivalent of a static main method. Have a look at the generated class files and you will see.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "scala, static, jvm, program entry point" }
What are best practices for login and passwords when there is only one user? I feel like there's a lot of information for developers on protecting user information when there are multiple users who each need to have their passwords stored. But what if there is only 1 user? A sign up page wouldn't be needed as you could set the username and password yourself. I'm basically making a nicer view for database stuff that is easier to get information from for someone who doesn't know SQL. But where do I store the username and password? I am using Node and I know you can use bcrypt but surely that's only useful if you're storing different user's passwords into the db and hashing them when you save it into the db. So how do I store the information securely? Does it not matter? Shall I just store it in the database and pull it when comparing to the password? Can I save it in the app.js file? Would be really helpful to know.
Given that you only have 2 reception staff accessing this website, I think the simplest solution for you would be to use Basic Authentication. It does not require you to create a database, or handle user accounts in a database. You can read more about it: < If your site runs on Apache, its super easy to setup using a `.htaccess` and a `.htpasswd`. As usual, make sure your site is https, otherwise the credentials will be sent in cleartext. If the sensitivity of the data changes, or if the power associated with this account changes you should revise this authentication method accordingly.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, authentication, web applications, passwords" }
How to list all mounted disks and their mount path location on FreeBSD? On FreeBSD I wish to see all mounted disks and all of their mount locations. For example this shows my disks. [root@freenas] ~# sysctl kern.disks kern.disks: xbd2 xbd1 ada0 [root@freenas] ~# Now I have the disks but I don't know where they are mounted.
You can use the mount command > The system maintains a list of currently mounted file systems. If no arguments are given to mount, this list is printed. Then parse the output looking for the disks you are interested in.
stackexchange-serverfault
{ "answer_score": 2, "question_score": -2, "tags": "freebsd, mount" }
Expected value of $E[Z^2 | Z^3]$ Assume we have a probability space with $\Omega = [-\frac{1}{2}, \frac{1}{2}], \; \mathcal{F} = \mathcal{B}([-\frac{1}{2}, \frac{1}{2}])$, P being the Lesbegue measure and two random variables given by $$ X(\omega) = \omega^2 \; and \; Y(\omega) = \omega^3 $$ How do you calculate $E[Y|X] \; and \; E[X|Y]$ in this specific case. I started by calculating the densites of both random varibales which should be $f_X = \frac{1}{2\sqrt{x}}$ and $f_Y = \frac{x^{-\frac{2}{3}}}{3}$ unless I didn't make a mistake there. But now I'm stuck trying to calculate the conditional densites of $f_{X|Y}$ and $f_{Y|X}$. Is an explicit calculation the right way to do it in this case? Or is there another way to obtain the answer by making use of the properties of the conditional expectation? Thanks in advance for any help with this problem.
Hints: $\omega \to \omega^{3}$ is a homemomorphism so $\sigma (Y)$ is nothing but the Borel sigma algebra of $[-1,1]$. Hence $X$ is measurable w.r.t. $\sigma (Y)$ which shows that $E(X|Y)=X$. $E(Y|X)=0$ by symmetry.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "probability theory, conditional expectation" }
Calculate probability rolling a die $10$ times I you roll a die $10$ times: What is the probability of getting at least a one and at least a two? I tried to use the complement rule and find the probabilities of not getting a one and not getting a two. As I have four numbers left the probability is $= 1 - \frac{4^{10}}{6^{10}} = 0.9826$ . But the right answers is $0.6943$ Thank you.
$$\scriptsize\rm P(1.2)=P((1'+2')')=1-P(1'+2')=1-[P(1')+P(2')-P(1'.2')]=1-\left[\frac{5^{10}}{6^{10}}+\frac{5^{10}}{6^{10}}-\frac{4^{10}}{6^{10}}\right]=\frac{6^{10}-2\times5^{10}+4^{10}}{6^{10}}\\\\\approx \color{red}{0.6943}\color{grey}{30364...}$$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "probability" }
What does a 'dotted-line' cloud icon in the iCloud file browser represent? What does this "dotted-line" cloud icon next to a file in the iCloud file browser mean? !iCloud file browser, showing cloud icon This is a plain-text file saved to iCloud from Byword, and it refuses to sync to my iPhone. But I'm having the same problem with subsequently-created files in Byword, and they don't feature this icon.
A dotted-lined iCloud icon means that it is waiting to be uploaded (or it is currently uploading). Although this KB article applies to iTunes Match, it might help you understand this icon better: < As for Byword's syncing issues, if it is not finished uploading, it won't be accessible by your iPhone. Are the subsequent documents also plain-text? This Byword support FAQ says that Byword's iOS app currently does not support RTF files (rich-text).
stackexchange-apple
{ "answer_score": 7, "question_score": 6, "tags": "macos, icloud" }
Why does file and folder icons disappear when I select vscode-icons extension as my preferred File Icon Theme in Visual Studio Code? I have installed **vscode-icons** extension. And set this as my preferred File-Icon Theme using **File** -> **Preferences** option in Visual Studio Code. All folders and files icons disappear. The extension is installed properly and I could see all the icons in the installed extension folder. But when I switch back to **Set(Visual Studio Code) theme** , all the folder and file icons are visible. I have tried all possible options like install and uninstalling packages, libraries, extensions and VS Code itself. Please find below screen shot, ![enter image description here](
I am able to see folder and file icons after installing one more alternative extension called **file-icons.file-icons**. Earlier I tried at least 2 extensions. But to my surprise, none of them worked. So I assumed that, something wrong in the VS Code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio code" }
Deploy Adobe Pro X GPO Issues I am trying to deploy adobe pro x extended to clients machines. The deploy is working fine except when you launch Adobe, it asks to enter the serial number. I have used the adobe customization x wizard and generated the MSI and MST files and they include the serial number but no matter what it still asks for the serial number. Anyone know if there is a step I am missing here? I go into GPO, computer, software installs and new package and point it to the msi that the wizard has created but it seems it is not processing the MST file for some reason, its set to install english only and still installs as english french and german. Any help would be great. Thanks.
Fixed this myself...was a missed step and didn't put the serial number in the ABCPY.INI file in the same dir as the MSI file.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "group policy, adobe, deployment, adobe acrobat" }
Removing seconds from UnixTime Value So I have a unixtime datetime stamp. For arguments sake, lets say it's now at 23:49:24 on 21/02/2011 (GMT). This would be: > 1298332164 Now, is there anyway to remove the seconds component from this? I'm writing this in Obj-C so currently I have: NSDate *todayNow = [NSDate date]; int unixtimeNow = [todayNow timeIntervalSince1970]; And would end up with: > 1298332140 Thanks
What about 1298332164 / 60 * 60 ?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, unix timestamp" }
Ist "Quereinsteiger" eine abwertende Bezeichnung? I war heute bei einem IT-Vortrag, wo der Referent unter anderem meinte, dass man im Marketing-Bereich das Wort "Quereinsteiger" meidet, da es eine abwertende Konnotation habe. Ich persönlich finde es nicht so. Zwar wird damit einer ohne passenden Abschluss auf seinem Gebiet gemeint, ich habe aber das Wort überwiegend im positiven Kontext gehört ("er hat keinen Abschluss, dennoch hat er viel erreicht). Wird das Wort auch für negative, abwertende Bezeichnung eines, der keinen (richtigen) Abschluss hat verwendet? Was ist daran abwertend?
Man findet für jeden Begriff eine abwertende Bedeutung, vor allem wenn er sarkastisch verwendet wird. Manche Leute machen sich dann zu viele Gedanken. Ich bin selbst Quereinsteiger in meinem Beruf. Ich bezeichne mich auch selbst als solchen. Das einzige "abwertende" ist, dass man ein geringeres Gehalt bekommt, als Leute die in diesem Beruf ausgebildet wurden. Ich bezweifle allerdings, dass sich das mit einer anderen Bezeichung ändert. Also, nein, ich kenne keine negative Verwendung des Wortes (außer ironischen/sarkistischen Bemerkungen, die es bei jedem Begriff gibt).
stackexchange-german
{ "answer_score": 14, "question_score": 16, "tags": "word usage, connotation" }
Parsing error (android) no element found This is the code <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:background="@drawable/quickscreen" /> It will not generate R.java because of it. Any ideas?
If you're using Eclipse, try disabling "Build Automatically", and then cleaning your project. Sometimes I even need to restart Eclipse before building the project again.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android" }
Which is faster xsl:function or xsl:call-template I have to process large data and confuse between use of `xsl:function` or `xsl:call-template`. Just want to know which is faster and appropriate to use. <xsl:variable name="tabledata"> <xsl:copy-of select="table:table_process(.)"/> </xsl:variable> or <xsl:variable name="tabledata"> <xsl:call-template name="table_process"> <xsl:with-param name="table_data" select="."/> </xsl:call-template> </xsl:variable>
I think you would have to measure performance with a particular XSLT processor and a particular set of XML input and XSLT code. I would prefer to use `<xsl:variable name="tabledata" select="table:table_process(.)"/>` as the most compact and elegant XSLT 2 notation, it might also perform better or at least consume less memory as that way you don't need to copy the result of the function call but directly use it. It all depends on what the function does exactly and whether you need to copy its result or not.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "xslt, comparison, xslt 2.0" }
How can I get a list of a Page's events? I'm new to the FB graph and having trouble getting a collection of Events associated with a Page. Is there any way to get a list of all the events created by a Page? I've tried these unsuccessfully: ` This isn't a valid query. ` Returns an empty set, I think because it's looking for events this Page is attending (rather than those it has created). Thanks.
` is the correct way to get a list of events that was created by a page. You need a valid access token to return the events list for a page. Visit < test this process. I'm seeing a bug with events created after Monday, April 23 where all events are not being returned by a valid Graph API or FQL call. See this post for more info: Graph API / FQL Does not return all events for a page I don't have bug creating privileges on < If you're seeing the same issue and can post a bug, please do so.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 9, "tags": "events, facebook graph api" }
Найти в строке 16 цифр и извлечь их Есть строка с текстом, среди этого текста есть цифры, которые следуют друг за другом. Строка может быть таких вариантов: текст текст 1234 5678 1234 5678 текст текст текст 1234567887654321 текст текст текст 1234-5678-1234-5678 текст Как извлечь только эти цифры, без лишних символов (без пробелов и тд.)? Извлечь просто цифры из строки не вариант, так как там могут быть ненужные, например `текст 25 текст 1234 5678 1234 5678 текст`. То есть нужно чтобы извлекало только 16 цифр, которые следуют друг за другом. Буду благодарен за помощь.
Можно рассмотреть как вариант (см. демо регулярного выражения): $content = ' текст текс 1234-5678-1234-5678 текст текст текст 1234 5678 1234 5678 текст '; preg_match_all('/(?:[-\h]*\d){16}/', $content, $matches); $matches = array_map(function($x) { return preg_replace('/\D+/', '', $x); }, $matches); print_r($matches);
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Display loading/processing while processing using CSOM My current implementation includes following, User adds an item, once saved it is redirected to the display form of the same item. I have implemented this requirement using below steps. 1. On PreSaveAction() redirect to an intermediate form by passing some values using querystring. 2. On intermediate page i use CSOM to retrieve the ID of latest saved item and again redirect to the Actual item Now this takes some time while processing and i want to show loading status using jquery or any sharepoint based solution. Something like this would be great : !enter image description here Can anybody please suggest me how can i do it?
you can use SP.UI.ModalDialog.showWaitScreenWithNoClose If you want to use the 'Waiting' dialog function OpenDialog(targetUrl) { var waitScreen = SP.UI.ModalDialog.showWaitScreenWithNoClose("Loading", "Please wait"); var options = SP.UI.$create_DialogOptions(); options.url = targetUrl; options.autoSize = true; options.allowMaximize = false; options.allowClose = true; options.args = waitScreen; //pass the reference of the wait screen to the dialog SP.UI.ModalDialog.showModalDialog(options); } $(document).ready(function(){ var waitScreen = SP.UI.ModalDialog.get_childDialog().get_args(); waitScreen.close(); }); follow this <
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 1, "tags": "sharepoint online, client object model, jquery" }
Can I reset MPI instance in c++? I wrote a sort algorithm with MPI. It is recursive mergesort, left child sorts half the array within the same process as the parent whereas right child gets a new process and receives half array from parent then sends the sorted array back to parent. Now I need to sort a bunch of integer files. Here is my current design: int main() { MPI_init(); if(my_rank == 0) { foreach data file { sort_mpi(array); } } else { MPI_Recv(right_array...); sort_mpi(right_array); MPI_Finalize(); } MPI_Finalize(); } With this code, the first file gets sorted and moves on to next file. However in the second interation of the for loop, it only stays in rank 0 and never goes to rank 1. It should be ideal if I can reset the MPI instance before going to the next file. Is there a way to do that?
You do not need to reset the MPI - you need to have a point where all the instances are "freezing" in, and continuing only after all the instances got to this point... Since it's homework - I won't tell you the method name, but I do Hope it helps. Think about the design of the sort, and what state you need all the nodes to be in, when, and how to enforce it. This example might be helpful (hoping it does not solve your homework, but just leading you in the right direction) Bitonic Sorting with MPI
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, mpi" }
Is it safe to leave stuff connected to the GPIO pins when the Pi is powered off? I am asking about stuff that would be within the normal operating limits when the Pi is on, i.e. 3v3 level voltages at small currents, when the pi is shut down (but still powered), and also when the Pi's power has been completely removed (and thus it's ground would be floating relative to the input signals) specific case: it seems like the l293d (or sn754410 alternative) motor chip tends to "leak" small amounts of current when powered on - do I need to completely disconnect it from the Pi when I want to shutdown the Pi? (yes, one solution would be to power it from the pi such that it shuts itself down when the pi power is removed, but I am curious what would happen and if it's safe)
When the pi is at halt but still powered you're fine. With no power to the pi, I would recommend making sure that there is no power leaking into the GPIO. It _probably_ won't toast things, but the GPIO _do_ connect **directly** to the Broadcom SoC with no buffering. So there _is_ a chance of breakage.
stackexchange-raspberrypi
{ "answer_score": 3, "question_score": 2, "tags": "gpio, safety" }
Different filename to class name yii In yii 2.0 for the class **is it possible** to use like below where Home is the name and Common is the folder And then on the filename just have Home.php <?php namespace app\controllers\common; use Yii; use yii\web\Controller; class HomeCommonController extends Controller { public function actionIndex() { echo "From the Common Home"; } } Then the url would be I am trying to see if possible to get same way opencart finds there controllers.
No, it's not possible without overriding core classes. Yii2 do not perform search for folder names in controller class name. I do not recommend to go against framework standards and conventions. Each one has their own, better accept it and adapt to it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "yii, yii2" }
How do I read a cell in a google spreadsheet in google scripts targeting the spreadsheet id I need help reading a specific cell in Google scripts by using the spreadsheet id or key. I've been trying for hours without any luck. i'm using this script at the moment but it doesnt read the spreadsheet key ` function getData() { var sheet = SpreadsheetApp.getActiveSheet(); var data = sheet.getDataRange().getValues(); Logger.log('Surname: ' + data[4][1]); } `
If you are trying to access a spreadsheet by ID you need to use: var ss = SpreadsheetApp.openById("abc1234567"); Logger.log(ss.getName()); To get the ID, open the spreadsheet and look in the address bar of the browser. The ID of the spreadsheet is at the end. ID is Here/edit#gid=123abc
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "google apps script" }
Replace consecutive duplicate letters with a single letter How do I create a function in SQL Server 2017 that identifies when a string contains duplicate consecutive letters (a-z) and replaces those duplicate letters with a single instance of that letter? Here are some examples of what should happen: CompanyAAABCD -> CompanyABCD CommpanyABYTTT -> CompanyABYT Company11111 -> Company11111
alter function fn_RemoveDuplicateChar(@name varchar(200)) RETURNS VARCHAR(200) as begin declare @strPosition int=1; declare @strlen int=0; declare @finalstr varchar(200)=''; declare @str varchar(200)=''; declare @fstr varchar(200)=''; select @strlen = (select len(@name)) while @strPosition<=@strlen begin select @fstr = SUBSTRING(@name, @strPosition, 1) select @str = SUBSTRING(@finalstr, len(@finalstr), 1) If @fstr <> @str or ( ISNUMERIC(@fstr)=1 and ISNUMERIC(@str)=1) set @finalstr = @finalstr + @fstr set @strPosition =@strPosition+1 end return (select @finalstr) end go select dbo.fn_RemoveDuplicateChar('CompanyAAABCD') select dbo.fn_RemoveDuplicateChar('CommpanyABYTTT') select dbo.fn_RemoveDuplicateChar('Company11111')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "sql, sql server, tsql, duplicates, sql server 2017" }
Ray local cluster web-ui shows 0 workers Launching the ray head node with web-ui: ray start --head --redis-port=6379 --include-webui --num-cpus=0 when I navigate to the UI (after I start training) I don't see any workers being used. Can someone confirm that this works for them? Thanks.![enter image description here](
This is the ui today (Aug, 2019). The docs are outdated with the UI pictures it seems. Just in case anyone in the future has similar question.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, ray" }
How can i generate sample XML from DTD? > **Possible Duplicate:** > How to generate sample XML documents from their DTD or XSD? Please let me know if there is way in java to generate sample XML from DTD.
Generating sample XML from XSD or DTD in Eclipse
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, xml, dtd" }
Alignment issue with icon position in mobile web There is an alignment issue in the positioning of inbox and achievements dialog box in mobile web. The normal position of the inbox and achievements dialog icons. > !enter image description here When clicking on those the icon position is centralized. > !enter image description here > > !enter image description here
This is building now. Mobile doesn't absolutely position its topbar dialogs, so it didn't take kindly to the modal being shoved between the two elements.
stackexchange-meta
{ "answer_score": 5, "question_score": 6, "tags": "bug, status completed, design, mobile web, achievements dialog" }
discord.py not able to delete author messages I am using Discord.py version 1.0.0. I am trying to write an echo command that, when given a message, will echo the message and delete the command from the chat. Here is an example of my code. client = Bot(description="Test bot", command_prefix="&", pm_help = False) @bot.command(pass_context=True) async def echo(ctx): await client.send(ctx.message) await client.delete_message(ctx.message) The errors I receive tell me that ctx does not have an attribute called "delete_message". I have tried with just delete(). I have looked at others having something of a similar issue, however the solutions did not help me. Any suggestions would be greatly appreciated.
In discord.py/rewrite (1.0.0), Delete is a method on the message, not on the client. This is the same for every function affecting a message/channel/guild etc. Instead of doing await client.delete_message(ctx.message) try doing await ctx.message.delete()
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python 3.x, discord, discord.py" }
Why is Ruby not part of RHEL/CentOS? It seems that Red Hat doesn't include software that is made by a company. OpenVPN and MongoDB come to mind. Perl and Python are in RHEL/CentOS. What could be a reason Ruby isn't in RHEL? **Update** RedHat have now announced Red Hat Software Collections 1.0 which exactly addresses this need.
I don't use distribution rubies. It is best to compile them from the latest version or whatever version you use, those packages in the distro repositories are frequently outdated. Check out RVM or RBENV. I guess why they are not could be interesting, but probably not a question StackOverflow at large is going to like.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "ruby, linux, centos, rhel" }
Reading Bios With C# i am looking for reading of bios with c#,VS-2005 with full features and contents is there any best tutorial for that.
There's some information available via Google for this. It appears that this one.aspx) is a good starting point.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c#" }
Sort files and folders in the same way in Windows Explorer - sorted by names I just want to **see files and folders** (sorted/grouped by their name) in a list that does **NOT separate files and folders**. I also don't want to order by `date modified` like here. I already tried several solutions. But unfortunaletly non worked. And I don't want to use grouped by that splits it up into A-G... and so on. Antelope[dir] Antelope.txt Badger[dir] Badger.txt .... Zebra[dir] Zebra.doc Questions that also didn't help me out: * Sort files and folders together by name (not by type)? * Sorting folders in Windows Explorer? * Show Files and Folders Sorted by name NOT Folders First then Files
**xplorer²** was able to solve this issue. Anyway I'm still interested in doing this in the Windows explorer. Just wrote a German Tutorial about this and xplorer² (< It should be easy to understand also for non-Germans. ;)
stackexchange-superuser
{ "answer_score": -1, "question_score": 0, "tags": "windows, windows explorer, sorting" }
I have a services table,service has a price, in new order should i save total amount of order or calculate every time services table do i need to save order amount in orders table or i can calculate everytime from services table against each order ID?
Just create a view of the orders table joined with the services table with the calculation you want against each orderID? If you want more details on how to do this then include the minimal data to help out: Table names, column names, example data. but if you know how to create views then this should suit your needs.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sql, .net, database" }
Post and excerpt I have the following piece of code which outputs a long article: `<?php the_content(); ?>` I am trying to show only an excerpt of the article (the first 29 words), strip out the HTML and add a "...more" at the end. <?php substr(the_content, 29) ?> I have tried this but it has no effect on the length. Any help? Thanks
What you need is the_excerpt <?php the_excerpt(); ?> //and you could check the doc how to set the length.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, wordpress, substr" }
Verbose mode of Git pull from origin Is there a way to show all commits like a "verbose" or "debug" function when using `git pull origin master`? I just want to see what changes are committed.
I use `git log` a lot. Try this out: git log --graph --all --decorate Gives a great overview.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "git" }
OutOfMemoryException in Custom Serialization - JSON.NET I created my own Custom Serialization method with JSON.NET, the method looks like : public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var Obj = (xObject)value; writer.WriteStartArray(); foreach(var TargetObject in Obj) { writer.WriteStartObject(); writer.WritePropertyName(TargetObject.Data.Key); writer.WriteValue(TargetObject.Data.Value); writer.WriteEndObject(); } writer.WriteEndArray(); } I got an `OutOfMemoryException` exception at `writer.WriteValue(TargetObject.Data.Value)`, saying insufficient memory, any idea that I can keep my custom serialization but avoid this issue? Note, yes, you are right,the object I'm trying to serialize is more than 1GB.
I found finally, the reason is because the exception from overflowing the String type from .NET. So , simply, its just too big data for a String field, there is no solution as there isn't a problem with json.net, my solution is to simplifying my data, or output as a file on drive rather than storing its whole data any time in memory as string field, just impossible....
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "c#, asp.net web api, serialization, json.net, datacontractjsonserializer" }
Convert file path to a file URI? Does the .NET Framework have any methods for converting a path (e.g. `"C:\whatever.txt"`) into a file URI (e.g. `"file:///C:/whatever.txt"`)? The System.Uri class has the reverse (from a file URI to absolute path), but nothing as far as I can find for converting to a file URI. Also, this is **not** an ASP.NET application.
The `System.Uri` constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following: var uri = new System.Uri("c:\\foo"); var converted = uri.AbsoluteUri;
stackexchange-stackoverflow
{ "answer_score": 340, "question_score": 242, "tags": "c#, .net, path, uri" }
Difference between document activities and regular activities When I read the end of the official guide, I found the sentence which says, > The default value is true for document activities, and false for regular activities. Could someone explain what's the difference between the both ? By default we touch the Back button to destroy an Activity, we still can see the task on the Recents Screen. So I guess it belongs to regular activities. But how about the document activities ? Could you take some examples which belong to them ?
A good explanation of document activities can be found here: < It is normal, even if you don't have a "Document Activity", for your app to show up in the list of recent tasks after you use the BACK button to finish it. The app is not running, but the list of recent tasks shows all running tasks and also a number of tasks that were recently used. Document activities allow multiple instances of the same `Activity` to exist in different tasks, and therefore there will be multiple instances of the same app (with different documents) in the list of recent tasks. Personally I think this concept is confusing for the user, but...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, android activity" }
dat.GUI and Complex Variables I'm fairly new to dat.GUI and I'm having problems getting it to work with a more complex variable. I have the following: let complexVariable= { topLayer: { deeperLayer: { deepestLayer: 20, //Other stuff } } } let gui = new dat.GUI(); gui.add(complexVariable, "topLayer.deeperLayer.deepestLayer", 10, 40); This gives me the following error: Uncaught Error: Object "[object Object]" has no property "topLayer.deeperLayer.deepestLayer" Any help here would be appreciated.
It currently doesn't seem possible by looking at the source code. They use bracket notation with the single property you pass in on the object. function add(gui, object, property, params) { if (object[property] === undefined) { throw new Error(`Object "${object}" has no property "${property}"`); } ... So what you are telling dat.GUI to do is find a top level property "topLayer.deeperLayer.deepestLayer" and that obviously does not exist on your object. It seems like more code would have to be written to support nested properties. dat.gui would have to do something like `if (object[property1][property2][...] === undefined)` or in your case - `complexVariable["topLayer"]["deeperLayer"]["deepestLayer"];`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, dat.gui" }
which PPA has the most current version of git for 12.04? ppa:git-core/ppa is outdated Just installed git via `ppa:git-core/ppa` and got `1.7.9.5` when the current version is `1.9.2`. $ sudo add-apt-repository ppa:git-core/ppa You are about to add the following PPA to your system: The most current stable version of Git for Ubuntu. For release candidates, go to . ... $ sudo apt-get install git Reading package lists... Done Building dependency tree ... $ git --version git version 1.7.9.5 ... As a bonus question, why aren't there more deb packages for widely used apps like git? I know `apt-get` works fine but I find the PPA system to be kinda haphazard. I don't know if debs would be any better; just wish something better existed. There's no tarball at < for `1.9.2`.
You should update your package list as version 1.9.2 is well available from the `git-core` ppa. sudo apt-add-repository ppa:git-core/ppa sudo apt-get update sudo apt-get install git=1:1.9.2-0ppa1~precise1
stackexchange-askubuntu
{ "answer_score": 11, "question_score": 6, "tags": "12.04, ppa, git" }
Difference and usage between WebForms' DynamicHyperLink and HyperLink What is the difference between these two server controls? When would I use one over the other?
DynamicHyperLink is used for dynamic data table actions (e.g. Edit, Insert) whereas HyperLink simply represents a standard link to another page which you can manipulate server side.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "asp.net" }
Oracle find customers who haven't rented in the past 3 years I have a database, with a few tables. One of them is a customer table, one of them is a rental table, and one of them is a rental details table. Let's call them `C`, `R` and `RD` respectively. `RD` has the `date_in` and `date_out` of the tools rented, and is linked to `R` by `RD`'s primary key. `R` is linked to `C` by `customer id`. Basically what I want to do is select (and delete) customers that have not rented anything in the past 3 years. So I can't use where `date_out > sysdate - 3 years` [representation not accurate code] because the tool might have been rented out 4 years ago and ALSO last week, so it needs to be kept in the database... I just need to delete tools that haven't been rented at all in the past 3 years. I know the database structure is retarded but I can't change it.
delete from c where not exists ( select * from r join rd using(r_id) where c_id=c.c_id and date_out>add_months(sysdate,-36) )
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "sql, database, oracle" }
Is there a reason why java does not have a class which allows both reading String and byte [] from a stream? Is there a reason why java does not have a class which allows both reading String and byte [] from a stream and also another for writing String and byte [] to a stream? What if it is necessary to transfer both byte [] and String like in HTTP?
There would likely be potential issues with character encodings. In particular, Java internally represents strings in UTF-16, which probably isn't what, say, someone on the other end of a network connection is expecting. The resulting behavior would be consistent, but not necessarily what the average programmer would expect. Getting a `byte[]` representation of a String isn't hard. Just use `String.getBytes()`, or the overloaded version which allows you to specify the encoding.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, http, stream" }
Do not receive something vs have not received something by a given time 1, If you have not received the letter by February 18, please let us know by email. 2, If you do not receive the letter by February 18, please let us know by email. Both 1 and 2 are talking about the things that may happen in a few weeks later, and I have seen that 1 and 2 are adopted on some universities's web sites. Does this mean that 1 and 2 are equivalent? If not, what are their differences then?
We can say: **If the swelling does not go down by tomorrow evening, take two more of these pills.** or **If the swelling has not gone down by tomorrow evening, take two more of these pills.** If there is a nuanced difference between them, 99.9% of native speakers won't be able to tell you what that difference might be. We can also say: **After a week, the swelling _will have gone down_ enough that you can put your full weight on your foot again.** That's the future perfect.
stackexchange-ell
{ "answer_score": 2, "question_score": 2, "tags": "grammaticality in context, time" }
Is it possible to calculate the following optimization expression? I'm faced with this expression: $$max(xy) : x \leq a, \; y \leq b,\; c = \frac{x}{y}$$ where all variables are greater than or equal to zero. I know the values for a, b, and c but I need to find the maximum value for x * y **and the values for x * y that produce the maximum**. I've started working on this on paper but I'm starting to wonder if it actually can be done. I enjoy deriving things so I'm not looking for an answer yet, would just like to know if I can somehow prove that it can be done.
Given the clarification, the third constraint gives $x=cy$. The problem is then $\max\limits_y cy^2$ subject to $cy\leq a,\,y\leq b,\, y\geq 0$. Choosing $y=\min\left\\{b,\dfrac{a}{c}\right\\}$ will then satisfy all three constraints with the largest objective function. The corresponding value for $x$ can be calculated.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "optimization" }
Include files in functions.php This is a rewritten post since the way I worded my old post totally confused everyone. MikeSchinkel shows how he uses Include files in his theme's functions.php file In this Stackexchange post: Organizing Code in your WordPress Theme's functions.php File? Example: require_once('includes/my-file.php'); How would you write this php line if the file to include is inside a directory, inside the wp-content directory? Location: [wordpress install]/wp-content/new-directory/my-file.php The only way I can think of is like this: require_once( ABSPATH . '/wp-content/new-directory/my-file.php' ); Would this be the correct way?
Including a file inside a subdirectory is the same as any other as long as you know the path to the file. Since it's possible to move the 'wp-content' directory, don't pass that part of the path to the `require` statement; instead, use the `WP_CONTENT_DIR` constant. require_once WP_CONTENT_DIR . '/new-directory/my-file.php'; Also, you can leave out the parentheses since `include` and `require` are statements, not functions.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "php, include" }
How to show that $\mathcal{R}=\{Dx+c:x\in\mathcal{M}\}$ is a polyhedron Let $\mathcal{M}\subseteq\mathbb{R}^n$ a polyhedron, $D\in\mathbb{R}^{m\times n}, c\in\mathbb{R}^m$. How do I show that $\mathcal{R}=\\{Dx+c:x\in\mathcal{M}\\}$ is a polyhedron? I know that a polyhedron can be defined as the convex hull of a finite set of points, but I really don't know how to use that to answer this question. I would really appreciate it, if someone could explain this to me. Thanks in advance!
The reason is the following: $\mathcal{R}$ is obtained via an affine transformation of $\mathcal{M}$. But affine transformations preserve affine combinations. That is, if $A,B\in\mathcal{M}$ and $C=\alpha A+\beta B$ with $\alpha+\beta=1$, then given any affine transformation $f$, $f(C)=\alpha f(A)+\beta f(B)$ (the proof of this fact is just a line). Therefore, if $C$ is in the segment joining $A$ and $B$, then $f(C)$ is in the segment between $f(A)$ and $f(B)$ (in this case $\alpha, \beta\ge 0$). This property extends to several points, so if $C$ is in the convex hull of a finite set of points, $f(C)$ is in the convex hull of their images. Finally, since $\mathcal{M}$ is a polyhedron, $f(\mathcal{M})$ will be a polyhedron as well, namely the convex hull of the images of the points that generate $\mathcal{M}$.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "optimization" }
Can a language extension written in Visual Studio Code be used in Visual Studio 2017? I am writing a language extension in Visual Studio code (see this article for an example), and I wish to know whether this extension will be useable in Visual Studio 2017 (and 2019 when it comes out).
According to the visual studio docs and especially to this picture it should be possible to migrate that language server to visual studio, too. However it is not possible to use the exact same extension for VS Code as well as for Visual Studio. At least you will have to change the _Provider-specific intizialization code_ (see the picture) to make the server work for Visual Studio, too. For further reading you can check out the corresponding VS Code docu on language server.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "visual studio, visual studio code" }
If $abc=1$ and $a,b,c$ are positive real numbers, prove that ${1 \over a+b+1} + {1 \over b+c+1} + {1 \over c+a+1} \le 1$. > If $abc=1$ and $a,b,c$ are positive real numbers, prove that $${1 \over a+b+1} + {1 \over b+c+1} + {1 \over c+a+1} \le 1\,.$$ The whole problem is in the title. If you wanna hear what I've tried, well, I've tried multiplying both sides by 3 and then using the homogenic mean. $${3 \over a+b+1} \le \sqrt[3]{{1\over ab}} = \sqrt[3]{c}$$ By adding the inequalities I get $$ {3 \over a+b+1} + {3 \over b+c+1} + {3 \over c+a+1} \le \sqrt[3]a + \sqrt[3]b + \sqrt[3]c$$ And then if I proof that that is less or equal to 3, then I've solved the problem. But the thing is, it's not less or equal to 3 (obviously, because you can think of a situation like $a=354$, $b={1\over 354}$ and $c=1$. Then the sum is a lot bigger than 3). So everything that I try doesn't work. I'd like to get some ideas. Thanks.
let $$a=x^3,b=y^3,c=z^3\Longrightarrow xyz=1$$ since $$y^3+z^3\ge y^2z+yz^2$$ so $$\dfrac{1}{1+b+c}=\dfrac{xyz}{xyz+y^3+z^3}\le\dfrac{xyz}{xyz+y^2z+yz^2}=\dfrac{x}{x+y+z}$$ so $$\sum_{cyc}\dfrac{1}{1+b+c}\le\sum_{cyc}\dfrac{x}{x+y+z}=1$$
stackexchange-math
{ "answer_score": 7, "question_score": 5, "tags": "inequality, contest math, rational functions, symmetric functions" }
how to create link in telegram bot I am designing a telegram bot. I want to show some links e.g. > 1- wkpviana > > 2- vianahosting that when user click it, open in browser. How I can create it in php? part of my code is: <?php ... $sLink = ""; foreach($Links as $Row){ $sLink .= "<a href='".$Row->link_url."'>".$Row->link_name."</a>"; } $Text = $sLink; ... $URL = " file_get_contents($URL); ?>
You seem to be attempting to send the links with the `<a>` tag, which works fine, but requires you to use the `parse_mode=html` parameter, as documented here. I believe it would look a bit like this: $URL = "
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 8, "tags": "php, telegram bot, php telegram bot" }
preimage of joint random variables and integration If the two random variables $X$ and $Y$ are independent, I need to determine the two sets A and B that will make the following equation true $Pr ((X^{-1}, Y^{-1}) (A \times B)) = \int _{-\infty} ^{t} f_{Y}(y) F_{X} (y) dy $ where $f_{Y}$ is the PDF of $Y$, and $F_{X}$ is the CDF of $X$ Can we write the event that corresponds to this integration in this form using the preimage of the random variables and the product of two sets?
Since $$F_{X} (y)=\int_{-\infty}^y f_X(x)dx$$ we have $$\int _{-\infty} ^{t} f_{Y}(y) F_{X} (y) dy=\int _{-\infty} ^{t} f_{Y}(y) \left[\int_{-\infty}^y f_X(x)dx\right]dy=$$$$=\int_{-\infty}^t\int_{-\infty}^yf_Y(y)f_X(x)\ dxdy=\iint_{\\{(x,y):\ x\leq y,\ y\leq t\\}}f_{X,Y}(x,y)\ dx dy.$$ This is a double integral of the joint probability density function over the region showed below: ![enter image description here]( That is $$\int _{-\infty} ^{t} f_{Y}(y) F_{X} (y) dy=P(Y\leq t\ \cap\ X\leq Y).$$ So the given integral cannot be written in the form of $$P((X^{-1}, Y^{-1}) (A \times B)). $$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability, probability distributions" }
Create XML in T-SQL with one table I'm trying to do a xml file in T-SQL Here is my Table: |Name| Rank| |Rob | 1 | |Matt| 1 | |Leo | 2 | |jin | 2 | |jo | 3 | So far my code is: select name, rank from Info order by rank for xml raw ('Data'), ROOT, ELEMENTS The result I got is: <root> <data> <rank>1<rank> <name>Rob</name> </data> <data> <rank>1<rank> <name>Matt</name> </data> ... Put I would like to have this result: <data> <rank id=1> <name>Rob</name> <name>Matt</name> </rank> <rank id=2> <name>Leo</name> <name>jin</name> </rank> <rank id = 3> <name>jo</name> </rank> </data> Do you know how I can have this? Thanks
Group by Rank and query the Name values for each Rank in a correlated subquery. select I1.rank as 'rank/@id', ( select I2.name from Info as I2 where I1.rank = I2.rank for xml path(''), type ) as rank from Info as I1 group by I1.rank for xml path('data')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "xml, tsql" }
Detect Blank with Regex I am using the following regex to check a name field for invalid characters... if (!preg_match("/^[a-zA-Z ]*$/",$mystring)) Is there a way to also detect if the string is blank using regex? Or am I better off doing that using PHP?
You can just do a simple check without a regex: if( $string == "") //do something or if(strlen($string) == 0) //do something or if(strlen(trim($string)) == 0) //do something
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex" }
boost iostreaming filter gets empty values I tried to build a stream buffer for reading and writing char* using boost::iostreams: class MemBuf : public std::streambuf { public: MemBuf(char* s, std::size_t n) { setg(s, s, (char*)s+ n); } }; reading works fine: char myreadBuff[100]; myreadBuff[0] = 'a'; MemBuf mb (myreadBuff, 100); istream istr (&mb); cout << istr; but writing does not work: char mywriteBuff[100]; MemBuf mb(mywriteBuff, 100); ostream ostr($mb); ostr << "hello world"; cout << mywriteBuff; What is missing? Thx
`setg` sets the pointers for the read area; it has no effect on writing. The simplest solution is to use two different `streambuf`, `MemBufIn` and `MemBufOut`: the first calls `setg`, and the second `setp`. If you want a bidirectional stream, or to support seeking, it gets more complicated.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, boost iostreams, streambuf" }
Url is not working properly in codeigniter giving error "No input file specified". I uploaded my codeigniter application to a demo server. The Home page is opening fine, but other pages are giving error. I changed the `base url` in my config file to: $config['base_url'] = ' It is working fine locally. Any idea how to fix it?
Looks like you're hosted on GoDaddy, having bumped into the same issue before, changing your .htaccess file to the below should fix it. RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) index.php?/$1 See <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "php, codeigniter" }
Prove or disprove: if $f(x)$ has a removable discontinuous point at 0 then $g(x)$ = $x*f(x)$ is differentiable at 0 I need to determine whether it is true that if $f(x)$ has a removable discontinuous point at 0 then $g(x)$ = $x*f(x)$ is differentiable at 0. I thought to prove it by proving that $g(x)$ is continuous from both positive and negative directions by saying that the limit of $f(x)$ from both positive and negative directions is equal and, because the function $h(x) = x$ is continuous. which will lead me to say that $g(x)$ is continuous and then find the derivative. But I'm not sure if it's possible to claim that.
_Here, it is worth just going back to the definition of a derivative as a limit._ By definition of a removable discontinuity, we have that $f$ is defined at $0$ and that $\lim_{x\to 0} f(x)$ exists, _but_ $f(0) \neq \lim_{x\to 0} f(x)$. Now, for $g$ as in the question, we have $g(0)=0\cdot f(0)=0$ by definition. For $x\neq 0$, we can write $$ \frac{g(x)-g(0)}{x-0} = \frac{g(x)}{x} = \frac{xf(x)}{x} = f(x) $$ so $\lim_{x\to 0} \frac{g(x)-g(0)}{x-0}$ exists since $\lim_{x\to 0} f(x)$ does. It follows that $g$ is differentiable at $0$, with $$ g'(0) = \lim_{x\to 0} \frac{g(x)-g(0)}{x-0} = \lim_{x\to 0} f(x) $$
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "calculus, limits, derivatives, continuity" }
Binding to Elements of Arrays in AngularJS In AngularJS, I can successfully bind text inputs to elements of arrays: <input type="text" ng-model="foo[2]" /> Is this allowed, or does it just work by accident? When I try to bind `select` elements or checkbox input to array elements they fail to work - i.e. the `select` element does not change the displayed, or bound, value on selection and the checkbox does not display a tick when clicked. Am I missing something here? * * * Update: It works in JSFiddle: <
It does work on select elements Look this jsfiddle < HTML <div ng-app> <div ng-controller="MyController"> Select <select ng-change="changed()" ng-options="option.value as option.label for option in options" ng-model="ar[0]"> </select> </div> </div> JS function MyController($scope){ $scope.options = [ { label : "first element", value : 0 }, { label : "second element", value : 1 }, ] $scope.ar = []; $scope.ar[0] = 0; $scope.changed = function(){ console.log($scope.ar[0]); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "javascript, arrays, angularjs, data binding" }
EC private key, RSA certificate. Is this realisable? I was wondering if is it possible to generate EC private key: > openssl ecparam -name sect571r1 -out ecparam.pem > > openssl ecparam -in ecparam.pem -genkey -noout -out eckey.pem then generate CSR, which would tell CA to sign it normally as RSA: > openssl req -new -sha512 -key eckey.pem -nodes -out csr.csr and give it to CA, which will sign it and make RSA certificate. Is there any way to do this? If not, is there at least some EC curve that can produce a key of 2048 bits or more? The longest I know is sect571r1.
The simple answer is no you can't have an RSA cert which has a ECC public key. By definition an RSA cert is a cert which has an RSA public key. The CA could sign your ECC cert with their RSA key but that wouldn't make it a RSA cert it would make it a ECC cert signed with an RSA key. Likewise a CA could sign a RSA cert with their ECC key but that wouldn't make it an ECC cert it would make it a RSA cert signed by a ECC key. Do you need an RSA cert or do you just need some digital cert signed by your CA? If you must have a RSA cert why are you generating ECC keypairs? Generate an RSA keypair, a CSR and have the CA create a cert from that.
stackexchange-security
{ "answer_score": 4, "question_score": 1, "tags": "certificates, public key infrastructure, openssl, ecc" }
Change file name and move files based on file path in Windows 7 I have a bunch of image files distributed in folders and sub folders. What I would like to do is move them all to one one folder and rename them them based on their previous path. To illustrate, the file src/a/b/file1.png should become src/a_b_file1.png There is probably a smart way to do this in Linux, but I am currently on a Windows 7 machine. Any tips would be nice, gui or commandline tools or some script, doesn't matter. Thanx.
I ended up using this program. Easy to install and easier to use that it appears at first glance.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "windows, file, command line, scripting" }
What adapter would power device that runs on 3 D batteries? I have a clock that runs on 3 D batteries and, as you can imagine, it's a pain to maintain them. I've found a DC adapter that delivers 4.5v (1.5v x 3) but it doesn't budge when connected. I imagine there's some issue with amperage or resistance, but those aren't listed on the batteries! What should I be doing?
There are a few possible problems. * Your power supply could be broken. Check it with a voltmeter. Jiggle the wires and make sure there's not an intermittent break somewhere. * Your power supply is actually putting out AC. Some wall warts are AC/AC. Does it say it puts out DC? * The batteries may be in parallel instead of in series, in which case you've already overvoltaged the clock's circuitry and may have destroyed it. Does it still work when you put batteries in? * Your power supply may not supply enough current to run the clock. That seems unlikely; clocks typically draw very little current. But you can check by seeing if the voltage on the output of your power supply collapses when you connect it to the clock. * You could have your polarity backwards. Make sure you've connected positive to positive, and negative to negative. Again, use a voltmeter. * You could have a bad connection. How are you connecting the adapter to the clock?
stackexchange-electronics
{ "answer_score": 5, "question_score": 0, "tags": "batteries, dc" }
Build Visual Studio 6 project without Visual Studio I have inherited a Visual Studio 6 C++ project. The project builds fine in Visual Studio 6 but I failed to compile certain files in the project with a gcc compiler. These issues relate to forward declarations and probably other issues. For the mean-time, I'm not interested in fixing these problems since the code is horrible. The code is also windows dependant since it uses win32 to communicate with com ports. So, I wish to compile with an ms compiler (and build and link...) but I don't have access anymore to Visual Studio due to company policy... What options are open to me? THanks for your help, Barry.
You can try downloading the free (as in beer) windows SDK. It's been a while, but I believe that these low level tools, such cl, link and make are available though these. < But you probably will need to massage the code a little, so you might need to deal with the win api a little bit too. Just to clarify, this is free and not associated with VS, so unless your company has some rather restrictive policies, you should be able to download and use the Windows SDK fine. Furthermore, the compiler tools should be somewhat friendly to VS6.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, visual studio, nmake" }
Let Σ = Ø. How many different languages can be defined on Σ? Here is the question: Let Σ = Ø. How many different languages can be defined on Σ?
There's exactly one language over the empty alphabet. Its only word is the empty word $\varepsilon$.
stackexchange-math
{ "answer_score": 0, "question_score": -1, "tags": "discrete mathematics" }
Relevance of const return type in NRVO cases This is a follow up question from Calling constructor in return statement. This a operator overload fun in a class. const Integer operator+(const Integer& IntObject) { cout << "Data : " << this->data << endl; return Integer(this->data + IntObject.data); } What is the relevance of const in the return type for such functions? int main() { Integer A(1); //Create 2 object of class Integer Integer B(2); const Integer C = A + B; //This will work Integer D = A + B; //This will also work fun(A + B); //Will work } void fun(Integer F) {} This is a case temporaries are not created during return step due to NRVO. The object to be returned is directly constructed on the callee's address.
There is no relevance in your code snippet, because you are making a **copy** of the returned value. In general, it is difficult to find good reasons to return a `const` value. I can only see it having an effect in this type of expression, attempting to call a non-const method on a `const` temporary: (someObject.someMethodReturningConstValue()).someNonConstMethod(); // error, calls non const method on const temporary so you should only use it if you want to disallow calling non-const methods on temporaries. On the other hand, it kills move-semantics in C++11 so is discouraged.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c++" }
Is work logging supported by Phabricator or Can we bring in a work logging feature? We were checking the feasibility of using Phabricator in our software development activities. We are currently using JIRA and is looking for a lighter replacement. We feel JIRA as a generic tool that doesn't only focus on software development and Phabricator for us looks lighter and well integrated. One feature we couldn't find is Work logging. Currently we are using jira work logging feature for extracting data for project management reporting. So basically my query is 1. Is work logging feature available in Phabricator ? 2. Would it be possible to extend the Phabricator for this purpose ?
Technically, yes, there is a work logging feature called Phrequent. It is one of the prototype applications in Phabricator (prototypes must be turned on from Config). However, it has a lot of missing features. While individuals can start and stop work time on tasks, they cannot edit or delete time entries, and the reporting features are less than ideal (you can only view by person, not by time range or task). More features are planned, though they appear to be low priority right now for the core development team.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "phabricator, agile project management, task management" }
How can I generate random variates from a from a PDF that I have defined? My problem is that `Pick` evaluates all the elements of a list at once. In my code I need a similar function that evaluates each element of a list. I need to generate 1000000 numbers for a PDF. My code is: n = 1000000; yteste = RandomReal[{0, 2/3}, 2 n]; xteste = RandomReal[{-1, 1}, 2 n]; f[x_] := 2/3 (1 - Abs[x]^3) If[Length[xaceitos] <= n, AppendTo[xaceitos, Pick[xteste, UnitStep[f[xteste] - yteste], 1]], Nothing] Is there any other function that can do it?
As @JM says, just use `ProbabilityDistribution`: dist = ProbabilityDistribution[f[x], {x, -1, 1}]; random = RandomVariate[dist, 10^6]; Length[random] > 1000000 Visualization: Histogram[random, Automatic, "PDF"] ![enter image description here](
stackexchange-mathematica
{ "answer_score": 7, "question_score": 4, "tags": "probability or statistics" }
String was not recognized as a valid DateTime. 6-26-2015 I tried several Q&A in here and made this piece of code: The idea is to compare dt1 with dt2 and do something later. date = row.Cells[3].Value.ToString(); DateTime dt1 = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture); dt1 = dt1.AddDays(-4); String dateStr = DateTime.Now.ToString("M/d/yyyy"); DateTime dt2 = DateTime.ParseExact(dateStr, "M/d/yyyy", CultureInfo.InvariantCulture); On the last line I am having this exception: > String was not recognized as a valid DateTime. While debugging this are the values: `date = 06/05/2015` `dt1 = "01-Jun-15 12:00:00 AM` `datestr = 6-26-2015`
Your format is incorrect if `datestr` value is "6-26-2015" you should use this: DateTime dt2 = DateTime.ParseExact(dateStr, "M-d-yyyy", CultureInfo.InvariantCulture); `ParseExact` tries to match the input string with the given format. In your case input string is `6-26-2015` and format is `M/d/yyyy`, `-` and `/` can not be matched so the exception is thrown.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#, .net, date, datetime" }
Does precision and scale of NUMBER influence the behaviour of ResultSet.getObject() -Oracle 11g -Oracle thin driver When a column is defined as NUMBER the getObject method on ResultSet will return a BigDecimal type. My question is, If we where to change the column definition to NUMBER(19,0) would the driver know to convert this to a Long when we called getObject?
I think no. Here the document says the SQL data types DEC, DECIMAL, NUMBER, NUMERIC are mapped into java.math.BigDecimal.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "java, oracle, jdbc, oracle11g" }
Slice with Projection with C# Is there any way to implement a slice along with a projection in just one query using the c# driver? Below is what i am trying to achieve using c#, but im stuck, can anyone help me out wit it? db.employee.find({"employeeId": "999"}, { "empActivity" : { "$slice": -1 } }, {"employeeId": 1, "empActivity.transId": 1, _id: 0}) Note : empActivity is a an array containing nested documents, my query above works perfectly via the mongo shell but i am not able to figure out its equivalent in C#.
There is a way to do this with the C# driver. Methods can be chanined on builders, so all of `.Slice()` and `.Include()`and `.Exclude()` var fields = Fields.Slice("empActivity", -1) .Include("employeeId", "empActivity.transId") .Exclude("_id"); var cursor = collection.Find(query).SetFields(fields);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, mongodb, mongodb query, mongodb .net driver" }
what is numpy random.RandomState import numpy as np rng=np.random.RandomState(123) for i in np.arange(1,21): number=2**i heads_tails=rng.randint(0,2,size=number) ptails=np.mean(heads_tails) print("Number of tosses:",number,"---","Probability of Tails:%.2f"%(ptails*100),"%","---", "Probabilty of Heads:%.2f"%(100-ptails*100),"%") _**Hi,I wrote this code and I didn't understand the random.RandomState's function in here,What is it using for or What is the function of that? If you can explain,I would be appreciated.**_
`np.random.RandomState()` constructs a random number generator. `np.random.RandomState()` returns a new seeded `RandomState` instance but otherwise does not change anything. You have to use the returned `RandomState` instance to get consistent pseudorandom numbers. For instance, if you use the functions in the `numpy.random` you will not get consistent pseudorandom numbers because they are pulling from a different `RandomState` instance than the one you just created. So to be consistent, you can create a specific `RandomState` and draw to pseudorandom numbers in a reproducible way.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, numpy, probability" }
Serialize into Datetime, Object I have map in this format, HashMap<String, Object> map = {"RequestsServed":{"2019-06-28T00:00:00Z":0.0},"PullRequests":{"2019-06-28T00:00:00Z":0.0}} My intension is to do `map.get("RequestsServed")` and get a map of `{"2019-06-28T00:00:00Z":0.0}` irrespective of number of key, value pair in it. I tried using, HashMap<DateTime, Object> result = new ObjectMapper().readValue(SerializationUtils.toJson(map.get("RequestsServed").toString()), HashMap.class); and failed. please help. Thanks
I was so dumb asking this question... map.get("RequestsServed") is gonna give me a LinkedTreeMap. I just have to parse it into a HashMap of my choice. serialising map.get("RequestsServed") to a json and parse the resultant value to HashMap will give me the required result easily. Thank you all for your time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, json, datetime, jackson" }
How to get exact regex for accepting Number with alphabet only? Hi I tried to get the exact regex for matching Number with alphabet only, I tried this Regex.IsMatch("1111", @"^[a-zA-Z0-9]+$") but the output is true. Here is what I want output 12345678 -> False abcdefgh -> False ABCDEFGH -> False 1234abcd -> True 1234ABCD -> True
Try the following positive lookahead matching expression: ^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$ This asserts that both grouped expressions are true and returns the full string on match. Example: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, regex" }
Find average of array using only average of 2 members at a time You are given an array of 8 cups of water, each cup filled with a different amount of water you must get equal amounts of water in all cups, and can only use this function public void equals(double[] arr, int i, int j) { arr[i] = arr[j] = (arr[i] + arr[j]) / 2; } Perhaps recursively? Any ideas?
Seems like you could use mergesort-esque logic here... If you have cups 1,2,3,4,5,6,7,8... First do equals(1,2), equals(3,4), equals(5,6), equals(7,8). At this point cups 1 & 2 have the same amount, cups 3 & 4 have the same amount and so on. Next do equals(1,3), equals(2,4), equals(5,7), equals(6,8). Now cups 1,2,3,4 have the same amount, and cups 5,6,7,8 have the same amount. Last do equals (1,5), equals(2,6), equals(3,7), equals(4,8). Note, you could also do equals(1,4), equals(1,5), etc because 1,2,3,4 all have the same amount. After this step, all cups have the same amount! If you need help coding this in java, just ask.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 2, "tags": "java, c, algorithm, recursion, average" }
Get user response of Word save prompt? **Background:** I am creating a VSTO Word Add-In using Visual Basic in Visual Studio 2015. **Problem:** When closing a document, I want the user to be prompted to save it. Below is the standard command I keep seeing everywhere and that I want to use: thisDoc.Close(Word.WdSaveOptions.wdPromptToSaveChanges) However, I want to store in a variable the option that the user has selected (i.e. Yes, No, or Cancel). How can I do this? I know how to do it using a Message Box (see code below) but would prefer to use wdPromptToSaveChanges. Dim userSaveResponse As MsgBoxResult = MsgBox("Do you want to save this doc?", vbYesNoCancel)
Close doesn't return anything, and I'm not aware of any fields that are changed during a save except `Document.Saved` (which, when false, would not tell you whether it was a No or Cancel) but at that point the document is closed and probably can't be accessed. One thing you can do, is call `thisDoc.Save()`, and if the user cancels out of it (or any other error occurs), a COMException will be thrown. Otherwise, it succeeded.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "vb.net, visual studio, vsto, office addins" }
Input-field: pre-filled value not deletable, but extendable As I'm not that familiar with JavaScript, I did some research around the web to have sth. to go on, but was not able to solve my problem. I created a fiddle to show you how it shall look like. Well, my problem is that the light-grey pre-filled value "E-Mail" shall not be deletable, but the value itself shall be extendable in black font color. Have you got an idea how to make it happen? Thank you.
try this < use lable for that input field and concat input field value and lable text
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, input" }
PDF Downloading not functioning properly I am using the following code to download a PDF.... header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="NewName.pdf"'); readfile($root_path.'/full-tile-book.pdf'); It's a 13 MB file and only downloads like 130k and of course can't be opened. How do I debug what the issue is here? My path to the pdf is correct.
Perhaps you are running into a memory/filesize error? I've had problems in the past dumping large files with readfile. In addition to setting the Content-Length header, I recommend using `fpassthru()`, as it does not read the file into a buffer, it just dumps it. set_time_limit(0); // disable timeout $file = $root_path.'/full-tile-book.pdf'; header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="NewName.pdf"'); header('Content-Length: ' . filesize($file)); session_write_close(); // remove this line if sessions are not active $f = fopen($file, 'rb'); fpassthru($f); fclose($f); exit; EDIT: If you are using any sessions_code, it is a good idea to end the session before starting the file dump process. I have updated my example to reflect this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, download" }
setHours is not a function when converting time from string I am trying to compare a time in string format to the current time. I've tried setting up two Date objects and calling .Now() on both of them, then on one of them adjusting the time to the time that is in string format by splitting it and parsing both the hours and minutes to integers, but I get the following error: > setHours is not a function The 'cutoff' value I'm using is '15:00' and when following in the debugger I can see this splits in to split[0] = 15 and split[1] = 00 (this is before they are parsed into integers. var cutoff = data.CutOff; var split = cutoff.split(":"); var today = Date.now(); var hours = parseInt(split[0]); var min = parseInt(split[1]); today.setHours(hours, min); if (Date.now() < today) { // Do Something }
You want to do `new Date()` as opposed to `Date.now()` `new Date` creates a `Date` instance which allows you to access the `Date` methods. `Date.now()` method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 4, "tags": "javascript, datetime" }
.net FIFO "Queue" combined with last known Topic Looking for any existing FIFO Queue which also handles overrides based on topic as follows given struct QueueItem { string Topic; .... other data } if the queue has items added in the order q.Add( new QueueItem() { topic = A, ... } ); //1 q.Add( new QueueItem() { topic = B, ... } ); //2 q.Add( new QueueItem() { topic = C, ... } ); //3 q.Add( new QueueItem() { topic = A, ... } ); //4 q.Add( new QueueItem() { topic = B, ... } ); //5 At retrieval the order should be #4 Topic A - skipping #1 #5 Topic B - skipping #2 #3 Topic C etc. NOTE - the order in which the items/Topics are added/processed is important given the rule above Wondering if this is a known scenario and there might be an existing implementation out there already
What you're looking for is a priority queue. Your requirement is slightly different in that it uses letters instead of integers for the priority, but the concept is the same. See answers C# Priority Queue and Priority queue in .Net
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, .net, collections" }
Monotouch - playing video on network share We are building an application that will only be used within our infrastructure. We have videos on a windows file share which we want to play within the app. The videos are working when they are embeded in the app but as some of them are so big we want to move them out. I am trying to reference the videos using an smb:// url but that doesn't seem to work. I am also trying to reference them using a file:// url to no avail. I can see the folder from the dev mac. Should this work or do I need to do more work to make it happen? Such as streaming?
iOS is not able to access any kind of shared directory (smb:// or file://), you will have to add code to your app to connect and transfer the files yourself if you want to use a shared directory like that. But iOS can access web servers, so if you can set up a simple http server (Apache or IIS), and serve the files using a http protocol, it should work just fine.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, xamarin.ios, video streaming" }
delete all rows up to a specific row How you can implement deleting lines in a text document up to a certain line? I find the line number using the code: #!/usr/bin/env python lookup = '00:00:00' filename = "test.txt" with open(filename) as text_file: for num, line in enumerate(text_file, 1): if lookup in line: print(num) `print(num)` outputs me the value of the string, for example 66. How do I delete all the lines up to 66, i.e. up to the found line by word?
That's easy. filename = "test.txt" lookup = '00:00:00' with open(filename,'r') as text_file: lines = text_file.readlines() res=[] for i in range(0,len(lines),1): if lookup in lines[i]: res=lines[i:] break with open(filename,'w') as text_file: text_file.writelines(res)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x" }
All value in a SQL syntax with precompiled query I have this SQL query: `SELECT * FROM MyTable t WHERE [any condition] AND t.range = x` The attribute `t.range` value is included in [0, 90]. So, the user have two possibility: 1. insert a value 2. view all value Now, it's can do the point 2 _without delete_ the part `AND t.range =` ?
WHERE [any condition] AND (t.range = x or x is null)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, oracle10g" }
How to create a pattern that matches Group A except host "test-host" and Group B? I have 2 groups of servers A and B, one of servers that I need to exclude is in group A I tried following pattern: GroupA:!test-host,GroupB Which results in 'no hosts matched' How can I do that?
The inventory shell> cat hosts [groupA] test1 test2 test-host [groupB] test3 test4 and the playbook shell> cat pb.yml - hosts: groupB:groupA:!test-host tasks: - debug: var: ansible_play_hosts_all run_once: true give shell> ansible-playbook -i hosts pb.yml ok: [test3] => { "ansible_play_hosts_all": [ "test3", "test4", "test1", "test2" ] } * * * With _`- hosts: all`_ in the playbook, the command gives the same result shell> ansible-playbook -i hosts -l 'groupB:groupA:!test-host' pb.yml
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ansible" }
How to add a view for the json result in asp.net mvc? I returned json result from a controller but how can i add a view that uses this json result.. public class MaterialsController : Controller { ConstructionRepository consRepository = new ConstructionRepository(); public JsonResult Index() { var materials = consRepository.FindAllMaterials().AsQueryable(); return Json(materials); } } How to add a view to this? Any suggestion...
If are returning JsonResult view will not be attached to it. It will be pure Json that will be sent to the browser. However you can use Asp.Net ClientSide template or JQuery Client Templates to render view using this Json. An example < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "asp.net mvc, json, controller" }
meaning of knowing What is the meaning of **knowing** in the following sentence > Having received such a stinging rebuke by the Supreme Court, the right course of action for Mr. Oli should be to resign on moral grounds, but **knowing** the combative politician, that is not going to happen. To Read The Full Article
Maybe some examples will help: * Knowing that fire is hot, I don't touch it. * Knowing that he's a trustworthy person, I gave him the keys to my car. * Knowing that he's a vegetarian, I made him tofu. * Knowing English, I could understand this answer. Mathematically, it's p -> q. Knowing something (p), I did something else (q).
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "meaning" }
Component Output with Promise I have a button component which has an Event Emitter, and when it is triggered I want to start a loading animation in the button, and when the promise is resolved, stop the loading animation. @Output() promiseClick: EventEmitter<any> = new EventEmitter<any>(); This would be used something like: <my-button (promiseClick)="makeAPICall()"></my-button> Where the makeAPICall() method returns a Promise. I need the my-button component to know when the makeAPICall() promise has been resolved. How can this be achieved?
<my-button #button (promiseClick)="button.makeKnown(makeAPICall())"></my-button> makeKnown(p:Promise) { p.then(result => this.result = result); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "angular, promise, angular2 components" }
How do I import an existing non-git java project into a github repository? I am currently trying to import a working Java Project which was provided by our professor into a private github repository to work on it in a group. So far we've tried to copy files over manually, which caused problems when Eclipse did not consider the files part of the src package, and moving all files into the empty git repository and adding them manually. When trying to add them manually, it gives the error message "The declared package "com.bar.foo" does not match the expected package "src.com.bar.foo"".
cd /java-project git init git remote add origin <git-url> git add * git commit -m "Initial Commit" git push -u origin master
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java, eclipse, git" }
JavaFx customize button's look I uploaded an image to my button, but it looks like this: ![enter image description here]( The button isn't shaped like the image, and the button colors are still visible on the edges. Is there a way to change this?
Use: button.setPadding(Insets.EMPTY);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, image, button, javafx" }
Best method of checking a value in ranges in android? I'm designing a roulette app. I need a way to take my ending rotation, "wheelRotateTo" and find out, in a list of degrees, which are currently in a stack of 36 "segments" on the wheel. So if the end degree is 355, it should identify the last stack object, because it's `< 360`, but greater than the degree of the segment below it.. Likewise, if wheelRotateTo was 339, it should give me the second stack segment down, because it fits there. This is just driving me crazy. Can someone explain a reasonable way to identify which segment or "Wheel number" it stops on? Thank you.
I can think of several solutions: 1. Divide the number of degrees by the number of degrees per section. This will give you the index for the section in your list. 2. Don't worry about degrees at all. Just randomly generate an index to your list.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, collections, stack" }
How to get first value from NSMutableArray (iPhone)? Now i am working in simple iphone application, i have stored some value in `NSMutableArray` like `"{54.399, 196}","{-268.246, 273}".`so i want to get 54.399 in first `indexpath`, how to get this, please help me Thanks in Advance
It seems you have an Array of Arrays, so it would be: [[myArray objectAtIndex:0] objectAtIndex:0]; Or using subscripting: myArray[0][0]; * * * **Edit** : Ok you have an Array of `NSStrings`. To do what you want (get the 53.399) do the following: NSString *myString = [myArray objectAtIndex:0]; NSArray *stringComponents = [myString componentsSeparatedByString:@","]; NSString *myFinalString = [stringComponents objectAtIndex:0]; With subscripting: NSString *myFinalString = [[myArray[0] componentsSeparatedByString:@","][0];
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 5, "tags": "iphone, ios, arrays, nsmutablearray" }
Mysql like regexp Hi there here is the query: SELECT * FROM `person` WHERE memo LIKE 'John Smith %' OR memo LIKE '% John Smith %' OR memo LIKE '% John % Smith %' OR memo LIKE '%John%Smith%' ORDER BY CASE WHEN memo LIKE 'John Smith %' THEN 1 WHEN memo LIKE '% John Smith %' THEN 2 WHEN memo LIKE '% John % Smith %' THEN 3 WHEN memo LIKE '%John%Smith%' THEN 4 ELSE 5 END how to convert to not use the `OR` operator can be regexps?
You can change the `where` just to: WHERE memo LIKE '%John%Smith%' The other conditions are redundant. As for the `order by`, there probably isn't any way to simplify that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "mysql, regex" }
Prepositions in a compound sentence Following Martha's advise I am splitting up a question Compound sentences, the punctuation and mooore. Consider the following sentence: > One of the items that needed a further development was a research on child nodes of a story representing its sub categories being updated the moment the list of sub categories is changed through edit page for stories. Did I miss any prepositions obligatory for sentences that complex? If you feel like it's not the right way to use English anyway, please see questions Constructing compound sentences and How to rephrase a sentence?.
Grammatically this sentence parses. No missed prepositions. There are two indefinite articles that might be superfluous: > One of the items that needed further development was research on child nodes... And yes, I do think that this sentence needs rephrasing (rule of brevity). See my answers on the corresponding questions.
stackexchange-english
{ "answer_score": 1, "question_score": 2, "tags": "prepositions, syntactic analysis" }
TypeError: img should be PIL Image. Got <class 'torch.Tensor'> even though using latest pytorch version I had to create a new pytorch environment in Anaconda, I created my code and it worked fine in my old environment. I then created the new environment with the same version of pytorch and cuda 10.1 (but then updated to cuda 11, same as the old one. WHen i try to run the same code i get the error: TypeError: img should be PIL Image. Got <class 'torch.Tensor'> When trying to apply any transformation to my tensors, for example the following code gives me an error: def randRoll(batch, deg): rotator = torchvision.transforms.RandomRotation(deg) batch = rotator(batch) return batch Nothing has changed and I can't understand why i would get this. Any suggestions?
Solved Turns out somehow torchvision 0.2.2 had been installed instead of the latest 0.9.1 (which my other environment used). This was solved by uninstalling torchvision using conda remove torchvision then installing torchvision using pip (using conda install gave me version 0.2.2) pip install torchvision I also had to reinstall six using pip.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, deep learning, pytorch" }