INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Selenium test priority in Flask
I have a use case in selenium in which the priority of test functions are important. I'm using `LiveServerTestCase` in flask for tests. In Java, there is a decorator `@Test(priority=0)` for defining test priorities. My question is what is the equivalent in Flask?
|
Test functions are executed according to their names(alphabetical order).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "python, selenium, liveservertestcase"
}
|
SharePoint 2007 Workflow Doesn't Trigger On InfoPath Form Submit
This is a follow-up question to this question.
This is what I expect to happen:
1. User navigates to Document Library
2. User clicks New
3. InfoPath form opens
4. User fills in data
5. User clicks Submit
6. Form submitted to Document Library
7. Workflow triggered by New Item sends stripped-down form data as e-mail
8. Everyone is happy
The problem is, I never reach Step #8 because the Workflow does not trigger. I have all three options selected for triggering the Workflow - Manual, New Item, Updated Item. The Manual trigger works great on items in the Document Library and the Workflow does exactly what it needs to do, but the other two triggers never seem to fire.
Any advice would be greatly appreciated...
|
Are you by any chance running as the system account? Have a look at this question and answer on sharepoint.stackexchange.com (where you really want to move all your SharePoint questions to)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sharepoint, sharepoint 2007, workflow, infopath, sharepoint workflow"
}
|
Can I store my getmail password in a gpg file?
Is there a way to have getmail get the password from a gpg encrypted file instead of leaving it in plain text?
|
Yes you can.
Add your key to gpg-agent or gnome-keyring, and configure either `gpg -d` or `pass` to write to stdout without prompting for key unlock. Mind to only include the password in the file. In ~/.getmail/getmailrc:
`password_command = ("/usr/bin/pass","email/gmail.pw")`
I installed getmail 5.5 from the official website instead of using the ubuntu-xenial repo (4.48) to get the password_command working.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 4,
"tags": "email, password, getmail"
}
|
How to convert a text file into excel in bash or perl
 | sed 's/:/\t/g' > a.csv
but this does not seem to work. also i want to export this text file into an excel sheet.
|
$ echo -e "header1\theader2"; cat file | tr : '\t' # > file.csv
header1 header2
aaaa 1.0
bbbb 1.1
cccc 1.3
or:
$ cat <(echo "header1:header2") file | tr : '\t' # > file.csv
header1 header2
aaaa 1.0
bbbb 1.1
cccc 1.3
Uncomment the `> file.csv` to actually write to a file.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel, bash, perl"
}
|
How do I turn .Any into a for loop?
I'm having some trouble turning the following code into a for loop. The purpose of the code is to check if the string has both a letter and a number in it.
else if (!string.Any(Char.IsLetter) || !string.Any(Char.IsDigit))
{
return false;
}
Any ideas?
|
Do you mean something like this?
bool anyLetter = false;
bool anyDigit = false;
foreach(var ch in str)
{
if(char.IsLetter(ch)) anyLetter = true;
if(char.IsDigit(ch)) anyDigit = true;
if(anyLetter && anyDigit) break;
}
return anyLetter || anyDigit;
Note that if this string should contain at least one digit **and** one letter, you need to use `&&` instead of `||`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": -2,
"tags": "c#, linq, for loop"
}
|
Codeigniter: How to include javascript files
Hello I just started working with CodeIgniter framework. My current directory structure is
Demo(Project name)
+System
+Application
-Controllers
demo.php
+Model
-Views
view_demo.php
-Js
ajax.js
jquery.js
Please tell me how to include .js files in view_demo.php.
Thanks Raj
|
You need to use the `base_url()` to include the javascript file in your VIEW.
So, in the view_demo.php file:
<script type="text/javascript" src="<?=base_url()?>js/jquery.js" ></script>
<script type="text/javascript" src="<?=base_url()?>js/ajax.js" ></script>
You will need the URL helper loaded. To load the helper you need to put on your demo.php controller:
$this->load->helper('url');
You can also autoload on \config\autoload.php on the helpers array.
More info about base_url(): < <
|
stackexchange-stackoverflow
|
{
"answer_score": 28,
"question_score": 20,
"tags": "javascript, codeigniter, include"
}
|
c#/.NET/Winforms RichTextBox : Highlight active line
I'm making a very simple text editor and I'd like to color the background of the whole selected line (left to right). And I'd like it to follow the cursor so if I go down two lines the background changes.
I'm looked a lot on here and google and found nothing interesting, it always colors the text instead of the background and it does not color the entire line, etc.
Any suggestions are welcome!
Thanks!
|
I am not sure you can easily color the full line where the caret is in the standard RichTextBox control, I think I mostly heard only the background of already entered text could be colored.
If you are not forced to stay with the standard RichText you can have a look at this:
ScintillaNET
this editor has an incredible amount of features, the only thing is that I am not sure if it supports many different fonts otr picture embedding, tables and so on.
if ScintillaNET is nout enough either I would then try with DevExpress components for Windows Forms, extremely feature rich and powerful, in theri demo they have basically made a text editor with tables, mailmerge and so many other things it looks almost like MS Word.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c#, .net, winforms, richtextbox"
}
|
Rails & MSSQL 2008 - Will We Hit Barriers?
The company I am working for is looking to switch platforms from ColdFusion 8 / Windows to Ruby on Rails / Linux. Our database solution will remain as MSSQL 2008 on Windows. I will likely follow up with a series of questions relating to this migration separately, but for now I have a MSSQL & Rails specific question.
Back in 2006 when I was working with Ruby on Rails for the first time, support for MSSQL installations was pretty iffy. Things worked for the most part, but ActiveRecord couldn't cope with certain functions lacking from T-SQL. Primarily, I recall auto-paging not working due to a lack of an OFFSET keyword like the one found in MySQL.
I am curious if our primary DB server running MSSQL 2008 will be able take advantage of **most** of ActiveRecord's functionality. If there are particular features that are not available, I'd be curious as to what they are.
|
Yes, there will be pain.
We're running Rails/SQL Server in production at the moment. All of our develompent is done on OS X / linux, and deployed to linux app servers.
We went with JRuby in the end as connecting via JDBC rather than ODBC was much less painful. JRuby itself is a good platform, but we've had no end of trouble due to quirks with 3rd party gems and plugins which often don't work under JRuby (especially if they've got native extensions).
There are still holes in the support - paging is still iffy, but kind of works now. From memory there are some quirks around unicode and character encoding as well.
The only reason SQL Server is used is because that was what the IT infrastructure team mandated. MySQL/Postgres is a much better solution if possible. It all just works.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 7,
"tags": "ruby on rails, sql server 2008, activerecord, compatibility"
}
|
How to get the Excel List values in VBA?
I have an Excel workbook in which say i have a cell A1 with dropdown list created using a formula. this is a dynamic list and keeps changing on other inputs. For example A1 will have a dropdown list of Apple, Orange, Pear
I want to read this list in VBA. Can any one help me out. Thanks in advance
|
Here's a simple example - in reality you should test there's validation and it's a List type etc:
Sub foo()
Dim vList
vList = Evaluate(Range("A1").Validation.Formula1)
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, vba"
}
|
How to add BBC podcasts to Rhythmbox?
I copied link address from RSS feed here < Then clicked ADD button in Rhythmbox podcast and added <
It gave the error that "The feed does not contain any downloadable items".
How to fix this problem?
Thanks.
|
It looks like you're adding the wrong URL. Here is what I did.
Opened Rhythmbox, clicked on Podcasts, and then right click choose New Podcast Feed, as shown in the image below.
!enter image description here
Once you get the screen shown below, add the URL (< and press Search. That will get you all the feeds, and then just choose the one you want.
!enter image description here
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 2,
"tags": "rhythmbox, podcast"
}
|
Filtering out integer from NSManaged object
I have the following core data property
@NSManaged public var part: [Int]?
and it may contain 0 or 1 or both. I am trying to filter out the `part` which contains 1 and did this
fetchRequest.predicate = NSPredicate(format:"part == %@", 1)
But I am getting the error
> Thread 1: EXC_BAD_ACCESS (code=1, address=0x1)
if I do the above. What am I doing wrong here? Thanks in advance.
|
The code you've written, i.e.
fetchRequest.predicate = NSPredicate(format:"part == %@", 1)
In the above code, you're trying to `filter` all the `fetched rows` based on whether `part is 1 or not`. So basically here you're using `part` as an `Int`. But as per the declaration, `part` is an `array [Int]`.
It will definitely `throw` an `exception`.
You need to `filter each row after fetching` like:
let filteredPart = part.filter({ $0 == 1 })
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift, nspredicate"
}
|
Whether we import source code or byte code of a class when importing that class in java?
I have started learning packages in java.I learned about the import keyword.Now my doubt is whether it is .class file or a .java file that is being imported while we import any class in java.
|
> Does the compiler use .class or .java files for an import?
Answer: _.class files, possibly compiling .java files._
This works, even in the following case (when there are no .class files):
// p/a/A.java
package p.a;
import p.b.B;
public class A {
public static final A DEFAULT_A = new B();
}
// p/b/B.java
package p.b;
import p.a.A;
public class B extends A {
}
The reason that this (a cyclic dependency) can be dealt with, is that .class files are comparable with .obj / .o object files: there is symbolic information (class and method names) in the .class files. And just as the object files are linked with a linker to an executable or library, the java class loader resolves everything.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, java package"
}
|
What's going on with z-indexing here of inputs in IE8?
I am trying to layer 2 inputs on top of each other in HTML. In most browsers (Safari, FF, IE7) I do this with the following code and it works fine so that the second input is placed on top of the first with the lighter text color, and when you click in the area the focus goes to it. In IE8 however, the first one appears to be over the second one, so that when you click it and start typing you see the lighter colored text.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style type="text/css" media="screen">
input {
background-color: transparent;
}
</style>
</head>
<body>
<input style="position:absolute;z-index: 1;color: #dedede;">
<input type="text" style="position:relative;z-index: 3;">
</body>
</html>
|
The problem seems pretty similar to that one, so I think you'll have to wrap a `<input>` into a `<div>` with higher z-index.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "html, css, z index"
}
|
Client / Server security from mobile to website
Hey. Am new to the world of web programming and learning a bunch of fairly simple new pieces of tech, trying to piece them all together.
So, we have a simple client (currently iPhone, to move to J2ME soon) that's pulling down lists of data via PHP, which is talking to a MySQL db. I have a rudimentary user/login system so that data is only served to someone who matches a known user etc, either on the website or on the client.
All the php scripts on the website that query the DB check to make sure an active session is in place, otherwise dumping the user back to the login screen.
I've read a little about SSL and want to know if that is sufficient to protect the website AND the data passing between the server and the client?
|
HTTPS is about protecting data and authenticating the endpoints. You still have to worry about properly authenticating the client to access your services. You also have to worry about vulnerabilities such as SQL Injection and other vulnerabilities that affect PHP. I highly recommend reading The OWASP Top 10 2010 A3: Broken Authentication and Session Management to make sure your session implementation is secure.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, iphone, security, encryption, ssl"
}
|
auto fill form without id tampermonkey
i'm a newbie with tampermonkey and i want to auto fill a form but has no id ...i already tried some codes but doesnt work
source
<input type="text" name="user_email" class="form-control-input" value="" placeholder="Enter your Email" onselectstart="return false" onpaste="return false;" oncopy="return false" oncut="return false" ondrag="return false" ondrop="return false" autocomplete="off">
code already tested
var mail = "[email protected]";
document.getElementsByClassName('form-control-input').value = mail;
|
I personally prefer to use jQuery over pure javascript in tampermonkey because it gives me more control such as loading the script when the DOM is ready. i.e. wrap the function in a $(document).ready(function() ...
you can try this out (make sure to change the @match)
// ==UserScript==
// @name New Userscript
// @namespace
// @version 0.1
// @description try to take over the world!
// @author You
// @match <your site here>
// @icon
// @grant none
// @require
// ==/UserScript==
(function() {
'use strict';
$(document).ready(function() {
var mail = "[email protected]";
$('[name=user_email]').val(mail);
});
})();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, tampermonkey"
}
|
Ruby Regex Match Multiple variable from a single string
Fairly new to ruby. I'm trying to parse a string and assign several variables with a regex.
I've consulted the docs, Googled a bit, and pretty sure that the following should work.
@operating_system, @os_update, @os_arch = @version_line[0].match(
/(Solaris \d+)\s+\d+\/\d+\ss\d+[sx]_u(\d+)\wos_\d+\w+\s+(\w+)$/
)
Where `@version_line = [" Oracle Solaris 10 9/10 s10x_u9wos_14a X86\n"] `
But all that happens is my first variable, @operating_system is assigned `Solaris 10 9/10 s10x_u9wos_14a X86`
Am I trying to do it the wrong way?
|
Actually, `match` returns a `MatchData` object, which happens to have a `to_s` method that produces the string you see.
To get all matched capture groups as an array, use the `captures` method:
@operating_system, @os_update, @os_arch = @version_line[0].match(
/(Solaris \d+)\s+\d+\/\d+\ss\d+[sx]_u(\d+)\wos_\d+\w+\s+(\w+)$/
).captures
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby, regex"
}
|
Access properties from source folder for exporting to runnable jar
I need to access the properties file from my jar when i export to runnable jar.So when i put props file in project root folder in eclipse it is running.But when exported it is not copied.So i wanted it to placed within source folder. So how to access it from source folder.
java.io.FileNotFoundException: config.properties (The system cannot find the fil e specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:106) at java.io.FileInputStream.(FileInputStream.java:66) at com.my.ashwinsakthi.twitterclient.IplHashtagReader.main(IplHashtagReader.jav a:38)!enter image description here
|
I copied the properties file into the jar and placed where my java class files where there and it worked...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, properties"
}
|
Function returning variable by reference?
In C++,
function() = 10;
Works if function returns a variable by reference, right?
Would someone please elaborate on this in detail?
|
Consider this piece of code first
int *function();
...
*function() = 10;
Looks similar, isn't it? In this example, `function` returns a pointer to `int`, and you can use it in the above way by applying a unary `*` operator to it.
Now, in this particular context you can think of references as "pointers in disguise". I.e. reference is a "pointer", except that you don't need to apply the `*` operator to it
int &function();
...
function() = 10;
In general, it is not a very good idea to equate references to pointers, but for this particular explanation it works very well.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 4,
"tags": "c++"
}
|
Using a variable for the value of size attribute in <select ..> (HTML, PHP, SQL)
I'm trying to make a drop-down menu using select. The contents are names from a database. I want the size of the select to be the ammount of entries in my table _tickets_.
I want the size of
echo '<select name="Tickets" size=5>'; //this works fine, but I want the size to be relative
to be a variable instead of the constant value of 5. So far, I've tried this:
$query = mysql_query("SELECT * FROM tickets order by ID");
$numrows = mysql_num_rows($query);
//echo $numrows; Was just testing to see if it got the right number (it did).
echo '<select name="Tickets" size=$numrows>';
but that doesn't seem to work. How do I achieve this? Cheers in advance!
|
You can't echo out a variable in `'`, it needs to be `"`.
So you can re-write it as this:
echo "<select name='Tickets' size=$numrows>";
Or this:
echo '<select name="Tickets" size='.$numrows.'>';
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, sql, html select"
}
|
How to set AES key is "private" in javascript?
I have a demo code to encrypt and decrypt a string by using AES, like this:
<script src="
<script>
var password = $('#Password').val();
var encrypted = CryptoJS.AES.encrypt(password, "0011");
var decrypted = CryptoJS.AES.decrypt(encrypted, "0011").toString(CryptoJS.enc.Utf8);
</script>
My question is: Is there a way to hide the key `0011` from javascript code?
I don't want any user can open my js file and view the key.
Thank you!
|
No. It is not possible.
You can't let the browser decrypt something without giving the browser the key.
The user controls the browser. Anything you give to the browser you also give to the user.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, encryption, cryptography"
}
|
How to refer previous task and stop the build in azure devops if there is no new data to publish an artifact
Getsolution.exe will give New data available or no new data available, if new data available then next jobs should be executed else nothing should be executed. How should i do it? (i am working on classic editor)
example: i have set of tasks, consider 4 tasks:
task-1: builds the solution
task-2: runs the Getstatus.exe which get the status of data available or no data available
task-3: i should be able to use the above task and make a condition/use some api query and to proceed to publish an artifact if data is available if not cleanly break out of the task and stop the build. it Shouldn't proceed to publish artifact or move to the next available task
task-4:publish artifact
|
First what you need is to set a variable in your task where you run `Getstatus.exe`:

new Chartkick.LineChart("chart-2", {"2013-02-10": 11, "2013-02-11": 6});
<
why does chartkick always have to include time ? how do i show the series in dates only ?
|
This is the answer, with discrete and hAxis,
<
new Chartkick.LineChart("chart-2",
{"2013-02-10": 11, "2013-02-11": 6, "2013-02-12": 12, "2013-02-13": 5},
{"library":
{title: "Company Performance",
"hAxis":{"title":"Date","gridlines":
{"count":3,"color":"#CCC"},"format":"dd/MM/yy"}},
"discrete": true});
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, ruby on rails, google visualization, chartkick"
}
|
How to exclude "property methods" in Type.GetMethods?
I'm able to get the methods of a class using `System.Type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)`.
However, the returned list will include "property methods", e.g. `get_PropertyX` and `set_PropertyX`.
How can we ensure that the returned list exclude "property methods"?
|
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => !m.IsSpecialName);
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 8,
"tags": "c#, .net, vb.net, reflection, .net 4.0"
}
|
BlackBerry - Convert EncodedImage to byte []
I am using below code where i don't want to use JPEGEncodedImage.encode because it increases the size. So I need to directly convert from EncodedImage to byte array.
FileConnection fc= (FileConnection)Connector.open(name);
is=fc.openInputStream();
byte[] ReimgData = IOUtilities.streamToBytes(is);
EncodedImage encode_image =
EncodedImage.createEncodedImage(ReimgData, 0, (int)fc.fileSize());
encode_image = sizeImage(encode_image, (int)maxWidth,(int)maxHeight);
JPEGEncodedImage encoder=JPEGEncodedImage.encode(encode_image.getBitmap(),50);
ReimgData=encoder.getData();
is.read(ReimgData);
HttpMultipartRequest(
content[0],
content[1],
content[2],
params,
"image",txtfile.getText(), "image/jpeg", ReimgData
);
|
Try EncodedImage.getData()):
_public final byte[] getData()_
Returns the encoded data of this image.
**Returns:** A byte array containing the encoded data for this image.
**Since:** JDE 3.7.0
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "image, graphics, blackberry, arrays, paint"
}
|
PHP mt_rand() function
Are PHP random numbers predictable? if so, how difficult would it be to predict random numbers that are in a range of 1 to 32? and is there any way to make it unpredictable?
<?php
function rand_best($min, $max) {
$generated = array();
for ($i = 0; $i < 100; $i++) {
$generated[] = mt_rand($min, $max);
}
shuffle($generated);
$position = mt_rand(0, 99);
return $generated[$position];
}
?>
|
The discussion around how random random-functions in programming is, is ancient.
Take a look at this: <
Anyway. The random-functions are so good today that they are (what I would call) as near random as possible. There's no way to predict a result between 1,32 (or any other number for that sake). The deal is that the numbers are not truly random because a computer can not do such a operation.
I'd say the rand-functions is more than good enough unless you are writing something for Pentagon
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "php"
}
|
XCode/Cocoa Development in Eclipse IDE on Mac
Is there any Plugin available in Eclipse (Mac) for XCode/Cocoa development? Is XCode Editor in Mac, the only option?
Regards, Sandip
|
Yes. Apple has provided Xcode and I am not aware of any other third party (or Apple provided IDE). So AFAIK Xcode is the only option.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "xcode"
}
|
Mapping An Array To Logical Array In Matlab
Let's say an `array a=[1,3,8,10,11,15,24]`, and a `logical array b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1]`, how to get `[1,1,3,1,3,8,1,3,8,1,2,3,8,10]`, see where logic becomes 1 in `b`, the array index of `a` resets so it starts from the beginning, also the same where the logic becomes 0 `a array` starts from beginning and continues as `1,3,8,10..etc.`
|
you can use `diff` to find where `b` changes, then use `arrayfun` to generate indexes for `a`:
a=[1,3,8,10,11,15,24];
b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1];
idxs = find(diff(b) ~= 0) + 1; % where b changes
startidxs = [1 idxs];
endidxs = [idxs - 1,length(b)];
% indexes for a
ia = cell2mat(arrayfun(@(x,y) 1:(y-x+1),startidxs,endidxs,'UniformOutput',0));
res = a(ia);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "arrays, matlab, indexing"
}
|
Linq to SQL: how get row security between write access?
I would like to allow two threads to write in a table at the same time (I know the problem of updating the same row, but this would be a story apart). I need that in behalf of speed up the operations in my aplication (one thread could write in row X while another could do the same in row X+n instead of waiting the first to finalize).
So, can I block rows instead of tables with Linq to SQL?
Thanks.
|
LINQ to SQL does not block any tables. It simply sends SQL queries to your SQL Server database and it is up to SQL Server to deside how to block. However, when your database has the proper design (right indexes etc) SQL server will not lock your whole table when you've queried a single row and update that row. Therefore, you can expect that scenario to just work.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "security, linq to sql"
}
|
What does construction ^(int&) mean in c#?
I found this construction with decompiler tool. Looks like it is something connected with multithreading. what does mean `^(int&)` in c#?
upd
It used like variable declaration
`^(int&) @someLock`
|
This is invalid code, unsafe or not.
* * *
**Assumption:** The person writing the decompiler comes from a C/C++ background and did not know how to construct legal C# code (if at all possible) for a construct found in IL.
If we're following the breadcrumbs of the "operators" involved, this _could_ mean this:
`@someLock` is a variable that will hold the value at some place in memory (`&` means it is actually an address, and `^` means we're dereferencing the address).
Basically, it could be "the value at some specific point in memory", crammed into a single variable declaration. Think of it as a variable that is placed specifically at some address. From knowledge (and I may absolutely be wrong here), IL can handle this, but C# cannot.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "c#"
}
|
How to instead of 'query.add_column' add field to entity?
I have some sqlalchemy query:
>>> items = (
Company.query
.add_column(Address.city)
.join(Company.address)
.filter(and_(
...some filters...
))
.all()
)
>>> items
[(Company(6239), Berlin), (Company(5388), Moscow), ...]
How can I modify my query, to put Address.city to entity Company? I want it to look as:
...
>>> items
[Company(6239), Company(5388), ...]
>>> items[0].city
Berlin
Thank you.
|
I do not think you can do it directly in a query without modifying the model.
But you can easily achive this in the code:
>>> items
[(Company(6239), Berlin), (Company(5388), Moscow), ...]
>>> # set company
>>> for (_company, _city) in items:
_company.city = _city
>>> # remove city attribute
>>>> items = [_company for (_company, _city) in items]
>>> items
[Company(6239), Company(5388), ...]
>>> items[0].city
Berlin
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "sqlalchemy"
}
|
Global variable initialization issue
I've a Drupal file (mymodule.module) which contains something like(actual code is very long):
$test =1;
//hook_user_login
function mymodule_user_login()
{
global $test;
print "$test";
}
But when this hook function "mymodule_user_login" is called by Drupal on user login -- $test's value is found to be null.
What could be the reason?
I've tried Googling but could not find useful answer.
|
The only way this could not work is if the file is included inside a function. E.g., your code is in `foo.php`, and is executed as:
function drupal_bar() {
include 'foo.php';
}
Then `$test` would not be in the `global` scope, hence the function cannot get it from there either. I don't know Drupal, but it seems likely that this would be the case.
The real solution is not to use the `global` scope, precisely because of this and because global state soon devolves into madness.
The localised solution for this particular case is to also write `global $test` before `$test = 1` to explicitly declare the variable in the global scope, wherever it may be included from later.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, drupal 7"
}
|
SharePoint Online Workflow Notes Field
I have a custom list the requires the user to enter some notes. I have a choice field that triggers a Workflow that will create a new item in a Task List. How can I transfer the information in the notes to the Task List Description Field?
|
1. First of all , You should ba aware of The task cannot be edited after it's status become `Completed`. So that to update `Description` column in Task List you should check if its `approval status` is `Pending`.
2. To update `Description` column for the assigned Task with `Note` Field at the current item do the following :
* Create Assign task action.
* Check if the associated task is pending
* Update List Item for association Task List.
Sheets. On the first page I have a set of rows with customer data.
That looks like
C D E
Joe - 100
Bob - 200
Joe - 300
Jane - 50
And on sheet 2 I have a column with a formula that attempts to query those values and sum the purchase values for each customer (col E).
The formula I tried to use which fails is:
"=(QUERY('data'!B40:E60, "Select C, Sum(E) where C contains """&A18&""" Pivot C"))
In all seriousness though I really don't care about selecting C this is just the 20th variation I tried. What I am trying to do is sum E for all rows where C matches the cell A18 which is the customer name on sheet 2.
|
Try:
=QUERY('data'!B40:E60, "Select C, Sum(E) where C = '"&A18&"' group by C")
and see if that works ?
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "google sheets"
}
|
Creating Relationships between tables in SQL server
I want to create a Master Table and there are other 2-3 tables which will have its relation on Master table. Please see the Details below:-
* Master table Name: tbl_org
There are more 2-3 tables which will have relation to this Master table. Please suggest how to proceed as I have never been created a Master table and given its relation.
Also, Please suggest what Datatype should I give to IsActive field.
|
Step 1:
---- Create master table
CREATE TABLE [dbo].[tbl_Master]
(
[MasterID] [int] NOT NULL,
[Value] varchar NULL
)
Step 2:
---- Create PRIMARY KEY on column for having unique values
ALTER TABLE [dbo].[tbl_Master] ADD CONSTRAINT [PK_tbl_Master] PRIMARY KEY CLUSTERED
(
[MasterID] ASC
)
step 3:
-- create chlid table
CREATE TABLE [dbo].tbl_Child NULL
) ON [PRIMARY]
step 4:
--- create relationship between chlid and master using FOREIGN KEY
ALTER TABLE [dbo].[tbl_Child] WITH CHECK ADD CONSTRAINT [FK_tbl_Child_tbl_Master] FOREIGN KEY([MasterID])
REFERENCES [dbo].[tbl_Master] ([MasterID])
GO
ALTER TABLE [dbo].[tbl_Child] CHECK CONSTRAINT [FK_tbl_Child_tbl_Master]
GO
Relationship diagram: !enter image description here
Note: The same way you can add many child tables .
More info on the relationship types:<
|
stackexchange-dba
|
{
"answer_score": 2,
"question_score": -8,
"tags": "sql server, table"
}
|
Select words without indentation in text editor
Currently you can select a line with the `select_line` command. The problem is that you select the complete line, with the indentations.
I'd like to know how I can select only the words of the current line, to integrate it in a pie please.
|
def execute(self, context):
bpy.ops.text.move(type='LINE_BEGIN')
bpy.ops.text.move(type='NEXT_WORD')
bpy.ops.text.move_select(type='LINE_END')
return {'FINISHED'}
This selects whitespace at the end of the line.
|
stackexchange-blender
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, text editor"
}
|
Trigger created with compilation errors. ORA-:missing SELECT keyword
I am trying to create a trigger that fires after an insert/update and checks for null values in couple of columns. In case any one of them is NULL, it queries other tables and updates the current table
CREATE OR REPLACE TRIGGER sample_trigger
AFTER INSERT OR UPDATE
ON test_table
FOR EACH ROW
BEGIN
IF :NEW.ID IS NULL OR :NEW.CODE IS NULL
THEN
UPDATE (:NEW.ID,:NEW.CODE) = (SELECT T1.ID,
T2.CODE
FROM TABLE_1 T1
JOIN TABLE_2 T2 ON T1.ID=T2.ID
WHERE ID=:NEW.TEST_ID);
END IF;
END;
/
Warning: Trigger created with compilation errors.
ERROR: PL/SQL: ORA-00928: missing SELECT keyword
|
You don't `UPDATE` the `:new` pseudo-record. Just assign values to it
SELECT t1.id, t2.code
INTO :new.id, :new.code
FROM table1 t1
join table2 t2 on t1.id = t2.id
WHERE id = :new.test_id
A couple additional notes
* Your `WHERE` clause will generate an ambiguous reference error. Since both `t1` and `t2` have an `ID` column, you'd need to specify which table's column you are comparing against.
* If `test_table` is the same as either `table_1` or `table_2`, that's going to produce a mutating table exception.
* Your trigger should be a `BEFORE INSERT` since it's modifying data not an `AFTER INSERT` trigger.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "oracle, database trigger"
}
|
mySQL join Feature
I am using a PHP mySQL query. Struggling with a Joins.
mysql_query("SELECT * FROM electors WHERE telephone > 0")
Then I need it to select from a table called voting_intention with matching ID from the electors table of this query and get a column called pledge that is equal to 'C' OR 'D'.
How do we do this in 1 mySQL query.
|
Your possible SQL statement will be,
SELECT voting_intention.pledge
FROM electors, voting_intention
WHERE
electors.id =voting_intention.id
and electors.telephone > 0
and voting_intention.pledge in {'C','D'}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, join"
}
|
Capitalization of "School" as an adjective
I am working on a research poster, and the teacher supervising wrote the following language. It doesn't seem to me like "School" is a proper noun, but he tells me it is when referring to a specific school. Is the following sentence correct? Is it the best way to say this?
> Such questions would allow us to learn how the School culture affected cheating.
"School" refers to _our school_ , but I still don't think it looks right capitalized (especially when used as an adjective).
|
It would be capitalized if it was preceded by the name of the school. For example:
> Students at the Brooklyn School of the Arts often collaborate on assignment with their mobile devices. The students were asked about cheating habits, and their mobile devices. Such questions would allow us to learn how the **School** culture affected cheating.
However, it would not be capitalized if you were using it like this:
> Schoolkids in the 21st century are using cellphones more than ever in schools. The New York Times asked 1000 students about their cheating habits and cellphone usage. Such questions would allow us to learn how the **school** culture affected cheating.
|
stackexchange-english
|
{
"answer_score": 2,
"question_score": 2,
"tags": "capitalization, proper nouns"
}
|
Do any of the latest browsers offer a modal confirm Yes No Dialog box?
I have been used to hand coding this type of thing in the past. With all the new things coming out with CSS3 has anyone seen any browsers yet supporting something like an alert box that will also give the user a couple of buttons for OK and Cancel. Note that I am not talking about a framework alert box. I was asking about something that might be part of Safari or Firefox.
|
## You need `confirm`
var bro = confirm("Bro, do you even javascript?");
alert("you selected " + bro);
It returns a boolean after the user selects his or her choice. It is a blocking function, use wisely :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, html, browser"
}
|
SHA2_256 Hashbytes generating different value on SQL Server 2012 with different version
I am facing a weird problem, I have one source - SQL Server 2012 with version no. 10.5.1753.0 - where hashbyte `SHA2_256` is generating a null value.
On the other hand, I have another source - SQL Server 2012 with version no. 11.0.3000.0 - where hashbyte `SHA2_256` is generating some value.
I have to deal with this problem, where I can't put request to source owner to upgrade their version and still I need to pull records from this source.
|
Versionnumber **10.5.1753.0** belongs to SQL Server **2008 R2** and not 2012.
SHA256 is only supported in SQL Server 2012+.
(BTW **10.5.1753.0** is a pretty old version back from 2010 and **11.0.3000.0** is from 2012. They really should be updated.)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server 2012, hashbytes"
}
|
Java - Записать куки на все пути URL
В сервлете по URL - /user/registration регистрирую пользователя и записываю в его браузер куки.
Cookie nickCookie = new Cookie( "nick", user.getNick());
Cookie codeCookie = new Cookie( "code", user.getCode());
resp.addCookie(nickCookie);
resp.addCookie(codeCookie);
Вот так вот в сервлете записываю куки, но записывает только по URL - /user/registration.
Вопрос - как мне записать куки например на все пути что будут после `
???
|
У класса `Cookie` есть метод `setPath()`. Он устанавливает куку для указанного каталога и всех подкаталогов
Cookie nickCookie = new Cookie( "nick", user.getNick());
nickCookie.setPath("/user");
Cookie codeCookie = new Cookie( "code", user.getCode());
codeCookie.setPath("/user");
resp.addCookie(nickCookie);
resp.addCookie(codeCookie);
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, cookie, servlet"
}
|
How to create and populate a table in a single step as part of a CSV import operation?
I am looking for a quick-and-dirty way to import CSV files into SQL Server _without having to create the table beforehand and define its columns_.
Each imported CSV would be imported into its own table.
We are not concerned about data-type inferencing. The CSV vary in structure and layout, and all of them have many many columns, yet we are only concerned with a few of them: street addresses and zipcodes. We just want to get the CSV data into the SQL database quickly and extract the relevant columns.
I'd like to supply the FieldTerminator and RowTerminator, point it at the CSV, and have the utility do the rest. Is there any way to create the table and populate it, all in one step, using BULK INSERT and/or OpenRowset(BULK ... ) ?
|
Referencing SQLServerPedia, I think this will work:
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
select TerritoryID
,TotalSales
,TotalCost
INTO CSVImportTable
from openrowset('MSDASQL'
,'Driver={Microsoft Access Text Driver (*.txt, *.csv)}'
,'select * from C:\csvtest.CSV')
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 18,
"tags": "sql server, sql server 2000, bulkinsert, create table, openrowset"
}
|
"Сбежать с тюрьмы" или "Сбежать из тюрьмы"?
Я прочитал правило, в котором говорится, что употребляется такой предлог, который указан в приставке.
**До** стучаться **до** небес. Вот тут все понятно. Получается, правильно так: сбежать с тюрьмы? Или как?
|
Семантическая соотносительность предлога и приставки возможна, но не обязательна, так как предлоги и приставки в русском языке многозначны.
Приставка С в глаголе "сбежать" имеет значение удаления посредством действия, названного мотивирующим глаголом, а предлог С имеет значение удаления с ПОВЕРХНОСТИ предмета, в нашем же случае мы имеем удаление ИЗНУТРИ предмета (из тюрьмы), и эту семантику важно обозначить.
В то же время можно сбежать с урока - здесь соотношение значений предлога и приставки соблюдается, так ка урок мыслится как отвлеченный предмет.
|
stackexchange-rus
|
{
"answer_score": 2,
"question_score": 0,
"tags": "другое"
}
|
iOS pageviewcontroller disable swipe
I have an application that has three navigation controllers in a UIPageViewController.
|-> Detail View
|-- nav 1 -> root view -|
| |-> Search View
UIPageViewController -|-- nav 2 -> root view
|
|-- nav 3 -> root view
Nav 1, 2, and 3 all have views that branch out from there. The issue is that once I open a subview of one of the navigation controllers, I can still swipe between the 3 separate navigation controllers. I want to disable swipe if I'm > 1 layer deep (detail or search view) of a navigation controller.
|
Why having 3 Navigation controllers ?
Put your PageViewController inside your NavigationController. You don't need to disable your swipe gesture like this.
But if you really want to have this architecture, you can remove the data source. Without `dataSource`, the pageViewController does not slides. Set again the dataSource to enable swipe again.
// Methods of the data source are called in response to gesture-based navigation.
// If the value of this property is nil, then gesture-based navigation is disabled.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift, uinavigationcontroller, uipageviewcontroller"
}
|
How to add a break point in Intelij IDEA to debug Rust code
I have installed Intellij IDEA on ubuntu with Rust plugin. How to add a break point in Intellij IDEA to debut RUST code. Do I need any additional plugin?
|
Debugging Rust code is available in CLion, IntelliJ IDEA Ultimate, PyCharm Professional, and GoLand. For IntelliJ IDEA Ultimate, PyCharm Pro, GoLand it is required to install the Native Debugging Support plugin.
See plugin's documentation for more information: Debugging.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "intellij idea, rust"
}
|
GNOME Terminal - process name in tab title
How can I put the current running process name into a GNOME Terminal tab title (or title bar when there's only one tab)?
\-- UPDATE --
To clarify, I want the tab title to update when I run a process, for example:
# title is currently "bash"
$ find / -name foo # while searching for foo, title is "find"
$ # title is once again "bash"
$ less /proc/cpuinfo # title changes to "less"
$ man ls # title changes to man
$ # title returns to "bash"
|
Found it. This site provides a good explanation of a solution.
In your bashrc, it would look like:
case "$TERM" in
xterm*|rxvt*)
set -o functrace
trap 'echo -ne "\e]0;$BASH_COMMAND\007"' DEBUG
PS1="\e]0;\s\007$PS1"
;;
*)
;;
esac
Personally, I don't think I would add it to my bashrc, because the DEBUG combined with trace does throw out a load of garbage when all your shell starts. If you can live with that, it actually does work. It does display the entire command, however, not just the first word.
|
stackexchange-superuser
|
{
"answer_score": 8,
"question_score": 9,
"tags": "linux, terminal, gnome"
}
|
Does the standard error of the mean approach 0 as the number of samples increases?
The standard error of the mean (SEM) is often given as $s / \sqrt n$, where $s$ is the standard deviation and $n$ the number of samples. Does this mean that if we were to calculate the SEM with more and more samples that the SEM would approach 0?
I ask because I feel like this would have implications for the t-distribution when defined as $ {\bar X - \mu \over s / \sqrt n} $, as it seems to me like this should cause the t-distribution to take increasingly larger values as the number of samples increases.
|
Yes. $S_n / \sqrt{n} \to 0$ since $S_n \to \sigma$, which is a constant. But notice that $(\bar{X_n} - \mu) \to 0$ as well, so we don't expect $\sqrt{n} |\bar{X_n} - \mu| / S_n \to \infty$. Basically the two terms converge to zero at the same rate so their ratio has a stable distribution even as $n \to \infty$.
|
stackexchange-stats
|
{
"answer_score": 4,
"question_score": 3,
"tags": "standard deviation, standard error, asymptotics, t distribution"
}
|
"Yon" vs. "Shi" in school names
I've tried Voicetext.jp and Google's text to voice service to read this
>
It reads something like
> Yon-chū no
But Google suggested this romanization, which left me doubtful
> Shi-chū no
So, I have been redirected to a similar question discussing why there is different pronunciations of the numbers 4, 7 and 9 (maybe there's more).
From the given answers, I can't decide how to read things like
>
Because none of the examples addressed there were close enough to school names, rankings and such...
|
In your case, it is fairly easy: do not think that is an isolated entity. It comes with , with ``, meaning `The fourth`.
In this case, whenever you encounter a counter, go with the . This was highlighted in the answer you linked:
> Kunyomi is typically used in cases where you point out you have X of some item.
For example, you would say to count flat things, to count cylindrical things, which is another way of saying fourth, to count animals and so on...
|
stackexchange-japanese
|
{
"answer_score": 4,
"question_score": 2,
"tags": "readings, rōmaji"
}
|
Looptools - cancel not working
I am working with Blender 2.9 and LoopTools Addon (which i like) but cancel does not seem to work. Whenever i change e.g. to circle and tap ctrl-z, it does not go back but just does other weird things... is this a bug or a feature?
ok, here is a movie, hopefully this helps. I hoped i could cancel the change from the quad to circle so it would be the quad again but it just selects some weird things. I am pretty new to Blender so maybe i make silly mistake... :( So the Command Z at the end (i am working on a mac, should be ctrl-z on windows to cancel a operation) is my problem
<
|
From your video, it seems you have a problem with your hotkeys. CTRL-Z for you is activating the Select More command, which the default hotkey is CTRL-numpad+ Check your keymap, type in "select more" into the search bar and check what it is mapped to. Since you're new to Blender, it might simply be easier to reset your keymapings to default.
.Range("E2:E" & iLast).FillDown
-2,3)+1.
Thank's you all..appreciate your help. <3
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, vba"
}
|
In codeigniter Using $this when not in object context
<?php
class Token {
private $CI;
function __construct($param) {
$this->CI =& get_instance();
if($param['flag'] == 1) {
$this->retrieveToken();
$this->validateToken();
}
}
public static function getAuthUserToken($empID) {
$class = $this->CI->db->query('select * from tbl_emp where emp_id ='.$empID);
$class = $class->result_array();
print_r($class);
}
}
?>
I'm creating custom library in codeigniter But, when i try to execute any operation with database.I'm getting above error message
**I also loaded database in autoload.php file**
$autoload['libraries'] = array('database');
|
It's your static method `getAuthUserToken($empID)` that is causing the error.
As it says in the PHP documentation on the keyword Static
> Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, codeigniter, libraries"
}
|
fixed point of a holomorphic function on a disk
Let $ \mathbb{D} = \\{ z : |z|<1 \\} $ and $ f $ an holomorphic function on $ \mathbb{D} $ and continuous on $ \overline{\mathbb{D}} $ such that $ f(\overline{\mathbb{D}}) \subset \mathbb{D} $.
Prove the following:
1. There exists single point $ z^* \in \mathbb{D} $ such that $ f(z^*)=z^* $ (obvious by Rouche theorem).
2. Let $ f_1=f,...,f_{n+1}=f(f_n) $ show that $ f_n(z) \longrightarrow z^* $ uniformly.
|
The key to all this is that $f(\bar{D}) \subset D$:
1. Since $f(\bar{D})$ is compact, there exists $r_0>0$ such that $f(\bar{D})\subset D_{r_0}$. So for any $r_0<r<1$ we have $|f(z)|=|(f(z)-z)+z|<|-z|$ on $D_r$ so by Rouché's theorem $-z$ and $f(z)-z$ have the same zeroes, which is one. Since this is valid for any $r>r_0$ the uniqueness result follows.
2. Since $|f(z)/z|=|f(z)|$ is continuous on $\partial D$ it has a maximum $M$, and by hypothesis $M<1$. So, assuming for the moment that $f(0)=0$, by the maximum principle we get $|f(z)|\leq M|z|$ for $z\in D$. This gives that $|f_n(z)|\leq M|f_{n-1}(z)|$ in $D$, and so $|f_n(z)|\leq M^n|z|$. Taking supremums over $\bar{D}$ and then the limit as $n\to \infty$ the result follows.
Assume now that $f(0)\neq 0$ then everything just said applies to $g=h\circ f\circ h^{-1}$ (with $h$ an appropiate automorphism of the disk), and the result follows in general.
|
stackexchange-math
|
{
"answer_score": 10,
"question_score": 10,
"tags": "complex analysis"
}
|
URLRetrieve Error Handling
I have the following code that grabs images using urlretrieve working..... too a point.
def Opt3():
global conn
curs = conn.cursor()
results = curs.execute("SELECT stock_code FROM COMPANY")
for row in results:
#for image_name in list_of_image_names:
page = requests.get('url?prodid=' + row[0])
tree = html.fromstring(page.text)
pic = tree.xpath('//*[@id="bigImg0"]')
#print pic[0].attrib['src']
print 'URL'+pic[0].attrib['src']
try:
urllib.urlretrieve('URL'+pic[0].attrib['src'],'images\\'+row[0]+'.jpg')
except:
pass
I am reading a CSV to input the image names. It works except when it hits an error/corrupt url (where there is no image I think). I was wondering if I could simply skip any corrupt urls and get the code to continue grabbing images? Thanks
|
Just use a `try/except` and `continue` if it fails
try:
page = requests.get('url?prodid=' + row[0])
except Exception,e:
print e
continue # continue to next row
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "python, python 2.7, urllib"
}
|
How do I stop Banshee from automatically starting when I plug in my Android device?
I set Banshee up as the default app to launch when I plug in my Android device, but have changed my mind. I'd prefer that Ubuntu simply mount it as a drive and leave the rest to me.
How would I go about changing this behavior?
|
You could try changing the default behaviour for plugged in devices in Nautilus settings (the tab is called Devices I believe).
Like "Insert Audio CD" --> "open player" etc
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 1,
"tags": "11.04, banshee, android"
}
|
Proving limit with $\log(n!)$
I am trying to calculate the following limits, but I don't know how: $$\lim_{n\to\infty}\frac{3\cdot \sqrt{n}}{\log(n!)}$$ And the second one is $$\lim_{n\to\infty}\frac{\log(n!)}{\log(n)^{\log(n)}}$$
I don't need to show a formal proof, and any tool can be used.
Thanks!
|
You can easily show that $2^n \leq n! \leq n^n$ for $n \geq 4$. The first inequality is a very standard induction proof, and the second inequality is straight-forward (you're comparing $1 \times 2 \times \dots \times n$ with $n \times n \times \dots \times n$).
From there, since $f(n) = \log n$ is an increasing function, you have that
$$n\log(2) \leq \log(n!) \leq n\log(n)$$
This tells you basically everything you will need. For example, for the first one:
$$ \lim_{n \to \infty} \frac{3 \sqrt{n}}{n\log n} \leq \lim_{n \to \infty}\frac{3 \sqrt{n}}{\log(n!)} \leq \lim_{n \to \infty} \frac{3 \sqrt{n}}{n \log(2)}. $$
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 12,
"tags": "limits, logarithms"
}
|
Oracle - Assign count value for a column based on another column in select query
Consider, I have the following in a select query:
ID Flag
5 Y
5 Y
5 N
6 Y
6 Y
6 Y
6 N
I should be adding a new column **count** in the same select which counts the **number of 'Y' records** for the ID and assigns it to all. (Eg: ID=5 has 3 records. All of them should be assigned the count value as '2').
Output required in select query:
ID Flag count
5 Y 2
5 Y 2
5 N 2
6 Y 3
6 Y 3
6 Y 3
6 N 3
|
Use a window function:
select id,
flag,
count(case when flag = 'Y' then 1 end) over (partition by id) as "count"
from the_table
order by id;
The `case` expression will return null for flags with `N` and thus they will be ignored by the count() function
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "oracle, select, group by"
}
|
Передать post данные и сделать редирект AJAX
Пытаюсь передать post данные в скрипт nomen.php, и после получения данных сделать редирект на этот же скрипт, но при нажатии кнопки страница обновляется.
JS:
$('#listNomen').submit(function(e) {
var filename = document.getElementById("userfile").files[0].name;
$.ajax({
type: 'POST',
url: 'nomen.php',
data: {s2: filename},
})
.done (function (data) {
$.redirect('nomen.php',data);
});
});
PHP:
$text= $_POST['s2'];
HTML:
<div id="showNomen">
<form id="listNomen" method="POST">
<br>
<label>TEST<input type="submit" value="Показать" style="position:absolute;left:12%;"></label>
</form>
<br>
</div>
|
При сабмите формы, она (СЮРПРИЗ!) сабмититься!
Для отмены дефолтного действия (события), нужно воспользоваться методом `preventDefault`
$('#listNomen').submit(function(e) {
e.preventDefault();
...
...
Однако это не имеет никакого смысла. Т.к. тут **совсем никак не используется сама форма** , а просто берутся данные из инпута, то и смысла в форме нет. Можно её смело удалить, а у кнопки убрать тип "submit" и обрабатывать клик по ней.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, html, jquery"
}
|
Milling an additional slot in an arbor press table plate?
I need to add a slot to the table plate of my Harbor Freight (Central Machinery) ½ ton arbor press.
It's obviously cast iron, but the surface is polished, so I'm not sure of its exact composition or if the surface is tough and it has a softer interior.
I don't have any carbide end mills, but I have some surplus HSS mills I don't mind destroying in this process.
Any ideas or suggestions?
Thanks!
|
My experience with cast iron in the process of milling and lathe turning (minimal, but valid reference) is that cast iron will cut nicely with ordinary HSS tools. The swarf will be granular, not long streams of ribbon and the surface will be moderately smooth, depending on your feed and speed.
A few references on the 'net suggest that it is "self-cooling" due to graphite in the iron. Another few references also suggest that use of coolant will create abrasive mud which will dull the tools.
You won't be destroying your tools.
|
stackexchange-crafts
|
{
"answer_score": 2,
"question_score": 2,
"tags": "metalworking"
}
|
How to edit multiple distinct rows in mysql with the same query
I have a mysql table with a row that contains vocabulary, like this:
* aller to go
* manger to eat
* soulager to relieve
There is also a unique column. The problem is that not all of the verbs have the to in the infinitive like above, so in reality the table looks more like this:
* aller go
* manger to eat
* soulager relieve
Is it possible to edit all these lines without the to so that they have it, i. e. so that the second example looks like the first one above? Otherwise I would have to go through the whole thing and edit them manually, which is time consuming as you can imagine.
It's easy to see them all:
SELECT * FROM vocab where french not like "to %";
But edit them?
|
I think you need an update:
update vocabulary
set french =
concat(substring_index(french, ' ', 1), ' to ', substring_index(french, ' ', -1))
where french not like '% to %';
See the demo.
Results:
| french |
| ------------------- |
| aller to go |
| manger to eat |
| soulager to relieve |
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, rows, edit"
}
|
Simple string replace question in C#
I need to replace all occurrences of `\b` with `<b>` and all occurrences of `\b0` with `</b>` in the following example:
> The quick \b brown fox\b0 jumps over the \b lazy dog\b0.
. Thanks
|
Regular expressions is massive overkill for this (and it often is). A simple:
string replace = text.Replace(@"\b0", "</b>")
.Replace(@"\b", "<b>");
will suffice.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 4,
"tags": "c#, .net"
}
|
How much does a "Potion of cure light wounds" heal?
According to the documentation, a potion of cure light wounds points to the spell "cure light wounds". Now, the spell has some info about healing:
> cures 1d8 points of damage +1 point per caster level (maximum +5)
But the caster level is just for the cleric who casts the **spell**. So what would be the correct amount of healing with the potion alone? just 1d8? or 1d8+5?
I could not find any clearer documentation for the potion yet.
|
The caster level (CL) is set by the creator of the potion, as per Brew Potion:
> When you create a potion, you set the caster level, which must be sufficient to cast the spell in question and no higher than your own level.
If you don't know it, the general rule of thumb is to use the minimum caster level required to cast the spell (as that's the minimum level it could be created at). For Cure Light Wounds, that is CL 1. Thus a normal potion of Cure Light Wounds heals 1d8+1.
It is possible for someone to create a CL 5 potion of Cure Light Wounds, though. That potion would have a higher value, which is explained on the Potions list.
> The price of a potion is equal to the level of the spell × the creator's caster level × 50 gp. If the potion has a material component cost, it is added to the base price and cost to create.
|
stackexchange-rpg
|
{
"answer_score": 27,
"question_score": 9,
"tags": "pathfinder 1e, magic items"
}
|
How can I find max heap size during runtime
I've an application running without any flags setting its max heap size i.e. I'm using the VM defaults. I'd like to know what they are and I'm wondering if theres any jsomething command that would return to me my stats for max heap size. I've already tried profiling and jstat, but these tools only show me how much I'm currently using. I'd like to know what's my current MAX heap size.
|
I've managed to solve it using jconsole:
jconsole hostname:port (usually 1099)
jmx has to be active to use it.
Go to VMSummary section and look for Maximum heap size.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "java, memory leaks"
}
|
Does every line through the origin come arbitrarily close to some other lattice point?
Given positive real numbers $x$ and $\epsilon$, do there necessarily exist positive integers $p$ and $q$ such that $\left| qx - p \right| < \epsilon$?
Or geometrically: in a two-dimensional Cartesian plane, does every line through the origin come arbitrarily close to some other lattice point? (I realize that that's not _exactly_ equivalent to the algebraic version, but if either is true than both are.)
I feel pretty certain that the answer must be "yes", but I'm not managing to prove it. My initial reaction was that it should be a direct consequence of the fact that the rationals are a dense subset of the reals; but that really only shows that we can satisfy the weaker condition that $\left| x - \frac{p}{q} \right| < \epsilon$, or equivalently, that $\left| qx - p \right| < q\epsilon$.
(This question was inspired by this recent answer on the Space Exploration Stack Exchange.)
|
Yes, this follows from a pigeonhole argument. <
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "irrational numbers, diophantine approximation"
}
|
Make textbox ignore style in css
I have a textbox with id="Email" in my view and I need the id to stay as it is. However, there is a #Email fields in a css file and my textbox gets the style in that fields. How can I make it to ignore that style?
|
in your css file try to write some parent element id before `#email` which is not present in case of `<input id="email">`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
From which country or area is the new moon visible first?
Being able to see the Moon is dependant on various factors like sunset timing etc. Considering all these factors, which country or area of the world sees the new moon first? I am asking about the **new** moon.
|
The duration of one lunation (the period between one new moon to the next one) isn't neither constant as the Moon rotates around the Earth and it around the Sun (changes between 29.272 and 29.833 days due to the perturbing effects of the Sun's gravity on the Moon's eccentric orbit), nor integer divisible by 24 hours or one Earth's rotation around its axis. So this position of the Moon on the skies where the next new moon as the first of its lunar phases will be first observable constantly changes.
!lunar phases
Phases of the Moon, as seen looking southward from the Northern Hemisphere. The Southern Hemisphere will see each phase
rotated through 180°. (Source: Wikipedia on Lunar phase)
Saying it differently, by the time the Moon completes one lunation (or it's synodic period) and starts the next one, it won't be positioned exactly above the same Earth's longitude (East to West) as the one it started at.
|
stackexchange-astronomy
|
{
"answer_score": 10,
"question_score": 9,
"tags": "the moon, moon phases"
}
|
Which algorithm and what combination of hyper-parameters will be the best to cluster this data?
I was learning about non-linear clustering algorithms and I came across this 2-D graph. I was wondering which clustering alogirthm and combination of hyper-parameters will cluster this data well.
!Plot
Just like a human will cluster those 5 spikes. I want my algorithm to do it. I tried KMeans but it was only clustering horizontly or vertically. I started using GMM but couldn't get the hyper-parameters right for the desired clustering.
|
If it doesn't work, always try to improve the preprocessing first. Algorithms such as k-means are very sensitive to scaling, so that is something that needs to be chosen carefully.
GMM is clearly your first choice here. It may be worth trying out different tools. R's Mclust is very slow. Sklearn's GMM is sometimes unstable. ELKI is a bit harder to get started with, but its EM gave me the best results usually.
Apart from GMM, it likely is worth trying out **correlation clustering**. These algorithms assume there is some manifold (e.g., a line) on which a cluster exists. Examples include ORCLUS, LMCLUS, CASH, 4C, ... But in my opinion these mostly work for synthetic toy data.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "cluster analysis, data science, k means, unsupervised learning, gmm"
}
|
How to check if SQL Server 2012 Shared Management Objects (SMO) is installed
To configure an install assistent, I have to check if SQL Server 2012 SMO is already installed. I found some answers for older versions of SQL Server (e.g. here and here) with the solutions to check the registry key `HKEY_CLASSES_ROOT\Microsoft.SqlServer.Management.Smo.Database` but this doesn't work for me. This registry key doesn't exists at Windows Vista and Windows 7, I think there are changes with the version 2012 of the SQL Server.
|
If you're checking for an installed component, then the best bet is to check the uninstall registry key.
On my machine the key value for "Microsoft SQL Server 2012 Management Objects (x64)" is this:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{43A5C316-9521-49C3-B9B6-FCE5E1005DF0}
There may be a different key entry for the 32bit version if you need that, but this is the way I always did software install checks when I was an SCCM admin.
EDIT: As it seems that Microsoft change the uninstall key every version making it difficult to keep track of the installation this way, there is another key here which is probably a good one to check:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion
You could check the value of this to see if it's greater than 11 and if not (or it doesn't exist) do your install.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql server, smo"
}
|
Maximize and NMaximize in comparison
If on one hand:
N@Maximize[{Sqrt[y^2 - x^2], x + y^2 == 0 && 0 < y < 2 && -y < x < y}, {x, y}]
> {0.5, {x -> -0.5, y -> 0.707107}}
which is what is desired, on the other hand:
NMaximize[{Sqrt[y^2 - x^2], x + y^2 == 0 && 0 < y < 2 && -y < x < y}, {x, y}]
produces a warning:
> NMaximize::nrnum: The function value 4.15623 -1.34058 I is not a real number at {x,y} = {-1.35352,0.186697}.
and a consequent incorrect result:
> {0.285088, {x -> -0.681805, y -> 0.739008}}
I can't understand why this behavior. Could you explain it to me? Thank you!
|
`Sqrt` isn't handled properly by `NMaximize`, I think.
Workaround
NMaximize[{Sqrt@RealAbs[y^2 - x^2], x + y^2 == 0 && 0 < y < 2 && -y < x < y}, {x, y}]
(*{0.5, {x -> -0.5, y -> 0.707107}}*)
gives the expected result.
|
stackexchange-mathematica
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mathematical optimization"
}
|
UIView animation to move and back
I would like to have animation on a view, that it will go 2 pixels right on x, and 2 pixels back left on x .
I have this for opacity, and i am looking to adjust this to make it ,
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=1.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
theAnimation.toValue=[NSNumber numberWithFloat:0.3];
[image.layer addAnimation:theAnimation forKey:@"animateOpacity"];
|
If you just want the animation to occur once then you can jump up a few levels of abstraction and use the block based view animations
[UIView animateWithDuration:1.f
delay:0
options:UIViewAnimationOptionAutoreverse
animations:^{
view.transform = CGAffineTransformMakeTranslation(2.f, 0.f);
} completion:^(BOOL finished) {
view.transform = CGAffineTransformIdentity;
}];
This applies a translation of two points right and then removes it on completion
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "objective c"
}
|
The operator '>=' can't be unconditionally invoked because the receiver can be 'null'. flutter null safety
I have the following code
if (myCart?.cart?.cartDetails != null &&
myCart?.cart?.cartDetails!
.indexWhere((element) => element.productId == productId) >=
0) {
return true;
}
this code gets an error in ">=" part saying it can be null. How can I fix this?
|
`indexWhere` can return null in your case and the `>=` operator cannot be used with a null value. Try the following code:
final index = myCart?.cart?.cartDetails
?.indexWhere((element) => element.productId == productId);
if (index != null && index >= 0) {
return true;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "flutter, dart"
}
|
Name of default screenshot tool in Freya?
After reading this question, I attempted to launch the default screenshot tool via the terminal (for debugging) but I couldn't find out what the name was.
I tried with `screen*` but nothing came up.
|
The command ran by clicking the screenshot application's icon is `gnome-screenshot --interactive` (Source).
|
stackexchange-elementaryos
|
{
"answer_score": 10,
"question_score": 7,
"tags": "release freya, screenshot"
}
|
Intransitivity with more than three elements
I have the following definition of intransitivity:
R is intransitive iff
for all xyz: xRy & yRz -> ~xRz
Now, given the following: aRb bRc cRd
Can I conclude that ~aRd?
Intuitively, I would say yes*, but I'm having problems with the formal proof.
*For example, if R would be 'is a parent of', and incest is impossible, clearly a is not a parent of d. But how to prove that?
|
How about a set of naturals, with $aRb \Leftrightarrow a \neq b \pmod 2$?
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "logic"
}
|
Why does the katakana ラ look similar to the hiragana う?
More specifically, is there a historical reason why some katakana characters look similar to the hiragana ones, as the question suggests?
|
It is just a coincidence. As you (probably) know, both hiragana and katakana came into existence as shorthand for kanji. Here's the graph shown on Wikipedia. So you can see that and are derived from different kanji and just so happen to look similar.
 ;20bytes: "stackstackstackstack"
