INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Is it possible to update my graphic card drivers?
This is what the lspci -v command shows in the VGA compatible controller section:
00:02.0 VGA compatible controller: Intel Corporation Atom Processor D4xx/D5xx/N4xx/N5xx Integrated Graphics Controller (prog-if 00 [VGA controller])
Subsystem: Dell Device 048e
Flags: bus master, fast devsel, latency 0, IRQ 44
Memory at f0200000 (32-bit, non-prefetchable) [size=512K]
I/O ports at 18d0 [size=8]
Memory at d0000000 (32-bit, prefetchable) [size=256M]
Memory at f0000000 (32-bit, non-prefetchable) [size=1M]
Expansion ROM at <unassigned> [disabled]
Capabilities: <access denied>
Kernel driver in use: i915
Kernel modules: i915
i915 is only compatible with OpenGL 1.4 and cannot use shaders and I'd like to use some Open GL 2.0 functionalities.
Is it possible to update the drivers or is my hardware limited to OpenGL 1.4 ? | Intel has not additional drivers (restricted drivers) available for Linux. The drivers are all open source.
If you want to update the driver for Intel graphics card you can add a PPA where the newest drivers included and update from there.
Example . Ubuntu X - Team
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get dist-upgrade
If you want to revert back (undo)
sudo apt-get install ppa-purge
sudo ppa-purge ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get dist-upgrade | stackexchange-askubuntu | {
"answer_score": 4,
"question_score": 4,
"tags": "drivers, intel graphics, opengl"
} |
"Пока" - это наречие или союз?
> Дорога вела вправо, но я по совету незнакомца продолжал идти по тропинке, **пока** не натолкнулся на изгородь.
**_"Пока"_** в данном предложении является союзом или наречием? Как определить? | Это предложение по своей структуре ближе **к сложному предложению** , а не предложению с однородными сказуемыми, так как сказуемые расположены не компактно, имеют разную грамматическую форму, ПОКА НЕ относится ко второму сказуемому.
**Поэтому ПОКА НЕ ― это союз в сложноподчиненном предложении** с придаточным времени, для проверки можно сделать замену:
Дорога вела вправо, но я по совету незнакомца продолжал идти по тропинке, **(до тех пор) пока (я) не натолкнулся на изгородь.** | stackexchange-rus | {
"answer_score": 2,
"question_score": 2,
"tags": "морфология, части речи, союзы, наречия"
} |
preg_match: Get the content of a div with spaces in the class name
I cant get the right code and I believe its because of the spaces in the class name:
<div class="post entry-content mess ">
Please notice the double space before "mess" and the space at the end. I cant change those. I want to get the contents of only the first div with that class. this is my code:
preg_match('/<div class=\"post entry\-content mess \">(.*?)<\/div>/s', $bitch, $match );
Where is the error?
Thank you. | You can get that match to work regardless how many spaces are between class names using the following regular expression:
/<div[^>]*class=\'\s*post\s+entry\-content\s+mensaje\s*\'[^>]*>(.*)<\/div>/smU | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "regex, preg match"
} |
adding bullets to header tag in orchard
I created list in orchard and the h1 tag takes the title of the list. I need to add a bullet for the header.
I need bullet before the h1 tag like the below image
!enter image description here
<
<header>
<h1>School info</h1>
</header>
I used the background:image property, but its not displaying the bullet. how can I get the bullets? | Try:
h1:before {
background-image: url(
background-repeat: no-repeat;
background-size: 20px;
width: 20px;
height: 20px;
display: inline-block;
content:"";
vertical-align: middle;
}
**Updated fiddle here.** | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "html, css, orchardcms"
} |
Application of name lookup to just declared name
int a;//1
int main()
{
int a;//2
}
As said in 3.4/1:
> The name lookup rules apply uniformly to all names (including typedef-names (7.1.3), namespace-names (7.3), and class-names (9.1))
Thus, for `//2` declaration name lookup will be applied. What name will be found? | > What name will be found?
The only thing possibly looked at will be the _declarative region_ , to check whether `a` is not redeclared invalidly. Obviously nothing will be found.
Moreover, there is no such thing as (unqualified) name lookup done while declaring names, rather when using them. The standard says nothing about unqualified name lookup for names being declared, rather for names used in specific contexts, such as a name as a postfix-expression for a function call. In particular, names being declared have to satisfy certain conditions, whether they are local, in class or in namespace scope; it is beyound this post to list them all up. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c++, declaration"
} |
bash if statement troubles [Error==Error]: not found
Everytime I run my script the following if statement gives me the error;
script.sh: [Error==Error]: not found
or
script.sh: [Error==-2]: not found
if ["$P1"=="$P2"];then
echo $name
fi
I've tried other versions
if ["$P1"=="$P2"]
then
echo $name
fi
and
if [[ "$P1" == "$P2" ]]
then
echo $name
fi
P1="Error"
P2="$(sed -n '1p' somefile.txt)"
`somefile.txt` might contain a number or a string | Spaces are significant. Use:
if [ "$P1" = "$P2" ]
### What went wrong
When the shell sees `["$P1"=="$P2"]`, it interprets it as a single word and looks for a command that matches that word. Since no such command exists, you get the `not found` error message. | stackexchange-unix | {
"answer_score": 8,
"question_score": 2,
"tags": "bash"
} |
In Server Images are not responding in rails3
I am having issue that with this alias when I am pointing to a server at that time images are not showing. My configuration of server for the application is
Alias /questions /app/xyz/public
PassengerRuby /usr/local/rvm/wrappers/ruby-1.9.3-p327@abcd/ruby
#RailsBaseURI /beingme
RailsBaseURI /questions
<Directory /app/xyz/public>
RailsEnv production
Options Indexes FollowSymLinks -MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
Please provide me the solutions. | You have to define one more Alias for assets
Alias /assets /app/xyz/public/assets
It will work for you, I hope. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby on rails 3, apache, passenger"
} |
BreezeJS/Query - Predicate on expanded field issue
var p1 = breeze.Predicate.create("Status", "==", 3);
var p2 = breeze.Predicate.create("Client/Status", "==", 1);
var p = breeze.Predicate.and([p1, p2]);
In the above code, the final predicate p gets converted as:
(Status eq 3) and (Client/Status eq '1')
when it is viewed in Fiddler/Web inspector xhr view.
Why is the integer number 1 is considered as string ('1') when a predicate is created on an expanded entity's field ("Client/Status", see predicate p2). This causes the http request to fail as a bad request.
The same kind of predicate is constructed correctly on a first level field ("Status", see predicate p1).
Note: This request works fine when I go to Fiddler, remove the single quotes around the value 1 and execute. | I think the issue is that you need to use a dots '.' to separate the parts of the path instead of a '/'. i.e.
var p2 = breeze.Predicate.create("Client.Status", "==", 1);
The reason that you are seeing 'Client/Status' interpreted as a string is that breeze defaults values to strings when it is unable to determine the actual datatype of the field. It determines the datatype by navigating the path and determining the datatype of each segment via metadata.
Hope this helps. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "breeze"
} |
How to run javascript after jquery and dom has finished loading in c#?
In my asp.net/c# solution, I am loading the jquery library with this
<SharePoint:ScriptLink ID="jquery_js" name="/_layouts/PDF Library/jquery-1.10.1.min.js" runat="server" OnDemand="False" Localizable="False" />
Now, in c# code, how can I insert javascript, that will only run when the jquery library is done loading and the dom is finished loading too. I can insert javascript like this:
ScriptManager.RegisterStartupScript(someControl, typeof(string), "AutoComplete", js_call, true);
Thanks. | $(window).load(function(){
//this will run after dom is loaded
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, jquery, html, asp.net, sharepoint 2010"
} |
Converting a string into a multi-dimensional array with commas and pipes
Tried searching but nothing was exactly what I was looking for.
I have a string that looks like this:
$string = "sku1,2|sku2,5";
I would like to convert it into a multi-dimensional array that would end up looking like this:
Array
(
[0] => Array
(
[sku] => sku1
[qty] => 2
)
[1] => Array
(
[sku] => sku2
[qty] => 5
)
)
So far I've tried using:
explode(',',$string);
Which is the right idea but it doesn't account for the pipe delimiter to know when to go to the next array group. | I wouldn't even bother with looking for `|` or manually traversing anything. You can generate the desired array already with `preg_match_all` containing just a few fillers:
preg_match_all(
"/(?<sku>\w+),(?<qty>\d+)\K/",
$string, $array, PREG_SET_ORDER
);
This simply extracts any combination of alphanumeric `\w+` and numeric `\d+` entries delimited by `,` comma. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays, string, multidimensional array"
} |
How to add configure event for zip file in AWS
How to add `configure event` if we are uploading as zip
 of area i.e. plot of garden bed.
