INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Asynch thread stopping main UI thread
Can anyone tell me why the following dialog box does not show until the _asynchronous_ thread has finished. I cannot figure this one out. This is running in the main UI thread. Not sure why a new thread would affect the flow of the main UI thread
dialog = new ProgressDialog(this);
dialog.show();
new Thread(new Runnable() {
public void run() {
while(imageLoader.isProcessing()) {}
doSomething();
}
}).run(); | You need to call the `start()` method of the anonymous Thread, not the `run()` method.
From the docs):
> public void start(): Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 3,
"tags": "java, android, multithreading, dialog"
} |
Gutenberg dependencies in package.json
Seeing as `@wordpress/scripts` will magic my development versions of `@wordpress/*` dependencies, should any of them be present in the `package.json` for my own block development?
Gutenberg examples package.json refers exclusively to `@wordpress/scripts` despite the entrypoint file referring to `@wordpress/i18n` and `@wordpress/blocks`. Should I do the same? | Yes and no, it depends...
The WP Scripts package depends on the `@wordpress/dependency-extraction-webpack-plugin` package at:
<
What this will do is search for packages from `@wordpress` and list them in a file to make it easy for you to load the list of dependencies when enqueuing. It also adjusts webpack so that it knows not to compile in those dependencies, but instead rely on WordPress to provide them at runtime via enqueuing. As a result, the packages aren't needed, and you don't end up with 20 copies of `@wordpress/element` loaded on the page from every extra block installed.
So, you don't need to put `@wordpress/element` in your `package.json` requirements when using wp scripts to build the assets. This only applies to WordPress packages though. Other libraries on the other hand get included the normal way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, block editor"
} |
type of openCV output SIFT descriptors
What is or what should be the type of the output descriptors Mat in openCV C++ ?
C++: void SIFT::operator()(InputArray img, InputArray mask, vector& keypoints, OutputArray descriptors, bool useProvidedKeypoints=false) Parameters:
img – Input 8-bit grayscale image
mask – Optional input mask that marks the regions where we should detect features.
keypoints – The input/output vector of keypoints
descriptors – The output matrix of descriptors. Pass cv::noArray() if you do not need them.
useProvidedKeypoints – Boolean flag. If it is true, the keypoint detector is not run. Instead, the provided vector of keypoints is used and the algorithm just computes their descriptors.
What I mean is "descriptors – The output matrix of descriptors."
Thanks. | as a rule of thumb: whenever you see an OutputArray, you don't have to worry about the size or type.
just supply an uninitialized Mat, the function will fill it.
in this case , the output will be a NxM float Mat where N(rows) will be the number of keypoints, and M(cols) will be 128, the length of a SIFT feature. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c++, opencv, sift"
} |
Buffer Strategy for * Component
Is it possible to create a `BufferStrategy` instance for any other `Component` except the Windows or Frames? | You are probably looking for java.awt.Canvas | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, graphics"
} |
Update Switch statement affects entire table
MS Access SQL. I'm doing a Update SQL statement using SWITCH.
Update Insurance Set [SellPrice]=SWITCH
([Cover]=50, 4.2,
[Cover]=100, 5.4,
[Cover]=200, 6.8)
The 3 fields in the statements are updated correctly, but it blanks out the SellPrice column for all other entries. The statement is updating all rows, not just the 3 that I identified. | This is usual behavior. Your update query always affects all rows, and a switch statement returns `Null` if none of the conditions are met.
You should filter the rows you want affected:
Update Insurance Set [SellPrice]=SWITCH
([Cover]=50, 4.2,
[Cover]=100, 5.4,
[Cover]=200, 6.8)
WHERE Cover IN (50,100,200)
Alternatively, you could make the `SWITCH` statement return the current value if none of the conditions are met:
Update Insurance Set [SellPrice]=SWITCH
([Cover]=50, 4.2,
[Cover]=100, 5.4,
[Cover]=200, 6.8,
True, SellPrice)
However, that will likely have worse performance and lead to more locks. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, ms access"
} |
forcing https with primary domain & www. but NOT subdomains
I have a domain and SSL certificate installed. it's NOT a wildcard SSL.
We have a third-party url rewrite for one of the subdomains that is hosted on their services - something I can't get rid of or control.
They do not have an SSL on the subdomain. Now that I've installed the SSL, the subdomain is always redirecting to https as well, which is throwing an error.
I want the sub to go to the http and the primary domain only to go to https.
I originally had the following in my htaccess:
RewriteCond %{HTTPS} !on
RewriteRule (.*)
I've since removed this and everything is still directing to https. | > We have a third-party url rewrite for one of the subdomains that is hosted on their services
Is this something that is being done outside of your .htaccess file? This 3rd party rewrite might be causing the issue.
However if you just want to ignore the subdomain just add it to the rule.
RewriteEngine on
RewriteCond %{HTTPS} !^on
RewriteCond %{HTTP_HOST} !^subdomain\.example\.com [NC]
RewriteRule (.*) [R=301,L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache, .htaccess, mod rewrite, ssl"
} |
How do I prevent, stop, or kill JavaScript function?
How do I prevent this JavaScript function from executing.
I have a js function that is causing a serious issue and I am not able to remove nor modify it source. I would like to know if it is possible to simply prevent, stop, or kill the function in order that it is not executed till I resolve the issue.
So somewhere inside the page:
<script type="text/javascript"><!--
problem_func();
//--></script>
And all I want is to stop that function from execution placing a stopper inside the header or external js.
Any advice?
**HERE IS THE LIVE EXAMPLE, HOW TO STOP THAT?< | If you know the function name, you can replace it with a function that does nothing. After the script tag of the source js file use this:
window.FunctionName=function(){return false;}; | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 8,
"tags": "javascript, dom, dom events"
} |
What to do when result from pipe is not last argument in next command
The example below shows what I want to do, namely take the result from my last pipe and put it into the middle of the next command (where I wrote `$RESULT_FROM_FIND_COMMAND`).
$ find . -name "*0.01*txt" | cp $RESULT_FROM_FIND_COMMAND $(awk '{{split($1,a,"/")} {print a[3]"_"a[4]"_"a[5]}}')
What variable or command must I use to achieve this?
I'm using bash if that matters.
Ps. note that awk should also take the result from find as an input. | In this case, use the shell to iterate
find . -name "*0.01*txt" | while IFS= read -r filename; do
newname=$(awk '{split($1,a,"/"), print a[3]"_"a[4]"_"a[5]}' <<< "$filename")"
cp "$filename" "$newname"
done
In general, xargs is helpful:
find .... -print0 | xargs -o -I FILE someCommand arg1 FILE arg3 FILE | stackexchange-unix | {
"answer_score": 3,
"question_score": 0,
"tags": "bash, pipe"
} |
Unicorn + Rails + Large Uploads
I'm trying to allow for large uploads when running Unicorn on Heroku with Rails but I've realised that any large uploads might take longer than the timeout period for a Unicorn worker. This will mean (I've seen this happen) that the Unicorn master process will kill the worker uploading the large file and the request will timeout (with a 503 error).
Without removing or massively increasing the timeout for my server is there any way to allow the uploading worker to hang while the upload completes? Or, am I completely misunderstanding and its most likely something else that is causing my uploads to timeout? | If you're uploading to S3, then you can "simply" have the user upload files direct to S3 instead of via your dynos, and get pinged when the upload is complete.
For significantly more information than this, check out something like CarrierWaveDirect | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 11,
"tags": "ruby on rails, http, heroku, unicorn"
} |
Вызов переменной из функции
Хочу добавить кнопку в окно `Toplevel`, но для этого надо занести её в переменную, для того что бы указать место, где она будет находиться.
Но когда я это делаю при выполнении скрипта, интерпретатор говорит, что переменная `top` не определена. Как мне использовать эту переменную?
from tkinter import *
main = Tk()
main_frame = Frame(main, width="300", height="300").pack()
def toplevelwin():
top = Toplevel(main_frame, relief=SUNKEN, width="300", height="300", takefocus=True)
def close_app():
main.destroy()
Button(top, text="Сохранить", relief=SUNKEN).pack()
Button(main_frame, text="Добавить пароль", command=toplevelwin, relief=FLAT).pack()
Button(main_frame, width="30", text="Закрыть", command=close_app).pack()
main.mainloop() | Окно `Toplevel()` не существует до вызова `toplevelwin()` функции. Нет нужды создавать кнопку, пока её родитель ещё не создан:
def toplevelwin():
top = Toplevel(main_frame, ...)
Button(top, text="Сохранить", relief=SUNKEN).pack()
main.eval('tk::PlaceWindow %s center' % top.winfo_pathname(top.winfo_id())) | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, python 3.x, tkinter"
} |
Which Python library for file access to analyse and manipulate?
For starters I'm going to make a program which analyses my poker hand histories which are stored automatically as text files.
So which library do I need to snoop around in if I'm looking to analyse .txt files? I mean I can find some functions but I want to become more independent instead of googling a solution each time and actually learning things by myself...tell me if this is a stupid idea.
Thanks in advance. | `open()` if its very simple, `csv` if its a bit more complicated and pandas for everything else. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python"
} |
How to change mysql database directory on WAMP
I'm running a dual boot server with Windows 7 and Ubuntu. On Ubuntu, everything is configured how I want it. On Windows, I need to know how to change my MySQL database directory so that it uses the same directory I'm using on Ubuntu. How do I do this? | Hope this image would guide clear. You can write click and select view image to see my answer clearly
; //<- Returns 3
If you mean your value is `3` and you want to turn that to `10 points` you can do the following.
var index = 3;
var scores = new List<string>
{
"1 point",
"2 points",
"5 points",
"10 points",
"15 points",
"20 points",
"25 points",
"30 points",
"40 points",
"50 points"
};
var score = scores[index]; //<- Returns 10 points | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#"
} |
Specify flask project with static port 5000 in visual studio 2015
I am new in flask development , and am using visual studio , when i run the project , it random generates **ports** e.g `44744,84849,84458` each time i run , how can i make it static to `5000` each time i run the project?. | What i did was to remove all the lines from file `runserver.py` :
if __name__ == '__main__':
HOST = environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
and replaced them with :
app.run(port=5000,debug=True) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "flask, visual studio 2013"
} |
How to update tag in a file by using powershell
I have a configuration file which is (test.properties)
File includes:
<a>aa</a>
<b>bb</b>
<c>ccc</c>
<d>dddd</d>
<Test>Yes</Test>
I want to replace a value of "Nope" in test.properties file by using powershell.
Existing : <Test>Nope<Test>
AFter Update it should be
<Test>Yes<Test>
How can i replace this value by using powershell? | Use replace! Below code will read the content in the file and replace your test tag with the new value and then write the content back to the same file
(Get-Content yourfile.xml).replace("<Test>Nope<Test>", "<Test>Yes<Test>") | Set-Content yourfile.xml | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "powershell"
} |
Как сменить фон формы по клику на её элемент?
Для программы нужна смена фона и размера окна Текущий код:
private: System::Void новичокToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)
{
//9*9
this->Height = 360;
this->Width = 300;
this->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"$this.BackgroundImage")));
this->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
}
Так как строки были взяты с кода самой формы подвязка картинки вызывает ошибку ;
Формат адреса (вариант ввода FileName)
C:\\Users\\User\\Desktop\\name.png | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "winforms, c++ cli"
} |
Is it possible to deprecate a sass/scss mixin?
When maintaining and updating the mixins for a large team of developers, is it possible to deprecate mixins so that they throw some sort of warning when the styles are compiled?
I do not simply want to remove the deprecated mixins as it will take some time to remove all the current uses, but it'd be nice to warn the other developers that this is being removed if they attempt to use it. | You can use the `@warn` directive for this. From the SASS documentation:
> The @warn directive prints the value of a SassScript expression to the standard error output stream. It’s useful for libraries that need to warn users of deprecations or recovering from minor mixin usage mistakes.
You'd use it like this:
@mixin old-mixin {
@warn "This old mixin is deprecated!";
// mixin definition here
} | stackexchange-stackoverflow | {
"answer_score": 19,
"question_score": 6,
"tags": "sass"
} |
Is the United States the country with the highest obesity rate?
> **Possible Duplicate:**
> Is the United States the fattest country in the world?
According to different sources and the media, the United States is well known for being the country with the highest obesity rate, no one ever has asked my weight so I don't see how reliable this information is. Is it true then? | No,
According to Forbes, Global Post and Infoplease, the country (island country) of Nauru
This is the top 10 list according to forbes:
Rank Country %
1. Nauru 94.5
2. Micronesia 91.1
3. Cook Islands 90.9
4. Tonga 90.8
5. Niue 81.7
6. Samoa 80.4
7. Palau 78.4
8. Kuwait 74.2
9. United States 74.1
10. Kiribati 73.6 | stackexchange-skeptics | {
"answer_score": 6,
"question_score": 3,
"tags": "nutrition"
} |
How to set different size of navigation drawer in different values folder
I want to resize the width of my navigation drawer between `layout-large` and `layout-xlarge`, so I've created different folders:
res/values-sw480dp
res/values-sw600dp
But it doesn't work, so i tried:
res/values-large
res/values-xlarge
But it doesn't work either:
<fragment
android:id="@+id/fragment_navigation_drawer"
android:name="fr.solutis.solutis.FragmentDrawer"
android:layout_width="@dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="@layout/fragment_navigation_drawer"
tools:layout="@layout/fragment_navigation_drawer" /> | res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra-large in landscape orientation
res/values-mdpi/your.xml // xmlfor medium-density
res/values-hdpi/your.xml // xml for high-density
res/values-xhdpi/your.xml // xml for extra-high-density
res/values-xxhdpi/your.xml // xml for extra-extra-high-density
res/values-sw600dp/your.xml // 7"
res/values-sw720dp/your.xml // 10" | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android studio, navigation"
} |
Python Module issues
Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale
CashAMDSale.AMDSale()
and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *
def AMDSale():
AMDInstance = DataFunctions.GetValidAMD()
And here is GetValidAMD
import pyodbc
def ValidAMD(GetValidAMD):
(short method talking to a database)
My error comes up on the line that has `AMDInstance = DataFunctions.GetValidAMD()`
I get the error `AttributeError: 'module' object has no attribute 'GetValidAMD'`
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks! | `DataFunctions` is a folder, which means it is a package and must contain an `__init__.py` file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD
or you need to add the following to the `__init__.py` of `DataFunctions`:
__all__ = ["GetValidAMD"]
then you can `import *` from the package and everything listen in `__all__` will be imported | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, module"
} |
How to update only modified values (EntityFramework 5.0)?
I have this entity, want to update using entityframework
EmployeeModel employee = new EmployeeModel
{
Id = 1000, //This one must
FirstName = modifiedValue,
Email = modifiedValue,
LastName = originalValue,
Phone = originalValue
};
Code to update
_db.ObjectStateManager.ChangeObjectState(employee, EntityState.Modified);
_db.SaveChanges();
This is the SQL statement got once updated
Update Employee set Id=1138,FirstName='modifiedValue',Email='modifiedValue',LastName= 'OriginalValue',phone='originalValue' where Id=1138
But I am expecting this
Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.
I dont know what I am missing here. Please let me know. | This is the solution I got
var entity = _db.CreateObjectSet<Employee>();
entity.Detach(employee);
entity.Attach(employee);
foreach (string modifiedPro in employeeModel.ModifiedProperties){
_db.ObjectStateManager.GetObjectStateEntry(employee).SetModifiedProperty(modifiedPro);}
_db.SaveChanges();
Only modified values in the sql update statement
Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138.
If anybody knows better answer than this, Please post your suggestions | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 8,
"tags": "entity framework, c# 4.0, entity framework 5"
} |
How to load parts of bash alias only when logging in via ssh
As the title states, is it possible to have an alias only load when I access the machine through `ssh`, or better yet, only from a specific computer through `ssh`? | In `.bashrc` (or where you define the aliases), you can make it conditional based on the variable `SSH_CONNECTION`, which is set only for ssh connections. For example:
if [[ $SSH_CONNECTION == *"your-IP"* ]]; then
alias ll="ls -l"
# your other aliases
fi | stackexchange-superuser | {
"answer_score": 7,
"question_score": 5,
"tags": "linux, bash, ssh, tmux, .bash profile"
} |
smooth scroll to name
I have seen some standard code for smooth scroll to a href with # but I am doing a link to anchor by way of `name` attribute. So the code would be like this:
<li>
<a href="#on-water">On Water</a>
</li>
goes to the section:
<a class="mwm-aal-item" name="on-water"></a>
It is a plugin called Better Anchor Links for wordpress, that is why it is set up that way. | **DEMO HERE**
$(document).ready(function(){
$('li > a').on('click', function(){
$('html,body').animate({scrollTop : $('.mwm-aal-item').offset().top},3000);
});
});
the previous example if you run the code for a specific anchor .. \-
but if you want to run that with all anchors use this **DEMO HERE**
$(document).ready(function(){
$('li > a').on('click', function(){
var GetaName = $(this).attr('href').split('#');
$('html,body').animate({scrollTop : $('a[name ='+GetaName[1]+']').offset().top},1000);
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, wordpress"
} |
Design pattern to display missing data in line/bar chart of a daily data feed
I am displaying a daily data feed in my app, i.e. one value per day. The data is displayed in either a bar or line chart. In the event that a data point is missing on a given day, I want to indicate somehow that the value is missing on that day. Here are a couple initial design concepts that are quite visually distracting or strong. I'm aiming for a design that is less distracting, more elegant.
!enter image description here
!enter image description here
(If my wording of the question is not specific enough, please leave comments and I'll improve it.) | Even I'm facing same issue in the analytics product I'm working on now.
My line of thinking is
Use solid base line(axis) for all the positions/bars which represent data existence. Use dotted base line for all the positions where data is missing as shown in the Mockup below:-
!enter image description here
Highlight the axis label where there is dotted line and provide tooltip info regarding missing data.
This I guess is the natural analogy, which is, solid line indicating something present/existing and dotted line indicating something missing or virtual.
And, it is well known that dotted lines are meant for filling something which is not there. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "data, charts"
} |
Should SO renumber questions that are abused by spammers?
See this question. The nortorious "ugg boot spammer" keeps returning to this question (if you have 10K powers you can see the deleted spam posts).
Obviously, some spammer has this bookmarked and keeps coming back to create new accounts and post garbage. Can this question be renumbered, killing its permalink? Would this help the problem? Perhaps if our boot pushing friend gets a 404 he'll just go away. | Breaking permalinks punishes everyone. If we were gonna go that far, then voyager's Closing suggestion would at least allow folks to still _find_ the question, even if they couldn't respond. | stackexchange-meta | {
"answer_score": 2,
"question_score": 0,
"tags": "discussion, spam"
} |
Compiling node.js, as means of testing for runtime errors?
Is it possible to compile a node.js program as a way of discovering 'evident' errors, rather than waiting for runtime. Currently I use eslint and testing, but would be I interested to see if there are other tools that can help reduce the risk?
I come from a background of Java development, where I am used to the compiler catching some of these mistakes. | You can't compile as such, but you can use a linter instead.
jshint is one of several available. jshint documentation page
The idea is to check the code for mistakes and errors, similar to the checks a compiler would make.
This process won't find all types of runtime errors but it will discover many of the issue that would be found by the compiler in languages like Java. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "node.js"
} |
SSL Login Structure
I have a members only celebrity photo and video gallery, for media professionals only. It's setup on a dedicated server and I have recently installed a wildcard SSL certificate.
I have a main public website which advertises our services, hosts the registrations forms and has the secure login form. The login form, when submitted, goes to the same server but to a different account/directory, like so:
From:
To:
... and then the login detail get processed.
Does my login page need to be on ` when they arrive on it, or does my login form need `action=" to make it secure? I'm not familiar with how SSL works. | If the landing page that has the login form isn't https, then attacker can deliver wahtever they want, and just rewrite the page to http. SSLStrip is a tool that an attacker can use to perform this attack.
But more importantly, who cares about the login page? Sure it should be protected, but a username and password isn't how the browser authenticates. The browser uses a cookie to authenticate with your web application, **this is the real authentication token**. It really doesn't mean anything if you login over https and then just spill the authentication token a few seconds later. the **entire session must be over https** or you will be violation of owasp a9. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "security, ssl, authentication"
} |
In PHP, how can I add an underscore between two variable names
I have some DB fields called
picture1_en
picture2_en
...
picture1_de
picture2_de
...
picture1_it
picture2_it
Yes, it could have been implemented in another way, but I cannot change the implementation.
Suppose I have a variable called $lang that contains "de" or "en" or "it"
Now, if I want to print the value, I could use this:
for($i=1; $i<=10; ++$i)
echo $r["picture$i_$lang"];
The problem is that PHP interprets the underscore as part of the variable name (e.g. it interprets it as "$i_"). I tried escaping the underscore in a lot of crazy ways, none of them working.
Sure, I could do
echo $r["picture".$i."_".$lang];
But I was wondering if there is a way to force PHP to interpret the "_" as a string literal, and not as a part of a variable name. | You can use curly braces to separate the variable name boundaries in a string (double quoted only)
$r["picture{$i}_{$lang}"];
or
$r["picture${i}_${lang}"];
<
**Complex (curly) syntax**
> Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear: | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 7,
"tags": "php, string"
} |
select items based on value first, then date order for all the others
I have a table with this structure:
| ID | TYPE | ... | ... | ... | TIME | ... |
I want to create a query which first lists all items with a `type` of `xxx` in date order, and then lists all other items in date order.
How do I create this query? I have never done this level of MySQL sorting using MySQL itself. | Use
SELECT whatever FROM whatever_table
ORDER BY type = 'xxx' DESC, `time`
The `type = 'xxx'` is a boolean expression and therefore returns true or false, 1 or 0. You can simply order by this. Since you want to have the one's where `type = 'xxx'` first, you have to sort descending. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "mysql"
} |
How do I return the correct variable from this function?
I am trying to print out a star rating from a database. The rating for this hotel is currently set to 5. This is my code:
<?php
function star_rating($stars) {
echo "star rating is $stars";
}
?>
and then in the place where I want to print the star rating
<?php star_rating(print $row['Rating']); ?>
I want it to print out 'star rating is 5' but it keeps printing out '5star rating is 1'
It is definitely connected to the database correctly because when i change the star rating in the database, the first number changes accordingly.
Sorry if this is really silly, I'm new to PHP! Thanks in advance for any help given. | `print` always return 1, so in your code, the value of `print $row['Rating']` is one. It's look like calling function like this : star_rating(1);
Also print send variable to output, in your case it will print `5` and send `1` to function, and in your function the output is `star rating is 1` and so on you will see `5star rating is 1` in output.
For this problem you just need remove `print`.
`<?php star_rating($row['Rating']); ?>` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, html, mysql"
} |
Removing a specific filename via mod rewrite
How would I accomplish the following via mod rewrite in the .htaccess
www.example.com/foo/test.php => www.example.com/foo
Also, this rewrite does not need to be reflected in the browser's address bar, i.e. doesnt need to be a redirect. | To match exactly it would look like this:
RewriteRule foo/test.php /foo [L]
If you want to match against only the test.php part, it would look like this:
RewriteRule ^(.*)/test.php /$1 [L]
Either rule will take a request `www.example.com/foo/test.php` and internally rewrite it to `/foo` and serve /foo to the browser. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "apache, .htaccess, mod rewrite"
} |
Check text file for data, if there is any write to webbrowser with javascript
I have a c program for a temperature sensor which create a file and write the temperature to the file and whether this is inside or outside some choosen values. The data from file is supposed to be displayed on a webbrowser and updated every 5 min.
I was wondering if anyone could help me how to make a javascript, that checks the file and write the data to the webbrowser and "refresh" this data every 5 min according to the data in the text file. Pretty "green" in javascript programming so hope someone could help me. | Try something like:
function refreshDivFromFile(){
$("#div").load("file.txt");
}
window.setInterval(refreshDivFromFile, 5 * 60 * 1000);
you need the div in your html:
<div id="div"></div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "javascript, jquery, html"
} |
How to get output value from python script executed in swi-prolog
How can I make a `swi-prolog` program that executes a Python file `score.py` and gets the output?
I've read about `process_create/3` and `exec/1` but I can't find much documentation | You need to use the `stdout/1` and `stderr/1` **options** of `process_create/3`.
For example, here is a simple predicate that simply _copies_ the process output to _standard output_:
output_from_process(Exec, Args) :-
process_create(Exec, Args, [stdout(pipe(Stream)),
stderr(pipe(Stream))]),
**copy_stream_data(Stream, current_output),**
% the process may terminate with any exit code.
catch(close(Stream), error(process_error(_,exit(_)), _), true).
You can adapt the `copy_stream_data/2` call to write the output to any other stream. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "python, prolog, swi prolog"
} |
Uninstall a specific python
I have installed two python3.6
/usr/local/Cellar/python/3.6.4_4/bin/python3
/Users/me/anaconda3/bin/python
`/Users/me/anaconda3/bin/python` was set as default by system
$ which python
/Users/me/anaconda3/bin/python
$ which python3
/Users/me/anaconda3/bin/python3
If I run `pip uninstall`, the default would be removed which was intended to keep.
How to uninstall the other one? | To directly answer your question: `pip3 uninstall`
`pip3 ...` to do pip for the python3 you've got installed...
`pip3 -V` for example should output the path to where Python 3 is installed | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x"
} |
Is it possible that the first arrival time of a poisson process is infinite?
Given is a Poisson process $(N_t)_{t \geq 0}$ with intensity $\lambda(t)$. I am interested in finding the distribution of the first arrival time $T$. I can use the fact that for any $t \geq 0$ it holds $T > t$ iff $N_t = 0$. By the definition of the process $N_t \sim Poi(\mu(t))$, where $\mu(t) = \int_0^t \lambda(z) dz$. I get $$ \mathbb{P}[T > t] = \mathbb{P}[N_t = 0] = \exp(-\int_0^t \lambda(z)dz), $$ and therefore the distribution is given by $\mathbb{P}[T \leq t] = 1 - \exp(-\int_0^t \lambda(z)dz)$.
If I consider the intensity $\lambda(z) = \frac1{1+z^2}$, I can calculate $$ \lim_{t \to \infty} \mathbb{P}[T \leq t] = 1 - \exp(-\int_0^\infty \lambda(z)dz) = 1 - \exp(-\frac\pi2) \neq 1, $$ so $\mathbb{P}[T < \infty] < 1$. Have I done something wrong or is it simply possible that $T$ attains infinity with positive probability, so the process never jumps? | A homogeneous Poisson process with intensity $\lambda > 0$ almost surely has a finite first arrival time, since $$\lim_{t \to \infty} \Pr[T \le t] = \lim_{t \to \infty} 1 - e^{-\lambda t} = 1.$$
However, as you have observed, this is not the case for an inhomogeneous process, since the cumulative intensity (aka cumulative hazard) need not be an unbounded function of time. That is to say, if $$\Lambda(t) = \int_{z = 0}^t \lambda(z) \, dz$$ obeys $$\lim_{t \to \infty} \Lambda(t) < \infty,$$ then the first arrival time may not be finite. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "probability distributions, stochastic processes, poisson process"
} |
How can I produce a select tag using JSTL or Standard Actions in a JSP
I want to make a select tag in a JSP, where the options are an Enumeration (for example, all US States). Is their a tag in JSTL or a standard tag that can do this, without manually iterating through the list? | There isn't in JSTL. However many frameworks provide such additional tags:
* Struts2 \- `<s:select>`
* Spring MVC \- `<form:select>`
* JSF \- `<h:selectOneMenu>` | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 10,
"tags": "java, html, jsp, jstl"
} |
Why does this IF statement not require an End IF
I am using the following snapshot of code to loop through files in a folder, it has a simple `If` to check if there are files in the folder then exits if there aren't. I've realised it does not require an `End If` at the end to compile correctly. However, I want to add a `msgbox` explaining why it has exited and to do so I need to introduce an `End If` to my code.
Why is that?
**Original Code**
If Len(strfilename) = 0 Then Exit Sub
Do Until strfilename = ""
'Do some stuff
strfilename = Dir()
Loop
**With MsgBox**
If Len(strfilename) = 0 Then
MsgBox ("No Files Found")
Exit Sub
Else
Do Until strfilename = ""
'Do some stuff
strfilename = Dir()
Loop
End If | There is a single line form of `if`:
if (expr) then X
where `X` must be on the same _line_ , which is nice for single expressions:
if 1=1 then exit sub
or the odd but legal (using `:` continuation character)
if 1 = 1 Then MsgBox ("No Files Found"): Exit Sub
which is better written using the more readable block form that requires an `end if` to tell the compiler when the `if` block ends:
if 1 = 1 Then
MsgBox ("No Files Found")
Exit Sub
end if | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "loops, if statement, excel, vba"
} |
What is the meaning of movabs in gas/x86 AT&T syntax?
I just found a strange instruction by assembling (with `gas`) and disassembling (with `objdump`) on a `amd64` architecture.
The original `amd64` assembly code is:
mov 0x89abcdef, %al
And, after `gas` compiled it (I am using the following command line: `gcc -m64 -march=i686 -c -o myobjectfile myassemblycode.s`), `objdump` gives the following code:
a0 df ce ab 89 00 00 movabs 0x89abcdef, %al
My problem is that I cannot find any `movabs`, nor `movab` in the Intel assembly manual (not even a `mova` instruction).
So, I am dreaming ? What is the meaning of this instruction ? My guess is that it is a quirks from the GNU binutils, but I am not sure of it.
PS: I checked precisely the spelling of this instruction, so it is NOT a `movaps` instruction for sure. | Here's the official documentation for `gas`, quoting the relevant section:
> In AT&T syntax the size of memory operands is determined from the last character of the instruction mnemonic. Mnemonic suffixes of `b`, `w`, `l` and `q` specify byte (8-bit), word (16-bit), long (32-bit) and quadruple word (64-bit) memory references. Intel syntax accomplishes this by prefixing memory operands (not the instruction mnemonics) with `byte ptr`, `word ptr`, `dword ptr` and `qword ptr`. Thus, Intel `mov al, byte ptr foo` is `movb foo, %al` in AT&T syntax.
>
> In 64-bit code, `movabs` can be used to encode the `mov` instruction with the 64-bit displacement or immediate operand.
Particularly read the last sentence.
**Note:** Found via Google operator `inurl`, searching for `movabs inurl:sourceware.org/binutils/`. | stackexchange-reverseengineering | {
"answer_score": 29,
"question_score": 32,
"tags": "x86, amd64"
} |
Are there any rewards for fully restoring Norende?
I know that in the demo you receive a play kit bonus for fully upgrading all of the shops in the village, but is there a similar reward for doing so in the full version of the game? | When you fully rebuild Norende you have access to some pretty sweet items, with the village shopkeepers occasionally sending you some of their stock as a gift (sadly, never weapons or armor). But besides that, you only get an extra Party Chat scene. No extra gifts as far as I can recall. | stackexchange-gaming | {
"answer_score": 6,
"question_score": 4,
"tags": "bravely default"
} |
What do C# Table Adapters actually return?
stack **overflow** !
I'm working on an application that manipulates SQL tables in a windows form application. Up until now, I've only been using the pre-generated Fill queries, and self-made update and delete queries (which return nothing).
I am interested in storing the value of a single value from a single column (an 'nchar(15)' name), and though I have easily written the SQL code to return that value to the application, I have no idea what it will be returned _as_.
SELECT [Contact First Name] FROM ContactSkillSet
WHERE [Contact ID] = @CurrentID
Can the result be stored directly as a string? Do I need to cast it? Invoke a toString method?
Thanks!
Edit: Interestingly enough, the following works:
String firstName = this.contactSkillSetTableAdapter.GrabFirstName(userKey);
The joys of the Visual Studio data wizard, I suppose. | A TableAdapter is used to fill a DataTable. The result of your example query will still be a DataTable but with a single column in a single row. You can get the value using:
var adapter = new SomeKindOfTableAdapter();
var dataTable = new DataTable();
adapter.Fill(dataTable);
string contactFirstName = (string)dataTable.Rows[0][0];
There are other ways to get your value without using a Table Adapter though:
string query = @"SELECT [Contact First Name]
FROM ContactSkillSet
WHERE [Contact ID] = @Current";
string result;
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand command = new SqlCommand(query, conn))
{
result = (string)command.ExecuteScalar();
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, sql, winforms"
} |
Is it possible to design view with uiscrollview in storyboard with checked auto layout?
Good day! i have hierarchy:
> view-scroll view - [set of elements: labels, textfields, etc.].
>
> Height of view is more than default size. i've added to scrollview in storyboard key with _contentSize_ , set _top and left constraint_ , in **viewDidLoad** i set
>
> **self.scrollView.frame = self.view.frame;**
but in emulator scrolling is not working...( if i uncheck auto layout scrolling is working. but i need it checked. So question is it possible to design view with uiscrollview in storyboard with checked auto layout? thanks everybody for answering!=) | found the solution: for correct working scrolling you need ONLY add constraint horizontal and vertical spaces + spaces from top and bottom Layout guide=) stay on scroll view - touch button "Add missing constraints"... after this constraints will be added automatically...=) good luck! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "layout, uiview, uiscrollview, scroll, autolayout"
} |
SpinBoxDelegate and QItemDelegate
I work on project It's like SpinBoxDelegate in Qt sample project but I must customize It, I mean having different widget(textbox) in second and third column of table view instead of spainBox.What do you suggest? | Try instead `tableView.setItemDelegate(&delegate);` from the example something like QTableView::setItemDelegateForColumn().
Plus have a look at this one tutor. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++, qt, qt4"
} |
Change brush strokes of drawn image
I'm really new to Illustrator and I drew an image I like, but then I noticed there were different brushes and think it'd look cooler with another one, so is there any way to change the brush strokes for what I've already drawn without having to trace over the entire thing? | * Select your stroke with the black arrow.
* Open the Brushes palette.
* Click on the new brush you want.
* Tada! | stackexchange-graphicdesign | {
"answer_score": 3,
"question_score": 2,
"tags": "adobe illustrator"
} |
Make TypeScript aware of loaded object
I'm trying to do some work with Google Analytics. The google js that you load adds a `gapi` variable to the `window` dom object.
When coding the TypeScript isn't complaining about the fact that `gapi` doesn't exist on `window` object.
I'm trying to detect if the `gapi` file is loaded and if not then load it dynamically from my script.
GAPI doesn't have a Type Definition that I can find so I'm trying to figure out how to check that it's loaded into the DOM. I've been able to check it's (non-) existence through the console on Chrome and through jQuery so either is an option. Just can't figure out how to do this in TypeScript since it doesn't know about `gapi` at all.
If you haven't used the Google Analytics js library. It returns both a `window.gapi` and a `gapi` ref for you to use in `code`/`DOM` | To make TypeScript aware of the addition you would use:
interface Window {
gapi: any;
}
Or the shorter:
declare var gapi: any;
You could optionally flesh out the definition.
This should then allow you to use gapi, including in your detection script:
if (typeof gapi === 'undefined') ... | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, typescript"
} |
Java. Начало карьеры.
Хочу начать карьеру Java2EE разработчика. Опыта в этой области нет. Собственно вопросы: Стоит ли пытаться делать что-то "для себя", потренироваться использовать популярные технологии (даст ли это что-то?) или лучше сразу идти искать где меня такого возьмут, пусть даже не в очень перспективной компании? Представляя себя в роли работодателя, меня могут взять: а) "на вырост"; б) делать какие-то мелкие задачи/исправления. По каким признакам можно отличить первое от второго? Интеграторы и консалтинг — гиблое дело? | Ну, карьера `Java2EE` разработчика, по моему, довольно перспективна. А еще более перспективна `Java` для `Andriod` (потому что больше платят и больше вакансий).
По-моему, для начала надо изучить азы. Если есть усидчивость, то флаг в руки и самоучитель перед глазами. Если маловато усидчивости, то прям сразу начинать программки писать, когда рядом учебник и интернет. Вот только опыта-то больше появляется от реальных проектов. Так что можно посоветовать изучить основы языка и пытаться найти работу. Пусть не высокооплачиваемую, но там можно уже на реальной практике обучиться.
Но и самое главное, что надо знать разработчику, так это `ПАТТЕРНЫ ПРОЕКТИРОВАНИЯ`. Вот прекрасная книга.
По поводу технологий, сразу много не изучишь, так что для начала основы языка.
По поводу самых распространенных, так я думаю, что это `EJB`, `JPA`, `Hibernate`, `Spring`. | stackexchange-ru_stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "работа, java"
} |
Java: Retrieve the generic parameter value at runtime
What is the best way to retrieve the runtime value of a generic parameter for a generic class? For example:
public class MyClass<T> {
public void printT() {
// print the class of T, something like:
// System.out.println(T.class.getName());
}
}
So if I call
new MyClass<String>().printT()
it will print "String" | You don't. Due to type erasure that information is (mostly) lost at runtime. If you really need the class this is what you do:
public class MyClass<T> {
private final Class<T> clazz;
public MyClass(Class<T> c) {
if (c == null) {
throw new NullPointerException("class cannot be null");
}
clazz = c;
}
public void printT() {
System.out.println(clazz.getName());
}
}
and then you have access to it. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "java, generics"
} |
Selecting multiple divs in html
How do we hover over multiple div in html at the same time?
I have two divs at different positions in a html page.
I want to hover on any of divs and it, and the other div to get selected.
How can I accomplish it using preferably css properties only? currently its going from parent to child not the vice versa,i tried all different combinations. even ~ and + properties.
html code:
<div id=one1>
<div id=two2></div>
</div>
css:
#one1:hover { background-color: yellow;}
#two2:hover { background-color: yellow;} | Did you mean something like this **Fiddle**
#one:hover ~ #two ,
#one:hover ~ #three
{ background-color: yellow; } | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 2,
"tags": "html, css, css selectors"
} |
I am trying to optimize my ruby else if statements
I am trying to find out if there is a more elegant way to write this piece of code:
result.each_with_index do |rowset,index|
if rowset["Answer"].to_i == 0
puts "1"
end
if rowset["Answer"].to_i == 1
puts "2"
end
if rowset["Answer"].to_i == 2
puts "3"
end
if rowset["Answer"].to_i == 3
puts "4"
end | How about this?
result = [{"Answer"=>"1"}, {"Answer"=>"3"}]
puts result.map(&-> v { v["Answer"].next })
Outputs:
2
4
=> nil | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, ruby"
} |
Trying to compile to release mode for the first time and it bring up errors
Can anyone tell me why when I try and build my solution in debug it works fine but then when I try to do it in release I get a wack of errors, especially with some referenced .dlls not being referenced anymore.
I have been working on this project for a while it is very big, and has alot of dependencies. I am now ready for it's first release copy and I cant get it going, I feel like I am missing something. Is there any flaws to distributing a debug copy of the software?
My next question is should I try and compile to any CPU or just compile to x86. I would like for everyone to be able to use the software? What is the norm?
Software is in vb.net using visual studio 2010. | Unless you post specific error messages its going to hard to give a solution, but it could well be simply a matter of copying the dlls from debug to the release folder. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "c#, .net, vb.net, visual studio 2010, visual studio"
} |
Fiducial Inference in Machine Learning
I was looking at the Fiducial Inference page on wikipedia, which is an alternative to the traditional Frequentist and Bayesian standpoints. Although it was out of favour in mainstream statistics for many years, there seems to have been a resurgence in interest in recent years (see for example Jan Hannig's recent publications on the subject). Does anyone know of anyone in the ML community looking at these ideas from a theoretical point of view, or who has successfully created an algorithm based on them? | I do not know of anybody in ML looking at this problem. (It's probably not in people's mind as a problem per se). ML folks are more interested in predictive problems, where the quality of the "learning" or "inference" is determined by how well it does on a test set. | stackexchange-stats | {
"answer_score": 6,
"question_score": 5,
"tags": "machine learning, inference, fiducial"
} |
does "wide range of food" mean? please give me an alternative if it does not
In the following sentence. is "wider range of food" a good collocation? I mean the range of things that an animals consumes as food. Is there any specific word to mention this?
> During the drought, however, omnivores appear to suffer less because they have a **wider range of food** compared with carnivorous or herbivorous species. | The _have_ in "they have a wider range of food" could either mean _eat_ or _possess_ as in "have got" that being the case both meanings are appropriate.
The sentence could be rephrased as:
1. ...appear to suffer less because they can eat a **greater variety** of food than that of carnivores and herbivores."
2. ... because they **consume a wider range of food compared to**... | stackexchange-ell | {
"answer_score": 2,
"question_score": 0,
"tags": "word usage, word request"
} |
Microsoft Azure Storage - Success Percentage
I added a microsoft azure storage to my hosting strategy and moved about 15gb if videos to Azure. I set up the CDN endpoint and it seems fine and i have no complaints . But I added monotoring and cant understand the "Success percentage" indicator and why would it not be 100%? | Because some requests can go wrong:
* Throttling
* Authentication failed (SAS key expired for example)
* Client / Server Timeout
* Network errors
The complete list of possible errors can be found here: Storage Analytics Logged Operations and Status Messages | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "azure, azure blob storage"
} |
How to unify different array data into 1 data arrays in javascript?
I have a data array is as below:
array = [
0: 'a',
1: 'b',
2: 'c'
]
I want to make the data array is as below
array = ['a', 'b', 'c']
Please help I really need this :') thank you... | it is an object not array
array = {
0: 'a',
1: 'b',
2: 'c'
}
you can use for in to get array from object
var array = {
"item-0": 'a',
"item-1": 'b',
"item-2": 'c'
}
var t = [];
for (const key in array) {
if (array.hasOwnProperty(key)) {
t.push(array[key]);
}
}
console.log(t)
is as array | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "javascript"
} |
Is this someone trying to hack the server?
I keep seeing the following coming up in my nginx and Apache server log files as a 400:
() { :; }; /bin/ping -c 3 x.x.x.x
x.x.x.x is different IPs. Does this look like a hacker trying to find a hole into the server? We have IP blocking facilities, but I don't want to do that if its genuine.
The full log file entry, is:
207.150.177.200 - - [25/Sep/2015:08:51:02 +0200] "GET / HTTP/1.0" 400 226 "() { :; }; /bin/ping -c 3 82.118.236.247" "-" | Yes, they are trying. And failing.
You can tell that they are failing by looking at the return code -`400 - bad request` means that your server is basically saying "No way I'm going to let you do that". Which, in this context, is a good thing. | stackexchange-serverfault | {
"answer_score": 9,
"question_score": -1,
"tags": "spam, hacking"
} |
Add line breaks inside property to be displayed within <p> tags in the template angular
I have a property errorMessage declared in my ts component. I need to store a string within this that contains multiple lines that need to be separated by a line. '\n' doesn't seem to work with this. Please suggest the way to do this.
In ts component:
this.errorMessage = 'An error has been encountered. \nDetails:\n' + errorString;
In html template:
<p>{{errorMessage}}</p> | You can do the one trick here as you can use **[innerHTML]** attribute to show you html that is inside your **errorMessage**
You have to modify your code in component like
this.errorMessage = 'An error has been encountered. <br>Details:' + errorString;
And in your template you can render you above message by using above attribute like
<p [innerHTML]="errorMessage"></p>
The above code will render your errorMessage as a HTML not a string so line break will also rendered | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "html, angular"
} |
Regular Expression to find CVE Matches
I am pretty new to the concept of regex and so I am hoping an expert user can help me craft the right expression to find all the matches in a string. I have a string that represents a lot of support information in it for vulnerabilities data. In that string are a series of CVE references in the format: CVE-2015-4000. Can anyone provide me a sample regex on finding all occurrences of that ? obviously, the numeric part of that changes throughout the string... | Generally you should always include your previous efforts in your question, what exactly you expect to match, etc. But since I am aware of the format and this is an easy one...
CVE-\d{4}-\d{4,7}
This matches first `CVE-` then a 4-digit number for the year identifier and then a 4 to 7 digit number to identify the vulnerability as per the new standard.
See this in action here. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 3,
"tags": "regex, pattern matching"
} |
Is there a way to color a specific word in Placeholder text QML?
Is there a way to color a specific word in placeholder of text in QML?
I saw you can do it in `TextArea` or `Flow` but I need two colors in a placeholder of a `TextField`. What I need is something like this: let's say my placeholderText is ("Last name"). I need "Last" in grey and "name" in pink. Is there any way to do that? | I've tried at random to use HTML instead of plain text and that suddenly works:
TextField {
anchors.centerIn: parent
placeholderText: "<font color='grey'>Last</font> <font color='pink'>name</font>"
width: 200
}
But this behavior is not described anywhere and I would not use this workaround in production. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "qt, qml"
} |
Error al publicar en Visual Studio 2019
Hasta el día de hoy no había tenido este problema al publicar en **visual studio** **2019.** estoy tratando de publicar un proyecto web en **.NET Framework4.6.2** y el error que me da es el siguiente:
> Error No se pudo ejecutar la tarea ejecutable especificada "sgen.exe". System.ComponentModel.Win32Exception (0x80004005): El nombre del archivo o la extensión es demasiado largo en System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) en System.Diagnostics.Process.Start() en Microsoft.Build.Utilities.ToolTask.ExecuteTool(String pathToTool, String responseFileCommands, String commandLineCommands) en Microsoft.Build.Utilities.ToolTask.Execute() BizInside Base MultiLogIn Compilación
El problema que veo, es que no se cual archivo es el problematico para intentar acortarlo.
Cualquier ayuda se agradece mucho! | Parte del error dice:
> El nombre del archivo o la extensión es demasiado largo
Por lo tanto, intenta mover el proyecto a una carpeta de nombre corto como `C:\Dev\TuProyectoAqui` | stackexchange-es_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": ".net"
} |
Overwrite values in for-loop PHP
How can i print values in same place when i echo the statement instead of printing the values in the same/next line (if using br tag). This is a sample for-loop
for($i=0;$i<10;$i++)
{
echo $i;
}
The output will be:
> 0123456789
But I want my output to be the one as shown below as it should overwrite values in the same place.
> 9
I will display all the values slowly one by one using timer or sleep but my objective here is to overwrite the previous value or display it in the same place. | I'm sorry, but you can't do it. If you want to change the output in the browser itself, after you flushed the buffer, you have to use JS.
Think of it this way: When you `echo`, you put some values in the buffer stream. When the buffer is flushed, you see the printed value in the browser. You can manage the buffer, flush it, clean it, change it, but you can't change whats already out there.
I hope that helps some how. Look at this link for more information about stream output: Output Control | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "php, for loop"
} |
Firestore: Get server timestamp value for making client-side time comparisons
I have a document retrieved from Firestore that has a date field X. I want to know if X is a date in the future or not. How would I do this in JavaScript from the browser?
It would be best if I could get a server-side timestamp S for this and then in the browser I would make the comparison X > S? How do I get S?
I know I have use a placeholder value for the server timestamp when uploading documents and doing queries but I want a concrete value for the timestamp here. | To get an estimate of the server time, simply write a document with a field that contains the server time sentinel token as a value, then immediately read the document back and look at the Timestamp that the server actually wrote. Then delete the document, of course. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "google cloud firestore"
} |
Add comma separator to a value variable
I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable
x = 10023871234981029898198264897123897.231241235
How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string. | First of all, for such huge numbers you should use string format:
var x = "10023871234981029898198264897123897.231241235";
Otherwise, JavaScript will automatically convert it to exponential notation, i.e. `1.002387123498103e+34`.
Then, according to the question about money formatting, you can use the following code:
x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
It will result in: `"10,023,871,234,981,029,898,198,264,897,123,897.231241235"`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript"
} |
R Shiny: Changing location of image src from www
I have quite a few images among a few different apps and I would like to store them in one central location.
Current, only images stored in the nested `www` directory of a shiny app seem to work when sourcing images:
tags$img(src="img123.img") #Image stored in ./www/plant123.img
I would like to query these images from another location, say:
`/opt/images_central`
I have tried using `addResourcePath`, but I have not had success in getting the images to render:
addResourcePath("www", "/opt/images_central")
Any ideas on how to avoid storing images in the nested www directory? | After a while of trying to figure this out, I got it to work.
addResourcePath("images", "/opt/images_central")
And then I call the images using the following path:
images/myimage.jpg
I was using: `/images/myimage.jpg` but that does not work. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, shiny"
} |
Hard disk write-once mode on Windows
Is it possible to force a hard disk into 'write-once' mode in Windows?
I want to securely store logs so they can't be changed, but I can't use tapes or optical media due to performance reasons. | You can look at some storage appliances that have some WORM capability. EMC Centera, HP StoreAll 9000 series, and others all have some WORM capability. These aren't exactly cheap however. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 7,
"tags": "windows, security, storage, hard drive"
} |
Is CiviCRM 4.6 Bootstrap Compatible
On a 4.5 site running the most recent Drupal, I have to use the themekey module to make CiviCRM public facing pages use a different theme from the site default because of Bootstrap compatibility problems. (For admin stuff I'm using a non-bootstrap admin theme.)
The client really wants the public-facing part of the site to use the same bootstrap theme for all pages.
Is 4.6 have any better Bootstrap compatibility than 4.5? | 4.7 should be, but not 4.6 as is. There was a GSoC student who worked on making CiviCRM more Bootstrap-friendly, unfortunately the patches were not merged in for 4.6.
I've started working on it again, based on Amilineni's work, but I'm slowly moving forward. If anyone beats me to it, I will be more than happy :)
So far, I've been trying to add a few classes to core forms (CRM/Core/Form.php), and try to see if we can override the CSS on buttons using Saas/Less, and perhaps moving a bit of CSS out of civicrm.css so that we can make it optional (to avoid loading extra CSS rules if we are using Bootstrap). | stackexchange-civicrm | {
"answer_score": 5,
"question_score": 4,
"tags": "ui"
} |
Is it possible to generate simultaneous touch events in the iOS simulator?
From time to time we get bug reports with our iOS iPad application where the steps to reproduce require 2 buttons to be pressed simultaneously (or at least within a very short space of time, a tenth of a second or less).
To reproduce these bugs I have to use a real device rather than the simulator. This is fine, but also a bit of an annoyance (as I type this I'm waiting for ~10k files to copy over to the documents folder of my app on my device to get it up to date, will likely take an hour or so longer).
Ideally I'd like to be able to reproduce these issues using the simulator, so my question is whether it is possible to generate 2 touch events near enough simultaneously using the simulator? | If you hold down Option in the Simulator you get a second "finger". If you also hold down Shift you can move around both fingers. This is usually meant to test pinch gestures. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, touch, ios simulator"
} |
HTML hyperlink with mouse over image
I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image. how to do this | That depends on where you need to display the image. If you are looking for something along the lines of an icon next to or behind the link, you could accomplish this through CSS using a background image on the hover state of the link:
a:link
{
background-image:none;
}
a:hover
{
background-image:url('images/icon.png');
background-repeat:no-repeat;
background-position:right;
padding-right:10px /*adjust based on icon size*/
}
I did this off the top of my head, so you may need to make some minor adjustments.
If you wanted to show an image somewhere else on the page, you could accomplish that using javascript to hide/show the image on the link's mouseover event.
If this doesn't solve your problem, maybe you could supply some additional information to help guide everybody to the right answer. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "asp.net, html"
} |
Is this a bug with the Angular Bootstrap date picker?
If I have an Angular bootstrap date picker with a format of "DD/MM/YYYY" and hide it with an ngIf it defaults back to a format of "MM/DD/YYYY" when it is shown again.
<button (click)="show = !show">{{ show ? 'Hide' : 'Show' }}</button><br>
<input bsDatepicker [bsConfig]="{ dateInputFormat: 'DD/MM/YYYY' }" type="text" [(bsValue)]="date" *ngIf="show">
See this StackBlitz <
Can anybody think of a work around? | One workaround would be to only hide the datepicker in DOM, instead of destroying/recreating it. So, instead of `*ngIf="show"`, `[class.hidden]="!show"` (and css: `.hidden { display: none; }`).
< | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "angular, angular bootstrap"
} |
What's the equivalent of the adjacency relation for a directed graph?
I've found several sources describing a relation notated $\sim$ signifying adjacency in an undirected graph, but nothing explicitly describing an equivalent for a directed graph. I've been using $\overset{\mathit{member}}{\longrightarrow}$, mainly because I have different types of edges so I need a long symbol to overset with the type of the edge linking the nodes. Is this appropriate? Is there a more usual notation? | An arrow is absolutely appropriate to use in this case. For example, see Shimon Even's _Graph Algorithms_. In fact, I think it would be questionable to use anything _but_ an arrow for a directed edge.
Note that Even places the name of the edge over the arrow; your notation of putting the edge type over the arrow is fine too. Or you might put the type underneath, to save room above for the name in case you might need it later. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "graph theory, notation, relations"
} |
Android Studio is not using gradle to build my projects
I imported a project from Eclipse and android studio is not using my gradle scripts to build the project. Anyone else having this issue? Is there anyway to force Android Studio to use gradle to build my project. | If you import an existing project with no gradle configuration, Android Studio will use the old build system. If you want to use gradle, you should follow the instructions in the documentation :
< | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "android, gradle, android studio"
} |
Provide a way to retrieve questions and answers that have been deleted
Could you please provide a way to retrieve deleted questions/answers?
Your database contains that data, until you hard delete it, so it would be useful for us to have the chance to play with it.
I'm suggesting to add a parameter like:
deleted (optional)
* When "true", will include deleted id where available.
* boolean
Why I'm asking it?
Well, because a lot of questions were recently deleted and it would be cool to have access to them without using the data dumps. | This goes hand in hand with authentication. | stackexchange-stackapps | {
"answer_score": 3,
"question_score": 26,
"tags": "feature request, api, api v2.2, posts"
} |
Value-Returning Function Not Returning Any Value
Am I doing something wrong? There was no errors running the program. This should output a boolean value, but when I run it there is no return value. The program lets the user to enter a number, but then the program doesn't return anything.
def main():
num = int(input("Enter a number:"))
isPrime(num)
def isPrime(num):
if num < 2:
return False
elif num == 2:
return True
else:
for counter in range(2, num):
if num % counter == 0:
return True
return False
main() | "return" only returns that value from the function, it does not display anything to the screen. You could assign the value that is being returned to a variable, but if it is not assigned or used, it is lost. If you wanted it to actually be displayed, you could do
print(isPrime(num))
which will then print out the resulting boolean to the console, or assign the returned value to a variable for later use. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x"
} |
Сохранение Canvas в SVG
Есть ли понятный алгоритм (или урок, или просто кусок кода) сохранения отрисованного в `Canvas` изображения в `SVG`?
Иными словами, нужно сохранить то, что приложение рисует при помощи инструментов `Canvas`, в вектор. | Для преобразования Canvas в SVG используйте js библиотеку canvas2svg.js. [[Demo]](
Ещё одна библиотека для преобразования: html5-canvas-svg
Ссылки на ресурсы взяты из ответа на аналогичный вопрос на enSO:
**Method to convert HTML5 canvas to SVG?** | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "android, svg, android canvas"
} |
concat just one element of 2d array in javascript
I am new in javascript so this question might be very basic..
I have a list like this:
[ ["word",number],["word2",number2]......]
I want to get one string like
concat_str = "word\nword1\n....."
I see that for 1d array there is this join..
array.join()
method..
But how do i do this for just one element of 2d array. | There's no simple function for what you want to do because what you want is a bit more specific: you want a specific element of each array to be concatenated. Not too hard, though:
array.reduce(function (prev, cur) {
return prev += cur[0] + "\n";
}, '').trim(); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "javascript"
} |
Why does $\ln(x) = \epsilon x$ have 2 solutions?
I was working on a problem involving perturbation methods and it asked me to sketch the graph of $\ln(x) = \epsilon x$ and explain why it must have 2 solutions. Clearly there is a solution near $x=1$ which depends on the value of $\epsilon$, but I fail to see why there must be a solution near $x \rightarrow \infty$. It was my understanding that $\ln x$ has no horizontal asymptote and continues to grow indefinitely, where for really small values of $\epsilon, \epsilon x$ should grow incredibly slowly. How can I 'see' that there are two solutions?
Thanks! | The _slope_ of $\log x$ falls of as $1/x$. So for, say, $x>1/\varepsilon$ the logarithm always grows strictly _slower_ than $\varepsilon x$, and the latter will eventually overtake it.
More precisely, if we put $a=2/\varepsilon$ then at any point to the right of $a$, the function $\varepsilon x$ gains at least $\varepsilon/2$ on the logarithm for each unit increase in $x$. Therefore $\varepsilon x$ will be larger than $\log x$ no later than at $x=a+\frac{2\log a}{\varepsilon}$. | stackexchange-math | {
"answer_score": 5,
"question_score": 7,
"tags": "functions, perturbation theory"
} |
problems with proving that f and g are homotopic.
i need to give an example of 2 continuous functions $f,g: X \rightarrow Y$ which are not homotopic, with: $X = [0,1] \times [0,1]$ and $Y = [0,1] \cup [2,3]$
and i need to show how many homotopical classes of continuous functions $f:X \rightarrow Y$ there exists.
for 1: i think the functions $f(x,y) = x$ and $g(x,y) = x+2$ will maybe work, using these functions we can make a function $F:X\times I \rightarrow Y$ with $F(x,t) = x+2t$. I find it confusing though by how to check wheter F is continous or not. Any hints about that?
for 2: I think the trick here is to let a random continuous function $f:X\rightarrow Y$ be homotopic to the zero-function $f'$, so we get one equavalention class. Is this the right way to think or am i on the wrong track?
Hints/tips and tricks would be very apreciated
Kees | For #1: Be careful! Your "homotopy" $F$ doesn't have values in $Y$ (and I guess you meant $F(x,y,t) = \dots$). For example $F(0, 0, \frac{3}{4}) = \frac{3}{2} \not\in Y$. To show that the two maps you define are not homotopic (and they are not), I advise you use the facts that:
* $X \times I$ is path-connected;
* $Y$ has two path-connected components: $[0,1]$ and $[2,3]$;
* the image of a path-connected space is path-connected.
So any you can't possibly have a homotopy $F : X \times I \to Y$ such that $F(x,y,0) = f(x,y)$ and $F(x,y,1) = g(x,y)$ (because the image would lie in two distinct path components.
For #2: $X$ is contractible and $Y$ has two contractible path components. How many homotopy classes of functions $\\{0\\} \to \\{0,1\\}$ are there? | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "general topology, homotopy theory"
} |
PowerPoint 2013 missing "Paste Special" context menu
This is the strangest thing. I have googled for answers but can't seem to find ones that apply.
All I want to do is select a portion of an Excel file and paste/link it into a PowerPoint presentation, so that if the Excel file is updated, the corresponding PowerPoint presentation reflects the updates made to the Excel spreadsheet.
According to everything I've read, I should be seeing a 'Paste Special' context menu in PowerPoint, that would allow me to paste the Excel snippet as an object.
However, it does not show up:

