INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Error: A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<int>'
I have list temp and call the function List but this error happens
This error happens only after updating flutter
`A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<int>'.`
I guess there is no List though ,,,
How can I fix this ??
List<int> arr = [];
List<List<int>> temp = [
[3,4],
[3,5],
[4,3],
[4,4],
[5,2],
[5,5],
[2,3],
[2,4],
];
arr = chord3(0,temp[2]); // I call chord3 function here
List chord3(f,List<int> s){ // this is function and error occurs here
List<int> temp = [];
temp.add(f);
temp.add(1);
return temp;
}
|
Just add `int` here:
List<int>chord3(f,List<int> s){ // this is function and error occurs here
List<int> temp = [];
temp.add(f);
temp.add(1);
return temp;
}
You also have this option, same result:
arr = List<int>.from(chord3(0,temp[2]));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "flutter, dart"
}
|
QlineEdit: No such file or directory
I have a problem. I have QT 5.3.1 and Ubuntu 14.04.
For example:
#include <QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QPixmap>
#include <QImage>
#include <QComboBox>
#include <QFileDialog>
#include <QlineEdit>
#include <QLabel>
#include <QFile>
#include <QIODevice>
#include <QSlider>
#include <QMessageBox>
Works well.
The problem is the following line:
#include <QlineEdit>
Compilator return error: QlineEdit: No such file or directory.
How do I fix this?
|
There is no such class a QlineEdit. However, there is a QLineEdit class.
Note the capital 'L' in Line.
As you've tagged your question with 'Ubuntu' and you're using Linux, it's likely to be case-sensitive, so the capitalisation matters here.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "qt, ubuntu"
}
|
Is this Modal (bisimulation) contraction correct?
Bellow I define model $M=(W,R,V)$ and Model $K=(W',R',V')$. Is model $K$ the model contraction (bisimulation contraction) of $M$?
Model $M$: $W = {a, b, c}$, and $R = {(a, b), (a, c), (b, c), (c, a), (c, b)}$, and $V (p) = {b}$
Model $K$: $W' = {d, e}$, and $R' = {(d, e), (e, e), (e, d)}$, and $V' (p) = {d}$
|
In short, yes, it is correct. However, depending on how pedantic you want to be, the correct answer will be _the bisimulation contraction of $M$ is isomorphic to $K$_. Recall that a bisimulation contraction of model $M$ is the quotient model of $M$ with respect to the maximal bisimulation of $M$ with itself (which is called autobisimulation). Hence, the contraction of $M$ in your example would be exactly like $K$ with $\\{b\\}$ and $\\{a,c\\}$ instead of $d$ and $e$ respectively.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "logic, modal logic"
}
|
Joda Date and SWT DateTime conflict
I've run into a problem I haven't seen before and a search pulled up nothing. I have imported SWT DateTime and Joda DateTime in my program, and it doesn't seem like they can co-exist. is there a way to allow both classes in eclipse?It keeps wanting to use swt DateTime widget exclusively, and I'm not sure how to deal with two classes of the same name in different imports. thanks!
|
You can just skip both imports and reference the classes using the full package name:
public class Main {
private org.joda.time.DateTime jodaDateTime;
private swt.DateTime swtDateTime;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "eclipse, datetime, swt"
}
|
What are the qualities of a country that might make it more or less likely to freely allow Bitcoins or crypto-currencies?
As some examples which seem logical to me, but should only be taken as examples:
A government that is susceptible to commercial lobbying is probably more likely to be pressured by banks to disallow competition with their services.
Governments that have a corruption problem might also be quietly bribed to legislate against a currency that competes with the official one.
Countries that support open source software might tend to have a "for the good of the community attitude" that matches the philosophy of Bitcoins.
For this question, it's probably important to provide references/examples (such as information about who is trying to stop use of bitcoins and why).
I see the need to ask this question to help provide a foundation for this one: Is there a list of countries that are not likely to persecute bitcoin businesses?
|
Countries which have strict AML (anti-money laundering) laws are less likely to freely allow Bitcoin use and exchange.
|
stackexchange-bitcoin
|
{
"answer_score": 2,
"question_score": 6,
"tags": "currencies, legal, banks, politics"
}
|
docker-compose fork/exec permission denied
Last night I updated Docker desktop to the latest version 4.10.1 and today when I tried to run my containers, I get this error:
**.
Downgrade to **Docker Desktop 4.9.1** :
Or run your container from Terminal:
docker-compose up
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 15,
"tags": "docker, docker compose, apple m1"
}
|
Google App Engine python Filter "property of property"
Having these models on google app engine:
class Choice(db.Model):
poll = db.ReferenceProperty(Poll, collection_name = 'choices' )
text = db.StringProperty()
class Vote(db.Model):
choice = db.ReferenceProperty(Choice, collection_name = 'votes' )
ip = db.StringProperty()
date = db.DateTimeProperty(auto_now=1)
How do I do this django query?
same_vote = Vote.filter(ip=self.ip, choice__poll=self.choice.poll)
|
The App Engine datastore isn't capable of doing a query like this, which requires a join. To perform such a query, you'll need to denormalize your data so your Vote entities include information about which Poll they apply to.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, django, google app engine"
}
|
Is it possible to use MS Coded UI Test framework to test Java GUI application?
MSDN page Supported Configurations and Platforms for Coded UI Tests and Action Recordings tells that Java platform is not supported. But now Java development is possible with Visual Studio Team Services (VSTS) and Team Foundation Server (TFS) (< so it is strange for me that in Coded UI Test there is no Java GUI testing support.
I tried to record actions for Java GUI in Microsoft Test Manager and it handles the task quite well (but this tool is primarily for manual testing and recording is just to help handle manual test steps). Still there is a possibility to export MTM tests to CodedUI tests in C# so may be there is something wrong in Coded UI Test support matrix? And it is possible to use MS Coded UI Test framework to test Java GUI application.
P.S.: I do not have VS Ultimate or Premium to check this feature (Coded UI Tests is only available in them)
|
The support matrix is right: **Java GUI testing is not supported by Coded UI Test**.
Generated code from recoded MTM test-case uses native `Windows OS` elements to work with and all actions (mouse clicks & key typing) are linked to them, e.g.:
...
Mouse.Click(someClient, new Point(239, 90));
Mouse.Click(someClient, new Point(139, 193));
Mouse.Click(someTitleBar, MouseButtons.Right, ModifierKeys.None, new Point(233, 9));
...
MTM can record actions on Java GUI just because it uses `Mouse.Click(obj, point)` and key typing events, the first one uses coordinates from GUI elements that treated like Windows native (window & it's titlebar)
|
stackexchange-sqa
|
{
"answer_score": 1,
"question_score": 1,
"tags": "automated testing, mtm, coded ui tests, java gui"
}
|
Redis - query by more than key
I use redis to store user sessions by a guid i generate when the log in. I use that as the key in their session object.
If i was to lock a user's account I currently have to go through all sessions and check if they are the user's then delete them.
Is there a way to also query by the user id? Should I be using the sorted set insured of just standard key value?
|
Going through all keys is probably not the best idea. What you could do is store every user sessions' guids in another key - the set data type seems to be the best choice for that - and add/remove from it as the user opens/closes a session. So, when a user opens a new session you will:
SET session:<guid> <session_object>
SADD user_sessions:<user_id> <session_guid>
and when the session is closed, you'll do:
DEL session:<guid>
SREM user_sessions:<user_id> <session_guid>
To find which session guids are a user's, e.g. for an account lock down, do:
SMEMBERS sessions:<user_id>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "redis, servicestack.redis"
}
|
If there was an engine malfunction, could we breathe contaminated air?
If the engine on airliners has for example, an oil leak, can the oil or other substances contaminate the air on the passenger cabin? How would this situation be avoided?
|
Yes, it is possible for contaminated air to enter the cabin. The air pressurization is provided by the "packs" (air conditioners), which are in turn powered by the bleed air (hot air extracted from low stages of the turbine) of the engine: , you better get down right away.
|
stackexchange-aviation
|
{
"answer_score": 3,
"question_score": 7,
"tags": "airliner, emergency"
}
|
Matrix form of differential equation, not diagonalizable
So I came across this problem while studying and I'm a little confused.
$$ y'(t) = \begin{bmatrix} 1 & 1 \\\ 0 & 1 \end{bmatrix}y(t) $$
Usually I solve for the eigenvalues and the corresponding eigenvectors and then basically plug into:
$$ y = c_{1} e^{\lambda_{1} t} \begin{bmatrix} e1 \\\ e2 \end{bmatrix}+ c_{2} e^{\lambda_{2} t} \begin{bmatrix} e3 \\\ e4 \end{bmatrix} $$
But in this case it isn't diagonalizable and I only get one eigenvector. How do you solve this?
|
For a $2\times 2$ matrix with repeated eigenvalue, and only one linearly independent eigenvector, one can obtain a second solution as $\vec y_2(t)=te^{\lambda t}\vec v_1+e^{\lambda t}\vec v_2$, where $\vec v_1$ is the eigenvector for the matrix, and $\vec v_2$ is a "generalized eigenvector", which satisfies $(A-\lambda I)\vec v_2=\vec v_1$, or equivalently satisfies $(A-\lambda I)^2\vec v_2=0$. So the general solution becomes $$\vec y(t)=c_1e^{\lambda t}\vec v_1+c_2(te^{\lambda t}\vec v_1+e^{\lambda t}\vec v_2)$$ If you are familiar with the matrix exponential, then you could also solve this problem using $e^{At}$ as a fundamental matrix. Notice here that $A$ can be written as the sum of the identity matrix, and a nilpotent matrix (i.e. $N^k=0$ for some $k\in\Bbb N$), so $A=I+N$, and $e^{At}=e^{It}e^{Nt}$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra, ordinary differential equations, eigenvalues eigenvectors"
}
|
rails - what does - multiple values for a block parameter (0 for 1) - mean?
I keep getting this error on Heroku but not locally. any idea why that would be?
/disk1/home/slugs/352624_0e85669_cd2f-9e7b2ba0-45de-479f-b275-af88d0b560c6/mnt/app/views/sessions/_new.html.erb:2: warning: multiple values for a block parameter (0 for 1)
from /home/slugs/352624_0e85669_cd2f-9e7b2ba0-45de-479f-b275-af88d0b560c6/mnt/.bundle/gems/ruby/1.8/gems/actionpack-3.0.0/lib/action_view/helpers/capture_helper.rb:39
Here's some of the template:
<div id="account-signin">
<%= form_tag(new_user_session_path, :method=>'post', :id => 'user_signin') do |f| %>
<table>
<tr>
<td>
<table>
<tr>
<td>
<%= label_tag 'Email' %>
</td>
<td>
<%= label_tag 'Password' %>
</td>
|
The block given to the form_tag method doesn't take any parameters. The error is telling you that your block requires an argument, but form_tag doesn't have any arguments to give it. Remove the "|f|" bit at the end of the form_tag line and it should work.
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 4,
"tags": "ruby on rails, ruby on rails 3"
}
|
Can Android emulator capture key-press event of PC keyboard
Can the Android emulator capture a key-press event of the computer (running the emulator) keyboard, such as: direction key, backspace key and enter key? If it could do that, can you tell me the key code of the implentation? Thanks a lot.
|
The mapping between PC keyboard keys and devices keys is detailed here: <
And you can respond to them using the keycodes that are listed here: <
For instance:
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.i("test", "onKeyDown(" + keyCode + ", " + event +")");
return super.onKeyDown(keyCode, event);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "android, android emulator, keyboard"
}
|
Regex match a character that's not part of word in string
Using Regex in JS I'm trying to match all `<` and `>` which are not part of a specific HTML element. In the below example, I try to exclude those associated with <sup> and </sup> but my current expression still matches with > at the end of the element.
How can I also exclude the ending > of the element?
Current expression:
/(?!<\/?sup>)[<>]/gi
!Image of Regex Example
|
Almost there; the special tag can show up before or after a tag, e.g. using (Demo):
(?<!sup)<>
Or if you want to make it more readable: `<(?!\/?sup)|(?<!\/?sup)>` We could optimize this with possessive quantifiers; unfortunately, JS does not support them.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, regex"
}
|
Счетчик времени во всплывающем окне
Не получается сделать в попапе счетчик времени (секунд), чтобы по прошествии 3-х секунд закрывалось окно. Хочу, чтобы тикало 3, потом 2, потом 1 и окно закрылвась, вот это тикание как реализовать? Знаю что через сетинтервал, но не получается.
|
var counter = 3;
var intervalId = setInterval(function(){
console.log(counter--);// вваш способ вывода отсчёта
if(counter==0){
clearInterval(intervalId);
console.log('close'); // ваш способ закрытия
}
}, 1000)
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript"
}
|
New Portable Hard Disk
I've just bought a portable 2TB TOSHIBA HD that I wanted to use for back-ups. I wanted to know if there are some things one should do when plugging it in for the first time (like see if it works properly, formatting it) and especially HOW to do those things.
I've looked into the specs of my HD and this are some info I believe to be important:
File system: NTFS (MS Windows)
-System Requirements: Windows® 10 / Windows 8.1 / Windows® 7
CPU with 750 MHz or faster, 10 MB system hard disk space,
256 MB system memory, one free port of USB 3.0 or USB 2.0
I have a dual-boot system on my pc (windows 8.1 and Ubuntu 17.04) so I can choose which OS to plug it in, you tell me whats best.
I'm a beginner, so please be patient, thanks.
|
The current file system, NTFS, is good because it can be accessed for reading and writing from both Ubuntu and Windows. This means that you can use it from both operating systems for backups.
I think you can start using it directly without tampering with partitions and file systems.
Edit:
One of the first things would be to check the drive in Windows (check that the NTFS file system is working correctly in Windows.)
Then try to read and write some small file in both operating systems. Come back with questions in comments (or if more details by editing your original question).
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 1,
"tags": "dual boot, hard drive"
}
|
How to retrieve a number (ID) inside a image path using js/jquery?
Here is the sample path, assuming the format is fixed
For the 4th image, the path is '`demo/medium/Web081112_P004_medium.jpg`'
so if the image is the 100 th ,then
'`demo/medium/Web081112_P100_medium.jpg` '
Is there any way to get the number in this format, I have thought about using reg exp? But it may cause a problem because I may retrieve 004 instead of 4, how to fix this? Thanks
|
This answer is based on the message in the original question
_sample path, assuming the format is fixed_
If the string is not going to change then you can use split:
var num = parseInt(path.split("_P")[1],10);
**Note** remember the parseInt needs the radix 10 to remove the leading 0s which would otherwise make the number OCTAL
Also note that splitting on `_P` will (as mentioned by Cerbrus) get the the string `004_medium.jpg` which still works with parseInt because parseInt will ignore trailing non-numeric characters
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Getting input to an executable via stdin?
I have an executable that I need to take input from a .wav file on my desktop. The executable expects input on stdin.
Let us use the example:
/Users/tomcruise/Desktop/executable
/Users/tomcruise/Desktop/music.wav
I am using Mac OS X.
|
Open Terminal and do the following:
$ cd /Users/tomcruise/Desktop
$ ./executable < music.wav
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "macos, unix, command line, stdin"
}
|
How to {} in format?
I try:
'TEST{0}: {TEMP}'.format("_TEST")
and result:
KeyError: 'TEMP
How to recived something like that by format:
'TEST_TEST: {TEMP}'
|
You can use double `{{` and `}}` to escape `{` and `}` . Example -
>>> 'TEST{0}: {{TEMP}}'.format("_TEST")
'TEST_TEST: {TEMP}'
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, string, format"
}
|
Find non-hexadecimal formatted data
I am trying to write a query in hive to find the rows that are not in hexadecimal format. I used RLIKE which retrieves the rows that are in hexadecimal.
|
Just use `NOT RLIKE`:
select col from table where col not rlike '^[0-9A-F]+$'; --apply your hexadecimal pattern
For both upper and lower case use this pattern: `'^[0-9a-fA-F]+$'`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "hive, hex"
}
|
Unable to type in text input in Firefox & IExplorer
I have a basic registration form on my website. While testing it in different browsers I noticed that it was fully functioning in Chrome but not in Firefox or IExplorer. In both Firefox and Iexplorer I'm unable to type in any of the input fields. I don't know what's causing it and I'm not getting any errors.
Here's the page.
|
You actually CAN type in the fields, you just can't see the text because the padding and height inside the text boxes are pushing the text around inside the text box, moving it outside the visible area of the input field.
The following will remove the unnecessary vertical padding:
#registration input, #registration textarea {
/* Your other properties */
padding: 0px 8px;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, internet explorer, firefox"
}
|
Why is MTM attempting to load the wrong version of CodedUITestFramework DLL when I run a test case via Microsoft Test Manager?
**The Set Up**
I have TFS 2012, VS 2013 and Test Controller 2013 on my machine which runs Windows 8.1 x64
I have installed a Windows 7 x86 VM and on it I've installed VS 2012, VS 2013 and Test Controller 2013 (in that order). The VM is my test controller.
**The Issue**
When I run the test case on MTM I get the following message:
> Error adding test case [14] to test run: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Why is it trying to load version 11?
|
Though the documentation mentions that the 2013 Test Agent should work with your TFS 2012 server, I've usually not mixed and matched agent versions and relied on the agent matching the TFS server version. It reduces these type of issues. I'm glad this was an option for you and that it also fixes your issue, though technically your original approach should also have worked according to the docs.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": ".net, visual studio 2012, tfs, visual studio 2013, microsoft test manager"
}
|
Spring3 portlets with JSF2
Did anybody ever used the new Spring3 with JSF2 and portlets (JSR286) ?
I used JSF1.2 with portlets (JSR168) we had some problems with stuff like file uploading, portlet intercommunication and other stuff.
There aren't a lot of resources online on this topic.
|
The Portlets in Action book covers JSR286, and has a couple of chapters on Spring3, but there's no mention of JSF2 sorry.
Much of JSR286 was done to address the problems in JSR168 with regards to file uploading and portlet communication. I would recommend dropping any JSR168 support in favour of JSR286 if you are able to.
UPDATE 1: Have you looked at the JBoss Portlet Bridge?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, spring, jsf, jsf 2"
}
|
RotateAnimation.setFillAfter(true) and .setFillEnabled(true) does not work
I'm trying to rotate 3 `imageViews` with a `rotateAnimation`. I calculate the degrees to rotate every 30ms. If the angle changed, I create the rotateAnimation:
rpmAnim=new RotateAnimation((float)Rpmcurrentdegree, (float)Rpmdegree, ivNadel.getWidth()/2, ivNadel.getHeight()/2);
rpmAnim.setFillEnabled(true);
rpmAnim.setFillAfter(true);
...and then I start the animation of the imageView:
ivNadel.startAnimation(rpmAnim);
The rotation works fine, but when the degrees **do not** change, it jumps back to its starting position. Does anyone know why?
|
set the setAnimationListener on rpmAnim:
rpmAnim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation arg0) {
// here rotate the image
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
to rotate the image you **can**
1. extends ImageView in order to create your custom image view
2. override onDraw
3. set your rotation angle
4. invalidate your custom image view
the overridden `onDraw` could look like:
protected void onDraw(Canvas canvas) {
canvas.save()
canvas.rotate(your rotation angle...)
super.onDraw(canvas)
canvas.restore()
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, image, animation, imageview, rotateanimation"
}
|
how to allow files starting with period and no extension in windows 2003 server?
How can I create this file in a directory in windows 2003 SP2:
.hgignore
I get error: You must type a file name.
|
That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt:
echo Hello there! > .hgignore
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 23,
"tags": "mercurial, windows server 2003, hgignore"
}
|
How do I use regular expressions in PostgreSQL to remove the end of a field matching pattern?
How can I simplify this PostgreSQL? Basically I want to check if the fields end with `(1)` or just `(1)` and replace and repeat from numbers from 1-30. I assume it can be done with regular expressions somehow, but I haven't got it working.
UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,' (1)'))
WHERE name LIKE '% (1)';
UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,'(1)'))
WHERE name LIKE '%(1)';
UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,' (2)'))
WHERE name LIKE '% (2)';
UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,'(2)'))
WHERE name LIKE '%(2)';
|
1. use the `regexp_replace(target, regexp, replacewith)` function
2. your pattern would be something like `' ?\(([1-9]|[12][0-9]|30)\)$'`
3. i'm not exactly sure what you are trying to replace with...just removing the number? if so, replace with `''`.
Regexp explanation:
" ?" = optional space
\( = opening parenthesis (escaped)
([1-9]|[12][0-9]|30) = numbers 1-30
\) = closing parenthesis (escaped)
$ = end of content
Regarding your comment:
update discogs.artist_meta
set name = regexp_replace(name, ' ?\(([1-9]|[12][0-9]|30)\)$', '')
where name ~ ' ?\(([1-9]|[12][0-9]|30)\)$'
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, regex, postgresql"
}
|
get_categories() only returns categories in use
$args = array(
"type" => "post",
"orderby" => "name",
"order" => "ASC");
$types = get_categories($args);
When this is executed. $types only contains "Uncategorized" since it is used as the default to my posts. There are other categories available, but they are not returned unless I have a post that uses them. How can I return all possible categories and not just the ones that are in use?
|
<?php $args = array("hide_empty" => 0,
"type" => "post",
"orderby" => "name",
"order" => "ASC" );
$types = get_categories($args);
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 37,
"question_score": 20,
"tags": "php, wordpress, plugins"
}
|
why string, array and dictionary in Swift changed to value type
In Objc string, array and dictionary are all reference types, while in Swift they are all value types.
1. I want to figure out what's the reason behind the scenes, for my understanding, no matter it is a reference type or value type, the objects live in the heap in both Objc and Swift.
2. Was the change for making coding easier? i.e. if it is reference type then the pointer to the object might not be nil, so need to check both pointer and the object not nil for accessing the object. While if it is value type then only need to check the object itself?
3. But in terms of memory allocation, value types and reference types are same, right? both allocated same size of memory?
thanks
|
Arrays, dictionaries etc. in Objective-C are often mutable. That means when I pass an array to another method, and then that array is modified behind the back of the other method, surprising (to put it gently) behaviour will happen.
By making arrays, dictionaries etc. value types, this surprising behaviour is avoided. When you receive a Swift array, you know that nobody is going to modify it behind your back. Objects that can be modified behind your back are a major source for problems.
In reality, the Swift compiler tries to avoid unnecessary copying whenever possible. So even if it says that an array is officially copied, it doesn't mean that it is _really_ copied.
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 29,
"tags": "objective c, swift, value type, reference type"
}
|
Jinja - load custom template tag set
Is there a way to load a custom tag set - or even individual custom tags?
In django templates, I was able to do this:
{% load custom_tag_set %}
Is there a way to do this in jinja?
|
The same mechanism exists but with a different name.
It's called Extensions
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "django, django templates, jinja2"
}
|
In the flux architecture, who is responsible for sending updates to the server?
So in the flux architecture, data flows as follows:
View -> Action -> Dispatcher -> Store
^ <-----------------------------|
So let's say the view is a comment box. When the user submits a comment, an addComment action is triggered, but where should that comment be sent to the server? Should it happen in the action function, before dispatching it, or should the store doing it when receiving the action from the dispatcher?
Both cases seam like a violation of the single responsibility pattern. Or should there be two CommentStores, one LocalCommentStore and a ServerCommentStore that both handle the addComment action?
|
In your case Action is responsible for both sending a pending action or optimistic update to the store and sending a call to the WebAPI:
View -> Action -> Pending Action or optimistic update -> Dispatcher -> Store -> emitEvent -> View
-> WebUtils.callAPI()
onWebAPISuccess -> Dispatcher -> Store -> emitEvent -> View
onWebAPIFail -> Dispatcher -> Store -> emitEvent -> View
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "javascript, architecture, single responsibility principle, reactjs flux"
}
|
Event/notification of member modification in C++
class A{
int i;
};
class B{
// sense i is changed by A
};
If the value of `i` is changed by A, then B should get notified. Any suggestion how to implement this?
|
Are you looking for the Observer Design Pattern?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, events, notify"
}
|
"start a bounty" missing
I have a question for which I want to start a bounty. The "start a bounty" is missing.
I checked this before asking here and I learnt that, per user account only one active bounty is allowed. Is only one active bounty allowed per user, all his stackexchange accounts puttogether? However, that - for the moment - is academic interest only, because I checked I have no active bounties on any of my stack exchange accounts.
I read through the page on all about bounties, and found that as regards the age of the question, the lower limit is 2 days which is clear in fact at the moment one posts his question.
But the question in concern was asked in 2012. So is there a tacit upper limit on the age of the question for starting a bounty??
|
You need to have more than 75 reputation.
|
stackexchange-meta_askubuntu
|
{
"answer_score": 6,
"question_score": 2,
"tags": "bug, status bydesign, bounty"
}
|
How to use a project in another project as a module?
I'm hoping to modularize an Android project so it will be easy to maintain in future use. I want to know whether its possible or not, to make an Android project used as a module within another Android project?
For example, let's say in my main android project I have three buttons for login, signup, forget password. and I have three separate projects for login, signup and forget password with their own views, activities and libraries. How can I use these separate android projects in the main Android project so when I click any of the three options in the main activity view so it will load the relevant view from those three module projects? (click the login button in the main view and load login view from the separate login project activities). I have tried to fiddle with build files and library module importing but couldn't do it. help me with saying if this approach is possible or not? if possible how to achieve it?
|
**settings.gradle** in root project include each project.
include ':loginApp'
include ':signupApp'
include ':resetpasswordApp'
project(':loginApp').projectDir = file('path/to/LoginApp')
project(':signupApp').projectDir = file('path/to/SignupApp')
project(':resetpasswordApp').projectDir = file('path/to/ResetpasswordApp')
**build.gradle** Of main module
implementation project(':loginApp')
implementation project(':signupApp')
implementation project(':resetpasswordApp')
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 9,
"tags": "java, android, build.gradle"
}
|
Am I supposed to be able to beat the monsters in the capital?
I just finished Final Fantasy XV, but one thing that has been budging me are the encounters in the final chapter: when you arrive to the crown city.
All the monsters, except the troopers, are ridiculously powerful. They will kill me several times before I can down them. I ended up dodging everyone.
Was I _supposed_ to be strong enough to kill them? To be fair, I rarely did any sidequests nor grinding, but that did not cause me any issues with story-related encounters ever.
|
The boss like monsters around Insomnia are **OPTIONAL** , _so no you are not "supposed" to be able to beat them._
That being said, the underlying question of should you be high enough level to beat them when you arrive is hard to answer. If you just go through the story and avoid most if not all sides quests, then no, you wont be high enough level to tackle them without a great deal of effort.
If you do most or all of the sidequesting before reaching the end of the game, they become manageable, but still difficult.
Realistically, to make them even-ish fights, you need to not only complete most of the side quests, but also make sure to "grind" exp as well. You would need to be around level 70 or 75 to be within a reasonable range of killing ALL of the mobs around Insomnia. Those monsters' levels vary from the 50's to the 80's.
|
stackexchange-gaming
|
{
"answer_score": 3,
"question_score": 1,
"tags": "final fantasy 15"
}
|
Grep exclude line only if multiple patterns match
I want to find lines that do not contain both `"path": "/"` and `"User-Agent": "curl`. Lines that contain only one of those should be included.
In other words, how can I exclude a line only if it matches multiple patterns?
|
These double checks in the same line are better done with `awk`:
awk '! (/"path": "\/"/ && /"User-Agent": "curl/)' file
This uses the logic `awk '! (condition1 && condition2)'`, so it will just fail whenever both strings are found.
### Test
$ cat a
"path": "/" and "User-Agent": "curl
"path": "/" hello
bye "User-Agent": "curl
this is a test
$ awk '! (/"path": "\/"/ && /"User-Agent": "curl/)' a
"path": "/" hello
bye "User-Agent": "curl
this is a test
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "regex, shell, grep, regex negation"
}
|
OpenGL - glGen* and unique identifiers
OpenGL defines a few glGen* functions, for example:
glGenTextures
glGenFrameBuffers
glGenBuffers
Does id generated by glGen function is unique globally or only within a glGen context - for example glGenTextures ?
|
Object names are only unique within a given space of object names. Usually, that means for the object type itself: texture names, buffer names, etc.
The only exception to this are shader and program objects who share the same name space, and thus their names cannot overlap.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "opengl"
}
|
JavaScript remove multiple spaces in a string
Multiple consecutive spaces are causing me a headache in my JS script. I tried doing this:
const originalStr = 'Hello there how are you'
const actual = originalStr.replace(/ /g, ' ')
const expected = 'Hello there how are you'
console.log(`originalStr = '${originalStr}'`)
console.log(`actual = '${actual}'`)
console.log(`expected = '${expected}'`)
console.log(`actual === expected ...`, actual === expected)
But as you can see it's not working. It's failing when there are 3 or more consecutive spaces. Is there a simple way to ensure that there are no consecutive spaces? TIA
|
Just modify your regex slightly:
const originalStr = 'Hello there how are you'
const actual = originalStr.replace(/ +/g, ' ')
const expected = 'Hello there how are you'
console.log(`originalStr = '${originalStr}'`)
console.log(`actual = '${actual}'`)
console.log(`expected = '${expected}'`)
console.log(`actual === expected ...`, actual === expected)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "javascript"
}
|
Mono - Command not found
I'm running `mono 2.10` on `CentOS 5.5` with `Apache 2`. I've installed it already, and am running a `WCF service` on it currently.
But I can't do `mono -V` or `mono program.exe`, which makes me think I installed it incorrectly. The mono binary is in my `/opt/mono/bin/` folder.
What can I do?
|
Try `/opt/mono/bin/mono --version`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, mono, centos"
}
|
MonteCarlo option pricing error estimate
Consider the problem of pricing an option via MonteCarlo with 10000 simulations. If the variance of the simulation is 100, which is the MC estimate of the error on the price?
|
If you are referring to the standard error, i.e. the simulation error, then this can be defined as:
$\frac{\hat{\sigma(M)}}{\sqrt{M}}$
where M is the number of simulations and $\sigma$ is the estimated standard deviation $(\sqrt{\hat{\sigma^2}})$ of the specific simulation run. The “ $\hat{}$” denotes that it is the estimate.
I hope that this will help you.
|
stackexchange-quant
|
{
"answer_score": 0,
"question_score": 0,
"tags": "option pricing, monte carlo"
}
|
iPhone app architecture with tab bars
I have an app that uses a tab bar controller. It has five tabs.
I need to base each tab on a UINavigationController. Do I require another view controller inside the nav controller, or is it valid to have a UINavigationController controlling a regular view?
(I'm guessing the latter but I'm really hitting a wall today getting it to work .. )
|
UINavigationController is created by setting a rootViewController inside it.
- (id)initWithRootViewController:(UIViewController *)rootViewController
That root view controller will control the view.
In your tab bar controller, you can add the UINavigationController.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "xamarin.ios, uitabbarcontroller"
}
|
Expected Value of a Binomial distribution?
If $\mathrm P(X=k)=\binom nkp^k(1-p)^{n-k}$ for a binomial distribution, then from the definition of the expected value $$\mathrm E(X) = \sum^n_{k=0}k\mathrm P(X=k)=\sum^n_{k=0}k\binom nkp^k(1-p)^{n-k}$$ but the expected value of a Binomal distribution is $np$, so how is
> $$\sum^n_{k=0}k\binom nkp^k(1-p)^{n-k}=np$$
|
The main idea is to factor out $np$. I believe we can rewrite:
$$\sum^n_{k=0}k\binom nkp^k(1-p)^{n-k}= \sum^n_{k=1} k\binom nkp^k(1-p)^{n-k}$$
Factoring out an $np$, this gives (and cancelling the $k$'s):
$$\sum^n_{k=1} k\binom nkp^k(1-p)^{n-k} = np \sum^n_{k=1} \dfrac{(n-1)!}{(n-k)!(k-1)!}p^{k-1}(1-p)^{n-k}$$
Notice that the RHS is:
$$np \sum^n_{k=1} \dfrac{(n-1)!}{(n-k)!(k-1)!}p^{k-1}(1-p)^{n-k} = np \sum^n_{k=1} \binom {n-1}{k-1}p^{k-1}(1-p)^{n-k},$$
and since $\displaystyle \sum^n_{k=1} \binom {n-1}{k-1}p^{k-1}(1-p)^{n-k} = (p + (1-p))^{n-1} = 1$, we therefore indeed have
$$\sum^n_{k=0}k\binom nkp^k(1-p)^{n-k} = np$$.
|
stackexchange-math
|
{
"answer_score": 66,
"question_score": 45,
"tags": "probability, combinatorics, probability distributions, binomial coefficients"
}
|
Codeigniter get id on same form
I have this problem,on the same form,i want to get the id from saved value. i already make some example on JS Fiddle
JS Fiddle :
Detailed Process :
1.Input Value on Form 1-3.
2.Save Value to database and get the auto incremented ID
3.Click Next,and use the ID from previous saved value (this is the question i want to ask).
Any Tips for doing this ?
|
This will give you the last insert ID
$this->db->insert_id();
Just redirect the user with correct URL by getting the LAST_INSERT_ID
redirect('controller/method/LAST_INSERT_ID', 'refresh');
The URL might Look something like this
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, codeigniter"
}
|
Is a DLL with only constants needed in distribution?
I've created two executable projects which depend on a single class library.
The class library contains only classes and constants (no variables or functions), and is used to store application-level protocol information for communication between the two executable projects.
When testing my two programs, I notice that they run without needing the class library (DLL) located in the same directory.
What is happening here? Do I need to distribute the DLL if only constants are used from it?
|
If they are _genuine_ constants, introduced with `const`, then the value of each constant will be inlined where it's used. For example, if you have:
// Assembly1
public static class Constants
{
public const string Foo = "Hello";
}
// Assembly2
public class Test
{
static void Main()
{
Console.WriteLine(Constants.Foo);
}
}
... then the value "Hello" will be inlined into Assembly2 and you don't need Assembly1 to be present. No code will refer to it, even if it's still listed as a reference within Assembly2.
However, if you ever access the constants by _reflection_ (which is entirely reasonable) then you would want to have Assembly1 present.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, dll, compilation, constants"
}
|
Date labels intersecting
I'm using `Matplotlib` to plot data on `Ubuntu 15.10`. My y-axis has numeric values and my x-axis timestamps.
I'm having the problem that the date labels intersect with each other making it look bad. How do I increase the distance between the x-axis ticks/labels to be evenly spaced still? Since the automatic selection of ticks was bad I'm okay with manually setting the amount of date ticks. Any other solution is appreciated, too.
Besides, I'm using the following `DateFormatter`:
formatter = DateFormatter('%m/%d/%y')
axis = plt.gca()
axis.xaxis.set_major_formatter(formatter)
|
You could add the following to your code:
plt.gcf().autofmt_xdate()
Which automatically formats the x axis for you (rotates the labels to something like 30 degrees etc).
You can also manually set the amount of x ticks that show on your x-axis to avoid it getting crowded, by using the following:
max_xticks = 10
xloc = plt.MaxNLocator(max_xticks)
ax.xaxis.set_major_locator(xloc)
I personally use both together as it makes the graph look much nicer when using dates.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, matplotlib"
}
|
What is the best approach on upgradation of a mule integration application from mule runtime 1.4 to 2.0 and java 8 to java 11?
I am currently involved in a project, that requires migration of 3.5 to 4.x, 4.14 is working fine. I am raising this question because, mule 2 is supporting Java 11, while mule recommended approach is to work on adoptopenjdk 8.0
<
|
It is not clear exactly what is the question, however migrating from Mule 4.1.x to 4.2.x doesn't require usually changes to applications. You are free to use Java 8 or 11, though 8 is recommended.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mule, anypoint studio, mule esb, mulesoft"
}
|
What would happen if 2 different photons overlap each other while travelling in the same direction?
Imagine 2 photons with same wavelength but from different sources overlap each other and since they don't interact with each other I like to know if there is any changes to their wavelength vs solo? Consider only low energy for simplicity. I was thinking they become brighter but then that can only work if they travel side by side so only conclusion is their momentum adds up and no change in frequency right?
|
Your reasoning is correct. As you stated, the two photons will not interact with each other. If overlapping changed their frequencies it would constitute interaction-- and so there is no frequency change. The momentum of the two photons is just the sum of their individual momenta, and the energy of the two is just the sum of their individual energies.
The above is true in a vacuum. However, in a material medium photons _can_ interact in various ways, including changing frequencies, exchanging momenta and energy, and so on.
|
stackexchange-physics
|
{
"answer_score": 2,
"question_score": 0,
"tags": "photons, quantum electrodynamics, wavelength, superposition"
}
|
How to calculate the volume between two cylinders
I am asked to calculate the volume between the two cylinder : $x^2+y^2=1$ and $x^2+z^2=1$
So my assumption here that the limit of $y$ and $z$ must be equal, and we are looking on the unit circle so the integral needs to be:
$$\int_{0}^{1} \int_{0}^{1} \int_{0}^{1} 1 dx\,dy\,dz$$
but the answer is just one and this is doesn't make sense (intuitively) because the radius it self is 1 and what I imagine in my head is that the marked domain is the line between $x=1$ and $x=-1$
|
I've attached a plot of the problem shown in the $xy$-plane. The red circle is a circular cross section of the cylinder $x^2+y^2=1$ where $z=0$, and the blue rectangle is a rectangular cross section of the cylinder $x^2+z^2=1$ where $z=0$ as well. We can see here then that we might choose to integrate from $z=-1$ to $z=1$, and we can determine the bounds of the $x$ and $y$ integrals by using the boundary conditions for the cylinders:
$$ x^2+z^2=1 \\\ x=\pm \sqrt{1-z^2} $$
and
$$ x^2+y^2=1\\\ y=\pm\sqrt{1-x^2} $$
So, the integral is:
$$ \int_{-1}^{1}\int_{-\sqrt{1-z^2}}^{\sqrt{1-z^2}}\int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}}\text{d}y\text{d}x\text{d}z $$
!Plot of the problem
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "calculus, integration, multivariable calculus"
}
|
Issue converting Data frame datatype from object to float64
I need to convert the datatype of y_test from object to float64. I first converted into an array of strings ( **In[54]** ) and then to an array of floating point numbers ( **Inputs [83] & [85]**) but it is not added to the y_test data frame.
y_test feature CO(ppm) is still displayed as _object_ datatype ( **Out[90]** ).
**Can someone please help me understand how to accomplish this? Thank you.**
).astype(float)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "arrays, python 3.x, pandas, numpy, dataframe"
}
|
Handling the export in eclipse thru a plugin
I have a java application that have different settings and dependency versions depending on the company branch it is install in.
So what I did is to create a plugin that create an item in the right click context menu of the project in eclipse to make these changes.
However I am wondering if its possible to catch the OnExport event of eclispe (if it exists) and do this automatically everytime the solution is exported.
Would this be possible?
Many thanks
|
If I understand what you're asking correctly, the Eclipse way to do this would be to write a Builder and add it to the project; then the settings file would be rebuilt whenever it's appropriate, making an up-to-date version always available to export. Here is a good place to start learning about how to do this.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, eclipse, plugins"
}
|
How do I get values of input element with the same name as an javascript array?
I want to get values of the input element that those elements are under the same name, name="items[]"
for example:
<div>...<input type="text" name="items[]" value="1" /></div>
<div>...<input type="text" name="items[]" value="2" /></div>
<div>...<input type="text" name="items[]" value="3" /></div>
And I wish to get the result something like:
[1, 2, 3] //that store in an javascript variable.
Do I need to do a loop to access all the elements to get its value? Please give me a good solution either javascript or JQuery.
Thanks
|
var values = [];
$("input[name='items[]']").each(function() {
values.push($(this).val());
});
|
stackexchange-stackoverflow
|
{
"answer_score": 38,
"question_score": 10,
"tags": "javascript, jquery"
}
|
Using null inside Coldfusion Array
I'm creating a array and need use null values
<cfset addLinha[1] = qEspecialidades.especialidade>
<cfloop index="i" from="1" to="#numColumnsAntes#">
<cfset arrayAppend(addLinha,null)>
</cfloop>
<cfset arrayAppend(addLinha,LSParseNumber(LSNumberFormat(AvgNota, "_.__")))>
<cfloop index="i" from="#numColumnsDepois#" to="#qEspecialidades.RecordCount#">
<cfset arrayAppend(addLinha,null)>
</cfloop>
I need a array something like this
["Especialidade",null,null,null,null,4.0,null,null,null]
But I haven't found how to append `null`.
|
ColdFusion does not have a null per se. Depending on what uses this variable, one or more of the following may be useful:
* Use a javaNull: `<cfset javaNull = javaCast( "null", 0 ) />`
* Use a blank: `""`
* Use an empty struct ie `{}`
Ben Nadel has some comments on this too.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "arrays, coldfusion, null, coldfusion 9"
}
|
How to call a function from another function
So I'm writing two functions, each is responsible for validating a textfield, one is for a phone number and the other name. I have both functions working, but Not sure how to call both of them from one button "calculate". I was wondering if I could somehow call the chkPH() function from my chkName() function, in its else statement. Like so:
function chkName()
{
if(not valid)
{error}
else { go to chkPH() function }
}
|
You call it same as from anywhere, by putting parentheses after its name:
function chkName() {
var valid = ...;
if (!valid) {
... error ...
}
else {
chkPh();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript"
}
|
What is $I$ in the noise described in the paper "Parameter Space Noise for Exploration"?
In the paper Parameter Space Noise for Exploration, the authors describe the noise that they add to the parameter vector as:
$$ \tilde{\theta} = \theta + \mathcal{N}(0, \sigma^2I) $$
is $I$ simply the identity matrix, or am I missing something?
|
Yes, since $\tilde{\theta}$ is a vector, to define its distribution one needs a covariance matrix. Here $I$ is the identity matrix, which means that the noise has a zero-mean normal distribution with standard deviation $\sigma$, and different components of this noise are uncorrelated.
|
stackexchange-ai
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reinforcement learning, notation"
}
|
how to output a component in angular that is provided via @Input()?
I am implementing a popup modal component. It receives a component via `@Input()` that should be displayed inside the popup component.
Current code is:
export class PopupComponent implements OnInit {
@Input()
component: any;
constructor() {}
ngOnInit(): void {}
}
template:
<div class="popup">
<div class="popup__content">
<a class="popup__close">X</a>
<div [outerHTML]="component"></div>
</div>
</div>
And when I provide a component like: `<app-popup [component]="MyTestComponent"></app-popup>`
I get an output of the component definition like: `class MyTestComponent implements OnInit ...` But I want to see it's template.
What is the solution?
|
You cannot pass components through an `Input`. You should read about transclusion and use of the `ng-content` tag.
Your component template should look like this:
<div class="popup">
<div class="popup__content">
<a class="popup__close">X</a>
<ng-content></ng-content>
</div>
</div>
Then you can use your component like this:
<PopupComponent>
<my-component></my-component>
<!-- Or any content... -->
<p>Anything</p>
</PopupComponent>
What is between the `PopupComponent` tags will be inserted where the `ng-content` tag is in your PopupComponent template.
If the content needs to be created dynamically you can also use Angular's dynamic component loading.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "angular"
}
|
Regex replace 'whole' decimal numbers not followed by a certain string
I want to replace "whole" decimal numbers not followed by `pt` with `M`.
For example, I need to replace `1`, `12`, and `36.7`, but not `45.63` in the following.
string exp = "y=tan^-1(45.63pt)+12sin(-36.7)";
I have already tried
string newExp = Regex.Replace(exp, @"(\d+\.?\d*)(?!pt)", "M");
and it gives
"y=tan^-M(M3pt)+Msin(-M)"
It does make sense to me why it works like this, but I need to get
"y=tan^-M(45.63pt)+Msin(-M)"
|
The problem with the regex is that it is still matching a portion of the decimal value `45.63`, up to the second-to-last decimal digit. One solution is to add a negative lookahead to the pattern to ensure that we only assert `(?!pt)` at the real end of every decimal value. This version is working:
string exp = "y=tan^-1(45.63pt)+12sin(-36.7)";
string newExp = Regex.Replace(exp, @"(\d+(?:\.\d+)?)(?![\d.])(?!pt)", "M");
Console.WriteLine(newExp);
This prints:
y=tan^-M(45.63pt)+Msin(-M)
Here is an explanation of the regex pattern used:
( match and capture:
\d+ one or more whole number digits
(?:\.\d+)? followed by an optional decimal component
) stop capturing
(?![\d.]) not being followed by another digit or dot
(?!pt) not followed by pt
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, regex"
}
|
pl sql how to get the day of the week for oracle db date
I have oracle date , I want to translate it to my date , for instance 24.7.2011 is sunday so i want a function to return 1 , for 25.7.2011 I want it to return 2 and so on...
I have been searching the wwb for examples but with no successes please help me.
|
The Oracle function for this is TO_DATE with the 'D' format model:
SQL> select to_char (date '2011-07-24', 'D') d from dual;
D
-
7
As you can see, this returns 7 for Sunday, not 1, when I run it. The value returned varies according to your NLS settings. If necessary you could do this to get what you want:
SQL> select to_char (date '2011-07-24'+1, 'D') d from dual;
D
-
1
More details about Oracle's date format models can be found here
|
stackexchange-stackoverflow
|
{
"answer_score": 34,
"question_score": 12,
"tags": "sql, oracle"
}
|
Vim Return to last point in file
can anybody provide an explanation as to what this is doing or point me to vimdocs? `line("'\"")`
function! ResCur()$
if line("'\"") <= line("$")
normal! g`"
return 1
endif$
endfunction
the function is for returning the caret to the same line when opening a file.
|
The `"` is escaped with a backslash because `'"` is surrounded with double quotes.
`:help '"` says:
To the cursor position when last exiting the current
buffer. Defaults to the first character of the first
line. See last-position-jump for how to use this
for each opened file.
Only one position is remembered per buffer, not one
for each window. As long as the buffer is visible in
a window the position won't be changed.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "vim, vimrc"
}
|
How to use lapply to find closest value in a list in R?
I'm trying to find the model-predicted value closest to a real observed value within a large dataframe. I believe I need to use lapply, but I'm really not sure. Thanks in advance, SE, and sorry if this is a repeat of a previous post, I looked.
df <- data.frame(pred = rnorm(50, mean = 100, sd = 10),
cand = I(replicate(50, exp = I(list(rnorm(6, mean = 100, sd = 10))))))
So far, I've come up with a 1-line function that works when run on a single row, but I have two problems:
df$closest <- sapply( df, function(x) { which.min( abs( df$pred[x] - df$cand[[x]] ) ) } )
1. This function won't work on the full list, probably because I am new to the apply family.
2. This function returns a list position, not the actual value, which is what I need.
`Error in df$cand[[x]] : no such index at level 1 `
|
`apply` allows us to operate on the rows, or the columns, because you are looking to loop through the rows, a margin of 1 (rows) should get the job done!
We could use `apply`:
df$closest <- apply( df,MARGIN = 1, function(x) { which.min( abs( x$pred - x$cand ) ) } )
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "r"
}
|
More than one type at once in JSON-LD notation
Is it valid by format conventions to use more then one type in JSON-LD notation? Like here:
{
"@context": "
"@type":
[
"MusicalEvent",
"CreativeWork"
],
"name": "Name",
"url": "
}
Thanks!
|
Yes, it's perfectly valid to use more than one type. If it makes sense, they don't even need to be from the same vocabulary (e.g. schema:Person and foaf:Person).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "microdata, linked data, structured data, json ld"
}
|
Hotel Reservation Request Booking Paypal PHP
I'm making a website for a small hotel in php. The hotel owners want a reservation system that uses paypal. They want people to see a calendar and choose a date to make a reservation. If the day has vacancy, they want the user to request booking a room. This would then require the hotel owner to accept the purchase.
I have not worked on a project that has this "request to purchase" method of buying with paypal. Is this possible? Does anyone know of an open php system that handles this?
|
There are a couple of popular WordPress themes with booking systems built in:
* HotelPress
* HotelBooking
|
stackexchange-webmasters
|
{
"answer_score": 3,
"question_score": 3,
"tags": "php, looking for a script, paypal"
}
|
Is there a .gitconfig pull option to always fetch annotated tags?
Git 2.4.1 introduced the `push.followTags` option, which will automatically push your annotated tags. That is, it makes every `git push...` equivalent to `git push --follow-tags...`, which is exactly what I want.
But I can't figure out how to get the same behavior when pulling. That is, I would like every
git pull
to be equivalent to:
git pull && git fetch --tags
Is there any option that accomplishes this?
|
As I mentioned in "Does “`git fetch --tags`” include “`git fetch`”?", since git 1.9+; `git fetch --tag` includes `git fetch` \+ the tags.
And `git pull --tags` would also include them.
So adding `--tags` is the surest way to get the tags in addition of what `git fetch/pull` is normally getting from the remote.
But by default, tags are not fetched automatically, to avoid polluting the tags namespace of the local repo, especially with the default refspecs `+refs/heads/*:refs/remotes/origin/*` which fetches `heads` only.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "git"
}
|
Organize desktop by name in Nemo
I'm using Nemo as my file manager and when I press the right mouse button the only option to sort my Desktop is by Name.
!right click Desktop menu
Is it possible to sort by other values, like Date Modified?
|
This is probably not possible.
Nemo is a fork of nautilus.)
When I right click on my desktop, I can't see a sort by anything else either:
!Nautilus right click menu
Have a look at this answer.
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 1,
"tags": "14.04, nautilus, nemo, file sorting"
}
|
Is it Bottling Time?
My bitter has been fermenting for 9 days now and I think it's time to bottle? Temp is fine and gravity is 1.006 for 3 days running,just in the bottling mark. No activity now, just a small amount of froth for the last 3 days.!enter image description here
|
Yes. It's at a stable gravity that's a reasonable terminal gravity for that style (1.006 is a _little_ dry for a bitter, but just a little). The krausen has fallen back into the beer, which is why there's just "a little froth" and "a small head". It's bottling time.
|
stackexchange-homebrew
|
{
"answer_score": 3,
"question_score": 1,
"tags": "secondary fermentation"
}
|
How to sort sequence based on a coroutine?
With a naive implementation like:
import asyncio
async def get_priority(value):
# Simulate sending out network request.
await asyncio.sleep(0.5)
return value
values = [1, 2, 3]
sorted_values = await sorted(values, key=get_priority)
(assume that the top-level `await` was wrapped in an `async def`)
`sorted` assumes that the key function is synchronous, and it will try to compare the coroutines themselves instead of the underlying values, leading to a `TypeError`.
How can I sort a sequence when I want the key function to be a coroutine? I could write the `sorted` implementation myself, but specifically wondering if I can somehow extract the asynchronous key computations outside of `sorted` using `asyncio`, so I can stick to standard lib.
|
Ended up stumbling upon Implement async/await in sort function of arrays javascript, which referenced a Schwartzian transform, where the priorities to sort the values by are precomputed and stored alongside the original values. Below is an implementation in Python:
import asyncio
from operator import itemgetter
async def get_priority(value):
# Simulate sending out network request.
await asyncio.sleep(0.5)
return value
values = [1, 2, 3]
value_priorities = await asyncio.gather(*map(get_priority, values))
sorted_values = [value for value, _ in sorted(
zip(values, value_priorities),
key=itemgetter(1)
)]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, sorting, asynchronous, async await, python asyncio"
}
|
How to add a downloaded .box file to Vagrant?
How do I add a downloaded `.box` file to Vagrant's list of available boxes? The `.box` file is located on an external drive.
I tried running `vagrant box add my-box d:/path/to/box`, but Vagrant interprets the path as a URL.
|
## Solution:
vagrant box add my-box file:///d:/path/to/file.box
Has to be in a URL format.
|
stackexchange-stackoverflow
|
{
"answer_score": 204,
"question_score": 133,
"tags": "windows, vagrant"
}
|
How to run R programs on multicore using doParallel package?
I am running SVM algorithm in R.It is taking long time to run the algorithm.I have system with 32GB RAM.How can I use that whole RAM memory to speed my process.
|
I would add a comment but I do not have enough reputation points. I might suggest Using "R revolution open". It is a Build of R that includes a lot of native support for multi-core processing. I have not used it much as my computer is very old, but it is defiantly worth looking at. Plus it is free.
|
stackexchange-datascience
|
{
"answer_score": 1,
"question_score": 3,
"tags": "r"
}
|
android: how to pass values from one broadcast receiver to another?
i have this broadcastreceiver that executes some code from time to time and triggers itself again by setting a timer (alarmmanager). the result of the calculations is an integer value, which should be used as input for the next time the algorithm is executed. therefore, i need to store this value.
i don't want to do this with SQLite as this would produce an enormous overhead - but what are the alternatives? manage this via shared preferences? store it within files?
any good ideas?
|
Carry the data around in the PendingIntent you specify to the AlarmManager. However, instead of a repeating alarm, you might need to set a new alarm each time.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
}
|
What were the tripods spraying and what does it have to do with the red weed in War of the Worlds?
in the remake of War of the Worlds (2005), what exactly were the aliens spraying on the ground after they captured and drained a human?
I understand that a human gets captured, the aliens suck everything out of them but what are the tripods spraying on the ground and what does it have to do with the red-weeds which are seemingly taking over? How does this benefit the aliens?
!Red weeds
|
The red mist was blood. That's why Tom Cruise's character was so freaked out when he saw it running down the walls in the basement. The tripods were essentially grinding up the humans and spraying the pulp on the ground.
In the book, along with the fighting tripods, there were harvester machines that gathered the humans and placed them in metal baskets. The captured humans were processed and injected directly into the alien's veins for food.
This film version kind of mixed the two machines into one, whereas the original never even touched on it.
The red-weed you're questioning about resembled a veinous system in appearance. I did read somewhere that it was actually supposed to be Martian vegetation, although the film never explicitly says that.
|
stackexchange-movies
|
{
"answer_score": 22,
"question_score": 21,
"tags": "plot explanation, war of the worlds"
}
|
If you are on waivers and under contract in the NFL can you get credit for serving a suspension?
For example, if Johnny Manziel is under contract with Cleveland for the 2016 season, he will likely get put on waivers and a suspension from the NFL.
Will he get credit for serving a suspension (e.g. 4 games) while he is on waivers?
|
NFL suspensions, when for a particular number of games, do take place even when as a free agent.
For example, Laron Landry was suspended for the first 10 games of the 2015 season for PED use; after week 10 he was reinstated despite not being on a team's roster for that period of time. (He was subsequently suspended again, of course... some people never learn.)
So, if Manziel is suspended a specific number of games (say, 6) for his domestic violence incident, he would serve those regardless of whether he was on a team's roster or not.
However, in some cases the Commissioner will suspend a player "indefinitely" (for example, another popular Browns player, Josh Gordon, is suspended indefinitely, but can apply for reinstatement after a year). The commissioner likely has more leeway in those cases.
|
stackexchange-sports
|
{
"answer_score": 2,
"question_score": 1,
"tags": "nfl, suspension"
}
|
Lazy tips ? (Like Visual Studio)
I recently discover Löve and Zerobrane, I come from VB.NET on Visual Studio 2013/17 and I look for configure some tricks.
After some search, I write this in system preferences :
acandtip.fillups = " +-*/%.,(){}[]"
Whith it, auto complete is quick (generally, I accept suggestion and I use these keys to continue my line)
But I don't find preferences for this : When I write "if true" and I press Enter, Visual Studio automaticaly write :
if true then
--my cursor is here
end
(Same trick on function, for, etc ...)
Another trick that I don't find : When I write "a=b+c", Visual Studio automaticaly write :
a = b + c
It's very usefull when you read your code ;)
I'm french, maybe I don't find correct words on google to find these preferences.
Thanks for your read and maybe for your help :D
|
ZeroBrane Studio doesn't automatically add those whitespaces and doesn't add `then end` snippets when typing `if true` in the current version.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "zerobrane"
}
|
What does accuracy mean in SPSS's automatic linear modeling output?
When running the Automatic Linear Modeling function of SPSS version 20, it will return an accuracy value.
The higher the accuracy, the more predictive the model (I assume). However, what does this accuracy really indiciate?
Is it the R2? Adjusted R2? Something else?
|
I believe that it is the adjusted R2, but you can check this by using a regular REGRESSION command that matches your linear specification to see if the statistics match.
HTH
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 2,
"tags": "regression, spss"
}
|
julia: how to read a bz2 compressed text file
In R, I can read a whole compressed text file into a character vector as
readLines("file.txt.bz2")
`readLines` transparently decompresses .gz and .bz2 files but also works with non-compressed files. Is there something analogous available in julia? I can do
text = open(f -> read(f, String), "file.txt")
but this cannot open compressed files. What is the preferred way to read bzip2 files? Is there any approach (besides manually checking the filename extension) that can deduce compression format automatically?
|
I don't know about anything automatic but this is how you could (create and) read a bz2 compressed file:
using CodecBzip2 # after ] add CodecBzip2
# Creating a dummy bz2 file
mystring = "Hello StackOverflow!"
mystring_compressed = transcode(Bzip2Compressor, mystring)
write("testfile.bz2", mystring_compressed)
# Reading and uncompressing it
compressed = read("testfile.bz2")
plain = transcode(Bzip2Decompressor, compressed)
String(plain) # "Hello StackOverflow!"
There are also streaming variants available. For more see CodecBzip2.jl.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "julia, compressed files"
}
|
boto3 sqs incorrect url when not specified endpoint url
Do I always need to specify `endpoint_url` when creating boto3 client? Why can't I specify `QueueUrl` as method argument?
# boto3==1.16.51
import boto3
client = boto3.client('sqs')
messages = client.receive_message(
QueueUrl='
WaitTimeSeconds=2,
MaxNumberOfMessages=1,
AttributeNames=["All"],
)
Exception:
> botocore.exceptions.ClientError: An error occurred (InvalidAddress) when calling the ReceiveMessage operation: The address < is not valid for this endpoint.
Seems like it takes default values for sqs queue. But why it does not take value from `QueueUrl`
|
The url from the error msg is different then `QueueUrl` because AWS CLI and boto3 use **legacy endpoint** , one of which is `eu-central-1.queue.amazonaws.com`. From docs:
> If you use the AWS CLI or SDK for Python, you can use the following **legacy endpoints**.
You can check this using:
print(client._endpoint)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "python, boto3, amazon sqs, boto"
}
|
How to fit a div exactly onto an underlaying image - the div is always slightly bigger in height
I've built a simple example pen: < I have a large image going completely across the whole container width. My goal was to get a div containing a headline and text to overlay one half of the image (in the example I've covered it completely).
Problem is I've assigned an height of `100%` to the overlay div which refers to the parent article element - now the overlay is slightly higher than the image.
Guess it is due to the context.
Is there an elegant way to solve and work around that issue?
|
I think that the following works:
img {
width:100%;
max-width: 100%;
height:auto; //!important;
vertical-align: top;
}
`img` is inline and has a small space below it due to line leading.
Adding `vertical-align: top` fixes it.
See demo at: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "html, css"
}
|
How to create an incremental list using shortcodes?
Right now I'm creating shortcodes like this:
function short_code($atts) {
$a = shortcode_atts( array(
'name' => ''
), $atts );
return '<div class="content">
<div class="container">
<p>' . esc_attr($a['name']) . '</p>
</div>
</div>';
}
add_shortcode( 'short-code', 'short_code' );
// Usage: [short-code name="John"]
How to do it so I can have incremental shortcodes? In other words, to modify the shortcode so I can do this? `[short-code name="John" name="Jack" name="Mary"]` and produce something like this?
<div class="content">
<div class="container">
<p>John</p>
<p>Jack</p>
<p>Mary</p>
</div>
</div>
I searched on Google but I couldn't find anything.
|
What you want is to use shortcode attributes. I Googled "wordpress shortcode attributes" and found the sample code below in the WP Codex
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
You would want to pass an array for the example you show in your question
[short-code names="John", "Jack", "Mary"]
You can get the list of names by following the sample code and accessing the names array:
foreach($a['names'] as $name){
echo "<p>$name</p>";
}
Edit: Just to be clear you would get the array from args as such:
$a = shortcode_atts( array(
'names' => 'names'
), $atts );
|
stackexchange-wordpress
|
{
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
}
|
Using libtool and autoconf
I am working on a system where libraries are installed with libtool (I just discovered libtool) and it seems to be a powerful tool like autotools.
My problem is that I am not able to link my programs using autoconf and automake. After some googling and stackoverflowing, I found how to link my program manually with libtool.
My question is, how to use libtool with autoconf? What are the commands to add in configure.ac and/or Makefile.am? I also found the lazy solution of copying the dependency from the .la file and put it in configure.ac, but I think it is the wrong solution.
I usually work on a system where I have the root permissions, so I am usually lazy and always install many things at system level, and everything always run smoothly until today where I am on a system where I do not have root privileges.
|
After more googling, I found the solution.
1) Add the macro LT_INIT to configure.ac
LT_INIT(static)
There are many other options, see <
2) Add the variable progname_LDADD to Makefile.am
progname_LDADD = library_name.la
where progname is defined in
bin_PROGRAM = progname
There are certainly things that I am missing, but it is working for now. Any suggestion is welcome.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linker, autoconf, automake, libtool"
}
|
Run playbook on multiple users on a server
I have inventory file which has multiple users for a server, like below.
[TEST]
server1 ansible_user=user1
server1 ansible_user=user2
server1 ansible_user=user3
server1 ansible_user=user4
When I run playbook using this inventory, it only runs on "server1 ansible_user=user4", ignoring first 3 users. How can I run playbook on all 4 users?
|
With this inventory you have **one** inventory entry `server1` and with each new line you override `ansible_user` variable.
If you really want (what is the use case) to make this happen, use host aliasing:
[TEST]
s1_u1 ansible_host=server1 ansible_user=user1
s1_u2 ansible_host=server1 ansible_user=user2
s1_u3 ansible_host=server1 ansible_user=user3
s1_u4 ansible_host=server1 ansible_user=user4
But be prepared to possible concurrency issues, like APT lock for example.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "ansible, ansible inventory"
}
|
Explain why these two multi-dimensional arrays seem like valid syntax yet only one gives expected results?
I've just realised the error of my ways in a bit of code that fills up a c 2 dimensional array.
I declared the array like this:
int myArray[5][5];
..but mistakenly set a value with:
*myArray[3,4] = 10;
..when it should have been:
myArray[3][4] = 10;
Ok, the first line is a mistake but it compiled and ran, albeit with very strange results. (ie, when I tried to print out the contents of *myArray[3,4], it had the wrong value in)
**Can someone explain what exactly that first assignment statement is _doing_?**
edit: I originally tried to use:
myArray[3,4] = 10;
..which threw a compiler error about me trying to assign an int to a *int type. I guess it evaluated 3,4 to 4 as per the answer below and figured that I was trying to add 4 to a pointer so should be using pointer addressing to access the array.
|
Comma has value of the second espression: (a,b) is b: <
`*myArray[3,4]` is like `*myArray[4]`
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "c, arrays, multidimensional array"
}
|
Combine Tuple and Tuples Tag
Does it make sense to combine the tuple and tuples tag on SO? Or make Tuples a synonym of Tuple?
|
ok, I merged into tuples and set up a synonym. We typically prefer the plural form of the tag.
|
stackexchange-meta
|
{
"answer_score": 2,
"question_score": 8,
"tags": "discussion, status completed, tag synonyms"
}
|
Is there a way to have code run on a time schedule in an ASP.NET web app?
I have an ASP.NET web app providing access to a database on the server. What I need is a way to run code in the background on a given schedule that auto-updates the server database from another source.
I know how to do this in a windows app by adding a timer, linking up a function to the timer tick event and starting the timer. I do not know how to do this in a web app.
Is there a start-up event for a web app or somewhere where I can start this background process regardless of whatever any users are doing on the site?
|
You should not do this in an ASP.NET website - this is a major no-no. You are correct in thinking to use a timer on a background .exe. You should look into creating either a Windows Task (a console .exe executed by the server task timer), or a Windows Service. I would suggest the Windows Service as that is standard practice.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "c#, asp.net, scheduled tasks"
}
|
One assert with multiple condition vs multiple assert
In java, If I need to ensure multiple conditions, I can write in two ways as using single assert with all condition vs using separate assert for each condition. Which one is better approach?
Example: Suppose we have three condition need to be ensured as cond1, cond2, cond3.
Using single assert
`assert cond1 && cond2 && cond3;`
Using multiple assert
`assert cond1;` `assert cond2;` `assert cond3;`
|
Multiple assert statements. One for each condition will help you easily determine which condition failed, in case there's a problem.
With a single assertion statement for all conditions, you will have to as a next step identify which condition failed. As test will just say that assertion failed but what exactly failed still needs to be determined.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, assert"
}
|
regex not fulfilling full condition
I am currently using regex to remove `www.` from any url entered into a text area. I ahve done this the following way:
var input = document.getElementById("tweet_text");
input.onkeyup = function() {
input.value = input.value.replace(/www\.*/,"");
}
When a URL is copied and then pasted into the textarea, the regex does it's job.
If i was to manually enter a url it doesnt remove the `.`. I get to the last `w` and then the `www` gets removed allowing me to continue to type. Obviously the next character will be a `.` which will remain there, and end up with something like this:
When it should look like this:
Any ideas on how to resolve this?
|
That's happening because `.*` also matches an empty space (0 or more repetition). So, `www\.*` will successfully match `www`, and replace it. And then when you go on to type `.`, it won't match the pattern, and hence won't be replaced.
Try using `www\.+` or `www\.` instead:
input.value = input.value.replace(/www\.+/,"");
or:
input.value = input.value.replace(/www\./,"");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, regex"
}
|
rails grouping an array of hashes
i know this is a simple question but its so frustating for me, i tried many hours and i didnt make it, so i hope can find the answer,
i have array of hashes like this
array = [{date: 1, branch: 1, value: "100"}, {date: 1, branch: 2, value: "200"}, {date: 2, branch: 1, value: "500"}, {date: 3, branch: 2, value: "500"}, {date: 3, branch: 3, value: "300"}]
and i want to grouping it like this
data = [{date: 1, 1: "100", 2: "200"}, {date: 2, 1: "500"}, {date: 3, 2: "500", 3: "300"}]
in the array = [{date: 1, branch: 1, value: "100"}, i want to take the value of branch and value and combine it like this 1: "100"
anyway i can do that, there is no problem if there is using loop or case when method
|
Probably could be shortened, but it works:
array.group_by { |h| h[:date] }.map do |k, v|
[:date, k, *v.map { |h| [h[:branch], h[:value]] }]
end.map { |x| Hash[*x.flatten] }
# => [{:date=>1, 1=>"100", 2=>"200"}, {:date=>2, 1=>"500"}, {:date=>3, 2=>"500", 3=>"300"}]
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ruby on rails, arrays, hash"
}
|
Mysql JDBC driver ClassNotFoundException
I can't register Mysql JDBC driver in my desktop APP
I download mysql-connector-java-5.1.16.zip
Unzip **mysql-connector-java-5.1.16-bin.jar** and put it into **lib** folder in my app
Add this jar file into Build Path in Eclipse
But Class.forName("com.mysql.jdbc.Driver") throws ClassNotFoundException
Whats wrong?
!enter image description here
|
try this:
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
}
The issue is that `Class.forName(String)` throws an checked exception. With a checked exception, you can either:
1. Catch the exception.
2. Declare that your method throws the exception. (which is what I suggested above).
Here is an example of catching the exception:
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
//do some exception handling
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, mysql"
}
|
How to apply SCSS based on browser language in Angular?
I am trying to apply `SCSS` based on browser language. On inspecting i am getting browser language in `<html lang = "de">` and on css `html[Attributes Style] {-webkit-locale: "en";}`like this.
How can I apply CSS on different classes based on the page language?
|
Could you try this trick?
html[lang="de"] {
//your styles
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "css, angular, typescript, sass"
}
|
What does the "ONET" in ONET.xml stand for?
In SharePoint, a file named ONET.xml is usually needed when creating a custom site definition. Out of curiosity, does anyone know what ONET stands for?
|
It stands for Office Net.
per this blog entry.
> On a side note: I heard that Onet stands for Office Net.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "sharepoint"
}
|
object creation in flex
We create Objects in flex by declaring type Object. for example
var objSampleObject:Object = new Object();
and we create properties directly with dot operator without creating any class
objSampleObject.name="xxx";
objSampleObject.id=123;
My question is in above process is there any class is created internally by flex?
|
Yes a class is created internally, not by Flex, but by the Flash runtime. Is there any reason why you need to know that?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apache flex, actionscript 3, class, object"
}
|
Encryption at Rest: AWS Elasticsearch
I'm trying to use AWS Elasticsearch with "Encrytion at Rest". I configured this setting while creating the Elasticsearch domain in Elasticsearch services in AWS.
Lets consider there are two users named A and B. I have created the KMS access policy where
1. User A is having permission to perform both es:* and kms:* actions
2. User B is having permission to perform only es: _,but not kms:_ actions.
Here, When ES Client is performing indexing and search some data as User A, Then it works. When ES Client is performing indexing and search some data as User B, Then also it works. But I expect this to fail as User B don't have access to kms:encrypt or kms:decrypt and other kms actions.
Any leads would be greatly appreciated.
|
The "Encryption at Rest" is more of a systemic feature than a user-based one. The IAM Role used for Encryption at Rest applies more to the Service and is not meant to be used as an access control for users.
Hope this clears up the confusion here.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "amazon web services, elasticsearch, encryption"
}
|
Whats Wikis questions and answers principles?
I am asking about the supposed principles that all the users need to follow on Stack Overflow,
There are some cases I want to understand:
1. Some one asked a question and made it as a wiki -> why all answers are wikis as well "I mean users used to make the answers as wikis, not forced to".
2. When its better to make a question as a wiki and when not?
3. When should you make an answer as a wiki and when not?
4. Whats the real purpose of Wikis on Stack Overflow, while I still see a lot of answers on the same wiki question?
5. Why wikis questions or answers votes, don't give to their owners more points? "I know its hard to calculate, but its also not fair to gain 100 votes on a question and not get at least one point, we need to think of a way"?
|
A Community Wiki is supposed to be a way to have a collection pot of information on some subject from the entire community.
So a CW does more things than you post. For example if you post an answer on a CW question and I edit this answer, your name will no longer appear. Since I am the last editor.
So any notion of ownership does not exist on a CW question.
Many users misunderstand CW's and many use them to ask subjective questions and prevent rep whoring on answers which many agree with. A CW question was not originally supposed to be about that.
|
stackexchange-meta
|
{
"answer_score": 3,
"question_score": 2,
"tags": "discussion, community wiki"
}
|
Non Dell memory in a PowerEdge 1850
Would it be acceptable to install compatible RAM from a non Dell manufacturer? Specifically I am wondering if it is OK to install HP PC2-5300P ECC memory into a PowerEdge 1850? The part number for the memory I am thinking of purchasing is: 408853-B21.
|
As long as the RAM is compatible, of the same speed and specification and physically fits, you should be fine.
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 3,
"tags": "memory, dell, dell poweredge"
}
|
Simplified Chinese Stroke order animation
I want to show Simplified Chinese stroke order animation with unity or C#, is there an open source library? If not, is there paid repository of stroke order diagrams in unity or C#?
|
This is the first result on google: <
|
stackexchange-chinese
|
{
"answer_score": 0,
"question_score": 3,
"tags": "characters, stroke order"
}
|
Velocity verlet algorithm not conserving energy
I was under the impression that the algorithm should conserve energy if the system being modelled does. I'm modelling the solar system, which should conserve energy. The program conserves angular momentum and does produce stable orbits, but the total energy (kinetic + gravitational potential) oscillates around some baseline. The oscillations are significant. Are there common reasons why this might happen?
Model assumes planets are point masses, circular orbits (I've also tried elliptical orbits and the energy still oscillates) and uses Newtonian mechanics. I can't think what other features of the program might be affecting the outcome.
If it is just expected that the energy oscillates, what causes that??
|
Merged from the comments: For a full gravitational N-body problem, I don't think any numerical integrator will be symplectic. Velocity Verlet isn't symplectic even for a single point orbiting a center (easy to check, since it has a trivial analytical solution with g = v^2/R). So I suggest trying a higher-order integrator (such as Runge-Kutta), and if energy deviations almost go away (meaning the the calculations are generally correct), you can re-scale the combined kinetic energy to keep the total energy conserved explicitly. Specifically, you compute the updated Ekin_actual and Ekin_desired = Etotal_initial - Epotential, and scale all velocities by sqrt(Ekin_desired / Ekin_actual)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, algorithm"
}
|
Vertical-Align list item to bottom
I've read through plenty of related articles on this site and others and it seems I'm still missing something pretty basic.
I have a parent div and an unordered list. The div has a set height and I want to list items to be inline-line and on the bottom of the parent div.
Thanks!
Fiddle: <
<div class="parent">
<ul>
<li> Item 1 </li>
<li> Item 1 </li>
<li> Item 1 </li>
<li> Item 1 </li>
</ul>
</div>
.parent {
border: 1px solid lime;
height: 100px;
}
ul {
border: 1px solid black;
}
li {
border: 1px solid red;
display: table-cell;
vertical-align: bottom
}
|
One approach is adding a full-height (pseudo-)element to the `.parent` to affect the parent's baseline and move the inline level elements to the bottom of the box, Then use `vertical-align: bottom` declaration in order to keep elements - including letters having descenders - within the parent:
**EXAMPLE HERE**
.parent:after {
content: "";
display: inline-block;
height: 100%;
vertical-align: bottom;
}
ul {
display: inline-block;
vertical-align: bottom;
}
li { float: left; }
You could refer to my answer for further info:
* How to align a label to the "BOTTOM" of a div in CSS?
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "html, css, vertical alignment"
}
|
Django: for loop and if condition in one line
I want to bring `if dynamic_tickets:` and `for ticket in dynamic_tickets:` in one line. I always receive a syntax error. Do you have an idea, how to achieve that?
def adjust_prices():
events = Event.objects.filter(status=EventStatus.LIVE)
active_events = [event for event in events if not event.is_over]
for active_event in active_events:
dynamic_tickets = [
ticket for ticket in active_event.tickets.all() if ticket.dynamic_pricing_activated()
]
if dynamic_tickets:
for ticket in dynamic_tickets:
print(ticket)
print("DO OTHER STUFF")
|
No need to use 'if dynamic_tickets:' , because when the list 'dynamic_tickets' will not be empty then only for loop will execute. just write the code like this:
def adjust_prices():
events = Event.objects.filter(status=EventStatus.LIVE)
active_events = [event for event in events if not event.is_over]
for active_event in active_events:
dynamic_tickets = [
ticket for ticket in active_event.tickets.all() if
ticket.dynamic_pricing_activated()
]
for ticket in dynamic_tickets:
print(ticket)
print("DO OTHER STUFF")
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, django"
}
|
Alias to complicated Template Typename
I have the following definition in file Segment.h
template<typename T, typename VecType = mat::vec3_gen<T> > class Segment
{
// class
}
Instead of having `typename VecType = mat::vec3_gen<T>` I want to use some alias for the type and be able to use it outside the file also. how can I do it?
|
Since the type `VecType` depends on `T`, you can make the type alias a member of `Segment`.
template<typename T>
class Segment {
public:
using VecType = mat::vec3_gen<T>;
};
Now you can use it in other code:
auto vec = Segment<int>::VecType;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c++, templates, typename"
}
|
Possible to add meta box to edit.php pages?
I've been googling this for a while, and came across this link here: Can I limit this meta box to a particular page?
What I am trying to achieve is adding a custom Meta Boxe I created onto a CPT Posts Screen (`edit.php?post_type=custom`).
What I tried to use is this:
add_action("admin_init", "admin_init");
function admin_init() {
global $pagenow, $page;
if ( 'edit.php' == $pagenow ) {
add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );
}
}
When adding and saving this into my `functions.php`, the page turns blank.
Is it even possible to add a meta box to `edit.php` pages?
* * *
**EDIT** OP wants to add the "QuickPress" functionality in this meta box. Screenshots from the comments to an answer.
> !enter image description here
|
From your comment, it sounds like you don't want a metabox. A metabox is used to add metadata to a particular post, not create a new post from scratch. What it sounds like you want to do is create a widget to do what you want and then invoke it through an action or filter at the top/bottom of the page. You can use the existing Quick Post dashboard widget as your base.
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, metabox"
}
|
changing CSV file in python
I have a csv file where i have datas like
reviews pos_neg
men hecne bawa duwmedim bu kitabdan. yeqin wie sunni ayrimi etmisiz men wieyem dede babadan bildiyim dualar bu kitabda bawqadi Negative
Cavidanquluzade_official instagram seyfem xeber pırogramı Negative
səhər və axşam zikrlərində 108 ci zikrin başlığının latınca yazılışı verilmiyib. Positive
Bir müslümana aid herşey var Positive
now i need to change all "positive" to "1" and all negatives to "0". Could you please help me?
|
If I would write that kind of utility, I'd do something like this:
import argparse
import csv
import sys
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType())
args = parser.parse_args()
out = csv.DictWriter(sys.stdout, ('review', 'pos_neg'))
out.writeheader()
for row in csv.DictReader(args.file):
row['pos_neg'] = ['Negative', 'Positive'].index(row['pos_neg'])
out.writerow(row)
Can be used like this on the command line:
$ python converter.py the_file.csv > the_new_file.csv
You may need to fiddle with the options for the CSV reader, as it appears you have a TSV or fix-width file perhaps…?
|
stackexchange-stackoverflow
|
{
"answer_score": -2,
"question_score": -4,
"tags": "python, csv"
}
|
Rounding while checking parameters
I have manage to be-able to check the input and tell if its an int or not, and re ask the user if it is not. However I want to add in a check that will convert doubles into ints by rounding them. I played around with the Math.round method, but could not get anything working properly.
public static int getInteger(String prompt)
{
int input = 0;
Scanner user_input = new Scanner( System.in );
System.out.print("Enter a integer: ");
while (!user_input.hasNextInt()) {
System.out.println("Is not a valid number.");
user_input.next();
}
return input;
}
Would be great if someone could show me how, cheers.
|
public static int getInteger()
{
int input = 0;
Scanner user_input = new Scanner( System.in );
System.out.print("Enter a integer: ");
while (!user_input.hasNextInt() && !user_input.hasNextDouble()) {
System.out.println("Is not a valid number.");
user_input.next();
}
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
input = Math.round((float) user_input.nextDouble()); //I assume here that your number is small as you said
}
return input;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, rounding"
}
|
Function Definition Containing unit F#
I'm new to f# programming, and I am defining a few helper functions to be used. Here are two of them:
let GetPieceAt piece playerType file rank = {
piece = {piece = piece; playerType = playerType} ;
place = { file= file; rank = rank}
}
let GetPieceOnRank piece rank playerType files () =
[for f in files -> GetPieceAt piece playerType f rank]
The first function is of the correct type: piece -> playerType -> file -> rank -> PieceAt
However, the second function has: piece -> rank -> playerType -> seq -> _unit_ -> PieceAt list
Where did this unit come from? And my other function that call this are getting unit -> unit ... -> {correct return value}, and this is making errors.
What am I doing wrong?
|
`unit` in F# is represented by the empty parentheses `()` in your `GetPieceOnRank` definition.
Unlike C#, functions do not need parentheses to be called. Perhaps the placement of those parentheses was a mistake, because they are not needed and simply removing them still allows the code to compile.
let GetPieceOnRank piece rank playerType files =
[for f in files -> GetPieceAt piece playerType f rank]
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "function, f#"
}
|
asp.net - register and login using mssql database
Simple question - is there any tutorials how to implement registration and login on asp.net mvc3 webpage using mssql database? And how to check user authorization (is logged or not and his privileges)?
Greetings
|
You shouldn't need to do that much as the heavy lifting is done by the membership provider - that is to say that all the controls and code as such are DB agnostic and don't really care which data storage mechanism you use. All you should need is to install MySQL Connector and change the configuration settings in Web.Config to point to the MySQL provider rather than the out of the box MSSQL provider - you should find what you need here:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, asp.net mvc 3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.