INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
tar only *.log files and delete orginals when finished
I am using the following script to create a tarball of a directory with php
exec("tar -zcvf archive_name.tar.gz *");
and this is working as expected, but I would like to extend this code so that it will only add files to the tarball that have a certain extension (*.log in this case) then delete the originals after the tarball has been created. Any advise or examples would be great.
TIA, Kevin | You can change you command to:
exec("tar -zcvf archive_name.tar.gz *.log && rm -f *.log")
Changes made:
* Instead of passing all file (`*`) as argument to `tar` we now pass `*.log`
* Added `&& rm -f *.log`. The command `rm -f *.log` forcefully deletes all `.log` files from the present working directory. We've used an `&&` as the glue between the two commands because we want the files to be deleted **only after** the tarball is created. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "shell, tar"
} |
%p for percent in stacked graph with jquery.flot.tooltip is not working
I am using jquery.flot.js (v 1.1) for graphs and for tooltip jquery.flot.tooltip.js (version: 0.6.7)
I wanted to show percentage area covered by each stack in stacked graph. I have tried it using %p. But it's not working, it return "%p" in tooltip. Code snippet:
tooltip: true,
tooltipOpts: {
content: "%s : %y : %p.1%"
}
My graph is-
!enter image description here
Could any one help me please ? | You can use `%p` only if you also use pie charts plugin < that placeholder was introduced only to support that plugin. I see that is not clear in the documentation.
In your case you need to count percentage value by yourself. You may use callback function for that. The format is `function(label, xval, yval, flotItem)` and must return a string in correct format (needed by tooltip).
Hope it helps! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "jquery, flot, flot.tooltip"
} |
I want to install Adobe CS 6 on an external hard drive but can't select the install location
My SSD is formatted case sensitive, so when I attempted to install I got this:
> Installation on case sensitive volumes isn't allowed. Please choose a case insensitive location.
But I can't select the install location. | Not the answer you want, but whatever.
Re-format your SSD to the default of HFS+ case-insensitive. Almost all Mac software is designed to run on a case-insensitive file system and you using case sensitivity is the problem.
Maybe you'll find a solution here. | stackexchange-apple | {
"answer_score": 0,
"question_score": 1,
"tags": "filesystem"
} |
помогите с решение в php или C++
Работа светофора запрограммирована таким образом: с начала каждого часа, **в течении трех минут** горит _зеленый_ сигнал, следующие **две минуты** горит _красный_ , дальше в течении **трех минут** \- _зеленый_ и т. д. Вам нужно разработать программу, которая по введенному числу определяла какого цвета сейчас горит сигнал. | Каждые 5 минут ситуация повторяется. Так?
Значит, берем количество минут после целого часа, находим остаток от деления на 5. Если это 0, 1 или 2 - значит, зеленый, иначе - красный.
Запрограммировать-то сами, надеюсь, сможете? | stackexchange-ru_stackoverflow | {
"answer_score": 6,
"question_score": -4,
"tags": "php, java, python, c++, алгоритм"
} |
Можно ли заливать venv на github?
Работаю в PyCharm. Создаю проект, и ИДЕ сама создает для него отдельный интерпретатор по пути {project}/venv, куда и скачивает сам интерпретатор питона и библиотеки.
Когда я делаю коммит и заливаю на гитхаб, то происходит следующее - веточка, взятая (checkout) с гитхаба, ругается на невозможность запустить проект по причине отсутствия python.exe. Причем даже не там, куда ссылается конфигурация проекта ({project}/venv/Scripts/python.exe), а на путь до AppData\Local (почему он туда лезет, откуда он вообще взял этот путь?).
Вопрос не столько "как починить?", а "а так вообще можно делать?". То есть можно ли вообще добавлять venv в проект гита и коммитить его. Ну и конечно же, как правильно выстроить архитектуру проекта. | Заливать venv на гит - бессмысленно Для того, чтобы другой разработчик мог развернуть проект у себя на машине нужно
1. Активировать виртуальное окружение
2. ввести в терминале `pip freeze > requirements.txt `, что запишет все установленные библиотеки в txt файл.
3. Залить requirements.txt на гит.
Так же вам стоит почитать про gitignore (его можно создать вместе с проектом на гитхаб выбрав нужный язык.)
UPD: На счёт архитектуры - лично я создаю окружение на одном уровне с проектом. Т.е. в корне у меня лежат
-project_name
-venv
Думаю если что-то не так - меня поправят в комментариях ![Думаю если что-то не так - меня поправят в комментариях]( | stackexchange-ru_stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "python, git, github, pycharm"
} |
Is there any way I can view the full source code of a webpage that uses Angular UI-Router?
For example, if you were to go to < no matter what page on that webpage.. if you Right Click --> View Source, the source code is always the same.
Is there any way I can view the HTML the browser is seeing in full all together? As in.. the "ui-view" portion of the Angular code cuts to another portion of HTML on a different page.. and I would like to see how the browser views all the HTMl when put together as one full page. | In Chrome: press F12 to open the Developer Tools, then go to the 'Sources' tab:
![enter image description here](
All currently loaded sources are displayed on the left, and clicking them shows the code in the middle. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "javascript, html, css, angularjs, angular ui router"
} |
PHP Path to Include Files
I have a site with an index.php. The index.php has a number of include files like
<?php include_once('scripts/php/index_mainImageJoin.php');?>
I've created a new folder off the root called 'extrapages' and I'm going to have pages in there that have information relating to the site. I've added the include_once files like above and change the path and these hook up fine.
The problem I'm find is paths within the include files fail. eg: if an image or another include file is within the include it fails when run from the 'extrapages' folder. Pathing issue.
Is there a good way to deal with this? Can I change/set the path to the site root (www) for pages under 'extrapages' to one folder down by chance?
I could move these pages onto the root and they would run fine but I really don't want all the clutter on the root of the site.
Any ideas & thx | The key to any path problem is called **absolute path**
* while creating _hyperlinks_ for your site (including image sources), always start it from `/` followed by full correct path. And it never fail you.
* same for the filesystem calls: always use absolute path. Your server usually provides you with very handy variable called `$_SERVER['DOCUMENT_ROOT']` contains the point where filesystem meet web-server, pointing to your web root directory.
So, when called from anywhere in your site,
include $_SERVER['DOCUMENT_ROOT'].'/scripts/php/index_mainImageJoin.php';
will point always to the same location | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, .htaccess, include path"
} |
Correct terminology between UTF8 and UTF-8
Which of the two is correct terminology? | That depends on where you use it...
The name of the encoding is `UTF-8`.
A dash is not valid to use everywhere, so for example in .NET framework the property of the `System.Text.Encoding` class that returns an instance of the `UTF8Encoding` class that handles the UTF-8 encoding is named `UTF8`. | stackexchange-stackoverflow | {
"answer_score": 43,
"question_score": 48,
"tags": "utf 8, terminology"
} |
Where can I find Squirt's Necklace?
While experimenting at the Auction House, I noticed that there were several copies of a particular Legendary necklace, called "Squirt's Necklace," for sale for crazy prices. I know that Squirt is a merchant in the Bazaar during Act 2, but I didn't see her selling this item, and she heavily implies that she would _hurt_ me if I was to try to take it from her directly.
It's a level 24 necklace from what I understand, so it would work well with my mid-to-late 20's Witch Doctor. However, the prices for this item on the AH are _crazy high_.
Is there any reliable way to get this item? Does it drop from some particular boss or mob? Does Squirt sell it under certain circumstances? Or am I just supposed to get lucky? | Squirt's Necklace is nothing special, just one of the low-level legendary items.
It's so expensive because it's so rare, nothing more. | stackexchange-gaming | {
"answer_score": 1,
"question_score": 0,
"tags": "diablo 3"
} |
Why does this logo not have blurry edges even when zoomed?
The logo at bottom don't have much blurry edges. All horizontal and vertical lines are crisp, even when zoomed 200%. (You can try it after opening in MS Paint or Windows photo viewer and similar options on any other OS).
One the other hand, most of horizontal and vertical lines of 1st logo are blurred even when not zoomed.
I designed 1st one. My friend designed 2nd one to show that _his_ edges are sharp unlike mine. He combined both in a single file and sent me for comparison.
Why is this different?
EDIT: My friend designed and exported this in PowerPoint.
![enter image description here]( | I'm guessing that the anchor points of your friend's logo follows the pixel grid:
![](
And that the anchor points of your logo doesn't and has decimal coordinates:
![](
If the contours of your vector shapes lies between the pixel grid, anti-aliasing will be introduced. | stackexchange-graphicdesign | {
"answer_score": 3,
"question_score": -1,
"tags": "adobe illustrator, logo, designers, pixel"
} |
PHP Date function
I meet a trouble with php data function.
echo strtotime("31/05/2011");
It prints empty.
What's problem with this?
Thanks. | **DD** /MM/YYYY Is not a valid date format (The manual outlines it must follow one of the supported date and time formats.) So, instead, it should be **MM** /DD/YYYY:
echo strtotime("05/31/2011");
Or, I guess as others have posted, the european (ISO8601 Notations) version uses hyphens:
echo strtotime("31-05-2011"); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "php, date"
} |
Multiple IF conditions in a python list comprehension
I was wondering, is it possible to put multiple `if` conditions in a list comprehension? I didn't find anything like this in the docs.
I want to be able to do something like this
ar=[]
for i in range(1,n):
if i%4 == 0: ar.append('four')
elif i%6 == 0: ar.append('six')
else: ar.append(i)
using a list comprehension. How can I do it?
Is this even possible? If its not, what would be the most elegant (pythonic) way to accomplish this? | How about
ar = [('four' if i % 4 == 0 else ('six' if i % 6 == 0 else i)) for i in range(1, n)]
For example, if `n = 30` this is
[1, 2, 3, 'four', 5, 'six', 7, 'four', 9, 10, 11, 'four', 13, 14, 15, 'four', 17, 'six', 19, 'four', 21, 22, 23, 'four', 25, 26, 27, 'four', 29]
ETA: Here's how you could apply a list of conditions:
CONDITIONS = [(lambda i: i % 4 == 0, "four"), (lambda i: i % 6 == 0, "six"),
(lambda i: i % 7 == 0, "seven")]
def apply_conditions(i):
for condition, replacement in CONDITIONS:
if condition(i):
return replacement
return i
ar = map(apply_conditions, range(0, n)) | stackexchange-stackoverflow | {
"answer_score": 47,
"question_score": 27,
"tags": "python, conditional statements, list comprehension"
} |
Handling file names with spaces in shell script
How to handle files with their names containing spaces in a shell script.
Here is what I am trying
find /abc/xyz -name 'BY567*.csv' | while read fname
do
mv "$fname" ./archive/$(basename $fname)-$(date +%Y%m%d-%T)
done
But when I do this it strips of the file name after space. Like if file name is BY567_Test file.csv , it will be changed to BY567_Test-datetimestamp and not BY567_Test file.csv-datetimestamp. | Put double-quotes arround the end of line and in basename :
mv "$fname" "./archive/$(basename "$fname")-$(date +%Y%m%d-%T)"
The variables will be interpreted and the spaces should be OK. | stackexchange-serverfault | {
"answer_score": 5,
"question_score": 2,
"tags": "bash, shell"
} |
WordPress | Modify rewrite rule
I have start maintaining a web site, that it is build from another person, and I like to modify the rewrite rules applied for a custom post type.
more specific, the custom post type is buidled with the following settings :
$args = array(
...
'rewrite' => array(
'slug' => 'myposttype',
'with_front' => false
),
....
)
register_post_type('myposttype', $args);
The permalink structure is the following:
Post name
but the url structure is the following:
how can I change it to
Any idea please ? | Note: This is not a good idea as it may conflict with pages having the same slug.
Here is a tutorial on how to remove the post type name from the url. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wordpress, url rewriting"
} |
Не работает вывод нескольких постов через get_posts() в wordpress
$posts = get_posts(array(
'include' => '111,222,333',
'post_type' => 'post',
));
foreach($posts as $post){
setup_postdata($post);
get_the_ID()
wp_reset_postdata();
}
get_the_ID() всегда один и тот же - первый, хотя в массиве $posts 3 нужных поста Почему не работает? | В итоге заработало так:
...
foreach($posts as $post){
setup_postdata($post);
> $pid = $post->ID;
> get_the_title($pid);
wp_reset_postdata();
}
Попробую как-нибудь вынести wp_reset_postdata(), но с таким положением не работало | stackexchange-ru_stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "wordpress"
} |
Careers my orders page broken
When I log into careers I click my account and go to the orders history page. At first and I've mentioned this in the past why does the my account 'Li' item appear active, its blue although you really have to click on it to display additional data.
In any event the Orders history page did not show our job listing. Then I realized I had to click one of the other members who placed the order. So after realizing this I then click an order number only to get a page not found error twice. So I cannot get any information about our listing, I also am not able to see views by candidate. Why is the careers site so inconsistent and so buggy. I know listings are only 350 bucks but seriously there has not been a single time I have successfully used this site without a bug. The interface is so hard to follow and it seems like just when I found a particular section its nearly impossible to find it again. | The bug has now been fixed. At first we were going to remove the links, I.E. allow admins to see ordering history but not the actual details. Some people thought it was a PCI/PII issue, but we've talked it over and since it's a company account, we're going to allow it.
As far as your UI concerns, it's because when the site first launched we had no capability for "company accounts" or multiple user hierarchies. It was individuals only. Improvements are coming in the future. | stackexchange-meta | {
"answer_score": 4,
"question_score": -2,
"tags": "bug, status completed, jobs"
} |
Bios Settings and Hardware RAID configuration from Ubuntu MAAS
Can we do the Bios Settings and Hardware RAID configuration from Ubuntu MAAS for HPE Servers?
Any pointers are highly appreciated?
Thanks, Ashraf | MAAS generally doesn't work with BIOS settings. You'll have to configure bios and raid before adding the machine to MAAS.
That said, if HPE has a configuration utility that:
* runs inside an OS,
* that can reach back into the bios to make changes,
* that has a CLI,
* that can be downloaded using curl in real-time,
you could inject it into MAAS using a commissioning script. But all MAAS is doing is downloading and running a program. There's no BIOS-awareness built into MAAS. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "maas, raid, bios"
} |
How to open Clip Board Viewer in Windows 7
In Windows XP **clipbrd** is the command to open the clipboard viewer.we can able to see the current copied items or the Path.
In Windows 7 what is the command to open clipboard viewer..?
can any one tell me the answer..? | There is no clipboard viewer in Windows 7 to the best of my knowledge. In fact I think clipbrd.exe was removed from Windows at Vista. However, the XP clipbrd.exe still works fine, or there are countless 3rd party clipboard viewers to choose from. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "windows, winforms"
} |
E: Package 'python-certbot-nginx' has no installation candidate
When I try to install Certbot for Nginx and run
sudo apt-get install python-certbot-nginx
I get
E: Package 'python-certbot-nginx' has no installation candidate
How to install Certbot for Nginx? | Since Python2 is no longer supported you just need to ask for Python3.
So
sudo apt-get install python3-certbot-nginx
should solve your Problem. | stackexchange-stackoverflow | {
"answer_score": 62,
"question_score": 15,
"tags": "bash, nginx, apt, certbot"
} |
use wrapper to center a nav ul
I'm using a < nav>< ul>< li> to make a menu. I want to put it horizontally and center the whole UL, but it looks that it doesn't work, the ul isn't centered with a margin-auto on a wrapper
<div id="wrap">
<nav>
<ul>
<li class="menuitem">Menu</li>
<li class="menuitem">Menu</li>
<li class="menuitem">Menu</li>
<li class="menuitem">Menu</li>
<li class="menuitem">Menu</li>
</ul>
.menuitem {
background-color: #E3E3E3;
float: left;
width: 100px;
height: 90px;
list-style-type: none;
text-align: center;
color: black;
display: inline;
}
#wrap {
margin: 0 auto;
}
Here is the fiddle | you should give your `.menu-nav` a fixed width, for example `width: 200px;` otherwise `margin: auto` doesnt work.
also you have the `text-align: center;` attribute in your `.menuitem` class. This centers the text. Delete that if you dont want the text centered within the menu.
* * *
To get more information about more advanced centering methods in css, read this blog post about css centering | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
} |
Safe way to check if array element exists?
I have a 2D array. I currently access that array using notation such as:
`myArray[5][9]` (for example).
What is the _safest way_ to check whether or not a certain array element exists? For example, let's say I am looping through the array and retrieving a property of each array element like so:
`myArray[5][9].firstName`
I then come to `myArray[9][11].firstName` (for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.
How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using `myArray.length`in a for loop will not work.
Is there a JS function / method for checking whether or not an array element exists?
Thanks. | like
if (!('firstname' in myArray[i][j])) { ... } | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 22,
"tags": "javascript, arrays, multidimensional array, null, element"
} |
IWindsorContainer - when to call Release()
When I have resolved a component using container.Resolve(), and I have finished using it, should I call Release()?
At the moment I call Dispose on any IDisposable that the container has got for me. Should I not call Dispose() on the object, but instead call Release() on the container instead? Does it do the same thing?
Thanks
David | Short answer:
* `Release` what you `Resolve` (explicitly, or implicitly - via typed factory)
* `Dispose` what you create and own. (and you don't own what container creates, so don't dispose it - container will).
Long answer: I wrote a blogpost going into more details
The documentation on lifestyles goes into more depth as well | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "castle windsor, dispose"
} |
flutter: when to save to Shared Preferences for best performance?
I've been reading the tutorials etc. and I'm now implementing Shared Preferences to save variables between screens. In my app the user moves to and from items in a ListView widget, and may return to a particular screen, I need to save their activity there in case of that.
In Java on Android you would save to sharePrefs when the user exits an activity (screen) because it's a slow operation and saving each time a variable changes is not performant.
Is there a best practice time to save in flutter? How do you know a user is exiting a screen, and descending back to an earlier dart file?
Apologies if this is a turbo ignorant question. | When you exit a page in Flutter, the dispose method is called so I think you could save the Shared Preferences in that method. Here's a pretty good article on this area: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "flutter, sharedpreferences"
} |
where do i send ajax requests in accordance with 'the rails way'
I have a search input box for them to insert 'tags', and it autocompletes the box. This is going to be an ajax request to `Tag.all`.
Unfortunately, i have `resource :tags` in my routes, and i'm using ALL the rest actions for other things in tags_controller.rb (:index, :get, :new, :create, :update, :destroy, etc).
Would I make an entirely new controller or how would i go about doing this. Or should I add something else to the tags_controller just for ajax. I know how to do it many other ways I just want to follow the best rails conventions.
Also how do I go about adding it so it returns json in the appropriate 'rails way'?
Thanks! | Rails normally would dictate that you use the index action (as you are requesting all the resourceS) with a respond_to block, and respond differently based on whether the call is asking for html or JSON. Here's a link to the Rails guides that explains it in a bit more depth.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby, ruby on rails 3"
} |
Dimension of irreducible affine variety is same as any open subset
Let $X$ be an irreducible affine variety. Let $U \subset X$ be a nonempty open subset. Show that dim $U=$ dim $X$.
Since $U \subset X$, dim $U \leq$ dim $X$ is immediate. I also know that the result is not true if $X$ is any irreducible topological space, so somehow the properties of an affine variety have to come in. I have tried assuming $U=X$ \ $V(f_1,...,f_k)$ but I don't know how to continue on.
Any help is appreciated! | Let $X=\operatorname{Spec} A$, and pick some nonzero $f\in A$ with $\operatorname{Spec} A_f = D(f) \subset U$. Then we can lift chains of closed sets to see that $\dim D(f) \leq \dim U \leq \dim X$.
But as shown here, we have $\dim D(f) = \dim A_f = \dim A = \dim X$. We can also see this quite quickly by noting that $A$ and $A_f$ have the same fraction fields, and therefore the same transcendence degree over $k$.
* * *
Note that this is false for general rings $A$, even if $A$ is assumed to be a noetherian domain. In fact, any DVR is a counterexample. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "algebraic geometry, krull dimension, affine schemes"
} |
The LSZ formula in Peskin and Schroeder
I'm working on the Eq.(7.57) in Peskin(page 236).
![enter image description here]( I try to verify it with LSZ formula.
According to Eq (7.42)
![enter image description here](
So $\mathcal{M}(p \rightarrow p)=-Z M^{2}\left(p^{2}\right)$
In this I have two question
① Consider S=1+iT, why did the "1" vanish?
② Is Eq.(2)->Eq.(3) correct?
Consider Eq 7.22in Peskin, it seems to lack a free propagator.
Eq.(2)= 1 + (1PI) + (1PI-1PI) + (1PI-1PI-1PI) + ...
Eq.(3)= (1PI) + (1PI-1PI) + (1PI-1PI-1PI) + ...
![enter image description here]( | 1. I think that your equality (2)=(3) is not correct. Moreover I am not sure what is the right interpretation of (3) in case of diagrams with exactly 2 exterior legs. Furthermore (4) seems to contradict the Kallen-Lehmann formula (see (7.9) in Peskin-Schroeder book). The latter implies that $$\int d^4x_1d^4x_2 e^{ip_1x_1}e^{-ip_2x_2}\langle\Omega|T\\{\phi(x_1)\phi(x_2)\\}|\Omega\rangle\approx (2\pi)^4\delta^{(4)}(p_1-p_2)\frac{iZ}{p_1^2-m^2+i\epsilon}.$$ Namely the exact propagator has a pole of first order as $p^2\to m^2$.
2. Another remark is that as far as I understand, in the Peskin-Schroeder book one particles states are assumed to be stable. That means in particular that $$\langle p_1|S|p_2\rangle=\delta^{(4)}(p_1-p_2).$$ That means that in the decomposition $S=1+iT$ the $1$ term is present, but the $iT$ term vanishes. | stackexchange-physics | {
"answer_score": 1,
"question_score": 3,
"tags": "quantum field theory, feynman diagrams, s matrix theory"
} |
Gson library, cast JsonObject to MyObject
Im currently using this code to create Objects out of JsonStrings from my Server:
JsonParser parser = new JsonParser();
JsonObject myJsonObject = (JsonObject) parser.parse(myInputStreamReader);
MyObject myObject = new Gson().fromJson(myJsonObject.toString(), MyObject.class);
This works pretty good in most cases, but sometimes, the objects are pretty big and therefor `myJsonObject.toString()` causes a `java.lang.OutOfMemoryError`. Is there a possibility to cast `JsonObjects` directly to the specified object without casting them to a string first?
I already bypassed the `OutOfMemmoryError` for JsonObject-creation by using the `StreamReader` instead of a `String` and now i have exactly the same problem again, just a few lines under it :/ | Why are you parsing the JSON stream to a JSON object, then transforming back the JSON object to a string, then transforming back this string to a MyObject? Just do the last part, and everything will be much faster, and use less memory.
MyObject myObject = new Gson().fromJson(myInputStreamReader, MyObject.class); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android, json, casting, gson"
} |
Trying to block the name Pat with a regular expression
For a ruby on rails assignment I am supposed to block anyone with the name Pat. I do not want to black names such as Patrick though. Right now I have
validates :author, :format => {:without => /pat/i}
The above validations will of course also block names such as Patrick I have tried the regular expression below and it didn't catch Pat unless there was a space or something else that is not a character.
/pat\W/i
I am unsure how to make it so it only catches a name that contains Pat but not a name with a Pat in it such as Patrick. Any help will be appreciated. | Use word boundaries:
/\bpat\b/i | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "regex, ruby on rails 3"
} |
OLAP dimension hierarchy for a date including the hours
I need to create the next hierarchy: Month -> Week of Month -> Day of Week -> Hour of Day.
I use "Dimension Wizard" in SQL Server Business Intelligence Development Studio 2008 to create a new dimension. When I am trying to create a dimension by choosing "Generate a time table on the server", the smallest time period, that can be chosen is a "Date". How to add hours to the hierarchy? | As you say, the lowest granularity of a SQL time dimension is date. You need to create both a DimDate, as well as a DimTime. The following article provides step by step instructions for the Time Dimension.
Code Project | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "date, ssas, hierarchy, olap"
} |
What is the difference between Private and Local scope -In Powershell?
Can you please explain the difference between Private and Local scope?
If we speak on an example, if I I create a new PS Drive with scope Private what is the difference compared to creating it with Local scope?
Thanks | Local vars are visible in child scopes (nested script blocks, functions called etc.) Private vars are only visible in the current script block. A simple example:
PS> & { $local:foo = 42; $private:bar = 42; & { "foo is $foo and bar is $bar" } }
foo is 42 and bar is
As you can see, `$bar` is not visible to the inner script block. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": ".net, powershell, scope, powershell 2.0"
} |
Is there a way to apply a formula to two vectors of values and getting a dataframe with the output for each combination?
For example if i have the following vectors:
a <- c(1,2,3)
b <- c(2,5,4,2)
And the operation would be to just multiply the values i would expect the output:
* [1] [2] [3]
[2] 2 4 6
[5] 5 10 15
[4] 4 8 12
[2] 2 4 6
Is there a way to do this in R without just running some loops? The operation im looking to run is
f(x,y) = (EXP(1*(x-y)))/(1+EXP(x-y))
and the vectors are just two numerical vectors, one has around 50000 values, the other around 25. | We can use `outer` to do this by passing the function in `FUN`
outer(b, a, FUN = function(x, y) exp(1*(x-y))/(1 + exp(x - y)))
and to get the `*`
outer(b, a) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r"
} |
Trying to view Table in H2 database While using the Grails as a Framework
recently I am dealing with grails. I am creating a very simple CRUD application without Scaffolding. I have created a Domain class. As I know This domain Class will automatically create a Table in the default H2 database. I am trying to view that table. How can I view The Table which was created in the H2 database? I want To view like the following image.
![enter image description here]( | your grails app should give you the endpoint '/dbconsole' in dev mode. just give it a try! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "database, grails, groovy, h2"
} |
Postgresql jsonb select object with dif order
I have one column in my table with this jsonb
{"parcelas": "[{"valor": "2136,45", "parcela": 75, "vencimento": "15/06/2019"}, {"valor": "2097,61", "parcela": 76, "vencimento": "15/07/2019"}, {"valor": "2058,33", "parcela": 77, "vencimento": "15/08/2019"}, {"valor": "2191,07", "parcela": 78, "vencimento": "15/09/2019"}]}"
It`s possible to find that row when I compare a equal object but without space or another order? sample
SELECT * FROM myTable where myJsonBField ->> 'parcelas' = '[{"vencimento":"15/06/2019","valor":"2136,45","parcela":75},{"vencimento":"15/07/2019","valor":"2097,61","parcela":76},{"vencimento":"15/08/2019","valor":"2058,33","parcela":77},{"vencimento":"15/09/2019","valor":"2191,07","parcela":78}]'
is the "same" object but in another order and with less space between itens.
tks | Just use `->` which gives a `jsonb` rather than a `text` and `=`.
SELECT *
FROM mytable
WHERE myjsonbfield->'parcelas' = '[{"vencimento":"15/06/2019","valor":"2136,45","parcela":75},{"vencimento":"15/07/2019","valor":"2097,61","parcela":76},{"vencimento":"15/08/2019","valor":"2058,33","parcela":77},{"vencimento":"15/09/2019","valor":"2191,07","parcela":78}]'::jsonb; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "postgresql, jsonb"
} |
How can I create a AlloyUI DiagramBuilder from the JSON returned by DiagramBuilder.toJSON()?
`DiagramBuilder.toJSON()` returns a JSON representation of the diagram. How can I use this JSON object to create a new `DiagramBuilder` with the same diagram? | You can pass the `jsonData.nodes` to the `fields` attribute of the `DiagramBuilder`:
var diagramBuilderJSON = diagramBuilder.toJSON();
new A.DiagramBuilder({ fields : diagramBuilderJSON.nodes }).render(); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, json, yui, yui3, alloy ui"
} |
How to tell Adobe Illustrator to use a font of a slightly different name?
I'm opening a PDF created with Adobe Illustrator CC in Adobe Illustrator CS6 and other than some features may not be available warning, it complains about a missing font:
> The font TrendRoughSlabOne is missing. Affected text will be displayed using a substitute font.
However, I did purchase that font, but it shows up in the Illustrator Font menu as `Trend Rh Slab One`.
How can I instruct Illustrator to substitute and use this name variant instead? | `Type > Find Font`
Click the original in the top pane, then choose the substitution in the bottom pane. Then click `Change All`. | stackexchange-graphicdesign | {
"answer_score": 4,
"question_score": 1,
"tags": "adobe illustrator, fonts, pdf, adobe acrobat"
} |
Repeated call to webkitNotifications.requestPermission() doesn't show permission request in chrome
Is it possible to request permission for showing desktop notifications in chrome when user has already denied it ? I don't want to spam user with repeated requests. I have accidentaly clicked the "Deny" button and now every time I try to request permission, nothing shows up. Restart of the browser doesn't help either.
This same thing could happen to user. I've searched but didn't find anything in the Settings or in Developer's tools. | OK, I've finally found answer to my question. Chrome keeps blocking repeated permission requests once the permission was denied in the first place.
However, there is possibility to change the permission manually in settings, but it's very hidden :-). You go to Wrench -> Settings -> Under the Hood -> Content settings -> Notifications -> Manage exceptions -> and there is a list of permissions (both denied and allowed) and you can change them as you like. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "google chrome, notifications"
} |
bigger height and width image is not occupying full space in product detail page
please visit this link :
you can see the base image is not occupying full space
the base image is occupying full space.
product 1's image is having bigger height and width size but why the product 1's image is
not occupying full space
please help me to find some solution....
thanks in advance | The image uploaded includes white space around it: <
Cropping out the white space should make it appear larger on the frontend after you upload the fixed image. | stackexchange-magento | {
"answer_score": 1,
"question_score": -1,
"tags": "image, product view"
} |
Login time issues on linux
I have observed that it takes a very long time on a Linux machine to deny the user to log in in case he mistyped his password than it takes to log him in actually. The difference can be even 5 seconds. Why is this? | It's a long standing habit to enforce a delay when a login fails. The rationale is that it rate-limits attacks.
There's a facility in the Pluggable Authentication Modules (PAM) of Linux which provides for a delay on a failed login attempt.
For PAM-Linux, the api is called `pam_fail_delay`, and is invoked in the authentication modules, and it requests a delay of the passed in number of microseconds. The system actually puts in an up to +/-25% delay in. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "linux, authentication, passwords"
} |
TypeError: not all arguments converted during string formatting while printing with %
I am a beginner in Python2.7, I am facing an issue while trying to execute below code. The first error pops up on line 3 (print). I get the error-> TypeError: not all arguments converted during string formatting. Please help. Below is my code snippet:
inputhours= int(raw_input('Enter the hours: '))
inputrate= int(raw_input('Enter the rate: '))
print('Hours is: '% inputhours)
print('Rate is: '% inputrate)
if (inputhours >40) :
pay= int((40*10)+(inputhours - 40)*(inputrate * 1.5))
print ('Pay is:'% pay)
else:
pay= int(inputhours * inputrate)
print ('Pay is:'% pay)
quit()
Spaces in above program are for your readability. | You need to include the tokens to replace in your initial strings. Your print statements should look like this:
print('Hours is: %d' % inputhours)
print('Rate is: %d' % inputrate)
or you can use the newer `.format()` method of the string class like this:
print('Hours is: {:d}'.format(inputhours))
print('Rate is: {:d}'.format(inputrate)) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, python 2.7"
} |
How to add and empty select list with Html.DropDownList
I am trying to add a drop down select element to my .net page, but I need it to be black so I can populat it with a json list I have with jQuery. Right now, my view has this:
@Html.DropDownList("Language", new SelectList(" "), "name = 'Laguange'", new { @class = "Language-List field form-group form-control" })
This 'works', but it seems to be confusing some stuff when I try to submit the form it is in. The value I select from it is never seen by the model, as it keeps triggering my `[Required]` validation helper.
Does anyone know How to add this without the `new SelectList(" ")` attribute? | I would suggest it's because youre using the name attribute in the wrong place. Try this:
@Html.DropDownList("Language", new SelectList(" "), new {Name="Language", @class = "Language-List field form-group form-control" })
Notice the capital Name
Although as they are the same, you can just leave it out:
@Html.DropDownList("Language", new SelectList(" "), new {@class = "Language-List field form-group form-control" }) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, model view controller, razor"
} |
When "dev-master" should be used in composer.json?
I'm starting to use Symfony2 and following many tutorials. I found that when they installed some new features using `composer.json`, they "always" declared `dev-master`. I don't know the reasons why they always use it. An example from DoctrineFixturesBundle:
{
"require": {
"doctrine/doctrine-fixtures-bundle": "dev-master"
}
}
Actually, I have googled and found some people written that If we use the `dev-master` instead of any `stable` version. It would be some conflicts in the future because the version today maybe `1.5.0` and tomorrow maybe `1.6.0`.
So, what we really use in practical works - `dev-master` or `specified version` and why? | **You should use a specific ( tagged stable at best ) version wherever possible.**
While `composer.lock` does lock the dependency to a specific commit even when using `dev-master` ... every `composer update` will update the dependency to the latest version and afterwards update the lockfile.
If your lockfile somehow gets deleted/lost and it is not backuped / under version control you can easily end up with a non-working project after running `composer install` or `composer update`!
A simple example would be `symfony/symfony` itself ... new commits might introduce new BC (backward compatibility) breaks in the `dev-master` branch any time leaving your application in a non-functional state. | stackexchange-stackoverflow | {
"answer_score": 30,
"question_score": 31,
"tags": "symfony, composer php"
} |
"Command Prompt Here" without shift key in Windows 10
I want "Command Prompt Here" in right click menu for all folders but without having to hold shift key.
It was possible in earlier versions of windows, like this but it's not working anymore, in Windows 10.
Has this method changed in Windows 10? or is there another way to do this? | The registry method actually has changed slightly, as I discovered tinkering with the registry.
There are now **two** locations that have the `Extended` key:
HKEY_CLASSES_ROOT\Directory\Background\shell\cmd
HKEY_CLASSES_ROOT\Directory\shell\cmd
The `\Background\shell` is newly added one and deleting the `Extended` key from that location is what worked for me. | stackexchange-superuser | {
"answer_score": 15,
"question_score": 9,
"tags": "windows 10, windows explorer"
} |
Is java.util.Vector serialization thread-safe?
I know the Vector class is thread-safe for adding and removing elements [reference].
If I serialize a Vector using an ObjectOutputStream am I guaranteed a consistent (and non-corrupt) state when I deserialize it even if other threads are adding and removing objects during the seralization? | The writeObject() method is synchronized. But there's nothing in the Javadoc that guarantees that unless it's implied by the statement 'Vector is synchronized'.
Note that the readObject() method doesn't need to be synchronized, as the object isn't accessible to anybody until readObject() returns. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "java, multithreading, vector, thread safety"
} |
Prevent span tags from being generated for computed HTML fields?
I have a computed field on my page that is set for HTML. The HTML generates but each computed field gets wrapped by a span tag. Is there any way to avoid this?
Is my question related to this question?
'Computed field' controll and disableOutputTag="true" doesnt work?
I need to use the disable tags property but there appears to be a bug?
Is there a workaround? | Yes, remove the name of the computed field. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "xpages"
} |
Center column headings in tabular: multicolumn not respected
I would like to center column headings (and column headings only) in the following table. Why does it work with the first column, but not the second (I thought `\multicolumn` is the correct approach to this problem).
\documentclass{article}
\usepackage[american]{babel}
\usepackage{tabularx}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{rr}
\toprule
\multicolumn{1}{c}{$\alpha$} & \multicolumn{1}{c}{$\alpha=0.99999$} \\
\midrule
10 & 69.681 \\
& 901.741 \\
1000 & 893.630 \\
& 82.806 \\
\bottomrule
\end{tabular}
\end{document} | This is just a little example of how you can make a small modification to your input in order to get the desired output:
!enter image description here
\documentclass{article}
\usepackage{tabularx}%
\usepackage{booktabs}%
\begin{document}
\begin{tabular}{rc}
\toprule
\multicolumn{1}{c}{$\alpha$} & $\alpha=0.99999$ \\
\midrule
10 & \phantom{0}69.681 \\
& 901.741 \\
1000 & 893.630 \\
& \phantom{0}82.806 \\
\bottomrule
\end{tabular}
\end{document}
The addition of a `\phantom` leading 0 for numbers less then 100 makes all the numbers the same width, so `c`entering is readily achieved. | stackexchange-tex | {
"answer_score": 4,
"question_score": 6,
"tags": "tables, horizontal alignment"
} |
How to get validation info of an input outside of a form?
We can get the validation info if the input is in a form: `$scope.myForm.myField.$invalid` etc..
What if input is outside of a form? How can we access the info?
I guess that field data (properties of the form object) is not same thing with `ngModel`. I tried something like this but didn't worked: (the model only contains string value of the input)
<input ng-model="myFakeForm.myField">
How can I achieve this? | Use the `ng-form` directive:
<div ng-form="set1">
<input name="field1" ng-model="myFakeForm.myField" ng-required="true" />
</div>
The input's `ngModelController` will be bound to `$scope.set1.field1`:
console.log($scope.set1.field1.$valid);
console.log($scope.set1.field1.$viewValue);
//... etc
For more information, see
* AngularJS ng-form Directive API Reference | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, angularjs ng form"
} |
VBA Excel loop through all days in a year
In Excel VBA:
How do I loop through all days in a given date range?
'2013-01-01' to '2013-01-03' should give:
2013-01-01
2013-01-02
2013-01-03 | This should at least show you how to get started with what you're trying to do:
Sub test()
Dim StartDate As Date
Dim EndDate As Date
Dim DateLooper As Date
StartDate = #1/1/2013#
EndDate = #12/31/2013#
For DateLooper = StartDate To EndDate
MsgBox (DateLooper)
Next DateLooper
End Sub | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 3,
"tags": "vba, excel"
} |
Console output - way to let caret jump to columns and rows
Is it possible to output such a escape code so that the caret in console moves to proper absolute location? I've seen something similar on unix console. Is this even possible on the basic and simple Windows console? Thanks | Don't use an escape code, use SetConsoleCursorPosition
COORD C = { 3, 3 };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), C); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c++, console, windows console"
} |
Sort Array in the bases of another array
I have 1 array of object which contains employees data. its unsorted.
I have another array which contains object which have employee data and order for that.
For example:
Employee *emp;
Ordered *orderedEmp = [[Ordered alloc]init];
ordreredEmp.emp = emp;
orderedEmp.order = any number;
NSArray *arr1 = [[NSArray alloc]initWithObjects:@emp,emp,nil];
NSArray *arr2 = [[NSArray alloc]initWithObjects:@orderedEmp,orderedEmp,nil];
Now here i want to sort first array according to second array.
Thanks In advance | Better you can use `NSPredicate` & `NSSortDescriptor`
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"emp == %@" ,@"emp"];
[NSMutablearray filterUsingPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Title" ascending:TRUE];
[NSMutablearray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release]; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, ios, ios5, nsarray, nssortdescriptor"
} |
obtaining a date from this string
I need to obtain a Date object from this String:This is a example)
M-27\nJUN-2012 DayOfWeek-dd\nMONTH-yyyy
Its impossible? I dont know how to use simpledateformat for this..The \n is a line jump. | Try following SimpleDateFormat:
String dateS = "M-27\nJUN-2012"; // your date string
SimpleDateFormat fmt = new SimpleDateFormat("dd\nMMM-yyyy"); // formatter
Date date = fmt.parse(dateS.substring(2));
System.out.println(date);
You can really drop out the day of week, because day, month and year defines this day. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, date, simpledateformat"
} |
Does StringFormat feature of WPF Xaml work on Label.Content?
I have bind my Amount **Label's** Content Property to a decimal property via DataContext. I am trying to apply stringformat but see no effect. Does **StringFormat** feature work on Label controls ?? Please tell me on which controls does this feature work. BTW following is the code for the Label Control for whom i want to apply the currency formatting
<Label Grid.Column="2" Content="{Binding Path=Amount, StringFormat={}{0:C}}" Height="23" HorizontalAlignment="Left" Margin="100,10,0,0" Name="tb" VerticalAlignment="Bottom" Width="120" /> | `StringFormat` works on properties of type string (when the object you are binding to is being converted to a string the string format is applied). The `Content` property is of type `Object`.
You can place a TextBlock inside your label to achieve the desired effect:
<Label Grid.Column="2" Height="23" HorizontalAlignment="Left" Margin="100,10,0,0" Name="tb" VerticalAlignment="Bottom" Width="120">
<TextBlock Text="{Binding Path=Amount, StringFormat={}{0:C}}"/>
</Label> | stackexchange-stackoverflow | {
"answer_score": 30,
"question_score": 26,
"tags": "wpf, xaml, label, string formatting"
} |
How do I make a custom form post to an external URL?
In Drupal 8, I want a form to post to another page, but when I change the action on `$form['#action']` to a URL that makes it post there, it skips the validation.
I need the code for posting to an external URL in a submission handler.
I tried this but it gives an error.
$response = new TrustedRedirectResponse('
$form_state->setResponse($response); | You can post your information using the Drupal HTTP client (Guzzle):
$client = \Drupal::httpClient();
$request = $client->post($url, $post_data);
$response = json_decode($request->getBody());
Where $url is the URL you want to post to, and $post_data is an array containing the data you want to post, in key => value format. You can build the key values in the submit handler of your form, getting the submitted values from $form_state.
You can read more about it here: <
You can build your post data something like this:
$post_data = [
'field1' => $form_state->getValue('field1'),
'field2' => $form_state->getValue('field2'),
...
]: | stackexchange-drupal | {
"answer_score": 5,
"question_score": -2,
"tags": "forms"
} |
(a/b) mod n for large numbers?
I need to calculate the sum of first n tetranacci numbers but the formula which I am using
sn = (f(n+2)+2*f(n)+f(n-1)-1)/3
has a division involved.
I am doing `f(n) modulo 10^9 + 7` to calculate nth tetranacci term. For some cases, it gives the correct answer but not for all.
Can someone please help me get the correct logic on how to calculate it? | For modular arithmetics, replace the division by a multiplication with the modular inverse.
If `k*d ≡ 1 (mod m)` and `n` is a multiple of `d`, then
n/d ≡ ((n % m)*k % m) (mod m)
You can see that by
k = (f*m + 1)/d
n*k = (n*(f*m + 1))/d = ((n*f)*m + n)/d = (n/d)*(f*m) + (n/d)
Now, `n/d` is by assumption an integer, hence `(n/d)*(f*m)` is a multiple of `m`, so
n*k ≡ n/d (mod m)
and since
n*k ≡ (n % m)*k (mod m)
the proposition follows.
In this case, `d = 3` and `m = 10^9 + 7`, so `k = (10^9 + 8)/3 = 333333336`.
If `n` is _not_ a multiple of `d`, that doesn't work, however. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "c, modulo"
} |
Get changed files from SVN command line between two revisions
I need to get the changed files list between two revisions in SVN.
I have used the following command:
svn diff -r 5001:6001 --summarize > output.txt
For some reason, the files modified on revision 5001 are not populated in the output text file.
What is the exact command to extract the files list between the two revisions (inclusive of from and to revisions, that is, including revision 5001 and revision 6001)? | Try `svn diff -r 5000:6001` instead. To understand this, consider the following: what would the output of `svn diff -r 100:100` look like? It would show no changes, because the revisions are the same. To see the changes for revision 100, we must use `-r 99:100`. | stackexchange-stackoverflow | {
"answer_score": 55,
"question_score": 42,
"tags": "svn, diff, revision"
} |
Mapreduce logs - File vs HDFS
I submitted a mapreduce and this is my output.
What is the difference between the FILE and HDFS as given below?
16/01/07 21:49:58 INFO mapreduce.Job: Counters: 38
File System Counters
FILE: Number of bytes read=4011012
FILE: Number of bytes written=8400605
FILE: Number of read operations=0
FILE: Number of large read operations=0
FILE: Number of write operations=0
HDFS: Number of bytes read=11928267
HDFS: Number of bytes written=883509
HDFS: Number of read operations=37
HDFS: Number of large read operations=0
HDFS: Number of write operations=6 | FILE - gives the amount of I/O performed on intermediate files, which are maintained internally between map and reduce phase (sort & shuffle phase)
HDFS - Amount of data read by mapper and data written by reducer. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "hadoop"
} |
DRBD8 and GFS on CentOS5
I am trying to combine DRBD8 and GFS2 on CentOS5. Is there any possibility to do this without using a mulicast-cluster underneath? (CentOS seems to use AIS)
This is a two-node-cluster, so a simple unicast setup should do. | The simple answer is: Forget GFS in this case. Use OCFS2 instead. | stackexchange-unix | {
"answer_score": 0,
"question_score": 1,
"tags": "centos, drbd"
} |
Comparing data from two data tables
I have this code which compares data from two data tables. It does this by using a primary column and inserting the new record from `table2` to `table1`. This loop continues for a large number of tables. I want to optimize it. Kindly give suggestions.
foreach (DataRow drRow in table2.Rows)
{
if(!table1.Rows.Contains(drRow["KeyId"]))
{
table1.ImportRow(drRow);
}
} | For .net framework 3.5, you can have following code improvements:
foreach (var drRow in table2.Rows.Cast<DataRow>()
.Where(drRow => !table1.Rows.Contains(drRow["KeyId"])))
{
table1.ImportRow(drRow);
}
1. part of body can be converted to LINQ-expression
2. use "var" (implicitly typed) instead of "DataRow" (explicitly typed) | stackexchange-codereview | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, optimization"
} |
Show that $f\not\in L^1(\mathbb{R})$ but $f\in L^2(\mathbb{R})$.
Let $f(x)=\min\\{1,1/|x|\\}$. Show that $f\not\in L^1(\mathbb{R})$ but $f\in L^2(\mathbb{R})$.
I think I want $||f||_1$ to not be finite and $||f||_2<\infty$, but I'm confused as to how to compute those from a minimum function. Would I just take $f(x)=\frac{1}{|x|}$ and compute as normal? Or is there something else I'm missing?
Any help would be greatly appreciated. | Set $f(x)=\min\\{1,1/|x|\\}$.
We may write $$ \begin{align} \int_\mathbb{R}|f(x)|dx&=\int_{|x|\leq 1}|f(x)|dx+\int_{|x|> 1}|f(x)|dx\\\\\\\ &=\int_{|x|\leq 1}1\:dx+\int_{|x|> 1}\frac1{|x|}dx\\\\\\\ \end{align} $$ and the latter integral is **divergent** , thus $f\not\in L^1(\mathbb{R})$.
Similarly$$ \begin{align} \int_\mathbb{R}|f(x)|^2dx&=\int_{|x|\leq 1}|f(x)|^2dx+\int_{|x|> 1}|f(x)|^2dx\\\\\\\ &=\int_{|x|\leq 1}1\:dx+\int_{|x|> 1}\frac1{|x|^2}dx\\\\\\\ \end{align} $$ and both integrals are **convergent** , thus $f\in L^2(\mathbb{R})$. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "real analysis, integration, functional analysis, definite integrals"
} |
How do I get the output from a Perl pipe as it becomes available?
The following code is working sort of fine:
open( PIPE, '-|', 'ant' );
for( <PIPE> ) {
print;
}
However, it doesn't do what I want. Since the Ant build can take 5 minutes, I would like to see the output line by line. Instead, I'm getting the entire input at the end of the process.
Looking at it with the Perl debugger, Perl waits at the 'for' statement, until Ant terminates. Why is that? | Just for completeness (problem was solved as pointed out in the comment to Uri's answer) the problem arose because the `for` expression evaluates the `<>` operator in list context (see), equivalently to the following:
foreach $line (@lines = <PIPE>) {
print $line;
}
In list context, the `<>` operator tries to read _all_ lines from its input to asign to the list - and the input comes from a process, it will block until the process ends. Only afterwards it it will enter the loop body.
The alternative syntax
while( <PIPE> ) {
print;
}
is equivalent instead to
while( $line = <PIPE> ) {
print $line;
}
i.e., it consumes each line from the input in each loop iteration, and this is what one wants to do in this scenario. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 7,
"tags": "perl, pipe"
} |
Which sounds more natural?
Sentence A: There are two dogs _biting_ in the street.
Sentence B: There are two dogs _fighting_ in the street.
Which sentence better expresses the intended meaning when I refer to two dogs engaged in an angry fight? | You could say
> There are two dogs fighting in the street.
>
> There are two dogs biting each other in the street.
But the present participle **biting** alone, intransitively, is not normally used to refer to the canine altercation itself. | stackexchange-ell | {
"answer_score": 1,
"question_score": 1,
"tags": "verbs"
} |
Joining list of lists by element
I want to join list of lists by element such that
lst = [['a','b','c'], [1,2,3], ['x','y','z'], [4,5,6]]
becomes
res = [['a',1,'x',4], ['b',2,'y',5], ['c',3,'z',6]]
I'v tried using list comprehension, concatenate and map, but haven't had any luck with it yet. (New to python) | Try `zip` (similar question: Transpose list of lists):
>>> lst = [["a","b","c"], [1,2,3], ["x","y","z"], [4,5,6]]
>>> res = [list(zipped) for zipped in zip(*lst)]
>>> res
[['a', 1, 'x', 4], ['b', 2, 'y', 5], ['c', 3, 'z', 6]] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python"
} |
Which cases save data in savedInstanceState?
I recently posted a question, and the answer I got was related to the status of savedInstanceState. I would like to know in which cases information is saved in savedInstanceState, also for what other purpose does the OS uses the savedInstanceState. I've found some info which relates savedInstanceState with Android lifecycle, but I can't understand exactly how. | Whenever an Activity is killed for resources or restarted due to configuration changes, onSaveInstanceState is called. This includes when a background Activity is terminated.
If an Activity is killed for normal reasons (like by calling finish) or terminated due to crash/ANR/force stopped then it isn't. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android lifecycle"
} |
Is Solaris or Linux the better C GUI development environment?
What might be a better choice?
I have my code (mostly C - as output from the GNU Eiffel compiler and some C++ for the GUI bindings) working with Sun Studio compiler and gcc.
But i now have to setup a new developer computer and wonder if i should use Solaris with DTrace, locklint or Linux with Valgrind etc for development.
It's just about introspecting and debugging and the development is done in GNU (SmallEiffel) and therefore there is no help in any way. But the output is plain C, so C tools help a lot.
I bought some books about the Solaris and printed the developer documentation. I have to say that it seems to be a much better development environment then all the undocumented Linux tools. But Sun Studio works also on Linux... | This is an _opinion_ so I'm marking it Community Wiki.
Solaris' days are past. That's it, really, that's all I wanted to say, thanks for listening.
Oh, and by the way, so is AIX and HP-UX. Linux is the present and the future (at least for a while) - that's where you should be putting your effort. That's where you'll get the best bang per buck for your support dollars. That's where you'll get hordes of opinionated clowns like myself willing to give you help at the drop of a hat. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c, unix"
} |
Align text within div tags
I've this below html
str+="<div class='label' date1='"+a+"' date2='"+a1+"' id='mydiv'> Start Date "+a;
str+="End Date "+a1;
Now I want date1 should be aligned left to the page and date2 should be aligned right to the page.
How to do this?
Regards | Make it simple with `flexbox` and `pseudo elements`.
#mydiv {
display: flex;
justify-content: space-between;
}
#mydiv::before {
content: "Start Date: " attr(date1);
}
#mydiv::after {
content: "End Date: " attr(date2);
}
<div class="label" date1="10/5/2016" date2="10/20/2016" id="mydiv"></div>
So, your code will be like this:
str+="<div class='label' date1='"+a+"' date2='"+a1+"' id='mydiv'></div>"; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "html, css"
} |
Why doesn't Entity Framework support ODBC?
Is there a specific reason that the EF requires new data providers and can't make use of ODBC? I figured it had to be some ORM specific problem, but NHibernate works fine via ODBC.
I'm using NHibernate and can continue to use Nhibernate, but I worry that I can't assume Nhibernate knowledge for any future programmers here. | The Entity Framework doesn't require new data providers, exactly. Rather, it requires Entity Framework providers which extend existing data providers, to provide additional services required by the Entity Framework, such as complex SQL generation, which are not part of the existing ADO.NET data model. I don't think that there's anything stopping anyone from writing an Entity Framework provider for ODBC based on the existing ADO.NET 2.0 ODBC bridge. You can download the source code for a sample SQL Server provider for more information about exactly what services are required when extending an existing ADO.NET provider for the Entity Framework. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 17,
"tags": "nhibernate, entity framework, ado.net"
} |
mysql single database relocation
I would like to know if it's possible to operate different databases on different filesystem locations.
Background: we are a hosting service, which hosts mysql, web, and smtp to it's customer, but all our services (sql, smtp, http) are located in a different place. We are going to assign a single logical volume to a customer, which will accommodate the customer's mailing, weppages and (hopefully) sql database. Web pages and mailing are already covered, but I am not able to find a configuration setting which would enable me to specify the location of a database (the directory where mysql stores the DB).
Let me please highlight, the target here is to relocate different databases to different locations in the filesystem, not moving them from a single place to an another (single) place.
Also please do not bother answering with soft and hard symbolic links. ;)
Thanks | You would like to place difference databases' data files under different directories and load them together in one MySQL instance, am i correct to say that ?
There is a directive called 'datadir' under [mysqld] block which normally used to determine where to store for database files.
As far as I aware, mysql cannot have multilple 'datadir' for one instance. You can have multiple instance using mysqld_multi and use each instance to point to different datadir. But, of cause, you'll have to use different ports for each instance. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
} |
check box enable in Jquery
<tr id="tr99"><td>......</td></tr>
<input type="checkbox" onclick="toggletr(this);" value="val" id="cbox" />
The javascript:
$(document).ready(function() {
function toggletr(obj)
{
if(obj.checked)
$(#tr99).hide();
else
$(#tr99).show();
}
hi.this is my code that runs in add page of staff. if user is in edit mode the value that value is checked in the code i mean to say in .cs . `checkbox.checked ="true"` means . that time i need to make that tr value "tr99" is visiable true if checkbox is not checked then make the tr as hide. | I think that you want this to happen
$(document).ready(function() {
function toggletr(obj){
if(obj.checked){
$("#tr99").show();
$("#cbox").attr("value", "tr99");
}else {
$("#tr99").hide();
}
}
});
Is that it? You can also add the function directly
function toggletr(obj){
if(obj.checked){
$("#tr99").show();
$("#cbox").attr("value", "tr99");
}else {
$("#tr99").hide();
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery"
} |
View list of items tagged "i like it"?
I have a basic install of Sharepoint 2010 Enterprise.
I'd like to know where I can view the list of items which I've tagged "i like it" (using the default button included), if such a place exists by default. | Click your name in the top-right corner of the page to bring up the welcome menu. From the welcome menu, choose "My Profile." Select the "Tags and Notes" tab and you'll be able to see everything you have tagged with "I like it" (as well as any other tags you may have used for content in SharePoint).
For more information, see this blog post. | stackexchange-sharepoint | {
"answer_score": 1,
"question_score": 0,
"tags": "2010, social, tagging"
} |
Is converting decltype's expression from constant l-value into an r-value discards `const` too?
Here I want to know how type specifier `decltype` works:
const int& rci = 5;// const ref bound to a temporary
decltype (rci) x = 2;
decltype (rci + 0) y = 10;
// ++x; // error: increment of read-only reference ‘x’|
++y; // why does this work
std::cout << typeid(x).name() << std::endl; // i
std::cout << typeid(y).name() << std::endl; // i
* Why `y` has only type `int` rather than `const int`?
* Does converting a constant lvalue into an rvalue discards in addition to reference operator, `const` qualifier too?
* Why `typeid` shows that the type of `x` is just `i` but not `const int&`? | **> Why y has only type int rather than const int?**
Because `(rci + 0)` is a prvalue, and prvalues of primitive types have const stripped.
**> Does converting a constant lvalue into an rvalue discards in addition to reference operator, const qualifier too?**
For non-class types, const qualifier is discarded. From the standard:
> 7.3.1.1
> [...] If T is a non-class type, the type of the prvalue is the cv-unqualified version of T.
**> Why typeid shows that the type of x is just i but not const int&?**
From cppreference:
> In all cases, cv-qualifiers are ignored by typeid (that is, typeid(const T) == typeid(T)). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "c++, c++11, constants, decltype"
} |
Current Date in SQLAlchemy ORM relationship
I'm trying to configure a relationship between two objects based on the current date. Say I have a `Person` object and a relationship to a bunch of `Event` objects. If the `Event` object holds a `DateTime` (`start`) on it, I want to make a relationship to all of today's events.
So far I have:
class Person:
id = Column(Integer, primary_key=True)
todays_events = relationship('Event', primaryjoin='and_(Person.id == Event.person_id, cast(Event.start, Date) == "2016-04-23"')
This works but I can't find what I need to replace the date string with "2016-04-23" to get the equivalent of `CURDATE()`.
Does anyone know what I'm looking for?
Thanks. | Found the answer right after posting... of course.
`func.current_date()`
so:
class Person:
id = Column(Integer, primary_key=True)
todays_events = relationship('Event', primaryjoin='and_(Person.id == Event.person_id, cast(Event.start, Date) == func.current_date()') | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 6,
"tags": "python, sqlalchemy, relationships"
} |
Active directory (AD) best-practice for clustering
We want to use AD as a regular LDAP for storing and accessing our application data in fast and reliable way. We have two physical server and want to organize some sort of clustering for AD and its data. What is the best-practice for such task? | AD is already clustered. You bind to the domain using the correct entries that AD has stored in DNS. Edit - to clarify :
You don't do anything to cluster AD. The process of dcpromo to make a server a DC will automatically make the new DC take part in AD replication. That keeps the AD database synced. You don't need to do anything to make you application failover-aware either; you bind to the domain, not a single serve
Having said that, it's not a great idea to store much of your own data in AD's schema. You may want to make your own partition, or use LDS (formerly ADAM.) | stackexchange-serverfault | {
"answer_score": 6,
"question_score": 3,
"tags": "active directory, cluster"
} |
Promoting intuition (for undergraduate students): visual thinking, geometic approaches, etc. in the classroom
_Note:_ This question is ment to extend the scope of some related questions of mine. I would appreciate very much any suggestion to improve the way the question is posed.
* * *
I would like to ask what is -- according to your experience as students beforehand and educators then -- a sensible approach to develop undergraduate students' mathematical intuition (*) (that is visual thinking, etc.).
As the question is very broad, collections of references to research papers in the field of mathematical education and to fitting textbooks are very welcome ad accepted as helpful answers (at least by me).
(*) in general, but in particular as regards the following fields:
* Analysis;
* Mathematical/theoretical physics/ dynamical systems;
* Linear Algebra;
* Geometry;
* Abstract Algebra;
* Number Theory;
* Probability/Combinatorics. | For Linear Algebra, try this classic MAA volume: Resources for Teaching Linear Algebra. It gives a lot of examples of different ways teachers have worked to make linear algebra more concrete, applications oriented, visual, technology-based, etc.
<
For Vector Calculus, I particularly liked the problems and curricula from the Vector Calculus Bridge Project. They apparently have disabled the download link, though, and you'll have to email them to get a copy of their labs and instructor's guide.
< | stackexchange-matheducators | {
"answer_score": 2,
"question_score": 4,
"tags": "mathematical pedagogy, reference request, textbooks, intuition"
} |
Does logger(1) command belong to util-linux?
Does logger(1) command belong to util-linux? it is not shown in < but in < | It's part of util-linux, but Debian has packaged it in the bsdutils package. There's a pile of other packages that are also compiled from the util-linux source package, apart from `util-linux` and `bsdutils`.
You can see the (installed) binary package a file belongs to with `dpkg -S`:
$ dpkg -S /usr/bin/logger
bsdutils: /usr/bin/logger
`apt-cache showsrc _package_` should show the corresponding source package, but I just looked at the online package search; the source package is mentioned in the side bar. | stackexchange-unix | {
"answer_score": 2,
"question_score": 0,
"tags": "debian, logger, util linux"
} |
Как поставить русский язык в консоле на ввод
У меня проблема - нормально не отображается русский язык, а так же не принимаются русские литеры. Как можно это исправить? SETLOCALE нормально не работает. | Используй
system("chcp 1251 > nul");
Это команда работает на ввод и на вывод. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "c++, консоль"
} |
Unable to filter object from json array in groovy
In groovy, I have below object. (Type: [Ljava.lang.Object)
test = [
{
"id":"rod_1565173117796",
"userName":"rod",
"displayName":"Rod",
"date":1565173117796,
"comment":"ok"
},
{
"id":"rod_1565173139923",
"userName":"rod",
"displayName":"Rod",
"date":1565173139923,
"comment":"fine"
}
]
I want to modify / delete this list of JSON array based on id.
I tried below thing filter the required json object from list.
parsedJSON = parser.parseText(test);
parsedJSON.findAll{ it.id == 'rod_1565173139923' });
Which is giving me that
> No such property: id for class: java.lang.String
What wrong i am doing?
Thanks! | just several syntax fixes and your code works:
def test = '''[
{
"id":"rod_1565173117796",
"userName":"rod",
"displayName":"Rod",
"date":1565173117796,
"comment":"ok"
},
{
"id":"rod_1565173139923",
"userName":"rod",
"displayName":"Rod",
"date":1565173139923,
"comment":"fine"
}
]'''
def parser = new groovy.json.JsonSlurper()
def parsedJSON = parser.parseText(test);
def filtered = parsedJSON.findAll{ it.id == 'rod_1565173139923' } | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "java, json, groovy"
} |
Cofinite topology if first countable iff $X$ is countable
Here are two statements I want to show:
> For cofinite topology space $(X, \mathcal{T})$:
>
> (a) Show that X is first countable if and only if X has countably many points.
I have known how to prove " if X is first countable then X has countably many points". I use the contradiction to find if $X$ is uncountable, we could not find a countable local base.
But how about the inverse statement? If $X$ is countable, suppose $X=\\{x_{i}\\}_{i=1}^{\infty}$. For every $x_i$, I try to find their countable local basis. How to show that for every open set $U$, there exists a countable local basis $V_{i}$ such that $x\in V_i\subset U$? for some $i$.
> (b) Show that X is second countable if and only if X has countably many points. | If $X$ is countable, it has only countably many finite sets (standard set theory, or use a mapping using prime numbers to show that all finite subsets of $\Bbb N$ are in bijection with $\Bbb N$, e.g.), so countably many closed sets, so countably many open sets.
The whole topology is then countable and is its own base, while (the also countable) subfamily, $\\{O: O \in \mathcal{T}, x \in O\\}$ is a local base at $x$, for any $x$.
As to the last question, $X$ uncountable implies $X$ not first countable and so $X$ not second countable, so it's the same argument. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "general topology, first countable"
} |
Find a specific Google Document in Drive
I am trying to write a script to get the URL of a specific yet dynamic Google Document in Drive. The Google Document is created every Tuesday with its date at the end of the title of the Google Document.
"TypeError: Cannot find function getUrl in object FileIterator." error shows on line `var agendaURL = file.getUrl();`. Not sure how to debug this.
var ssUrl = 'LINK BUFFERED';
var sheetName = 'SHEET1'; // name of sheet to use
var rangeName = 'C30'; // range of values to include
var dateRange = SpreadsheetApp.openByUrl(ssUrl)
.getSheetByName(sheetName)
.getRange(rangeName)
.getValues();
// NEED TO find how to find file by name below!
var file = DriveApp.getFilesByName("Weekly Agenda | " +dateRange);
var agendaURL = file.getUrl(); | It is because you need to iterate through all of the files that meet the search criteria. The solution is here: <
var files = DriveApp.getFilesByName("Weekly Agenda | " +dateRange);
while (files.hasNext()) {
var file = files.next();
var agendaURL = file.getUrl();
return agendaURL //for first one, or you can return each one, push to an array, etc...
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "file, google apps script, find, drive"
} |
callbacks are not working
I have a critical problem that is my jquery plugins have call backs when I clicked on the elements the callbacks should be called.
I was observed that click event triggering more than one time for that I put unbind working some items well, but some items are not triggering callbacks.
$(this).children('li').unbind('click').click(function(){
switch(this.id){
case 'foo' : options.foocallback();
break;
case 'bla' : options.blacallback();
break;
.....
}
});
HTML:
<ul>
<li id="foo">...</li>
<li id="bla">...</li>
...
</ul>
now when I click on list items some working fine and calling callbacks
** But some items are not calling the callbacks** | You can try something like this _(if your event binding don't depend on some conditions)_
_**HTML_**
<ul id="listholder">
<li id="foo">...</li>
<li id="bla">...</li>
...
</ul>
_**jQuery_**
$('#listholder li').on('click', function() {
switch(this.id){
case 'foo' : options.foocallback();
break;
case 'bla' : options.blacallback();
break;
.....
}
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, jquery ui"
} |
orthonormal basis for $\mathbb{R}^n$
Let $\\{u_1,u_2,\dots, u_n\\}$ be an orthonormal basis for $\mathbb{R}^n$.
Show that
$$ \Vert v \Vert^2 = (v\cdot u_1)^2+(v\cdot u_2)^2+\dots+(v\cdot u_n)^2.$$
By the properties of a basis, $v$ can be written as $v=c_1u_1+c_2u_2+\dots+c_nu_n$.
I tried this !enter image description here | Since $\\{u_1,\cdots, u_n\\}$ is a basis for $\mathbb{R}^n$ then these vectors span $\mathbb{R}^n$ and we can write $$v=c_1 u_1+\cdots c_n u_n \qquad (1)$$ for some $c_i \in \mathbb{R}$.
Take the inner-product (the scalar product) of both sides of (1) by $u_i$ to get that
$$v\cdot u_i=c_1 u_1\cdot u_i+\cdots c_i u_i\cdot u_i+\cdots c_n u_n\cdot u_i= c_i $$ becaue $u_i\cdot u_i=1$ and $u_j\cdot u_i=0$ if $j\neq i$.
Therefore, by (1), we have the representation $$v= (u_1\cdot v) u_1+\cdots (u_n\cdot v) u_n.$$
Now, $$\|v\|^2= v\cdot v= \left((u_1\cdot v) u_1+\cdots (u_n\cdot v) u_n\right)\cdot\left( (u_1\cdot v) u_1+\cdots (u_n\cdot v) u_n\right)$$ $$=\sum_{i=1}^{n}\sum_{j=1}^{n} (u_i\cdot v)(u_j\cdot v) u_i \cdot u_j$$ $$=\sum_{i=1}^{n} (u_i\cdot v)(u_i\cdot v) u_i \cdot u_i= \sum_{i=1}^{n} (u_i\cdot v)^2.$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "linear algebra, vector spaces, orthonormal"
} |
How to add dpi responsive images to android studio?
I am new to the android development environment. I want to add an image into my application but with different dpi. If I go to drawable > new > Image Asset I can only add an icon for my app/menu button/notification icon. If I select the launcher icon, my image becomes way too small. If I click the menu bar menu, it becomes white. If I click notification, they're as tiny as an ant. Anyways, I was wondering if I can make android studio make the image responsive by adding differing dpis. like splash.png _HDPI_ splash.png _MDPI_ See what I mean? I made a splashscreen but on different devices it's either too small/too big.
**Note: PARDON ME IF THIS HAS BEEN ASKED BEFORE. I AM KINDA NEW** | in your res folder there multiple folders for drawables drawable-mdpi drawable-hdpi drawable-xhdpi ...
if you want to add an image for hdpi devices add it into drawable-hdpi | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, android, image, uiimageasset"
} |
Initialize variable (Read out of file and store in ArrayList/HashMap) once in Java
I have a program which reads out of files repeatedly. I want to initialize it only once then use the arraylist/HashMAP.
public boolean negative(String text, String type) throws FileNotFoundException
{
ArrayList<String> negative_list = new ArrayList<String>();
Scanner scan = new Scanner(new File("NegatingWordList.txt"));
while (scan.hasNextLine())
{
negative_list.add(scan.nextLine());
}
if(negative_list.contains(text))
{
return true;
}
return false;
}
So, after initializing negative_list, I needn't do it again. | From what I understand, your problem is that you want to save the contents of the file in memory. In that case, globally store your list, initialize to new list when your program starts, in your `negative` method, if list is empty then read from file into list, after that just check if the list contains the text or not. So after it fills up the list once, it wont read from file again. This will work if your file is not empty. If it is empty, it will read every time. This implementation is simple, therefore, for practice sake you should implement it yourself rather than anybody providing it. You have most of it working anyway. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "java, arraylist"
} |
Unicode support between different OS and browsers
I would like to develop a web application that uses Unicode. The problem is that I don't know if the user supports the full Unicode set or not.
Is the Unicode support dependent on the browser or the operating system? How well do the common browsers/OS behave when working with Unicode?
The goal is to find big subsets of mainly supported Unicode characters (with the fact that I accept to not support old tech). | > is the unicode support depends on the browser or the operating system ?
Both
> how well main browsers/OS behave ?
Current versions of the most popular browsers support (most of) Unicode (so long as you have fonts available that contain glyphs for the scripts you want to render). You need to make sure your web-server provides the appropriate character-set and encoding indications in HTTP headers and/or in HTML.
See Wikipedia, Unicode consortium and Alan Wood | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "browser, operating systems, web, unicode"
} |
Making function for php condition statement
i'm new to php, i'm making Online Cart website in php with admin panels, i've 3 type of users 1: admin (all roles) 2: sellers (who will sell their items) 3: customers/buyers (who will buy items)
function user_access($user){
$_SESSION['access'] == '$user';
return $user;
}
if(user_access('admin')){
echo "you are logged in as admin";
} else { echo "undefine access"; }
but its outpul is same :( how i can make functions for this type of conditions, like wordpress.
sorry for my bad english, | This:
function user_access($user){
$_SESSION['access'] == '$user';
return $user;
}
should be just:
function user_access($user){
return $_SESSION['access'] == $user;
}
So, you need to remove the quotes around `$user`, and return the result of the comparison, not the $user variable. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
How to upload large SQL Files?
I have a large sql file < 600 MB.
This files is backup for forum and I want to upload it to empty db.
How I can upload it??
I can't use PHPMyAdmin? and I used BigDump and it doesn't insert all tables.
How to do it?? Is there any other way?
Thanks
EDIT : I don't have access to command line, I just have my CPanel | Try the command line. Must be something like:
mysql --user=name --password=pw < mysql_db_dump.sql | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, mysql, database, backup"
} |
Replace special character of number to words BI publisher
I am trying to replace the "-" in FIVE HUNDRED THIRTY-FIVE AND NINETY-EIGHT to blank. However, whenever I have tried to add the xdoxslt in xdofx, it seems to display a blank value
<?xdofx:replace(xdoxslt:toCheckNumber($_XDOLOCALE, 535.98,'USD','CASE_UPPER','DECIMAL_STYLE_WORDS') ,'-', ' ')?>
This will display FIVE HUNDRED THIRTY-FIVE AND NINETY-EIGHT
<?xdoxslt:toCheckNumber($_XDOLOCALE, Order_Total_ID10,'USD' ,'CASE_UPPER','DECIMAL_STYLE_WORDS')?> | This will work:
<?xdoxslt:replace(xdoxslt:toCheckNumber($_XDOLOCALE, 535.98,'USD','CASE_UPPER','DECIMAL_STYLE_WORDS') ,'-', ' ')?> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "oracle, rtf, bi publisher"
} |
Swap() func in the book Essential C does not compile
wtf.c:11:6: error: expected declaration specifiers or '...' before '&' token Swap(&a, &b);
wtf.c:11:10: error: expected declaration specifiers or '...' before '&' token Swap(&a, &b);
Did not want to resort to StackOverflow for my personal problem but i cannot figure it out. The code is exactly the same as the book's. I've also tried making separated pointers and using them as arguments but i get the same error. Can someone shine some light on what am i doing wrong? I'm using gcc to compile the code.
static void Swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int a = 1;
int b = 2;
Swap(&a, &b);
I expected it to compile at least the exact example from the book but apparently not even that's possible. | #include <stdio.h>
static void Swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 1;
int b = 2;
Swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}
That compile and the execution print "2 1", as you can see _swap_ works
* * *
You had the compiler errors because of the form `Swap(&a, &b);` which is not a declaration nor a definition (it is a function call)
As it is said in remark the entry point of any C program is the function _main_ , automatically called, for more read documentation about C | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c, pointers, specifier"
} |
List of users that modified by a single Opportunity record
I have one opportunity record which is shared to 4 users in my organization. Any one can login and change the opportunity status.
I have to find list of users that modified that particular record.
I tried with LastModifiedById but i am getting only last user modified Id only.
SELECT opp.LastModifiedById FROM Opportunity opp WHERE Id = '002232332dwwsds'
How to retrieve all the users that modifies the opportunity record? | Your best solution for this is to enable Field History tracking on the fields where it is most important to see who changed them and then Salesforce will automatically log the change to the fields and who changed them.
You enable field history tracking from the Setup->Build->Customise->Opportunity->Fields and click the 'Set History Tracking' button. | stackexchange-salesforce | {
"answer_score": 3,
"question_score": 1,
"tags": "soql"
} |
How I can pass the results obtained by a query with group_concat(distinct) in another query?
I have a table named university_schools which contains all the courses records of each university and a table university_main_campus which contains records of all the universities. I want all the courses names from another table called 'courses'(which contains all the details including course_name, course_slug etc) of each course within that university.
Here is my query:
SELECT * FROM courses
WHERE course_id IN (SELECT GROUP_CONCAT(DISTINCT course_id) AS STR_CRSE_IDS
FROM `university_schools` WHERE univ_id = '2289')
I am getting only the first record whereas there should be 11 records.
Please help... | Try this query,
SELECT courses.*, b.STR_CRSE_IDS FROM courses INNER JOIN (SELECT DISTINCT course_id as STR_CRSE_IDS FROM university_schools WHERE univ_id = '2289') AS b ON courses.course_id = b.STR_CRSE_IDS | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, subquery, group concat"
} |
Compile less and output minify and non-minify files
I have a task in Gulp that compile a less file in css. I want to output the non-minify and the minify version with sourcemaps. I can't find a soluction. This is my actual task that should do this job:
return gulp.src(['./src/less/main.less'])
.pipe(sourcemaps.init())
.pipe(less({
paths: ['node_modules'],
}))
.pipe(sourcemaps.write('.'))
.pipe(cssnano())
.pipe(rename(function (path) {
console.log(path);
path.basename = path.basename.split('.')[0] + '.min' + (path.basename.split[1] || ''); //to change the name from main.css to main.min.css
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/css/'));
I get an error because cssnano want minify the map file. Can someone post his complete task with that feature?
Thank you in advance! | Something like this using 'gulp-clone' package:
var files = gulp.src(['./src/less/main.less']);
files
.pipe(clone())
.pipe(sourcemaps.init())
.pipe(less())
.pipe(cssnano())
.pipe(sourcemaps.write('.'));
files
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write('.')); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "gulp, gulp less, gulp sourcemaps"
} |
Как группировать числа?
Есть форма ввода цены "от" и "до" когда человек вводит цифры то они выглядят вот так: "10000" и "20000"
![введите сюда описание изображения](
Как сделать чтоб их группировать по 3 вот так:
"10 000" и "20 000" | в javaScript есть метод
number.toLocaleString()
он возвращает строку содержащую число в том виде который вам нужен | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, javascript, html, css, css animation"
} |
Are humans the only species that hunts down competitors, denies and destroys food for others?
In the book _Ishmael_) by Daniel Quinn, there's a passage that claims "Takers" (i.e. modern man) are the only thing in nature that hunt down competitors, destroy or otherwise deny someone else food. Are there strong arguments to be made that other animals exhibit the same behavior?
> "you may compete to the full extent of your capabilities, but you may not hunt down competitors or destroy their food or deny them access to food. In other words, you may compete but you may not wage war." All species inevitably follow this law, or as a consequence go extinct. The Takers believe themselves to be exempt from this Law and flout it at every point.
I'm disqualifying Kleptoparasitism which directly benefits the thief as an answer. There's no need to make a case about animals that do all 3 of the above mentioned things, refuting one of them is enough. | Ants are remarkable for waging war and enslaving and cultivating other species.
You may also be interested in a paper documenting ants being hostile to their neighbors. | stackexchange-skeptics | {
"answer_score": 62,
"question_score": 37,
"tags": "biology, ethology"
} |
"うとましく思う" meaning?
Google gave me "disagreeable" for just "" and "to be shy" for ""
These obviously don't have the same meaning. What's more, when I put the full sentence that I'm trying to translate into DeepL Translator and Google Translate, (the sentence was "") it came up with "to be envious"
So which is correct? or are none of those correct? Any reason why I got all these different answers (plus "to have an inferiority complex?) | I'm not quite sure how Google got "to be shy" for . In my experience, usually means more "to be annoyed", "to have bad feelings about (something/someone)", "to feel like (something) is not right/unfair", etc.
I suppose in some contexts, things like can be interpreted as "feeling isolated/estranged", which may be where Google got "shy" from, but I think that's really more a feeling of not getting along with someone or being excluded from a group, etc, not merely being shy or introverted.
So given this, I think one can also see how it might actually make sense to translate it as something like "envious" too, in sentences like your example.
This is another good example of why you shouldn't put too much trust in things like Google Translate (DeepL is much better, IMHO, but still not perfect either), especially for translating individual words/phrases out of context... | stackexchange-japanese | {
"answer_score": 2,
"question_score": 0,
"tags": "translation, verbs, adjectives"
} |
Indirect call of a column from different sheet
I know how to use the indirect formula in a sheet itself.
=INDIRECT(CHAR(ROW(A5))&ROW(A5))
However, I am having hard time manipulating this to find a formula from different sheet called 'sheet1'
I am trying to retrieve value in B3 of Sheet1 using indirect formula. Any help is appreciated.
Please note, going forward (I plan to drag this formula down) I plan to manipulate rows and columns so I do want both of them (rows and columns) as variable values.
Eg: NOT indirect('Sheet1'!B3) but rather something like indirect('Sheet1!'&char(row(a5))...etc) which is not working for me.
Thanks for the help! | `=INDIRECT(CHAR(ROW(A5))&ROW(A5))` just returns `#REF`
do not use something like `CHAR()` to build a "A1" address. Better use R1C1:
=INDIRECT("'Sheet1'!R3C2",0)
to make the row dragable:
=INDIRECT("'Sheet1'!R"&ROW()&"C2",0)
or to fit the columns:
=INDIRECT("'Sheet1'!R3C"&COLUMN(),0)
or for both:
=INDIRECT("'Sheet1'!R"&ROW()&"C"&COLUMN(),0) | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "excel, excel formula"
} |
MongoDB Geospacial search and official C# driver
Can some expert point the best ways to a Geospacial search using official C# driver in MongoDB. Best Object constructor(strings /doubles), Build an index, find near. Many thanks for your help.
db.places.ensureIndex( { loc : "2d" } , { min : -500 , max : 500 } ),
db.places.find( { loc : { $near : [50,50] , $maxDistance : 5 } } ).limit(20), | The C# equivalent to those Mongo shell commands is:
places.EnsureIndex(IndexKeys.GeoSpatial("loc"), IndexOptions.SetGeoSpatialRange(-500, 500));
var query = Query.Near("loc", 50, 50, 5);
var cursor = places.Find(query).SetLimit(20);
foreach (var hit in cursor) {
// process hit
} | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 6,
"tags": "c#, mongodb, mongodb .net driver"
} |
iCal Format - Organizer Property
I am currently programming a scheduling application which loosely based on iCalendar standard. Does anyone knows in which property can I store the event creator's information? By browsing through the iCalendar RFC 2445, I find this property: Organizer. can I store the event creator's information in the property even if he/she is the only person involved in the event? or there is already a field to store the event creator's information???! | Some notes from the rfc2445
Conformance: This property MUST be specified in an iCalendar object that specifies a group scheduled calendar entity. This property MUST be specified in an iCalendar object that specifies the publication of a calendar user's busy time. This property **MUST NOT be specified** in an iCalendar object that specifies only a time zone definition or that **defines calendar entities that are not group scheduled entities, but are entities only on a single user's calendar**. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "icalendar, rfc2445, rfc5545"
} |
Must a sequence be well-founded?
> Must a sequence be well-founded?
Is $\Bbb Z=(\ldots-1,0,1,2,\ldots)$ a sequence?
Conventionally we think of $\Bbb N=(0,1,2,3,\ldots)$ as a sequence, but what about if it has no starting value?
Obviously we can reorder any countable set $X$ into a well-founded sequence e.g. by an injection $f:X\to \Bbb N$ but what about in its raw form, do we call $\Bbb Z$ a sequence? | That is not a sequence, but it is a net).
**Definition** A nonempty set $A$ together with a binary relation $\le $ is said to be a _directed set_ if $\le$ satisfies
* $a \le a, \quad\forall a \in A$
* $a \le b \text{ and } b \le c \text{ implies } a \le c, \quad \forall a,b,c \in A$
* $\forall a,b \in A \,\exists c \in A \text{ such that } a\le c \text{ and } b \le c$
**Definition** Let $(A, \le)$ be a directed set and let $X$ be any set. Any function $f : A \to X$ is said to be a _net_ in $X$.
We see that $\mathbb{Z}$ with its standard order $\le$ is a directed set (and so is every totally ordered set) so the identity function $\operatorname{id} :\mathbb{Z} \to \mathbb{Z}$ is a net in $\mathbb{Z}$.
Sequences are precisely nets with the domain $(\mathbb{N}, \le)$.
Bear in mind that the informal terminology _"an $S$-indexed sequence"_, where $S$ is only a set, may also be used to describe a function $f : S \to X$. | stackexchange-math | {
"answer_score": 6,
"question_score": 12,
"tags": "sequences and series, terminology, order theory"
} |
Mutate a new column and paste value from existing columns conditional on string in column names
I have this dataframe:
df <- structure(list(number = 1:3, a_1 = c(1L, 4L, 7L), a_2 = c(2L,
5L, 8L), a_3 = c(3L, 6L, 9L)), class = "data.frame", row.names = c(NA,
-3L))
number a_1 a_2 a_3
1 1 1 2 3
2 2 4 5 6
3 3 7 8 9
I want to mutate a `new_col` and fill it with values conditional on string match of column `number` to column names.
Desired output:
number a_1 a_2 a_3 new_col
<int> <int> <int> <int> <int>
1 1 1 2 3 1
2 2 4 5 6 5
3 3 7 8 9 9
I tried with `str_extract`, `str_detect` ... but I can't do it! | We may use `get` after `paste`ing the 'a_' with 'number'
library(dplyr)
library(stringr)
df %>%
rowwise %>%
mutate(new_col = get(str_c('a_', number))) %>%
ungroup
-output
# A tibble: 3 x 5
number a_1 a_2 a_3 new_col
<int> <int> <int> <int> <int>
1 1 1 2 3 1
2 2 4 5 6 5
3 3 7 8 9 9
* * *
It may be better to use a vectorized option with `row/column` indexing
df$newcol <- df[-1][cbind(seq_len(nrow(df)),
match(paste0("a_", df$number), names(df)[-1]))] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "r, tidyverse, string matching, dplyr"
} |
Copy to Output Directory in Visual Studio 2017
Hello I am walking through this tutorial here.
I have created a Console App project in Visual Studio 2017 and have successfully added references to the EmguCV library. However I am struggling with the OpenCv files.
After adding them to the solution, then highlighting them and clicking properties, there is no available option to "Copy to Output Directory".
![enter image description here](
The properties window only displays the Misc section. How do enable "Copy to Output Directory" for these files in VS 2017? | The Solution Items are part of the solution folder structure and do no belong to a project, Copy to Output directory relates to a project build, which copies the items to the output directory on a successful build.
In your case, you want to copy those 2 dlls when you build your ConsoleOCR Project, you can use post build events.
Go to your project, right click and select Properties. Then go to Build Events tab, click Edit Post-Build and specify the commands:
xcopy "$(SolutionDir)\opencv_core2410.dll" "$(TargetDir)"
xcopy "$(SolutionDir)\opencv_imgproc2410.dll" "$(TargetDir)"
I assume you use those DLLs as references in your project, you can go to your References in the project and right click them then change the property of Copy Local to True. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "c#, opencv, visual studio 2017"
} |
I cant see root in my gradle to extract SHA key for google login .my android version is 4.2
enter image description here
my android version is 4.2
Here it is gradle showing dependencies only
Iam done gradle configuration and jdk configuration
I've checked their version .working good | Click on the elephant icon:
![enter image description here](
and type `signingReport` -> enter -> find the SHA-1 key. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android"
} |
Is jQuery cache disabling trick needed if a server returns cache prevention headers?
I need to fully prevent caching of Ajax calls results. Jquery ajax() function has a`cache: false` option for this. The option appends timestamp to each requested resource (`?_=1353592676117`). This should do the job, but is not very elegant. It pollutes logs and can be puzzling for someone not familiar with the trick.
Is enabling this option ever needed if the server returns a correct set of cache prevention headers (`no-cache`, `no-store`, `must-revalidate`, optionally also `max-age=0`)? If so, in which cases headers are not enough? | You don't need to set `cache: false` flag if you are setting correct cache prevention response headers at your server. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "jquery, http, http headers, browser cache, http caching"
} |