INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Priority of vector operators
What is the precedence order for cross product, dot product and scalar multiplication?
$$x \overrightarrow {A}\cdot \overrightarrow {B} \times \overrightarrow {C} =\quad?$$
|
First note that the cross product is an operation between two vector that gives a vector as result and the dot product is an operation between two vectors that gives a scalar as result. So the mixed product $$ A\cdot B \times C $$ has a sense only in the oreder $A\cdot(B\times C)$ and has a scalar as a result.
For the scalar product by a real number $x$ we know that both the dot and cross product are compatible with scalar multiplication, this means that: $$ x(A\cdot B)= (xA)\cdot B = A \cdot (xB) $$ and
$$ x(A\times B)= (xA)\times B = A \times (xB) $$ so in the expression $ xA\cdot B\times C$ we can perform the scalar multiplication when we want ( but only one time for one vector) but we have to calculate the cross product before the dot product.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 5,
"tags": "vectors, arithmetic"
}
|
Why does JavaScript console.log of objects sometimes show prototype/constructor pattern forever
I've always noticed this, but never actually understood what's happening here. I have a fairly simple object that I've put in a `console.log`. It has a seemingly never ending pattern of prototype -> constructor -> prototype -> etc. What exactly is it's purpose?
, and the logger isn't smart enough to realize it will never finish if it naively follows all references.
|
stackexchange-softwareengineering
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript, prototyping, constructors"
}
|
Find Mac OSX version installed using AppleScript
How can I find which version of OSX is installed on my Mac by using AppleScript? I want to install an app programatically and run different pkg files based on the version.
Thanks
|
I'm not on a Mac, so there may be a better way to do this, but the first approach that comes to mind is just executing a shell command to query the OS version.
<
<
Based on these references, you probably want to do something like:
set os_version to do shell script "sw_vers -productVersion"
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 10,
"tags": "macos, applescript"
}
|
Criteria Builder Convert Lower
I have the following Predicate condition
predicate =
cb.like(root.get(Product_.prodName),prod.getProductName());
How to use lower in the above starement, I have tried as
predicate =
cb.like(cb.lower(root.get(Product_.prodName), prod.getProdName());
However it gives me the following error
method lower(javax.persistence.criteria.Path<java.lang.String>,
java.lang.String) not found in interface
javax.persistence.criteria.CriteriaBuilder
What is the correct way to convert to lower?
|
Change the code to
predicate =
criteriaBuilder.like(criteriaBuilder.lower(root.get(Product_.prodName)),
wrapper.getProdName());
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, jpa, eclipselink, criteria api"
}
|
Does estimated fixed effects change if we change reference level?
Consider a fixed effect model $$y_{it}=x_{it}'\beta+\alpha_{i}+\epsilon_{it}$$ To estimate the fixed effects $\alpha_i$ we can add a dummy for each individual and run the least-squares dummy variables regression. We will need to omit one individual dummy because of co-linearity. For the estimates of other $\alpha_i$, they are the estimated individual fixed effects. (Hope I am correct so far)
My question:
1. What about the fixed effect of the individual we omitted when estimating the regression? Is that zero?
2. Should I interpret the fixed effects of other individuals as relative values to the omitted individual?
3. If we change the reference level (omit different individuals when estimating the coefficients), will the result (estimated fixed effects and other coefficients) change? If so, how should we choose the reference level?
|
You can force Stata to exclude an intercept with
* using ibn. prefix for the id variable (no base level)
* using noconstant option
This means that everyone gets their own FEs and no one is dropped. If you had other categorical variable in your model, this becomes impossible.
The alternative is that the omitted individual gets the intercept as his FE, and everyone else gets the intercept plus their own FE. This is what Stata will do by default.
It does not matter whom you drop. The dummy variable coefficients will change, but not the actual value of the FE. The other coefficients should stay the same.
The FEs are unbiased, but they are inconsistent, so don't take them too seriously at unit level. Their sample average, however, is a consistent estimator of the mean of the population distribution of heterogeneity. If you want to do a regression with the estimated FEs as the outcome, you can think of that regression as calculating a conditional mean, which may be OK.
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 2,
"tags": "econometrics, fixed effects model, identifiability"
}
|
Tempo and Rhythm
If an eighth note is half the duration of a quarter note, would the duration of an eighth note played at 60bpm be equal to the duration of a quarter note at 120bpm? If yes, why was the concept of different notes, like half, quarter, eighth, formed?
Wouldn't it be easier to have just one base/reference note and vary the tempo of the song whenever necessary?
Because if the first para is true, then having an 8th/16th note would be the same as changing the tempo of a quarter note to make it twice or 4 times as fast
|
I'm sure other reasons exist, but to give you a quick answer, I'll extract it right from your question:
> If yes, why was the concept of **different notes** , like half, quarter, eighth, formed?
>
> Wouldn't it be easier to have just one base/reference note and vary **the tempo of the song** whenever necessary?
The notation system sets a particular duration per note, tempo is per song. Try to apply your idea to something like this (i.e. different notes played at the same time)
!Imgur
It won't work.
|
stackexchange-music
|
{
"answer_score": 4,
"question_score": 3,
"tags": "theory"
}
|
Outlook app shows notifications but corresponding emails are MIA
I've been using the Outlook app on my Android for years. This just started happening a few weeks ago. I often will get emails and see the notifications but when I open the app, they're not there. Sometimes it takes hours until the new emails are visible in the app. So as soon as I dismiss the notification either by swiping it away or by opening the app, I have no hint as to what my new emails are about. At the same time, I know those emails are in my inbox both because I read the notification as well as being able to read them in a browser or Windows app. I've already tried using the app's "reset account" which does nothing to help this. Please advise. Thank you!
_Outlook app version 4.2247.1
Samsung Galaxy S9
Phone model number SM-G960U1
Android version 10
One UI version 2.5_
|
First, I went into the phone's app settings and hit "clear **cache** " for Outlook. It only helped for about an hour.
Then, in the same location, I chose "clear **data** " for the app. It _seems_ to have solved the problem for now. (Warning: doing so will remove your email account from the app. You'll need to re-add it.) We shall see...
|
stackexchange-android
|
{
"answer_score": 0,
"question_score": 2,
"tags": "notification bar, outlook"
}
|
How to interpret variable declarations with right to left rule while typedef is included?
I am having trouble when using right to left rule to interpret variable declarations when typedef is involved.
In the C++ primer 5th edition book I saw the following code:
typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char
const pstring *ps; // ps is a pointer to a constant pointer to char
If I replace the pstring with char * then it stands like this:
`const char *cstr`
So I expect cstr to be a pointer to a const char. But the comments in the book states the pointer itself is constant. My question is what's wrong with my way of thinking.
|
A `typedef` is not a macro. You don't just text replace it.
Read it as `cstr` is a "constant `pstring`", which is a "constant (pointer to char)". Compare this to `const char*`, which is "pointer to constant `char`".
If you were to replace the typedef it would look like this:
char* const cstr = 0;
char* const* ps;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, c, typedef"
}
|
GCDWebServer always aborts on options check
I started using GCDWebServer version 3.1 in an app last year, and this line in the `addHandlerWithMatchBlock` method of `GCDWebServer.m` always caused the system to abort immediately:
GWS_DCHECK(_options == nil);
I ended up just changing it to this to avoid the problem:
GWS_DCHECK(_options != nil);
Now I'm updating to the latest version 3.3.2 and see the same problem. My hack still works here, but I would like to know what a real solution would be. Can someone explain?
|
See docs in header:
> Addling handlers while the server is running is not allowed.
Attempting to do this will result in undefined behavior.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, gcdwebserver"
}
|
Keyboard shortcut for Spotlight doesn't work in full screen Google Chrome on Mac OS X 10.7 (Lion)
I've noticed that the Spotlight Search keyboard shortcut (cmd space) doesn't work if I'm running Google Chrome (12.0.742.122) as full screen application in Lion.
Is this a Chrome-related bug or is this inherent of some type of applications? Is there a way to fix it?
|
Problem seems to be resolved in newer Chrome versions.
|
stackexchange-apple
|
{
"answer_score": 1,
"question_score": 0,
"tags": "macos, keyboard, spotlight, google chrome, fullscreen"
}
|
Is there a more rational way to replace all slashes using javascript than this?
var input = '/string/';
var output = input.replace(/\//g,'');
// requested output = 'string';
What I don't like about this method is that the double slashes might be considered a comment and ignored by certain browsers, or am I wrong?
It works in my browser, but I can't test in every browser. Is it a perfectly proper method, or is there a better solution?
|
> What I don't like about this method is that the double slashes might be considered a comment and ignored by certain browsers
What double slashes? The ones in the regexp? Certainly not, unless the browser's JavaScript parser is **totally broken.**
> Is it a perfectly proper method
Yes.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript"
}
|
EmberJs ember-data with ember-localstorage-adapter
Im using REST adapter by ember-data and it works fine. But now I want to use local storage for user settings storing.
Please, explain me, what is the right way?
I'm using ember-cli.
|
All you need to do is create a file in the adapters folder, **with the same name of your model**
//app/adapters/settings.js
import LSAdapter from "your_adapter"
export default LSAdapter.extend();
For local storage you can use Local Forage Adapter
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, ember.js, ember data, adapter"
}
|
How to pass arguments to an isolated scope when using & in custom directive?
I have a function in my controller scope
$scope.read = function(a, b, c){};
I've binded it to my custom directive
<dir read="read(a, b, c)"></dir>
And my custom directive
angular.module('app').directive('dir', function() {
restrict: 'E',
scope: {
read: '&'
},
link: function() {
read(a, b, c);
}
});
When I debuged it, all three arguments are `undefined`. How can I make it work?
|
The way to call the function from the directive is:
link: function(scope, elem, attrs) {
scope.read({a: your_a_argument, b: your_b_argument, c: your_c_argument});
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, angularjs directive, angularjs scope"
}
|
Change Active Directory / Domain Controller in Ms CRM
We have had a working MS CRM 2016 up until now, some thing happened and we lost our Domain Controller and Active Directory Machine, now we can not even login to ms crm, or even open the Deployment Manager since no user from that AD is available any more, is there any way to change the AD settings in MS CRM or anyother way to not reinstall the MS CRM ?
Basically the question would be this,
How to change a working MS CRM's Domain and AD to a new Domain (Even with same name) while the current AD is not accessible.
|
Appearently this is not possible, at least in a supported way.
The supported way is
1- install a fresh CRM in a computer in the new domain
2- remove the fresh organization from Deployment Manager
3- restore the previous database in the sql server your going to use with your new CRM (obviously should be in the new domain)
4- from Deployment Manager, Organization section, Import an organization, connect to the restored database and related sql reporting server in the wizard, and select automatic user mapping (in this part users get mapped based on their login name and the users which can not be mapped will be asked from you)
5- Hallelujah
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "active directory, dynamics crm, domaincontroller"
}
|
What's the relationship between WIC and GDI+?
I'm fuzzy on the relationship between Windows Imaging Component (WIC) and GDI+. I've done some work in the past that showed that, for example, WIC produces visually superior GIF encodings, but I'm surprised I don't see more people using it for image processing vs. GDI+. I know it doesn't have GDI+'s draw operations, but for encoding/decoding it seems superior. So why don't we see a migration?
|
The relationship (or rather the difference between) WIC and GDI+ is that WIC is an extensible imaging codec framework which allows applications implementing the framework to receive support for new image formats via provided codecs. GDI+ is a core component of Windows which supports draw operations such as lines, fonts, gradients, etc.
While GDI+ has native support for several common image formats, WIC codecs can be provided for any image format.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "graphics, image processing, gdi+, wic"
}
|
Is a class by default public, private or internal
When i declare a class:
class foo {
//code goes here
}
Is the class standard `public`, `private` or `internal`? I was wondering about this and wasn't able to find any information about it.
|
According to the documentation :
> All entities in your code (with a few specific exceptions, as described later in this chapter) have a default access level of internal if you do not specify an explicit access level yourself. As a result, in many cases you do not need to specify an explicit access level in your code
it is internal.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "class, swift"
}
|
Plot lineshape every 5th point on x-axis
I would like to create a plot using ggplot where several lines are ploted. The x-axis goes from `1:100`.
I would also like to include line shapes for each line but I would not like to display them for each point on the x-axis. Instead I want to plot them every 5th point so `seq(1,100,5)`
I cannot find the appropriate command for this but I assume it exists. Can someone help?
|
Is this what you mean? You could add an extra column to your `data.frame` and use `geom_point()` to plot it with whatever shape you like. Just repeat for each line you are plotting.
library(ggplot2)
set.seed(1)
pd <- data.frame(x = c(1:100), y = rnorm(100))
pd$pt <- pd$y
pd$pt[-seq(1, 100, 5)] <- NA
ggplot(pd, aes(x = x, y = y)) +
geom_line() +
geom_point(aes(x = x, y = pt))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, ggplot2"
}
|
Is there a simple way to create a tag pair (<TagName> value</TagName>) in ASP.net
Is there a built in function (I know I can easily create one) to create simple tags:
MakeTag("Tag","myvalue") would generate: `<Tag>myvalue</Tag>`
I'd rather something simpler than an XML class and all I need is just a tag created like this.
Also, any suggestions on a parser for the same?
|
Without rolling your own implementation, `HtmlGenericControl` is about as close as you are going to get:
var control = new HtmlGenericControl("Tag") { InnerText = "myvalue" };
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "asp.net"
}
|
Determining whether $ L = \{ 0^n1^{n^2} | n \ge 0 \} $ is a CFL
Assuming $L$ is defined as follows:
$$ L = \\{ 0^n1^{n^2} | n \ge 0 \\} $$
I'm trying to either prove/disprove whether $L$ is CFL or not.
My intuition tells me its not CFL since I cannot express the power $n^2$ by itself using CFL, but I'm having trouble proving so using the pumping lemma. Also, I failed to create any such PDA (which my intuition says its impossible).
|
Let $h\colon \\{0,1\\} \to \\{0\\}$ be the homomorphism given by $h(0) = \epsilon$ and $h(1) = 0$. If $L$ were context-free, so would $h(L) = \\{ 0^{n^2} : n \geq 0 \\}$ be. Since $h(L)$ is a unary language, it would be regular. However, a unary language is regular iff it is eventually periodic, which it isn't. Therefore $L$ cannot have been context-free.
More generally, if $L$ is context-free then:
1. The set of lengths of words in $L$ is eventually periodic.
2. The set of number of occurrences of a symbol in $L$ is eventually periodic.
The most general statement of this kind is Parikh's theorem.
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 0,
"tags": "automata, pumping lemma, pushdown automata"
}
|
What sign -> means in spock framework?
Could anyone explain me what means sign -> in spock framework?
For exaple we have code like below:
given:
UserService service = Stub()
service.save({ User user -> 'Michael' == user.name }) >> {
throw new IllegalArgumentException("We don't want you here, Micheal!")
}
I know what this code do, but I dont know how role have sign -> in this code.
|
The Spock Framework assumes a basic level of understanding of the Groovy language and sometimes the more intricate parts of Groovy show up (like in your example).
The `->` denotes a **closure** as described in the Groovy documentation.
For instance, a closure in Groovy could look like this:
def greeting = "Hello"
def sayHiTo = { name -> greeting + " " + name }
println sayHiTo("user3664097")
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "spock"
}
|
Backbone.js - Adding keydown events when view is active?
I have a view called gallery that options. I want to listen and act on keydown events when the gallery is rendered (until it's closed).
How do I do this in backbone events? I've tried all variations of 'keydown X':function and none have worked.
|
I just tested the following and it worked flawlessly:
var view = Backbone.View.extend({
// ... snip ...
events: {
'keyup :input': 'logKey'
,'keypress :input': 'logKey'
}
,logKey: function(e) {
console.log(e.type, e.keyCode);
}
});
I'd go back and check your code. All events in Backbone are defined as delegates attached to the `viewInstance.el` element. To unbind the events, call `viewInstance.remove()` which calls `$(viewInstance.el).remove()` under the covers and cleans up all the delegated events.
Also note that in some browsers (Firefox I believe) there's a known issue that some keys (like arrow keys) don't bubble and will not work properly with delegated `keypress` events. If you're catching special keys, you're probably better off using `keyup` and `keydown`.
|
stackexchange-stackoverflow
|
{
"answer_score": 23,
"question_score": 15,
"tags": "javascript, view, backbone.js, javascriptmvc"
}
|
Building my first Java Web Application
I have to build a java web application and I'm not sure where to start.
I have a good amount of experience with java but I would like to know if anybody can point me to a good example of how to integrate java into a web page?
I searched google without much luck. Is there a decent example on how to do this? Is it similar to adding a flash object with an object tag? Thanks
|
You can start creating sample web application based on html and servlets, This site will guide you in doing so.
<
You will need
JDK Apache Tomcat(jars will be in tomcat so no need to download separatly)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, web applications"
}
|
c++ access PEB_LDR_DATA struct member by offset
I am new to c++ and I am trying to access the InLoadOrderModuleList member in PEB_LDR_DATA structure.
I tried this:
// the ldrData data type is PPEB_LDR_DATA
PLIST_ENTRY firstitem_InMemoryOrderModuleList = ((PLIST_ENTRY)(pebLdrData + 0x0010)-> Flink);
without success. How should I accessing it?
|
The solution is to declare typedef structures of LDR_DATA_TABLE_ENTRY and PEB_LDR_DATA with its full structure.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "winapi"
}
|
Current user for apps in Microsoft OneDrive API
The SDKs for other cloud storage providers (e.g., `Google Drive`, `Dropbox`, `Box`) offer an option to retrieve the "current" (signed-in) user.
The same applies for `Microsoft OneDrive`, via the `Microsoft Graph API` (via calling `GET /me`). However, for applications getting an accessToken via clientId and clientSecret, that API does not work.
Is there any "current" user for such cases?
|
If you are getting an access token via clientId and clientSecret(client credentials flow), you will not be able to call `GET/me`. However, you can call `GET /users/{id | userPrincipalName}` to get a user if you have granted your app **User.Read.All** permission.
If you want to call `GET/me`, you need to get access on behalf of a user.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "rest, api, authentication, microsoft graph api, onedrive"
}
|
Storing Files to Local Disk in Chrome Extensions
I am writing a Chrome Extension to extract images in a web page and store them into local disk. Now I have got the URLs of all the images, how can I store them into local disk?
|
This problem may be solved by using NPAPI but it is not recommanded
> NPAPI plugin has the full permissions of the current user and is not sandboxed or shielded from malicious input by Google Chrome in any way
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, google chrome extension"
}
|
Samba 4 `wbinfo` missing on CentOS
I have installed samba4.x86_64 and the samba4-winbind using yum. The `wbinfo` command is not present anywhere on the box.
Is there an alternative to `wbinfo` in Samba4?
|
Please install:
samba4-winbind-clients
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "samba, samba4"
}
|
Detecting button press in CardAction BotBuilder
So within a carousel I have `builder.CardAction.imBack(session, 'relatedStuff', 'Related stuff'),`
and i've been doing a match to match once this is selected and handle a new dialog like so:
bot.dialog('relatedStuff', (session, args, next) => {
// console.log(session, '<<<<<< SESSION');
session.endDialog('This is a simple bot that collects a name and age.');
}).triggerAction({
matches: /^relatedStuff$/,
onSelectAction: (session, args, next) => {
session.beginDialog(args.action, args);
},
});
How can I identify what's being selected rather than doing a match?
So for example,
`builder.CardAction.imBack(session, data.name, 'Related events'),` and do a dialog that says `if (data.name === 'something) { do something.. }`
I can't find anything in the docs that tells me how to identify what's been selected if I don't know the value beforehand.
|
`session.message.text` will contain the value of the button pressed. You should check for the value there.
Here is an example of how this works.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "javascript, node.js, botframework"
}
|
Field assignment in a Java foreach declaration
I know that the foreach loop used in the following example doesn't compile. But does anybody know why using a field in a foreach loop declaration isn't allowed?
public class Foo {
private Object obj;
public void run(List<Object> objects) {
for (obj : objects) {
process();
}
}
private void process() {
// do something with obj
}
}
|
I expect there are a few reasons, but it probably just comes down to preventing programmer error.
One thing that would be confusing is "what would be the value of obj after the loop had executed"? Unlike the standard for-loop, the enhanced for-each loop isn't trying to make guarantees about its own mechanics.
Another thing is that instance fields represent an object's state. What you'd be saying by using an instance field in a for-each loop is that the object could changes from one state, then to one or many intermediate states, then to final a state _during the course of a single operation_. That's just bad design, and worth preventing.
Why not pass obj as an argument to `process()`?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "java, foreach"
}
|
Отдельный параметр проекта для msbuild при сборке решения
Можно ли передать параметр компиляции для определенного проекта в решении, но при этом для компиляции указать только решение?
Необходимо что бы в режиме отладки программа собиралась как консольное приложение, а в релизе, как Win32. Или тут поможет только последовательная сборка проектов?
|
Ну в принципе это можно сделать, хотя для Visual Studio это не вполне поддерживаемый сценарий.
С точки зрения компиляции, .csproj — это полноценный скрипт для MsBuild, и в нём вы можете задавать любые условия. Например, если вы создадите WPF-приложение, откроете .csproj на редактирование, замените строку
<OutputType>WinExe</OutputType>
на
<OutputType Condition=" '$(Configuration)' == 'Debug' ">Exe</OutputType>
<OutputType Condition=" '$(Configuration)' != 'Debug' ">WinExe</OutputType>
Будет создаваться такой исполнимый файл, как вам надо.
* * *
Минусы: поскольку это для Visual Studio не является поддерживаемым сценарием, у меня в тестовом приложении вывод в консоль не происходил, если запускать программу через `F5` (Start Debugging). Если запускать через `Ctrl-F5` (Start Without Debugging), всё работает как надо.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".net, visual studio, компиляция, msbuild"
}
|
How to know the parent class of the invoked java program?
I am working on a distributed application and getting an exception in the main method of a class. How do I know which java program has invoked it ? I tried debugging the distributed application, but could not figure it out.
|
> Let's say Java Class A invokes Java Class B (like "java classB") . I am getting the exception in class B. How do I want to know which class has invoked "java classB"?
You cannot know what invoked the java process from ClassB. The Exception will only go as deep as it's own call stack from it's process. If something else started the process, even if it was java itself, there is no way of know this from ClassB.
You are better off using helpful logging (of both debug/info messages and exception stacktraces) from ClassA. You will have to make sure that ClassB exits appropriately when it fails (exit with a code other than 0) and then ClassA can see this failure in the process it spawned.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, parent child"
}
|
Xcode - Show message on screen (No AlertView)
I am making an thats going to show a little message on the screen. I don't want it to cancel the current touches. I don't either like to force the user to disable the view with a button as the UIAlertView does.
I have discovered a message like this in an app called "Wrapp" (with ID:458640944)
Look at the screenshot: !Screenshot of a message in Wrapp
(I don't know if it is possible to resize the image in StackOverFlow, it's to big)
Here you can see the message about the server problem for example. I want a message like this.
-Not disables the touches
-no buttons to disable
-just being there for a few seconds
Jonathan Gurebo
|
you can use one of the following libraries:
< Shows a toast-like message.
I've used this as well:
< comes with all sort of progress controls.
Both of them are quite easy to implement but if you have specific questions on them you can always ask.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, iphone, objective c, xcode, popup"
}
|
Draw a network/graph on world map using basemap (python)
I have a list of hundreds of connected countries:
...
Albania ; Austria
Albania ; Azerbaijan
...
This gives a graph. I would like to draw lines (straight or curved) between the connected countries on the world map (using basemap / python)?
here is an example of the kind of result I would like to achieve <
|
It would be really helpful if you provided more information regarding what you have already tried. I have just posted an answer to a question which addresses what appears to be the subject of this question: <
The resulting image of the code in that answer looks like:
!example output
HTH
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, network programming, matplotlib, matplotlib basemap"
}
|
sending hex and ascii values using python module serial
I am trying to send a command to a lighting device.
The command below works in the hyper term.
\05387988c2g<CR>
* `\` is an ascii character
* `g<CR>` is at the end of every command
* `g` is the acknowledgement key and `<CR>` is the carriage return
I have tried sending this command using Python's Serial Module in the code below, but it does not work because `\` is an ascii character and `g` and `<CR>` are strings that need to be at the end of the command.
Could someone tell me what command I have to send. Any help is appreciated.Thanks.
|
its not really clear what you expect to send ... but assuming I understand this may help.
use r"" which will consider everything to be literal (including \\)... additionally you may need to send a carriage return (\r)
conn.write(r'\05387988c2g')
conn.write('\r')#may or may not be needed or some other ending character
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python"
}
|
The number of ways of posting the letters when no letter box remains empty is?
> $6$ letters are to be posted in three letter boxes.The number of ways of posting the letters when no letter box remains empty is?
I solved the sum like dividing into possibilities $(4,1,1),(3,2,1)$ and $(2,2,2)$ and calculated the three cases separately getting $90,360$ and $90$ respectively.
What I wanted to know is there any shortcut method to solve this problem faster?Can stars and bars be used?How?
Or can the method of coefficients be used like say finding coefficient of $t^6$ in $(t+t^2+t^3+t^4)^3$.Will that method work here?
|
Inclusion-Exclusion.
$3^6$ ways total.
$2^6$ ways if you only mail to $1\&2,2\&3$ or $1\&3$, subtract them off (3 alike cases).
$1^6$ way if you only mail to $1$, or to $2$, or to $3$, add them back in because they were subtracted twice (agai, 3 cases all alike).
$3^6 - 3 \cdot 2^6 + 3 \cdot 1^6$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "combinatorics"
}
|
Proving a contrapositive of the ratio test for sequences.
Let $(a_n)$ be a sequence s.t. $a_n\rightarrow L\in\mathbb{R}\setminus{\\{0\\}}$, let $\forall n\in\mathbb{N},a_n>0$. We wish to show that $\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1$. (From definition). My go:
By assumption, for any $\epsilon>0$ there is some $n_0$ for which $L-\epsilon<a_n<L+\epsilon$. Now, divide through by $a_{n+1}$ to obtain $$\frac{L-\epsilon}{a_{n+1}}<\frac{a_n}{a_{n+1}}<\frac{L+\epsilon}{a_{n+1}}$$ now as $a_{n+1}$ is a subsequence of $a_n$ it follows that $a_{n+1}\rightarrow L$, hence $$\frac{L-\epsilon}{L}<\frac{a_n}{a_{n+1}}<\frac{L+\epsilon}{L}$$ now further simplify to $$|\frac{a_{n}}{a_{n+1}}-1|<\epsilon/L$$ which holds for all $\epsilon>0$ and thus $\frac{a_{n}}{a_{n+1}}\rightarrow 1$. Would that be a correct approach?
|
First observe that $L > 0$, and for any $\epsilon > 0$, $\exists N \ge 1$ such that: if $n \ge N$, then : $|a_n - L| < \dfrac{L}{2} \implies a_n > \dfrac{L}{2}$, and $|a_{n+1} - L| < \dfrac{L\epsilon}{4}$, $|a_n - L| < \dfrac{L\epsilon}{4}$. Thus: if $n \ge N$, then: $\left|\dfrac{a_{n+1}}{a_n} - 1\right|= \left|\dfrac{(a_{n+1} - L) + (L - a_n)}{a_n}\right|\le \dfrac{1}{a_n}\left(|a_{n+1}-L|+|a_n - L|\right)< \dfrac{2}{L}\cdot \left(\dfrac{L\epsilon}{2}\right)=\epsilon$. Proving the claim.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, sequences and series, proof verification"
}
|
Assembly instruction and an extra 2E prefix before its opcode?
When I was tracing a piece of assembly program, I encountered an instruction "CALL DWORD PTR CS:[<&KERNEL32.GetPrivateProfileIntA>] with opcode 2E:FF15 84244100! Now I'm interested to know:
1. Though the opcode relevent to Call instruction is EA , why is the opcode mentioned as above used instead?
2. What does 2E: preceding the FF15 refer to?
|
2e is the CS segment override.
`FF /2` is `call r/m32`. The destination of the call is in the memory operand. (i.e. it loads a new EIP from memory). Without the CS prefix, it would have used the DS segment's base/limit for that addressing mode.
(EA is far jump so I think you meant E8 which is the opcode for the usual call rel32.)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "assembly, x86"
}
|
trying to create an array that prints out: how many there is of each value in an ARRAY
info before: i have halfway succeded, as i managed to print out it and it didnt loop crazy, however i did not manage to find the reason why it still prints out a undefinded
* * *
HTML: <button id="btn">button</button>
<label id="textarea"></label>
* * *
var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
var btn = document.getElementById("btn");
tall.sort(function(a, b){return a-b})
btn.onclick = function(){
for( var i = 0; i < tall.length; i++){
a = 0;
for(var j = 0; j<i ; j++){
a++;
tall.splice(i, 2)
document.write("number "+tall[i]+" is "+ a+" times<br>")
}
}
}
|
* we can use reduce to calculate how many times number is shown
* then we can use `Object.entries` with `forEach` \- to show data to UI
var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
var btn = document.getElementById("btn");
btn.onclick = function(){
const objectResult = tall.reduce((a,c) => (a.hasOwnProperty(c) ? {...a, [c]: a[c] + 1} : {...a, [c]: 1}), {});
Object.entries(objectResult).forEach(([number, times]) => document.write(`number: ${number} is ${times} times<br>`))
}
<button id="btn">button</button>
<label id="textarea"></label>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, arrays, slice"
}
|
Nullifying user-submitted formatting with CSS
I'm working on an online publication that will accept submissions from the general public. My WYSIWYG editor is set to strip out any embedded style/class tags (except those allowed by the editor), and I'm also checking this on the server side when it is saved. As a third layer of defense I would like to implement some CSS overrides to nullify any CSS directives embedded within a certain element of the page. Is this possible? I would imagine not for embedded `style` attributes, but possibly for embedded `<style></style>` blocks and `class` attributes?
|
You could use `!important` in your stylesheet to make sure that your rule will wins out over any other styling, inline or otherwise etc. Live example: <
<div class="override" style="background:salmon; height: 50px; width: 50px;"></div>
.override{
height: 200px !important;
width: 200px !important;
background: skyblue !important;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
Lift of a morphism between geometric quotients
Let $S$ be a scheme.
**Definition.** Let $X$ be an $S$-scheme and $G$ a smooth affine group $S$-scheme acting on $X.$ An $S$-scheme $Y$ is a _geometric quotient_ of $X$ by $G$ if there exists a morphism $\pi_X\colon X\rightarrow Y$ such that
1. $\pi_X$ is $G$-invariant,
2. the geometric fibers of $\pi_X$ are orbits,
3. $\pi_X$ is universally submersive, i.e., $U\subset Y$ is open iff $\pi_X^{-1}(U)\subset X$ is open, and this property is preserved by base change,
4. $(\pi_X)_*(\mathcal{O}_X)^G=\mathcal{O}_Y.$
Let $X$ and $X'$ be $S$-schemes with a $G$-action, where $G$ is the same introduced before. Assume that there exist geometric quotients $\pi_X\colon X\rightarrow Y$ and $\pi_{X'}\colon X'\rightarrow Y'.$
**Question.** Let $g\colon Y\rightarrow Y'$ be a morphism. Is there a $G$-equivariant morphism $f\colon X\rightarrow X'$ such that $\pi_{X'}\circ f = g\circ \pi_{X}$?
|
It is not true : for instance, $X$ and $X'$ might be two non-isomorphic $G$-torsors on the same $S$-scheme $T$.
Here is a precise example. Consider $S=T=Spec(\mathbb{R})$ and $G=\mathbb{Z}/2\mathbb{Z}$, let $X=Spec(\mathbb{C})$ and $X'=Spec(\mathbb{R})\cup Spec(\mathbb{R})$ viewed as $S$-schemes, and let $G$ act on $X$ and $X'$ respectively by complex conjugation and by exchanging the connected components. Both actions admit $Spec(\mathbb{R})$ as a geometric quotient. But an isomorphism between these quotients obviously doesn't lift to an equivariant morphism between $X$ and $X'$.
Here is another example : take $S=Spec(\mathbb{C})$, $G=\mathbb{G}_m$, $T=\mathbb{P}^1_{\mathbb{C}}$. Let $X$ (resp. $X'$) be the total space of the line bundle $\mathcal{O}$ (resp. $\mathcal{O}(1)$) on $T$ minus the zero-section, with the natural $G$-action. Both actions admit $T$ as a geometric quotient, but there is no equivariant morphism between $X$ and $X'$ lifting identity.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 6,
"question_score": 4,
"tags": "ag.algebraic geometry, geometric invariant theory"
}
|
jquery find children selector performance
Is there a better way to write this. I'm checking the input of a textarea and trying to find if it contains an object or iframe tags, if not then set var x =1
if ($textareaval.find('iframe').length > 0) {
alert('iframe')
} else if ($textareaval.find('param').length > 0) {
alert('object')
} else {
var x = 1;
alert(x)
|
If you don't care which one it has you could combine the two checks into one:
if ($textareaval.has('iframe, param').length > 0) {
x = 1;
}
**Edit:** You say you do care, though, so then no. Your code is fine, no improvement needed.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, find, children"
}
|
$f(ct)=cf(t)$ for all rational numbers $c$ and $f$ is continuous
Given that $f(ct)=cf(t)$ for all rational numbers $c$ and that $f$ is continuous, it must be that $f$ is a straight line. Can the same conclusion can be drawn if $f(2t)=2f(t)$ and $f$ is continuous, i.e. the statement holds only for $c=2$? Clearly it cannot if $f$ is not continuous, as you could set $f(0)=0, f(1)=1, f(2)=2, f(4)=4, f(8)=8$, and then for another "sequence" of numbers, set $f(0)=0, f(3)=1, f(6)=2$, and you would end up with many dots that lie on lines. But I was wondering if the assertion that $f$ is continuous forces $f$ to be a straight line even when the condition is reduced from all rational numbers $c$ to just one number.
|
If $f(ct)=cf(t)$ is only required to be true for $c=2$, then there are many possibilities for what $f$ can be.
Take _any_ continuous function $f_1$ on $[1,2]$ such that $f_1(2)=2f_1(1)$. Then we can extend this uniquely to any positive real number input. For instance, $$f(3)=2f_1(1.5)\\\ f(10)=8f_1(1.25)\\\ f(1/3)=\frac14f_1(4/3)$$ And then you can do something similar for the negative real numbers separately: start with a continuous $f_2$ on $[-2,-1]$ with $f_2(-2)=2f_2(-1)$, and expand as above.
To ensure continuity of $f$ at $0$, it is quite obvious from the above expansion construction that $\lim_{t\to0}f(t)=0$, so we need $f(0)=0$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 3,
"tags": "real analysis, sequences and series, limits, continuity"
}
|
merging two elements of two arrays in php
Hello Everyone I have a Array in php like
array (size=2)
0 => string 'A6,A5,B12,B11,' (length=14)
1 => string 'B6,B5,B8,B7,' (length=12)
on var_dump($arr). How could I convert it to something like
array('A6,A5,B12,B11,B6,B5,B8,B7,')
in php. here is what i'm doing eaxctly to get the above array
$id= "1";
$data['busInfo']= $this->dashboard_model->find_bus($id);
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$arr =array();
foreach ($data['reservationInfo'] as $reserved){
$seatBooked = $reserved->seats_numbers;
array_push($arr, $seatBooked);
}
var_dump($arr);
I'm using Codeigniter as my framework.
|
You can just append to a string, then create a single element array with that string (if you actually need an array):
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$str='';
foreach ($data['reservationInfo'] as $reserved){
$str .= $reserved->seats_numbers;
}
var_dump(array($str));
Or just implode the source array:
var_dump(array(implode('', $this->dashboard_model->get_booked_seats_info($id))));
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, arrays, codeigniter, foreach"
}
|
What is the XPath expression for <span>s not inside <div>s?
I'm trying to find ONLY the `<span>` tags OUTSIDE `div` tags. Sample HTML:
<span>find me</span>
<span>find me</span>
<div>
<span>don't find me</span>
</div>
What I've tried is the following, but I'm getting all `<span>`'s
//*[not(self::div)]/span
|
This should work:
//span[not(ancestor::div)]
Literally, this will match all nodes with `span` tag name who have no ancestor with tag name `div`.
Credits to this post
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, xpath"
}
|
Easiest to read fonts
Has there been studies to determine what fonts make it easiest to read? I'm interested in the font type, but also size and color. For example, is dark gray better than pitch black?
Also of interest is eye strain. Which fonts are the softest to our eyes?
|
For size and colour, the other answers have covered them well.
For font choice, I can't recall where the research was from, but I read a study that showed reading large blocks of text was faster with serif fonts. But there was no real difference between serif and sans serif fonts for shorter pieces of text (like labels or headlines).
This explains why almost all novels and newspapers are printed with a serif font.
For a specific font, my vote would be for Palatino for serif and Helvetica for sans serif (purely personal opinion though).
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "user behavior, color, font, perception, readability"
}
|
Make JFrame / JPanel unclickable
I have a JFrame with an associated JPanel which fill the screen, both having `setFocusable(false)` and in Front another JFrame with a Jpanel with a fixed size and centered (both are unmoveable). In this 'front' Panel theres a game, but when i click on the background Frame the front Panel moves to the background i only see the (dark grey) background Panel.
This is very annoying as you can imagine and i guess there must be a simple solution (i thought the setFocusable(false) would do the trick) but i simply cannot find it
|
Have you tried JFrame.setAlwaysOnTop( true )
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, jframe, jpanel"
}
|
Symfony2 how to render Checkboxes?
I have a formbuilder form with a multiple choice list of countries. When I render them on my form like this:
{{ form_widget(edit_form.countries) }}
They appear like this:
<input type="checkbox" name="..." value="AD" /><label for="...">Andorra</label>
<input type="checkbox" name="..." value="AE" /><label for="...">United Arab Emirates</label>
<input type="checkbox" name="..." value="AF" /><label for="...">Afghanistan</label>
I would like each option displayed on it's own line in the browser, instead of all in a row. How can I inject html around or between the options? Or is there a CSS method to accomplish this?
Thanks.
|
From The Symfony Docs
* Form theming
* How to customize form rendering
* Default form div layout
What you basically need to do is to overload **checkbox_widget** block.
{% form_theme form _self %}
{% block checkbox_widget %}
{% spaceless %}
<input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endspaceless %}
{% endblock checkbox_widget %}
Of course you can place your widgets in its own line with CSS (but it's not a Symfony2 question).
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 3,
"tags": "symfony, formbuilder"
}
|
Show that $\sum_{n=0}^\infty a_n z^n$ converges $\forall z\in\mathbb{C}.$
Assume that $\sum_{n=0}^\infty b_n z^n$ converges $\forall z\in\mathbb{C}.$ Let $x=\lim_{ n\rightarrow\infty}|\frac{a_n}{b_n}|$ exists. Show that $\sum_{n=0}^\infty a_n z^n$ converges $\forall z\in\mathbb{C}.$
**Proof:**
Since $\sum_{n=0}^\infty b_n z^n$ converges $\forall z\in\mathbb{C},$ the radius of convergence $R_{(b_n)}=\infty, \mbox{ i.e. } \limsup_{n\rightarrow\infty} b_n = 0.$ As $x=\lim_{ n\rightarrow\infty}|\frac{a_n}{b_n}|$ exists, we can write $x=\lim_{ n\rightarrow\infty}|\frac{a_n}{b_n}|=\limsup_{n\rightarrow\infty}|\frac{a_n}{b_m}|.$ I am stuck here.
I know that to show $\sum_{n=0}^\infty a_n z^n$ converges $\forall z\in\mathbb{C},$ I need to prove that $\limsup_{n\rightarrow\infty}a_n=0.$ Any suggestions?
|
Since the limit $\lim_{n\to \infty}\left|\frac{a_n}{b_n}\right|$ exists it follows that the sequence $\left|\frac{a_n}{b_n}\right|$ is bounded. Therefore there exists a positive number $M$ such that $\left|a_n\right|\leq M\left|b_n\right|$ for all $n\in\mathbb N$.
We conclude that $\left|a_nz^n\right|\leq M\left|b_nz^n\right|$ for all $n\in\mathbb N$ and $z\in\mathbb C$ and the result follows.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "analysis, convergence divergence, power series"
}
|
How to get UIImage of a specific area in current screen ios
The following code get UIImage of the current screen:
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:ctx];
UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
If I have a CGRect rect and I want to get only the UIImage of the current screen in that rect, how can I do?
|
**For Get Rect (Crop) Image:**
UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS You Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
Use following method that return `UIImage` ( _as You want size of image_ )
- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 6,
"tags": "ios, uiimage, screen, area"
}
|
Setting value for label using ComponentQuery.query()
I have created a Window, and added a label. Now i want to access that label using `query` and set text to that label. How am i suppose to do it ? I need to change the Text of the label (`firstlabel`) using `Ext.ComponentQuery.query`. Can someone help me please ?
Ext.define('ProjectExample.view.ex.FirstWin', {
extend: 'Ext.window.Window',
alias : 'widget.firstW',
items: [
xtype: 'panel',
title: 'First Panel',
items: [{
xtype: 'label',
name: 'firstlabel',
text: 'THIS IS A LABEL'
}]
];
var panelArr = Ext.ComponentQuery.query('panel');
});
|
You can do:
var label = Ext.ComponentQuery.query('window > panel > label')[0];
label.setText('new label text');
Here is an example: <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "extjs, extjs4, extjs4.1"
}
|
Are sessions safe to use to store permission information
I am currently writing an application in Django and I am looking at storing specific permission information during a user's session. The permissions are made up of the following values:
* No Permissions - 0
* Read Only - 1
* Edit - 2
* Add and Edit - 3
* Full Permission - 4
The higher the value, the better the permission a user has. If a user has only "Edit" permission for the module "Projects", I want to store that somewhere so I don't have to get Django to query the database constantly. Would it be appropriate to use the following;
request.session['project_permission'] = '2'
Or would the user be able to edit this value and sneak in a higher number like 3 or 4?
|
Assuming you are using Django's default sessions model backend, the user will not be able to edit any session related data.
The only information that is stored on the client side is the sessionid (in a cookie) which is the primary key to the Django Sessions table.
Django sessions table also has a column called "session_data" which stores the hashed session data (which the user will not have access to, unless they have access to your db)
I do not recommend storing permissions in sessions, there are better ways to implement this. Additionally, sessions (default django sessions model backend) data is stored in the database, so indirectly queries are being made
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "django, session"
}
|
C# regex get string beetween numbers
I have a simple string that would look like
string text = "1\t2:3|5"
So my goal is to get the chars between numbers something like:
string[] result = {"\t", ":", "|"}
I tried to bite this by getting numbers first
Regex.Matches(text , "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
And then use this regex pattern
> /[^ \w]/g
Well I am getting symbols but "\t" is splitted to "" and without "t", how to regex this?
|
You can do it with `Regex` or `String.Split` \- result is same
char[] separators = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
var splitResult = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
var matchesResult = Regex.Matches(text, @"(?<=\d)\D+(?=\d)").Select(w => w.Value).ToArray();
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, regex"
}
|
Given the address of an object, how would I call Obj-C methods on it in an LLDB Python script?
In pseudo-code, I'd like to create a reusable LLDB Python script that works like this:
get_super_class(int address) {
return ((id)address).getSuperClass();
}
Called like this:
(lldb) get_super_class(0x123abc)
UIViewController
Any ideas? I'm a python novice. I would think there is something in the documentation for SBValue that would get me close to what I want, but I don't see it if there is.
|
I am not at my computer (actually at a restaurant in Reno :) so what follows is mostly cursory but it should point you in the right direction
What you want to do is compose the expression as a string. Say you are looking to do foo(X) where foo is defined as
id foo(id arg)
What you can do is make yourself a string
"(id)foo((id)0xaddr"
Then you want to evaluate that as an expression.
I believe either SBTarget or SBFrame have an EvaluateExpression method To that you pass your dutifully crafted string, and remember to enable dynamic types since you are dealing with ObjC and most likely want them to be resolved.
What that API will return is yet another SBValue. That you can query for value, summary, description, or you can fetch its children value etc etc..
Hope this helps. If you need more details feel free to ask and I will try and fill in the gaps as I get a chance!
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, objective c, lldb"
}
|
Is it possible to get access to training materials for Sitecore® Experience Solution 9 Developer Certification?
I want to prepare for the `Sitecore® Experience Solution 9 Developer Certification`. However, I can't find anywhere some training courses, notes, or any material which will help with the preparation.
I did find some links but they were returning 404. Thus, do you guys know if there are any materials available for such preparation or it's not at all?
Thanks in advance!
|
Welcome to Sitecore Stack Exchange. You should start by looking at the sitecore training options listed on the documentation page < and also at the official courses available on < After you enlist to the certification you'll also get some training questions and topics that will be covered during the exam.
In order to pass the sitecore certification make sure you are proficient in covering all areas of the exam competencies which are described < For this you would need to either cover them through the online training courses or by having experience working as a Sitecore developer as listed in the prerequisites for the exam.
If you are planning on learning sitecore and becoming a developer please take a look at the post How can I get started learning Sitecore? and <
|
stackexchange-sitecore
|
{
"answer_score": 4,
"question_score": 1,
"tags": "training certification"
}
|
Get everything in a string after the 4th '/'
Can somebody please help me out. I would like to return everything in a string after the fourth '/'.
The file name that I am trying to edit is:
/students/levans10/public_html/cs130a/group4
so i want to include cs130a/group4.
I would also like to isolate the levans10 so the string between the 2nd and 3rd '/'.
Thanks.
|
This should work for you:
(Just `explode()` your string by slashes, then you can use `array_slice()` to extract the part which you want and with `implode()` you can print it again)
<?php
$str = "/students/levans10/public_html/cs130a/group4";
$arr = explode("/", $str);
echo implode("/", array_slice($arr, 4));//echo implode("/", array_slice($arr, 2, 1));
?>
output:
cs130a/group4 //levans10
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, split"
}
|
Non-cyclotomic abelian extensions
Suppose $L|\mathbb{Q}$ is an abelian extension of number fields. Then, all the roots of unity are certainly contained in the maximal abelian extension $L^{ab}$ of $L$. Why is it obvious that if $L \ne \mathbb{Q}$ then $L^{ab} \ne \mathbb{Q}^{ab}$.
|
~~Pick some $\gamma_1\in L\setminus\mathbb Q$ which is not a square.~~ Pick some $\gamma\in L^\times/(L^\times)^2$ which is not fixed by $\operatorname{Gal}(L/\mathbb Q)$ and fix a lift $\gamma_1\in L$. Let $\gamma_1,\ldots,\gamma_n$ be the orbit of $\gamma_1$ under $\operatorname{Gal}(L/\mathbb Q)$. Then it is an easy exercise in Galois theory to show that:
1. $L(\sqrt{\gamma_1},\ldots,\sqrt{\gamma_n})/L$ is Galois with abelian Galois group $\subseteq(\mathbb Z/2\mathbb Z)^n$.
2. $L(\sqrt{\gamma_1},\ldots,\sqrt{\gamma_n})/\mathbb Q$ is Galois with nonabelian Galois group $\subseteq\operatorname{Gal}(L/\mathbb Q)\ltimes(\mathbb Z/2\mathbb Z)^n$.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 10,
"question_score": 4,
"tags": "class field theory, nt.number theory"
}
|
How to check data is getting pushed into JSON or not
**JSON**
This is my JSON structure. I am pushing data into this on button click.
var arrtopic = {
"info" : []
};
**JS**
I wrote this is function
arrtopic.info.push({
"Name" :name,
"Number" : num
});
**JS for json data display**
function displayJson(){
var obj = eval ("(" + arrtopic + ")");
document.getElementById("newme").innerHTML=obj.info.Name;
}
This is not working, please suggest something
**Thank you in advance for your help**
|
Try this
function displayJson(){
document.getElementById("newme").innerHTML= arrtopic.info[0].Name;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, json, arrays"
}
|
Struggling with inversion
* (The guy that was fired) - For what he was responsible?
* (The guy that was fired) - For what was he responsible?
* (The guy that was fired) - What for he was responsible?
* (The guy that was fired) - What for was he responsible?
Which one is correct?
|
In modern spoken English, most people would say this:
> What was he responsible for?
There is really not much to explain. You just need to learn the pattern. Here's how it works:
> what + helping verb or the verb to be + subject + main verb (optionally) + preposition?
Example #1:
> **What** are you looking at me like that **for**? What did I do?
Example #2:
> **What** are you arresting him **for**? He didn't do anything wrong!
Example #3:
> **What user name** are you currently logged in **under**?
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 0,
"tags": "subject verb inversion"
}
|
python: make a variable equal an operator (+,/,*,-)
is it possible to assign a variable a maths operator.
this is what I've currently got, just a sample (typed it in now, so dont worry about simple errors)
if image == "lighten":
red_channel = red_channel + 50
else: // image is darken
red_channel = red_channel - 50
notice how i am repeating the exact same code, with a different operator. Is it possible to achieve something like this:
if (image == "lighten"):
operator = +
else:
operator = -
red_channel = red_channel operator 50
|
import operator
if (image == 'lighten'):
op = operator.add
else:
op = operator.sub
red_channel = op(red_channel, 50)
Or, if you have a number of possible operations,
op = {
'lighten':operator.add,
'darken':operator.sub,
...
}
red_channel = opimage
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "python, coding style"
}
|
How is it decided as to which character is used on the tech terminology?
Usually the technological terminology is mapped to an equivalent word in Chinese. For example:
* Deep Learning:
* Linear Algebra:
* Web Server:
However, may also be a valid choice. In fact Japanese people use `` on the term (i.e. ).
So how is which characters are used decided and by who? Is there any organization that lays it down?
|
* '' = 'in-depth learning'
* '' = 'deep level learning'
As you mentioned, Japanese use '' instead of '' for 'deep learning'
( is the preferred translation of 'Deep learning' in Hong Kong too)
Different countries and regions have different translations of some technological terms from foreign language. Hard to say which is better.
Blaszard wrote:
> _I didn't ask which is better or what meaning each word exactly has; I asked how it is determined and by who._
When a new terminology is coined in foreign language, different medias and publications may have trouble deciding on an unified translation.
Eventually, they will follow the lead of the authority in that particular field. If the Science journal in China translates 'Deep learning' as , the news would adopt it and the general public will follow. Finally, dictionaries would make it official by listing it.
|
stackexchange-chinese
|
{
"answer_score": 3,
"question_score": 2,
"tags": "characters, terminology, technology"
}
|
Android Service onBind method receiving stale intent
I am instantiating a service as follows:
try {
Intent intent = new Intent(this, SOMEService.class);
intent.putExtra("key", SOME UUID);
startService(intent);
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
inside my service's onBind method, I check whether the supplied key matches the expected key in the service. This key is refreshed on every transaction.
The issue is, if i close the app and reopen it (forcing the service to rebind), after that the onBind method receives the previous intent with the stale key and not the newer intent with the new key.
Any ideas why this may be happening?
|
When you start Service, it will run indefinetely and restart even if Android stops it due to lack of resources. So, when you close app, Service is kept running - you only onbind from it. If you want your Service running only when app is open, stop it when app closes and then start again.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android intent, android service"
}
|
For Loop in R - deleting all rows which match by one variable
I'm trying to completely delete rows in a dataset for cases with matching variables (case ID) with the help of this function I wrote:
del_row_func <- function(x){
for(i in 1:length(x$FALL_ID)){
for(j in 1:length(x$FALL_ID)){
if(x$FALL_ID[i] == x$FALL_ID[j] & i != j){
x[-i, ]
}
}
}
}
Anybody have an idea, why it doesn't work?
|
The reason your code didn't work was that you weren't modifying or returning `x`. However, there is a better way to remove all rows with a duplicated ID:
dat = data.frame(FALL_ID = c(1, 2, 2, 3), y = 1:4)
dat
# FALL_ID y
# 1 1 1
# 2 2 2
# 3 2 3
# 4 3 4
dat[!duplicated(dat$FALL_ID) & !duplicated(dat$FALL_ID, fromLast=T),]
# FALL_ID y
# 1 1 1
# 4 3 4
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "r, for loop"
}
|
Deletion from B-Tree - M=5
I'm dealing with a deletion in BTree in very specific case
M=5 - that is - maximum number of keys in node is 4 and minimum number of keys in node is 2
Now when deleting in BTree using the defensive approach (I must use this one) when I approach a node I must guarantee that it has one key more than the minimum required.
Here is my problem - let's say I have a root with one key and two children with 2 keys each. When I will approach one of these children I will have to guarantee that it has at least 3 keys (because M=5).
I have two ways to do it - borrow from neighbor or borrow from father and merge. I can't borrow from neighbor as it has the minimum of 2 keys but borrowing from the father and merging creates a node with 5 keys - and it's more than the maximum of the allowed keys (as M=5).
What should I do in this case? More specifically - what is the correct way to treat such situation
|
Classical B-trees constrain key counts for non-root nodes to lie between d and 2d for some d. This means that merging of nodes is only possible if an underflow has **already occurred** and the other node involved in the merge has minimum occupancy. Together with the separator key pulled from the parent node this makes for a key count of (d - 1) + d + 1 = 2d, which is the maximum that fits into a node. Merging on the way down 'just in case' is not possible.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "algorithm, tree, b tree"
}
|
Dropdown box: How to know if a value is selected or not
in the code below, I need to know what choice is being selected. What is the appropriate way? Thank you
$(window).ready(function() {
$("#Tmimata > option").each(function(index) {
var mythis = $(this);
if (mythis.selected) {
}
else {
}
});
});
|
you'd use the **`:selected`** selector
if (mythis.is(':selected')) {
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, drop down menu, selecteditem"
}
|
tomcat stops serving behind apache when shifted to mod_proxy_ajp using SSL
We are facing an issue for last many days that our tomcat(8.0.5) stop responding to web requests which are targeting to a servlet deployed on tomcat but requests are coming from our website deployed on apache(2.2) on centos.
After going through many docs and posts we have come to conclusion to set maxThreads (in server.xml of tomcat) to same as maxClients settings (in apache httpd.conf for prefork MPM ) i.e. 256. But when I have gone through the AJP docs here: <
I came to know that it should be tomcat's "maxConnections" rather than "maxThreads". My collegue is convinced to have it "maxThreads" while i think it should be "maxConnections", so can someone clarify this confusion on our part. By the way - maxThreads settings is working fine since we applied this. Regards.
|
The maxConnections means the max tcp connections that tomcat could establish, the maxThreads means max number of tomcat threads that could be used to process the requests from the connections.
I think in most cases, it is a good idea to set both number to be the same, tomcat 8 will set the maxConnections to the same number of maxThreads.
If you set the maxConnections to be larger than maxThreads, tomcat will establish more connections than the maxThreads, so there could be not enough number of threads to process the connections, and some connections will be blocked and wait for spare threads.
For BIO connectors if you set the maxThreads, the maxConnections is **automatically** changed by tomcat, For NIO and NIO2 the default is 10000. For APR/native, the default is 8192(Double checked tomcat docs, it said so). if you change the maxConnections, the maxThreads will **NOT** be changed accordingly.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, apache, tomcat, ajp"
}
|
Balls in bins: Prove that the probability that there is some bins of $k+1$ or more balls is at most $\frac n{k^2}$
(Using _Chebyshev's inequality_ and _Union bound_ )
Suppose that we throw $n$ balls into n bins uniformly at random. Let $k≥\sqrt n$ be a positive integer Show that with probability at least $1-\frac n{k^2}$, no bin has strictly more than $k$ balls.
Prove that the probability that there is some bins of $k+1$ or more balls is at most $\frac n{k^2}$.
|
Consider of the distribution of balls that land in a particular bin, $X$. This will be a binomial distribution. Its mean is $n\cdot$$1\over n$$=1$ and its variance is $n\cdot$$1\over n$$\cdot(1-$$1\over n$$)$$=1-$$1\over n$. Then Chebyshev tells us $P(|X-1|\ge k\cdot(1-$$1 \over n$$)) \le$$ 1\over k^2$. For $1\le k\lt n$, since $k\over n$$\lt 1$ this means $P(|X| \ge k+1) \le $$1\over k^2$. Now if $k \ge \sqrt n$ then the probability of one of the n bins having more than k balls will be at most $n\over k^2$ by the union bound (for $k \lt \sqrt n$ the upper bound we get is greater than 1 and so is meaningless). For the case $k=n$ simply note the $P(X=n)=($$1\over n$$)^n$ so the union bound gives $P($n balls land in some box$)=$$n \over n^n$$\le$$ n\over n^2$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "probability, balls in bins"
}
|
Is the following sentence correct - "usage of apprehending"?
Thus, you reduce the risk of any software changes by apprehending the possible cause.
|
That's right! _apprehending something_ is possible.
The word is used correctly but **it's old-fashioned.**
OALD has an entry like that
> _apprehend something_
To avoid complexity, you may simply come up with other options. Maybe...
> Thus, you reduce the risk of any software changes by _knowing/understanding/recognizing_ the possible cause.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sentence construction"
}
|
Is this boolean answer correct?
F(x,y,z) = (x + y')(x + y)(xz')
= (xx) + (xy) + (xy')+(y'y)(xz')
= [x + (xy) + (xy') + 0 ] (xz')
= [x + x(y + y') + 0] (xz')
= [x + x(1) + 0] (xz')
= [x + x + 0] (xz')
= [x + x] (xz')
= x*(xz')
= (xx)*z'
= xz'
xz' is my final answer.
|
Well yes, $$(x+y^\prime)(x+y)=x$$ and $$x(xz^\prime) = xz^\prime,$$ so your result is correct.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "boolean algebra"
}
|
Is there any issue if ternary operator is used in super() method
I am using a ternary operator in super () method of my code. While the code went for review, I got a reply that
> Strictly don’t use ternary operators in the Super() calls.
Is there any problem if we use ternary operators in the super() method?
|
I would reply to your reviewer and ask them to explain their comment. A critical part of the review process is understanding _why_ code should be changed. Perhaps it doesn't adhere to the established coding standards, or similar code caused a problem in the past. Point is, ask why, in the spirit of understanding.
|
stackexchange-softwareengineering
|
{
"answer_score": 10,
"question_score": 2,
"tags": "java, code reviews"
}
|
How do Microsoft hotfixes actually work?
I don't get how Microsoft hotfixes work in practice. Hypothetical example:
Imagine a simple app – just one file, **CoolApp.exe**. **Hotfix1** is released to resolve an issue. Later on, **Hotfix2** is released to resolve a different issue.
Does **Hotfix2** implicitly include **Hotfix1**?
If no, then how can we enjoy the benefit of both hotfixes simultaneously?
If yes, then what happens if we need the fix that **Hotfix2** provides but we _do not_ want the fix that **Hotfix1** provides?
|
To answer in simple terms, **yes**. If an update changes the version of a specific file, the fixes in Microsoft's previous versions of that file are also there. This is why updates often supersede other updates, rather than add to the total amount of updates available.
While you can choose to apply only certain updates (assuming no dependencies), you can't choose only certain fixes be applied to a particular file.
In reality, there is much more to Windows Update than just downloading files and replacing them with newer versions. For example, Binary Delta Compression downloads only the data containing the differences between files. This technology has been used by Microsoft for nearly 10 years.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 0,
"tags": "windows, updates, software update"
}
|
How to trim zeros after bigDecimal value using Scala Spark
I'm beginner in spark scala. I have tried regex but it is used only for string Datatypes. I want Col_2 to be decimal without changing the precision and scale. Can someOne please guide me to solve this.
Col_1 : string
Col_2 : decimal(38,18) -->BigDecimal
Col_1 Col_2
ABC 2.000000000
DEF 2.501000000
XMN 0.00
RST 1.28
wanted result
Col_1 : string Col_2 : string
Col_1 Col_2
ABC 2
DEF 2.501
XMN 0
RST 1.28
|
You can achieve this result using the code below, but it's better to keep numeric data using one of the numeric formats.
import spark.implicits._
val inputData = List(("ABC" -> 2.000000000),("DEF" -> 2.501000000),("XMN" -> 0.00),("RST" -> 1.28))
val resultDF = inputData.toDF
.selectExpr("_1 as Col_1", "regexp_replace(cast(_2 as String), '\\.?0+$', '') as Col_2")
resultDF.show
Output
+-----+-----+
|Col_1|Col_2|
+-----+-----+
| ABC| 2|
| DEF|2.501|
| XMN| 0|
| RST| 1.28|
+-----+-----+
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "scala, apache spark, hadoop"
}
|
How can I use a PHP email variable with cron?
I have a service that sends out text to an email entered after x number of days. I want to use cron, but I know that because my PHP script uses variables, this would not work. How can I change my PHP or do anything that would allow me to use cron (or even something else)? I just need something where it will store the emails then send them. I'm **really** new to PHP, so keep it simple please.
Here’s my code:
<?php
if(isset($_POST['email']))
{
$headers = "From: Memory Jet <[email protected]>\r\n";
$to_visitor = $_POST["email"];
$common_data = $_POST["message"];
mail($to_visitor, "Your Memory", $common_data, $headers);
}
?>
|
use argv array to read CLI params - <
if your script is named `/bin/script.php` then if invoked as `/bin/script.php xyz` the following:
$email = $argv[1];
will assign `'xyz'` to `$email`.
just read doc I've provided - there's all you need
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, email, cron"
}
|
JavaScript not working inside form
I have the following HTML code
<div class = "login">
<form>
<input type="text" id="username" name="username" placeholder="Username" style="text-align:center"> <br> <br>
<input type="password" id="password" name="password" placeholder="Password" style="text-align:center"> <br> <br>
<input onclick="loginButton();" name="login_btn" id="login_btn" type="submit" value="Login">
</form>
</div>
And the following JavaScript:
<script type="text/javascript">
function loginButton() {
console.log("this function was called")
}
</script>
In my console, when I click the submit button, "this function was called" appears for only a brief second, and then disappears. Yet when I put the submit button outside of the form, the message stays, and fully executes the rest of my function.
|
Your form gets submitted and the page reloads - because of `type="submit"` on `input` element.
Change it either to
`type="button"`
or
`onclick="loginButton(); return false;"`
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "javascript, html"
}
|
Vue not displaying data from data object
I am using NuxtJs and created `test.vue` in `pages` directory. Here is my code in `test.vue`.
<template>
<div>
<h1 style="font-size: 30px">{{ message }} </h1>
<h1 style="font-size: 30px"> Messsage here </h1>
</div>
</template>
<script>
export default {
data: {
message: 'sdfsd'
}
}
</script>
But `{{ message }}` not displaying. What is the problem?
|
The `data` needs to be a `function` so that each instance can maintain an independent copy of the returned data object.
export default {
data() {
return {
message: 'sdfsd'
}
}
}
Read more here
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vue.js, nuxt.js"
}
|
Problema consulta MySQL con PHP
No sé cómo devolver cada valor en una variable distinta.
**Mi código:**
$query = "SELECT id_tienda,id_prod from prod_tienda where id_prod='$row' ";
$result = mysqli_query($con, $query);
while ($mostrar = mysqli_fetch_array($result)) {
$id = ($mostrar['id_tienda']);
echo $id;
|
_Un posible ejemplo:_
$query = "SELECT id_tienda,id_prod FROM prod_tienda WHERE id_prod='$row'";
$result = mysqli_query($con, $query);
//Comprobamos si existe registro.
if (mysqli_num_rows($result) > 0) {
//Tu array con los datos desde la Base de Datos.
$mostrar = mysqli_fetch_array($result);
} else {
echo 'No se encontraron datos.';
}
> **Nota:** te aconsejo por seguridad utilizar sentencias mysqli prepare o PDO. También te aconsejo leer bien ¿Cómo evitar la inyección SQL en PHP?
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, mysqli"
}
|
Add banner on Free shipping
I setup price based shipping fees calculation and they are reduced to zero when cart value is greater than 50 euros. Is it possible to show a code (maybe a banner) when shipping rates result is 0? I use lotusbreath one page checkout
|
Shipping Charge can get at checkout page by below:
Mage::getSingleton('checkout/session')->getQuote()
->getShippingAddress()->getShippingAmount();
If you use magento default checkout onepage then just goto `app/design/frontend/YourPackage/YourTheme/template/checkout/onepage.phtml`.
Just put a condtion is if `Mage::getSingleton('checkout/session')->getQuote() ->getShippingAddress()->getShippingAmount()` is `0` the put a banner.
**Like:**
<?php if(intval(Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount())==0): ?>
// call banner
<?php endif; ?>
|
stackexchange-magento
|
{
"answer_score": 3,
"question_score": 3,
"tags": "shipping"
}
|
In which episode of Golden Time did Koko say "I love you" to Banri on the school staircase?
There was a sequence on the school staircase where Koko said "I love you" and Banri fainted. Which episode was that?
|
Actually it was Banri that fainted not 2D-kun. As you can see, he's still standing on the top of the staircase. This happens in episode 7 at ~7:30-7:40

{
tree.put("my.path.to.thing", true);
}
|
For a simple solution, you can use get_optional()
According to the documentation, if it exists, it returns the value otherwise it returns an uninitialized `optional`
Example
boost::property_tree::ptree tree;
// if path doesn't exist, put value
if (!tree.get_optional<bool>("my.path.to.thing").is_initialized())
{
tree.put("my.path.to.thing", true);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c++, json, xml, boost, boost propertytree"
}
|
Figure out time by latitude/longitude?
Here's the deal. I have a latitude/longitude set of a location. I need to figure out what the current time is in that location. Here's how I was getting it before:
NSDateFormatter *theFormatter = [[NSDateFormatter alloc] init];
[theFormatter setDateFormat:@"h:mm a"];
NSDate *todaysdate = [NSDate date];
NSString *todaysDate = [theFormatter stringFromDate:todaysdate];
[theFormatter release];
However, I realized that this will give the time for the user's current location. Is there an API somewhere that gives me the time based off of a lat/lon pair?
Thanks in advance.
|
Unfortunately timezones (and time in general) is never as simple as you would like.
For a simple approximation you can follow jer's suggestion. Longitude ranges from -180 to 180 degrees, there are 24 hours in a day, so you get 15 degrees of longitude per time zone. Center those time zones on 0 degrees longitude so UTC extends from -7.5 to 7.5, UTC+1 is from 7.5 to 22.5, UTC-1 is from -7.5 to -22.5, and so on. You would then have a very simplistic, and wrong, model of how we use time zones.
Take a look at this map of time zones.
* Time zones are not well ordered; regions in UTC-1 are adjacent to regions in UTC-3.
* UTC-9.5, UTC-4.5, UTC+3.5, UTC+5.75, and UTC+13 are all valid time zones and actively in use.
Once you get that sorted out then you can start to consider daylight savings time.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "iphone, objective c, cocoa touch, time"
}
|
Nginx: location directive for sub domains under a single server
I have a server config like this
server {
listen 80;
server_name www.site.com;
server_name stage.site.com;
server_name nagios.site.com;
location ~* (.*)nagios {
auth_basic "Admin";
auth_basic_user_file /etc/nginx/.htpasswd;
}
When I try to apply a location directive to the sub domain it does not seem to work.
I don’t want to duplicate server. It’s a lot of code.
How do I rectify this?
|
> When I try to apply a location directive to the sub domain it does not seem to work.
`location` directive is used for URI, not sub domain.
> I don’t want to duplicate server. It’s a lot of code.
But it is the **right** way to do this. Checking `$http_host` with `if` directive is not recommend, either.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "nginx"
}
|
How to detect when a ScrollViewer finishes scrolling?
BTW I'm using UWP in case it matters. So I am using a ListView and all ListViews have a ScrollViewer attached to them (in default template) by default. The problem is that I cannot find an event (on the ListView itself or on its ScrollViewer) that triggers when the ListView finishes scrolling.
I used the scrollViewer.ChangeView() method to automatically scroll to the beginning of the ListView and it uses an animation to scroll to the top, so I think that has something to do with it because the ViewChanged event fires before the animation completes. If I am correct about that then there would have to be a way to determine if the animation is complete because I need to be alerted when the ListView is completely idle again, which is only when the scroll animation completes. Thanks.
|
You can wire up the scrollViewer's ViewChanged event, and check the `IsIntermediate` of the event argument.
private void ScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
if (e.IsIntermediate)
{
System.Diagnostics.Debug.WriteLine("scroll ongoing");
}
else
{
System.Diagnostics.Debug.WriteLine("scroll finish");
}
}
This event is fired multiple times. When the scroll finishes, `IsIntermediate` is false.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "c#, xaml, listview, uwp, scrollviewer"
}
|
Python read() not working
I'm trying to open a file, read the content, compare that with a hash and if necessary overwrite the file again. Should be basic stuff, but somehow I can't get it to work. I have now:
with open(name, 'wb+') as des:
current_content = des.read()
I'm 100% sure the file is not empty, that I'm looking at the right file (later data gets written to it and that works) but somehow current_content ends up as an empty string.
with open(name, 'wb+') as des:
des.write('Test')
des.seek(0)
current_content = des.read()
If I try the above current_content will return 'Test'. Anyone an idea what could cause this behaviour?
|
Change the file reading option `wb+` to `ab+` and test it now. The problem is `ab+` supports reading and appending the data(At EOF) in a binary file according to documentation. When you are using `wb+` it may overwrite the existing file.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python 2.7, pycharm"
}
|
What are the correct terms for these visualization components?
### What is the proper term for a vertical line on a visualization that follows a mouse cursor?
_Nb, screenshots have removed my mouse cursor but it exists on the same vertical plane as the dot in the second figure in both visualizations._
 "Does **someone** of you know the full name of our chemistry teacher"
>
> b) "Does **some** of you know the full name of our chemistry teacher"
|
You use **someone** in affirmative clauses and **anyone** in negative and interrogative clauses. This is a question, so you should use **anyone**. See this link for more information.
When you ask this question, you are expecting each person to consider their own situation, rather than have somebody answering on behalf of the whole group. So, rather than saying "Does some of you..", you ask "Does anyone...".
> Does anyone know the full name of our chemistry teacher?
Note that **some** is plural, so your question b should have been "Do some of you.."
|
stackexchange-ell
|
{
"answer_score": 4,
"question_score": 2,
"tags": "pronouns"
}
|
How to add button to call a specific number
I want to add a button to my app that will allow the phone to call a particular number. I also want to add message service.
|
try this code for calling particular number
call.setOnClickListener(new View.OnClickListener() {//here call is the button
public void onClick(View v) {
try {
String Numb = "tel:" + repphone;// repphone is phonr num
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(Numb));
startActivity(intent);
} catch (Exception e) {
// Modules.showLongMessage(contact.this, e.getMessage());
}
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android"
}
|
Wordpress: get attached images and show them inside post
I want to show attached images inside the post .. Just like
<a href"LINK TO FULL SIZE IMAGE"><img src"LINK TO THUMB"></img></a>
I get the following from codex.wordpress but how to tell the code to use large image link with `<href` and thumb link with `<img`
<?php
$attachment_id = 8; // attachment ID
$image_attributes = wp_get_attachment_image_src( $attachment_id ); // returns an array
?>
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">
|
You can use `wp_get_attachment_link` instead of `wp_get_attachment_image_src` :
echo wp_get_attachment_link($attachment_id, 'large');
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, wordpress"
}
|
No Internet Connectivity in Windows 10 after uninstalling Comodo Firewall
I had Comodo firewall installed on my laptop,there was some conflict after I installed avast antivirus software,most applications failed to launch.So I booted to safe mode and removed the AV and Firewall. After doing this and connecting to a wifi network ,there is no intenet Connectivity. USB Tethering is also not working.
Tried network diagnostics tool and it identified some driver issues.
Reinstalled the driver,but it did not help.
Tried some utilities to fix internet connection,still no use.
What might have gone wrong?
Please advice ?
|
I faced the same issue today on Windows 10(1803). I tried different solutions like resting networking etc... All in vain.
1. Downloaded Comodo uninstaller from here. (Direct links 32bit, 64bit)
2. Boot up in safe mode and ran Comodo Internet Security Uninstaller (for me in normal mode it caused death screen)
3. Bootup in normal mode (Comodo Internet Security Uninstaller will automatically start and remove some other stuff)
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows 10, wireless networking, internet connection"
}
|
Kubernetes for Windows networking - default CNI
Under this official doc, calico and flannel are not yet fully supported by windows. I plan to use ToR (top of rack) static routing.
How do I install the default CNI? (just do nothing?)
E.g. using flannel I will need to run - kubectl apply -f kube-flannel.yml
So what do I need to install for default CNI for ToR static routing?
Also a quick note, I'm using Kubeadm to set this up on-prem so any insight would be appreciated.
|
Actually, there's a default CNI config here. It also shows you steps to set it up on a Windows hosts. And this script would setup up the PodCidr that you'd need to run your kubelet.
You still need as you mentioned, setup your own ToR static routes.
Hope it helps!
Update from @JuniorPenguin:
> I would just add enable NIC promiscuous mode if you are using VMware
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "networking, kubernetes, cni"
}
|
CheckboxPreference onClick()
I want to implement a 2 part preference screen. If checkbox is clicked, first category should lock and 2nd one unlock. If it's not, reverse. Now I see it only works if I go to previous activity and then to new (sharedPreferences). What listener should I override and how?
|
You could try something like:
final Preference otherpref = (Preference) findPreference("otherpref");
final Preference pref = (Preference) findPreference("checkbox");
pPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
otherPref.setSelectable(false);
Toast.makeText(getBaseContext(), "Some text", Toast.LENGTH_SHORT).show();
return true;
}
});
And disable your desired categories.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "android, checkbox, checkboxpreference"
}
|
lsf awk command quotes
When I run this command in the bash terminal it works:
awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt
But when I run this:
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"
It does not work. I also tried changing ' to \' but also does not work.
I get the following errors: for the first case:
awk: { sum += } END { print sum }
awk: ^ syntax error
for the case I used \'
awk: '{
awk: ^ invalid char ''' in expression
Any ideas where I am messing up with the syntax? I am quite puzzled.
Thanks
|
notice how the `$1` has disappeared in the error message?
awk: { sum += } END { print sum }
awk: ^ syntax error
This is because in shell, when you quote something FIRST with dbl-quotes, as you have done with
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"
any ${var} references are expanded to their value. The single-quotes have lost their magic power to prevent variable expansion when they are inside a dbl-quoted string.
How to fix, escape your `$`s. not sure what bsub is, but this should do it:
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += \$1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"
# -------------^^^
IHTH
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "awk, lsf"
}
|
How to split element of custom Data type
I am a newbie to haskell.
I am quite confused of custom data type
So what I want to make it is to show total age of person and each person's name and age
so I expects it looks like this
Detail "Ben" 20 Student
"Joy" 25 Police
"Hellen" 10 Student
Total 55 -- 20 + 25 + 10
So this is my code
data Person = Name String Int Job deriving Show -- name age Job
data Det = Total Int | Detail String Int Job deriving Show -- age | name age Job
data Job = Police | Student deriving Show
Split :: Person -> Int -- Need to get eacn age to accumulate one another for total age
Split (Name _ age _ ) = age
check1 :: [Person] -> Det -- Need to sum all the age with Split function
......?
|
total :: [Person] -> Int
total [] = 0
total (x:xs) = getAge x where
getAge (Name _ age _ ) = age + total xs
You need to use a list of the Person type. This will return the total age of all elements in the list.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "haskell"
}
|
Microsoft Teams Toolkit - Support for Multitenant Teams App
I am developing a Teams App which have Tab and Search Message extension as a capability. The app should support multitenant scenarios, where the app will be deployed on different tenant and should be able to do some operation using Graph api. Hence I am calling a On-Behalf-user token. My request fails for these scenarios. When I tried to make Tab App registration to support Multitenant, I receive below error: .
Are there beings, mythological objects, or locations that are characterised by stone in Norse mythology?
|
Hrungnir, a mighty jötunn, is said to **have a stone head and heart** , as well as a stone shield and weapon. He appears in the _Prose Edda_ where he fought and was slain by Thor. A translation of the account can be found here:
> Hrungnir had the heart which is notorious, of hard stone and spiked with three corners, even as the written character is since formed, which men call Hrungnir's Heart. His head also was of stone; his shield too was stone, wide and thick, and he had the shield before him when he stood at Grjótúnagard and waited for Thor. Moreover he had a hone for a weapon, and brandished it over his shoulders, and he was not a pretty sight.
|
stackexchange-mythology
|
{
"answer_score": 9,
"question_score": 8,
"tags": "norse"
}
|
Android on BackPress reach 3rd previous activity using finish() only
Activity's flow of run
A->B->C->D
* from D onBackPressed() reach A
* from C onBackPressed() reach B
!enter image description here
I don't want to call `startActivity(new Intent(context, A.class));` by only using finish.
|
Thanks for your response but i recently solved problem with this way.
Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, android activity, onbackpressed"
}
|
Is there any way to get 2 dragon eggs on bedrock, without cheating or dupes?
Recently I was playing Minecraft with one of my friends. I was playing on my switch, I didn't know what they were playing on.
We went and beat the dragon and before that, I took the egg from a previous fight (?).
After we beat the dragon, we went to our homes. When I went and placed my egg down, I said that I was happy to have this one-of-a-kind object.
Then, my friend said, "it's not one of a kind, I have one too".
I told them **that's impossible,** and they came over and placed their egg in their house!
How could they have gotten another egg??!? They didn't cheat it in (I got the end achievement) and they didnt dupe it (they had theirs before I took mine from the original pedestal in the end).
|
It appears your world has had some sort of glitch, as a second egg spawning after the Dragon's death is impossible. According to the Minecraft Wiki,
> The dragon egg is a decorative block or a "trophy item", and is the rarest item obtainable in the game, as **it generates once and once only.**
Or, your friends may have duped the dragon egg and placed one for you. This is most likely the occurrence, as the egg you found from the "previous fight" simply doesn't generate in that fashion, and your friends did in fact just place an extra fake egg on the podium for you.
|
stackexchange-gaming
|
{
"answer_score": 3,
"question_score": 1,
"tags": "minecraft bedrock edition"
}
|
Pasted tables from Jupyter to StackOverflow get ill-formatted
Consider the code:
df = pd.DataFrame({
"name":["john","jim","eric","jim","john","jim","jim","eric","eric","john"],
"category":["a","b","c","b","a","b","c","c","a","c"],
"amount":[100,200,13,23,40,2,43,92,83,1]
})
df
When I copy the output, I get a not nicely formatted table here on StackOverflow:
name category amount sum count
0 john a 100 140 2
1 jim b 200 225 3
2 eric c 13 105 2
3 jim b 23 225 3
4 john a 40 140 2
5 jim b 2 225 3
6 jim c 43 43 1
7 eric c 92 105 2
8 eric a 83 83 1
9 john c 1 1 1
How to fix this problem?
|
from an `ipython` terminal session I can paste:
In [73]: df
Out[73]:
name category amount
0 john a 100
1 jim b 200
2 eric c 13
3 jim b 23
4 john a 40
5 jim b 2
6 jim c 43
7 eric c 92
8 eric a 83
9 john c 1
From a notebook, it looks like `print(df)` gives a better result:
name category amount
0 john a 100
1 jim b 200
2 eric c 13
3 jim b 23
4 john a 40
5 jim b 2
6 jim c 43
7 eric c 92
8 eric a 83
9 john c 1
The copy selection should be a solid color block.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jupyter notebook, jupyter, jupyter lab"
}
|
Simplest way for end users to run Python script on network drive without installation?
I want to start using Python at work, and I have a script that I need all the end users to run on a central network drive.
However, they don't have admin rights to install Python and I am not going to call desktop support and go through that mess. I'm thinking of putting my WinPython installation on the network, pointing to the py.exe in a BAT file, and instruct users to run the BAT file.
Is there a better way to do this?
|
I ended up using WinPython and that suited my needs nicely. It's a convenient little package.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "python, batch file, deployment"
}
|
How to check file process in visual studio in c# language?
I am working on pdf creator in Asp.net with c#. In my code it created a pdf file and after that i use flush, close and dispost the streamwriter and in the nest function i am opening the same file in the next function i am opening this same file to show in browser pdf viewer. my pdf creation method is used threading and pdf reading function is in normal mode function.
My question is that how to check that this pdf file is use in another process in c# code? Because if i have created very small pdf file it will works fine but if i am creating a pdf file of 5-10 pages in that case it will throws error. i.e. `the process cannot access the file because it is being used by another process`
I want to use check the process monitor code on that file and how to explicitly kill that process?
|
If you are starting process that creates PDF, just wait for it and check exitcode, of course if the process that creates PDF return proper exit codes for success or some error, here is some example code :
Process proc = Process.Start("createpdf.exe", "params");
proc.WaitForExit();
int result = proc.ExitCode;
/// do something based on result
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net, file, c# 4.0, file io"
}
|
How do you read URLs from a .txt file to perform requests.get and save the responses to a file?
I am able to save the response of a single URL but I have a list of URLs in a .txt file and would like to print the all the responses. How can I read the URLs from the .txt file and save the responses in python?
This is what I currently have. Thanks!
import requests
data = requests.get('www.url.com')
with open('file.txt', 'wb') as f:
f.write(data.text)
|
you first want to read the urls from a file 'infile.txt', then iteratively send the requests and write the data to an outfile 'outfile.txt'.
with open('infile.txt', 'r') as f:
urls = f.readlines()
datalist=[]
for url in urls:
data = requests.get(url)
datalist.append(data.text)
with open('outfile.txt', 'w') as f:
for item in datalist:
f.write("%s\n" % item)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, database, file, get, python requests"
}
|
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table? I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio. But SQLCMD is always an option.
UPDATE: I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime. Is there something else I am missing with sp_help?
Here is what I call:
sp_help airports
Note that I really do want the DDL that defines the table.
|
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'
SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
|
stackexchange-stackoverflow
|
{
"answer_score": 149,
"question_score": 132,
"tags": "sql server, tsql"
}
|
How to generate the file names as follows?
Suppose I have two variables called `var1` and `var2` which can have arbitrary values. I use them in a toy example as follows
val1 = 0.001;
val2 = 500;
f[x_] := val1 + 10 x/val2;
p1 = Plot[f[x], {x, 0, 10}, PlotLegends -> "plot 1"];
Export["name.PNG", p1]
Since I have to change the values of `val1` and `val2` each time, I intend to write an appropriate code for naming the exported file name so that it is not necessary to name it manually. For example I want to use a combination of a constant string ("plot_function" for example),`val1` and `val2` for naming the file as follows:
file name="plot_function"_val1_val2
In fact I look for a general way to generate a string composed from different identities (in this case variables and strings) which can be used as argument of Print[] or naming an file and etc. I tried `ToExpression[val1]` but I have no idea how to proceed?!
|
I would use a `StringTemplate` for this,
In[46]:= StringTemplate["name_`1`_`2`.PNG"][val1, val2]
Out[46]= "name_0.001_500.PNG"
|
stackexchange-mathematica
|
{
"answer_score": 7,
"question_score": 2,
"tags": "export"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.