+ (NSString *)extractNumbersFromString {
return [[self componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
}
I have this error: "no known class method for selector componentsSeparatedByCharactersInSet"
why? if this selector is part of NSString and I am extending it, I don't understand this error... | `componentsSeparatedByCharactersInSet:` is an instance method, not a class method. You are trying to call it within a class method, so there is no instance to which the message should be sent.
So, the message is being sent to what it thinks is a class method called `componentsSeparatedByCharactersInSet:`, which doesn't exist - hence the error.
To fix it change the signature of your extension to:
- (NSString *)extractNumbersFromString | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, iphone, ipad"
} |
Upper bounds for the least $a$ in $p \nmid x^3-a$
Are there any bounds for $a$ when for all $x$, $p \nmid x^3-a$ and $p$ is a prime number?
There have been numerous studies on the smallest quadratic non residue.
However, are there such bounds for cubes as well?
It is known that no such $a$ exists when $p-1$ is coprime to $3$.
However, what happens if $p-1$ is not coprime to $3$?
Because of Thue`s Lemma, there exists $x \equiv ky \pmod p$ where $x,y$ has a absolute value less than $\sqrt {p}$ and $k$ is a number coprime to $p$.
If we set $k$ as a primitive root of $p$, and if all numbers smaller than $\sqrt {p}$ was not such a $a$, it would be a contradiction.
My Question is Thus: For $p \equiv 1 \pmod 3$ is it true that $a<2\sqrt [ 3 ]{ p }$?
This seems to be true, but I cannot prove it, nor do I have any idea how to solve it. Any help would be appreciated. | If $3 \mid p-1$ then let $g$ be a primitive root modulo $p$. Write $a=g^k$ then $$x^3 \equiv g^k \mod{p} \Leftrightarrow 3 |k$$
So the question you ask is the following: Find the smallest positive integer $a$ which is in the set $$A:=\\{ g^k | 3 \nmid k \\}$$
Therefore, the order of magnitude of primitive roots link here give you some upperbounds. But since $A$ can contain (especially when $p-1$ has many divisors) many non-primitive roots, it is likely that a better upperbound can be found, but I don't see any obvious one. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "number theory"
} |
Flag when character appears more than once in a string
I have seen something similar answered for Python but not for R. Say I have the sample data below, and I want to create the "want" column, which flags when the character "|" appears more than once in the string in the "var1" column. How would I do this in R? I know I can use `grepl` to flag whenever "|" appears, but this would also capture when it only appears once.
Sample data:
var1<-c("BLUE|RED","RED|BLUE","WHITE|BLACK|ORANGE","BLACK|WHITE|ORANGE")
want<-c(0,0,1,1)
have<-as.data.frame(cbind(var1,want))
var1 want
BLUE|RED 0
RED|BLUE 0
WHITE|BLACK|ORANGE 1
BLACK|WHITE|ORANGE 1 | `str_count` can be used - count the number of `|` (metacharacter - so escape (`\\`) or specify as `fixed`, and then create a logical vector (`> 1`), convert the logical to binary (`as.integer` or `+`)
library(stringr)
have$want <- +(str_count(have$var1, fixed("|") ) > 1) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "r, string, grepl"
} |
Problems with PayPal IPN - redirect and post data
After users have been redirected to PayPal and completed the payment, they get redirected back to my site (ipn.php). However, it turns out it only sends back the user using HTTP get method.
I'm using the following IPN listener: <
However, it just says "Invalid HTTP request method" when user arrives on the ipn.php page. It's supposed to post back data and redirect the user. Am I missing a PayPal setting here or something?
Really appreciate some help on this. | The PayPal IPN does not occur when they redirect the users back to your site. Your users get redirected to a normal confirmation page.
The IPN request happens later. The delay can vary quite significantly and it only occurs when the transaction has been fully confirmed. It's essentially a webservice call from PayPal to your system. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, paypal ipn"
} |
Upload app in playstore , but my app not show in some device?
I have uploaded an app in the playstore , but my app is not showing in some device under kitkat version? how setting filter search in my app
How can I set the filter for my app so that it is visible for all devices? | You should use minimum sdk version to work on every device | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, upload"
} |
Difference between 看完 and 看到
My homework requires to fill in this blank.
A:
B:
I have 2 options that means "I finish reading half the book".
I am a bit confused because I think involves the entire book. **So, both are correct?** | “” means “I’ve finished this book”. The here suggests the subject has finished reading the entire book.
So when you say “”, it means you’ve finished reading the “entire portion of the first half”, so to speak.
When you say ””, it means you’ve read “half the book, up to the point you stopped”.
Note that doesn’t mean . If you have a 200 page book, doesn’t literally mean you’ve read 100 pages of it. It just means you have read a substantial part of the story. | stackexchange-chinese | {
"answer_score": 4,
"question_score": 3,
"tags": "meaning in context, result complement"
} |
UK Shares in Gold?
> **Possible Duplicate:**
> Investing in gold without holding physical gold
Instead of buying actual gold, bringing it into your house, then worrying about it getting stolen. Is it possible to buy shares in gold? | ETFs are a safer version oh holding gold awithout all the headache of getting robbed. ETFs traded in LSE. One more from LSE | stackexchange-money | {
"answer_score": 2,
"question_score": 0,
"tags": "investing, gold, starting out investing"
} |
Count in 'in' SQL Server
I have a problem with:
select UsersInfo.fName 'نام', UsersInfo.lName 'نام خانوادگی'
from UsersInfo
where UsersInfo.MemberID in (
select COUNT(ToLend.UserID), ToLend.UserID 'تعداد کتاب های قرض گرفته'
from ToLend
inner join UsersInfo on ToLend.UserID = UsersInfo.MemberID
group by UserID
having count(UserID) > 2
)
Error is:
> Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
In this code, how can "count" for UserID? | If you want to know which user is lended > 2, you can remove COUNT(ToLend.UserID) in subquery. And if you want to know how many times is lended you can add subquery in select
select UsersInfo.fName 'نام',
UsersInfo.lName 'نام خانوادگی',
(select COUNT(UserID)
from ToLend
where UserID = UsersInfo.MemberID
group by UserID
having count(UserID) > 2) 'Lended count'
from UsersInfo
where UsersInfo.MemberID in (
select ToLend.UserID 'تعداد کتاب های قرض گرفته'
from ToLend
inner join UsersInfo on ToLend.UserID = UsersInfo.MemberID
group by UserID
having count(UserID) > 2
) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server, sql in"
} |
Форматирование текста в Html.ActionLink
Имею вот такое меню:
<ul class="menu">
<li><a href="/"><span class="activ">пункт1</span></a></li>
<li><a href="/"><span>пункт2</span></a></li>
</ul>
Необходимо воспользоваться [@Html](/users/14007/htmlplus).ActionLink, могу так написать
<ul class="menu">
<li><a href="/"><span class="@ViewBag.ClassActive">пункт1</span></a></li>
<li>[@Html](/users/14007/htmlplus).ActionLink("Пункт1", ....)</li>
</ul>
как мне строку "Пункт1" обернуть в <span class="@ViewBag.ClassActive">пункт1</span>?
а то выводиться как обычный текст. Хотел использовать Html.Raw и new HtmlString, но тип не подходит
> преобразование типа из "System.Web.IHtmlString" в "string" невозможно | Помимо @Html.ActionLink, который формирует разметку типа `<a href="/....">пункт2</a>`, есть метод @Url.Action, который формирует только ссылку. Т.е. Вашу задачу можно решить так:
<li><a href="@Url.Action("Пункт1", ....)"><span>пункт2</span></a></li> | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, asp.net mvc, html, строки"
} |
partially update fields in a document - findAndModify remove all other fields?
When using MongoTemplate - collection.findAndModify It will delete all document fields, and leave only the updated column/s.
Why is that?
How to partially update fields in a document?
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject("phoneNumber","404-525-3928");
DBObject result = collection.findAndModify(query, update);
At this point - all fields removed from company 1...
The workaround will be to go to the DB, fetch company 1 document update the field/s and save it...,
But what if i need to update 10K of them? | You need the **`$set`** operator in the update document. You use that and other update operators here otherwise what you specify **will replace** whatever the document currently contains:
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject(
"$set", new BasicDBObject("phoneNumber","404-525-3928")
);
DBObject result = collection.findAndModify(query, update); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, mongodb, mongodb query, mongo java"
} |
iPhone real world application tutorial
Can anyone suggest to me a book, video, or website that offers instructions on building a real world application for the iPhone. I've seen many bits and pieces but I'm looking for a resource that puts it all together into one working application.
Thanks in advance | Stanford iphone class is great. There are slides, videos, sample code and good guide for a complicated project. You can view it on iTunes U < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "iphone, objective c, xcode"
} |
What causes Earth's gravity?
Why Earth is like a magnet? how can earth attract any object irrespective of what it is made of? What is the reason behind Celestial Body's gravity? i.e Sun,Jupiter,Moon etc. | Any object's mass warps the space around it towards the center of the object which causes other objects to 'fall' in towards that object or towards each other. Bigger objects have more mass therefore they warp space to higher degree causing more gravity. It doesn't matter what a substance is made of as long as it has mass. If it has mass it causes gravity. | stackexchange-astronomy | {
"answer_score": 6,
"question_score": 2,
"tags": "gravity"
} |
Return all values not within a radius
I am a new postgis user and I have a simple question. My intention is to know all point values that not have a line feature near (10 meters of tolerance) How can I do this?
I've tried to find by ST_Dwithin operator, but I need the opposite result. All line features are not within the point radius. Something similar to "not covered by..." | Just use a `NOT EXISTS ( SELECT FROM WHERE ST_DWithin() )`
SELECT *
FROM t1
WHERE NOT EXISTS (
SELECT 1
FROM t2
WHERE ST_DWithin( t1, t2, m )
);
This will return all `t1` not within `m` of `t2` | stackexchange-gis | {
"answer_score": 7,
"question_score": 5,
"tags": "postgis, sql"
} |
Textarea - required, but with default text
How can I set two attributes (default text, which hides after click and required) for textarea?
<textarea name="dedication" id="dedTextArea" required onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">Default text</textarea>
HTML "thinks" that `Default text` is my input. How Can I repair it? Thanks for all. | You used the attribute `placeholder` for the "default text which hides after click". However be aware that `placeholder` only works on browsers with HTML5 support. You are setting required correctly, it also just doesn't work on some browsers.
<textarea name="dedication" id="dedTextArea"
required
placeholder="default text"></textarea> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html"
} |
Position this div in the center of it's container?
> Before you attempt to solve this please carefully read the constraints I'm dealing with.
## Constraints
1. `.pictureContainer` needs to remain `position: relative` (because I have a hover menu that positions absolutely relative to it.)
2. The image could be smaller than 80% of `#slide` in which case it still must align in the center. What this translates to? You can't simply do a `margin: 0 10%` because yes that would center this specific case, but it will not satisfy the case where the image is smaller than 80% of the width of `#slide`
Hello, I am inline-block element that is positioned beside another inline block element, isn't that wonderful? I think that is wonderful! | Why not simply add:
text-align: center;
to pictureContainer css declaration. It will center any image in it. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "html, css, position"
} |
iOS keychain usage
I have an app that I want to make available for free - but only for a period of time ( trial period ). After this period has elapsed, user only have limited access to the app.
As I understand it, the cleanest way would be to implement a back end which stores the user installation details (that way if user install & reinstall, this info will still persist somewhere). But I also come across the concept of keychain, which seems to allow me to store arbitrary data in Apple's hosted server. So I am thinking to use this mechanism - to store the installation date for the user.
My questions : 1\. Does this violate the intention of keychain ? 2\. Can the user delete the keychain entry manually ? I think I read somewhere that user can reset their phone to delete entries.
Thanks in advance !
Regards
Alex | Not answering your main question, but I think you'll find that your first idea of a backend which tracks the install won't work, as Apple are hugely against apps being able to send any info that uniquely identifies the device.
As for the keychain, I'm fairly sure that while you could quite probably store enough data in there for your purposes, uninstalling the app will also wipe it's data from the keychain. You could possibly use iCloud to store what you need, but if the user realised that's what was happening, they could always delete your app's data from iCloud. I'd probably still go that route though. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ios, keychain"
} |
Preventing matcha deposits
I've recently started preparing matcha latte at home, I bought matcha powder and I proceed as follows:
1. Put 2 tsp of matcha powder in a cup through a sieve
2. Add 2 tsp of brown sugar
3. Add 2 tbsp of hot (below boiling) water
4. Stir the whole thing with a fork for a couple of minutes
5. Add boiling water to almost fill the cup, then add milk to taste
the result is very good but I find myself constantly stirring it to prevent it from depositing on the bottom of the cup. If I don't stir it all the time I get a very light taste at the beginning and a very strong taste at the end.
The question is: how can I prepare matcha latte so that it doesn't deposit on the bottom of my cup?
(apparently I am not able to create new tags from the mobile app, I would have used "green-tea" and "matcha") | Matcha doesn't dissolve.
It is very finely ground to be suspended in water after _very vigorous_ whisking when the preparation is done the traditional way.
A few tips for your matcha latte:
* Use good, high quality matcha. High quality matcha is bright green and a _very_ fine powder (almost like confectioner's sugar or cornstarch) - this helps keeping it suspended in liquid
* Whisk _very_ vigorously with the appropriate tools. Traditional tea ceremony uses a bamboo whisk with a lot of room in the bowl to make sure the tea is very well suspended and aerated, and the fork is _not_ the best tool for that. Use a fouet and prepare in a bowl or, if possible, use a blender (a bullet blender or immersion blender would work for small quantities). If all things fail, even a nutritional supplement shaker (the one that has a wire ball inside to help dissolve whey) would be more effective. | stackexchange-cooking | {
"answer_score": 4,
"question_score": 1,
"tags": "tea"
} |
"Wessen erinnert er sich noch?" vs. Woran oder an wen erinnert er sich noch?"
Ich lese hier und hier den Satz
> Wessen erinnert er sich noch?
es war eine Überraschung für mich, weil ich gelernt habe, dass das Verb "erinnern" ein Verb mit der Präpositionalergänzung "an+AKK" ist, also wäre der Satz
> Woran oder an wen erinnert er sich noch?
Meine Frage ist, der erste und zweite Satz haben identische Bedeutung?
Wenn ja, warum haben wir "wessen" in dem ersten Satz und nicht "woran" oder "an wen"?
Wenn nein, warum? | _Erinnern_ kann sowohl mit einem **Präpositionalobjekt** als auch mit dem **Genitiv** verwendet werden. Letzteres wird aber meist nur bei gehobener Ausdrucksweise genutzt. Der Genitiv wird generell in der Sprache durch die anderen beiden Fälle (v.a. den Dativ) verdrängt.
Also ja, beide Fragesätze haben die gleiche Bedeutung, unterscheiden sich aber im _Stil_. | stackexchange-german | {
"answer_score": 9,
"question_score": 10,
"tags": "phrase, pronoun"
} |
Pumping lemma for language that is regular
I am trying to show how the pumping lemma applies to a language that is for sure regular. I have the language over {0, 1} that has an even number of 1's. This language can be represented by a DFA that has two states.
So the pumping length here is 2, correct? The pumping lemma states that "if s is **any string** in A of length at least p," then it may be divided into xyz such that the 3 PL conditions are true. So say we choose a string '000110' and want to show that _somehow_ it can be split into xyz such that |xy| <= p (and |y| > 0, and x(y^i)z is in L).
In this case y would have to be '11' so that it can be repeated and still be even... which would make x = '000', right? This would then make |xy| = 5, which is more than p.
I don't see any other way of splitting the given string so that |xy| < p. What am I missing here? Thanks very much. | @Jim Lewis provided the answer to my question - we can have x = empty string, y = '0' and a z of '00110', which will enabled us to pump y as much (or as little) as we want, satisfying the requirements of the pumping lemma. Thanks! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "pumping lemma"
} |
PHP recursive function not returning expected
I have the following code:
use app\models\Kategorije;
function hasMoreParent($id,$i = 0){
$model = new Kategorije();
$parent_id = $model::find()->where('id = :id',[':id' => $id])->one()->parent_id;
if ($parent_id > 1) {
$i++;
hasMoreParent($parent_id,$i);
}
return $i;
}
And, if $i is greater than 0 it always returns 1 instead of 2 or 3.. How can I make it to return those other numbers? | You are missing the return keyword in order to achieve the recursion, otherwise the function `hasMoreParent` will be executed, but the flow will continue and reach the `return $i;` statement.
use app\models\Kategorije;
function hasMoreParent($id, $i = 0) {
$model = new Kategorije();
$parent_id = $model::find()->where('id = :id', [':id' = > $id])->one()->parent_id;
if ($parent_id > 1) {
$i++;
return hasMoreParent($parent_id, $i);
}
return $i;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php"
} |
Char to Int explicit Conversion in C#
I was trying to learn explicit conversion in c#.
First I explicitly converted `string` to `int`
namespace MyfirstCSharpCode
{
class Program
{
static void Main(string[] args)
{
string str = "1234";
int i = Convert.ToInt16(str);
Console.WriteLine(i);
}
}
}
it worked and the result is : `1234`
Now I tried to convert `char` to `int`
namespace MyfirstCSharpCode
{
class Program
{
static void Main(string[] args)
{
char str = '1';
int i = Convert.ToInt16(str);
Console.WriteLine(i);
}
}
}
And now the result is `49`, the ASCII value of `1`. How to get the char `1` instead of ASCII value. Please don't be too harsh its my first day in c# ;).. | You hit the overload methods of `Conver.ToInt16(char)` , and `char` is a UTF-16 code unit and representing 1 is 49. You can use `Int16.TryParse` to safe parse the number (need in 16 bit sign number) in order to get the valid integer.
string str = "1"; // use string if your number e.g 122
short number; // convert to 16 bit signed integer equivalent.
if (Int16.TryParse(str, out number))
{
Console.WriteLine(number);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, explicit conversion"
} |
shift mouse click trigger
I can trigger click event on `element selector` using `trigger`
$('element selector').trigger('click')
Is it possible to trigger shift click. I mean `shift` \+ left mouse click. | try
var shiftClick = jQuery.Event("click");
shiftClick.shiftKey = true;
$("element selector").click(function(event) {
if (event.shiftKey) {
alert("Shift key is pressed");
}
else {
alert('No shift hey');
}
});
$("element selector").trigger(shiftClick);
**JSFiddle** | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 12,
"tags": "javascript, jquery, keyboard events"
} |
suspect message "sshd-keygen-wrapper would like to receive keystrokes from any application"
I am receiving this message about "sshd-keygen-wrapper would like to receive keystrokes from any application", here is a screenshot:
 | This happens when you run something _(apps/binaries/scripts etc.)_ needing Accessibility Permissions while in an SSH session on that machine.
You can reproduce this in the following way:
1. Make sure to remove `sshd-keygen-wrapper` from the Accessibility list so it is allowed to ask again for permissions
*  {
document.getElementById("cantseeme").style.display='block'; // Show it
}
</script>
</head>
<body onload="showHidden();">
<div id="cantseeme" style="display:none;">Hidden element</div>
</body>
</html> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.