INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to replace the bytes in a binary file?
My binary file `test.bin` contains
11 22 33 44 55 66 ...
I want to modify the 3rd position with `AA` and my file should be like
11 22 33 AA 55 66 .... | Open the file for update in binary mode, seek to the desired position in the file, then write the replacement character. The following will work in Python 2 and 3 and will overwrite the 4th byte of the file (3rd position if counting from 0) with 0xAA.
with open('test.bin', 'rb+') as f:
f.seek(3)
f.write(b'\xAA') | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": -5,
"tags": "python, perl"
} |
setting a limit on a variable in a function and return error else wise in haskell
Hi i'm new to haskell and i'm trying to implement the following and I can't quite get it right
here is a basic algorithm of what i'm trying to do lets say you have
--define some basic example function
fun x y = x + y
--pseudo code for what i am trying to do
x >= -1.0 || x <= 1.0 --variables x must be within this range else ERROR
y >= 1.0 || y <= 2.0 --variables y must be within this range else ERROR | A very simple way to do this is as follows. This uses a guard:
fun x y
| x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = error "Value out of range"
| otherwise = x + y
See here for a series of increasingly complex and sophisticated ways to report and handle errors.
Sometimes a `Maybe` type is preferable, as ivanm points out. Here's an example for completeness:
fun' :: Float -> Float -> Maybe Float
fun' x y
| x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = Nothing
| otherwise = Just (x + y) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "haskell"
} |
Add time scale to columns in a grid
I'm developing an app that creates a timeline in run time. So I created a Grid (not a datagrid) and I wanna put some time stamps in equal spaces (60 pixels/hour - 1 pixel/minute).
I already know how to create the columns programmatically:
public void ColumnCreator(double totalInterval, double divPattern)
{
int divisionPattern = Convert.ToInt16(divPattern);
if (divisionPattern < totalInterval)
{
for (int i = 0; i < totalInterval; i += divisionPattern)
{
internalGrid.ColumnDefinitions.Add(new ColumnDefinition() {
Width = new GridLength(divisionPattern, GridUnitType.Pixel) });
}
}
}
but these lines are not synchronized. Does anybody have a solution for me?
Thanks in advance 8-) | As was pointed out especially for _real time_ visualization `Grid` may be the worse choice you can made. `Grid` is responsible for **containing controls layout management** and has a heavy impact on performance.
Use a `Canvas` to **draw** a stuff on it. Use `Shape` and `Path` for drawing. To achive a reasonable performance on real time UI you need to read at least this link: <
Do not use `Pixels` but provided by WPF `Units`, which are device independent way to declaring the dimension of something in WPF. So your drawing will maintain a proportion on different monitors `screen sizes` and `dpi`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, wpf, grid, dynamic"
} |
C++ Verify if string 1 exist in string 2
Help me please !!
it doesn't work and i didn't founf the mistake !?
there is a function to verify existence of strings in each other ? Thank You !!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string mot1="abc";
string mot2="oooooabcooo";
int j=1;
while((j!=mot1.length())||(j!=0))
{
for(int i=0;i<=mot.length();i++)
{
if(mot1[i]==mot2[i])
{j++;}
else j=0;
}
}
if(j==mot1.length())
cout<<mot1<<" existe dans "<<mot2<<endl;
else
if(j=0)
cout<<"erreur";
return 0;
} | Here is the function you are looking for.
mot2.find(mot1); // also std::find
Hope this helps. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++, string"
} |
Front end flashdata / system messaging without URL segments
I'd like to be able to display incidental messages on the front end, such as for 'thank-you' content and success/error messages after form submissions. However, I'd like to do this without polluting the URLs with extra segments... Is there a standard solution for this? | Sure, cookies would be the way to go here if you don't want extra segments. Cookies Plus looks like it could make this easy for you (though there are some negative reviews ... no harm in giving it a shot of course, it would save you from writing this custom or adding PHP into your templates).
First, your form would redirect to **forms/submit/success**.
In that template you'd put:
{exp:cookie_plus:set name="flash_message" value="Your entry was submitted." seconds="10"}
{redirect="forms/submit"}
Then in your **forms/submit** template:
{exp:cookie_plus:get name="flash_message"}
{if cookie}
<p class="message success">{cookie}</p>
{/if}
{/exp:cookie_plus:get}
You can get more elaborate if you want to conditionally check for different cookie names that represent different kinds of messages, etc. | stackexchange-expressionengine | {
"answer_score": 2,
"question_score": 3,
"tags": "system messages"
} |
How do I rename a key while preserving order in dictionaries (Python 3.7+)?
I have a dictionary, with this value:
{"a": 1, "b": 2, "c": 3}
I would like to rename the key `b` to `B`, without it losing its second place. In Python 3.7 and higher, dictionaries preserve insertion order, so the order of the keys can be counted on and might mean something. The end result I'm looking for is:
{"a": 1, "B": 2, "c": 3}
The obvious code would be to run:
>>> dictionary["B"] = dictionary.pop("b")
{'a': 1, 'c': 3, 'B': 2}
However, this doesn't preserve the order as desired. | This solution modifies the dictionary `d` in-place. If performance is not a concern, you could do the following:
d = {"a": 1, "b": 2, "c": 3, "d": 4}
replacement = {"b": "B"}
for k, v in list(d.items()):
d[replacement.get(k, k)] = d.pop(k)
print(d)
**Output:**
{'a': 1, 'B': 2, 'c': 3, 'd': 4}
Notice that the above solution will work for any numbers of keys to be replaced. Also note that you need to iterate over a copy of `d.items()` (using `list(d.items())`), as you shouldn't iterate over a dictionary while modifying its keys. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 9,
"tags": "python, python 3.x"
} |
How do I bring a drop down list to the front in Laravel?
I have a website build on Laravel/ css and I have a drop down list but it seems to cut off as soon as it hits the next section of the site (I'll provide screenshots to explain this). I'm rather new to this so looking for any help on how to make sure the full list is displayed. Maybe some sort of 'bring to front' on the css file? The first screenshot is on a 4k desktop monitor and the second is a mobile phone (iPhone 12) Any help is greatly appreciated.
. I want the center div to fill in all the space between the two outside divs when the window adjusts.
Here's an example of my attempt: <
#div_1 {
float: left;
background: red;
display: inline-block;
width: 300px;
height: 50px;
text-align: left;}
#div_2 {
overflow: hidden;
background: green;
display: inline-block;
height: 50px;
text-align: center;
}
#div_3 {
float: right;
display: inline-block;
background: blue;
width: 350px;
text-decoration: underline;
font-weight: bold;
color: white;
height: 50px;
text-align: right;
}
Here's an idea of what I want it to look like: <
Any help is very appreciated, thank you. | **Demo:** <
HTML:
<div>
<div id="div_1">LEFT COL STATIC WIDTH 300px</div>
<div id="div_3">RIGHT COL STATIC WIDTH 350px</div>
<div id="div_2">CENTER COL DYNAMIC WIDTH</div>
</div>
CSS:
#div_1 {
float: left;
background: red;
display: inline-block;
width: 300px;
height: 50px;
text-align: left;}
#div_2 {
overflow: hidden;
background: green;
display: block;
height: 50px;
text-align: center;
}
#div_3 {
float: right;
display: inline-block;
background: blue;
width: 350px;
text-decoration: underline;
font-weight: bold;
color: white;
height: 50px;
text-align: right;
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "css, html, responsive design, width"
} |
How to display a ForeignKey field as a selection field in django template
I need to display a foreignKey field as a selection field in Django template, which will show all the available records as a dropdown. On considering the case of querying to database every time on selecting the field, which is the best method to achieve above goal to make a selection field from ForeignKey field. | You should use first views to get that foreign key field and pass it over the context dict. to the template.
Inside Views.py
DEPENDENT_FILED = DB.OBJECT.ALL() // field which has all the drop-down values.
FR_FIELD = DB.OBJECT.GET(DB_OBJ_HAVING_FR) // selected drop-down from template
context['FR_FIELD'] = FR_FIELD
Inside example.html
{% if FR_FIELD %}
<select name="dropdown_field">
{%for fr_key in DEPENDENT_FILED %}
<option value="{{fr_key.field_name}}" {% if fr_key.field_name = FR_FIELD|add:0 %}selected{% endif %}>{{fr_key.option_name}}</option>
{% endfor %}
</select> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, django, django 1.9"
} |
jQuery checkbox: change from a click method to something else
I have a jQuery method (function?) on a checkbox that executes when the checkbox is clicked
click.function() {
// blah blah
}
But now I want the checkbox to be checked by default...how do I make the function run automatically (without waiting for the checkbox to be clicked on?) | $('#checkboxId').click(function() {
// blah blah
}).trigger('click'); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery"
} |
Forming a splitting of $R^2$
In my topology course i recently learned about the concept of a splitting and using it to assist in determining whether a set is connected or not. So I am trying to determine if a subset in $R^2$ is connected that has the subspace topology induced on it coming from the standard topology on $R^2$. But i am having an issue successfully splitting up $R^2$ in order to get open sets to use in the subspace topology. Any suggestions? Is it even possible? Because here thinking about it, i can't come up with any
The set is $$X = \\{(x,y): xy = 1 \\} $$ | You don't really need to split $\mathbb{R}^2$ to show that some subset of $\mathbb{R}^2$ is not connected. You just need to find subsets of $\mathbb{R}^2$ which are open with empty intersection and they should _cover the given subset (and not $\mathbb{R}^2$)._
So for your set the open left and right half planes will do the job. Or if you want you can actually go with the first and the third quadrant itself. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "general topology"
} |
How can I use field_attach_load()
> **Possible Duplicate:**
> Listing entity fields
I want list fields of my content type(example: blog), so as described at Drupal API reference, I should pass $entity_type and $entities to this function.
I know $entity_type is 'node', but how can I fill $entities? I should fill $entities with bundle of "blog" so I should know the bundle ID. How can I know bundle ID for blog? | If you want the list of fields per content type (now bundles in Drupal 7), you should use `field_info_instances()`.
//List all fields of bundle "your_content_type" using devel module
dsm(field_info_instances('node', 'your_content_type')); | stackexchange-drupal | {
"answer_score": 3,
"question_score": 0,
"tags": "7, entities"
} |
jQuery inline style rgb fallback for rgba color IE 8
I am using jQuery to set the background of a div and i want to use rgba color in the browsers that support it but if they don't i would like to use rgb color as a fallback. I know how to achive this with plain css.
style="background: rgb(250, 0, 0); background: rgba(250, 0, 0, 0.5);"
Do you know how i could achieve this with jQuery `.css()`? | I believe if you use `css()`, it will overwrite the previous value for a property. If you want to do something like that, you can either set it manually via `attr()`, or you can use the callback function to see if it's IE or not, and set the value accordingly.
**using`attr()`**
$('element').attr('style','background: rgb(250, 0, 0); background: rgba(250, 0, 0, 0.5);');
**using`.css()`**
$('element').css('background', function() {
// if you're using jquery version < 1.9
if($.browser.msie && parseInt($.browser.version, 10) === 8)
return 'rgb(250, 0, 0);';
else
return "rgba(250, 0, 0, 0.5)";
});
NOTE: if you're using jquery version 1.9 or above, `$.browser` is removed, so you will need to detect IE8 in a different way. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, jquery, css, internet explorer"
} |
Implement drag from NSImageView and save image to a file
I've studied Apple's example: CocoaDragAndDrop. I understand how to drag a image to NSImageView and drag an image between views. However, I still don't known how to drag an image and save it to a file when the image is dropped onto the Finder.
Can anybody give me a example? | I finally found out how to do it. And I wrote a demo on Github | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 5,
"tags": "cocoa, drag and drop, nsimageview"
} |
Run an SQL Query With a DateTime Parameter from Excel 2010
I am using ODBC connection Excel 2010, I know we can set up parameter in MS Query by adding [Blah Blah] and would add `?` in actual query.
But I don't know how to do a parameter for datatime with to_date.
Here is my where clause.
where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS'))
I am not sure what Info I need to here, but here is data type of time_stamp field.
SQL> desc tablet
Name Null? Type
----------------------------------------- -------- -----------------------
TIME_STAMP DATE | I think you are just preparing a SQL query and sending it to Oracle. I thought you were calling an Oracle stored procedure.
Your where clause should look like:
where ("R"."TIME_STAMP" between ? and ?)
and in Excel, you need a cell to input the date or date/time (assume it is `A1`), and then another cell with the formula `=TEXT(A1, "MM-DD-yyyy hh:mm:ss")`. This is the cell to link to in MS Query. Repeat for the second parameter. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, oracle, excel"
} |
How To make image botton without effect in android studio
i have Imagebotton in content_main.xml with code :
<ImageButton
android:src="@drawable/tri1"
android:layout_width="110dp"
android:layout_height="130dp"
android:id="@+id/imageButtonTri"
android:layout_marginLeft="75dp"
/>
and show : !enter image description here
but i want the imageBotton without box effect, like : !enter image description here
and than, i will make this imageBotton to go to next layout
how can i do it??? | <ImageButton
android:src="@drawable/tri1"
android:layout_width="110dp"
android:layout_height="130dp"
android:scaleType="fitCenter"
android:background="@android:color/transparent"
android:id="@+id/imageButtonTri"
android:layout_marginLeft="75dp"
/> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "java, android, xml, android studio"
} |
Difference in accessing arrays in PHP 5.3 and 5.4 or some configuration mismatch?
I'm trying to access nested array element like this:
$dbSettings = $sm->get( 'Config' )[ 'doctrine' ][ 'connection' ][ 'orm_default' ][ 'params' ];
It's inside `Module.php` of Zend's framework 2 project. `$sm->get('Config')` return an array which I can access with code above locally, with PHP 5.4, while doing so on client's machine, it gives me an error:
Parse error: syntax error, unexpected '[' in /home/.../azk/module/Main/Module.php on line 121
Is there any difference in PHP 5.3 <=> 5.4 in accessing nested arrays or I have some default PHP configuration which is set differently on clients machne? | Array dereferencing, which is what you are using, was introduced in PHP 5.4 and won't work in PHP 5.3.
So
$dbSettings = $sm->get( 'Config' )[ 'doctrine' ][ 'connection' ][ 'orm_default' ][ 'params' ];
Would need to be:
$dbSettings = $sm->get( 'Config' );
$params = $dbSettings[ 'doctrine' ][ 'connection' ][ 'orm_default' ][ 'params' ]; | stackexchange-stackoverflow | {
"answer_score": 20,
"question_score": 7,
"tags": "php, arrays, zend framework2"
} |
Find max vertical distance
What is the maximum vertical distance between the line $y = x + 20$ and the parabola $y = x^2$ for $−4 ≤ x ≤ 5?$
What steps do I take to solve this? Do I have to use the distance formula and what do I do with the points it gave me?
If anyone could just bounce me in the right direction that would be neat. I can probably work an answer from there!
Also what's the distance formula to use here? | The vertical distance at $x=a$ is the difference in $y$-coordinates at $x=a$, so it’s $|(x+20)-x^2|$. Now $x^2-x-20=(x+4)(x-5)$, so it’s negative between $x=-4$ and $x=5$. Thus, on the interval $[-4,5]$ we have $|(x+20)-x^2|=x+20-x^2$, not $x^2-x-20$.
Now let $f(x)=x+20-x^2$ and find the maximum of $f(x)$ on the interval $[-4,5]$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus"
} |
Complexity to find cube root of n
The cube root of a natural number n is defined as the largest natural number m such that m^3≤n. The complexity of computing the cube root of n (n is represented in binary notation) is
(A) O(n) but not O(n^0.5)
(B) O(n^0.5) but not O((log n)^k) for any constant k > 0
(C) O((log n)^k) for some constant k > 0, but not O((log log n)^m) for any constant m > 0
(D) O((log log n)^k) for some constant k > 0.5, but not O((log log n)^0.5)
I am lost solving this previous year problem .Can any one help me to understand this question | To answer that question, you need to find upper and perhaps lower bounds on the complexity of finding an integer cube root m of n. At least one upper bound is trivial, and rules out answers A and B: m can be found in O(log n) time using binary search.
Also note that the input size is O(log n) because the minimum number of bits needed to represent an arbitrary n in binary notation is proportional to log n. Because all bits of the number must be processed to solve the problem, θ(log n) is a lower bound on the time to solve the problem, and therefore the problem cannot be solved in time O((log log n)^w) [where w is some constant > 0] because that isn't O(log n). Thus, answer C applies. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "algorithm, big o, time complexity"
} |
$sp^3$ Hybridization wavefunctions and probability density
I have plotted a hydrogen-like sp3-hybrid orbital probability density and it looks like this:
 and square the resulting function to get the probability density, I always come up with a sphere:
 Is this an expected result? If not, what am I doing wrong?