How does this instruction work? How does this instruction allocate space for 4 "stack". How does it do so?
|
`4 DUP 'stack'` just means "4 copies of the string `'stack'`".
for (int i=0; i < 4; ++i) {
AllocateSpaceFor("stack");
}
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "assembly, masm, masm32"
}
|
Is it possible to redownload enterprise apps through Apple ID's?
To me, it seems as if this should be possible. With a normal app, you can go to 'Purchased' and re-download any previously downloaded apps.
Is it possible to do the same with an enterprise app which was **_not_** downloaded through the app store?
|
No, if it was not originally purchased/downloaded from the Apple App Store, you will not find it in the _Purchased_ section.
Usually, enterprise apps are distributed from that company's 'app store' only. If they are deleted from your iOS device, you can revisit the company app store and re-download the app again. It's up to that company if they want to have a _Purchased_ tab or some other way of seeing previously downloaded apps.
|
stackexchange-apple
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ios appstore, apple id, enterprise"
}
|
One app multiple appereances for different customers? (Apple Rules)
Does apple allow apps that change appearance depending on what my servers provides?
For example: I have three customers that use the same app (my app) which is an inventory management system.
It would be kind of unnecessary to create three separate apps, so my idea is that since all inventory management happens remotely on a server, I might as well create one app and let them log in to my inventory management system over the internet and supply the app with a layout-file (XML file or whatever) that changes the app appearance depending on who is logged in and which company the user works for.
Is this allowed or is it against Apple guidelines?
|
I think the typical solution to your problem is B2B distribution of your app. In which case you would have multiple versions of the app, but only one version would be available to each company.
Having said that, I do not believe Apple has guidelines against this sort of dynamic branding. However, the Review Guidelines change semi-regularly, so it's always best to go read them if you have a question.
It's also worth keeping in mind that the guidelines are the "spirit of the law" in that Apple will reject something that doesn't exactly break the rules but breaks what the rules were implying.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, xcode, customization, rules, appearance"
}
|
How to copy a file in Python?
I need to copy a file specified by the user and make a copy of it (giving it a name specified by the user). This is my code:
import copy
def main():
userfile = raw_input('Please enter the name of the input file.')
userfile2 = raw_input('Please enter the name of the output file.')
infile = open(userfile,'r')
file_contents = infile.read()
infile.close()
print(file_contents)
userfile2 = copy.copy(file_contents)
outfile = open(userfile2,'w+')
file_contents2 = outfile.read()
print(file_contents2)
main()
Something strange is happening here, as it doesn't print the contents of the second file, outfile.
|
Python's shutil is a much more portable method of copying files. Try the sample below:
import os
import sys
import shutil
source = raw_input("Enter source file path: ")
dest = raw_input("Enter destination path: ")
if not os.path.isfile(source):
print "Source file %s does not exist." % source
sys.exit(3)
try:
shutil.copy(source, dest)
except IOError, e:
print "Could not copy file %s to destination %s" % (source, dest)
print e
sys.exit(3)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, file, copy"
}
|
A Google extension without Omnibar Icon
This is probably a simple question, but I'm trying to create a Google extension without an icon, one that just runs in the background without a popup or anything. What would I put into the manifest to get this to happen?
|
Simply remove this from the `manifest.json`:
...
"browser_action": {
"default_icon": "icon.png"
},
...
Now the app will not appear in the top bar.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "google chrome extension, manifest"
}
|
Python multiprocessing giving two different pid for same object
i'm using **Windows**
import multiprocessing
import os
class BaseModule(multiprocessing.Process):
def __init__(self):
print("Initialize time pid: ",os.getpid())
multiprocessing.Process.__init__(self)
super().__init__()
def get_pid(self):
print("After new process pid: ",os.getpid())
def run(self):
self.get_pid()
if __name__ == '__main__':
process = BaseModule()
process.start()
OUTPUT:
Initialize time pid: 22148
After new process pid: 21244
In here same object get two different pid I need **full object create and run in new process using multiprocessing(same pid)?**
|
I Found a Way, in here I used a function for creating Object. Now I got same pid.
import multiprocessing
import os
class BaseModule:
def __init__(self):
print("Initialize time pid: ",os.getpid())
def get_pid(self):
print("After new process pid: ",os.getpid())
def run(self):
self.get_pid()
def use_multiprocessing():
obj = BaseModule()
obj.run()
if __name__ == '__main__':
process = multiprocessing.Process(target=use_multiprocessing)
process.start()
**OUTPUT**
Initialize time pid: 18240
After new process pid: 18240
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, multiprocessing, python multiprocessing"
}
|
Is this enough to detect race conditions?
Say I have a multithreaded application and I run it with the **same inputs**. Is it enough to instrument every load and stores to detect write-write and write-read data races? I mean from the logged load and store addresses, if we can see which thread did which load and which thread did which store, we can detect write-read and write-write data race by noticing the overlapped addresses. Or am I missing something?
|
> Or am I missing something?
You _are_ missing a lot. As Pubby said, if you see read, then write in T1, and later read, then write in T2, you can't say _anything_ about absence of races. You need to know about locks involved.
You may want to use a tool, such as Google's ThreadSanitizer instead.
Update:
> But will my approach cover all races or at least some of the races?
Your comments here and on other answers appear to show that you don't understand what a race is.
Your approach _may_ expose _some_ of the races, yes. It is guaranteed to _not_ cover most of them (which will make the exercise futile).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "c, linux, gcc"
}
|
SQL to change user in Sybase IQ
Is there an SQL in Sybase IQ so that I can change the username ?
In Sybase ASE you can change database by the 'USE' statement or in PostgreSQL which has SET search_path TO myschema;
Any similar SQL in Sybase IQ ?
|
You can always use the prefix for a user e.g. something like "dbo"."my_fancy_table". IQ is not having something like schema you would change in PostgreSQL with `SET search_path`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sap iq"
}
|
How do I get the query parameter from paramMap in Angular 5?
How do I get the query parameter from paramMap in Angular 5?
This code doesn't work as I'm trying to assign the value to void. I want to chain additional calls in the switchmap that rely on the id.
this.route.paramMap
.switchMap((params: ParamMap) =>
console.log(params.get('id'));
|
if your route looks like this
{path: 'foo/:fid', component: fooDetailsComponent}
then in your component
export class PopDetailsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private actRoute: ActivatedRoute){
this.subscription = this.actRoute.params.subscribe(
(params: any) => {
if (params.hasOwnProperty('fid') && params['fid'] != '') {
this.fooId = params['fid'];
});
}
ngOnDestroy() {
if(this.subscription) {
this.subscription.unsubscribe();
}
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angular"
}
|
Infinitary logic—can infinite conjunctions contain themselves as proper subformulae?
Can infinite conjunctions contain themselves as proper subformulae?
I feel like I'm missing something obvious, but with definitions like "If $\Phi$ is a set of formulae of $\mathcal{L}\kappa$$\omega$ of cardinality less than $\kappa$, then $\bigvee\Phi$ is in $\mathcal{L}\kappa$$\omega$" I'm not seeing what rules it out.
|
Formulae in $\mathcal{L}_{\kappa\omega}$ are built up inductively. For each $\varphi\in \mathcal{L}_{\kappa\omega}$ we can inductively define the set $S_\varphi=\\{S_\psi : \psi \mbox{ is a proper subformula of } \varphi\\}$.
A $\varphi$ as you've proposed would give $S_\varphi\in S_\varphi$, violating foundation.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "logic"
}
|
Check if All Values Exist as Keys in Dictionary
I have a list of values, and a dictionary. I want to ensure that each value in the list exists as a key in the dictionary. At the moment I'm using two sets to figure out if any values don't exist in the dictionary
unmapped = set(foo) - set(bar.keys())
Is there a more pythonic way to test this though? It feels like a bit of a hack?
|
Your approach will work, however, there will be overhead from the conversion to `set`.
Another solution with the same time complexity would be:
all(i in bar for i in foo)
Both of these have time complexity `O(len(foo))`
bar = {str(i): i for i in range(100000)}
foo = [str(i) for i in range(1, 10000, 2)]
%timeit all(i in bar for i in foo)
462 µs ± 14.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit set(foo) - set(bar)
14.6 ms ± 174 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# The overhead is all the difference here:
foo = set(foo)
bar = set(bar)
%timeit foo - bar
213 µs ± 1.48 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
The overhead here makes a pretty big difference, so I would choose `all` here.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "python"
}
|
In Angular2+, when are static variables set?
Suppose I have a service in Angular 5 that looks like
@Injectable()
export class CognitoUtil {
constructor(
private anotherService: AnotherService
) {}
public static GREETING = "Howdie Partner";
}
What is the lifecycle of the variable `GREETING`?
When is it set? Is it set as soon as the app is loaded before it is even bootstrapped (it seems so to me) ? Is there anyway to get something to happen before it runs - for example, to set other values that might affect the final given value to `GREETING`?
I'd really appreciate some clarification on this.
Thanks!
|
First of all, i think you are right about "When is it set".
Second, from my perspective, you should not use static variables in the services because you are violating Dependencies Injection pattern.
If you must use it, i think you can try to use the APP_INITIALIZER provided by Angular.
as example:
import { HttpClientModule } from "@angular/common/http";
import { CognitoService } from './cognito.service';
import { AnotherService } from './another.service';
export function init_app(anotherService : AnotherService ) {
return () => {
CognitoService.GREETING = anotherService.someValue;
};
}
@NgModule({
imports: [HttpClientModule],
providers: [
AnotherService,
CognitoService,
{ provide: APP_INITIALIZER, useFactory: init_app, deps: [AnotherService], multi: true }
]
})
export class AppLoadModule { }
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "angular, typescript, lifecycle, angular services, static variables"
}
|
How can I make the line beneath my heading the same width as the text?
How can I make sure the line beneath my header is the same length as the text itself?
This is my HTML:
<h2>Hello world!</h2>
This is my CSS:
h2:after {
content: " ";
display: block;
width: inherit;
height: 4px;
background-color: #f77f00;
color: #f77f00;
}
What I have tried:
* Setting width of pseudo element to 100%
* width: inherit on pseudo element
CodePen example: <
|
Use `display: inline-block` on your `h2`
h2{
display: inline-block;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
}
|
rhc port-forward not working for collaborated app
I am trying to use the "rhc port-forward " command for an app that my friend has made me a collaborator on. The app appears with my other apps when I do "rhc apps" and the gear is not off or in idle. Does anyone know what is wrong or if it is an openshift bug?
|
Since their application is in another namespace, make sure that you are using the -n or --namespace flag when running rhc port-forward
Usage: rhc port-forward <application>
Forward remote ports to the workstation
Options
-n, --namespace NAME Name of a domain
-g, --gear ID Gear ID you are port forwarding to (optional)
-a, --app NAME Name of an application
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "openshift, portforwarding, collaboration, openshift client tools"
}
|
WCF / Local Data Access Layer
I'm looking for a way to create a data access layer that can either reside on a server and be accessed via WCF services or can reside on the local machine in which case it would just be accessed directly without having to run through iis. Is there a way to abstract this in such a way that changing from the local to the WCF version can be done via a configuration file?
|
It sounds like you want the provider model.
Check out: <
You create two providers that share a common interface and choose the appropriate one based on the configuration.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "wcf, data access layer"
}
|
Simple way to implement current month in Django template?
I am looking for a simple way to implement the current month in my template, in the spelled out format, e.g. "June". So this: `"The current month is:" {{ code here }}` should produce `The current month is: June"`
I could create my own filters however I wanted to know if there was something akin to `{% now "Y" %}` \- which works for the current year.
|
Use the format `F` with `now`:
The current month is: {% now "F" %}
A list of the format specifiers can be found at date formats.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "python, django, jinja2"
}
|
503 Service Unavailable...Trying to Read Configuration data from file
I tried to go to one of my local websites and encountered this error in the event log: "The worker process for application pool 'My Website' encountered an error 'Cannot read configuration file ' trying to read configuration data from file '\\\?\', line number '0'. The data field contains the error code."
I received a 503 Service Unavailable on the website and the app pool is stopped.
|
The solution was to go to C:\inetpub\temp\appPools. In my case, there was a shortcut with the name of my website that doesn't go anywhere. I deleted the shortcut and restarted the website. A folder with the name of the website is created with a .config file inside of it. After that, the website works and the app pool continues running.
This was a strange error. I hope this will help anyone else who encounters it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "iis 7, http status code 503"
}
|
How do you get rid of "Validation (XHTML 1.0 Transitional): Attribute 'data-bind' is not a valid attribute of element"
Is there a nice way I can get rid of this in visual studio 10 when using knockoutjs? It just pollutes the warnings.
|
Yes you can do this in VS 2010 SP1 and VS 11 Developer Preview
> Tools > Options
Select:
> Text Editing > HTML > Validation
And select `XHTML5` or `HTML5` from the drop down list
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 45,
"question_score": 27,
"tags": "visual studio 2010, knockout.js"
}
|
I would like to know why the result of this exercise is "10x"
The resolution of this exercise $(2\sqrt{x})*(5\sqrt[3]{x})$ is **10x**. But I can't understand the steps to reach that result, since when I try to solve it, I get to:
* $(2\sqrt{x})\cdot(5\sqrt[3]{x})$
* $5 \cdot 2$
* $(\sqrt{x}) = x ^ \frac{1}{2}$ and $(\sqrt[3]{x}) = x ^ \frac{1}{3}$
* $x ^ \frac{1}{2} \cdot x ^ \frac{1}{3} = x ^ \frac{5}{6}$
* $ 10x ^ \frac{5}{6} $
I would like to know how it is resolved
|
It is $$10x^{1/2}\times x^{1/3}=10x^{1/2+1/3}=10x^{\frac{3+2}{6}}=10x^{5/6}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "radicals"
}
|
Angular2 + ngrx/store for handling failure HTTP requests
I want to have a simple code path for creating and dispatching HTTP actions. What I would like to do is something like:
this.http.request(...)
.map((res: Response) => res.json())
.catch((err: any) => err.json())
.map((payload: any) => { type: 'SUCCESS', payload })
.catch((payload: any) => { type: 'FAILURE', payload})
.subscribe((action: Action) => this.store.dispatch(action));
That way both the success and failure responses are converted to JSON and then based upon the success/fail criteria assign the correct reduction type so that the store can be operated on properly. (think user login success and failure which returns a 200 or 401).
Is there a cleaner or better way of handling this? Current the 2nd `.catch` doesn't play well since it is not returning an observable.
Suggestions or other solutions welcome?
|
In one of my services I do it like this:
get(url, actionType) {
this._http.get(BASE_URL + url)
.map(response => response.json())
.map(payload => ({ type: actionType, payload }))
.subscribe(action => this.store.dispatch(action), error => this._apiErrorHandler(error));
}
private _apiErrorHandler(response) {
let payload = response.json().error;
this.store.dispatch({ type: 'API_ERROR', payload });
}
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 9,
"tags": "angular, redux, rxjs, ngrx"
}
|
read ArrayList elements
Why it print the wrong output?
ArrayList<String> loc = new ArrayList<String>();
This arraylist stored the value of:
[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]
the firs index 0 is = topLeft
if(loc.get(1)=="topLeft")
System.out.println("same")
else {
System.out.println("not same")
}
This program print the wrong output `not same` instead of `same`
|
Use the `equals(Object)` method, not the `==` operator, for example `loc.equals("topLeft")`
The `==` operator returns true if two references point to the same Object in memory. The equals(Object o) method checks whether the two objects are equivalent, so will return true if two Strings contain only the same characters in the same order.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, arraylist, println"
}
|
Google Maps Can I get tiles?
I want to dynamically create a map but in the same/similar UI to Google maps. Is there a place to get tiles that I can use? An example: enter link description here
|
Open Street Map is a place where you can download the map data.
www.openstreetmap.org
gmap catcher can save tiles from it: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "google maps, user interface, maps, tiles game"
}
|
In aspx, fileUpload is alway null after postBack
I have a fileUpload in an aspx webpage. When a user chooses a JPEG file and clicks a button, I cannot get JPEG file. fileUpload always return null. I think it gets nulled on postback. How can I fix this?
my code is like below
protected void btnPost_Click(object sender, EventArgs e)
{
Stream fs = fileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
....
....
}
|
Without seeing your ASPX markup it is difficult to say precisely.
Your ASPX markup should be similar to:
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="myFile" name="myFile" />
<asp:Button runat="server" ID="btnPost" OnClick="btnPostClick" Text="Upload" />
</form>
C# Code-behind:
protected void btnPost_Click(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files["myFile"];
if (file != null && file.ContentLength > 0)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, asp.net, file upload"
}
|
Avoid multiple AsyncTask when calling Autocomplete google places
I am using a text watcher to show the user a list of google places predictions, each time the user types a character, the asyncTask starts to get the new prediction, but when the user types too fast, all asyncTasks are triggered and will show multiple laggy results.
My question here, can i cancel old asyncTasks and only trigger the one with the last typed character?
|
I finally managed to make the correct answer .. thanks @torque203
I initialized Google Places AsyncTask method in the beginning of the class as following
private GooglePlaces GP = null;
and then ..
if (GP != null) {
GP.cancel(true);
GP = new GooglePlaces();
GP.execute(sb.toString());
} else {
GP = new GooglePlaces();
GP.execute(sb.toString());
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, android asynctask"
}
|
Can google search engine read meta tags that are echo using php
I'm creating a website which is based on php; So i have a page
Which changes it content depending on variable i put in url
And insde of my .php file I want to have
<meta name="keywords" content="<?php echo $_GET["var"] ?>" />
Can google search engine read this
|
Yes, There is no difference for google crawler wheather you write a static content in you HTML OR you write it dynamically using PHP or any other server side programming language.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -4,
"tags": "php, html, google search, meta"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.