2. "Plot" _in Mathematics_ refers to a graph of several coordinates
So, to sum up, Plotting cannot be used in place of Area, _in mathematics_ because it causes confusion.
Notice I keep on emphasising _in mathematics_. This is because, in normal usage, "area" and "plot" are _sometimes_ interchangeable. But absolutely _not_ in mathematics. | stackexchange-english | {
"answer_score": 4,
"question_score": 2,
"tags": "terminology, mathematics"
} |
Easiest way to convert a List to a Set in Java
What is the easiest way to convert a `List` to a `Set` in Java? | Set<Foo> foo = new HashSet<Foo>(myList); | stackexchange-stackoverflow | {
"answer_score": 1214,
"question_score": 753,
"tags": "java, collections"
} |
When OnPrem with Kubernetes, what is the recommended way to do file storage buckets?
When you are running kubernetes on GKS, AKS, etc, you use your cloud provider specific storage bucket such as Amazon S3, google cloud storage, azure blob storage, to store your raw binary content in a super fast, easy to use manner.
But when you are deploying Kubernetes behind the firewall, you do not have a storage bucket SDK from your cloud provider.
What is the alternative to this when you are using, for example, OpenShift? Do we have to just use persistent volumes? | You have many, many options. The following all provide an S3-compatible object storage API:
* If you are using OpenShift, you can install OpenShift Data Foundation, which includes the Noobaa object storage service. This provides `ObjectBucket` and `ObjectBucketClaim` resources that are analgous to `PersistentVolume` and `PersistentVolumeClaim` resources.
* You could run MinIO, which can be deployed on Kubernetes via an operator or a helm chart.
* You can run your own Ceph cluster, which includes the object gateway.
* You could run OpenStack Swift. | stackexchange-devops | {
"answer_score": 1,
"question_score": 0,
"tags": "kubernetes, amazon s3, storage, google cloud storage"
} |
Trigger state change in model from another model
New to rails and learning how to use state machines. How would I make the fans of an actor, whose state is crying, change to the same crying state?
class Actor < ApplicationRecord
include AASM
has_many :fans
aasm do
state :laughing, :initial => true
state :crying
event :cry do
transitions :from => :laughing, :to => :crying
end
event :laugh do
transitions :from => :crying, :to => :laughing
end
end
end
class Fan < ApplicationRecord
include AASM
belongs_to :author
aasm do
state :laughing, :initial => true
state :crying
event :cry do
transitions :from => :laughing, :to => :crying
end
event :laugh do
transitions :from => :crying, :to => :laughing
end
end
end | You can use lifecycle callbacks to trigger further methods on an actor:
class Actor < ApplicationRecord
include AASM
has_many :fans
aasm do
state :laughing, :initial => true
state :crying, :success => :fans_cry_too
# ...
end
private
def fans_cry_too
fans.each(&:cry)
end
end | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "ruby on rails, ruby"
} |
Mercurial: Creating a diff of two commits
Is there a way to get the changes of two commits with mercurial? The second commit is not directly after the first one, there are some other ones between them.
I tried
hg diff [some params] --change xxxxx --change yyyyy > file.patch
but that only includes the last changeset.
If there is no way to achieve this with hg, is there maybe a tool to combine patches? | I came upon this page while trying to figure this very thing out. I found my solution via `hg help diff` .
`hg diff -r <rev> -r <rev>` worked for my needs (diffing between two tags) | stackexchange-stackoverflow | {
"answer_score": 57,
"question_score": 37,
"tags": "mercurial, diff"
} |
How do I italicize words in an entry title?
I'm working on a site with a "Research" channel that is going to have scientific names in the titles of the entries.
What's the best way to allow these names to be marked up with `<em>` tags so I can display them in italics?
Right now I'm using the default "Title" field Craft supplies when you set up a section, but I haven't needed to insert formatting here before. | I'd also suggest to enter the titles with markdown formatting. But instead of using the Craft built-in `markdown` filter, I'd suggest to look into the parsedown plugin provided by P+T. The plugin has an option for single line output, so you won't end up with your title wrapped in `<p>` tags.
<h1>{{ entry.title|parsedown('line') }}</h1> | stackexchange-craftcms | {
"answer_score": 1,
"question_score": 3,
"tags": "titles"
} |
Alternative to Actioncable in rails 4.2
I want to know which is the best alternative to develop Websockets in rails 4.2 since actioncable is only available for rails 5 | I'm Plezi's author, which leverages Iodine's implementation of the Rack Websocket draft, making it easy to use Websockets with Ruby applications.
Plezi can be used as middleware within Rails, so you can get the best of both worlds. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "ruby on rails, actioncable"
} |
Eclipse not picking up Android Support Library
I'm getting this : !enter image description here
and I'm not sure if the red tick marks in SDK Manager are related :
!enter image description here
I have the files and they appear to be in the correct locations :
!enter image description here
And my SDK location appears correct :
!enter image description here | Try importing v7/appcompat as a library project to Eclipse and then add to your project.
Library project is at following path:
sdk/extras/android/support/v7/appcompat
Also take a look at how to use this recently updated library for supporting ActionBar on older versions. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, android, eclipse, adt"
} |
Python module changes aren't being imported
I've got a python sub-project referencing a module in a higher directory:
/
misc/
subproject/
main2.py
project/
__init__.py
main1.py
To run main2 I `cd` to the `subproject/` directory and run
PYTHONPATH=../.. main2.py
In main2 I'm trying to use new functions that I've written into main1, but I'm getting an
AttributeError ('module' object has no attribute 'function name').
Running `dir(main1)` after the import shows me that none of the functions I added are present in the module; I commented out the entire file and tried importing it, but `dir(main1)` showed all the old top-level declarations, with none of them removed. This made me think it's a caching problem, even though I've cleared any `*.pyc` files I can find. | I had installed the main1 project, so even though I had set my PYTHONPATH to include the current version of the main1 project, the installed version was what was getting imported, and so shadowing the updates I was making to the code.
Thanks to Martijn Pieters for pointing me to using `print main1.__file__` to see what actual file the main1 module was being imported from. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, import, module"
} |
Sharing a type with a generic class?
How do you declare a variable to be the same type as a type parameter used to instantiate a generic class? The following code does not compile:
class
TEST [G, H -> INTEGER]
feature
f (i: INDEXABLE [G, H])
local
y: H
do
y := i.lower -- Type error here.
end
end
The compiler says that the _source of the assignment is not compatible with target_. | In the current implementation, `INDEXABLE [G, H]` inherits from `TABLE [G, INTEGER]`. As a result, `lower` is of type `INTEGER`, not `H`. And `INTEGER` does not conform to the formal generic type `H` of the class `TEST`. This explains the error.
To me, it looks like a mistake in the declaration of class `INDEXABLE`. It should inherit from `TABLE [G, H]` instead. Then, the example code would compile. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "generic programming, eiffel"
} |
How can i see the SQL Server queries coming from my program?
I have this c# web app that relies heavily on two dll files that i can't see nor edit. The rest of the app is visible and editable.
The app generates SQL exceptions, and i would like to see the queries sent from the DLLs. Is there a way to do that? | You can use SQL Profiler to see the queries that goes to your database. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 3,
"tags": "sql, sql server"
} |
Improved python interpreter
I'm looking for a python interpreter, it can be command line, or have a GUI, I don't really care (or an emacs plugin, would work also, actually).
What I'm looking for is real-time text-highlighting, and backwards search through previous lines. Most interpreter/shells have up-arrow, so you can scroll through previous commands, I'd like to be able to search backwards, like in bash, for example. Additional features would be great, but those are the two that I'm really annoyed by the lack of.
I'm on a mac, but I have coworkers on Windows, so either would be appreciated. | Have you considered using IPython? It is an interactive shell with lots of powerful features like syntax highlighting and history. It works on all major platforms.
If you have problems with installation on Mac/Windows, try Anaconda or similar Python distributions - made to get up running quickly. | stackexchange-softwarerecs | {
"answer_score": 3,
"question_score": 1,
"tags": "windows, osx, python"
} |
PHP - if echo $_GET['q']; empty add this TEXT
this is my code
amzn_assoc_default_search_phrase = "<?php error_reporting(0); echo $_GET['q'];?>";
and if `$_GET['q']` is empty, add my text example: `perfume` how i can do this ?
Thank you. I hope i get help this time. | First off, don't turn `error_reporting()` off. That's a bad idea since it will be pretty hard for you to debug your code later on if there are other errors/issues.
If you're using a PHP version older than PHP 7, you can use isset():
<?= isset($_GET['q']) ? $_GET['q'] : 'perfume' ?>
If you're using PHP 7+, you can use the new shorter null coalescing operator (`??`) syntax that does the same:
<?= $_GET['q'] ?? 'perfume' ?> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php"
} |
highlight words in php and return part that contains highlighted words
I am creating a search engine for my web app. Now I want to highlight the results found for user search request. I have the following function:
function highlight($text, $words) {
foreach ($words as $word) {
$word = preg_quote($word);
$text = preg_replace("/\b($word)\b/i", '<span class="highlighted">\1</span>', $text);
}
return $text;
}
It is working well but I don't want the whole text to appear in search results page, because it can be thounds of lines of text, so I want to show only part of it that has highlighted words. | What about this solution? It uses `preg_match_all()` to get all occurrences of the word and displays max 10 characters left or right of it but highlights only the matched word
$text = <<<EOF
hello_world sdfsdf
sd fsdfdsf hello_world
hello_world
safdsa
EOF;
$word = preg_quote('hello_world');
$text = preg_match_all("~\b(.{0,10})($word)(.{0,10})\b~is", $text, $matches);
for($i = 0; $i < count($matches[0]); $i++) {
echo '<p>'
. $matches[1][$i]
. '<span class="hl">'
. $matches[2][$i]
. '</span>'
. $matches[3][$i]
. '</p>';
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, search, replace, search engine, highlight"
} |
como crear una vista de una tabla diferente a otra base de datos?
Quisiera utilizar los datos de una tabla diferente en otra BD en la misma instancia, como hago para crear un vista para poder manejar dichos datos? gracias
estoy usando el ejemplo de que me mando el primer user y no me funciona
SELECT * FROM [NOMBRE BASE DE DATOS].[dbo].[NOMBRE DE LA TABLA]
 application.