2.) What is usually depicted on the sp3-hybridization schemes: overlapping wavefunctions, sums of the wavefunctons, probability density or something else? | The $sp^3$ orbitals are a mix of an $s$ orbital and all three $p$ orbitals and form four equivalent hybrids. Due to orthogonality, it can be proven that the orbitals have the following form:
$$|h_1\rangle=\frac{1}{2}\left(|s\rangle+|p_x\rangle+|p_y\rangle+|p_z\rangle\right)\\\ |h_2\rangle=\frac{1}{2}\left(|s\rangle+|p_x\rangle-|p_y\rangle-|p_z\rangle\right)\\\ |h_3\rangle=\frac{1}{2}\left(|s\rangle-|p_x\rangle+|p_y\rangle-|p_z\rangle\right)\\\ |h_4\rangle=\frac{1}{2}\left(|s\rangle-|p_x\rangle-|p_y\rangle+|p_z\rangle\right)$$
The addition of all hybrid orbitals is, wait for it, an $|s\rangle$ orbital! So yes, it should be a spheric orbital.
Source: Electonic Structure of Materials, A. Sutton | stackexchange-physics | {
"answer_score": 3,
"question_score": 2,
"tags": "quantum mechanics, condensed matter, wavefunction, orbitals, quantum chemistry"
} |
Property not able to set
I've got an issue with a list property that holds bookmarks. Before I started fiddling around it worked just fine. I want the list to always be sorted from a-z when fetched and I want the list to be able to set to the value put in.
I am not sure why it won't work. Any suggestions on getting the latter to work, or any suggestions to sort the list in any other manner is greatly appreciated and welcome!
Here the bookmark list is being set from a database query:
model.Bookmarks = GetBookmarks().Select(b => new UIBookmark(b, DbHelper)).ToList();
This worked:
public List<UIBookmark> Bookmarks { get; set; }
This doesn't:
public List<UIBookmark> Bookmarks { get { return Bookmarks.OrderBy(b => b.Name).ToList(); } set { Bookmarks = value; } } | If you are not using auto-properties, you **HAVE TO** use a field to store your data.
private List<UIBookmark> _bookmarks;
public List<UIBookmark> Bookmarks { get { return _bookmarks.OrderBy(b => b.Name).ToList(); } set { _bookmarks = value; } }
_Basicly, auto-properties do the same thing, you just don't have to write anything._ | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c#, entity framework"
} |
Absolute position and overflow property
I an making this page, which have a sticky footer.
The content div, is going through the sticky footer, and because of the absolute positioning I cant make `overflow:hidden;` work properly.
Can anyone help me ?
Please no comments on the design :P not my cup of tea either.
Link to site | Link to jsfiddle example | Add the following CSS to the footer
position: fixed;
bottom: 0;
width: 100% | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, css, css position"
} |
Filter all object form django modal if its id is not available to other table and on some conditions
Comments(models.Model):
comments = models.CharField(max_length=55)
UsedComment(model.Model):
bot = model.ForeignKey(InstagramBot, on_delete=models.CASCADE)
comment_id = model.ForeignKey(Comments, on_delete=models.CASCADE)
I want to filter all the comments from Comments Model if its id is not used by same bot in UsedComment. I mean comment can be repeated, but same bot can not use same comment | > I want to filter all the comments from Comments Model if its id is not used by same bot in UsedComment. I mean comment can be repeated, but same bot can not use same comment
You can use `~Q` in filter
from django.db.models import Q
Comments.objects.filter(~Q(usedcomment__bot=your_bot)) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "django"
} |
Negative value format with in parentheses
normally php will output negative integer with this format `-1234`, how to it show in parentheses format `(1234)`
example:
$foo = 10 - 20;
// output: $foo = -10
// expected output $foo = (10) | I don't think there is a way to make PHP do this automatically.
echo ($foo < 0 ? "(".abs($foo).")" : $foo);
is the shortest solution that comes to mind. | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 2,
"tags": "php"
} |
MongoDB collection hyphenated name
I'm using Node.js program to insert data into a MongoDB database. I have inserted data into a collection named "repl-failOver".
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://localhost:30002/test", function(err, db) {
if (err) throw err;
db.collection("repl-failOver").insert( { "documentNumber" : document++}, function (err, doc) {
if (err) throw err;
console.log(doc);
});
db.close();
});
When I use the Mongo shell and list down the collections in the database using `show collections` I am able to see the collection "repl-failOver".
How do I run a find command from the mongo shell for this collection? | Use this syntax:
db['repl-failOver'].find({})
or
db.getCollection('repl-failOver').find({})
You can find more information in the Executing Queries section of the manual:
> If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen, or starts with a number, you can use an alternate syntax to refer to the collection, as in the following:
>
>
> db["3test"].find()
>
> db.getCollection("3test").find()
> | stackexchange-stackoverflow | {
"answer_score": 144,
"question_score": 74,
"tags": "mongodb, collections"
} |
Nesting for loops in if statements in ansible
I need to loop through a variable list and embed the `<debug nested for loop>` code in a jinja2 template.
Here is what the playbook looks like
vars:
env:
- dev
- prod
- staging
tasks:
- name: set variable
set_fact:
denv: 'dev'
- name: debug for loop
debug: msg='{% for i in env %} {{i}} {% endfor %}'
- name: debug nested for loop
debug: msg='{% if denv =='{% for i in env %} {{i}} {% endfor %}' %} yay {% else %} nay {% endif %}'
The goal is to loop through the `env` list and if the values match `denv` print `yay` else print `nay`
Any idea on how to better write this? The way it is currently written is triggering errors. | I'm not sure why you need a nested loop. What you want is to check for a value within a list right? Try using the when keyword. That way your debug message will only say Yay when it finds the right value.
---
- hosts: localhost
connection: local
gather_facts: False
vars:
envs:
- dev
- prod
- staging
tasks:
- name: set variable
set_fact:
denv: 'dev'
- name: find dev
debug: msg="Yay it's {{ item }}"
with_items: "{{ envs }}"
when: item == denv | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "ansible, jinja2"
} |
Is my proof that $f(x)$ where $f(f(x)) = 6x - f(x)$ for all $f:R+→R+$ is linear correct?
The top functional equation was assigned in a Putnam competition. To prove that this function is linear, I did the following algebra: $$f(f(x))=6x-f(x)$$ $$f(f(x)) + f(x) = 6x$$ $$\frac{f(f(x))+f(x)}{x}=6$$ Can I now say that, since this identity always results in a constant, $f(x)$ is a linear function? | No, you cannot conclude this. From your remark in the comments, you recalled a video in which someone showed a claim like $$\require{cancel}g(x+1)-g(x)=2$$ and concluded that $g$ is linear. This sort of claim does not generalize to $$(\text{any sort of formula using $f$ twice})=(\text{const})\Rightarrow f\text{ is linear}$$
To see why the $g$-like claim works, suppose we can ensure that $x$ is an integer like $0,1,2,\dots$. Then $$g(3)=(g(3)-\cancel{g(2)})+(\cancel{g(2)}-\cancel{g(1)})+(\cancel{g(1)}-\cancel{g(0)})+g(0)=2+2+2+g(0)$$ In general, if $g(k)$ has $k$ summands, and so $g(k)=2k+g(0)$, which is linear. _If $x$ is not an integer, then the claim is actually wrong: there are many solutions to the functional equation that are not linear._
In your particular example, there is no obvious way to iterate your construction to get many values of $x$. But note that when the functional equation was asked here, the accepted answer did develop a similar technique to solve it. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, contest math, functional equations"
} |
ArcGIS Online's new map viewer - sublayers?
I just opened up ArcGIS online for the first time in a few weeks and I see their new map view is out. I'm trying to get comfortable with it, but I'm struggling to find the sublayers option for layers that have more than one sublayer. For example, for these LANDFIRE layers, there are multiple sublayers you can access. With the classic map viewer, they're easy to navigate:
 when it ought to target dark colours (less than the threshold). As a result, the dark shapes are being covered by the blur effect on the white background. Solution: change the direction (> vs. <) of the test.
