INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Можно ли навести фокус на текст? document.querySelector('p').onfocus = function() { alert('фокус'); } <p>текст</p>
Можно, только сначала для `p` нужно задать `tabindex`: document.querySelector('p').onfocus = function() { console.log('фокус'); } <p tabindex="-1">текст</p>
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript" }
sql update multiple values to one column from another table I have two tables. table_a table_b idA idB nameA nameB remarkA1 remarkB remarkA2 Update from Comment: Code I have tired UPDATE table_b SET remarkB = table_a.remarkA1 FROM table_a WHERE table_b.id = table_a.id But this code I can only update one value to column remarkB,If i want update values in `table_b` from `table_a` by update values from `remarkA1`, `remarkA2` to `remarkB` How should I write?
You can use the following Update Statement along with you need a string `CONCAT` I'm assuming the data type of `table_a.remarkA1` and `table_a.remarkA2` are string (i.e., `VARCHAR`) UPDATE table_b SET remarkB = CONCAT(table_a.remarkA1, ' ', table_a.remarkA2) FROM table_a WHERE table_b.idB = table_a.idA
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql, sql server, tsql" }
MKMapItem with specific Location How can I launch the default maps app for iOS6 and pass it a custom location? For example: [[MKMapItem setLocation:MyLocation] openInMapsWithLaunchOptions:nil]; I followed the example here, but was unable to figure it out. How can I launch the Google Maps iPhone application from within my own native application?
Here is the code to open the Maps native application with a custom location: double latitude = 35.0; double longitude = 1.0; MKPlacemark *placemark = [[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude) addressDictionary:nil] autorelease]; MKMapItem *mapItem = [[[MKMapItem alloc] initWithPlacemark:placemark] autorelease]; [mapItem setName:@"Name of your location"]; [mapItem openInMapsWithLaunchOptions:nil];
stackexchange-stackoverflow
{ "answer_score": 34, "question_score": 10, "tags": "objective c, iphone, xcode, mkmapitem" }
Rename Batch File Has To Be In Same Folder For some reason my code below only works if the batch file is in the same folder as the files to be renamed even though i've specified the path. When the batch file is in a different folder I receive an error saying the file can't be found. Any input on this? @echo off&setlocal set "name1=Bart" set "name2=Carl" set "name3=Judy" for /f "delims=" %%a in ('dir C:\Users\%username%\Downloads\Export_*.csv /b /a-d /o-d') do ( set "fname=%%~a" set /a counter+=1 SETLOCAL ENABLEDELAYEDEXPANSION call set "nname=%%name!counter!%%" ren "!fname!" "!nname!%%~xa" endlocal )
just add a working path: @echo off&setlocal set "workingpath=%userprofile%\Downloads" set "name1=Bart" set "name2=Carl" set "name3=Judy" for /f "delims=" %%a in ('dir "%workingpath%\Export_*.csv" /b /a-d /o-d') do ( set "fname=%%~a" set /a counter+=1 SETLOCAL ENABLEDELAYEDEXPANSION call set "nname=%%name!counter!%%" ren "%workingpath%\!fname!" "!nname!%%~xa" endlocal )
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "batch file, batch rename" }
Linux kernel development I want to run some script/binary after system start and every 1000 ms (for example) inside Linux kernel (without the use of software as a crontab and kernel modules). Where can I put such code: #include <linux/kmod.h> char *envp[] = { "HOME=/", NULL }; char *argv[] = { "/bin/ls", NULL }; call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
Try to use kernel timer API: < > The simplest method is a call to setup_timer, which initializes the timer and sets the user-provided callback function and context. Otherwise, the user can set these values (function and data) in the timer and simply call init_timer. Note that init_timer is called internally by setup_timer" > > > void init_timer( struct timer_list *timer ); > void setup_timer( struct timer_list *timer, > void (*function)(unsigned long), unsigned long data ); >
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "linux, timer, linux kernel, kernel, cron" }
PHP drop down coding question Can someone show me how to make a If statement where if a drop down does not equal the default value of 0 (in my case) to automatically submit the form if possible? session_start(); $current = isset($_SESSION['ClientNamefour']) ? $_SESSION['ClientNamefour'] : 0; while ($row = mysql_fetch_array($result)) { $id = $row["Client_Code"]; $thing = $row["Client_Full_Name"]; $value = "$id, $thing"; $sel=($id==$current)?'SELECTED':''; $options4.="<OPTION $sel VALUE=\"$value\">$thing</option>"; } ?> <FORM name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <SELECT NAME="ClientNamefour" OnChange="this.form.submit()" )"> <OPTION VALUE=0>Client <?php echo $options4?> </SELECT> </FORM>
Use the `onchange` event and some JavaScript. In general your generated HTML should look something like this: <form id="form" name="form" method="POST" action=" <select id="select" name="select" onChange="document.getElementById('form').submit();"> <option value="0" selected="selected">0</option> <option value="1">1</option> <option value="2">2</option> </select> </form> The `onchange` event is only fired when you select an unselected option, so no additional checks are required. Compared with your solution: * the `id` is missing in your `<form>` tag * you need closing `</option>` tags * you'd probably need to change the JavaScript in the `onchange` attribute of the `<select>` tag
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php" }
deducing $\lnot B \implies \lnot A$ from $A \implies B$ One way how to prove a statement of the form $A \implies B$ is to presume that $A$ is true and deduce $B$. Lets have $A \implies B$ and lets assume that $\text{not}~B$ is true. $A$ is true or it is false (duh). If it were true, $B$ would also be true. However, we know that $B$ is not true and therefore $A$ must not be true either. We conclude $\lnot B \implies \lnot A$. The other direction follows similarly. 1. Is my deduction sound? 2. Is there a more formal way to see these two are equivalent?
Yes, indeed, you've informally argued using a proof by contradiction. (1) Given $A \rightarrow B$. * (2) Assume $\lnot B$. * (3) Assume $A$. * (4) Then $B\;$ ((1) & (3), modus ponens) * (5) Then $\lnot B \land B\;$ ((2) & (4) $\land$-Introduction) * (6) $\perp\;$ Contradiction. (5) * (7) Therefore $\lnot A\;$ ((3) - (6), $\lnot$-Introduction) (8) Therefore $\lnot B \rightarrow \lnot A\;$ (2-7) Similarly, we can deduce $A\rightarrow B$ if given that $\lnot B \rightarrow \lnot A$. With both directions proven, we will have then proven (by natural deduction) the equivalence of an implication and its contrapositive: $$A \rightarrow B \iff \lnot B \rightarrow \lnot A$$
stackexchange-math
{ "answer_score": 9, "question_score": 2, "tags": "logic, propositional calculus" }
Is the volume of a cube the greatest among rectangular-faced shapes of the same perimeter? My child's teacher raised a quesion in class for students who are interested to prove. The teacher says that the volume of a cube is the greatest among rectangular-faced shapes of the same perimeter and asks his students to prove this proposition. I considered the relationship between the length of the sides of a cube and the lengths of the sides of rectangular-faced shapes in different situation. But when the calculations came down to polynomials, I couldn't proceed due to the uncertainty of the variables in the polynomials. Can anyone please find a good way to prove the above proposition? Or is there already a proof? Thank you for your help!
If you mean by "perimeter" the sum of the edges, then yes, the cube is the maximal rectangular parallelepiped among those with the same "perimeter". Let the edges have lengths $(a,b,c)$. Then the volume is $V=abc$ and the "perimeter" is $p=4(a+b+c).$ We can maximize volume while constraining the sum of the edges using Lagrange multipliers: $$\begin{aligned} L &= abc-\lambda \left(a+b +c-\frac{p}{4}\right)\\\ 0&=\frac{\partial L}{\partial a} = bc - \lambda\\\ 0&=\frac{\partial L}{\partial b} = ac - \lambda\\\ 0&=\frac{\partial L}{\partial c} = ab - \lambda\\\ \end{aligned}$$ so that $$bc=ac=ab$$ and $$a=b=c.$$
stackexchange-math
{ "answer_score": 4, "question_score": 6, "tags": "geometry" }
Redirect https to http without causing client errors I have developed an app which talks to a server over https. I recently discovered that my certificate has expired, and now the app refuses to talk to the server. NSURLConnection/CFURLConnection (kCFStreamErrorDomainSSL, -9814) How can I do a quick fix so that my app will work (insecurely), until I can renew my certificate? I tried the following, but the app still protests (as does browsers). server { ssl on; ssl_certificate ssl/server.crt; ssl_certificate_key ssl/server.key; listen 443; rewrite ^ permanent; # temporary workaround }
It is fundamentally impossible. TLS handshake and all checks are done before any request will be sent. This is what "security" is about.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "http, https, nginx" }
Default function on an object? Is it possible to set a default function on an object, such that when I call `myObj()` that function is executed? Let's say I have the following `func` object function func(_func) { this._func = _func; this.call = function() { alert("called a function"); this._func(); } } var test = new func(function() { // do something }); test.call(); ​I'd like to replace `test.call()` with simply `test()`. Is that possible?
return a function: function func(_func) { this._func = _func; return function() { alert("called a function"); this._func(); } } var test = new func(function() { // do something }); test(); but then `this` refers to the _returned function (right?) or window_ , you will have to cache `this` to access it from inside the function (`this._func();`) function func(_func) { var that = this; this._func = _func; return function() { alert("called a function"); that._func(); } }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 7, "tags": "javascript, function, object" }
Как запустить файл через приложение? Каким способом можно перехватить запуск файла через приложение? Например, к файлу `C:\app.exe` обращается файл `test.txt`, этот файл должен открыться при условии, что в приложении есть разрешение на запуск такого имени файла. Если разрешения нет, то запретить запуск. Файл `app.exe` это приложение в которое должно разрешать или запрещать запуск файлов по имени. Если файл `test.txt` (или любой другой) прописан каким либо образом внутри приложения `app.exe`, то ему разрешено запускаться. Пользователь перемещает файл на приложение, и приложение решает, можно разрешать файлу открыться или нет (по имени файла). ![введите сюда описание изображения](
Точкой входа в любое приложение является метод `Main` по умолчанию. У него есть (может быть) список входных параметров `args`. Если программа будет запущена, когда на неё перетащен какой-либо файл, то имя этого файла будет в этом списке. Соответственно, достаточно проверить это имя со списком разрешённых файлов. static void Main(string[] args) { // Файлы, разрешённые к обработке. // "Белый" список. var whitelist = new HashSet<string> { @"C:\test.txt", @"C:\test2.txt" }; if (args.Any() && whitelist.Contains(args[0])) { // Обработка разрешена } else { // Обработка запрещена return; // завершаем программу } // другой код }
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "c#, .net, winforms, консоль" }
Asp.net Textbox has a very small area to activate cursor I have a text box that is enabled, but almost acts like it is disabled. It will only put the cursor in the textbox if I click on the left border of the box. If I click in any of the other normal white space in the box, it doesn't do anything. I have to hunt for the 'sweet spot' to get the cursor to appear and start typing. This seemed to randomly crop up and I do not know of any settings that would relate to this behavior. Any Ideas?
It is being covered partially by another element. Use a tool that allows you to right click and inspect an element, such as Firefox's built in inspector or firebug and that should show you the element that is in front of the textbox.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, asp.net" }
Print number of records in a table? How do you print the number of records in a mysql table?
Modified from PHP: mysql_result <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db('database_name')) { die('Could not select database: ' . mysql_error()); } $result = mysql_query('SELECT COUNT(*) FROM myTable'); if (!$result) { die('Could not query:' . mysql_error()); } $rowCount = mysql_result($result, 0); // get the count echo $rowCount; // echo the count mysql_close($link); ?> Check out the PHP mysql functions if you're just getting started. If you're using any kind of framework, check out the database documentation for that framework.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, mysql" }
Adobe Acrobat / Microsoft Outlook - Placing a <hr> or similar in a mailto link Currently I have: mailto:[email protected]?subject=Test Subject &body=Paragraph One. %0A%0A <hr/> %0A%0AParagraph Two. %0A%0AParagraph Three. %0A%0AParagraph Four. And the hr code isn't working because it is in the body and it is reading it as plain-text. Any way to get a hr working in the mailto or anything similar? Would love to break up paragraph one from the rest of the body if possible. Thank you !
Can't do that. Mailto only works with plain text body, no HTML.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "pdf, outlook, acrobat, mailto" }
Windows Phone read the accounts of the owner I am making an app for Windows Phone 8 and I want to know if I can read the phone owner's accounts programmatically, such as windows live id, gmail, facebook and so on.
No, users have to authenticate with all of those again in your app.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "facebook, windows phone 8, gmail, windows phone, windows live id" }
Fastest way to iterate a List<T> in the order defined by an int[] What ist the fastest way to iterate a list of elements where each item has an associated "score" and items with hightest score come first. Example: List<X> items = new List<X>(new X[]{a,b,c,d}); int[] score = new int[]{20,301,-34,7}; foreach(X x in IterateByScore(items,score)) { // <-- Fastest way to do this? // order should be b - a - d - c } **Edit** : The first example used an order list which could be used as indices, but I have a list of "scores". Please excuse the mistake.
For the updated question, I assume that the most efficient would be the `Array.Sort` method: List<X> items = new List<X>(new X[] { a, b, c, d }); int[] score = new int[] { 20, 301, -34, 7 }; List<X> sorted = items.ToArray(); Array.Sort(score, sorted); foreach (X x in sorted) { // process x here }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "c#, sorting, iteration" }
Port forward an incoming SQL connection over TeamViewer VPN I have a remote server which in turn has access to a SQL Server instance running in the same network. I am developing tools to use this SQL server, but have no backup or rights to backup/copy the structure of the database. Therefore I need access to this database on my development machine. We connect to the remote server using TeamViewer, and can access the server using the TeamViewer VPN. Is there any way I can set the server to "Forward" on all incoming connections on Port 1433 (these will only come over the VPN) to the local IP address for SQL Server?
Thanks to @TheCleaner for the guidance. However I found a workaround that I thought I'd share in case someone else runs into a similar situation. The trick was to install SQL Server Express on the intermediate server which I have control over. I then added a "Linked Server" to the target SQL Server instance on a different server. The TeamViewer VPN allows me to reach the intermediate SQL Server, and then I can query the Linked server from my development machine. A small tweak to my code allows the queries to run against the linked server "server.database.dbo.table" rather than just "dbo.table" when I'm in development mode.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "sql server, port forwarding, teamviewer" }
Likelihood function for MLE Refer to the Example 7 in this lecture: ![enter image description here]( How did the author obtain the likelihood function ? Is it from binomial? Can someone show the steps to the likelihood function? Thank you!
Suppose $k_1+k_2+k_3=n$ with $k_i\in\\{0,1,\ldots,n\\}$, so that a sample of $n$ people is being considered. Here $k_i$ denotes the _observed_ number of people in the sample having a particular genotype. Let $X_i$ be the number of people having a particular genotype in the population, $i=1,2,3$. Then $(X_1,X_2,X_3)$ has a multinomial distribution with probability mass function $$P(X_1=k_1,X_2=k_2,X_3=k_3\mid\theta)=\frac{n!}{k_1!k_2!k_3!}\theta^{2k_1}(2\theta(1-\theta))^{k_2}(1-\theta)^{2k_3}\quad,k_1+k_2+k_3=n$$ This is the formula for the likelihood function used in your note. But since the likelihood is a function of the parameter $\theta$ with respect to which it is to be maximized to get an estimate of $\theta$, you can drop the constant which is free of $\theta$. So having observed $(k_1,k_2,k_3)$, likelihood function is simply $$L(\theta\mid k_1,k_2,k_3)\propto \theta^{2k_1}(2\theta(1-\theta))^{k_2}(1-\theta)^{2k_3}\quad,\,0<\theta<1$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, statistics, probability distributions, maximum likelihood" }
How to detect when UIviewcontroller becomes active again after pushing a child view? How to detect when UIviewcontroller becomes active again after pushing a child view? Ie when using Uinavigatipncontroller Ie which callback method in the parent uiviewcontroleer to use?
If this is for an iPhone app, then `viewDidAppear:` or possibly `viewWillAppear:` will get called when the child view goes away.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "iphone, ios, uiviewcontroller, uinavigationcontroller" }
Two inequalities imply third? I'm spinning my wheels here - I was able to figure out the solution to my previous question: < but need help on the finishing touch. $$\mathrm{Does} \ \ \dfrac{\tau+1}{\mu+\mu_T}<1, \dfrac{\beta(1+\dfrac{1}{\tau})}{\mu+\mu_A}<1 \Rightarrow \dfrac{(\beta+\tau)(1+\dfrac{1}{\tau})}{\mu+\mu_T+\mu_A}<1?$$
**No.** Let $\tau, \beta, \mu = 10$ and $\mu_T = \mu_A = 2$. Then $$\frac {10+1} {10+2} = \frac {10(1+1/10)} {10+2} = \frac {11} {12} < 1,$$ but $$\frac {(10+10)(1+1/10)} {10+2+2} = \frac{22}{14} > 1$$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "inequality" }
How can I record an offline contribution with multiple line items? My use case is a donor who makes a donation that needs to be allocated to multiple funds. For instance, a check for $20,000, with $10K for general operating expenses and $10K for a special program fund. While I'm clear how to make an online contribution page that allocates funds to multiple line items, I'm not sure if there's a way to do this from an offline contribution page.
* Create a Price Set for contributions pointing to the multiple funds needed. Each fund should have a price of 1.00. You could include additional funds besides the two in question so that the Price Set is ready to be used like this in the future for other potential donation splits. * If the donation needs to be attributed to a certain contribution page, create that contribution page. * Enter a 'New Contribution' under 'Contributions' menu. * Once the price set is created, next to the amount field, you should have the option to choose a Price Set. * Choose your new price set, and split the donation as needed to each fund. * Enter the check info and other pertinent contribution info. * Pick Contribution Page under 'Additional Details' if needed.
stackexchange-civicrm
{ "answer_score": 3, "question_score": 1, "tags": "contributions, line items" }
How to let Terminal on Mac OS behave show folders and executables and such in different colors? On Linux (e.g. Ubuntu) the terminal shows you executables and folders and such in different colors so you can identify them easier. Is this possible on Mac OS Terminal, too?
To add color output of the _ls_ command, you need to edit your ~/.bash_profile and add: export CLICOLOR=1 export LSCOLORS=ExFxCxDxBxegedabagacad This is just an example, look at the _ls_ manpage on how to change specific color values.
stackexchange-apple
{ "answer_score": 16, "question_score": 7, "tags": "terminal, color" }
How can we take out the product of elements? I have the list named as `input_list = [1, 2, 3, 4, 5]` , I want to take the product of every elements except the specific index which is running at the moment. **Example** input_list1 = [1, 2, 3, 4, 5] If I say that in the first index the value is 1 , in the output list, its product will be the all elements except first index `(5*4*3*2)` and insert it into new list, same goes for all elements. **Expected_Output:** prod = [120, 60, 40, 30, 24]
You can use `math.prod` for the task: import math out = [ math.prod(input_list1[:i] + input_list1[i + 1 :]) for i in range(len(input_list1)) ] print(out) Prints: [120, 60, 40, 30, 24]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "python, list, product" }
Equal area projection of Antarctica ? I was looking for an equal area projection of Antarctica, but it seems that the Lambert Azimuthal Equal Area (< , also called 102020 by ESRI) is deprecated because it is not a "true" equal area projection. Is there any "equal area" projection that I could use as a standard for the South Pole ? If not, what are the possible workarounds ?
Following the chain of references in Lambert Azimuthal Equal Area EPSG:3974 leads via NSIDC EASE-Grid South to WGS 84 / NSIDC EASE-Grid 2.0 South that looks promising. This points to Brodzik, M. J., B. Billingsley, T. Haran, B. Raup, M. H. Savoie. 2014. _EASE-Grid 2.0: Incremental but Significant Improvements for Earth-Gridded Data Sets._ ISPRS International Journal of Geo-Information 2012, 1, 32-45 & correction in 2014, 3, 1154-1156.
stackexchange-gis
{ "answer_score": 1, "question_score": 3, "tags": "coordinate system, antarctica, equal area" }
How to get row data from DataGridview after user deleting it I'm working in a project for a shop and using DataGridView to store all customer orders and update the total price continuously. I update the price when he order more items easily. When I remove a specific item, I need to know its data to update the total price too. So I need that row's content to make the change I need. That's what I use to update the total price when he adds more items: DataGridViewRow row = new DataGridViewRow(); row.CreateCells(pill); row.Cells[2].Value = name; row.Cells[1].Value = price; row.Cells[0].Value = quantity; pill.Rows.Add(row); totalPrice += price * quantity; total.Text = totalPrice.ToString();
There is an event called `UserDeletingRow`. It accepts `DataGridViewRowCancelEventArgs` which contains row that user deletes. What you need to do is to subscribe to this event, and update your price from there.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, desktop application" }
How to append an Observable array to existing one consumed via Angular async pipes? I've got a service call that loads ten items onto the screen. When users click a "View More" button, I send another call to the service with different paging arguments. What's the best way to gracefully append the new array of items from the second call into the existing array emitted by the first call? My example below technically works, but it resets the original observable, refreshing all items on the screen, rather than just adding the new ones. Thoughts? Could Subjects help with this? private onViewMoreClicked(): void { this.pageOffset += this.pageLimit; const moreItems$ = this.itemService.get( this.pageLimit, this.pageOffset ); this.items$ = forkJoin(this.items$, moreItems$).pipe( map(([a, b]) => [...a, ...b]) );
Maybe try something like this or this... Setup in the on-init… ngOnInit() { this.pageOffset = 0; this.items$ = this.nextPage$.pipe( // load first batch when Angular async pipe subscribes startWith(this.pageOffset), // switch observable to output of getMessages switchMap(offset => this.itemService.get( this.pageLimit, offset )), // add newly-emitted batch to previously-emitted items scan((acc, curr) => { acc.push(...curr); return acc; }, []) ); } And this should be the view more click handler… private onViewMoreClicked(): void { this.pageOffset += this.pageLimit; // load new items into message$ this.nextPage$.next(this.pageOffset); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "angular, rxjs, rxjs5, rxjs6" }
Is there a set identity_insert on equivalent for SQLite? In TSQL there is SET IDENTITY_INSERT ON; is there a functional equivalent in SQLite?
SQLite always allows inserting a value into the primary key column; automatically generated values are used only when the inserted value is `NULL` (explicitly or omitted). For details, see the documentation.
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 14, "tags": "sql server, sqlite, auto increment" }
How to open a form with a button and automatically assign a value to one of the fields I want to open a form by clicking a button and I want the form to open with a value written in one of the fields. I could achieve this by just puting the value in the default value of the field. but i want it dynamic in a way that when i open the form with another button, i want another specified value to show up in the field. This is the code of the button to open the form FRM_PRODUCT_COMMENT. I want inventory to be wriiten in the field 'Thema' `'DoCmd.OpenForm "FRM_PRODUCT_COMMENT", WhereCondition:=[THEMA]= "Inventory" , acNormal, , ,acFormAdd` Also from another button , i want to open the same form with another thing writtten in the field 'Thema'
Something like so, setting the textbox value afterwards : DoCmd.OpenForm "frmTestForm", acNormal, , , acFormAdd, acWindowNormal Forms("frmTestForm").Controls("txtTextboxTest").Value = "Testing"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vba, ms access" }
Angularjs for inside Controller running just once I'm trying to store the ids of an array of objs, but appears that this for loop is running just once, very strange for (var i = 0; i < softwareIds.length; i++) { var b = softwareIds[i].id; } console.log(b); console.log(softwareIds); the last two lines of consoles returns this: (number 2 is the first console.log returning the last obj id, and [Object, Object, Object] in the second console.log) ![enter image description here]( I'm using angujarJS, this for are inside a Controller, any idea?
You should declare the array first. see below $scope.b = []; for (var i = 0; i < softwareIds.length; i++) { $scope.b.push(softwareIds[i].id); } console.log(b); Your for loop is working fine but you are every time overwriting the value stored in the variable. You should push id value in an array.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, angularjs" }
cancan: is it possible to create an alias for more than one action? My ability model contains 8 roles. I'd like to use aliases to help simplify the content. Can an alias contain more than one action, e.g. alias_action :action1, action2, :to => :basic_access Also, is this the correct placement of the alias? class Ability include CanCan::Ability alias_action :action1, action2, :to => :basic_access def initialize(user) ... Thanks
From the wiki: < 1. Yes, `alias_action` can be called with more than one action. 2. It looks like you need to move your `alias_action` call into `initialize`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails 3, cancan" }
How to get the attr reference in code? I'm looking to get the pointing reference from an attribute via code. In my xml layouts I can easily get the referenced drawable like this: android:background="?attr/listItemBackground" The attribute reference is set by my Theme. I'm looking to see if it's possible to get that referenced drawable via code. I can work around this by creating style attr and reading the value inside a custom view but in this case I want to figure out if this is possible without doing all that. I would think it would be possible but I haven't found ways to get that attribute reference. Thanks!
This is how you do it: // Create an array of the attributes we want to resolve // using values from a theme int[] attrs = new int[] { R.attr.listItemBackground /* index 0 */}; // Obtain the styled attributes. 'themedContext' is a context with a // theme, typically the current Activity (i.e. 'this') TypedArray ta = themedContext.obtainStyledAttributes(attrs); // To get the value of the 'listItemBackground' attribute that was // set in the theme used in 'themedContext'. The parameter is the index // of the attribute in the 'attrs' array. The returned Drawable // is what you are after Drawable drawableFromTheme = ta.getDrawable(0 /* index */); // Finally, free the resources used by TypedArray ta.recycle();
stackexchange-stackoverflow
{ "answer_score": 114, "question_score": 49, "tags": "android, android layout" }
composer.json specifies dependency, but no composer.lock was found I have added sendgrid and changed composer.json file in heroku. composer.json file contains { "require": { "ext-mbstring": "*", "sendgrid/sendgrid": "2.0.5" } } on commit the file !enter image description here When I push into heroku I wiil occurs error as shown in below image !enter image description here
After installed composer and restart the computer I have used the `composer update` command and then it works fine and error solved
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "git, heroku, composer php, sendgrid" }
Creating a Dom element for form onsubmit="return function(x)" I am trying to create a DOM element of a form that has "return function(input)" as it's onsubmit. But the function doesn't see, to be called function AddComment(id) { alert(id); return false; } Above is the function that should be called. Below is the DOM element's code where I generate the onsubmit event: ... form.onsubmit = 'return AddComment('+ place.place_id+')'; ...
The `form.onsubmit` property expects a function reference instead of a string containing code to be evaluated. You could create a wrapper function and assign that instead: form.onsubmit = function() { return AddComment(place.place_id); };
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, dom" }
Why does my lua script print both values? first of all, this is my first time coding in Lua, let alone coding at all. I'm testing out lua for making some mods, and I can't really figure out what i'm doing wrong. I'm trying to get my script to say 2 different things with 2 different values, but lua keeps printing BOTH values. Here is my code: sword = unequipped if sword == equipped then print("This feels quite heavy")end if sword == unequipped then print("I feel unstoppable") end When I run the script, it prints out both values, so in terminal, it says; This feels quite heavy I feel unstoppable How can i fix this? Thanks in advance!
I suspect your problem is you haven't defined `unequipped` or `equipped` so they are both `nil` so `sword` is equal to both of them. In general when you have a problem like this, try using the interactive interpreter. e.g. bash-3.2$ lua Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio > sword = unequipped > print(sword) nil > print(equipped) nil > print(sword == equipped) true
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "lua" }
Rails_admin, change order of columns in list In rails_admin list shows all available columns of model according to how columns are ordered in database: ![pic]( However, I want different order in list page. I want first `name` and then other fields in table. Is it even possible? There are no mentions in documentation of rails_admin about it.
You can read about ordering of fields here: < In case your model is called User, create a new configuration file `config/initializers/rails_admin/user.rb` with the following content: if User.table_exists? RailsAdmin.config User do list do # simply adding fields by their names (order will be maintained) include_fields :name, :id, :created_at, :updated_at, :version, :shopping_malls end end end Let me know if this works out!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "ruby on rails, rails admin" }
encode x264(libx264) raw yuv frame data I am trying to encode an MP4 video using raw YUV frames data, but I am not sure how can I fill the plane data (preferably without using other libraries like ffmpeg) The frame data is already encoded in I420, and does not need conversion. Here is what I am trying to do: const char *frameData = /* Raw frame data */; x264_t *encoder = x264_encoder_open(&param); x264_picture_t imgInput, imgOutput; x264_picture_alloc(&imgInput, X264_CSP_I420, width, height); // how can I fill the struct data of imgInput x264_nal_t *nals; int i_nals; int frameSize = x264_encoder_encode(encoder, &nals, &i_nals, &imgInput, &imgOutput); The equivalent command line that I have found is : x264 --output video.mp4 --fps 15 --input-res 1280x800 imgdata_01.raw But I could not figure out how the app does it. Thanks.
Look at libx264 API usage example. This example use fread() to fill frame allocated by x264_picture_alloc() with actual i420 data from stdin. If you already have i420 data in memory and want to skip memcpy step than instead of it you can: 1. Use x264_picture_init() instead of x264_picture_alloc() and x264_picture_clean(). Because you don't need allocate memory on heap for frame data. 2. Fill x264_picture_t.img struct fields: * i_csp = X264_CSP_I420; * i_plane = 3; * plane[0] = pointer to Y-plane; * i_stride[0] = stride in bytes for Y-plane; * plane[1] = pointer to U-plane; * i_stride[1] = stride in bytes for U-plane; * plane[2] = pointer to V-plane; * i_stride[2] = stride in bytes for V-plane;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, c, x264, libx264" }
Does the parity of the identity of a group hold any known significance? I understand that for permutation groups, the parity of identity is even. However when considering, for example $\langle\mathbb{Q} \setminus \\{0\\}, \cdot\rangle$ where $\cdot$ is regular multiplication, the identity is _odd_. Does the parity of the identity tell us anything about the group or the operation?
The two notions of parity you've brought up are really unrelated. In fact the "parity" of $1 \in \mathbb{Z}$ is not intrinsic to that group in any way. You could have labeled the elements of $\langle \mathbb{Z}, \cdot \rangle$ however you liked, not even necessarily with numbers, as long as the binary operation works out the same way. You could have called the multiplicative identity $\mathfrak{I}$ if you wanted, or $\ddot\smile$. What would the parity of the identity be then?
stackexchange-math
{ "answer_score": 3, "question_score": -1, "tags": "abstract algebra, group theory, permutations, parity" }
Can I use .NET with classic ASP? Due to a customer requirement I am forced to use classic ASP, so I am wondering if I could use .Net (or maybe JScript which as new features) to try to add some advanced features. I really would like a decent way to connect to SQL Server. How to do it? Amazingly the customer relented and would like to go with ASP.Net now. Thanks for all the help.
I have some links for you to try 1) .NET COM+ Interop Component with Classic ASP 2) Consume a .NET Assembly from a classic ASP page. Good luck
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": ".net, asp classic" }
create ip external valid in the network interface I am buying a software, but the distributor said that it needs the valid ip configured in the network interfaces, is it possible? ![enter image description here](
If your software vendor requires a public IP address to be bound to your VM instance, the answer is that this is not possible. In Google (and AWS, Azure, etc), public IP addresses are not bound to the Ethernet interfaces on the VM instance. The public IP address is assigned to the public side of a 1-to-1 NAT gateway. This gateway does the translation from a public IP address to the private IP address that is assigned to your VM instance. Share this information with the software vendor. As the cloud grows in popularity, they will need to find another way to authorize their licenses.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "google cloud platform, google cloud networking" }
How to keep groups when pulling with git I have a staging site that is a working directory of a git repository. How to set up git to let a developer pull out a branch or release without changing the group of the modified files? An example. Let's say I have two developers, robin and david. They are both in git-users group, so initially they can both have write permissions on site.php. -rw-rw-r-- 1 robin git-users 46068 Nov 16 12:12 site.php drwxrwxr-x 8 robin git-users 4096 Nov 16 14:11 .git After robin-server1$ git pull origin master: -rw-rw-r-- 1 robin robin 46068 Nov 16 12:35 site.php drwxrwxr-x 8 robin git-users 4096 Nov 16 14:11 .git And david do not have write permissions on site.php, because the group changed from 'git-users' to 'robin'. From now on, david will get a permission denied, when he tries to pull to this repository.
This is best addressed with setting the permissions on all of the directories. If you set the the group 'setgid' bit, all files in the directory will maintain the group of the directory when members of the group modify them. So, to quickly set this on the staging site do the following: chmod g+ws [directory] find [directory] -type d -exec chmod g+ws {} \; find [directory] -type f -exec chmod g+w {} \; The first command sets the write and setgid bits for the group on the site top level directory. The second then finds all subdirectories of the top level folder and does the same. The third then makes sure the the group has write access to all of the files. When you initially create the git repository, you can have it do the above automatically by using the `--shared` option: git create --shared [directory]
stackexchange-serverfault
{ "answer_score": 5, "question_score": 1, "tags": "linux, git, file permissions" }
What is the alternate to \n in python? I want to print the following output in python: 99 buckets of bits on the bus. 99 buckets of bits. Take one down, short it to ground. 98 buckets of bits on the bus. with a single print command and no "\n" characters in between. How can this be done?
With triple-quoted string literals, you can use actual newlines instead of `\n`. print(""" 99 buckets of bits on the bus. 99 buckets of bits. Take one down, short it to ground. 98 buckets of bits on the bus.""")
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -4, "tags": "python, newline, end of line" }
Best Practice of saving an access token in iOS I am currently working on an iPhone-App which needs to store an access-token somehow. I am just saving it inside the NSUserdefaults but i dont think it is safest way of persisting sensitive data like this. So my question now is: What is the best and safest way of storing data like this on an iOS-Device?
> I am just saving it inside `NSUserDefaults` but I don't think it is the safest way of persisting sensitive data like this. Almost. `NSUserDefaults` uses plaintext for storing data, so it is insecure. If you want to be a bit safer, you can store the data in the keychain (however, even this considered-to-be-secure storage can be easily dumped...)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "ios, cocoa touch, security, nsuserdefaults, access token" }
How should I keep track of an elements' state within a window/view? I am trying to implement a view that contains many elements, whose state change depending on the actions you perform on it. I guess this is something that people often run into so I would like to know what approach works best for you. What I usually do is define several states for my view: {Loaded,Initialized,...} and then set the state of each element for that state. The thing is even the most trivial event,a click on a button for example, makes the state change, so I need a lot of different states, with many of them containing duplicate information since they are very similar to each other. This seems very repetitive and unefficient but has worked for me up until now, when I need a better way of doing this kind of stuff. This issue must have been around for quite a while, so it would be nice to know people's tricks & tips, best-practices, and documents of reference.
To be honest, I am a bit baffled by your question. I have now read it several times and this just doesn't make any sense. If you work in a proper MVC environment, then your view shouldn't need to keep track of state. The view simply displays the data and the state held in the model. It receives events and dispatches them to the controller or directly to the model components (depending on how strict your MVC implementation is). If the click of a button changes the state of an underlying model, then that model will raise another event, which can lead to a modification of the view through an event handler. But maybe I am totally off the track here. Could you explain this in a little more detail?
stackexchange-softwareengineering
{ "answer_score": 1, "question_score": 0, "tags": "event programming" }
Does "**societies**" here mean "groups of people" or "registered organizations"? This page says > In the decades since the 1960s, ACM, along with leading professional and scientific computing **societies** , has endeavored to tailor curriculum recommendations to the rapidly changing landscape of computer technology. As the computing field continues to evolve, and new computing-related disciplines emerge, existing curriculum reports will be updated, and additional reports for new computing disciplines will be drafted. Does " **societies** " here mean "groups of people" or "registered organizations"?
In this case, _societies_ mean organizations with similar interest and profession. > _ACM and leading professional and scientific computing societies (organizations or firms sharing similar profession or interest) has endeavoured..._ More such usages are here on Collins.
stackexchange-ell
{ "answer_score": 0, "question_score": 0, "tags": "meaning, expressions" }
Can't cancel the subscription on stripe in cakephp I'm using this Cakephp StripeComponent plugin : < Everything is working fine but I can't cancel the subscription with this plugin. I had tried this < but no success. As its saying to `retrieve` the subscription and then `cancel()`But this plugin doesn't have any `retrieve subscription` function. When I tried this, $sub = \Stripe\Subscription::retrieve('SUBSCRIPTION_ID'); $sub->cancel(); I'm getting error `Fatal error: Call to undefined method Stripe\Subscription::retrieve()` I'm stuck.. Please help me out from this.
I searched this problem too much on google but I got only some results like * Update Stripe library to 3.13.0. * Add custom functions.... etc. Finally I solved this problem by myself.. In the `StripeComponent.php`, write this function: public function subscriptionCancel($cust_id) { Stripe::setApiKey($this->key); $customer = false; try { $customer = Stripe_Customer::retrieve($cust_id); $customer->cancelSubscription(); } catch (Exception $e) { return false; } return $customer; } And call this `function subscriptionCancel()` in your Controller as: `$subscription = $this->Stripe->subscriptionCancel($cust_id);` So the subscription related to particular `$cust_id` will be canceled.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "cakephp 2.0, stripe payments" }
Which Data Source I have an xl spreadsheet that I'd like to scrap. I'll replace it with a simple windows form application built with c#. The spreadsheet has a table with just two columns: * Date * Staff Member So a sample of the table might look like: * 01-Jan Jason * 02-Jan * 03-Jan Mike As you can see it's very simple. I use Sqlserver everyday but it would seem like overkill to put this table into a db on Sqlserver. What datasouce should I use for the windows form - a text file? note: not sure if it influences my choice of datasouce but I'm thinking of using a calender tool and maybe a datagridview in the form.
Its not overhead to use sql server at all, if you wish to ditch the file/spreadsheet. Also using sql-server will be a consistent method of data storage if that is what you currently use for other apps. It really should take very little time to do. Also assuming your sql setup does automatic backups etc, then it will ensure you don't lose the information. Hands down make use of sql server if you have access to it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, winforms" }
Get hostname of client pc via javascript or jquery I have an intranet app that needs to know where to print some labels. We have multiple workstations setup. I need a way to retrieve the host name of the client so that when they print something it comes out of the correct printer. Right now I have this being set at login but was curious if I could actually pull the host name on the client side, then on the server side i could easily parse the hostname to set the printer. The solves the problem of a user being logged into two workstations at once. Granted it shouldn't happen but users will be users. The application is printing labels to a zebra printer so the printing occurs on the server but the print job is sent to the label printer that is next to the workstation being used. TIA!
Since the printing is done server-side, why do you need a JavaScript solution? What you need is to check whatever is the equivalent to the REMOTE_HOST and/or REMOTE_ADDR CGI variables on your server's implementation. **Edit** : in case you can't change the printing code, reverting to a separate script called through AJAX, as Andrew suggested, may be a way of getting what you want. But it looks like a very circuitous way of doing it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
webkit - css transition effect on a div I am trying to do fadein/out effect when I change innerHTML of a div. Even tried example given at safari doc I want the div to fade-out, change the contents and then fade-in again with new content. <style> .cv { background-color: #eee; -webkit-transition: all 1s ease-in-out;} .cf {opacity: 0;} </style> <body> <div id="main"> <div id="c"> OLD </div> </div> </body> <script> var c = document.getElementById("c"); c.setAttribute("class", "cf"); c.innerHTML = ''; c.appendChild(fragment); c.setAttribute("class", "cv"); </script> Please help me here
This is what I finally ended doing. Thank you all for the answers init: function(fragment) { var c = document.getElementById("c"); c.addEventListener( 'webkitTransitionEnd', IDR.callHook(c, fragment), false); c.setAttribute("class", "cv hide"); }, callHook: function(c, fragment) { var fp = function() { c.removeEventListener('webkitTransitionEnd', fp, false); c.innerHTML = ''; c.setAttribute("class", "cv"); c.appendChild(fragment); }; return fp; },
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, css, webkit, css transitions" }
using an implode inside double quotes why is this not valid: `$foo = "blah blah {implode(',', $some_array['a key'])}";` which gives the error: > unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier I think using a key of the array is the reason. Is it possible to use implode inside double quotes, or do I have to put the string in a variable first?
The way you are using it now is designed for class propeties for instance: $foo = "blah blah {$user->name}"; If you want to use functions without declaring the variable earlier, just use it this way: $foo = 'blah blah ' . implode(',', $some_array['a key']);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -3, "tags": "php" }
how do I upload a file to the server in the folder uploads in yii basic. I have tried but its npt working Its not uploading the file the folder in the project. How can I upload the file? public function actionCreate() { $model = new UploadForm(); if ($model->load(Yii::$app->request->post()) && $model->save()) { $filename=$model->filename; $model->file= UploadedFile::getInstance($model,'file'); $model->file->saveAs('uploads/' .$filename.'.'.$model->file->extension );
Declare an attribute to store the file name in the model class. Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name. Then, in the controller class define an action method to collect user-submitted data. $model = new UploadForm(); if(isset(Yii::$app->request->post())) { $model->attributes=Yii::$app->request->post(); $model->file=UploadedFile::getInstance($model,'file'); if($model->save()) { $model->file->saveAs('path/to/localFile'); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "php, yii2" }
Delphi - Find text in large TMemo I have a TMemo which **contains quite a lot of texts** , 80M (about 400K lines). The TMemo is set with WordWrap = FALSE, there is **no need** to find texts that wrapped in 2 lines. I need a fast way to find a text, from the beginning, and also find next. So, I put a TEdit for putting the text to find and a TButton to find the text in the TMemo. I was thinking to use Pos(), checking line by line, but that will be slow. And I don't know how to determine the TMemo.Lines[index] for current cursor position. Anyone can come up with solution? Thanks **UPDATE:** I found a solution from here: Search thru a memo in Delphi? The SearchText() function works, fast, and very fast. Took couple of seconds to search unique string at the bottom end.
A little addition to the previous answers: you can get the line number without selecting the pattern found, like this: procedure TForm1.Button3Click(Sender: TObject); var I, L: Integer; begin Memo1.WordWrap:= False; Memo1.Lines.LoadFromFile('Windows.pas'); I:= Pos('finalization', Memo1.Text); if I > 0 then begin L := SendMessage(Memo1.Handle, EM_LINEFROMCHAR, I - 1, 0); ShowMessage('Found at line ' + IntToStr(L)); // if you need to select the text found: Memo1.SelStart := I - 1; Memo1.SelLength := Length('finalization'); Memo1.SetFocus; end; end; Note that line number is zero-based, also you should subtract 1 from `Pos` result to obtain zero-based offset for `SendMessage` and `TMemo.SelStart`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "delphi, full text search, delphi 7, memo" }
WPF SelectedIndex set issue of TabControl I have a TabControl with two items. <TabControl x:Name="tab" SelectionChanged="TabControl_SelectionChanged"> <TabItem Header="TabItem1"> <Grid /> </TabItem> <TabItem Header="TabItem2"> <Grid /> </TabItem> </TabControl> private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { Debug.WriteLine("Selected Index: " + tab.SelectedIndex); if (tab.SelectedIndex == 1) { tab.SelectedIndex = 0; } } when click 2nd item, 1st item have focus and print below. Selected Index: 1 Selected Index: 0 but retry clicking 2nd item, no output! SelectionChanged event do not fire. what's wrong? Is there work around?
This is because you are changing the selectedIndex within the SelcetedIndexChanged event which will call itself in sycnhronous manner. Instead try to put it on UI dispatcher in an aysnchronous manner like this - private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { Debug.WriteLine("Selected Index: " + tab.SelectedIndex); if (tab.SelectedIndex == 1) { Application.Current.Dispatcher.BeginInvoke ((Action)delegate { tab.SelectedIndex = 0; }, DispatcherPriority.Render, null); } } It will give you the desired output.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "wpf, tabcontrol, selectedindex" }
indexes versus labels in neo4j I was looking into Neo4j sometime last year before labels were introduced, and am trying to catch up to changes to get back into 2.0. What's the difference between **labels** and the current automatic node **indexes** , and how should I use them differently in modeling? Is it that labeling doesn't enforce uniqueness on a param, but indexing on that param does? (The link on the main neo4j page is down: < so I'm having trouble trying to just look this up.)
Always use labels for exact indexing--they're more efficient and easier to use, as well as offering things like unique constraints on fields. The legacy indexes are still required for things that require lucene syntax or FTS, but hopefully the new indexes will support that functionality soon. The main reason the new label-based indexes are more efficient is you pick which nodes you want to index by the label (there's a separate index for each label/property). With autoindexes, there was no way to do this--all nodes were indexed.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "database design, indexing, neo4j, modeling" }
PySpark how to get the partition name on query results? I would like to retrieve the partition name on query results. So if I have a partition like: dataset/foo/ key=value1 key=value2 key=value3 I can do this query results = session.read.parquet('dataset/foo/key=value[12]') \ .select(['BAR']) \ .where('BAZ < 10') Once I do this how to know the partition origin for each results ? Indeed I can get only values form the `BAR` column. Thanks for your help
Include `key` column in your select statement! #read foo directory as it is partiitoned so we can filter on the key results = session.read.parquet('foo/') \ .select(['BAR','key']) \ .filter((col("key") == "value1") & (col("BAZ") < '10')) * * * In case if you want to add origin **filename** to all records then use `input_file_name()` from pyspark.sql.functions import * results = session.read.parquet('foo/') \ .select(['BAR','key'])\ .withColumn("input_file", input_file_name()) \ .filter((col("key") == "value1") & (col("BAZ") < '10'))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "pyspark, apache spark sql, parquet" }
QuickStart Tutorials for Rational Functional Tester (RFT) I am new to RFT. Infact I have seen the interface only once. But now my next project seems to be an automation using RFT. I would like to get some quick start on learning RFT(Rational Functional Tester). Can anyone show me some quick links as to where can I start with this? Thanks in advance.
Your best bet is to first download RFT from here Once the installation is done, Click the Help tab, and then click Tutorials. That will be a good quick start IMO. Then access the sample projects in RFT and it is Eclipse based, so if you have used Eclipse before, it will be fairly easy to pick up. You could go in more detail later, and look up features like "keyword driven frameworks" etc for a real world example. Best of luck!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "rft" }
How can I print polymorphic values in Standard ML? Is there a way to print polymorphic values in Standard ML (SML/NJ specifically)? I have a polymorphic function that is not doing what I want and due to the abysmal state that is debugging in SML (see Any real world experience debugging a production functional program?), I would like to see what it is doing with some good-ol' `print`'s. A simple example would be (at a prompt): fun justThisOnce(x : 'a) : 'a = (print(x); x); justThisOnce(42); Other suggestions are appreciated. In the meantime I'll keep staring the offending code into submission. ### Update I was able to find the bug but the question still stands in the hopes of preventing future pain and suffering.
No, there is no way to print a polymorphic value. You have two choices: * Specialize your function to integers or strings, which are readily printed. Then when the bug is slain, make it polymorphic again. * If the bug manifests only with some other instantiation, pass `show` as an additional argument to your function. So for example, if your polymorphic function has type 'a list -> 'a list you extend the type to ('a -> string) -> 'a list -> 'a list You use `show` internally to print, and then by partially applying the function to a suitable `show`, you can get a version you can use in the original context. It's very tedious but it does help. (But be warned: it may drive you to try Haskell.)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "functional programming, polymorphism, printing, sml" }
Exporting entire bbox from overpass turbo? I'm trying to export all the elements (peak, tracks, routes, streets.....) of a bounding box I have selected. I'm trying to do this with the wizard, but within it, I have to choose specific tags and so export one element per each time, right?
To copy from the documentation, `(node(50.746,7.154,50.748,7.157); <;); out meta;` (replace numbers with `lat_min`, `lon_min`, `lat_max`, `lon_max` for your query) to get all the features for a bounding box. Note that the amount of data returned can be very, very large. If you need an entire dataset for a administrative region or a whole country, you better off using regional extracts.
stackexchange-gis
{ "answer_score": 5, "question_score": 1, "tags": "openstreetmap, extents, overpass api" }
Angularjs $http GET method change to OPTION, while adding custom headers var users= $resource(' {}); users.get(); After adding header method, http GET method change to OPTION var users= $resource(' {}, { get:{ method:"GET", headers:{'x-access-token':'token'} } }); users.get(); Please guide me why GET method change to OPTION Method.
Preflight that causes confusion --> Preflight is an additional request the XHR object makes to make sure it's allowed to actually make the request Check out <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "javascript, angularjs, cross domain" }
How to delete line if longer than XY? How can i delete a line if it is longer than e.g.: 2048 chars?
sed '/^.\{2048\}./d' input.txt > output.txt
stackexchange-unix
{ "answer_score": 40, "question_score": 36, "tags": "sed" }
How to adjust constraints / DB mapping for Map within grails domain class Following grails domain class: class MyClass { Map myMap } Now for myMap, grails automatically creates a new table for the elements in the map. However if I add elements which are too long (e.g. 1024 characters), I get a DB error. Can I somehow tell grails to make the respective column in myMap's table big enough to allow for larger Strings, or do I have to do this manually in the DB? I already tried static constraints = { myMap(maxSize:1024) } which doesn't work (as expected because maxSize should refer to the Map's values and not to the Map itself). If not via constraints, maybe there's a way to do it via static mapping { ... } ?
An alternative approach I used successfully was to push the map out into a collection of a collaborator domain class. class DynaProperty { String name String value static belongsTo = MyClass static constraints = { value(maxSize:4000) //Or whatever number is appropriate } } And then in MyClass: class MyClass { static hasMany = [dynaProperties:DynaProperty] } This is _almost_ a map, and it gives you the ability to use dynamic finders to pull up an individual entry.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "database, grails, mapping, hibernate mapping, grails domain class" }
Difference between " in a row" and "at a stretch" There is a sentence, "He would study for eight to ten hours at a stretch." If I say, "He would study for eight to ten hours in a row.", does the meaning the same? The dictionary says that "in a row" means without a break, and "at a stretch" means continuously. To me, these two phrases seem to have the same meaning. Could you explain how to use these two? Also how about "eight to ten straight hours"? Does this also have the same meaning?
If something happens several times in a row, it happens in exactly the same way each time and nothing different happens in the time between. _Example:"He won two gold medals in a row."_ "At a stretch"means to do something without stopping. _Example:"He used to read for hours at a stretch."_ So as you see, they don't mean the same thing. On the other hand,"to do something for two hours straight.", means that you do something continuously, without interruption,so it has the same meaning with "at a stretch." _Example:"They have been studying for ten hours straight.", or "They have been studying for ten staight hours_."
stackexchange-ell
{ "answer_score": 2, "question_score": 3, "tags": "word meaning" }
Is there an easy way to delete all records in multiple tables (but not every table)? So I "fixed" an issue the other day, which has caused a snowball of new issues (imagine that). I have a large group of tables that serve as Temp tables for many import/export processes that flow to other systems. Each table is labeled "TO_xxxx". I want to clear all records from each "TO_" table. Is there a way to structure a delete statement to clear all records from only "TO_" tables? Is it as easy as Delete from TO_% or is there more to it? There's about 80 "TO_" tables total, so I figured I'd post here before manually going through everything. If you can help, I would appreciate it. Thanks. System is SQL Server 2016.
Borrowing from this answer, which `drops` tables with a common prefix, you could use something like this DECLARE @sql NVARCHAR(MAX) = N''; SELECT @sql += ' DELETE FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';' FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] WHERE t.name LIKE 'to[_]%'; PRINT @sql; -- EXEC sp_executesql @sql; * * * The above example _prints_ the `delete` commands. When you are ready to actually run it, uncomment the `EXEC`
stackexchange-dba
{ "answer_score": 1, "question_score": 0, "tags": "sql server 2016, delete" }
Jquery + PHP Function called by $_GET that need $_POST i've a PHP function like this: function setUser() { $userName=$_POST['userName']; $userSurname=$_POST['userSurname']; //code... } I call this function with an address like: ?index.php&module=registration So, how do i call with jquery $_GET['module'] to recall the setUser(); function and to pass it all POST parameters that i need? Can you please make me an example? Thanks and sorry for my bad english!
$("#button").click(function(e){ //e.preventDefault(); $.post('index.php?module=registration',{ userName: 'test', userSurname: 'test'}, function(data){ //callback; }); } that would be a simple jquery script to post the data. Presumably you will be grabbing the values of the post parameters dynamically from some page fields and feed it to the post function (something like `$("#name").val()`). More info at < I also added the click event, because most likely you will have this attached to a button, which when clicked will post the data (if you are using submit button you will have to uncomment the preventDefault line).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, jquery, ajax, function" }
Apply Formula to Cell Using a VBA defined Array There are definitely easier ways to achieve what this code is trying to do, but I created a simplified code to show what I am trying to achieve. Basically I want to perform calculations on lots of data and I don't want to have to have to add that to the worksheets. So basically I need to run formulas like sum, averageifs, etc. in a worksheet through using an Array that I defined in my Macro. At this point I can't figure out how to turn this array, containing 5 values, into a "=sum( )" function. Thanks in advance for your help! Sub ArraySum() Dim numbers(5) As Double Dim E As Double For I = 1 To 5 E = Cells(I, 1) numbers(I) = Cos(E) Next I Range("b1").Formula = "=sum(" & numbers & ")" End Sub
It's not clear why you'd want to do it this way, but: Sub ArraySum() Dim numbers(1 To 5) '<<< Dim E As Double For I = 1 To 5 E = Cells(I, 1) numbers(I) = Cos(E) Next I Range("B1").Formula = "=SUM(" & Join(numbers, ",") & ")" End Sub but then you might as well just do: Range("B1").FormulaArray = "=SUM(COS(A1:A5))"
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "arrays, vba, excel" }
Inequality $a^2+2b^2+8c^2\geq2a(b+2c)$ Can someone prove this inequality for the real numbers a,b,c? $$a^2+2b^2+8c^2\geq2a(b+2c)$$ I have tried simple manipulation of the terms to get quadratic expressions, but since one cannot factor the $4ac$ on the right side, I abandoned that approach. Then I tried turning it into an expression where I could apply AM-GM, but that did not work either. Maybe something like Muirhead, though I do not know where to start with that? Any and all help would be greatly appreciated!!
Your inequation is equivalent to $$(a-b-2c)^2+(b-2c)^2 \ge 0 \tag{1}$$ The advantage of expression (1) is that it allows to clearly obtain the limit cases where there is an equality sign in (1) instead of a $">"$ symbol, i.e., iff $$a=2b=4c$$ * * * **Edit:** One can wonder how I have found expression (1). If you happen to know the concept of matrix associated with a quadratic form, here is the explanation: $$a^2+2b^2+8c^2-2a(b+2c)$$ $$=\begin{pmatrix}a&b&c\end{pmatrix}\begin{pmatrix} 1& -1&-2\\\ -1&2&0\\\ -2&0&8 \end{pmatrix}\begin{pmatrix}a\\\b\\\c\end{pmatrix}$$ which can be transformed, using the so-called (incomplete) Cholesky factorization: $$=\begin{pmatrix}a&b&c\end{pmatrix}\begin{pmatrix} 1&0&0\\\ -1&1& \ \ 0\\\ -2&-2 & \ \ 0 \end{pmatrix}\begin{pmatrix} 1&-1&-2\\\ \ \ 0&\ \ 1&-2\\\ 0&0 &0 \end{pmatrix}\begin{pmatrix}a\\\b\\\c\end{pmatrix}$$ $$=\begin{pmatrix}(a-b-2c)&(b-2c)&0\end{pmatrix}\begin{pmatrix}(a-b-2c)\\\\(b-2c)\\\0\end{pmatrix}$$ $$=(a-b-2c)^2+(b-2c)^2$$
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "inequality, cauchy schwarz inequality, a.m. g.m. inequality" }
Scroll down functionality in RSS reader like Google Reader I have implemented a simple RSS reader in Java. I hit a URL and I get back some XML text. I parse it and retrieve data that I'm interested in. Now I want to implement what Google Reader is doing. It has a functionality by which we can scroll down and see old posts. How can I get these old posts as what I see is every time I hit the URL I get the same XML back?
Google hits the rss links much more often than you read it, and stores all the articles in a database. So when you read it and you scroll down in Google Reader, it actually shows you all the articles it stored in the database. The RSS url is kind of only used by Google Reader to fill its database, but not directly for the display.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java, rss, google reader, rss reader" }
Euler class as obstruction to have a never vanishing cross section We know that (see Hatcher's vector bundles and K-theory Prop. 3.22) the Euler class of an orientable vector bundle or rank $r$, $E\to M$ is the first obstruction to the existence of a never vanishing section of $E$ and thus belongs to $H^r(M,\mathbb{Z})$ . It follows that if we consider $E= TM$ the tangent bundle $r=\dim (M) =: n$ and thus the Euler class $e(TM)$ is non just the _first_ obstruction but _all_ the obstruction. > Consequently if $e(TM)=0$ there exists a non vanishing section of $TM$ This seems a bit strong as would imply that the Euler characteristic is zero _iif_ we have a never vanishing vector field. Is my argument correct?
(part of comment above converted to answer) Note that the Euler class is only defined in the case of an oriented bundle, so you are assuming your manifold to have an orientation. In that case, your argument is correct. As you noted, the Euler class is the one and only obstruction to finding a section of the sphere bundle of the tangent bundle, i.e. a nowhere-zero vector field on the manifold.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "algebraic topology, differential topology, characteristic classes, obstruction theory" }
Method with multiple @Schedule annotations does not pick second line I have stateless bean on Glassfish server v 3.1.2 with two methods which should be executed by schedule. One method should be executed once in a week and annotated as follows: @Schedule(dayOfWeek = "Sun", hour = "1", minute = "5", second = "0") Second one runs every 15 minutes, except times when first method runs and annotated @Schedules({ @Schedule(dayOfWeek = "Mon-Sat", hour = "*", minute = "*/15", second = "0", persistent = false), @Schedule(dayOfWeek = "Sun", hour = "0,2-23", minute = "*/15", second = "0", persistent = false) }) Problem is that second method runs every second from Saturday 23:45 until Sunday 00:00, then resumes execution nomrally, every 15 minutes. That suggests, that something wrong with Sunday schedule, but have no idea what's wrong. @Schedules Javadoc notes that this annotation available from Java 6. Any ideas welcome.
As no responses received, solution was found by experimenting. The solution was to rewrite `@Schedules` annotation as follows. `@Schedules({ @Schedule(dayOfWeek="Mon,Tue,Wed,Thu,Fri,Sat", hour="*", minute="*/15", second="0", persistent=false), @Schedule(dayOfWeek="Sun", hour="0,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23", minute="*/15", second="0", persistent=false) })`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, glassfish 3" }
Java output to file in table format? I have a bunch of info that I want to output to a file and it needs to be setup like a table. For example, I need columns with titles and information below each column. I have four items being printed at a time that each need their own row. A %n before the next. Should I use system.out.format? Should I be appending data to a file with the PrintStream class? I would like to stick with Java's basic utilities and classes. I want my output to look like this... *Title1* *Title2* *Title3* *Title4* *Title5* info1 info1 info1 info1 info1 info2 info2 info2 info2 info2 ....3 Thanks for any help!
You can use code like this: Formatter fmt = new Formatter(); System.out.println(fmt.format("%s %s %s %s %s", "Title*", "Title*", "Title*", "Title*", "Title*")); See Formatter java doc Sample code which prints table which has 20 characters column width: Formatter formatter = new Formatter(); System.out.println(formatter.format("%20s %20s %20s %20s %20s", "Title*", "Title*", "Title*", "Title*", "Title*")); for (int i = 0; i < 10; i++) { formatter = new Formatter(); String rowData = "info" + i; System.out.println(formatter.format("%20s %20s %20s %20s %20s", rowData, rowData, rowData, rowData, rowData)); } For writing data to file you can use java.io package
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "java, file io, formatting" }
When is map between $H^1$ of curves injective? Given a morphism $f\colon X \to Y$ of smooth projective curves over $\overline{\mathbb F_p}$, when can one expect the map $$H^1(Y,\mathcal O_Y) \to H^1(X,f^*\mathcal O_Y) = H^1(X,\mathcal O_X)$$ to be injective?
I assume that the map is not constant, otherwise clearly the map is zero. If $p$ does not divide $\deg f$, then the inclusion $\mathcal{O}_Y\to f_*\mathcal{O}_X$ splits by the trace map and thus the map you want is injective. May be separability of $f$ is enough, but am not sure. If inseparable (for example, the Frobenius), things can go wrong, like in the case of supersingular curves.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "algebraic geometry" }
PHP array delete one item Just a simple question - have this array: Array ( [year] => Array ( [0] => 2019 [1] => 2020 ) [user] => [email protected] ) I just want to completely remove `[user] => [email protected]` from this Array. The user will have always only one ocurrence. I tried `unset($filter['user'][0]);` also `unset($filter['user']);` but nothing works.
you can use unset <?php $array = Array ( "year" => Array ( 0 => 2019, 1 => 2020 ), "user"=> "[email protected]" ); unset($array['user']); print_r($array); ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, arrays" }
Null termination for char array of size 1 while using sprintf I am performing sprintf on a char array of size 1 and the code works fine. i.e strlen returns 1 even though it may not be null terminated. To my understanding sprintf will do null termination, however in this case it does not have enough space. Can someone explain the reason it works? #include <stdio.h> #include <string.h> #define STATUS "1" int main(void){ char *data = malloc(1); sprintf(data, "%s", STATUS); printf(">%s<\n", data); printf(">%d<\n", strlen(data)); } **Output** >1< >1<
The program has undefined behavior. It works because in general malloc allocates memory chunks multiple by the paragraph size equal to 16 or some other implementation defined value.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "c, null, printf" }
Image is being cut off on resizing in Firefox I'm currently working on a website. I noticed some elements are beeing cut off, if viewed in Firefox. I attached an Image, showing the problem. The image below is a jsfiddle Screenshot from Firefox. !cut off image The code reproducing it is located here: **JSFIDDLE** It's just an image, with an percantage value set with CSS. .image-percent { width: 30%; } The weird thing is, sometimes I am able to reproduce the bug and sometimes it simply vanishes after adding random HTML-Elements or other CSS-Properties. Anyone already experiences this behaviour or know a workaround, forcing Firefox to resize the image the right way?
Actually found the solution in this thread Firefox blurs an image when scaled through external CSS or inline style. Firefox implemented non-standart css property `image-rendering` < Playing with different values this solution gives more or less appropriate result: image-rendering:optimizeQuality; <
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 7, "tags": "html, css, image, firefox" }
Casual English: Dropping the The Verb BE I heard the question: "What are you talking about?" frequently in American movies. However I notice they tend to drop the verb "are" and treat "y" as a vowel. The /t/ in the word "what" sounds like a flap t (tapped T). I'm not a native speaker and I'm trying to rely on my ears. I would like to know if my observation is correct. I would be grateful for any suggestion.
I think this is the pronunciation that is sometimes written "What'cha talking about?" or "Whaddaya talking about?" (depending on the speaker's accent). If so, I _think_ that most native speakers would consider the verb to still be there even though it has been almost completely swallowed. If you ask someone to repeat the question slowly they will likely either produce the verb ("What ... are ... you ..."), or keep it combined with the "what" ("Whadda ... ya ... talking ... about?"). But that could vary by dialect.
stackexchange-ell
{ "answer_score": 3, "question_score": 1, "tags": "american english, pronunciation, connected speech" }
Suppose that $A$ is an $m\times m$ skew-symmetric matrix. Show that $-A^2$ is a nonnegative definite matrix. Please help me I know that all elements of $-A^2$ is positive-semidefinite, but I don't know the next.
$$A = -A^T \implies -x^TA^2x = -x^T(-A^T)Ax = (Ax)^T(Ax) = \left\|Ax\right\|^2$$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "linear algebra, matrices, positive definite, symmetric matrices, positive semidefinite" }
find the general solution of the ODE if the solution of the form $e^{ct}$ ,or some constant $c$ Given that the equation $$t\frac{d^2y}{dt^2}-(1+3t)\frac{dy}{dt}+3y=0$$ has a solution of the form $e^{ct}$ , for some constant $c$, find the general solution. **My idea** i tried inserted $y=e^{ct}$, because given equation has solution of the form $e^{ct}$ But i cant solve the equation can any one help me plz
$y'=ce^{ct}=cy$ and $y'' = cy' = c^2y $, so putting this solution in gives, $$ (tc^2-(1+3t)c+3)y=0. $$ Since $y \neq 0$, $0 = tc^2-(1+3t)c+3 = (c-3)(ct-1), $ so $c=3$. A linearly independent solution will be of the form $y(t) = u(t)e^{3t}$ for some nonconstant $u$. Differentiating gives $$ y' = (u'+3u)e^{3t} \\\ y'' = (u''+6u'+9u)e^{3t} $$ Substituting this into the differential equation and dividing by $e^{3t}$ gives $$ 0 = (u''+6u'+9u)t - (1+3t)(u'+3u) + 3u = tu''+ (3t-1) u' = 0, $$ which can be solved as a first-order equation for $u'$, and then integrated one more time to give $u$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "ordinary differential equations" }
Why is there no sweet (as in 'with sugar') butter? I understand salted butter can be useful is some situations, but why there's no such thing as "sugar butter" that can be sold in stores? I mean, there is sweet milk (concentrated, for instance) and sweet yoghurt, but no sweet butter nor sweet cheese. Is it just cultural or is there some chemical explanation behind it?
Butter traditionally has salt in it as a preservative, mainly to stop bacterial growth on the residual whey, and to slow fat rancidity Modern butter has a much lower amount of salt than is required for shelf storage in the pre-electric era. Now we have refrigerators, salt is not required at such a high level Butter with no salt has nearly half of the shelf life of modern salted butter Processed sugar is a modern ingredient, and therefore there is no culture in having it in butter. Sweet yoghurt and milk are all "new" inventions Using salt as a preservative is as old as recorded history. Many cultures used salt to preserve fruits, as well as meats and vegetables
stackexchange-cooking
{ "answer_score": 10, "question_score": 6, "tags": "butter" }
Вывод разных страниц на основе параметров URL Вот мой код: <?php if ($_SERVER['REQUEST_URI'] == '/okt/') { $page = 'home'; } else { $page = substr($_SERVER['REQUEST_URI'], 5); if ( !preg_match('/^[A-z0-9,\.\/+]{3,20}$/', $page)){ exit('error url'); } } if (file_exists('okt/all/'.$page.'.php')) include 'okt/all/'.$page.'.php'; elseif ( file_exists('okt/auth/'.$page.'.php')) include 'okt/auth/'.$page.'.php'; elseif ( file_exists('okt/guest/'.$page.'.php')) include 'okt/guest/'.$page.'.php'; else exit('Страница не найдена');?> У меня есть папка `all`, в которой лежит файл `info.php`. Предполагается, что при вводе в адресную строку после ` слова `info` должен открыться файл `info.php` из папки `all`. Но этого не происходит: постоянно срабатывает условие `else` и я получаю `СТРАНИЦА НЕ НАЙДЕНА`. Помогите, уже замучился искать ошибку.
Вне зависимости от того, что у вас в `.htaccess` файле (что само по себе важно). Укажите полный путь до файла или используйте переменную `$_SERVER['DOCUMENT_ROOT']`, к примеру: $_SERVER['DOCUMENT_ROOT'].'/okt/all/'.$page.'.php' При таком варианте все должно работать корректно.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, url" }
binding Maybe value in do-block works while it does not work in a function In the following example, "try 0" works and I get "Nothing" while "try2 0" does not work and I get "Irrefutable pattern failed for pattern Just (x, y)" I don't know how I get "Nothing" from "try 0" ... because the output of "calc n" is binded to (x,y)...Please help me understand why.. try n = do (x,y) <- calc n return (x+1, y+1) try2 n = (x+1,y+1) where Just (x,y) = calc n calc x | x == 0 = Nothing | otherwise = Just (x+1, 1) main :: IO () main = print $ try 0
You get `Nothing` from `try` because you get `Nothing` from `calc`. The `Maybe` Monad instance (which you invoke via `do`-notation) propagates the `Nothing` forward to the output. `try2` fails because you attempt to match `Nothing` with the pattern `Just (x,y)`. These obviously don't match because one is a `Just` and one is a `Nothing`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "haskell" }
Getting undefined for object properties and unable to get count I have an object with 3 properties and each object's property has an object as its value. I am trying to console.log the online property of each object but I get `undefined`. I am also try count the number of online properties set to true but no number is returned. Why do I get undefined and how do I count the online properties set to true? function countOnline(usersObj) { let count = 0; for (let user in usersObj) { console.log(user); console.log(user.online); } return count; } const users = { Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } } countOnline(users);
`user` is the key, not the value. Furthermore, you need to increment the `count` each time the online property is true. for (let user in usersObj) { console.log(usersObj[user]); console.log(userObjs[user].online); if(userObjs[user].online) ++count; } Live Example: function countOnline(usersObj) { let count = 0; for (let user in usersObj) { console.log(usersObj[user]); console.log(usersObj[user].online); if(usersObj[user].online) ++count; } return count; } const users = { Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } } console.log(countOnline(users));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, javascript objects" }
Use sudo -i in bash script I would like to write a bash script to perform some tasks under root while logging as normal user. Is it possible to have something like this? #!/usr/bash sudo -i <multiple line perform all my sudo command> ... ... ... exit <back to my user command, continue some other task> Of course I can put a sudo every line, but I would like to find out is it possible to do something like above? Thanks.
How about something simple like this. #!/usr/bash sudo bash << EOF # Everything until EOF is run in a sub-shell echo 'Hello World' whoami EOF
stackexchange-serverfault
{ "answer_score": 11, "question_score": 5, "tags": "bash, sudo" }
How can I control which record type is selected by default when creating a new record? When creating a new record for an object that has multiple record types, how can I control which record type is selected by default? Is this something I was supposed to set when creating the record types? Can this be changed? For example, I have two Opportunity record types - Service and Products. When I click New, Service is selected by default. Can I change that so that Products is selected by default? I still want to be able to choose, but control what the default choice is. ![enter image description here](
Normally, when creating record types, you can assign them to profiles and set defaults. This is usually the first place where you might want to configure this. ![enter image description here]( < If you want to do this after RecordType creation, you can set the RecordType as default in each Profile. ![enter image description here](
stackexchange-salesforce
{ "answer_score": 4, "question_score": 0, "tags": "record type" }
Nested query to reference field from parent query Simplified example: select ticket_id, `number` as 'ticket number', (SELECT count(*) from ost_thread_entry join ost_thread on ost_thread_entry.thread_id = ost_thread.id where ost_thread.object_id = 1234) as 'number of posts in ticket' from ost_ticket I need to reference the value from `ticket_id` instead of **1234**
You may use table _aliases_ here: SELECT ticket_id, number AS `ticket number`, (SELECT COUNT(*) FROM ost_thread_entry ote INNER JOIN ost_thread ot ON ote.thread_id = ot.id WHERE ot.object_id = t.ticket_id) AS `number of posts in ticket` FROM ost_ticket t; Note that you might also be able to write your query without the correlated subquery, instead using joins: SELECT t.ticket_id, t.number AS `ticket number`, COUNT(ote.thread_id) AS `number of posts in ticket` FROM ost_ticket t LEFT JOIN ost_thread ot ON ot.object_id = t.ticket_id LEFT JOIN ost_thread_entry ote ON ote.thread_id = ot.id GROUP BY t.ticket_id, t.number;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
How to make python print 1 as opposed to 1.0 I am making a math solving program, it keeps printing the whole numbers as decimals. Like 1 is 1.0, 5 is 5.0, and my code is: print("Type in the cooridinates of the two points.") print("") print("---------------------") print("First point:") x1 = int(input("X: ")) y1 = int(input("Y: ")) print("") print("---------------------") print("Second point:") x2 = int(input("X: ")) y2 = int(input("Y: ")) m = (y1-y2) / (x1-x2) b = y1 - m * x1 round(m, 0) round(b, 0) print("Completed equation:") print("") if b < 0: print("Y = "+ str(m) +"X - "+ str(b) +".") elif b > 0: print("Y = "+ str(m) +"X + "+ str(b) +".") elif b == 0: print("Y = "+ str(m) +"X.") input("Press enter to continue.")
Since you're dividing integers, Python represents the result as a `float`, not as an `int`. To format the `float`s as you'd like, you'll have to use string formatting: >>> print('{:g}'.format(3.14)) 3.14 >>> print('{:g}'.format(3.0)) 3 So plugging it into your code: print("Y = {:g}X - {}.".format(m, b))
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "python, int" }
How to perform a check on an object key and replace its value? I have an object in form of: let serviceData = [{title: "Template 1", note: "One time fee", usd: "200", eur: "185", gbp: "165"}, {title: "Template 2", note: "Monthly", usd: "200", eur: "185", gbp: "165"}, {title: "Template 3", note: "One time fee", usd: "200", eur: "185", gbp: "165"}] What's the standard way to perform a check on the key `note` to see if it's equal to `monthly` or not, and if it is to replace the value of `usd` by multiplying it by 12 and returning the updated object?
You can loop through and modify the objects in place: for (const obj of serviceData) { if (obj.note === "Monthly") { obj.usd *= 12; } } If you don't want to clobber the original array, you can make a copy by `map`ping it: const modifiedData = serviceData.map(obj => { if (obj.note === "Monthly") { return {...obj, note: obj.note * 12}; } return {...obj}; }); This utilizes object spread syntax.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
Group a teacher list by School Board and School I have query that return a list of Teachers and I need to group them by School Board and School. Actually a show the data like bellow: School Board Name 1 School Name 1 Teacher Name 1 School Board Name 1 School Name 1 Teacher Name 2 School Board Name 1 School Name 2 Teacher Name 3 School Board Name 1 School Name 2 Teacher Name 4 What I need to show: School Board Name 1 School Name 1 Teacher Name 1 Teacher Name 2 School Board Name 1 School Name 2 Teacher Name 3 Teacher Name 4 I'm trying using Linq or Lambda to make this, I don't know if this is the best way. Thanks.
Group your entities by composite key - i.e. use new anonymous type to group teachers by school board name and school name: var query = teachers.GroupBy(t => new { t.SchoolBoardName, t.SchoolName }); foreach(var schoolGroup in query) { Console.WriteLine(schoolGroup.Key.SchoolBoardName); Console.WriteLine(schoolGroup.Key.SchoolName); foreach(var teacher in schoolGroup) Console.WriteLine(teacher.TeacherName); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, asp.net, linq, list, lambda" }
Get lines that start with number I have a bash command `diff file1 file2`, and the corresponding output is something like: 74,100c74,100 < some text This is just a small subset, and of course, starting of lines in `diff` output varies widely (I know of `>, <, -, \` and chars from `1` to `9`, but there may be others, I'm not really sure). I only want output lines that start with a number from `1` to `9` (not `0`, because I'm only concerned with the positions where changes occurred, and line number won't start with `0`). Thus, if I pipe `diff` with that command, the output should be: 74,100c74,100 How can I achieve this? Thanks...
Could you please try following. Written based on description of OP. your_command | awk '/^[1-9]/' You could also use `grep` too like: your_commamd | grep "^[1-9]" _**Explanation:**_ In `awk` in case we have to use a regex to match in current line we use that regex inside `/` that's why giving `^[1-9]` means look if line starts from anything between 1 to 9 and if regex matches for current line as it's by default action printing of current line happens.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "regex, awk, grep, diff" }
Syntax for collecting data in var query I am collecting some data from database using var query and storing it in an integer. Below is the code: var query1 = from meet_emp in db.Meet_Emps where meet_emp.Employee_ID == empid select meet_emp.Meeting_ID; int meetNum = query1.First(); Here query1 contains multiple meeting ids. I wish to store all id's into an int variable or int array as I would be using each meeting id later into another query. With syntax "int meetNum = query1.First()", I get only the first meeting id. How do I get all the meeting id's
Just change to `ToList` then you will have a list of IDs var query1 = from meet_emp in db.Meet_Emps where meet_emp.Employee_ID == empid select meet_emp.Meeting_ID; var meetNum = query1.ToList();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net, database, var" }
First click - change ul height, second click - reset height I need the button to change ul height (first click - minimize (make height:0px;) and second click - maximize (make height:100px)) <button> minimize / maximize</button> <ul> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> </ul> <style> ul { height:100px; overflow:scroll; border:1px solid red; } </style> Demo
You can toggle class on ul : JavaScript : $(function(){ $('button').click(function(){ $('ul').toggleClass('maximize'); $('ul').toggleClass('minimize'); }); $('ul').addClass('minimize'); })(); CSS : ul { height:100px; overflow:scroll; border:1px solid red; } .maximize{ height:200px; } .minimize{ height:0px; } HTML : <button> minimize / maximize</button> <ul> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> <li>123</li> </ul> Demo : <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, css" }
How to solve this with LINQ? I have a list contain CategoryId and StatusId. If their is a specific Status then I want to remove all the CategoryId from the list. !enter image description here In this example I want to remove all the StatusId = 1 and remove that CategoryId from the list as well. So, in this case Id 1, 3 and 4 will be removed. Dim list As New List(Of CatlogViewModel) ' CatlogViewModel has the property of Id, CategoryId, StatusId
First get all the categories for that status: Dim categories = New HashSet(Of Integer)( _ list.Where(Function(x) x.StatusId = 1).Select(Function(x) x.CategoryId) _ ) Then get the items where the category is not one of those: list = list.Where(Function(x) Not categories.Contains(x.CategoryId)).ToList
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "vb.net, linq" }
PHP-Read the csv line from the particular number of row? I want to get the data frome the file in PHP.there fore i create code like this <?php $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ?> but this code give the the output of start to end but i want to start the reading file from some particular number of the row. Is it possible?how to do it??
Call `fgets()` to read the lines you want to skip before going into the `while` loop. <?php $row = 1; $skip = 10; if (($handle = fopen("test.csv", "r")) !== FALSE) { for ($i = 0; $i < $skip; $i++) { fgets($handle); } while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Use git commit history to find project hot-spots? I'm joining a new project with a long and storied commit history, and I'd like to use that history to show me the hot-spots in the project: the files that have been most commonly (and most recently) edited. Ideally, I'd like to avoid writing more than a few lines of script (ruby, python, javascript; doesn't matter which). Anybody know of a one-liner that can rank git project files according to their activity in a commit history?
You can use this one-liner to print the top 100 most frequently changed files: git log --pretty=format: --name-only | sed '/^\s*$/d' | sort | uniq -c | sort -rg | head -100
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 11, "tags": "git" }
How can I determine which element is found from an electron count vs binding energy graph I am given tables of data that I have made into graphs with electron count vs binding energy. The goal of this assignment is to determine the element of the surface material using data that was gathered in an X-ray photoelectron spectroscopy experiment. This graph is one I made from data that represents carbon. ![carbon]( I know that the peaks in the graph are where I should be looking to determine the element, but I am not sure what to do next. ![element 1]( ![element 2]( This is extra credit for a honors physics 1 class, so this content isn't being covered in class. Any insight into XPS would be appreciated.
insight into XPS: there are tons of books, and good ones for an introduction are An introduction to surface analysis by XPS and AES by Watts and Wolstenholme Practical Surface Analysis by Briggs and Seah or simply the Wikipedia article The position (binding energy of the maximum) of the peak is characteristic for one transition of one element. For example the Carbon data you have is the transition of an electron from a Carbon 1s state to vacuum. You can llok up the elements in reference charts, for example at < (Identify spectral lines)
stackexchange-physics
{ "answer_score": 0, "question_score": 0, "tags": "electrons, binding energy, elements" }
Uploading files to sharepoint via standalone site I have a question regarding sharepoints capabilities when it comes to file management. Essentially, what I'd like to do is use a file upload portal on a standalone website, that would transfer the file into a database within sharepoint. So basically it would go: 1. User is on standalone (non sharepoint) website. 2. User clicks a button on the standalone website to upload a file. 3. The file the user uploads on standalone website portal, gets stored in a sharepoint file management system (separate website) I'm curious if this is possible? Please let me know if I need to illustrate or describe in more detail. Thanks.
The standalone website can store a file on SharePoint. There are few things to note for the website. 1. Needs to authenticate to SharePoint and that account must have at least contribute permission on the SharePoint library where the file would store. 2. If the website is ASP.Net then it can utilize the SharePoint C# client object model APIs. Otherwise can utilize the SharePoint copy.asmx web service. 3. Can check SharePoint provider hosted Add-In option - though a bit complex in your scenario.
stackexchange-sharepoint
{ "answer_score": 4, "question_score": 3, "tags": "sharepoint online, sharepoint designer" }
What is the purpose of phase invert? Can anyone explain why when I record are jam sessions that after a certain amount of time the recording starts sounding like there is effects being added and the guitar starts to sound like it's off in the background with a twang effect. I am clueless
To avoid the effect of _Phase Cancellation_ , as pictured below: ![]( This happens when you record with multiple microphones and their phases are _cancelling_ each other. You should use it when visually you notice that one signal is cancelling the other, inverting one of the channels should solve the issue.
stackexchange-music
{ "answer_score": 4, "question_score": 7, "tags": "sound, mixing, mixer" }
Is it necessary to clearBatch and cancel if connected to Oracle? This is my code: statement.clearBatch(); statement.cancel(); statement.close(); Is it necessary to `clearBatch` and `cancel`?
`clearBatch()` clears the current batch so you can add a new one. `cancel()` cancels the currently executing statement even in another thread. `close()` closes the statement and releases any associated resources such as `ResultSets`. They all do different things. You call them when you want those things done. I don't see that any of them implies any other.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, oracle, connection" }
R remove roman numerals from column I have a table in R with the following information. Some rows in `employee` have roman numerals, some do not: employee <- c('JOHN SMITH II','PETER RABBIT','POPE GREGORY XIII', 'MARY SUE IV') salary <- c(21000, 23400, 26800, 100000) employee_df <- data.frame(employee, salary) > employee_df employee salary 1 JOHN SMITH II 21000 2 PETER RABBIT 23400 3 POPE GREGORY XIII 26800 4 MARY SUE IV 100000 How would I remove the roman numerals so that `employee_df$employee` would be the follwing? JOHN SMITH PETER RABBIT POPE GREGORY MARY SUE
Try this: #Code employee_df$employee <-gsub('^([0-9]+)|([IVXLCM]+)\\.?$','',employee_df$employee) Output: employee salary 1 JOHN SMITH 21000 2 PETER RABBIT 23400 3 POPE GREGORY 26800 4 MARY SUE 100000 Or cleaner: #Code2 employee_df$employee <- trimws(gsub('^([0-9]+)|([IVXLCM]+)\\.?$','',employee_df$employee)) Output: employee salary 1 JOHN SMITH 21000 2 PETER RABBIT 23400 3 POPE GREGORY 26800 4 MARY SUE 100000 The numeric component of regex is not necessary (Many thanks **@BenBolker** ). You can use: #Code3 employee_df$employee <- trimws(gsub('([IVXLCM]+)\\.?$','',employee_df$employee)) And obtain the same result.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r, substring" }
Selecting the last row using VBA and copying down I need to select the last row in my spreadsheet with values and then drag it down (including formulas). I am able to find the last row with values but am having issues selecting this last row. With Sheets("Data") Dim LR1 As Long LR1 = .Range("A" & .Rows.Count).End(xlUp).Row .Range(LR1).Select End With I just want this last row selected and dragged down 1 row. I haven't attempted to add code to drag down because I can't seem to select the last row of data.
If you wanted to autofill your last cell into the cell below it, Sub Data_Button1_Click() Dim LR1 As Long With Sheets("Data") LR1 = .Range("A" & .Rows.Count).End(xlUp).Row With .Range("A" & LR1) .AutoFill Destination:=.Range("A1:A2") End With End With End Sub
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vba, excel, excel 2010" }
"does not take parameters" when chaining method calls without periods I have a class: class Greeter { def hi = { print ("hi"); this } def hello = { print ("hello"); this } def and = this } I would like to call the `new Greeter().hi.and.hello` as `new Greeter() hi and hello` but this results in: error: Greeter does not take parameters g hi and hello ^ (note: the caret is under "hi") I believe this means that Scala is takes the `hi` as `this` and tries to pass the `and`. But `and` is not an object. What can I pass to `apply` to chain the call to the `and` method?
You can't chain parameterless method calls like that. The general syntax that works without dots and parentheses is (informally): `object method parameter method parameter method parameter ...` When you write `new Greeter() hi and hello`, `and` is interpreted as a parameter to the method `hi`. Using postfix syntax you _could_ do: ((new Greeter hi) and) hello But that's not really recommended except for specialized DSLs where you absolutely want that syntax. Here's something you could play around with to get sort of what you want: object and class Greeter { def hi(a: and.type) = { print("hi"); this } def hello = { print("hello"); this } } new Greeter hi and hello
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 6, "tags": "scala" }
Object reference count is different in swift and objective c **Swift Code** override func viewDidLoad() { super.viewDidLoad() var v1 = ViewController() let v2 = ViewController2() print("\(CFGetRetainCount(v1)) and \(CFGetRetainCount(v2))") } > In Swift reference count printing **as 2 and 2** **Objective C Code** - (void)viewDidLoad { [super viewDidLoad]; ViewController *v1 = [[ViewController alloc]init]; ViewController2 *v2 = [[ViewController2 alloc]init]; NSLog(@"%ld and %ld",CFGetRetainCount((__bridge CFTypeRef)(v1)),CFGetRetainCount((__bridge CFTypeRef)(v2))); } > In Objective C reference count printing as 1 and 1 Why reference counts are different in **objective c** and **swift** ?
It has _never_ been the case that you could rely on the retain count having a particular absolute value. Even in the days before ARC in Objective-C, you could not attribute any real significance to the retain count. All you cared about is that you matched the number of `retain`s and `release`s that you wrote and if you retained the object more than you have released it, you owned it and it will therefore not go away. If you have a problem with an object disappearing before it should do or one not going away when it should, you should use the object allocation profiling tools to find the problem, not print out the retain count. The retain count is just an implementation detail. It might even go away altogether in the future. In both of the above two cases, Swift and Objective-C are doing things behind the scenes that you don't know about or should care about. Both numbers are right in the context.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "ios, objective c, swift, reference counting, retaincount" }