INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
double limit of a series summation
There is a sequence $a_n$ and $a_n \to 0$ as $n \to \infty$. Let $S_N = \sum_{n=0}^{N} a_n$. Let the sequence $S_N$ be converging to a limit $l$ where $l \in \mathbb{R}$. What is $\lim_{K\to\infty}\lim_{N\to\infty}\sum_{n=K}^{N} a_n $ ? | 0.
$l = \lim_{N\to\infty}\sum_{n=0}^{N} a_n$. Therefore $\lim_{N\to\infty}\sum_{n=K}^{N} a_n = l - \sum_{n=0}^{K-1} a_n = l - S_{K-1}$.
But since the sequence converges to $l$, $\lim_{K\to\infty} |S_{K} - l| = 0$. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "sequences and series"
} |
Python: is there a difference between using an object as an argument e.g. method(XXX) vs. this syntax: XXX.method()?
Sorry that I do not yet have the vocabulary to express this question properly.
For example:
# Import sas7bdat package
from sas7bdat import SAS7BDAT
# Save file to a DataFrame: df_sas
with SAS7BDAT('sales.sas7bdat') as file:
df_sas = file.to_data_frame()
# Print head of DataFrame
print(df_sas.head())
and
# Save file to a DataFrame: df_sas
with SAS7BDAT('sales.sas7bdat') as file:
df_sas = SAS7BDAT.to_data_frame(file)
# Print head of DataFrame
print(df_sas.head())
both produce the same result. Are they generally equivalent or is this a special circumstance? | I wouldn't call it a special case but rather indirect.
You are creating an object `file` that is an instance of that class SAS7BDAT with `with SAS7BDAT('sales.sas7bdat') as file:` and then you are using the Class method `to_data_frame`from the Class instead from the instance directly. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, syntax, arguments, function call"
} |
Can I destroy a class instance even if there are still references?
For debugging reasons I want to destroy a class instance which still as references. Is that possible? It doesn't have to be elegant or stable, because this'll never end up in production code.
To clarify:
Public Sub Main
Dim o as MyClass
Set o = New MyClass //o is created, one reference
DestroyObject o //Class_Terminate is called and the object destroyed
//Further code, not using o
End Sub //Possible runtime error here (don't care)
Is that possible? One way would be to call `IUnknown::Release` to manually decrease the reference count, but how do I now how often I must call it? | This is a very bad idea
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private m_oRef As Class1
Private Sub Command1_Click()
Dim o As Class1
Set o = New Class1
Set m_oRef = o
DestroyObject o
' releasing m_oRef after this point will bring down the IDE '
End Sub
Private Sub DestroyObject(pArg As Object)
Dim lRefCount As Long
Dim lIdx As Long
Dim pUnk As IUnknown
lIdx = ObjPtr(pArg) + &H20
Call CopyMemory(lRefCount, ByVal lIdx, 4)
For lIdx = 1 To lRefCount - 2
Call CopyMemory(pUnk, pArg, 4)
Set pUnk = Nothing
Next
Set pArg = Nothing
End Sub | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "debugging, vb6, activex, reference counting"
} |
is it possible to get a class return true in is_null?
I am building some kind of a proxy pattern class for lazyloading SQL queries.
The proxy pattern uses `__call`, `__get` and `__set` for relaying calls on it's object, but sometimes there is no object, if the SQL did not return any rows.
My question is then, if i do a `is_null()` on the proxy class, is it possible to make the class return `true` then? I am thinking is there any SPL interface I can implement like Countable which makes the class work in `count()`.
Any suggestions? | Sadly, this is not possible I'm afraid for a object passed to is_null to return true. Some alternative might be to:
1. Use NullObjects, an interesting discussion on these can be found recently on sitepoint <
2. Actually return null rather than an object, although this may not be possible in your situation. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, proxy, isnull"
} |
Libraries for date validation in C?
I have a struct of values for a date.
struct date
{
int day;
int month;
int year;
};
Are there any libraries for C for quick and easy date validation. | The standard C library function `mktime()` will convert year/month/day (really a full `struct tm`) to a `time_t`, and tell you if something went wrong. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c, validation, date"
} |
Убрать пустые строки или неразрывный пробел BS4
Пытаюсь вывести описание ресторана, но в нём есть символы неразрывного пробела, или что-то типа того, которые никак не удаётся убрать. Подскажите, пожалуйста, как от этого можно избавиться? upd: помимо неразрывных пробелов, нужно убрать переход строки, чтоб вывод был однострочный, если такое вообще возможно
url = "
hdr = {'User-Agent': 'Mozilla/5.0'}
reqs = requests.get(url, headers=hdr)
soup = BeautifulSoup(reqs.text, 'lxml')
for link in soup.find_all(class_='place-title__header'):
for link2 in soup.find(class_='place__description').find_all(class_='expandable-text'):
print(url + '|' + str.strip(link.text) + '|' + str.strip(link2.text).replace('\xa0', '').replace('\n', ''))
Вывод: < | name = soup.find(class_='place-title__header').text
title = ' '.join(soup.find(class_="expandable-text__t").stripped_strings)
print(url)
print(name)
print(title) | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, beautiful soup, web scraping"
} |
WebDriver get text
I use WebDriver and ChromeDriver. How i can fetch text from this speech bubble:
![click to see picture 1]
And code this speech bubble from website:
!click to see picture 2
Thank you for your help! | Use xpath to get it
//img[@data-id='c085ede491334747f26718fc2e8009e3')]
You can use this code and try:
driver.findElement(By.xpath("//img[@data-id='c085ede491334747f26718fc2e8009e3')]")).getAttribute("data-content"); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "java, selenium, selenium chromedriver, chrome web driver"
} |
Is the validity of measuring area by approximation an assumption of calculus?
The assumption that if you subdivide an area into more and more sub intervals, the approximation gets better and better. Has this been formally proved, or is it just intuition? Thanks! | I think a good thing for you to think about is upper and lower Riemann sums.
If you have an over-approximation of the area (via the assumption of finite additivity of area) and an under-approximation of the area (again via this assumption), and the over-approximation and under-approximation converge to the same thing then we can safely call/define this the area.
These upper and lower sums don't always converge in which case we have to rethink things. | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "calculus, measure theory, math history, geometric measure theory"
} |
How can I have two strings within an IF(CONTAINS( function?
If the text field contains both "A" and "B", then it should result in "AB".
My formula:
if(contains(
Text_Field__c, "A" & "B"
), "AB",
It goes through; there are no syntax errors. But it doesn´t work.
Any ideas? | You need to use `&&` operator :
if((contains(Text_Field__c, "A") && contains(Text_Field__c, "B")), "AB", "")
Or use `AND` operator :
IF(AND(contains(Text_Field__c, "A"), contains(Text_Field__c, "B")), "AB", "") | stackexchange-salesforce | {
"answer_score": 1,
"question_score": 0,
"tags": "formula, formula field, contains"
} |
SQL Server PROCEDURE Variable Declaration
I got a doubt why we have to reassign the variable to new value when we are calling a stored procedure with parameter. In procedure we need 2 variables. and that variables need to be reassigned for using inside the procedure. | Parameter sniffing
<
> SQL Server compiles the stored procedures using (sniffing) the parameters send the first time the procedure is compiled and put it in plan cache. After that every time the procedure executed again, SQL Server retrieves the execution plan from the cache and uses it (unless there is a reason for recompilation). The potential problem arises when the first time the stored procedure is executed, the set of parameters generate an acceptable plan for that set of parameters but very bad for other more common sets of parameters.
One of the solutions in the link provided is to use local variables. E.g what you are already doing. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "sql, variables, stored procedures, declaration, procedure"
} |
Filtering issue with Urchin 6
I have the following filter for one of my profile:
* filter type: Include Pattern Only
* filter field: user_defined_variable (AUTO)
* filter pattern: \\[53\\]
* case sensitive: no
In my content, I have the following javascript:
_userv=0;
urchinTracker();
__utmSetVar("various string in here");
Now, the issue is that in this profiles, there are files that are showing up in the report that shouldn't. For instance, for a specific profile, in the Webmaster View > Content By Title, a page with the following variable (as seen from the source) shows up :
__utmSetVar("[3][345]")
I have no idea why this is happening. The filter pattern doesn't match thus it shouldn't show up. | It turns out that it's supposed to include files that may have a different pattern. The reason is that it will report on all the files that were seen during a single visit, which includes other files with different custom variables.
To see the report on the custom vars:
Marketing Optimization \- Visitor segment performance \-- User defined | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "google analytics, urchin"
} |
CString Unable to Load Japanese string from Resource
I don‘t know its a valid question or not.
I am working on one project where I want to Load a Japanese string from a string Table.
But I am unable to do that. When I am Loading String Resource in `CString` it Load Japanese Char as `???????????`.
I am using following code to Load String.
`CString msg;`
`msg.LoadString(JAPANESE_STRING_RESOURCE_ID)`
and in String Table I have added string as
`JAPANESE_STRING_RESOURCE_ID 128 " "`
I am not able to trace for the same.
Can any one help me out on this? | In most cases, using Unicode on project helps with this kind of troubles. If you definitely need to use Multibyte in your project, you still can use Unicode CSrting-s - it's CStringW. This can help:
CStringW msg;
msg.LoadString(JAPANESE_STRING_RESOURCE_ID) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, string, mfc, cstring"
} |
How can I disable SSE in GCC?
I'm trying to make a package in debian (squeeze, armel). Problem is, my GCC seems to have set -msse2 which is unsupported on ARM, and I have no idea how to disable it. How can I change GCC's default flags to disable this? Thanks.
Full error:
Building CXX object frameworks/CoreLib/CMakeFiles/.....cpp.o
cc1plus: error: unrecognized command line option "-msse2"
make[2] \*\*\* [fframeworks/CoreLib/CMakeFiles/.....cpp.o] Error 1
make[1] \*\*\* [frameworks/CoreLib/CMakeFiles/.....dir/all] Error 2
make \*\*\* [all] Error 2
thing is, none of the files mention have -msse2 in them, anywhere, which is why I think the compiler might be to blame. | MMX, SSE an SSE2 are Intel/AMD specific extensions that are not supported on ARM, ARM has it's own NEON SIMD extensions. It seems to me like you're trying to cross-compile a program for ARM and using the _native_ toochain, for that you will need a toolchain for the target platform. Here's a tutorial on how to install an ARM toolchain that might help
Edit: now that I see the error, the Makefile is passing `-msse2` to gcc, you should read the instructions for compiling that package to ARM see if that is even possible. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "gcc, arm, debian, sse"
} |
Can I pass an intent to Play, for the newly installed app to receive on startup?
I have two Android apps. Activating a particular feature in one should send an intent to the other, but if that other application is not installed, I have to send the user to Play to install it.
I know how to detect whether the other app is installed and how to open the market - Download app if intent not installed \- and I'm aware that I could set up a listener to detect when the second application is freshly installed and in principle send it the intent I first wanted to send - How to catch or receive android os ' broadcasts' of installed applications? \- but is there a way to embed the intent I wanted to send to the other app into the play-launching intent, so it will be activated automagically when that other app is installed? | You can't intervene on the play-launching intent.
What you can do is, as you said, listen for the install of the app.
Once the app is installed, send it an intent containing any data you would like it to receive.
In the receiving application, take that intent and store the data to SharedPreferences or to a file. Once the user installs the newly opened app, check for that data in the main activity and use it accordingly. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, android intent, google play"
} |
Primitive = Non-negative + Irreducible + 1 Positive element on main diagonal
Can anyone provide me with the proof for the sufficient condition for a matrix to be primitive as described by the definition from planetmath.org? (< = \gcd\\{ n: P^n_{ii} >0\\}=1.$$ Since, the matrix is irreducible, all the states have the same period, namely $d = 1$ (i.e. the matrix is aperiodic). Thus, we have an irreducible and aperiodic matrix. Now, this answer addresses the question why an irreducible and aperiodic matrix is primitive. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "matrices, proof writing"
} |
javascript variable not been assigned properly
I am very new to javascript and have started learning recently. I am not able to assign the variable to correct value. Below is the code:
person={
firstname: fnName,
lastname:"Doe",
age:50,
eyecolor:"blue"
}
var fnName=(function(){
return 'John';
})();
console.log(person.firstname + " is " + person.age + " years old.");
The output should be John is 50 years old. The jsfiddle link is <
Please let me know where I am going wrong? | Try:
var fnName = function() {
return 'John';
}
var person = {
firstname: fnName,
lastname: "Doe",
age: 50,
eyecolor: "blue"
}
console.log(person.firstname + " is " + person.age + " years old.");
That way the object "person" will know what fName is. Also you don't need your function to call itself when the code is first executed. Format your function like the code above. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript"
} |
How to make a type alias that references itself?
I made a few gateways / providers to integrate with an API in my API, using RX Swift and I'm trying to handle the pagination in what seems to me like a clean and simple way.
Basically, the function signature would look like that:
func getPlaces(with location: CLLocationCoordinate2D) -> Observable<(value: [Place], next: Observable<(value: [Places], Observable<(value: [Place], next: ... ... >>
This quickly appears impractical, so I tried creating a typealias for that:
typealias Result = Observable<(value: [Place], next: Result?)>
So my function signature would look like this:
func getPlaces(with location: CLLocationCoordinate2D) -> Result
But Xcode wouldn't get fooled so easily and calls me out for referencing my typealias inside itself
So... is it even doable ? How ? | I don't think this is possible using a `typealias` because you are creating an infinite type. The only way I can think of is to make `Observable` a recursive enumeration:
enum Observable {
case end([Place])
indirect case node([Place], Observable)
} | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "swift, rx swift"
} |
How can I get Number of Threads and Duration from CSV in Jmeter
I can easily get username and password from CSV using CSV config control in Jmeter but I can't do same for Number of Threads & Duration for Thread Group.
I tried and provided Number of Threads and duration in CSV but seems not working. Getting Number of Threads always Zero.
Is there any way to get it? Just want to make my JMX dynamic so no need to open JMX if I only want to change number of threads and duration and can be easily update. | Your requirement is to parameterize the number of threads and duration. But should it be from CSV file by using `CSV config element`? Because We can not do that way!
One suggestion is to keep a properties file for thread numbers and duration for each Thread Group and pass the properties file as parameter.
This is exactly explained here with more additional information as well.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jmeter, jmeter plugins"
} |
How to return data in Promise Angular?
I have a simple Promise like:
return new Promise((resolve) => {
resolve();
});
Also there is an object: `var obj = {};`
How to return this object in Promise described above?
Like this:
return new Promise((resolve) => {
resolve(obj);
}); | Try following code snippet.
obj = {
"fname": "data"
};
function getData() {
return new Promise((resolve) => {
resolve(obj);
});
}
getData().then((data) => {
console.log(data);
});
**JSFIDDLE** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angular"
} |
How to make a link within a TeX file into a page of an existing PDF file
Suppose there is a large online textbook in PDF, without TeX source code. How do I link to a certain page of it within my PDFLaTeX document? | Adobe has specified a syntax to open PDF files with some parameters inside URLs, see Parameters for Opening PDF files.
With package `hyperref`, your PDF document can refer to other PDF documents. For example, the external document should be opened at page 4:
\url{
\href{ page 4}
However, all party members have to support this:
* The options should go into the link in the PDF file, done by package `hyperref`.
* The PDF viewer.
* The web browser, if the PDF is viewed there, and its PDF viewing component (browser itself, plugin, ...). | stackexchange-tex | {
"answer_score": 3,
"question_score": 2,
"tags": "pdftex, cross referencing, pdf"
} |
Behavior of $|f'(z)|/(1+|f(z)|^2)$ as $|z| \rightarrow \infty$?
Let $f(z)$ be an entire holomorphic function in $\mathbb{C}$, and consider the real-valued function $$g_f(z)=\frac{|f'(z)|}{1+|f(z)|^2}.$$ If $f(z)$ is a polynomial, then it is easy to prove that $\lim_{|z|\rightarrow \infty}g_f(z)=0$.
When $f$ is transcendental, say $f(z)=e^z$, then $g_f(z)=\frac{e^x}{1+e^{2x}}$, which goes to zero when $Re(z)$ is going $\infty$, but remains a constant when $z$ is moving on any vertical line. So far I have not found any example such that the limit goes to zero when $f$ is transcendental.
**My question** is, can we rigorously prove that there is no transcendental entire function $f$ such that $$ \lim_{|z|\rightarrow \infty}g_f(z)=0\; ? $$ | This is not true. The optimal estimate from below for transcendental entire functions is $$\limsup_{z\to\infty}\frac{|z||f'(z)|}{\log|z|(1+|f(z)|^2)}=\infty,$$ and this is best possible,
J. Clunie and W. Hayman, The spherical derivative of integral and meromorphic functons, Comment Math. Helv., 40 (1966) 117-148.
More precisely, for every function $\phi(r)\to+\infty$, they constructed an example of transcendental entire function for which $$\frac{|z||f'(z)|}{\phi(|z|)\log|z|(1+|f(z)|^2)}$$ is bounded. The function in this example is of the form $$f(z)=\prod_{n=1}^\infty\left(1-\frac{z}{2^{k_n}}\right)^{k_n},$$ where $k_n$ is an increasing sequence of integers, which is choosen, depending on $\phi$. | stackexchange-mathoverflow_net_7z | {
"answer_score": 16,
"question_score": 13,
"tags": "cv.complex variables, analytic functions"
} |
Is that a negated inner join
I have seen some times this query. A double from x in list.
Is that a negated inner join?
var pupilsWithoutTests = from p in allPupils
from tp in test.PupilsTests
where p.Id != tp.PupilId
because I can not do
var pupilsWithoutTests = from p in allPupils
join tp in test.PupilsTests on p.id !equals tp.PupilId;
select p; | This is a cross join followed by a filter. I have never heard the term negated join. It is equivalent to `select * from a join b on a.x != b.x`, though, if that's what you mean. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, linq"
} |
Run Button is Disabled in Android Studio
I can't click the run button. Does anyone know how to fix it?
!Disabled Run Button | Click Run on the menu and then Edit Configurations... then click on Android Application on the left and click the + button. Choose Android Application from the pop-up menu. Then pick the module (its normally app or something like that). Then click apply and ok.
If you have more errors after that, try to re-import the project in Android Studio. | stackexchange-stackoverflow | {
"answer_score": 207,
"question_score": 158,
"tags": "android, android studio"
} |
Exception Handling in C#: Multple Try/Catches vs. One
Is it good practice to have more than one `try{} catch{}` statement per method? | In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it.
As Lisa pointed out you should catch specific exceptions and _only_ catch the exceptions the method can actually handle. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 5,
"tags": "c#, exception"
} |
The local farm is not accessible
When I run SharePoint PowerShell on my SharePoint server I get the following error:
Error: `"The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered".` | Make sure the logged in user has rights to configuration database.
< | stackexchange-sharepoint | {
"answer_score": 2,
"question_score": 2,
"tags": "sharepoint enterprise, powershell"
} |
Bitlocker: USB drive accessible by other os users
I have a bitlocker encrypted USB drive connected to my PC. I just noticed that other OS-users on that PC can also access the USB drive.
e.g.
* I login to my account - the USB drive is automatically unlocked (I need this for auto-backup on start)
* when I now press WIN+L and switch to another user, that user also has access to the USB drive
Is there a way to avoid this? | I am pretty sure Bitlocker is a per machine encryption technology, not per user. So as you noticed if one user unlocks a drive, it is unlocked for everybody.
This is also the case for other technologies like VeraCrypt.
You can try to make sure that nobody else can log onto your machine while you have unlocked a drive, and always lock it when you leave.
Otherwise you need to look into other options depending on your needs. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "windows 10, bitlocker, usb storage"
} |
How do I access a taxonomy term's field(s)?
Specifically, I'm trying to access a field called 'logo' inside of a couple taxonomy terms (Tweet and Wikipedia edit), which is an image. I have a news feed on the front page of my site, and for each feed item that has a term reference to one of these image beside each feed item in the feed. What would be the best way to go about exposing or accessing the logo field from each taxonomy term? | If you are going to be accessing the content of what drupal call entities (data objects, like nodes, users, taxonomies etc), you might considder using the entity module. It adds some nice helper functions. What Nikit writes is not possible, you would do something like this:
$term_id_1 = $node->field_term['und'][0]['tid'];
$term_id_2 = $node->field_term['und'][1]['tid'];
Then you would have to load the terms etc. Instead with the entity module you can do.
$images = array();
$node_wrapper = entity_metadata_wrapper('node', $node);
foreach ($node_wrapper->field_term as $term_wrapper) {
$images[] = $term_wrapper->field_image->value();
}
`$images` will now be an array with the image field object that holds info like uri, fid etc. | stackexchange-drupal | {
"answer_score": 8,
"question_score": 7,
"tags": "7, taxonomy terms"
} |
Search and Replace in a Text File In Flask
I want to search and replace in a text file in flask.
@app.route('/links', methods=['POST'])
def get_links():
search_line= "blah blah"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt')):
x = line.replace(search_line,
search_line + "\n" + request.form.get(u'query'))
except BaseException as e:
print e
return render_template('index.html')
This code always deletes all lines in my txt file. And I have unicode and "input() already active" erros.
Is this a correct way to do this? I have to work with python 2.6 | Your code will always delete all lines since you are not writing lines back to files in both case i.e when search_line is present and when search_line is not present.
**Please check the below code with comments inline.**
@app.route('/links', methods=['POST'])
def get_links():
search_line= "blah blah"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt'),inplace=1):
#Search line
if search_line in line:
#If yes Modify it
x = line.replace(search_line,search_line + "\n" + request.form.get(u'query'))
#Write to file
print (x)
else:
#Write as it is
print (x)
except BaseException as e:
print e
return render_template('index.html') | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "python, flask"
} |
Data representation and bit/time complexity
I have a simple technical question on multiplication of finite bit words. Say the number of bits of words that need to be multiplied is $O(\log{M})$ and say an hypothetical algorithm uses $O(\log{M})$ intermediate words of size $O(\log\log{M})$ bits (doing simple addition and modulo-$2$ operations for $O(\log{M})$ times on these $O(\log\log{M})$ bit words) and producing the final output of $O(\log{M})$ bits, would that be an $O(\log{M})$ bit/time complexity or an $O(\log{M}\log\log{M})$ bit/time complexity algorithm? I looked on literature and I could not identify the exact notion/relation bit time and bit space complexity of such algorithms. Atleast it was not clear to me. | Your algorithm has a time complexity of $O(n \log n)$.
Your algorithm uses $O(\log M)$ intermediate words each of size $O(\log \log M)$. Thus, the algorithm writes up to $O(\log M \log \log M)$ bits, taking $O(\log M \log \log M)$ elementary bit steps. Since the complexity is measured based on the input size, which is $\log M$ in your case, it has a complexity of $O(n \log n)$ [to multiply two words represented by $n$ bits].
Further note that since $O(.)$ only gives an upper bound on the asymptotic worst-case runtime, it is possible that your algorithm is actually faster, ie, the bound was not tight. For example, the algorithm could use just 1 intermediary word of size 1, which would make the algorithm be in $O(1)$. | stackexchange-cstheory | {
"answer_score": 1,
"question_score": -1,
"tags": "cc.complexity theory, terminology"
} |
javascript windows alert with redirect function
.guys I have the following code:
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Succesfully Updated')
</SCRIPT>");
what i want to do is that when i click ok on the windows.alert the page will be redirected to a my edit.php.
or how is it possible to create a javascript which will execute an insert query. | Alert will block the program flow so you can just write the following.
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='
</script>"); | stackexchange-stackoverflow | {
"answer_score": 37,
"question_score": 11,
"tags": "php, javascript, html"
} |
Jscript regex to get text between slashes
Trying to create regex to extract part of the string with use of jscript/jquery I am noob in both :P
**String pattern** :
> A..Z/CB..C/ABC+BCD/ABCD/TextToGet1/TextToGet2/1-9/1-9
text to get is after 4th slash and 5th slash [TextToGet1] and [TextToGet2]
thx | How about using `split` instead, since it is by `/` that you want your results like:
var result = " A..Z/CB..C/ABC+BCD/ABCD/TextToGet1/TextToGet2/1-9/1-9".split('/')
`result[4] //outputs TextToGet1`
and
`result[5] //outputs TextToGet2` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "regex, jscript"
} |
How do i change iOS storyboard Interface Builder to show iPhone4 preview?
Currently I have to run it on a device, and I have no idea how to see a preview on the storyboard (for iphone4 VS iphone5)
I am using XCode 6 | This my first experience with Xcode coding for iOS, so I'm using Xcode 6 and I didn't find any of the widgets in @return-true answer.
I guess in Xcode 6 you're left with the options shown in the w-vs-h widget at the bottom of the storyboard:
 not navigating to the exact place of the comment?