If you want bloom on shadows as well as lights, try:
> (Colour < Shadow Threshold || Colour > Highlight Threshold)
But it probably won't look great. | stackexchange-gamedev | {
"answer_score": 2,
"question_score": 2,
"tags": "xna, bloom, glow"
} |
is it ok to use the exports keyword with commonjs - webpack 1
Is it ok to use the `exports` keyword to access the exported values, inside the module it self ? ( is it part of the es6 modules spec ? ) It seems to be working fine with webpack and babel / commonjs modules, the `exports` keywords contains a reference to all exported methods.
But my concern is that this might not be valid and maybe this is only possible because it's a babel / commonjs enviroment.
Also I am not sure how this would affect tree-shaking, as now it would be impossible to determine which exports are actually being used, since the `bindMethods` method can access all methods in this module dynamically, without having to declare explicit names.
Example:
import bindMethods from 'module';
var binder = bindMethods(exports);
export function foo(value){
binder(value).bar();
}
export function bar(value){
binder(value).foo();
} | Yes, you'd be right in saying using `exports` like that isn't valid es6 and is only working because babel transpiles your code into commonjs.
Webpack 1 doesn't support tree shaking so it shouldn't cause any problems there. It would be interesting to see what happens if you disable `transform-es2015-modules-commonjs` and use Webpack 2 to see whether it does effect tree shaking -- I highly doubt it will though. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ecmascript 6, webpack, babeljs, commonjs, es6 modules"
} |
Решить проблему со скриптом в JavaScript (jQuery)
У меня есть скрипт:
var checkedItem = [];
$(".block-insideBlock .user").on("click", function () {
event.preventDefault();
$(this).toggleClass("checked-item");
checkedItem.push($(this).text());
})
При нажатии на тег с классом `.user` (Как показано в скрипте), к тегу прибавляется класс `checked-item` и в массив `checkedItem[]` добавляется текст из тега, при вторичном нажатии класс `checked-item` удаляется, а вот текст в массиве нет. Вопрос в том как сделать так, чтобы при вторичном нажатии помимо класса исчезал и текст из массива? | $(".block-insideBlock .user").on("click", function (event) {
event.preventDefault();
$(this).toggleClass("checked-item");
checkedItem.length = 0;
$(".block-insideBlock .user.checked-item").each(function() {
checkedItem.push($(this).text());
});
}) | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery"
} |
Dos return en una function de laravel
necesito saber si se puede y como devolver tanto los usuarios como la vista
public function show()
{
//
$data['usuarios'] = DB::select("SELECT * FROM users WHERE rol = 2");
return $data['usuarios'];
return view('usuarios.list');
} | * Dentro de una función/método no pueden existir múltiples return, es solo uno y este deberá ser capaz de devolver el resultado del procesamiento interno
* Laravel ya ofrece una sintaxis para retornar valores a través del método `view` al cual como segundo argumento le podemos pasar la data que planeamos mandar a la vista
Entonces debería quedar así:
return view('tu-vista', ["clave" => $variable]);
Donde `$variable` es la que esta almacenando el resultado de tu consulta, recomiendo leas este apartado de la documentación donde de hecho puedes ver mas opciones para lograr lo que buscas.
Para el caso de **`return`** te recomiendo la documentación de PHP pues finalmente este es el le guaje base de Laravel. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, laravel"
} |
SELECT rows having equal column(c1) value and adding adding another column(c2) value. Performing same for all the distinct column values for column c1
I need to write an SQL Query for MySQL Database which gives me the data according to the necessary conditions
I have a table having structure like this
id: orderId
amount : itemAmount
rate : itemRate
time : orderTime
Now I have to select all the rows having same rates and then have to add all the items having same rates. This should work for each rate means for eg.
> row with id 1 is having rate $20 with 2 items and row 3 is having rate $20 with 5 items
>
> row with id 2 is having rate $40 with 4 items and row 4 is having rate $40 with 7 items
I should get result is
rate: $20 totalItem : 7
rate: $40 totalItem : 11 | As I stated in my comment, I don't know what your columns are called, I'll assume in my answer they're called `id`, `amount`, `rate` and `time`.
SELECT rate, COUNT(*) AS totalItems -- Select the rate, and count everything
FROM theRelevantTable -- Use the rows in this table
GROUP BY rate -- But do the selection per group.
In clearer English:
Group the rows in theRelevantTable by their `rate`, then, for every group, give me the rate and count how many rows there are in the group.
I hope this is what you meant. I do not entirely understand your question. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql"
} |
Conditional comparison with out of range values in C
How is this resolved by the compiler? Which implicit conversion is carried? Is it optimized maybe so that the conditional is always true? Will the following code be always safe? Or depends on the compiler.
#define MaxCfgDev 500
uint8 numdev;
.
.
.
if(numdev < MaxCfgDev)
.
.
.
I know maybe could not make sense at first sight to compare to a number beyond limits, but imagine that this `MaxCfgDev` is not defined so obviously but comes from another complex definition, maybe from other defines coming from external modules and this specific module only needs to check that `numdev` it is below some system level definitions or whatever. | A `#define` performs a symbol substitution prior to the compiler being run. So after substitution the condition will be exactly equivalent to:
if(numdev < 500)
It doesn't matter how "obvious" the definition of `MaxCfgDev` is. If it evaluates to a compile time constant that is 256 or larger the condition will always be true, and the compiler may optimize out the test. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c"
} |
Deleting values with more than 2 decimal place in array
I have an array with chunks of values.
$value = array(
array(3075,15,461.25,16,535.05),
array(3075,15,461.25808,16,535.05),//to be removed
array(3075,15,461.2,16,535.05234)//to be removed
);
I need to remove the rows that has values with more than 2 decimal places. How do i do that? | You can use `strlen(substr(strrchr($x, "."), 1))` to count the decimals and `array_filter` to remove any array value with more than 2 decimals
$value = array(
array(3075,15,461.25,16,535.05),
array(3075,15,461.25808,16,535.05),//to be removed
array(3075,15,461.2,16,535.05234)//to be removed
);
$value = array_filter($value,
function ($v) {
foreach ($v as $x) {
if (strlen(substr(strrchr($x, "."), 1)) > 2)
return false;
}
return true;
});
var_dump($value);
Output
array (size=1)
0 =>
array (size=5)
0 => int 3075
1 => int 15
2 => float 461.25
3 => int 16
4 => float 535.05 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, multidimensional array"
} |
Local database solutions for windows phone development
I am maintaining a simple set of records. I want to store these records as table on my Windows phone.
I have come across Linq-to-SQL. My question is, is it the default database provided by the Windows phone system just as SQLite is provided by ANDROID?
Is Linq-to-SQL used by the Windows phone native apps like Contacts Manager?
I have also come across SQLite support for Windows phone. I am able to install the necessary extensions and packages required.
My question here is, when I will deploy my application on the phone, is there a need to install the SQLite library separately first for that phone?
When we include the extension in our Visual Studio IDE then while deploying my application on the phone does the IDE take care of installation of SQLite on the phone? | SQLite's distribution contains everything needed to make use of a local database file asset packaged within its DLL that you reference in your project when you pull in its NuGet package. No additional installations or assets are required by users of your applications.
If you are interested in Microsoft technologies for use with your project, you're looking for SQL Compact 3.5. Compact 4.0 is not currently supported by Windows Phone. You can create a new compact database SDF file and add it to your project as an embedded resource, then access it with a connection string as simple as `isostore:/FileName.sdf`. You'll still need to generate a DB context and entities to make use of the database, but I've found that I can use LINQ-to-SQL's ORM and import the generated classes, removing the two unsupported interface context constructors that aren't in the Windows Phone library. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "database, windows, sqlite, windows phone 8, linq to sql"
} |
Render Partial View from other controller
Is there a way to render inside my view of controller **A** a partial view from other controller **B**?
Edit: I wrote a partial view that is good for only two controllers and I don't want to copy it to their both Views folder.
I want The partial view to be displayed each time the View is rendered not after something happens. | 1. You can share views between controllers by putting them into the Views/Shared folder. Each controller can then render that view by name.
2. You can render a partial view (which can be shared between controllers as in (1)) within the current view using `Html.Partial()`.
3. You can use `Html.Action()` to invoke an action on a different controller and render the results within the current view.
4. You can use AJAX to load a partial view from a different controller after the page has been rendered. | stackexchange-stackoverflow | {
"answer_score": 78,
"question_score": 65,
"tags": "c#, asp.net mvc, asp.net mvc 3, razor, partial views"
} |
Are there any differences with the git provided by Apple and the official git?
I've come across several topics about 'updating' or 'installing' an 'official' version of git to replace the git pre-installed by Apple.
I haven't been able to find the reasons/benefits for/of doing so... Can someone explain why doing this is important or unimportant?
Thanks in advance ! | It's almost the same as the official versions but in a different versioning.
Read below on how to update and upgrade your git version: < | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 17,
"tags": "ios, git"
} |
Function to get the index of the combinations produced by itertools.product's combination/matrix representation in python?
For example:
alist=[['a','b'],[1,2]]
and the combination
('a',1)
Is there a way to get the index of this combination i.e. (0,0) because both are at the 0-th position in their respective list or a matrix like
[[1,1],[0,0]]
where the 1s indicate the position get selected to form the combination? | Well you can just create the indices as ruaridhw pointed out. You can do it like so:
from itertools import product
alist = [['a','b'],[1,2]]
print [a for a in product(*alist)]
print [list(a) for a in product(*[range(len(x)) for x in alist])]
Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
[[0, 0], [0, 1], [1, 0], [1, 1]] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, numpy, python itertools"
} |
Is my modulus logic for this loop correct?
So here's the pattern i'm looking for
out of a finite set, I want to retrieve the first 2 values for one set, then followed by the next 4 for another set, then 2 for that first set, and then 4 for the other set, and so on..
grab 2 | grab 4 | grab 2 | grab 4 ...
$count = 0;
foreach ($listing as $entry){
if ($count % 4 == 0){
// add to 4-item set
} else if ($count % 2 == 0){
// add to 2-item set
}
$count++;
}
**My confusion is that when $count%4=0 then $count%2 will also = 0.**
So should i be safe by not reaching the wrong modulus case (since both are true for any arbitrary number divisible by 4) by checking **first** if $count%4 == 0? | If I get it right, your desired distribution is actually:
A A, B B B B, A A, B B B B, A A, B B B B, ...
So you want to _group them into **six_** and then pick the first two into basked A, the other four into B:
if ($count % 6 < 2){
// add to 2-item set
}
elseif ($count % 6 < 6){
// add to 4-item set
}
Splitting it into if/elseif will ensure that the items only end up in either one. The `< n` comparison on the `% 6` distribution would mean:
$count % 6 = 0 1 2 3 4 5 0
if = <2 <2 <6 <6 <6 <6 <2
basket = A A B B B B A | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "php, javascript, loops, logic"
} |
Uploading multiple files with metadata in SharePoint 2013
Is it possible to upload multiple files with metadata in the document library in SharePoint 2013? | It is still not supported to upload multiple files with managed metadata or simple metadata. | stackexchange-sharepoint | {
"answer_score": 4,
"question_score": 1,
"tags": "document library, managed metadata, 2013, metadata, file"
} |
How to know where application is deployed on heroku Rails 3
I have two places where I deploy my application on heroku.
Both are production.
One is for staging and testing. The other is the live public application.
I know how to test the Rails env to see if its production or development.
Is there a way to test where the application is deployed so I can set up my sendgrid smtp settings for each environment and test the mail settings. | Your best bet is to use the Rails env for what it was intended. You can simply create a new file in your config/environments folder named staging.rb and copy your production settings into it but change any variables that you need to for your staging/testing application deployment.
Once you've done that set the heroku RAILS_ENV (via `heroku config add RAILS_ENV=staging`) config variable on Heroku to 'staging' and it would use that file and have the smtp settings relevant to that environment loaded.
Read more about config variables (which may also be used for SMTP settings) at < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails 3, heroku"
} |
Merge into list groupby in pandas
I have a such dataframe
id sid frame type
1 10 15 person
2 11 45 person
2 11 45 animal
3 13 75 person
4 14 45 person
my goal is to transform this dataframe in this.
id sid frame type
1 10 15 person
2 11 45 [person, animal]
3 13 75 person
4 14 45 person
Im looking a for a way to merge `type` column in a row with the same `id, sid, frame` | You can use `groupby` with `list` with condition:
df = (df.groupby(['id','sid','frame'])['type']
.apply(lambda x: x.tolist() if len(x) > 1 else x.values[0])
.reset_index())
print (df)
id sid frame type
0 1 10 15 person
1 2 11 45 [person, animal]
2 3 13 75 person
3 4 14 45 person
If all values should be `list`s:
df = (df.groupby(['id','sid','frame'])['type']
.apply(list)
.reset_index())
print (df)
id sid frame type
0 1 10 15 [person]
1 2 11 45 [person, animal]
2 3 13 75 [person]
3 4 14 45 [person] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas"
} |
Run JUnit Test on a file not in project folder
I would like to run a JUnitTest on a .java file which is not in the project folder. So far I implemented running the test succesfully if the .java file which should be tested is in the project folder:
public Result testAStudent(Class aTestClass){
Result r = org.junit.runner.JUnitCore.runClasses(aTestClass);
return r;
}
How can I run the test on a file which is not in my project folder? I found a possibility to do it in the shell, but I do not want to execute shell commands. Is there a way to do it "internal"? Thank you! | Unit tests allow testing compiled class files. Not `.java` source files. For the test to be able to use (and thus test) a given class, this class must be available in the classpath.
So, when launching JUnit, make sure to have the directory or jar file containing the classes to test in the classpath. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, junit"
} |
Joining 2 text files using pandas, 1st text file into header, the 2nd as the body
I am using jupyter and I have 2 text file. dataset.txt and feature_names.txt. I input the following code.
header1 = r'./data/feature_names.txt'
main = r'./data/dataset.txt'
df = pd.read_csv(main, names=[header1])
The output
For some reason it only printed ./data/feature_names.txt although when I print the header it prints fine. But the only issue is when I join it with the main. I'm not sure how to make the header file become a header. I am using the Jupyter Website for help but I still don't get it. I was told this would be enough to do solve this problem. | The problem is that the `names` parameter of the `read_csv` function expects an array of names. You instead passed it the name of the file which contains your column names. Try this:
header1 = r'./data/feature_names.txt'
header_file = open(header1, 'r')
# Assuming one column name per line
headers = []
for line in header_file:
headers.append(line.strip())
header_file.close()
main = r'./data/dataset.txt'
df = pd.read_csv(main, names=headers) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, jupyter"
} |
SSLException - Connection closed by peer on Android 4.x versions
The issue is not occurring on higher OS versions. Is there a known problem on Android 4.x versions?
If yes, how can this issue be addressed? Should there be a change on the mobile app or on the backend side? | I actually don't have the full stack trace. This is what's visible to me.
IOException:Connection closed by peer
EXCEPTION class: class javax.net.ssl.SSLException
EXCEPTION cause: null
EXCEPTION message: Connection closed by peer
RESPONSE: SSLException
The issue was due to TLSv1 being disabled on backend.
Depending on the case there can be two approach to address this issue.
1\. Enable TLSv1 on backend server.
2\. As suggested, update the SSLEngine to support higher TLS versions on mobile app. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 6,
"tags": "android, ssl, android 4.4 kitkat"
} |
Prove that $\left[\mathbb{Q}(\sqrt[3]{5}+\sqrt{2}):\mathbb Q\right]=6$
> Prove that $\left[\mathbb{Q}(\sqrt[3]{5}+\sqrt{2}):\mathbb Q\right]=6$
My idea was to find the minimal polynomial of $\sqrt[3]{5}+\sqrt{2}$ over $\mathbb{Q}$ and to show that $\deg p(x)=6$
_Attempt:_
Let $u:=\sqrt[3]{5}+\sqrt{2}\\\ u-\sqrt[3]{5}=\sqrt 2\\\ (u-\sqrt[3]{5})^2=2\\\ u^2-2\sqrt[3]{5}u+5^{2/3}-2=0\\\ u^2-2-5^{2/3}=2\sqrt[3]{5}u\\\ (u^2-2-5^{2/3})^3=2^3\cdot 5 \cdot u$
I'm stuck here
Here Wolfram's result%2Bsqrt+2)
[My previous question over $\mathbb{Q}(\sqrt[3]{5})$]( | Hint: $[(Q\sqrt[3]5+\sqrt2):Q]=[(Q\sqrt[3]5+\sqrt2):Q(\sqrt2][Q(\sqrt2):Q]$. $[Q(\sqrt2:Q]=2$ and $((\sqrt[3]5+\sqrt2)-\sqrt2)^3=5$, so $\sqrt[3]5+\sqrt2$ is a root of $(X-\sqrt2)^3-5$ in $Q(\sqrt2)$. Show that $\sqrt[3]5+\sqrt2$ is not in $Q(\sqrt2)$ and deduce that $[(Q\sqrt[3]5+\sqrt2):Q(\sqrt2)]=3$. | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "abstract algebra, polynomials"
} |
How do you find missing number in list?
Say I have a List [1,2,4,5], I would like to have a predicate that returns 3 as the missing element. You can assuming that the input list is always sorted sequentially.
My solution so far:
% missing_number/2 (ListToBeChecked, ListToBeCompared, MissingNum)
missing_number([], [], []) :- !.
missing_number([Head | Tail], [Head | Rest], Number) :-
missing_number(Tail, Rest, Number).
missing_number(_, [X | _], [X | Node]) :-
missing_number(_, _, Number), !. | Use `between/3` to generate all numbers from min to max. Use `memberchk/2` (or `member/2`) to find the missing ones.
L = [1,2,4,5],
L = [M|_],
last(L, N),
between(M, N, I),
\+ memberchk(I, L).
Exercise for the reader: wrap this up in a predicate.
**EDIT** Efficient solution, by popular request:
missing([I,K|_], M) :-
I1 is I+1,
K1 is K-1,
between(I1, K1, M).
missing([_|Ns], M) :-
missing(Ns, M).
**EDIT 2** : More elegant version of the above, inspired by @chac, not necessarily very efficient:
missing(L,M) :- append(_, [I,J|_], L), I1 is I+1, J1 is J-1, between(I1,J1,M). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "prolog"
} |
How to allow jenkins from local machine to run remote python test scripts
I have a jenkins running on my local centos machine.
I have configured my local jenkins and was able to run a successful local build . Now, i want to run remote tests which are python scripts on a remote centos machine which is not having jenkins installed. also, i dont want to install any jenkins process on the remote linux system as it is "like a" production server and am advised not to install any apps on it. How do i use my local jenkins to run a build to execute those remote tests and report/output on my local jenkins console.
Do i need to use jenkins master-slave architecture ? if yes, how do i configure that given my above requirement. | You might want to have a look at this: <
for you req, precisely this part: <
However, i believe you still have to have java on your slave unix node to run the slave.jar on it | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, jenkins, jenkins slave"
} |
PHP: Parse unnamed arguments from url
I'm truing to parse arguments like ` module/border.php?type,colorScheme,template`. How to parse it by `$_GET`?
`print_r($_GET);` outputs `Array ( [type,colorScheme,template] => )` | Try:
$args = explode(",", key($_GET)); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "php"
} |
Are there any benefits to develop for ios in Mavericks ?
I have Snow Leopard and I want to upgrade so that I can start developing for iOS. I know I need 10.7 (Lion) but was wondering if there's any real benefit to upgrade to the latest OS (Mavericks) ?
thanks | The current version of Xcode on the App Store (5.0.2) requires Mountain Lion (10.8.4), so that's a good reason to be running at least 10.8. Always good to use the latest tools.
And really you might as well just upgrade to Mavericks seeing as the upgrade is free. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "osx snow leopard"
} |
Does Quicksort always have quadratic runtime if you choose a maximum element as pivot?
If you have a quick-sort algorithm, and you always select the smallest (or largest) element as your pivot; am I right in assuming that if you provide an already sorted data set, you will always get worst-case performance regardless of whether your 'already sorted' list is in ascending or descending order?
My thinking is that, if you always choose the smallest element for your pivot, then whether your 'already-sorted' input is sorted by ascending or descending doesn't matter because the subset chosen to be sorted relative to your pivot will always be the same size? | The worst case complexity for quicksort is $\Theta(n^2)$. This is achieved by picking pivots that divide the set such that one group has only a single member. With a bad pivot picking algorithm, this can easily be achieved by picking one end of a sorted set. Your assumption is correct. | stackexchange-cs | {
"answer_score": 16,
"question_score": 9,
"tags": "algorithms, time complexity, algorithm analysis, runtime analysis, sorting"
} |
Ruby on Rails: Faster way to navigate through YAML files?
I am just localizing a Rails app for the first time and I wonder if there's a shorter way to say this:
flash[:success] = t('.views.person.flash_messages.person_was_successfully_updated')
This is an excerpt of my `de.yml` file:
de:
views:
person:
flash_messages:
person_was_successfully_updated: "Person aktualisiert."
I would _looove_ to say something like this:
flash[:success] = t('person_was_successfully_updated')
But Rails is giving me an error, when I try to do so.
I don't understand why because `person_was_successfully_updated` is absolutely unique in my `.yml` file and I don't see the need for typing in the entire path every time. This is not very _DRY_ either.
Any ideas? | _I would looove to say something like this_
If you want to call `person_was_successfully_updated` directly then you should put that in first level. i.e., under **de:**..
_But Rails is giving me an error, when I try to do so._
Yes it will definitely give error because there is no `person_was_successfully_updated` in root level.
For more info. < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails 3, ruby on rails 3.1, ruby on rails 3.2"
} |
How to remove a text block from a file with bash
I have file of bind config with following config:
zone "domain1.com" {
type master;
file "masters/domain1.com";
allow-transfer {
dnscontroller_acl;
};
};
zone "domain2.com" {
type master;
file "masters/domain2.com";
allow-transfer {
dnscontroller_acl;
};
};
zone "domain3.com" {
type master;
file "masters/domain3.com";
allow-transfer {
dnscontroller_acl;
};
};
zone "domain4.com" {
type master;
file "masters/domain4.com";
allow-transfer {
dnscontroller_acl;
};
};
How to remove zone config (start from `zone` filename and end of `};`) from file with help of bash? | You can use `sed` to remove the config for a given zone:
sed '/^zone "domain4.com" {$/,/^};/d' file
If you want a script that can take a zone as an argument, just add the she-bang and the argument:
#!/bin/bash
sed '/^zone "'"$1"'" {$/,/^};/d' file | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "linux, bash, sed, awk"
} |
Xamarin Forms Hardware Button CrossPlateform
I don't find any solution or explaination to use the **BackButton hardware** (Android & WinPhone 8.1) from MyPage, defined in the **PCL** part.
Is it possible to handle that button from a Portable Class Library?
Thank | Yes it is. You can ovveride default behaviour for back button in pcl. For example if you want to deactivate it, you can use in the page you want:
protected override bool OnBackButtonPressed()
{
return true;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "button, xamarin.forms, hardware"
} |
bgp filtering based on conjunction of prefix-list and as-path originator
Is there any way of having a filter that uses as-path origin and prefix-list together. For example I want to accept updates from origin of AS 5745 and prefix-list is say 189.150.20.X/24. Any other prefix from origin AS 5745 will be denied.
Thanks. | For Cisco IOS, You can have more than one match criteria, and they will be processed as a logical AND.
For example
Route-map mymap permit 10
Match as-path access-list abc
Match ip prefix-list def
The route map will only match prefixes that match abc AND def.
For IOS-XR, there is a more flexible method than route- maps called RPL. | stackexchange-networkengineering | {
"answer_score": 3,
"question_score": 0,
"tags": "bgp"
} |
solutions to overcome "site goes offline due to mysql 'max_user_connections' error."
I have been working on eCommerce site (using drupal). Few days ago before i am getting this error my site was working fine no issues was there. But now a days no. of times my site goes offline with the error message ('max_user_connection').
I was using some custom code containing mysql_connect and mysql_query now i changed everything into module and no custom queries left as such.The error is still their. On some of the pages data is populated with two different databases and to handle two database at same page i am using drupal function db_set_active().
I had discussed with hosting provider also they have increased a 'connection_limit' but error is still coming, what will be the possible reasons of having this kind of issue and the ways to handle this. | In this case the dbms is not able to serve all incoming connection requests to the database.
You can check with the "show full processlist" (which requires SUPER privilege) for current count of connections.
You now have either two choices: alter you application logic so that overall connections are descreased or you can try to alter the max_connections system variable in order to allow your DBMS to server more connections (also requires SUPER privilege).
But if your provider already told you that they increased 'connection_limit, you should go for the first approach (alter your application logic). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, database, drupal"
} |
Is it posible to play iPod songs using AVAudioPlayer?
I have a question that, Is it possible to get and play the iPod library songs / playlist using AVAudioPlayer instead of using MPMusicPlayer?
Thanks in advance, Chandra. | One way i tried with is just copy the song from iPod library to your app then you can play. When you close then you can delete also those songs. But makes your app heavy in terms of size. See my post.
Another way i found is using AVPlayer of AVFoundation framework. This supports iPod library. For reference of AVPlayer you can go to post | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios4, avaudioplayer, mpmusicplayercontroller"
} |
What JQuery script is this?
<
On the right hand side, there are selector tabs (with the selected arrow pointing to the left)
What CSS menu is this? Why can't I find this on the JQuery UI website? | It's not a plugin, it's a simple bit of html/css/javascript that's on the page.
the javascript that controls the menu is in < .
The specific part:
//Rewrite and prepare links of right-hand sub navigation
$('#demo-config-menu a').each(function() {
$(this).attr('target', 'demo-frame');
$(this).click(function(e) {
resetDemos();
$(this).parents('ul').find('li').removeClass('demo-config-on');
$(this).parent().addClass('demo-config-on');
//Set the hash to the actual page without ".html"
window.location.hash = this.getAttribute('href').match((/\/([^\/\\]+)\.html/))[1];
loadDemo(this.getAttribute('href'));
e.preventDefault();
});
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, css, templates"
} |
hosting asmx web service in .net 2.0 clr without iis
I have .net 2.0 asmx service. Have windows xp sp2 without IIS, with .net 2.0.
I know about hosting wcf server in your app, but it's only in 3.5 framework.
i have no right to install higer .net or iis on this machine.
How i can easily host that service, maybe some known libraries? | Compile the `WebService` with .NET 2.0 instead of 3.5 or 4.0 and you should be able to host it inside your IIS.
Here is an example on how to create and host a Web Service using .NET 2.0 and IIS.
**Update**
Since you don't have IIS and probably Can't install it, you can use Web Matrix, it's not a software that should be use to host your web services permanently, but it's very ideal when you develop web applications. You don't even need administration priviliges since it uses ports above 1024. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, soap, asmx"
} |
XML key/keyref across multiple XML instances
is it possible to validate key/keyref across multiple XML instances. Example: xsd1 defines a schema and namespace for a list of DataTypes, each DataType has a unique identifier ID which is defined as a keyref. xsd2 defines a list of entities, that shall use the IDs from xsd1. In the XML authoring software Oxygen e.g. the xsd-referencing with key/keyref across the two namespaces works, but I do not manage to create a validation scenario like: "Field X in XML2 (validated against xsd2) can only contain values from the fields ID in XML1(validated against xsd1)"
Is this possible in XML-authoring state at all? Or would I always have to implement that validation manually? Which wouldn't be a big deal, but it might be helpful to provide users with a sophisticated authoring-validation-toolbox if such exists.
Many thanks in advance! | It is not possible to do it with XSD. You could do it across documents using Schematron. Now, Schematron equivalent for key/keyref is not that declarative as its XSD counterpart, but nonetheless doable. Have a look at this article for details... keep in mind that it is meant to be a generic solution to the key/unique/keyref construct, you could probably do it simpler for your particular case. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "xml, validation, xsd, key, keyref"
} |
Where can find examples and tutorials for Perl's Net::Pcap module?
Could someone provide a good documentation / tutorial/ PDFs/ reference to book link about `Net::Pcap` in addtion to the module documentation and this Perl and Net::Pcap article on PerlMonks? | See Chapter 2 materials for Programming the Network with Perl. See also an example included in the distribution. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "perl, network programming"
} |
Rails: tumblr_client gem works in console, not in app
I'm new to Rails and have been writing a simple app to post to Tumblr. I got all my oauth stuff working, and decided to use the tumblr_client gem to facilitate posting. I can get it to post just fine through the console, but the same code does not do anything in the controller. It doesn't throw any errors, it just does nothing. Any suggestions? (I censored the blog with {blogname}, but it is correct in my code)
def post
@user = Tumblog.find_by_user_id(5)
@client = Tumblr::Client.new(:consumer_key => @key, :consumer_secret => @secret, :oauth_token => @user.oauth_token, :oauth_token_secret => @user.oauth_secret)
@client.text("{blogname}.tumblr.com", :body => "test", :state => "draft")
redirect_to "
end | It turns out that it was a conflict with my instance variable name. Changed `@client` to `@clients` and it worked just fine. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "ruby on rails, ruby, tumblr"
} |
C言語のstrcmp関数を実行すると、例外のスローというのが出てきて実行されません
0x560FC6BC (ucrtbased.dll) (ConsoleApplication1.exe ): 0xC0000005: 0x00900000
#include "pch.h"
#include <iostream>
#include<string.h>
#include<stdio.h>
int main(void)
{
char str1[256], str2[] = "DRAGONQUESUT";
scanf_s("%s", str1);
if (strcmp(str1, str2) == 0) {
printf("\n");
}
else {
printf("\n");
}
return 0;
} | `strcmp`
`scanf_s`
> Unlike `scanf` and `wscanf`, `scanf_s` and `wscanf_s` require you to specify buffer sizes for some parameters. Specify the sizes for all `c`, `C`, `s`, `S`, or string control set [] parameters. The buffer size in characters is passed as an additional parameter. It immediately follows the pointer to the buffer or variable. For example, if you're reading a string, the buffer size for that string is passed as follows:
>
>
> char s[10];
> scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification is 9
>
`scanf``%s`
CC++
scanf_s("%s", str1, (unsigned)_countof(str1));
| stackexchange-ja_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c, visual c++"
} |
Order by id desc in google app engine
Im using google app engine data-store built in eclipse using my model for the table. The id is just the date and time from android.
I can query by a row like this and it does work!
select from Quotes as Quotes ORDER BY votes DESC
I want to get my results back by my entities id however this query does not work
select from Quotes as Quotes ORDER BY Id DESC
Here is my table. How can I query by my id/Name and trust me ive tried
select from Quotes as Quotes ORDER BY ID/Name DESC
!enter image description here
edit: you probably notice i have a dummyid. I do not want to use that row because I made it in a very hacky way and requires extra loading on the users side. | Oh, dear. I see the problem, now. You have a column named `ID/Name`. It's usually wise to keep identifiers limited to alphanumeric characters.
Can you rename the column? That would be the best step forward.
If that's not an option, you can wrap it in backticks so that it's treated as an identifier:
SELECT * FROM Quotes ORDER BY `ID/Name` DESC;
See SQL Fiddle, which almost certainly won't match your schema but should get the point across. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android, mysql, sql, google app engine"
} |
How to uniquely identify organism in planet , in which all are biologically same?
Consider a planet where there is only one type of organism. And this organism reproduces through fission.
Thus the offspring is exactly similar to the parent. These organisms are multi-cellular and similar to human in structure and behavior but every single body is genetically identical to the others.
What may be the other ways which they may use to avoid confusion among them and to identify a specific individual?
The population in the planet is about 100 million units. And their technology is similar to our year 1900. | # Name tags
_Because why not?_
As life goes on we tend to wear our histories on our skin. A tan, scars and tattoos, a beard, a limp, age that shows more for one than for another, the marks of stress or a soft life. Whether you carry a little extra weight, train hard, or just diet.
As a being undergoes fission, the children are identical to the parent, though of about half the mass, and to each other. There's no way to distinguish between them, but equally there's no reason to. As their lives lead separate ways, as with identical twins, they'll start to look different and the differences will show. | stackexchange-worldbuilding | {
"answer_score": 4,
"question_score": 0,
"tags": "aliens"
} |
Is it safe to move the .ethereum data directory?
I just bought a new 1TB SSD drive and I would like to move my .ethereum directory from the 60GB to the 1000GB HD. Is it safe to simply move the directory? | Should be fine (I've done it several times with Parity's data directory and with `geth`). However, if the logical location of the directory has moved, you need to make sure your Ethereum client knows to look for the data directory in the new location. `geth` is perfectly happy with symlinks. Alternately, you can use the `--datadir` option when starting `geth`. | stackexchange-ethereum | {
"answer_score": 2,
"question_score": 2,
"tags": "storage, datadir"
} |
UV export layout for baking in cycles
just a quick question : is it possible to save the UV map with the UV export layout when we create a mesh, so we can just use it for do the baking and dont be obliged to unwrap again?
I hope im clear enought with my broken english.
Thanks | UV layouts are saved withing the mesh itself, not exported. You should never have to "unwrap again" unless you change your mesh, exporting is used for editing textures in external applications like Photoshop, GIMP, or other image editing software – Duarte Farrajota Ramos | stackexchange-blender | {
"answer_score": 0,
"question_score": 0,
"tags": "baking"
} |
Parabolas passing through $4$ given points in an affine plane
I need to find equations for parabolas which are passing through $(0,-1)$,$(-2,0)$,$(0,3)$,$(4,0)$. Help me. I know that parabolas determined by those four points but how to find equations explicitly? | Use the general parabola equation below,
$$ax^2 + 2\sqrt{ab}xy + b y^2 + gx + fy + c = 0$$
Plug in the points (0,-1) and (0,3) and, without losing generality, let $b=1$ for now,
$$1-f+c, \>\>\>9+3f+c = 0$$
which gives $f=-2$ and $c=-3$. Then, plug in the points (-2,0) and (4,0),
$$4a -2g-3=0,\>\>\>16a+4g-3=0$$
which gives $a=\frac 38$ and $g=-\frac 32$.
Thus, the equation for the parabola is,
$$\frac 38 x^2 + \sqrt{\frac 32 }xy + y^2 -\frac 32 x - 2y -3= 0$$
or, with $b=8$,
$$3 x^2 + 4\sqrt{6}xy + 8y^2 -12 x - 16y -24= 0$$
Edit: As pointed out by @Blue below. A second equation can be obtained by reserving the sign of the cross term. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "geometry, affine geometry"
} |
Dropbox Core API list all folders
So I have been playing with Dropbox APIs for awhile. My app is retrieving all the image files from a user's dropbox via Core API.
Now I want to improve it a bit by allowing users to choose which folder to sync.. i.e. once they authorise the app, it will give them all the folders inside their account. Users can then choose one or many folder(s), the app will only retrieve image files from selected folders.
Is there a specific API that list out all folders inside a user's dropbox?
I'm not using any SDK. | Using the ` gives you the details of the contents of directory
import requests
...
headers = ... # set up auth
...
params = { 'list' : 'true' }
response = requests.get(' params=params, headers=headers)
subdirs = [d['path'] for d in response.json()['contents'] if d['is_dir'] == True]
print(subdirs) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "python, dropbox, dropbox api"
} |
Hide part of an email address
What's the best way to hide 4 characters before the @ sign of an email address using ruby eg
[email protected] = fake####@example.com
It's going to be used in a view when I display a list of testimonials and I don't want to display the whole address.
My long way round attempt:
name = '[email protected]'.split("@")[0]
email = '[email protected]'.split("@")[1]
new_address = name [0..-4] + "@" + email | Try the below that will even handle short names like [email protected]
'[email protected]'.gsub(/.{0,4}@/, '####@') | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "ruby on rails, ruby"
} |
How to add a new column in an existing table in Rails 5?
I want to add a new column in one of my table in Rails 5. I recently renamed a column by using the following way:
rails g migration ChangeJobsTable
then in `20160802104312_change_jobs_table.rb`:
class ChangeJobsTable < ActiveRecord::Migration[5.0]
def change
rename_column :jobs, :skills, :skills1
end
end
then
rails db:migrate
It worked fine, but now if I want to also add a new column `skills2`, do I need to do it like this?
class ChangeJobsTable < ActiveRecord::Migration[5.0]
def change
add_column :jobs, :skills2
end
end | You forgot to add `datatype`, below is the updated migration.
class ChangeJobsTable < ActiveRecord::Migration[5.0]
def change
add_column :jobs, :skills2, :string
end
end | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 11,
"tags": "ruby on rails, ruby, rails migrations, ruby on rails 5"
} |
Select newest datetime for each userid MS Sql Server
I have a table used for a chat. Among others there is a field called userid and a field called timesent. I need to know the latest timesent for each userid in the table, so that I can delete them from the table if they haven't said anything for 3 minutes, in which case I will assume they are gone.
I can't really crack this nut... How do I query.
I could of course split it up and first select all the userids and then loop through them and select top 1 timesent in my method, but I was wondering if sql alone can do the trick, so I don't need to execute tons of queries. | To get the latest `timesent` per `userid` you can use `MAX`
SELECT userid, MAX(timesent) AS timesent
FROM your_table
GROUP BY userid
Or to do the specified `delete` you can use
DELETE your_table
FROM your_table y1
WHERE NOT EXISTS(SELECT *
FROM your_table y2
WHERE y2.userid = y1.userid
AND y2.timesent >= DATEADD(MINUTE, -3, GETDATE())) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "sql server, select"
} |
How does the Dow Jones Industrial Average (DJIA) divisor change to account for dividends?
The DJIA is a price-weighted index tracking of 30 companies chosen by the Dow Jones Company. It takes the current share price of these 30 stocks and divides by a specific number called the _divisor_. The index is not affected by price changes caused by stock splits and dividend payments, which is due to the divisor being changed in response to stock splits and dividend payments.
How does the divisor change for a **dividend payment**? Is there a specific equation to take into account the amount of dividend sent out? I have only seen information on how the divisor changes for stock splits. | The methodology for divisor changes is based on splits and composition changes. Dividends are ignored by the index.
Side note - this is why, in my opinion, that any discussion of the Dow's change over a long term becomes meaningless. Ignoring even a 2% per year dividend has a significant impact over many decades.
The divisor can be found at < | stackexchange-money | {
"answer_score": 5,
"question_score": 4,
"tags": "stocks, calculation, dividends, market indexes"
} |
Let A be a family of pairwise disjoint sets. Prove that if B⊆A, then B is a family or pairwise disjoint sets.
I know that for this problem I have to use contradiction. Could anyone check my work and guide me through the problem if it's wrong? So far, this is what I have.Thanks!!
Contradiction: $\mathcal B\subseteq \mathcal A$, then $\mathcal B$ is not a family of pairwise disjoint sets.
If $\mathcal B$ is not pairwise disjoint then $\mathcal A \neq \mathcal B$ or $\mathcal A \cap \mathcal B\neq \varnothing $
then, x $\in \mathcal A$ and x$\notin \mathcal B$
However, x $\in \mathcal B\subseteq \mathcal A$ , which is a contradiction since we said that x$\notin \mathcal B$. | There is no need to use contradiction. Suppose that $B_0,B_1$ in $\mathscr{B}$ with $B_0\ne B_1$. Then $B_0$ and $B_1$ are distinct members of $\mathscr{A}$, so $B_0\cap B_1=\varnothing$ (since $\mathscr{A}$ is a pairwise disjoint family). Thus, every pair of distinct members of $\mathscr{B}$ are disjoint, and by definition $\mathscr{B}$ is a pairwise disjoint family.
The argument that you’ve given does not make sense. $\mathscr{B}$ is a **family** of sets, and in order to show that this family is pairwise disjoint, you must show that if $B_0,B_1\in\mathscr{B}$, then either $B_0=B_1$, or $B_0\cap B_1=\varnothing$. There is no point to looking at $\mathscr{A}\cap\mathscr{B}$: we know that $\mathscr{A}\cap\mathscr{B}=\mathscr{B}$ simply because $\mathscr{B}\subseteq\mathscr{A}$. This fact has in itself no bearing on whether $\mathscr{B}$ is pairwise disjoint. | stackexchange-math | {
"answer_score": 4,
"question_score": 2,
"tags": "elementary set theory"
} |
Ruby: how to check how many parameters a block accepts?
I'm trying to set up a method that takes a block as a parameter. I know you do this by giving the last parameter an & prefix, but once it's been passed, how should I verify it?
If I want to verify that an argument is a string, I could use `is_a?(String)`, for example. But how do I verify that I have received a block that accepts one parameter? Or 2? | You can use the `Proc#arity` method to check how many arguments the block accepts:
def foo(&block)
puts block.arity
end
foo { } # => 0
foo { |a| } # => 1
foo { |a, b| } # => 2
From the documentation:
> Returns the number of arguments that would not be ignored. If the block is declared to take no arguments, returns 0. If the block is known to take exactly n arguments, returns n. If the block has optional arguments, return -n-1, where n is the number of mandatory arguments. A proc with no argument declarations is the same a block declaring || as its arguments. | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 4,
"tags": "ruby"
} |
Does python coerce types when doing operator overloading?
I have the following code:
a = str('5')
b = int(5)
a == b
# False
But if I make a subclass of `int`, and reimplement `__cmp__`:
class A(int):
def __cmp__(self, other):
return super(A, self).__cmp__(other)
a = str('5')
b = A(5)
a == b
# TypeError: A.__cmp__(x,y) requires y to be a 'A', not a 'str'
Why are these two different? Is the python runtime catching the TypeError thrown by `int.__cmp__()`, and interpreting that as a `False` value? Can someone point me to the bit in the 2.x cpython source that shows how this is working? | The documentation isn't completely explicit on this point, but see here:
> If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a `__cmp__` method or rich comparison methods like `__gt__`, described in section Special method names.
This (particularly the implicit contrast between "objects of different types" and "objects of non-built-in types") suggests that the normal process of actually calling comparison methods is skipped for built-in types: if you try to compare objects of two dfferent (and non-numeric) built-in types, it just short-circuits to an automatic False. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "python"
} |
Insert <span> in <p> element
I got like;
<p>Variable Text</p>
And I want to it to be;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function. | Try this
var txt = "Hello bye";
var dataArr = txt.split(' ');
var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";
Here is a demo | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 8,
"tags": "javascript, css, text, html"
} |
How to extract a sublist by the value of the first element from a nested list
I want to extract a sublist from a nested list based on the first element in each list. I have the following nested list:
input = [
['nom', 'N', 'eye'],
['acc', 'E', 'computer'],
['dat', 'C', 'screen']
]
I want to have a function which returns `['nom', 'N', 'eye']` when the first element of the sublist `'nom'` is inputted, for instance:
output = ['nom', 'N', 'eye'] # When the function takes 'nom' as its argument
output = ['acc', 'E', 'computer'] # When the function takes 'acc' as its argument
output = ['dat', 'C', 'screen'] # When the function takes 'dat' as its argument
How should I achieve this with python3.6+? | my_list = [
['nom', 'N', 'eye'],
['acc', 'E', 'computer'],
['dat', 'C', 'screen']
]
my_input = input("Enter first string to find: ")
for lis in my_list:
if lis[0] == my_input:
print(lis)
break
Output:
Enter variable name: nom
['nom', 'N', 'eye'] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "python, python 3.x, list"
} |
How to use Ios UI Automation xpath in appium for ios
I am using iosuiautomator for finding the xpath of element
. while running following error is displaying
.target.().etc`. You can start from right after `mainWindow()`. I also noticed you put the tap action inside the quotes but is actually a function of the mobile element (and has 2 parameters) so what you'd want is:
`driver.findElementByIosUIAutomation(".tableViews()[2].cells()[2]").tap(1, 250)` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "appium, ios ui automation, appium ios"
} |
Как отсортировать массив из структур?
Есть структура вида:
type RegionStruct struct {
Id int
Name string
Num string
}
Есть массив состоящий из структуры:
var Regions []RegionStruct
Как отсортировать массив в алфавитном порядке по ключу `Name`? Как отсорировать массив по ключу `Num`? | Используйте `sort.Slice`:
var rs = []Region{{
Name: "C",
}, {
Name: "A",
}, {
Name: "B",
}}
sort.Slice(rs, func(i, j int) (less bool) {
return rs[i].Name < rs[j].Name
})
fmt.Printf("%+v\n", rs)
// Output:
// [{ID:0 Name:A Num:} {ID:0 Name:B Num:} {ID:0 Name:C Num:}]
_Playground_ : <
Либо имплементируйте `sort.Interface`.
* * *
Уважайте сообщество! Форматируйте ваш код и следуйте правилам именования! | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "golang, сортировка"
} |
Get site region DateTime in ASP.NET
I need to get real DateTime by CultureInfo object. For example, my site is on US company server (that has own US time) but site is for Italy (example), where time is different, and on the site I should show Italy time, not US. In web.congig I have currentCulture="it-It"
Is it possible to get time for site and if so, what is the right way to do it? Actually it would be great to have a function like:
public static DateTime GetSiteDate(CultureInfo ci)
{
....
return siteDate;
}
Thanks! | It is likely not possible to get the local time based on culture alone, mostly because time zones don't correspond one-to-one to countries. While Italy's time zone is Central European Standard Time (if I'm not mistaken), it will not always be the case that each country has a single time zone. For example, in the United States there are at least four time zones. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net, datetime, cultureinfo"
} |
Get Tables and Relationships
Is there a way to get a list of tables and relationships from an EDMX using the MetadataLoader? | Try this:
MetadataWorkspace metadataWorkspace = null;
bool allMetadataLoaded = loader.TryLoadAllMetadata(inputFile, out metadataWorkspace);
StoreItemCollection itemCollection = (StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace);
// Tables
foreach (var entity in itemCollection.GetItems<EntityType>())
{
...
}
// Relations
foreach (var association in itemCollection.GetItems<AssociationType>())
{
...
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": ".net, entity framework, edmx"
} |
List all constants from a unit
I need to convert a huge number of constants from an application. Is it possible to get all the constants declared in a unit and their values, other then parsing the .pas file? | It seems that this is not possible without parsing your unit and extract the constants. During the compilation constants are replaced by value, so it is impossible to get the value from them at runtime.
LE: maybe there is someone who can explain this in depth. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "delphi, delphi 2006"
} |
How to make a dynamic list of elements appear horizontally up to each 6 index and then vertically in flutter
I have a dynamic list which will be increased every 10 seconds and I want this list to be displayed in flutter UI in such a way that the first 6 numbers should display on the first line and the next 6 numbers should display on the next line and so on.
Currently, the code I made just displays a list in a horizontally scrollable view.
Widget horizontalList1 = new Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 40.0,
child: new ListView(
scrollDirection: Axis.horizontal,
children: calledNumersArray(),
)
);
,
height: 40.0,
child: GridView.count(
count: calledNumbersArraay().length
crossAxisCount: 6,
children: calledNumersArray(),
)
);
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "flutter, flutter layout"
} |
What's best pass data to another activity or do two queries to sqlite
I've a big questionaire to fill, so I've decide to split it in two activities/screens. My question is: \- Should I send the data from activity1 to activity2 (startActivityForResult) and insert all the data on sqlite with an insert on activity2? \- Should I make an insert on activity1 and an update on activity2 since I know the row _id?
The option 1 is better to ensure the user fills all the questionaire, right? | First option is better, because with this you will never have incomplete information in database (what happens if user exits from app when he finishes with first screen?) and you only will make a unique call to insert data. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android"
} |
How to schedule tasks without Quartz
Can anyone tell,advice how to run a scheduler without Quartz in java. I want to implement such features that if application server remain stop , my scheduler will run. So I thought the executable class to place outside of the war file. So can anyone give me suggestion ? Thanks. | Regarding scheduling tasks without `Quartz`, you can use Java's ScheduledExecutorService:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
// Beeps every 10 seconds
scheduler.scheduleAtFixedRate(beeper, 0, 10, TimeUnit.SECONDS);
Now, regarding doing it when your application is not running, I see three options:
* Develop a stand-alone application with your scheduled tasks, decoupled from your webapp
* Look up for Application Server features for that purpose
* OS scheduled tasks, as Linux's cron job | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, job scheduling"
} |
Eureka Server - list all registered instances
I have a Spring Boot application that is also a Eureka Server. I want to list all instances that have been registered to this Eureka Server. How do I do it? | Fetch the `registry` using `EurekaServerContextHolder.getInstance().getServerContext().getRegistry()` then use the `registry` to list all `Applications`
PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext().getRegistry();
Applications applications = registry.getApplications();
applications.getRegisteredApplications().forEach((registeredApplication) -> {
registeredApplication.getInstances().forEach((instance) -> {
System.out.println(instance.getAppName() + " (" + instance.getInstanceId() + ") : " + response);
});
}); | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 11,
"tags": "java, spring boot, netflix eureka"
} |
PHP 7 - error in function mb_convert_encoding
My knowledge of PHP is limited, so I searched the solution for this problem before, but I couldn't fix it.
Upon upgrading PHP to version 7, a script is returning the error:
> Call to undefined function mb_convert_encoding()
Which refers to the line:
echo "<td>" . mb_convert_encoding($row['teste'],'utf-8', 'iso-8859-1') . "</td>";
So, removing the function to:
echo "<td>" . $row['teste'] . "</td>";
Will remove the error, but now the characters are like:
Gesto oramental
Is there another function I could use? | Go to your php.ini file and uncomment `extension=php_mbstring.dll`.
_mb_convert_encoding_ is also supported in PHP 7, so it should work. It's probably an extension problem. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
Truncate string and replace with "X" Python Pandas DataFrame
I have a df such as:
d = {'col1': [11111111, 2222222]]}
df = pd.DataFrame(data=d)
df
col1
0 11111111
1 2222222
I need to remove everything before the first four characters and replace with something like "X" such that the new df would be
d = {'col1': [XXXX1111, XXX2222]]}
df = pd.DataFrame(data=d)
df
col1
0 XXXX1111
1 XXX2222
New to python still and have been able to for example slice the last four characters. But have not been able to replace everything else with X's.
Also, strings can be different lengths. So the number of X's is dependent on the length of the string. That particularly is what has given me trouble. If they were all the same length this would be much easier. | df['col1'] = list(map(lambda l: 'X'*(l-4), df['col1'].astype(str).apply(len))) + df['col1'].astype(str).str[-4:]
* `map()` is to repeat `X` `n-4` times, where `n` is the length of each element in `col1`.
* `.str[-4:]` is to get the last 4 character in `col1` column
# print(df)
col1
0 XXXX1111
1 XXX2222 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, pandas, dataframe"
} |
Does the SES email quota apply to verification mail by Amazon Cognito?
I'm setting up Amazon Cognito user pools as means to authenticate my users. Cognito sends verification emails (password reset, confirm email address etc.). Cognito uses Amazon SES for sending emails and Amazon SES is limited to 200 daily email quota per day. I'm afraid that once I've imported all my users to Amazon Cognito, resulting with each of them receiving a couple of emails upon their next login, I'll be well over the quota and they will not be able to receive those emails. Does anyone know whether this quota applies to automatic emails by Amazon Cognito? | Cognito has gotten a much higher sending limit than 200, you shouldn't run into issues. If you do, feel free to reach out to us via the forums/support and we can get you around that. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "amazon web services, amazon cognito, amazon ses"
} |
How to initialize class member array with 0
I have the next class and want to initialize _operators array with 0:
//Entity.h
class Entity
{
static const unsigned short operatorTypeColumn = 1;
static const unsigned short outputValueColumn = 4;
private:
mainDataType _operators[operatorsMaxCount][operatorsTableWidth];
}
//Entity.cpp. I thought this should work in C++ v11
Entity::Entity(void) : _operators[operatorsMaxCount][operatorsTableWidth]
{
}
I thought this sold work in C++ v11 but i got error... how can i initialize array with 0.. with ugly for? i don't want make it static | You just need to value-initialize the array:
Entity::Entity() : _operators() {}
// ^^
This works in C++03 and C++11. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 0,
"tags": "c++, arrays, initialization"
} |
How to increase mouse cursor speed in Ubuntu? (Gnome)
How do I increase the mouse speed in Ubuntu Linux? Running Gnome 2.30.0. I've already maxed out Pointer Speed Sensitivity in the Mouse Preferences control panel. I am not interested in increasing the Acceleration. Is there a config file I can edit to boost it past what the control panel allows?
I know that this mouse can track faster because it does in Windows. | Ok, if I remember right you can use the command
> xset m X Y
With X and Y being two different values, Acceleration and Threshold I believe. These settings change after a reboot so you would have to add them into a startup script. A quick search says that this command will give you your current value on ubuntu, but im not in a location I can try it right now.
> xset -q | grep accel
Also if you look in your Xorg.conf file under the section for mouse you should see an option title "Resolution" increasing this number should increase your mouse speed as well. | stackexchange-superuser | {
"answer_score": 6,
"question_score": 4,
"tags": "linux, ubuntu, mouse, gnome, speed"
} |
Pyramid with mako and pyjade
Let's say, that I have a template written in mako: `base.mako`. I would like to use it as a renderer in a view named: `base_view`. Also I have a template written in mako named: `concrete.mako`, which inherits from `base.mako` this way: `<%inherit file="base.mako" />`. It is used by different view.
Question:
I would like, to rewrite `concrete.mako` in pyjade (as a `concrete.jade`), and on rendering it, I would like it to compile to mako, and then to compile to `concrete html`. How to set it up in pyramid (it would be great, if the pyramid system will use different renderers depending on file extension, and after using pyjade will also compile pyjade output with mako compiler to concrete html).
Thx. | Well pyramid does use different renderers based on file extension. However they do not cascade or anything, a renderer just returns a string. I think you'll have to write your own `.jade2mako2html` renderer to do what you're asking.
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, pyramid, mako, pyjade"
} |
Are there any FTP programs which can automatically send the contents of a folder to a remote server?
Are there any FTP programs which can automatically copy (or rather 'move') the contents of a folder to a remote server? I have of course googled this but only really found one or two ancient products which look really clunky and unmaintained. I was wondering if there's a way to do this from the command line or any better solution to the base problem.
In more detail, new files get written to a folder every few hours. These new files need to be FTP'd elsewhere and then deleted. Mirroring or synchonisation systems are probably out of the picture as we need to delete the source files once they've been successfully transferred.
If it's easier, the 'solution' could pull the files off the server (rather than the server pushing them to the client). The computers will both be Windows OS. | In the end I used a program called FTP Auto Sync: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ftp, automation, file transfer"
} |
Bilinear form and quotient space
Let $U,V$ be two finite dimensional vector spaces of a field $K$ and let $f:U \times V \to K$a bilinear form. The set $U_0 = \\{u \in U: f(u,v) = 0,\forall v \in V \\}$ is called the left kernel of $f$ and $V_0 = \\{v \in V: f(u,v) =0, \forall u \in U\\}$ is called the right kernel of $f$.
Show that $\dim U/U_0 = \dim V/V_0$ and the kernels of $g: U/U_0 \times V/V_0 \to K$ given by $g(u+U_0,v+V_0) = f(u,v)$ is the null space.
The second statement is obvious, but how can I show the first?? that is, $\dim U/U_0 = \dim V/V_0$. | Using the bilinear form, you get a linear map $U/U_0 \to (V/V_0)^*$ and this is injective. Now compare dimensions and you get an inequality (the spaces are finite-dimensional, so dual spaces do not change the dimension). | stackexchange-math | {
"answer_score": 4,
"question_score": 1,
"tags": "quotient spaces, bilinear form"
} |
Get IPs for specific interface
`Socket.ip_address_list` gives the list of all IPs for all interfaces. How can I get the IPs for a specific interface?
I can't update my Ruby to anything newer than 1.9.3. | According to the `ip_address_list` documentation, `Socket#ip_address_list` returns local IP addresses as an array. An array has `select` and `collect` methods.
Socket.ip_address_list.select{|i| i.ipv4?}.collect(&:ip_address)
=> ["127.0.0.1", "192.168.0.13"] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "ruby"
} |
"Just wanted to know whether you consider reading this at all"
In chat, there were these lines:
> xxx: Check %title name% out. Pretty nice work.
> (after a couple of days)
> xxx: So, what do you think about it?
> yyy: Sorry, didn't have time to look at it.
> xxx: That's ok. Just wanted to know whether you consider reading this at all.
Is the last sentence of _xxx_ correct? Especially **at all** part. | I believe the structure is correct, accept that I would add something like: Just wanted to know whether you would consider reading this at all. -OR- Just wanted to know whether you had considered reading this at all.
"at all" could be left off of the sentence.
Using the word "this" is OK, because the subject you are referring to (%title name%) is still in context. If the subject was not present, you would want to refer back to the subject "%title name%". | stackexchange-ell | {
"answer_score": 0,
"question_score": 0,
"tags": "sentence construction"
} |
In GameMaker, how to bounce object further with the Bounce action?
I've set it up so that when my character collides with a wall, it bounces (non-precisely, if that matters). However, I'd like it to bounce further than it currently does, and I don't see an option to adjust it. How should this be achieved?
Thanks! | On collision, increase the velocity of the object. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "gml"
} |
C# Language Question: priority of matching
I'm reading book "C# Language", and hit this example from Page 123-124:
The meaning of a name within a block may differ based on the context in which the name is used.
In the example
using System;
class A { }
class Test
{
static void Main()
{
string A = "hello, world";
string s = A; // Expression context
Type t = typeof(A); // Type context
Console.WriteLine(s); // Writes "hello, world"
Console.WriteLine(t); // Writes "A"
}
}
the name A is used in an expression context to refer to the local variable A and in a type context to refer to the class A.
I'm fine with the visibility of class A. However, here (`Type t = typeof(A)`) class `A` preceded string `A`. So, what is the "priority" or "sequence" of matching/choosing a possible "A"? | There's no conflict. `typeof` only works on class names. To get the Type of an object instance, you use `.GetType()`. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "c#"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.