ILabelDecorator decorator = PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator("MyPlug-In-Id");
TableDecoratingLabelProvider lp = new TableDecoratingLabelProvider(new LabelProvider(), decorator);
structuredViewer.setLabelProvider(new DecoratingLabelProvider(lp, decorator));
Unfortunately, `PlatformUI.getWorkbench()` throws an `IllegalStateException: Workbench has not been created yet.` on e4. As I understand, this is intended as this method is only valid in e3. But then, how to display item decorations in e4?
Any help is really appreciated, thank you in advance! | You can't do this in an e4 application. The 3.x workbench is not available in an e4 application and the `org.eclipse.ui.decorators` label decorator extension point is not supported.
You can JFace decorator classes such as `DecoratingLabelProvider` and `DecoratingStyledCellLabelProvider` but you will have to rework the decorators to use `ILabelDecorator`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "eclipse, eclipse plugin, e4, emf"
} |
Setting nano cursor using mouse via putty doesn't work if sudo
I needed to be able to set the cursor using mouse when editing text via `nano` over `putty`. I have already set the below in `~/.nanorc`:
set mouse
If I start `nano file` just like that then it works, but if I require elevated rights and `sudo nano file` then it's not. How on earth is that possible? I suppose in that case `nano` is using another `.nanorc`? | > I suppose in that case nano is using another .nanorc?
Yep. When you run `sudo nano file`, `HOME` environment variable is set to `/root`, so `nano` looks for `.nanorc` there.
Just add the setting into `/root/.nanorc`, and you should be fine. | stackexchange-unix | {
"answer_score": 2,
"question_score": 1,
"tags": "sudo, nano"
} |
How can I get the user's username?
I know that I can do `getpass.getuser()` but that shows the user's name, not their account logon username and I want their account logon username | Try this one:
**For Unix**
import os
import pwd
pwd.getpwduid(os.getuid())[0]
**For Windows**
import os
os.getlogin() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, python 3.x, user accounts"
} |
approving application in marketplace that reloads data instead of tombstoning it
I have an application in which i have listboxes,textboxes, etc. I load data in `OnNavigatedTo` so when i come from tombstoning, my data is reloaded.
Is this a problem in app submission? Must i necesarally save the state of the app or is it correct to reload the data (i reload from my database) ?
What is actually tested in the application submission process? The app itself or is my code actually verified? | How you reload your apps state will not affect certification. Your app will go through some automated testing and will be checked for calls to unmanaged code etc. but the actual code/logic will only be tested against the Windows Phone 7 Certification Requirements. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "windows phone 7"
} |
Which clustering algorithms can be used with Word Mover's Distance from M. Kusner's paper?
I am new to machine learning and now I am interested in document clustering (short texts with different lengths) according to their semantic similarity (I just want to go beyond the standard TF/IDF approach). I read the paper < where the Word Mover's distance for word embeddings is explained. In the paper they used it for classification. My question is now - can I use it for clustering? If so, is there a paper where this kind of usage is discribed?
P.S.: I am basically interested in clustering which takes into account the semantic similarity, so even a word2vec or doc2vec approach will do the job - I just couldn't find any papers where they are used in a clustering problem. | If you could afford to compute an entire distance matrix, then you could do hierarchical clustering, for example.
It's easy today find other clusterings that accept any distance and use a threshold. These could even use the bounds for performance. But it's not obvious that they will work on such data. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "cluster analysis, similarity, unsupervised learning"
} |
PHP - refex find from to and replace
I have an **img** tag with the src which looks like this:
src="
The part **< is dynamic and will be changed depending on servers address, and **/assets/img/resources/someimage** will not be a subject to the change. I need to replace that part (everything to the **/assets** ) with a dot. How can I do this? | You can use:
$repl = preg_replace('~^.+?/assets(/img/resources/someimage)$~', '.$1', $input);
//=> ./img/resources/singature.png
`^.+?/assets/` will match 1 or more characters before `/assets/`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, regex, preg replace"
} |
Maximum number of PasswordCredential in PasswordVault UWP
I didn't find any information on the online documentation that provide the allowed number of PasswordCredential Object that can be stored in Windows PasswordVault. Anyone has an idea ? | According to the **Remarks** of PasswordVault.Add | add method
> You can only store up to ten credentials per app in the Credential Locker. If you try to store more than ten credentials, you will encounter an Exception.
So the maximum number of `PasswordCredential` in `PasswordVault` is **10**. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": ".net, windows store apps, win universal app"
} |
CSS - which code renders faster and is more efficient?
I would like to know which of below codes renders faster and is more efficient:
This -
body{background:#ddd;font-family:verdana;font-size:12px;color:#808080;}
a{color:#808080;outline:0;text-decoration:none;}
input{margin:0;padding:0;font-family:verdana;color:#808080;}
ul{padding:0;margin:0;}
Or this -
body,input{font-family:verdana}
body,input,a{color:#808080;}
body{background:#ddd;;font-size:12px;}
a{outline:0;text-decoration:none;}
input,ul{margin:0;padding:0;} | Efficiency is irrelevant here.
Go with whichever is easier to read/understand/maintain, which is clearly the first snippet.
However, that second snippet looks like it's been minified, which is a good thing to do, because it reduces the transfer size of the CSS - it doesn't improve the "rendering speed".
You should write your CSS in the most understandable way, then generate a minified version when you put it live. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "css, performance"
} |
Is the audioTracks element available on the Chromecast?
I'm trying to test mp4 videos with multiple audio tracks on the Chromecast but `audioTracks` appears to be missing from the `video` element. Is there some way for me to switch audio tracks on mp4 videos? | If you look on the Release Notes of Google Cast, it seems that audioTracks is not yet supported on the Cast API. This related SO question also ask about audioTrack on chromecast, but the owner of the question found out that it is not yet supported. For more information, you can check this Media Player Library and Audio Device that is currently or only available for the Cast API. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "chromecast, google cast"
} |
Generating multiple rows from a single row, based on the number in the cell next to it
This SQL question explains exactly what I would like to achieve in Google Sheets.
Would it be possible to create some automation in Google sheet, that read through the sheet, and changes single rows into multiple rows, based on the number in the cell next to it? | I'm not sure if you want the exact example in your link, with dates?
But anyway, here is a formula version of it:
=ArrayFormula(if(row(C2:C)<sum(C2:C)+2,
eomonth(vlookup(row(C2:C)-2,{sumif(row(C2:C),"<="&row(C2:C),C2:C)-C2:C,B2:B},2,true)
,row(C2:C)-3-vlookup(row(C2:C)-2,sumif(row(C2:C),"<="&row(C2:C),C2:C)-C2:C,1,true))+1,""))
And to get the amount
=ArrayFormula(vlookup(row(C2:C)-2,{sumif(row(C2:C),"<="&row(C2:C),C2:C)-C2:C,E2:E},2,true))
:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
withView:(UIView *)view
atScale:(float)scale {
view.contentScaleFactor = scale * [UIScreen mainScreen].scale;
}
You _might_ also have to tell the view that it needs redrawing, but try it without first and see what happens. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, uiscrollview, drawrect, uibezierpath"
} |
Protection of variable from concurrent access
I am writing a REST API. In this API I am using a bearer token. This token has a longer expiry time. i.e., several minutes and should be reused until it expires. My REST API may get called concurently from several clients. Whenver, the totken is close to expiry, I need to generate again and store it in a global variable.
Requirement is to delay a function call or fail, when token is being generated. I came across the following topic. Wanted to know whether there is a better method something like mutex in C.
Currency HTTP Requests
Here is my pseduo code:
// lock
if (isset($this->token) == false || ($this->token_expiry_time - time()) < 60) {
$this->token = $this->generateToken()
}
// unlock
//use token | I suggest you check the Magento API response when you have performed your request. Specifically, you try your API call with an expired token on purpose: the exception message will be useful.
On my local today, I did alter the token to trick my API call to return an error. My error is: `{"message":"The consumer isn't authorized to access %resources."`..
Once you know the exact message given when an expired token is used, then you can re-authenticate doing like the code below:
$token = $this->getSessionToken();
$response = $this->sendAPICall($token);
$result = $response->getBody();
$result = json_decode($result);
if (strpos($result->message, 'The consumer isn\'t authorized to access') !== false) {
$token = $this->renewSessionToken();
... rebuild the API request
$response = $this->sendAPICall($token);
$result = $response->getBody();
} | stackexchange-magento | {
"answer_score": 0,
"question_score": 0,
"tags": "magento2.3, php 7.2"
} |
Are "Extensions" something that disappeared many Mac OS versions ago?
On a sheet of Mac keyboard shortcuts for booting, one of them says, "hold down shift while booting and the computer will not load login items or extensions".
Am I wrong, or are Mac OS "extensions" something that were phased out a long time ago? (In other words, with OS X Lion, the shift key simply cancels loading the login items, period?)
Note that, of course, I know that "extensions" has meaning in other apps -- Firefox, Safari, Thunderbird, etc. But please confirm my Mac OS X suspicion as I describe it above.
(Yep, I know this is related to my other question. Getting this answer clear will allow me to resolve both questions clearly and designate their correct answers.) | Your expectation that extensions are only a thing of the past is incorrect.
Modern Mac OS X uses kernel extensions, which are not identical to the "old school" extensions used in Mac OS 9 and earlier, but yes, there are still such a thing as extensions. You can find them in `/System/Library/Extensions`.
Apple expands on this in this support document about Safe Mode. | stackexchange-apple | {
"answer_score": 6,
"question_score": 1,
"tags": "boot, login, safe mode"
} |
Tagging versions in github repository
I would like to set a tag in my github repository to a specific commit.
I have a development pc which is making the commits to the repositories, and i have a server where i just pulling the changes.
In the server i set a tag to specific commit:
git tag -a v0.1.0 56886a
I would like to set that tag to my github repository without overwriting or merging any code or files in the repository. Keep in mind in that server i don't want to push or commit anything, just tag. How can i do that? | You push tags with `git push --tags`. If you don't want to push from the server you need to tag from your dev machine (which IMO is what you should be doing anyway) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "git, github"
} |
Rails SEO friendly URL
I got long brake from RoR and have some problem:
I have this URL:
How can I change "?" for params on "/" ?
This URL is created by:
<%= link_to f.title, blog_post_path( :tit => f.slug ) %></div>
Or how can I make most SEO friendly URL - I already use friendly_id gem | Add a route to your `routes.rb` file which includes the `tit` paramter directly in the path.
For example:
Rails.application.routes.draw do
get 'post/:tit' => 'posts#show', as: :blog_post
end
Of course you have to adjust the routes to your needs.
Just have a short look into this question. It doesn't matter if you have parameters in the URL anymore. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails"
} |
Direct vs uniform initialization in std::allocator
> This question has also been submitted to Usenet, where it is more appropriate, but this is a larger and more reliable forum.
`std::allocator::construct` is defined to forward its argument parameter pack to object construction using parentheses, a.k.a. direct-initialization.
If it used braces, a.k.a. uniform initialization, we could initialize aggregate data types from functions such as `std::make_shared` and `container::emplace`. Also, it would be acceptable to put the contents of an initializer list into the argument list of such a function, solving the problem of `initializer_list` type deduction under forwarding.
Was this alternative considered and rejected? Is it too late to switch in a future standard? It seems this would be a breaking change, but not a particularly heinous one. | I don't know what the SC considered, but keep in mind that uniform initialization doesn't really 'work' in generic contexts (barring value construction*). Consider this attempt:
template<typename T, typename... Args>
T
make(Args&&... args)
{
return T { std::forward<Args>(args)... };
}
You get:
assert( make<std::vector<int>>(10, 0).size() == 2 );
assert( std::vector<int>(10, 0).size() == 10 );
and this doesn't compile:
make<std::vector<int*>>(10u, 0);
whereas this does:
std::vector<int*>(10u, 0);
If the particular interaction between perfect forwarding and initializer lists that causes this was formalized soon enough I could see the SC not wanting to restart from scratch.
(*): `T {}` is fine even in generic contexts. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 8,
"tags": "c++, c++11, uniform initialization"
} |
Understanding this proof for $\sin(a+b)=\sin(a)\cos(b)+\sin(b)\cos(a)$ from Gelfand
We would like to have a small question concerning this proof for $\sin(a+b)=\sin(a)\cos(b)+\sin(b)\cos(a)$ from Gelfand's Trigonometry
.
**Only limitation:** Make sure both monitors have same resolutions and refresh rate.
!alt text | stackexchange-superuser | {
"answer_score": 2,
"question_score": 2,
"tags": "display"
} |
use of **and** operator within an **if statement**
I was directed to this website by a friend.
I am trying to use `and` in Delphi, but I seem to be doing something wrong. Is there something you need to put in uses?
I have the following code:
procedure TForm1.Button1Click(Sender: TObject);
var
a,b:string;
begin
a:=edit1.Text;
b:=edit2.Text;
if a=abc and b=def then
showmessage(a+b);
end;
I get an error at the second = sign | You have to put some parentheses to change the operator precedence:
if (a=abc) and (b=def) then
Operator `and` precedes `=` so the construction without parenthesis is understood as `a=(abc and b=def)` which produces the syntax error. | stackexchange-stackoverflow | {
"answer_score": 34,
"question_score": 6,
"tags": "delphi, if statement, and operator"
} |
How are thermodynamics properties of gases and liquids calculated numerically?
I was wondering how the values of thermodynamic properties as enthalpy, entropy, internal energy, specific heat, specific volumes ... etc, of gases and liquids are calculated using programming libraries such as `cantera` and `thermopy` as an example.
How are steam tables made for instance? How do we get all these values of properties if not experimentally? | The answer is using a thermodynamic equation of state (EOS). An EOS is one that relates the free energy of a substance to its physical properties (temperature and density for example). Once such an equation is developed all other thermodynamic properties can be derived from them (via thermodynamic relationships). To see an example for water, checkout the The International Association for the Properties of Water and Steam website (< Here they have their latest release on water properties: <
Now water is the most common and most used substance so the model is very detailed with a lot of parameters so as to match experimental conditions almost perfectly. Other substances are typically correlated with more general EOSs. A thermodynamics textbook would be a good place to learn more.
By the way, you are probably familiar with the most famous of these equations. The ideal gas equation of state is useful for the prediction of the thermodynamic properties for gases at low pressures. | stackexchange-engineering | {
"answer_score": 4,
"question_score": 6,
"tags": "mechanical engineering, thermodynamics, numerical methods"
} |
Random Color Strings
First, this is not a duplicate of: Generate random string/characters in JavaScript
I specifically want a string to change to random colours starting on green. I am writing in JS
function changeColor()
{
var change;
for( var i=0; i < 11; i++ )
{
change += script.charAt(Math.floor(Math.random() //Input ur suggestion here, I suspect it is the script variable and different colours
script = document.getElementById('txt');
script.style.color = "#33cc33";
}
} | The for loop completes right away, you need a timeout to actually see the color change, and a random color generator to generate the colors, then throw in a recursive IIFE and you're there :
var color = '#33cc33',
elem = document.getElementById('txt');
(function fn() {
elem.style.color = color;
setTimeout(function() {
color = '#'+Math.floor(Math.random()*16777215).toString(16);
fn();
}, 500);
})();
**FIDDLE** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
Neo4j query shows 3 copies of subgraph in browser?
I'm learning Neo4j and playing around with the movie graph in a browser. Following a tutorial, I extract a subgraph around Tom Hanks with the following query:
MATCH (a {name: "Tom Hanks"})-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) RETURN a,m,d LIMIT 10;
As expected, this displays a subgraph of Tom Hanks, ten nodes representing movies he acted in, and the directors of each movie. Wanting to know what the subgraph looks like when not limited to 10 movies, I tried running:
MATCH (a {name: "Tom Hanks"})-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) RETURN a,m,d;
For reasons I don't understand, this produces 3 copies of the expected subgraph, as shown below. Can anyone explain why this happens, and what would be the correct command to display the expected graph?  DETACH DELETE n
And then run the browser guide again to add the data set.
Once you're feeling comfortable with the movies guide, perhaps you can learn more about the different ways to create Nodes and Relationships in Neo4j. Check this page out, and the associated topics under "Cypher Query Language" menu on the left | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "neo4j, cypher"
} |
Convergence of the maximum of sums of random variables in probability
Let $X_i$ be independent random variables. Let $S_{m, n} = X_{m+1} + \cdots +X_n$. Then Levy's theorem says that $$P\left(\max_{m<j\leq n} |S_{m,j}| \geq 2a\right) \min_{m<k\leq n} P(|S_{k,n}| \leq a) \leq P(|S_{m,n}| > a)$$ I am trying to use this result to prove that if $S_n = X_1 + \cdots+X_n$ and $S_n/n \rightarrow 0$ in probability, then also $(\max_{1 \leq m \leq n} S_m) /n \rightarrow 0$ in probability.
If we apply Levy's Theorem with $a$ replaced by $an$, we get $$P(\max_{1 \leq m \leq n} |S_m| > 2an) \leq \frac{P(|S_{0,n}| > an)}{\min_{0 < k \leq n} P(|S_{k,n}| \leq an)}$$ Now the numerator goes to $0$ by our assumption, but I don't know what to do with the denominator at all. How can I finish this? | I found the answer. Cut off the max from below at some large $l$, rather than at $0$. For large enough $l$, the denominator is bounded below by a simple triangle inequality argument. | stackexchange-math | {
"answer_score": 0,
"question_score": 3,
"tags": "probability, random variables"
} |
SkImageDecoder factory returned null upon loading an image from resources
I'm trying to load an image into my image view using the following line of code:
iv_flagged.setImageResource(R.drawable.not_flagged);
However when I run this line of code, I get the a debug log cat message '07-16 16:12:03.610: D/skia(21114): --- SkImageDecoder::Factory returned null'
The not_flagged image is definitely in the drawable folder.
I've loaded images into image views loads of times before, here, where am I going wrong? | Whoops, the file I thought was a .png was actually a .psd file, but with a .png file extention. Hence the image decoder thought it was invalid. Idiot! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "android"
} |
How can I output XML stored string from controller or view in Codeigniter
I want to show XML content header type output from view but getting an error. Below is the code that I am putting into my view.
<?php header("Content-Type: text/xml;charset=iso-8859-1"); ?>
<?php '<?xml version="1.0" encoding="UTF-8" ?>' ?>
<urlset xmlns="">
<url>
<loc>Something</loc>
<priority>1.0</priority>
</url>
<!-- My code is looking quite different, but the principle is similar -->
<url>
<loc>Somthing</loc>
<priority>0.5</priority>
</url>
</urlset>
And that is the error that I am getting from it.
Click to view Error Message | Codeigniter has an easier way to output different kinds of content types (XML, JSON...), give it a try:
Remove the code you created, inside your controller method put this code at the end instead:
$this->output
->set_content_type('text/xml')
->set_output('your xml file or XML content');
It is important to now that, if there is any blank line before the code above your browser might interpret the output differently of XML, so when you get the result, check for a blank line in the output page (if there is no, you are okay). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, xml, codeigniter, xml parsing"
} |
Helloworld issue with React/Redux
I'm having an issue getting my action to trigger successfully in a very very basic example.
All I want is to show/hide my state output.
When I click on the onClick text which triggers the dispatch, I get this error `Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.`
Please view the repo here, `npm install` at root level and then run `webpack` inside the `simple` folder to bundle the example I'm stuck with (then open index.html, no server needed):
< | Take a look at `mapDispatchToProps` at **showAllContainer.js** really carefully. You can pass an object containing the action mapping there. That's often the easiest way to bind the actions to the dispatcher.
It would accept a function too. I think your definition didn't conform with the specification, though. That's why you received the error you did. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "reactjs, redux, react redux"
} |
Why do standard cells typically have slower timing with high temperature, and faster timing with low temperature?
Threshhold voltage typically falls with increasing temperature, which would seem to indicate that high temperature operating conditions should result in faster gates than low temperature OCs. However, standard cells typically have slower timing with high temperature, and faster timing with low temperature. What is the physical explanation as to why this is the case? I would guess that it has to do with the carrier mobility. | High temperature implies more thermal noise and random collisions of electrons, thus device resistance goes up and electron mobility goes down.
If resistance goes up then the RC constant(s) across the device nodes will be higher and speed will be lower, as speed is inversely related to RC.
**edit** : to address 2nd comment
From 'CMOS, Cirucit Design, Layout, and Simulation' R. Baker p 176:
(w/ respect to temperature effects)--
> For digital applications, the change in threshold voltage is usually negligible compared to the mobility changes; that is, the mobility changing generally has a much greater impact on the propagation delay than does the threshold voltage. | stackexchange-electronics | {
"answer_score": 7,
"question_score": 6,
"tags": "voltage, temperature, timing, chip design"
} |
Ifnum operations
I had write in my code
\newcommand \no {#1} % #1 is a number
\ifnum\i<\no....etc...\else....\fi.
But instead of it I need to multiply #1 per 3 and then sum another number. I tried `\ifnum\i < {2*#2+5}` but it didn't work. What is the correct syntax? Thx in advance.
\begin{tikzpicture} %not working
\foreach \i in {1,...,21}
\fill[\ifnum\i<{3*#2-1}\acommand\else\anothercommand\fi] (90-360/21*\i:.55cm) circle [x radius=1mm, y radius=.5mm, rotate=90-360/21*\i];
\node (0,0) {\LARGE\sffamily\bf \textsf{#2}};
\end{tikzpicture} | You need to use `\numexpr <expression> \relax` to evaluate an integer expression in an `\ifnum` context. Beware though that `\numexpr` does not really perform integer arithmetic when it comes to division.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\newcommand\acommand{blue}
\newcommand\anothercommand{red}
\newcommand\WhyWouldAnybodyUseATikzpictureInsideACommand[2]{
\begin{tikzpicture}
\foreach \i in {1,...,21} {
\fill[\ifnum\i<\numexpr3*#2-1\relax \acommand\else\anothercommand\fi] (90-360/21*\i:.55cm) circle [x radius=1mm, y radius=.5mm, rotate=90-360/21*\i];
}
\node (0,0) {\LARGE\sffamily\bf \textsf{#2}};
\end{tikzpicture}
}
\WhyWouldAnybodyUseATikzpictureInsideACommand{unused}{5}
\end{document}
>  that is taller then fits in the screen, automatically gets resized in any mobile browser, making it tiny and forcing user to zoom in.
Does anybody have a work around on this?
Im using a fluid design, width=100% etc. All other pages display fine, even if content is more then initial screen. The problem occurs only with forms that are longer. Small forms with only 2 or 3 input fields display fine.
Thank you very much for your advice! | Did you try adding the following meta tag to your html:
<meta content="width=device-width, initial-scale=1, name="viewport">
And you can use this instead to prevent the user from zooming
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "css, html, mobile, tablet"
} |
What are problems at the center of geometric topology of 2 dimensions?
I am working on Geometric Topology in 2 dimensions but I don't know which problems are important and make many connections between different areas. I hope Mathematicians can give me some ideas? Thank you so much! | The Table of Contents of this book might help focus your question, e.g., one chapter is on "The Schönflies theorem."
> Moise, Edwin E. _Geometric topology in dimensions 2 and 3_. Vol. 47. Springer Science & Business Media, 2013. (Springer link.)
>
> * * *
>
> textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
} | You can directly check like this
-(BOOL)textFieldShouldReturn:(UITextField*)textField {
if (textField.tag == 1) {
//Do the stuff what you want here
}
}
For setting the tag
textFieldName.tag = 1; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "iphone, uitextfield, uiresponder"
} |
Using Expresso store in a responsive design
I'm looking for an ecommerce solution to use with EE but I need to be able to use it within a responsive design. I don't see anything in the docs as to what markup is output with a cart tag or checkout tag. From the "showcase" sites on the website, it looks like the cart is a table and the checkout is a simple form. Is this the case?
I've built a responsive ecommerce site using Foxycart before and had to override a lot of their CSS, but got it working. How much control does the developer have over the markup and styling of the cart, checkout and other basic templates or tags?
Is there a vanilla install somewhere out there to look at the code?
Thanks. | Store like ExpressionEngine does not make any assumptions about your template content. The checkout tag and product tags will create an opening and closing `<form>` tag but other then that you are free to arrange your template however you see fit. There are no predesignated styles or html elements that you need to use or create.
When you purchase Store there is a set of example templates that you can use but the actual html portion is completely up to you. | stackexchange-expressionengine | {
"answer_score": 6,
"question_score": 5,
"tags": "expresso store"
} |
Is passing the entire object really the way to do this?
At this page, I see this code:
post._id = Posts.insert(post);
Router.go('postPage', post);
...to load a page based on the _id value.
Is this really what it should be, or should it be instead:
var id = Posts.insert(post);
Router.go('postPage', id);
?
IOW, why pass the entire object when all that is needed is the id, which is returned from the insert function (quoting from the page linked to above, " _La función insert() devuelve el identificador _id del objeto que se ha insertado en la base de datos_ ")?
Even if the way shown works (the router is smart enough to extract the id), isn't "my way" better (even though I'm not Sinatra)? | You're correct. The example code in the blog post you cite won't even work.
Router.route('/posts/:_id', {
name: 'postPage',
data: function() { return Posts.findOne(this.params._id); }
});
will fail when passed _post_ as a parameter because _this.params._id_ is the whole _:_id_ parameter, not an extraction of the __id_ from a passed object. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, mongodb, meteor, dom events"
} |
Running cron job from browser
I have several cron jobs that run automatically, and I was requested to add a button that says 'run now' in the browser... Is this possible? Some of these cron jobs need to be executed from command line as they take around 15 minutes... Is it possible to execute them from the browser, not as a normal php function but somehow trigger an external php from the browser? | You're looking for the `exec()` function.
If it's a 15 minute task, you have to redirect its output and execute in in the background. Normally, `exec()` waits for the command to finish.
Example: `exec("somecommand > /dev/null 2>/dev/null &");` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, cron"
} |
Functions and return const char*
const char* test(bool i)
{
const char t[] = "aa\n";
const char* p = "bbb\n";
if(i)
return p;
return t;
}
int main(array<System::String ^> ^args)
{
printf(test(true));
printf(test(false));
return 0;
}
That returns something of sort:
bbb
%^&$^$%
It is clear that **test(false)** returns a pointer to a local variable. The question is that p is also local variable. Why the memory for "bbb\n" is not cleaned after the function returns. I thought const char[] is interpreted same way as const char* but it is not true as it seems. | `p` is a local variable, which you return by value, but points to a **string literal** , which resides in read-only memory, not in the automatic memory allocated for the method.
Returning `t` and the using it indeed results in undefined behavior.
Also, don't think of pointers and arrays to be equivalent. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "arrays, c++ cli, char, constants"
} |
Mongodb - Setting the replication at the db or collection level
I come across the following phase and I had fair idea of distributed systems like hdfs and elasticsearch etc ..
> A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. This section introduces replication in MongoDB as well as the components and architecture of replica sets. The section also provides tutorials for common tasks related to replica sets.
In all those distributed systems like hdfs , elasticsearch - we can set the replication factor at the file level or index level. It seems it is not possible to do with mongo db, the only way to do the replication with mongodb is at the _instance / process_ level - which means the machines in the replicaset group will have similar data no matter what.
Isnt it possible to create the replication at the _db_ level ? | In a MongoDB replica set, each document is stored on each node (hence the replication factor is the number of nodes, and it is not configurable).
The benefit of this design is each node can answer any query from its locally stored data, without needing to retrieve data from other nodes. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mongodb, elasticsearch"
} |
assertion in first order logic
Can anybody give me an idea how to write this assertion in in first order logic?
> X has not passed one or more of the prerequisites for A.
Here, X is the name of a person and A is a constant representing a course name. | Expressing properties of elements of the universe in first order logic is mostly achieved through defining appropriate relations. So for this you might like to consider relations like:
* $P(x)$ - $x$ is a person,
* $C(x)$ - $x$ is a course,
* $Pre(x,y)$ - $x$ is a prerequisite of $y$ (note that this doesn't actually say that $x$ and $y$ are courses),
* $Pass(x,y)$ - $x$ has passed course $y$.
(The parentheses are just included for clarity - you may have seen different notation where relations are written without.)
Then the rest is just building the logical formula, which in this case should be fairly obvious.
> $notready(x,a) \equiv P(x) \wedge C(a) \wedge \exists y(C(y) \wedge Pre(y,a) \wedge \neg Pass(x,y)) $ | stackexchange-cs | {
"answer_score": 4,
"question_score": 1,
"tags": "logic"
} |
How do I dump information from a Windows *.lnk shortcut on Linux?
To launch Windows lnk shortcut on Linux, one can use `wine start qqq.lnk`.
But do I view the information (command line, current directory) about it? `strings` is not enough. | It seems there aren't a lot of programs to do this...I found two Perl scripts that kinda work.
**lslnk.pl** and **lnk-parse**
Use them like this: `<whicheverscript> Name.lnk` | stackexchange-superuser | {
"answer_score": 14,
"question_score": 27,
"tags": "linux, wine, file shortcut"
} |
What does "look what the wind blew in" mean?
From the movie Masterminds (2016)
In the beggining the main character is saying about the story of his life.
> In 1997, I was a quiet middle-aged man knocking on 40. But then, then the wind blew in Miss Kelly Campbell.
Searching the Internet I learned that "look what the wind blew in" probably has the same meaning as "look what the cat dragged in" which a one says when someone that is disliked shows up. But in the movie the main character's saying the phrase about "the wind" blandly, like he actually was glad that Miss Kelly Campbell showed up in his life.
My question is - does the phtase mean only something or someone unpleasant or it has more neutral nature, like "But then she showed up" | This phrase means something happened unexpectedly. There is no implication of unpleasantness. | stackexchange-ell | {
"answer_score": 5,
"question_score": 1,
"tags": "meaning, phrase meaning, phrase usage, definition"
} |
How to change server time?
I need to change server time from asp.net page. Is it possible? | Possible or not, it's a bad idea. And the only way I can think of allowing this is if the user account the app pool is executing under has some serious access rights to the machine; which is also a very bad idea.
Servers should be sync'd with a time server. This is normally controlled at the OS level.
All sorts of funky things can happen once one server in a mix gets out of an acceptable date range.
Which leads us to the question: Why?
* * *
**UPDATE**
You could pinvoke SetSystemTime. This will require the user the app pool is running under to have the SeSystemTimePrivilege. More information and an example of pinvoking here: <
Again, this is a Bad Idea(tm). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": ".net, asp.net"
} |
Как проверить является ли введенная строка числом?
Есть ли какой-то булевый метод в java, который принимает строку и проверяет является ли она числом?Например имеем переменную `String var="2";`. И надо проверить можно ли ее перегнать в переменную числового типа(Например так `Integer.parseInt(var);`) | public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
(c) from | stackexchange-ru_stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "java, android"
} |
How to read all .txt files in a directory in C
I currently have a short program to read and sort a text tile in C.
If I want to read many files, is there a substitute for:
`FILE *f f = fopen("*.txt", "rw"); `
Thanks in advance. | f = fopen("*.txt", "rw"); won't work in any case.
The usual way to do this probably depends on your operating system. On Unix-like systems, the simple way is to invoke your program with a command line like "my_pgm *.txt" and let the shell find the matching files. (You'll get multiple arguments, each one being a file name.) I understand that microsoft OSes would require the program to find the files itself.
To do that more or less portably, I'd probably use opendir() and readdir() to examine directory entries and see whether they matched the desired pattern. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "c, file, directory"
} |
Preventing reverse-engineering of a Java game source code using client server model
I'm looking to find ways to prevent a Java made game such as runescape from being hacked by using the client server model for keeping the important source code in the server and sending the data to the client. My question is how would it be possible to make something like this, any information links or articles would be helpful.
I'm also wondering what kind of information can someone send from a server that can also be rendered in a 3d graphics engine, or how is it done? | > I'm also wondering what kind of information can someone send from a server that can also be rendered in a 3d graphics engine, or how is it done?
While I am not a game/3d developer myself, I found this article illuminating (browse their wiki for more!)
Source Multiplayer Networking [valvesoftware.com] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, client server, reverse engineering"
} |
How is skill damage calculated based on weapon damage?
I understand that spell damage in based on weapon damage, but how? A weapon has both a damage attribute (e.g., 2-3 damage), and a damage-per-second attribute (e.g., 3.0 damage per second).
Let's say we have two scenarios:
1. You equip an apprentice's wand: 3.0 Damage Per Second, 2–3 Damage, 1.20 Attacks per Second
2. You equip a variation of this wand: 3.0 Damage Per Second, 1-1.5 Damage, 2.40 Attacks per Second.
Now if you cast a Magic Missile (110% weapon damage) in scenario one, would it deal 2.2-3.3 damage? And 1.1-1.65 damage in scenario two?
So this could be balanced by the fact that weapons with higher attacks per second allow you to cast spells faster. But in this case, it would cost more arcane power. Is arcane power adjusted with attacks per second? Is this mechanism explained somewhere ? | To answer the question posed in the initial question: _Only if you had 0 intelligence and no other damage bonuses!_
Base damage is simply weapon damage + any damage bonus from gear (+elemental damage is effectively "+damage" as far as the system is concerned).
The formula is roughly as follows
> **Base Damage** =
> (weapon damage range + bonus damage from gear)
> × bonus from **primary attribute** †
> × other class bonuses from **skills**.
>
> **Ability Damage** =
> Base Damage (as above)
> × **% Weapon Damage** listed on the ability.
>
> †1 primary attribute = +1% bonus damage
**Weapon speed doesn't come into play at all when calculating damage from abilities.**
What this means is that weapon speed is balanced as a stat; either you deal more damage per hit (by picking a slower weapon), or you use more abilities (since weapon speed affects animation time). DPS is entirely useless as a comparison metric unless you're _only_ auto-attacking. | stackexchange-gaming | {
"answer_score": 24,
"question_score": 37,
"tags": "diablo 3"
} |
PHP include strange behaviour
I am working on a client site (PHP) and there is a very strange behavior. Using include, include_once, require, or require_once also seems to pull in other content that should not be there at all. Has anyone heard of anything like this?
Even if the include file is empty or has just some text on it, the behavior persists. Could this be some kind of setting / global behavior?
Thank you
For example:
<?php require_once('dir/subdir/file.php'); ?> | You should always use absolute paths. It's the only reliable way to reference files.
<?php require_once(__DIR__ . '/dir/subdir/file.php'); ?>
Or on PHP 5.2:
<?php require_once(dirname(__FILE__) . '/dir/subdir/file.php'); ?> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, include"
} |
How can I connect a DIN plug keyboard to USB?
I have a wonderful IBM Model M keyboard, which has the best key action of all keyboards I ever used. The problem is it has the big round 5-pin DIN connector used in AT PCs.
I have some PS/2 to USB converters, and I know they are very 'moody', often only working with keyboards they were shipped with, and sometimes not even that. I do have DIN to PS/2 connector, but - expectably - the double conversion it doesn't work with these PS/2 to USB converters.
How can I use my 'retro' keyboard with modern PCs without PS/2? | If the IBM Model M keyboard is one of the ones that uses the AT protocol, you may be able to use a passive 5-pin to PS/2 adapter, chained with an active PS/2 to USB converter such as the Belkin F5U119.
If it uses another protocol (such as XT or 3270 terminal) you will need a custom-made active converter -- < lists several, of which the best known is probably "Soarer's". | stackexchange-retrocomputing | {
"answer_score": 19,
"question_score": 26,
"tags": "keyboards, ibm pc, old hardware adaptation"
} |
syncing code with repo/backup
I am doing a small software project on my local PC. I'm the only person working on this. I'd like to back this up to the cloud every day so that if anything happens to my HDD I have a various copies going back in time.
I have a box account although that seems to want to sync continuously and with constant file changes with code I don't really want this.
Can anyone recommend any site or software that will allow me to back up to an external location online? I'm happy to manually kick off this process at the end of each day. | If it's a software project, you should absolutely be using version control, even if you're the only developer. It'll also take care of the backup aspect if you use a repository that's on another machine. I recommend Git. GitHub is a good repository host and free for open source projects.
For my general purpose backup needs I've been very happy with CrashPlan. It runs silently in the background and backups what you want automatically, so that the backups are always up to date (the backup interval is configurable). It keeps multiple old versions of files, which is a life saver when you have deleted or overwritten the wrong files. CrashPlan is free if you backup to your own machines or disks - the online backup costs a little. | stackexchange-softwareengineering | {
"answer_score": 2,
"question_score": -2,
"tags": "development process, solo development, backups"
} |
Probability distribution of bored people
> 5 people are arranged in a row, a person is talkative with a probability of $p$ and silent with a probability of $1-p$, each is independent. A person is bored if he's talkative and sits between two silent people. $x$ is the amount of bored people.
>
> Find the probability distribution for $x$.
So $x\in[0,2]$.
$p(x=2)=p^2(1-p)^3$
Now I have trouble with $p(x=1)$, there's only one triplet with a bored person in the middle and then two spots. So it's either `sts--` (times 2) or `-sts-`:
$p(sts--)=p(1-p)^2(p^2+(1-p)2)$ that's the triplet times either two talkative or silent and then two options.
$p(-sts-)=2^2p(1-p)^2$ that's the triplet and two options for both ends.
When I sum it up it isn't right...
It's supposed to be: $p(x=1)=(1-p)^2p+2p(1-p)^2(1-p(1-p))$ | Since the discussion got a little detailed, I'll just write out an enumeration. Only way to be sure.
The "one bored guy" states:
one T: STSSS, SSTSS, SSSTS 3 in total, each with probability $p(1-p)^4$
two T: TSSTS TSTSS STSST SSTST 4 in total each with probability $p^2(1-p)^3$
three T: TSTST, TTSTS, STSTT 3 in total each with probability $p^3(1-p)^2$
Accordingly, I believe the answer to be: $$p(1-p)^2\left[3(1-p)^2+4p(1-p)+3p^2\right]$$.
I trust this matches the reference? | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability, probability distributions, random variables"
} |
How to print multiple copies of an image on a single page
I have an image, about 300x300 pixels large. I want to print as many copies as possible on a single page (I am planning to cut them apart with scissors afterwards).
Is there a way to do this? Is there a way to generate a PDF with copies (without opening something like gimp and manually doing copy-paste work). | You can use ImageMagick's `montage` tool.
1. Install the imagemagic tools
sudo apt-get install imagemagick
2. Combine your images. I have created this image, called `foo.png` as a demonstration:
!enter image description here
Run `montage`, telling it to make 3 rows of 5 images each (`-tile 3x5`), keeping the original size of the image (`-geometry 300x400` and give it the same image 15 times as input:
montage -geometry 300x400 -tile 3x5 foo.png foo.png foo.png foo.png foo.png foo.png foo.png foo.png \
foo.png foo.png foo.png foo.png foo.png foo.png foo.png montage.ps
The result is:
!enter image description here
3. Since that creates a postscript file (the language printers speak), you can print it directly from the command line using tools like `lp` or `enscript`. I don't have a printer at the moment so I can't check but this should work
lp montage.ps
or
enscript montage.ps | stackexchange-askubuntu | {
"answer_score": 12,
"question_score": 14,
"tags": "printing, pdf"
} |
Command line option to check if another user is connected to the system
I know how to find it out by GUI, but I need to check this in cmd in batch script. Basically I need to find out if connection on PC is shared to some other users. | > **Command line option to check if another user is connected to the system?**
Perhaps the `net session` command?
* * *
Update:
> **I need to find out if sharing network is enabled on windows in general**
To view what is shared by a specific computer
net view \\computername
For example
C:\> net view \\BUBBA
Shared resources at \\BUBBA
bubba Miniserver
Share name Type Used as Comment
-----------------------------------------------
home Disk Home Directories
storage Disk Common storage
The command completed successfully. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "windows, networking, network shares"
} |
Check if `isql` queries succeed
Is there any way to check if an `isql` query has failed? It seems `isql` returns 0 whether queries succeed or not, only returning false if there was a error connecting to the server. How can I determine whether or not my Sybase queries work from the command line? | `--retserverror` seemed to be what I was looking for. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "sql, linux, isql"
} |
strtolower() on an array
Using strtolower() on an array, is there a way to make the output below lower case?
<?=$rdata['batch_id']?>
strtolower($rdata['batch_id']) | You may mean strtolower:
<?php echo strtolower($rdata['batch_id']); ?> | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 36,
"tags": "php, arrays, string"
} |
Ignore one specific row from MySQL output
I have written an application that contains a users MySQL table. The following code finds users from the table that have a coolness rating within 20% of the current user's coolness rating.
$query = "SELECT USERNAME FROM USERS WHERE RATING BETWEEN ".$coolnessRating." * 0.8 AND ".$coolnessRating." * 1.2";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['USERNAME'];
}
My problem is this: if I have a user and their coolness rating is 20 for example, they themselves are returned in the result set as obviously their own rating is within 20% of their rating if that makes sense.
Is there a way to ignore this specific row but print out the rest of the result set? | "If I have a user" means you have their username or id, right? Add the condition to your where clause with AND. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, mysql"
} |
Removing empty folder svn commit during translation to git
I'm converting a repository from _svn_ to _git_ with `subgit` and it generates some empty commits because there are some folder only commits.
Is there any way to filter out them, preferably in the conversion process? | Yes, you can specify
[translate]
createEmptyGitCommits = false
in `subgit/config` file (you can set that anytime, but the best of all is to set that immediately after `subgit configure` step) and run
$ subgit install path/to/repository
to apply changes. Since that moment empty Git commits won't be created when translating new SVN revisions, older (already translated) empty Git commits won't be removed in order not to change SHA-1 hashes in the Git repository. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "subgit"
} |
mat-menu sizing problem at 1033 pixels; truncates data
I'm in an Angular 7 project using Material Design and FlexLayout
I can't figure out why the mat-menu behaves like that : When my window is greater that 1032 pixel width the mat-menu does not size according to its items and truncate contents.
Am I doing something wrong?
I have made a simple Stackblitz to show the issue : <
.
I ended up wrapping my inside a `<div id="appContainer">` and applied the styles to this div :
<body>
<div id="appContainer">
<app-root></app-root>
</div>
</body>
#appContainer {
height: 100%;
margin: 0 auto;
color:#444444;
max-width: 980px;
min-width: 400px;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angular, angular material, angular7, angular flex layout"
} |
Criar uma lista de imagens no ListView usando foreach
tenho um form com um ListView puxando informaçoes do banco como ex: Nome, porem quero que traga tambem uma imagem para estar junto com a descrição, oque eu quero fazer na verdade e uma tela com controle de mesas porem nao estou conseguindo. esse e meu codigo.
como exemplo eu quero que fique dessa forma | Considerando que você vinculou o Listview ao imagelist através da propriedade ListView.LargImageList, adicione abaixo da criação do novo item o indice ImageIndex referenciando a imagem do ImageList.
ListViewItem item = new ListViewItem(c.nome);
// adicione essa linha.
item.ImageIndex = 0 ;/* aqui você atribui o indice em relação com a
imagem no ImageList, 0,1,2,3 conforme a
sequência das imagens */ | stackexchange-pt_stackoverflow | {
"answer_score": -3,
"question_score": -4,
"tags": "c#, sql server, entity framework, windows"
} |
Is @ useful in comment?
When I ask some questions, someone would like to reply in comment. So I communicate with them in comment. To tell them I have replied to them, I @mention their ID at comment beginning. But it doesn't become a link. So I don't know if it is useful. If it doesn't work, how should I reply to them in comment? | It is useful, because, although it doesn't become a link, the mentioned user will get a notification in their inbox.
Users get notified about a comment, if...
* the user owns the post, or
* the user was mentioned and was previously active on the post | stackexchange-meta_stackoverflow | {
"answer_score": 7,
"question_score": -10,
"tags": "discussion, comment replies"
} |
Generating Flutter route after action?
I'm trying to automatically route back to my menu screen after a successful login and I'm having trouble generating a Widget build and/or context. I'm doing this in a Stateless Widget. Here is my code. I would like to call route after the last print statement...
Future<Null> _handleSignIn() async {
try {
await _googleSignIn.disconnect();
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
print(googleAuth.idToken);
await FirebaseAuth.instance.signInWithGoogle(idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
} catch (error) {
print(error);
}
print("Let's Do This");
print(_googleSignIn.currentUser.displayName);
print(FirebaseAuth.instance.currentUser);
} | From what I understand from your question you basically need to setup your sign in button to redirect the users to wherever you want them to be after a successful sign in.
You can setup your onPressed call as follows, and you should be fine from here:
onPressed: () {_handleSignIn().whenComplete( ()=>Navigator.of(context).pushNamed("/MyHome"));
}
**Note** that you can not use Navigator outside your build method, hence you always need to handle the navigation parts within your widgets. **Check the comment on this answer.** | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "routes, flutter, navigator"
} |
Setting a watchpoint on errno in gdb
I'm trying to find out when errno changes.
At first, I tried "watch errno" in gdb, which led to the error
Cannot find thread-local variables on this target
I was able to fix this by compiling with "-pthread". However, it still doesn't work and I now get the error
Cannot find shared library `/usr/lib/debug/lib/x86_64-linux-gnu/libc-2.13.so' in dynamic linker's load module list
when I type "watch errno". What do I need to do such that setting a watchpoint on errno works? | `errno` is not just a static variable anymore. Here's how it appears to userland apps on Linux (from my local `/usr/include/x86_64-linux-gnu/bits/errno.h`):
# define errno (*__errno_location ())
This is to get error state per thread. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 7,
"tags": "debugging, gdb, libc, errno, watchpoint"
} |
How to use busy table from view side?
I have crons what inserts data to odds table each 5 minutes, processes are always active and table is always busy.
Now from view side i use odds table, and when someone click on some match it returns odds for that match but page loading is 5-20 seconds for single match, while other page requests are normal speed, when i click to change days and get all matches for that days than is normal because it select data from baby table, but when i click on single match there is problem.
My question is can i somehow use busy table from view side without 5-20 seconds waiting or i need to increase ram server size, or maybe to copy all odds data to some copyodds table for example? | You may use following trick for insertion:
1. Method-1
>
> INSERT INTO TABLE_A (A, B, C, D) VALUES
> (1,1,1,1),
> (2,2,2,2),
> (3,3,3,3),
> (4,4,4,4);
>
2. Method-2
Use `INSERT DELAYED INTO` if stale read is not an issue. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "php, mysql, query optimization"
} |
Change chapter caption style to section caption style
`\documentclass[12pt,a4paper]{report}` is the format of my document. Writing `\chapter{Chapter one}` will create a new chapter on a new page with a lot of white space above the caption. Writing `\section{Section one}` will create a small caption with little white space around it.
How can I override the style of `\chapter{}` with the style of `\section{}` so that they will look the same? And is the caption of the table of contents also defined as an unnumbered `\chapter{}` heading? I am asking because I want the caption of my table of contents (and my list of tables/figures/etc.) to look like a `\section{}` caption as well. | Use the `memoir` class with the `article` option, instead of the `report` class. The option makes `\chapter`s behave as `\section`s, `section` as `subsection` etc.
% \documentclass[...]{report}
\documentclass[article,...]{memoir}
and what you have already | stackexchange-tex | {
"answer_score": 2,
"question_score": 0,
"tags": "sectioning, chapters, report"
} |
{{var payment_html}} is empty
In sales transactional e-mails I cannot find out how to make magento print **payment method.** I have two options (cash on delivery or credit card on delivery) for customers. It's empty every time.
In back-end at the View order page I can't see it neither because there is only written Order was placed using.
How can I fix it, please? | I haven't found why var payment_html is totally empty but yet I found solution.
In transactional emails template use instead of `{{var payment_html}}` this
{{var order.getPayment().getMethodInstance().getTitle()}}
Now I see at least in those emails which method customers chose. | stackexchange-magento | {
"answer_score": 0,
"question_score": 3,
"tags": "magento 1.9, payment methods, transactional mail"
} |
Page loads before Style and Scripts, causing stutter
I have an extremely annoying bug and Im at a loss for what to try or where to begin. Im using `Wordpress 3.9.1`.
When you go to my site and refresh the page, click on another page, etc, it loses its style for a split second. It's as if the page loads before my style and jquery scripts kick in.
I have disabled all scripts and my background canvas effect, to check if maybe a slow or bulky script was at fault, and could not fix the issue.
Is there possibly a way to tell the page to not show unless all the styles and scripts load? There arent that many scripts and they are extremely light weight.
**EDIT:** Ill post code if requested. I have all my styles and scripts `wp_enqueued`.
Anyone at all? | Ok, this has got to be one of the weirdest solutions to this problem. I left my `enqueue` scripts the same, except I added this line to my header.php
// Added Line
<link rel="stylesheet" type="text/css" media="all" href="<? bloginfo( '' ); ?>" />
// Unchanged Line
<link rel="stylesheet" type="text/css" media="all" href="<? bloginfo( 'stylesheet_url' ); ?>" />
Without the added link `<? bloginfo( '' ); ?>` my page stutters horribly on page-load. Can anyone possibly explain why this fixes it.........? | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "jquery, css, styles, load, refresh"
} |
Извлечение значений типа double из строки
Работаю с Api yandex-geocoder. В ответе от сервера приходит строка с координатами, в которой сначала указывается долгота (lon), а затем широта (lat). Например: "36.587223 50.59566". Мне нужно извлечь эти 2 значения из типа String, поместить их в тип double и поменять местами, чтобы первое значение приходило в переменную lat, а второе - в переменную lon. Подскажите, пожалуйста, как это можно осуществить? | Для начала можно будет разбить строку на строковый массив по пробелам:
String a = your string;
String[] array = a.split(" ");
У нас получится массив с двумя элементами - вашими координатами. Потом запишем в две переменные типа double:
double defaultLon = Double.parseDouble(array[0]);
double defaultLat = Double.parseDouble(array[1]);
Теперь у вас есть две переменные - долгота и широта и вы можете их использовать дальше. Если вам нужна опять строка то можно сделать так:
String answer = "" + defaultLat + " " + defaultLon; | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "android, android studio, геокодирование"
} |
Trying to modify column type but get error
I'm running this command
alter table client_details alter column name type character varying(120);
but then get the error
ERROR: syntax error at or near "view" at character 7
LINE 1: alter view v1 alter column name type character varying(120);
I've noticed that a view exists thats causing the problem, how can I alter the type in the vieww, or solve this issue? | Unfortunately PostgreSQL is very strict about this.
You need to drop the view that references that table, then alter the column type and then recreate the view. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "postgresql"
} |
How can I use a regex expression to look for a particular URL?
I connected to a site using URLConnection and the result I'm looking for is the url inside these parenthesis: `callback_request(" + escape(text), handleResult);`
The problem I'm having is the : `s=bOVZmsrjbNQzntbDei*324JUo*3ozJ7hR*h1KNlxc6kPaBeKCBrdKIxD*edhi4qH` is random each time--it's the session.
How can I use a regex expression to scan the page and look for ` | Try this:
import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args)
{
Pattern p = Pattern.compile("
System.out.println(p.matcher("
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, regex"
} |
Real-time baseball data?
I want to make a display using arduino that shows "who's on first" etc at yankee stadium. So, I'm looking for a real-time feed with that info. What are my options? | Not sure you're going to find a "free" solution that is legitimately usable in the fashion you require and official/guaranteed to persist.
That said, MLB does publish an API, and has for years - it's just not something they guarantee. It's their GamedayAPI. I'm not sure how frequently it's updated, but I just peeked at the folder for 9/24/2015 ARIvsLAN and found that they were at least on the current inning compared to the live site, so it's obviously pretty up to date.
The most common commercial product is from Baseball Info Solutions, which provides data to sites like FanGraphs. | stackexchange-sports | {
"answer_score": 6,
"question_score": 2,
"tags": "baseball, statistics"
} |
Is the wedge product of two harmonic forms harmonic?
* Is the wedge product of two harmonic forms on a compact Riemannian manifold harmonic? I'm looking for a counter-example that the textbooks say exists.
* I would like to see a counter example that is on a complex manifold, Ricci-flat (or Einstein) manifold or both, if it is at all possible.
* In general, I'm trying to understand the interaction between the wedge product, Hodge star and the Laplacian on forms and it's eigen-vectors, references will be much appreciated. | It is easy to construct examples on Riemann surfaces of genus $>1$. Take any surface like this. Let $A$ and $B$ be two harmonic $1$-forms, that are not proportional. Then $A \wedge B$ is non-zero, but it vanishes at some point, since both $A$ and $B$ have zeros. At the same time a harmonic $2$-form on a Riemann surface is constant. Explicit examples of $1$-forms on Riemann surfaces can be obtained as real parts of holomorphic $1$-forms.
Note of course that the above example is complex, and Einstein just take the standard metric of curvature $-1$. If you want an example on a Ricci flat manifold you should take a $K3$ surface. It is complex and admits a Ricci flat metric. Now, its second cohomology has dimension $22$. Now it should be possible to find two anti-self-dual two-forms whose wedge product vanishes at one point on $K3$ but is not identically zero. This is because the dimension of the space of self dual forms is 19 which is big enought to get vanishing at one point | stackexchange-mathoverflow_net_7z | {
"answer_score": 32,
"question_score": 19,
"tags": "riemannian geometry, complex geometry"
} |
How do I make a dropdown box clickable more than once?
I am just learning jquery and I am confused about how to make my information appear and reappear more than one time?
<
$(".drop").hide();
$(".experience").click(function(){
$(".drop").show()
$(".experience").click(function(){
$(".drop").hide()
});
}); | You could use
$(".experience").click(function(){
$(".drop").toggle();
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
} |
Developer tools for cinnamon extensions (applets, desklets)
Are there developer tools for cinnamon applets and desklets?
The only thing I could come up with is removing the desklet folder from `~/.local/share/cinnamon/desklets/{desklet}` copying the new one and restart cinnamon with `cinnamon --replace` and wait 20 secs until it restarts. After that I can check on the desktop whether my code works and possibly debug it based on the stdout and stderr. I can do this only from terminal since I cannot use sudo from the run configuration in webstorm as far as I know. Now this is very far from a good testing/developer environment... :S | You could try applet called Cinnamon Developer's Tools which provides easy access to
Looking Glass (the integrated debugger for gnome shell). It also provides quick access to the content of `~/.xsession-errors`, many frequently used modules from `cinnamon-settings` and allows to inspect applets and extensions. It also provides a button to restart cinnamon. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 3,
"tags": "linux, linux mint"
} |
Find all usages of C# class recursively
I've made some changes to the class and it is located in some shared project, so it can be used in many websites. How can I determine which projects will be affected?
The cases when this is useful: I want to update only changed production servers or I want to understand, how harmful is my change.
Current solution (using resharper or only visual studio): find usages of class, then find usages of all usages, then find usages of usages of usages and so on. Is there any way to make it easier? | For methods you're changing you can put your cursor on the methodname and press ctrl+shift+alt+A and pick 'Incoming calls', this way you can see the whole hierarchy where this method is used. If you follow through those hierarchies you can find in which projects and classes this method in your shared project is used. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "c#, visual studio, resharper"
} |
Why str(random.choice()) returns /string/
I am trying to make a function that randomly throws the strings of rock paper or scissors. However when I debug I notice that the variable attaching random. choice is in the following format:
!Output of the random.choice
That means that the condition is never met. This the code of my function.: _I know is not complete._
def detect(player_pick):
enemy_pick = str(random.choices(['rock', 'paper', 'scissors']))
# Rock detection
if enemy_pick == 'rock' and player_pick == 'scissors':
print("you lose")
return "rock_win_enemy"
elif enemy_pick == 'scissors' and player_pick == 'rock':
print("Enemy lose")
return "rock_win_player"
elif enemy_pick == 'rock' and player_pick == 'rock':
print("tie")
return "tie"
# Paper detection
# Scissors detection | You called `random.choices` (with an `s`) not `random.choice`. It returns a `list` of results (and oddly, doesn't require you to say how many you want; it defaults to making just one choice). As a result, `enemy_pick` is always a length 1 `list`, the `str` form of which will never be equal to any of your strings (they aren't wrapped in square brackets). Use `random.choice` (no `s`), not `random.choices`, and it should work (you can remove the `str()` wrapping too; all the choices available are already `str`). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python, string, random"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.