When I clicked **"Modified -- ago"** of one of the post in Pro Webmasters, it's navigating the question and not to the exact comment of an answer. But the question URL is passing the ID of that comment. Instead of placing the position in question, we should navigate exactly to the comment which will be more useful for users. Because If we have more answers or comments for a particular question, it will be difficult to find where the exact modification has been done.
Screenshot:
 cause 'modified' to be shown on the homepage.
In this case, the user posted an NAA as an answer, which a moderator converted to a comment. Their username is shown as the modification because they did cause the modification by answering the question. However, their answer no longer exists.
The ID is not the ID of the comment but rather the ID of the now-deleted answer. The page does not scroll anywhere because the answer has been deleted, and you do not have the privilege to see deleted posts, so the anchor to scroll to does not exist. Should you have the privilege, the link works fine and scrolls to the deleted answer. | stackexchange-meta | {
"answer_score": 8,
"question_score": 2,
"tags": "discussion, feature request, comments, navigation"
} |
Can I prompt a user to log in to facebook through a bookmarklet generated div?
I'm looking to see some info about my facebook contacts, and I want the info to be overlayed on the currently open website.
Currently, I'm trying to do this via a bookmarklet.
Is it possible for me to overlay a div over the currently open web page and populate it with a functioning facebook login button (if the user is not logged in)? Are there publicly available working examples of something like this? | It is probably not possible to simply embed Facebook within an iframe because Facebook blocks people from embedding their pages within frames or iframes by putting this into the response header, "X-Frame-Options: DENY". This is most likely to prevent click-jacking and similar security exploits.
To test this, enter any page from Facebook into <
Facebook has an API which allows you to do many things, but it requires server side code, and can not be done simply with a bookmarklet.
There is also always the brute force method where your server scrapes data from any website you want it to. Then that data could be put into a bookmarklet.
Finally, the same thing could be achieved by writing an add-on or a user script without using a bookmarklet at all. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "facebook graph api, facebook javascript sdk, bookmarklet"
} |
foreach output a set number of arrays only
How would I output only a set of numbers in an array, say if theres 10 arrays, I would only like to output 8 of them?
foreach($arrays as $array){
//do I use a for loop/
}
Thanks! | `foreach` is only the natural approach if you actually want to iterate over **each** item (as the name implies). However, you could do something like this:
$i = 0;
foreach($arrays as $array){
...
$i++;
if ($i == $limit) {
break;
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays, foreach, count, iteration"
} |
How does canvas.bind(event, handler) pass event to the event handler?
The primary way of passing arguments to a function in Python is this:
def function(x):
# function definition
function(y)
That is, when we call `function` we pass a value to it inside parenthesis.
However, I am using tkinter, and the event `canvas.bind()` method works thus:
def event_handler(event):
# function definition
canvas.bind('event-name', event_handler)
That is, when `canvas.bind` calls the method `event_handler`, it seemingly does not pass the argument `'event-name'` to `event_handler` as one would expect (i.e. by doing `event_handler('event-name')`). Instead, it just calls `event_handler` without any arguments.
So how does `event-handler` receive the event argument it is supposed to receive, going by its definition? | It does it just like you expect. In the binding you are giving the _name_ of the function to call. When the event fires, the internal tkinter code that processes the event actually calls it just as you would: `event_handler(event)`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, canvas, tkinter, tkinter canvas"
} |
Cast Java array of arrays to Java 2D array
I have an object that is of type `Object[]`. All elements of the array are actually `Object[]` objects. So essentially it looks like this
Object[] oneD = {objectArray1, objectArray2, objectArray3, ...}
I want to cast this to an `Object[][]`, like this:
Object[][] twoD = (Object[][])oneD;
but I get compiler errors and `ClassCastException`'s.
Is there a (correct) way to do this? | You can't cast between array types - java ain't C, but you can transform one pretty easily:
Object[] oneD = {new Object[]{}, new Object[]{}, ...};
Object[][] twoD = Arrays.stream(oneD).map(Object[].class::cast).toArray(Object[][]::new); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, arrays, casting"
} |
update cursor inputting the same values
I've got a numpy array and need to sum the values in the rows. Then use the Update Cursor to update a field with this value. However the update cursor is updating the field with the same values.
tbl = arcpy.da.FeatureClassToNumPyArray(dg, ave_fields)
with arcpy.da.UpdateCursor(dg, "Weekly_Ave") as ucursor:
for urow in ucursor:
for i in range(len(tbl)):
urow[0] = sum(tbl[i])
ucursor.updateRow(urow) | With each row you iterate through integers of the length of `tbl` (`1, 2, 3, 4....`) and update each row for each value. The final value will always be the last value in `tbl`. You'll need to get rid of your nested loop to fix the problem. | stackexchange-gis | {
"answer_score": 5,
"question_score": 1,
"tags": "arcpy, cursor"
} |
Angular Material Table automatic scroll
Is there any way to scroll the Angular Material Table in the code behind?
I have a requirement that the table should be always at the bottom bosition when the page loads. Unfortunately paging is not an option. | Typically, scrollable elements in angular material with scroll capability use cdkScrollable directive, but it doesn't seem to be the case with `mat-table`
So for now you could bypass it by directly accessing the element, and scroll to a high y value
scrollBottom() {
document.querySelector('mat-table').scrollBy(0, 10000);
}
Example | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "angular, angular material, angular material 5"
} |
Does fabric CA server have to be run in 24hours?
I am wondering if Fabric CA server must be run in 24hours. If so, do I need any server computer(cloud or physical)?
Is there no other way to resolve authentication issue **by nodes autonomously without server cost**? | No. The CA is only for users and nodes to be created. But once you have an certificate from the CA, you don't need it in order to transact on the Blockchain.
However, if you want to revoke a user/node you will need the CA to create a CRL. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "hyperledger fabric"
} |
Cell layout right after dequeueReusableCell
Can I assume that after getting a cell from `let cell = tableView.dequeueReusableCell()` the cell will have all it's contents sizes (specifically - will be laid out) and I can safely access f.e. the width of a label that's residing inside the cell?
It seems to be working in my project, but I wanted to be totally shure, but cannot find relevant information in docs. | Much more reliable:
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// do your setup tasks here
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, uitableview, cocoa touch"
} |
Have MTOM and Text message encoding in the same service
I have a WCF service, which expose multiple operation contracts. One contract is to upload a large file. So I want to use MTOM message encoding for that method and text encoding for other methods? How do I create a single service and use text and MTOM message encoding? | Each service contract has to be exposed on separate endpoint so for your upload file contract you can define endpoint with binding using MTOM encoding and for other contracts you can define endpoints with binding using text encoding. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wcf, encoding, mtom"
} |
Appending onto QList<QFile*>
I was wondering why when you make a QList of QFIle you must make them pointers. For example I have a class that has a QList< QFile* >:
class Files
{
public:
void AddFile(QString newFile);
private:
QList<QFile*> files;
}
Now when AddFIle is called it does this:
QFile* newt = new QFile(new_File);
files += newf;
Why am I not able to change the QList< QFile* > into QList< QFile >? Every time I try and do that I get an error:
**QFIle::QFile(const QFile &) is private**
Here is what the code looks like when I change it to QList< QFile >:
class Files
{
public:
void AddFile(QString newFile);
private:
QList<QFile> files;
}
Then the .cpp
QFile newt(new_File);
files += newf; | The `QFile` type must be used as `*QFile` in your example because the author made the copy constructor private. The `QList` type needs access to a copy constructor of its template parameter. The `QFile`'s copy constructor cannot be accessed, but the `QFile*` type has an accessible copy constructor.
This was most likely intentional. It is probably unsafe to make copies of a `QFile` object. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++, qt, raii"
} |
Facilitate SQL table query functionality in Java application
Say I have a couple of columns say **First Name, LastName, Email, Phone**.
I want to query for a row based on a dynamic column selection.
Say the application will ask for a record based on 1) lastname and phone or 2) FirstName 3) Phone and Email
Instead of creating a table to do a SQL query to find a row based on the column data is there a data structure which suits my needs? **I am coding in Java, so if there is an inbuilt API please suggest one**
FirstName | LastName | Email | Phone
abc | xyz | [email protected] | 123
pqr | qwe | [email protected] | 342
ijk | uio | [email protected] | 987 | I'd point you to any of the available in memory SQL Db libraries:
1. H2
2. Derby
3. HSQL
Or maybe you want an indexable, queryable in-memory store:
1. Hazelcast
2. Ehcache
Any one of these allows you to write a query against the data stored. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "java, sql, data structures"
} |
how to launch 10 coroutines in for loop and wait until all of them finish?
I need to fill list of objects from DB. And before passing value to itemes I want all of them to finish. Is here any short way calling await() for each item to wait. I want to make clean code, May be some design pattern or trick?
for (x in 0..10) {
launch {
withContext(Dispatchers.IO){
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}
}
items.value = list | coroutineScope { // limits the scope of concurrency
(0..10).map { // is a shorter way to write IntRange(0, 10)
async(Dispatchers.IO) { // async means "concurrently", context goes here
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}.awaitAll() // waits all of them
} // if any task crashes -- this scope ends with exception | stackexchange-stackoverflow | {
"answer_score": 38,
"question_score": 14,
"tags": "android, kotlin coroutines"
} |
How to delete a zip file on Cloudinary?
My code creates a zip file by calling,
Cloudinary.Multi()
Now I've to delete images.zip on cloudinary.
Cloudinary.DeleteResourcesByTag() //don't work because images.zip has no tag to it.
Cloudinary.DeleteAllResources() // Deletes all images. Zip files persist
Cloudinary.DeleteResources() //May work, what parameters should I pass to it?
I'm using Cloudinary .Net with PowerShell. An answer in C# or any syntax will be o.k
How can I delete the zip? | Based on reply from Cloudinary support,
> In order to delete a ZIP file generated by the multi API, you should set its public ID, e.g., outbox,zip (mind the comma), and also set the type to multi at the deletion API call.
I was able to develop a working solution as,
Cloudinary cloudinary = new Cloudinary(account);
List<string> IDlist = new List<string>();
list.Add("outbox,zip");
DelResParams delParams = new DelResParams();
delParams.PublicIds = IDlist;
delParams.Type = "multi";
cloudinary.DeleteResources(delParams);
And the PowerShell version is,
$list = New-Object -TypeName System.Collections.Generic.List[string]
$list.Add("outbox,zip")
$deleteParams = New-Object CloudinaryDotNet.Actions.DelResParams
$deleteParams.PublicIDs = $list
$deleteParams.Type = "multi"
$cloudinary.DeleteResources($deleteParams) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, powershell, cloudinary"
} |
Add to home function
> **Possible Duplicate:**
> How could I create a shortcut on desktop in iOS through an app
I want to know if it's possible with the iOS API to put a web page on the home screen (in Objective-C). A specific event to catch ? A "magic" function ? :)
Thanks :) | Nope, apps can not do anything outside their sandbox.
As the answer to this question explains, you can launch your page you want to save in Safari and provide users with instructions to save the page from there, then use a url to switch apps back to your app from Safari afterwards, but you can't add a webapp to the springboard from your app itself | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "objective c, ios, sdk, html, homescreen"
} |
proof for double summation formula
I am looking for a proof for this formula:
$$\sum_{t=1}^N\sum_{s=1}^N f(t-s) = \sum_{k=-N+1}^{N-1} (N-|k|)f(k)$$ | ... and from $k = 1-N$ to $N-1$.
Hint: how many pairs $(s,t)$ are there with $t-s = k$? | stackexchange-math | {
"answer_score": 0,
"question_score": -1,
"tags": "statistics, reference request, time series"
} |
have the pointer select beginning of text in a html input?
I am trying to mimic the search bar at < I having almost everything down except I don't know how to place the pointer at the beginning of the text instead of at the end.
How can I have it so when a user clicks in the field, it goes to the front of the "Search" text? | That is a watermark, take a look at this `jQuery` watermark plugin
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "jquery, input"
} |
Is $\ln(x^{p(x)}) = p(x) \ln(x)$?
I am trying to prove that:
$x^{\frac{\ln(\ln(x))}{\ln(x)}} = \ln(x)$
My "solution":
$e^{\ln\left(x^{\frac{\ln(\ln(x))}{\ln(x)}}\right)} = e^{\frac{\ln(\ln(x))}{\ln(x)} \ln(x)} = e^{\ln(\ln(x))} = \ln(x)$
Is the first step valid, i.e is $\ln(x^{p(x)}) = p(x) \ln(x)$
How can I find out for myself? | $$x^{\frac{\ln(\ln(x))}{\ln(x)}}$$ $$=x^{\log_x(\ln(x))}$$ $$=\ln(x)^{\log_x(x)}$$ $$=\ln(x)$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "logarithms"
} |
NAS with eMule and IP blacklists support
There are bunch of ready-made home NAS appliances that claim to handle downloads via eDonkey network (eMule, MLDonkey, etc.) I wonder if any of them can automatically download and apply P2P IP blacklists? | I found that Synology NASes support eMule's ipfilter.dat and there is a 3rd party app to download the IP block lists automatically. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "nas, p2p"
} |
Figuring out the meaning and syntax of the English translation of Charmides
I was reading _The Dialogues of Socrates_ translated into English and one particular sentence in _Charmides_ sprung out as odd. I can't tell what it is trying to say, but I also can't figure out if it is grammatically correct or not.
> Very good, I said; and did you not admit, just now, that temperance is noble?
>
> Yes, certainly, he said.
>
> And the temperate are also good?
>
> Yes.
>
> **And can that be good which does not make men good?**
>
> Certainly not.
I'm guessing that this is correct English but it simply fell out of usage in modern times (e.g. saying "[VERB] + not" instead of "Do + not + [VERB]" for negation). Having said all that, I'm not sure what it is. | There's an extraposition in there.
A more normal order would be
> Can that which does not make men good be good?
but (especially in writing) this is _**less**_ comprehensible, because of the difficulty of finding the end of the relative clause _which does not make men good_.
Also _that which ..._ is somewhat literary: a more ordinary form would be _something which_.
Does this answer your question? | stackexchange-english | {
"answer_score": 3,
"question_score": 0,
"tags": "meaning in context, syntactic analysis, semantics, archaicisms"
} |
How to make code to close program after 5 seconds
So here is my code and I just want to close the program after pressing any key and then the program should display the message saying your program will close in 10,9,8,7... until it's 0 and closes.I know it's very simple but I just began my journey with coding and I simply cannot find the solution to this.
Dim count as Integer
Console.WriteLine("Please press any key to close the program...")
For count = 10 To 1 Step -1
Console.WriteLine("Program will close in: " & count)
Console.ReadKey()
Next | Dim count As Integer
Console.WriteLine("Please press any key to close the program...")
Console.ReadKey()
For count = 10 To 1 Step -1
Console.WriteLine("Program will close in: " & count)
Threading.Thread.Sleep(1000)
Next
This looks like what you are trying to do - but remember there is processing time between those sleeps - so your countdown will not be perfect to the millisecond. You could also accomplish this with Timers. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "vb.net"
} |
Rundll32 load order problem
My product consists of two dlls (A.dll and B.dll for clarity), A.dll depends on B.dll. Both A and B dlls are in the same folder (say c:\app). At the same time old version of B.dll is in Windows\System32 folder. When I try to run following command from command prompt (current folder is c:\app):
rundll32.exe "c:\app\A.dll",DoWork
`
I receive error because rundll32 uses old version of B.dll from System32 folder. I tried to use SetDllDirectory API from DllMain function of A.dll library to add c:\app folder to the search path but it doesn't work for me.
I can't find any useful and complete information about rundll32 internals or any information about dll loading order.
Is it possible to execute rundll32 successfuly in this deployment configuration? (I mean load new B.dll version from c:\app folder). | ## DLL Hell on SO
Well, it's kind of cool in a retro sort of way. Here is a thought: try copying rundll32.exe into the same folder as the new dll's and your product, and run it from there. It might work... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c++, deployment"
} |
Is there a closed form for the number of ways to put up to $k$ chess pieces on a board with $n$ squares?
Given a chess board with $n$ squares, the number of ways $c(n,k)$ to put up to $k$ pairwise distinguishable chess pieces on the board can be described by
$$c(n,k)=nc(n-1,k-1)+c(n,k-1)\quad\hbox{where }c(n,0)=1\hbox{ and }c(0,k)=1$$
where the first term indicates the choice to place the next piece on the board and the second term indicates the choice to leave the next piece off the board.
One can easily see that the second term can be unfolded to yield
$$c(n,k) = 1+n\sum_{i=1}^kc(n-1,i-1)$$
but that's where I couldn't progress anymore. Is there a closed form for $c(n,k)$? | As per comments, I noted that this problem was essentially $$\sum_{i=0}^k \binom{k}{i} \frac{n!}{(n-i)!}$$
While not technically closed form, it might help to find some simplifying factorial or binomial identities... | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "combinatorics, closed form"
} |
How to dynamically include a javascript file, before the page loads
I want to include a local .js file in my index.html page, based on the outcome of an 'if' statement, as described in my sample code below. I need the .js contents to be included in the initial loading of the page, as the contents will be displayed in the html itself on load.
**index.html:**
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<script>
include_another_script();
</script>
</body>
</html>
**script.js:**
include_another_script function(){
var url;
if( //some stuff){
url = "script1.js";
} else {
url = "script2.js";
}
document.write("<script src=url></script>");
} | Try this instead
<head>
<script type="text/javascript">
var url;
if( blah == blah){
url = 'myUrl.js';
}else{
url = 'myOtherUrl.js';
}
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = url;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
</script>
</head> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, html"
} |
Regular expression to find both non-null and NULL values
My stored procedure is using regular expression as a parameter to filter a set of rows:
DECLARE @filter = '%'
SELECT *
FROM TableA
WHERE ColumnA LIKE @filter
Value '%' extracts all non-null values of ColumnA. However I need to extract both non-null AND null values.
The idea of using second condition (and ColumnA is NULL) is not suitable as the filter shall come as a single parameter.
It would be great to find if there any regex expression which can cover NULL values | SQL Server doesn't support Regex, only it's own (more limited) pattern matching.
_Normally_ I wouldn't recommend this answer, however, as you have a leading wild card already performance will be out the window. Assuming you want `'%'` to return every row, you _could_ do:
DECLARE @Filter = '%';
SELECT *
FROM TableA
WHERE ISNULL(ColumnA,'|') LIKE @Filter;
Note, however, that if you _might_ not be using leading wild cards this is a really bad idea; it'll kill performance. If that is the case, then use Lukasz's solution, and not this one. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql server, regex, tsql"
} |
Take a psd and export all the layers into separate image files without using Photoshop
This is my first question here and I'm not sure if this is the appropriate site for my question, but here it goes. If this is not the correct site, please direct me to the correct one.
I have a psd file. I simply want to extract the layers from it into separate image files. I do not have Photoshop and I've already used up the free Photoshop trial.
I am running Mountain Lion on a MacBook Pro. I have installed Gimp, but I can't figure out how to do what I want. I have searched using Google, but have been completely unable to find a tutorial showing me how to do this.
I would really appreciate instructions or a link to an appropriate tutorial. I have seen some answers here, but they simply say use Gimp, which doesn't help me. | If you don't want to install any plugin, do this using GIMP (open source tool):
1. Select the layer and copy `Ctrl`+`C` or `Edit > Copy`
2. Then `Select > File > Create > From Clipboard`, this creates a new document from the copied layer, or you can just make the layer you want the only thing visible.
3. Then `select > File > Save As...` then go down to "Select File Type (By Extension)"
4. In the box where it says "All images select that box and go down to "PNG image (*.png)" | stackexchange-superuser | {
"answer_score": 17,
"question_score": 24,
"tags": "images, adobe photoshop, gimp, layers, psd"
} |
Cloud9 give the editor window focus
Within the Cloud9 IDE, if the focus is set to the Files sidebar (toggleable via `ctrl` \+ `u`), how does one refocus on the editor window to continue coding without reverting to using the mouse?
My current workaround is to hit `ctrl` \+ `g` for `go to line {n}`, but this adds unnecessary steps and can lead to the page scrolling to a completely different location than currently working on. | There is no shortcut for this. But it is easy to add with user script
var editors = require("ext/editors/editors");
require("ext/commands/commands").addCommand({
name: "focusEditor",
exec:function() {
if (editors.currentEditor)
editors.currentEditor.focus();
},
bindKey: "ctrl-alt-w"
});
if you can think of a good shortcut for this suggest it on < too | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "ide, focus, keyboard shortcuts, cloud9 ide"
} |
EM radiation from processes without photon emission
Would it be possible to create EM radiation, starting this process without photon emission from subatomic particles? | Classical electromagnetic waves and quantum field theoretical photons describe the _same phenomena_ —indeed, photons are modes of the field.
There is no distinction between "EM radiation" and "photon emission" except for how you frame the description.
So the answer is **"No."** | stackexchange-physics | {
"answer_score": 4,
"question_score": 0,
"tags": "electromagnetic radiation, photons"
} |
How to create a simple React Dropdown
How do you create a very, very simple dropdown select with React? Nothing seem to work.
I have an array: `var num = [1,2,3,4,5]`
**Function:**
num(e){
this.setState({selected: e.target.value});
}
**In the render:**
<select option="{num}" value={this.state.selected} onChange={this.num} />
No error message, no nothing. I normally use npm plugin for this but I only need something basic. | Setting `option={num}` will not work in jsx. You need to use `<option>` tags:
Something like this is what you are after:
<select name="select" onChange={this.num}>
{num.map(function(n) {
return (<option value={n} selected={this.state.selected === n}>{n}</option>);
})}
</select> | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 9,
"tags": "reactjs"
} |
If I declare 2 replicas of PostgreSQL StatefulSet pods in k8s, are they the same database or they just share the volume?
After making 2 replicas of PostgreSQL StatefulSet pods in k8s, are the the same database? If they do, why I created DB and user in one pod, and can not find the value in the other. If they not, is there no point of creating replicas? | There isn't one simple answer here, it depends on how you configured things. Postgres doesn't support multiple instances sharing the same underlying volume without massive corruption so if you did set things up that way, it's definitely a mistake. More common would be to use the volumeClaimTemplate system so each pod gets its own distinct storage. Then you set up Postgres streaming replication yourself.
Or look at using an operator which handles that setup (and probably more) for you. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "postgresql, kubernetes"
} |
move middle div down if window gets smaller
I have three divs side by side. If the browser window gets smaller I want that the middle div moves down under the first div and the right div moves to the "middle".
For a better understanding, i made following outline !enter image description here
Can someone please tell me how you'd do this? | This jsfiddle should get you started. I forked Candlejack's fiddle, and tried to provide a css only solution.
Basically you put the 2nd div last:
<section id='container'>
<div id='box-1' class='myBox'>1</div>
<div id='box-3' class='myBox'>3</div>
<div id='box-2' class='myBox'>2</div>
</section>
Then you float left div-1 and div-2 while the div-3 floats right, div-1 and div-3 have display: block; while div-2 display: inline-block;
#container { display:inline-block; width:100%; padding: 0.5em 0; border: 1px solid black;}
.myBox { display:inline-block; min-height: 100px; width:300px; margin: 0.5em 0 0.5em 3%; float:left; display: block; }
#box-1 { border:1px solid blue;}
#box-2 { border:1px solid red; display: inline-block; float: left;}
#box-3 { border:1px solid green;float:right;} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "html, css"
} |
Why jQuery doesn't find an element in ready event?
I defined object of _CgridAdminView_ with the properties and methods:
var CgridAdminView = {
controller_name: 'work',
div_table_id: 'grid-admin-works',
tr_add: $('#' + this.div_table_id).find('tr').eq(1),
disabled: '.td_workGroup',
list_cols: [
'index',
'shortName',
'fullName',
'codeName',
'workGroup_id',
'period',
'performers']
};
_tr_add_ property doesn't contain elements in the processor of an event of _ready_ :
$(function(){
CgridAdminView.tr_add.hide();
});
It is works:
$(function(){
var tr_add = $('#'+CgridAdminView.div_table_id).find('tr').eq(1);
tr_add.hide();
});
But _tr_add_ property contains the necessary element in methods of object of _CgridAdminView_.
In what error? | Looks like you are not declaring `CgridAdminView` inside a dom ready handler
$(function () {
var CgridAdminView = {
controller_name: 'work',
div_table_id: 'grid-admin-works',
tr_add: $('#' + this.div_table_id).find('tr').eq(1),
disabled: '.td_workGroup',
list_cols: [
'index',
'shortName',
'fullName',
'codeName',
'workGroup_id',
'period',
'performers']
};
CgridAdminView.tr_add.hide();
})
Because the `tr_add` properties value is assigned when `CgridAdminView` is created, so when the object is create if the target element is not loaded then the evaluation of `$('#' + this.div_table_id).find('tr').eq(1)` will not return any result.
The main point is the jQuery selector need to happen in dom ready | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, properties, ready"
} |
Converting Upper Case to Lower Case using pointers in C
I've been trying to change upper case letters to lower case letter using pointers but I keep getting segmentation faults. Here is my source code:
#include <stdlib.h>
#include <string.h>
char *changeL(char *s);
char *changeL(char *s)
{
char *upper = s;
for (int i = 0; upper[i] != '\0'; i++)
{
if (upper[i] >= 'A' && upper[i] <= 'Z')
{
upper[i] += 32;
}
}
printf("%s\n", upper);
return upper;
}
int main()
{
char *first;
char *second;
first = "HELLO My Name is LoL";
printf("%s\n", first);
second = changeL(first);
printf("There is no error here\n\n");
printf("%s\n", second);
return 0;
}
Using gdb I found the seg fault to be in "upper[i] += 32;". I don't understand why the seg fault is there. | "HELLO My Name is LoL" is the constant memory. You can`t change it. However you pass pointer to this memory(first) to a function which tries to change it. Thus you got segmentation fault. You should copy this string to memory butffer. Like
char buffer[] = "HELLO My Name is LoL";
and then pass buffer to changeL | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c, pointers"
} |
what is the difference between linq to sql class and entity framework
> **Possible Duplicate:**
> Entity Framework vs LINQ to SQL
what is the difference between linq to sql class and entity framework and what kind of situation linq to sql should use and when entity framework will be the best option. | Check out this link for a quick comparison. For me linq to sql is a quicker way to get a small application up and running and the entity framework is more for large more complex applications that you can take time to build a big foundation for. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "linq to sql, entity framework"
} |
How to iterate two files with different steps without loading them all in memory using python?
Let's say I have two files A and B
in A I have 100 lines, in B I have 10 lines, I need to do an operation on every 10 lines in A and every 1 line in B.
for example in A, I have following lines a1 a2 ... a10 a11 .. a20 ... a100
in B I have following lines: b1 b2 ... b10
I would like to do an operation on data a1,a2..a10 and b1, and I would like to do the operation again on data a11, a12... a20 and b2.
So the problem is both A and B are very huge, I cannot load them all in memory, so I need to iterate them line by line, but with different speed because 10 lines in A map to 1 line in B. How to do that without preprocessing A to make it with same row size with B?
(I use python 2.7) | There's a common idiom to iterate over "chunks" using `itertools.izip` and an unpacked list of references to a single iterator:
from itertools import izip
for values in izip(*[iter]*n): # values will hold n values at a time
For your purpose, you can add a reference to your smaller file along with multiple references to the larger file (files are iterators):
with open("A") as file_a, open("B") as file_b:
for values in izip(file_b, *[file_a]*10): # values will have one B value and 10 A values
# do stuff here with the values
If the files might not line up exactly, you can use `itertools.izip_longest` instead of the regular `izip`. It will let you supply a default value to use if the inputs don't match up exactly right. In Python 3, the regular builtin `zip` works like `itertools.izip` does in Python 2, so you wouldn't need to import anything. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, algorithm"
} |
Getting django error even after deleting mistake line
i've been trying djano project that include channels & redis. recently i recreated venv and i get following even after deleting mistaken line. is there a way to clear cache in django project and runserver again?
''' line 52, in message to = models.ForeignKey(to='user',on_delete='',related_name = 'to') File "/home//python-projects/DjangoChannels/.env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in **init** raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable.''' | i've just reinstalled python from source and problem was gone! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, django, redis, django channels"
} |
Where can I find Delphi´s component editor for TPopupMenu and TMenuItem?
I need to write custom component editors for Delphi's TPopupMenu and TMenuItem descendent controls.
Finding the native editors will make my work a lot easier, but after inspecting the folder "\source\Property Editors", I was unable to find files that seems to be the right ones for them.
Any help will be much appreciate. | > Where can I find Delphi's component editor for `TPopupMenu` and `TMenuItem`?
You can't. The source code for these component editors is not published. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "delphi, components"
} |
Facebox + Blueprintcss looks great in Firefox, falls apart in IE 7
Not sure how to fix this or where to look in resolving how Facebook content that has been laid-out using Blueprintcss looks so poorly spaced in IE7.
Is there any guidance on this? | Did you include your ie.css file?
Did you add the following line at the top of the page to ensure that FBML renders properly in IE.
<html xmlns=" xmlns:fb=" | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "internet explorer, facebox"
} |
Make a list into list of list in certain order using python
I have list
my_list= [33,29,33,87,83,138,141,145,191,191,191]
Now i have another list
split_list = [2,4,7]
Now I need to separate my_list values by using the values in split_list as my position value of my_list,
in this link they have grouped the list in with 4 elements in each list using scala, like wise i want to use the number in split_list as grouping factor
like this
answer_list = [(33,29,33),(87,83),(138,141,145),(191,191,191)] | You can do this with a list comprehension by slightly adjusting the `split_list`:
>>> my_list= [33,29,33,87,83,138,141,145,191,191,191]
>>> split_list = [2,4,7]
>>> split_list = [-1] + split_list + [len(my_list)]
>>> [tuple(my_list[split_list[i]+1:split_list[i+1]+1]) for i in range(len(split_list)-1)]
[(33, 29, 33), (87, 83), (138, 141, 145), (191, 191, 191)]
If the indices were instead the index of the item _before which_ the slice occurred, you could have slightly nicer code:
>>> my_list= [33,29,33,87,83,138,141,145,191,191,191]
>>> split_list = [2,4,7]
>>> split_list = [i + 1 for i in split_list] # To change the list to [3,5,8]
>>> split_list = [None] + split_list + [None]
>>> [tuple(my_list[split_list[i]:split_list[i+1]]) for i in range(len(split_list)-1)]
[(33, 29, 33), (87, 83), (138, 141, 145), (191, 191, 191)] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -4,
"tags": "python, sorting"
} |
-[NSResponder showContextHelp:] example
I'm curious with the method -showContextHelp: in NSResponder.
The documentation states:
> Implemented by subclasses to invoke the help system, displaying information relevant to the receiver and its current state.
How and when is this method called? Can't seem to find anymore information on it. | `-showContextHelp:` and related methods on `NSResponder` are no longer relevant because they were used to respond to Help key events on older Apple keyboards. The Help key no longer exists on any of Apple's keyboards as of 2007.
However, if you're still interested in understanding its purpose, Peter Hosey wrote a great article on `NSResponder`'s help related functionality. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "cocoa, nsresponder"
} |
Why does the BackgroundWorker's ProgressChanged event work without calling RunWorkerAsync?
I have a question regarding the `BackgroundWorker`. I can call the `ProgressChanged` event without having started the thread with `RunWorkerAsync`.
I don't understand why this works. How can it notify the original thread if the new thread didn't even start yet?
This seems to work regardless, since it updates the GUI without a problem, which wasn't like this before I implemented the `BackgroundWorker`. | Calling `ReportProgressChanged()` will always raise the `ProgressChanged` event regardless of which thread it was called from.
Inside the inplementation of `ReportProgressChanged()` is a mechanism which raises the event on the UI thread if it wasn't called from the UI thread. If `ReportProgressChanged()` _is_ being called from the UI thread, then it just raises the event without needing to do that extra marshalling. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "c#, winforms, backgroundworker"
} |
Possible NullReferenceException ReSharper code analysis C#
ReSharper code analysis tells me that in following code snippet
if (users.Select(a => a.id).Contains(user_id))
{
return users.FirstOrDefault(a => a.id == user_id).type == 2;
}
the line `return users.FirstOrDefault(a => a.id == user_id).type` might result in a possible `System.NullReferenceException`. Is this true given that I already check whether this specific `user_id` exists in the `users` container?
class users
{
int id {get; set;}
int other_stuff {get; set;}
} | > Is this true given that I already check whether this specific `user_id` exists in the `users` container?
Yes, this is warning is correct, because `users` may be changed concurrently between the call to `Contains` and the call to `FirstOrDefault`. ReSharper's logic analyzer does not assume exclusive access to the container, so issuing a warning is the right behavior.
You can fix this warning with a null-conditional operator:
var optType = users.FirstOrDefault(a => a.id == user_id)?.type;
if (optType.HasValue) {
return optType == 2;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, resharper"
} |
What geological properties of the earth could we deduce by measuring magnetic field strength and direction?
I wonder if it is of any use for a geophysicist, if we measure the magnetic field strength and direction of the earth. Could we make valid statements about the composition of the the earth, earth crust or core? What if we detect detect variations from the expected field strength, could that help us to draw a conclusion on the underlying local composition the earth?
I only know about one direct use for the magnetic field direction of the earth. Are there more use cases? | Magnetic surveys are used for prospecting for oil or minerals.
On top of the earth's magnetic field there are small contributions form magnetic materials in the surface rocks, especially granites.
You can use this to either find large bodies of volcanic rock that migth have minerals or diamonds - or alternatively you can find large volumes with no magnetic field which might be oil or gas reservoirs.
The tricky part is that the local fields are only a fraction of a percent of the overall Earth's field and the Earth's field varies by much than this - so there is a complex mapping process to take out the natural background. | stackexchange-physics | {
"answer_score": 3,
"question_score": 1,
"tags": "experimental physics, geophysics, magnetic fields, geomagnetism"
} |
No effect when changing BEAMER_THEME
I don't get any effect if I put the following line at the start of my Org-mode file:
#+BEAMER_THEME: metropolis
Indeed, whatever theme name I write after `#+BEAMER_THEME:`, there's not mention of it in the resulting `.tex` file, and I always get the default theme.
I'm using Org mode 9.5 and Emacs 27.2. Am I missing something here? What's the correct way to change the Beamer theme?
EDIT: I'm using Doom Emacs v2.0.9 | `beamer` export is _different_ from `latex` export: for `latex`, you say `C-c C-e l l` (or similar - this produces a TeX file but does not process it to PDF); for `beamer`, you say `C-c C-e l b` (again this produces a TeX file but does not process it - there are other options specific to `beamer` export for processing to PDF).
If you don't have these entries in the menu, then `beamer` export is not enabled. To enable it, go to the `*scratch*` buffer and type `(require 'ox-beamer)` followed by `C-j`: that enables it for this session. To enable it permanently, add `(require 'ox-beamer)` to your init file (I'd add it towards the end, after the rest of Org mode initialization, but that's probably not necessary). | stackexchange-emacs | {
"answer_score": 1,
"question_score": 2,
"tags": "org mode, beamer"
} |
Why System.Decimal inheritance hierarchy
I was under the impression that **all** value types inherit from System.ValueType, and because I know that Decimal is a **struct** which is also a value type it goes to say that Decimal hence _must be a value type_. So why does resharper show the type hierarchy as such:
!enter image description here
or am I misunderstanding something here? | If I show (in ReSharper 5.1) _Decimal_ in another view mode ( _Supertypes Hierarchy_ ) I see that:
!enter image description here
So all is as you would expect. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, resharper"
} |
How to check if $e^{-2t}cos(2 \pi t)$ is periodic/non-periodic?
So by graphing the function it is clearly non-periodic, but I would like to know how to solve it in a more mathematical way. Is there is a way to expand this function somehow that I forget? | The function has the value $1$ at $0$ and it approaches $0$ as $ t \to \infty$. So it cannot be periodic.
If it has period $p$ then $f(np)=f(0)=1$ for all $n$ so $f(np)$ does not tend to $0$. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "exponential function, periodic functions, almost periodic functions"
} |
Modifying JSON Key Value Pairs In Nifi
I have incoming JSON rows of data like,
{"signalName": "IU_BATT_ParkAssist", "msgId": 2268, "epoch": 1582322746, "usec": 376360, "vlan": "-1", "msgName": "EBS_Frame12", "vin": "000004", "value": 14.171869, "timestamp": 1582322746376}
I want the output to be modified to produce,
{"IU_BATT_ParkAssist":14.171869, "msgId": 2268, "epoch": 1582322746, "usec": 376360, "vlan": "-1", "msgName": "EBS_Frame12", "vin": "000004", "timestamp": 1582322746376}
The signalName and value keys were combined to make one new **key:value pair** with the key being the signalName and the value being the value field, **"IU_BATT_ParkAssist":14.171869** along with the other original key, value pairs.
How can I achieve this in Nifi given that the signalName field will be dynamically changing in each row? | **`Try with below spec:`**
[
{
"operation": "shift",
"spec": {
"@(1,value)": "@(2,signalName)",
"*": "&"
}
},
{
"operation": "remove",
"spec": {
"signalName": "",
"value": ""
}
}
]
In **shift** operation we are combining **`signalName and value`**.
In **remove** operation we are removing **`signalName and value`** from our `json` data.
**`Output:`**
{
"IU_BATT_ParkAssist" : 14.171869,
"msgId" : 2268,
"epoch" : 1582322746,
"usec" : 376360,
"vlan" : "-1",
"msgName" : "EBS_Frame12",
"vin" : "000004",
"timestamp" : 1582322746376
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "apache nifi, jolt"
} |
Why is my old logo still showing after I updated the logo?
I am using Magento Go and I had my logo set but when I set an updated version of it, I am still seeing the old version on the front-end. **Why is this?** It appears that I cannot flush the cache in Magento Go, and I have already cleared my browser's cache. I have also tried renaming the file and re uploading it but this didn't work either. It appears to be loading from the CDN.
Response Headers:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: image/png
Date: Wed, 09 Oct 2013 12:41:15 GMT
Last-Modified: Tue, 10 Sep 2013 15:55:08 GMT
Server: ECS (jfk/5F35)
X-Cache: HIT
X-Server: w81
Content-Length: 2300 | I ended up reuploading my logo a third time. It finally worked. I have no idea why it didn't work the first two times. Thanks for everyone's input. | stackexchange-magento | {
"answer_score": -1,
"question_score": 0,
"tags": "cache, image, magento go"
} |
How do I set TargetConnectionString of SSDT Publish profile from AppConfig
We have recently moved to `SSDT publish profiles`, we have couple of sql servers to which our app can connect.
Also, we have a SSDT Publish Profile for each server, thereby having a lot of .publish.xml files.
Our app.config which contains SQLConnectionString is placed in startup project. Can I have my SSDT Publish profiles in a way, where I have only one profile and that read target connection string from app.config ?
Please let me know if any clarification is needed thanks. | The way I give myself the most flexibility is to avoid using the publish and instead I have a set of powershell scripts which call sqlpackage.exe
You can then do whatever you like in powershell such as opening the app.config file for your app and getting the connection string.
The only downside is that you don't get F5 publishing any more but in reality I haven't missed it.
The overall process then becomes, build solution, run powershell (can be done from the immediate vs window or a seperate powershell win) and then so whatever I want to do.
ed | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": ".net, sql server, connection string, sql server data tools, publish profiles"
} |
Detect When User Resizes Div With CSS resize: both
I know I can use `ResizeObserver` to detect when a div's size changes, but I would like to only know when the user resizes the div with the CSS property `resize: both`, and not when the page gets resized.
// Detect when user resizes element with the property resize: both;
div {
resize: both;
overflow: auto;
border: 1px solid;
}
<div>
Hi!
</div> | You can use `MutationObserver` for this. Source here.
let observer = new MutationObserver(function(mutations) {
console.log('Resized');
});
let child = document.querySelector('div');
observer.observe(child, { attributes: true });
div {
resize: both;
overflow: auto;
border: 1px solid;
width: 200px;
height: 200px;
}
<div>
Hi!
</div> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "javascript, html, css"
} |
Getting both columns to wrap around a table
I'm trying to make a table around which text in both columns will wrap. I've looked around and `wraptable` from `wrapfig` has been suggested, but it seems to just make things worse.
\documentclass[twocolumn]{article}
\usepackage{blindtext} %for lorem ipsum
\usepackage{wrapfig}
\begin{document}
\blindtext[1]
\begin{wraptable}{l}{10cm}
\begin{tabular}{lp{8cm}}
X & Y \\
\hline \\[-2mm]
AAAA & \Blindtext[1][1] \\
CCCC & x
\end{tabular}
\end{wraptable}
\blindtext[3]
\end{document}
!enter image description here | `twocoulmn` is somewhat rigid. If you want wide tables spanning both the columns, you may use `table*`. But it can't be put in the first page of the document. In other pages you can place them on top or bottom. If needed, you may use `placeins` package and its `FloatBarrier` to restrict the placement. There is also `float` package with similar functionality (`[H]` instead of `[htb]`. Or you may issue a `\clearpage` by yourself.
\documentclass[twocolumn]{article}
\usepackage{lipsum} %for lorem ipsum
\usepackage{placeins} % provides \FloatBarrier
\begin{document}
\lipsum[1-20]
\begin{table*}[t]
\centering
\begin{tabular}{lp{8cm}}
X & Y \\
\hline \\[-2mm]
AAAA & \lipsum[1] \\
CCCC & x
\end{tabular}
\end{table*}
%\FloatBarrier To force the table here if needed.
\lipsum
\end{document} | stackexchange-tex | {
"answer_score": 3,
"question_score": 0,
"tags": "tables, wrap"
} |
Hiding a Categories content on just the Homepage 'Posts'?
Is there a way I can hide a certain categories content from just the homepage Posts section of my Wordpress Site? So, those posts are still posted and live; just not visible nor accessible from the homepage posts area. I'm calling the category twice on the homepage; once in the header within a plugin I'm using, and the other where the posts are created by default by Wordpress. How can I hide my 'featured' category in the main page content of recent posts on the homepage? | Okay, it sounds like you'll want to modify the primary Loop using `query_posts()`, but only on the **Site Front Page**.
I don't think TwentyTen includes a `front-page.php` template file, so we'll modify `index.php` directly. Add the following code to `index.php`, anywhere _before the Loop output_ :
<?php
// Determine if we're on the site Front Page
if ( is_front_page() ) {
// Globalize $wp_query
global $wp_query;
// Create argument array in which we
// exclude desired category IDs. Categories
// are listed as a comma-separated string.
// e.g. '-3', or '-1,-2,-3'
$exclude_cats = array( 'cat' => '-3' );
// Merge custom arguments with default query args array
$custom_query_args = array_merge( $wp_query->query, $exclude_cats );
// Query posts using our modified argument array
query_posts( $custom_query_args );
} // is_front_page()
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
Why does my Jose4j JSON Web Key cause this InvalidKeyException?
I am using Jose4j to perform the encryption of a JSON Web Token in Java.
I create a key as a String in JSON format to pass to the `JsonWebKey.Factory.newJwk` method, thus:
String jwkJson = "{\"kty\":\"oct\",\"k\":\"5uP3r53cR37k3yPW\"}";
I pass it to the factory and get a `JsonWebKey (jwk)` back. Then pass the key (from the `jwk.getKey()` method) in to the JsonWebEncryption's `setKey()` method. I set the `AlgorithmHeaderValue` and the `EncryptionMethodHeaderParameter`...
Then, when I call `jwe.getCompactSerialization()` it throws the following exception
org.jose4j.lang.InvalidKeyException:
Invalid key for JWE A128KW, expected a 128 bit key but a 96 bit key was provided.
I passed in 16 bytes, so why does this evaluate to 96 bits insted of 128?? | You need to base64 encode the key string before adding it to the JSON object `jwkJson`.
E.G.
String pass = "5uP3r53cR37k3yPW";
String jwkJson = "{\"kty\":\"oct\",\"k\":\""+ Base64Url.encodeUtf8ByteRepresentation(pass) +"\"}";
In the factory method of JsonWebKey, after it has retrieved the key (k) value from the JSON object, it base64 decodes it. This has the effect (if you have not encoded it first) of reducing the number of characters that the bit pattern represents by 3.
As to why this occurs, I am a little confused. I would assume that if you took a binary string that describes a string of characters using an 8 bit representation (UTF-8, the native charset in Java), that re-interpreting that binary string as characters using a 6 bit representation (base64), would yield a longer string! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, json, encryption, jwt, jose4j"
} |
Unit Tests on Single DB
My rig has a CMS & Civi combined database. This was to make life easier through drush sql-sync from @prod to @dev.
However, @dev is a vagrant box, with two databases, one for CMS, one for Civi.
When I run unit tests, instead of it cloning from the CMS database it clones from the old civi one.
My question is, how can I get it to clone from the CMS database? I've changed settings in the local test file and the civicrm.settings.php file. | Looks like the new, fledgling, e2e tests are my answer... | stackexchange-civicrm | {
"answer_score": 0,
"question_score": 1,
"tags": "developer, phpunit"
} |
PostgreSQL high disk usage
I have a PostgreSQL database on a docker container with 50MB of data:
SELECT pg_size_pretty(pg_database_size('db_1'));
pg_size_pretty
------------------
50 MB
but the volume size is 8.5GB :
sudo du -hd1 db_volume
8.5G db_volume
and my docker-compose is like this:
version: '3.8'
services:
r3-db:
image: postgres:12
restart: always
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: PASSWORD
POSTGRES_USER: USER
POSTGRES_DB: db_1
volumes:
- ./db_volume/:/var/lib/postgresql/data:Z
I try using `VACUUM(FULL, ANALYZE, VERBOSE)` on any table but the file size of the database doesn't change!
The volume contains many files named `core.NUMBER` with size of 145MB,
 to Unix line endings (LF).
So if you use Notepad to edit the file it will have Windows line endings. So dos2unix should be used on your computer (for that file) before sending it by FTP (or executing it on the host if you have ssh access and they have dos2unix).
But if you already use an editor which supports converting to Unix line endings, like UltraEdit or Notepad++ then all you need is to do a "convert to Unix" before saving the file. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "shell, ssh, command, putty, fileinfo"
} |
select selected option by value with jquery
in order to set the selected option by value for a html select with jquery i do this as follows:
$('#mySelectId option[value="avancement d\'échelon"]').attr("selected","selected");
is the problem because my string value contains `'` ? | Use
$('#mySelectId option[value="avancement d\'échelon"]').attr("selected", true);
instead.
Also to remove the selected attribute use
$('#mySelectId option[value="avancement d\'échelon"]').attr("selected", false); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, select, selectedvalue"
} |
removable(draggable) and replaceable DIV
I want to create some `<div>`s. I want to be able to move and replace these Divs. I think I can use jQuery, and I found this :
<script>
$(function() {
$( "#draggable" ).draggable();
});
</script>
but this is not exactly what I want.
i want some code like this : varzesh3 | As per your given example site < , you can use the jquery ui portlets below is the link hope it will help for you.
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, jquery ui, html, draggable, movable"
} |
Making git auto-commit
I'd like to use git to record all the changes to a file.
Is there a way I can turn git 'commit' on to automatically happen every time a file is updated - so there is a new commit for every change to a file?
Ideally I'd like my users to not even know that git is running behind the scenes. A user could then potentially "undo" changes to a file - and this could be achieved by pulling a previous version out of git. | On Linux you could use **inotifywait** to automatically execute a command every time a file's content is changed.
Edit: the following command commits file.txt as soon as it is saved:
inotifywait -q -m -e CLOSE_WRITE --format="git commit -m 'autocommit on change' %w" file.txt | sh | stackexchange-stackoverflow | {
"answer_score": 138,
"question_score": 174,
"tags": "git"
} |
Is it possible to avoid pipes when reading from mysql in bash
I have sth like this :
mysql --user=$db_user --password=$db_pwd -e"$expQ" | while read name; do
if [ $name != 'name' ];then
COUNTER=$(($COUNTER + 1))
fi
done
I want to update global counter , but when I executed next query the `COUNTER` does not pick the previous value bcz of the "|" (pipe) .
How I can change the above code to work with named pipes or any other alternative . Here is reference but I am new to bash and unable to understand if that is possible with mysql My bash version says:
`GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0) Copyright (C) 2007 Free Software Foundation, Inc. ` | Use Process Substitution instead, as shown below:
COUNTER=0
while read -r name
do
if [[ $name != "name" ]]
then
((COUNTER++))
fi
done < <(mysql --user="$db_user" --password="$db_pwd" -e"$expQ") | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "bash"
} |
Invalidating an HTML5 cache (manifest) completely?
I have an iPhone web-app, and I want to know how to force a cache refresh.
My cache manifest is this:
CACHE MANIFEST
index.html
file1.css
file1.js
`index.html` is the meat of the application, so I put that in the cache. At this point, I seem to be boned, as I can't figure out how to get iPhone to invalidate the cache. Even going to `Settings > Safari > Clear Cache` doesn't work, although I'd like to be able to control this programatically. Removing `index.html` from the manifest and re-adding it seems to work, but I would have to know that all my clients had a clean hit of the updated manifest.
How do I cache `index.html` and still have it updated when it changes? | Off the top of my head, any change to the manifest will do the trick - and manifests can contain comments starting with #. Just add a random comment and it'll work.
It's a useful property, when I worked on an HTML5 application in a git repository I used to have the manifest automatically regenerated with a comment containing the HEAD hash after each commit so that the changes always propagate to the users. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "iphone, html, caching, manifest, local storage"
} |
Does Google Cloud Spanner support default column values?
Having the capability to compute a UTC timestamp as the default value for a column is a handy feature of most popular database solutions. Does Google Cloud Spanner support this? If not, is this a possible roadmap item? | Cloud Spanner doesn't actually allow any default value to be specified regardless of type. This means the implicit default is Null, or Error, depending on whether to column was specified with `NOT NULL`
Cloud Spanner internally stores a 'timestamp' of when a row was committed, but it doesn't expose this directly. It also doesn't behave like a default value (set once), so unfortunately the answer to your question is currently no.
Definitely something for the team to consider. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "database, google cloud platform, database schema, google cloud spanner"
} |
Why word "because" used at starting of the sentence?
Two Guys questioning the innocent guy for destroyed vehicle. Michael is separate guy who responsible for car wreck here.
> Guy A: How're you doing?
>
> Innocent Guy: Don't fool with me. Not in the mood.
>
> Guy B: You wrecked my car.
>
> Innocent Guy: No, Michael did. Why don't you go see him? That'd be a matchup.
>
> Guy A: **Because** we want you. | What are you expecting as an answer to your question? "Because" is the usual answer to a "why" question. This is similar to other languages. For example, in Spanish (as far as I know), "por qué" starts a "why" question, and "porque" starts a "because" answer.
Now, maybe you know that "because" answers "why". However, you also noticed that "Because we want you" is not a complete sentence, and that is the real intent of your question. Or maybe it isn't. I'll answer that question too, anyway. The complete sentence that means the same thing as "Because we want you" is "I didn't go see him because we want you." The because is still there, it is just a complete sentence now. In informal (usually spoken) English, people don't try to follow rules as much as they try to make sense, and that makes complete sense: "Why x?" -> "Because y." | stackexchange-ell | {
"answer_score": 1,
"question_score": 0,
"tags": "meaning in context"
} |
parsing C code using python
I have a huge C file (~100k lines) which I need to be able to parse. Mainly I need to be able to get details about individual fields of every structure (like field name and type for every field in the structure) from its definition. Is there a good(open source, which i can use in my code) way to do this already? Or should I write my own parser for this. If I have to write my own, can anyone suggest a good place to start? I have never worked with python before.
Thanks | Take a look at this link for an extensive list of parsing tools available for Python. Specifically, for parsing c code, try the pycparser | stackexchange-stackoverflow | {
"answer_score": 23,
"question_score": 19,
"tags": "python, parsing"
} |
Characteristic Function as projection operator
Let $(X, \mu)$ be a measure space and denote $\chi_E$ by the characteristic function of a measurable set E. Then the operator $Q_E f=\chi_E f$ defined in $L^2 (X, \mu)$ is a projection. Under what condition on $E$,$F$ is $Q_E+Q_F$ a projection?
I don't really understand what I need to do in order to show that an operator is a projection? If someone could provide a proof I this will help out immensely. | Hints:
* $P = Q_E + Q_F$ is a projection if $P^2 = P$.
* If $A \cap B = \emptyset$, then $Q_A Q_B = Q_B Q_A = 0$.
* You can write $P = Q_{E \backslash F} + 2Q_{F\cap E} + Q_{F \backslash E}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "functional analysis"
} |
How avoid error on not evaluated code C++?
Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?
class A {
//..implementation
int id() { return 1; }
};
class B {
//..implementation
int id() { return 2; }
bool hasSmth() { return true; }
};
int main()
{
auto obj = someFunction();//returns A or B
if (obj.id() == 1 || (obj.id() == 2 && obj.hasSmth())) {
...
}
}
If the function returns obj of type B, then we are good.
But if it returns obj of type A, compiler will complain about A not having hasSmth, regardless of that part of if never been evaluated.
Can someone give a workaround please? | > Can someone give a workaround please?
Read the declaration of `someFunction` to see what it returns. In the case it doesn't return `B`, then don't write `obj.hasSmth()`. Problem solved.
Now, let's change the question a bit. Let's say that you want to make this work without knowing the return type. Perhaps because rather than `main` you may be actually writing a template that works with different types. There are several approaches, but function overloads are a simple one:
bool check([[maybe_unused]] const A&) {
return true;
}
bool check(const B& b) {
return b.hasSmth();
}
template<bool returnsA>
void foo() {
auto obj = someTemplate<returnsA>(); // returns A or B
if (check(obj)) { | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, c++11, expression evaluation"
} |
My Makefile just doesnt work.
I have a makefile which is just not working. Can you guys help me to find where the error is? Thanks!
CC = gcc
FILES = workfile.c insert.c
TARGETS = exe
CFLAGS = -o
DBUG =
RM = rm -f
OBJS = *.o
#Master Rule
all: $(TARGETS)
#Build
exe: workfile.o insert.o
$(CC) $(CFLAGS) $(DBUG) workfile.o insert.o exe
#workfile
workfile.o: workfile.c
$(CC) $(DBUG) -c *.c
insert.o: insert.c
$(CC) $(DBUG) -c *.c
clean:
$(RM) $(TARGETS) $(OBJS)
The error is as follows
$make all
gcc -c *.c
gcc -o workfile.o insert.o exe
gcc: error: exe: No such file or directory
make: *** [exe] Error 1
I even tried changing the names of the targets. But did not help. Could not continue further. | I don't think it is a good idea to put `-o` in `CFLAGS`, I would rather to remove `-o` from it.
`CFLAGS = -o` -> `CFLAGS =`
Now you can work on your `exe`, the output path should follow `-o` immediately.
exe: workfile.o insert.o
$(CC) $(CFLAGS) $(DBUG) workfile.o insert.o exe
=>
exe: workfile.o insert.o
$(CC) $(CFLAGS) $(DBUG) -o exe workfile.o insert.o
So the full makefile should look like:
CC = gcc
FILES = workfile.c insert.c
TARGETS = exe
CFLAGS =
DBUG =
RM = rm -f
OBJS = *.o
#Master Rule
all: $(TARGETS)
#Build
exe: workfile.o insert.o
$(CC) $(CFLAGS) $(DBUG) -o exe workfile.o insert.o
#workfile
workfile.o: workfile.c
$(CC) $(DBUG) -o workfile.o -c workfile.c
insert.o: insert.c
$(CC) $(DBUG) -o insert.o -c insert.c
clean:
$(RM) $(TARGETS) $(OBJS) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "makefile"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.