INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
What happens when auto number reaches its pre-set max?
I have a standard field that I have assigned the following Display format "A-{0000}". What happens when it reaches A-9999? I'm not able to find the answer online and I want to make sure it does not restart. I need this to be a unique field.
|
I just created a custom object using an Auto Number Display Format of `T-{0}` and names like `T-10` and `T-11` were created.
So looks like no restarting, with the formatting expanding as you might expect for the numbers that use more characters than specified by the format.
**PS**
And there is this Salesforce Knowledge Article on the subject stolen from DerekF's comment: Effects when auto-number field exceeds the specified digits.
|
stackexchange-salesforce
|
{
"answer_score": 5,
"question_score": 3,
"tags": "auto number"
}
|
md-select same object in ng-option and ng-model
Is it possible to use same json object in ng-option and ng-model of md-select?
> Here I'm using Angular Material md-select instead of HTML Select
**Controller:**
$scope.languages = [
{ name: 'English', value: true },
{ name: 'English', value: false }
];
**View:**
<md-select ng-model="languages"
placeholder="Select"
class="select-dropdown md-no-underline"
multiple>
<md-option ng-value="language.value" ng-repeat="language in languages">
{{language.name}}
</md-option>
</md-select>
|
It is so because when you `select` or `un-select` the list items from your `md-checkbox` it alters the list from which `ng-repeat` is getting values. You need to maintain the selections in another variable.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "angularjs, angularjs material, md select"
}
|
Webdriverio element needs to be type of string?
Webdriverio element needs to be type of string?
My code is as followed:
describe('Test Contact Us form WebdriverUni', function() {
it.only('Should be able to submit a successful submission via contact us form', function(done) {
browser.pause(5000);
var firstNameTextField = $("[name='first_name']");
var firstNameTextField = "[name='last_name']";
browser.setValue(firstNameTextField, 'Joe');
Using the following code: var and $, I seem to be receiving the following exception: 'element needs to be type of String'.
Also the following fails with the same exception:
var firstNameTextField = browser.element("[name='last_name']");
However the following works:
browser.setValue("[name='first_name']", 'Joe');
Any ideas?
|
You see, webdriver setValue takes a selector that must be for type String.
When you use this piece of code: `var firstNameTextField = $("[name='first_name']");` you are getting an object, not a string.
When however you call it like that: `browser.setValue("[name='first_name']", 'Joe');` you are providing a selector of type String. And it works.
So, you should probably change your variable to `var firstNameTextField = "[name='first_name']";`
EDIT:
I also noticed you are using the same variable name twice here:
var firstNameTextField = $("[name='first_name']");
var firstNameTextField = "[name='last_name']";
Shouldn't the second one be lastNameTextField?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, selenium webdriver, webdriver io"
}
|
Storing previous event.target.id in a variable
I am in a situation where I need to keep track of the previously clicked event.target.id that is firing the click event.
A very simple example of my code is as follows (I am using dojo and jQuery):
on(dom.byId("div-tools-draw"), "click", function (evt) {
var lastActiveTool = evt.target.id;
}
This code keeps overwriting the lastActiveTool variable with the current event id. However, I need a way to keep track of the previous one.
Sorry if this is a silly question, I am still learning JS.
|
var lastActiveTool;
on(dom.byId("div-tools-draw"), "click", function (evt) {
//do whatever you want with previous value if there is one
lastActiveTool = evt.target.id;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, dojo"
}
|
Get periods without cover by another periods
I Have Db Entity which looks like:
TimeEntity {
public DateFrom {get; set;}
public DateTo {get; set;}
}
 && ctx.Periods.Any(p2 => p2.DateFrom > p.DateTo)
select p;
var gapPeriods =
from p in withoutAdjacent
select new TimeEntity
{
DateFrom = p.DateTo,
DateTo = ctx.Periods.Where(p2 => p2.DateFrom > p.DateTo).Min(p2 => DateFrom)
};
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, entity framework, linq, entity framework core, entity"
}
|
Is it possible to configure User.current in origen-sdk?
As I started running Origen on WSL Ubuntu, I realized that my User ID was incorrect vs what was expected when I tried to use API that required a login. This was due to how I named my WSL username. I see the Origen docs can handle LDAP, is there a way to configure my local copy or Origen to use another username?
thx
|
fix implemented in an impending pull request...
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "origen sdk"
}
|
Is an elliptic curve a function?
I am currently reading the book Analysis 1 from Terence Tao. The way he defines a function says that it should pass the vertical line test. Sometimes ago I came across an elliptic curve and saw that it doesn't pass the vertical line test. Is the elliptic curve a function ?
|
No, it's not a function. The definition of an elliptic curve is the set of all points such that $y^2 = x^3 + ax + b$. That is, $E_{a, b, c} \equiv \\{ (x, y) : y^2 = x^3 + ax + b \\}$.
Let a solution $(x_0, y_0) \in E_{a, b, c}$. then by definition $y_0^2 = x_0^3 + a x_0 + b$,. So, $(-y_0)^2 = y_0^2 = x_0^3 + ax_0 + b$. Therefore, $(x_0, -y_0) \in E_{a, b, c}.$ Hence, this will fail the vertical line test at $x = x_0$.
That is to say, an elliptic curve cannot be a function.
### Some pictures of elliptic curves to see the symmetry along the $x$-axis:
. Always bulkify triggers, flows, etc. You never know when you'll need it.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 0,
"tags": "trigger, database, emailmessage, email2case"
}
|
JavaScript for Project Euler problems
I am trying to solve Q10 from Project Euler. I am using JavaScript and Sieve of Atkins algorithm to solve the problem. When I run the code on browsers(Safari and FF) the browsers prompts that the script is unresponsive. Even if I let the script to continue I never got the answer. I know there are threads for the same Project Euler problem.
My questions would be:-
1.How far JavaScript is capable to solve such complex mathematical problems for browsers?
2.Is there any other environment where I can I test my JavaScript programs?
Thank you All.
|
1. I would have thought as capable as any other - JavaScript implementations have been optimised a lot in recent years thanks to increased used in the web.
2. You can use either node.js or CScript (a command line version of the Windows Script host - this is supplied as part of Windows).
If I remember my implementation of that question (in Python) was significantly slower than I thought it would be. The chances are the slowness is due to your algorithm rather than the language.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "javascript"
}
|
How to store an array which is dynamic in an class by instantiating once
Using VB.NET we can store values to array or list in a class which is a public variable and using constructor. Can I do same thing using using vba
Ex:
class Class1
{
public string Variable1 { get; set; }
public string Variable2 { get; set; }
public List<string> List1 { get; set; }
public Class1()
{
Variable1 = string.Empty;
Variable2 = string.Empty;
List1 = new List<string>(0);
}
}
I want to replicate this in vba.
|
Just inserrt to your project `Class Module` (note that name of this module will be name of your class as well!):

Var1 = ""
Var2 = ""
Set Collection1 = New Collection
'MsgBox "Instance created!"
End Sub
Then the usage would like this:
Sub test()
Dim c As Class1
Set c = New Class1
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, vba"
}
|
The crate "pallet-contracts-rpc" does not exists for the branch "polkadot-v0.9.31". Is there any replacement?
Branch(polkadot-v0.9.31) <
Branch(polkadot-v0.9.30) <
Since for the branch "polkadot-v0.9.30" the pallet-contracts-rpc was there. I would like to upgrade my outer node file rpc.rs to accommodate the branch "polkadot-v0.9.31". please.
I tried to search in the release notes but I was not able to find anything about this.
Cheers,
|
Have you checked this PR?
I think that checking the files it changed you'll be able to update accordingly.
|
stackexchange-substrate
|
{
"answer_score": 1,
"question_score": 1,
"tags": "polkadot, smart contract, contracts"
}
|
How to tell if a string contains characters in Hebrew using PHP?
Trying to figure out how to tell whether a string contains _any_ characters in Hebrew with no luck.
How can this be done?
|
_If_ the source string is UTF-8 encoded, then the simpler approach would be using `\p{Hebrew}` in the regex.
The call also should have the `/u` modifier.
= preg_match("/\p{Hebrew}/u", $string)
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 8,
"tags": "php, regex, hebrew"
}
|
Releasing synthesized property after alloc init
i have a property
//.h
@property (nonatomic, retain) SomeCLass * someSynthInstance;
//.m
@synthesize someSynthInstance = _someSynthInstance;
- (void) foo
{
self.someSynthInstance = [[SomeCLass alloc] init];
//[self.someSynthInstance release]; <- SHOULD I RELEASE HERE???
}
- (void) dealloc
{
self.someSynthInstance = nil;
}
my theory goes, that [alloc, init] creates a count of 1, and the setter, inc that count, so it becomes 2, therefore i should release it, right after
but aim getting exc_bad_access in the application after i changed everything like this, so aim not sure if its ok
|
you want to be releasing the instance variable rather than the property. so you can do either:
self.someSynthInstance = [[[SomeCLass alloc] init] autorelease]; // puts it in the autoreleasepool so it'll get released automatically at some point in the near future
or
_someSynthInstance = [[SomeCLass alloc] init]; // skip the property
or
self.someSynthInstance = [[SomeCLass alloc] init];
[_someSynthInstance release]; // call release on the instance variable
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "objective c"
}
|
Why does getSignatureStatuses always return null?
I want to build a nice ui that shows the current status of a transaction counting up the confirmations up to 31.
For some reason I am not getting a result. Any ideas what I am doing wrong?
The json I am sending to the RPC.
> {"method":"getSignatureStatuses","params":[["3EKVxNaGsuZBm24Kb33exdbB3uy3XTGv5GbuLYhmmZifrQpEka3PEhNZs2m8gbLWBHo3TLMLsxM8QjabW3tuDkXs"]],"jsonrpc":"2.0","id":0}
The result I am getting
> {"jsonrpc":"2.0","result":{"context":{"apiVersion":"1.10.29","slot":141942914},"value":[null]},"id":0}
I can use getSignaturesForAddress, which works, but it seems a bit of a waste and does not show me the confirmations either.
|
`getSignatureStatus(es)` only searches the so-called `StatusCache` by default. This cache contains all processed transactions that have not yet been finalized. This default behavior is intended to provided the quickest reply to the request.
The methods can optionally request that transaction "history" be searched, which will look in both the local ledger, and if available a deep ledger history store like BigTable.
Something like this should work, assuming the block including the transaction has not been pruned from the local ledger or deep history is available.
{
"method":"getSignatureStatuses",
"params":[
[
"3EKVxNaGsuZBm24Kb33exdbB3uy3XTGv5GbuLYhmmZifrQpEka3PEhNZs2m8gbLWBHo3TLMLsxM8QjabW3tuDkXs"
],
{
"searchTransactionHistory":true
}
],
"jsonrpc":"2.0",
"id":0
}
|
stackexchange-solana
|
{
"answer_score": 2,
"question_score": 2,
"tags": "transactions, jsonrpc api"
}
|
Use ArrayList or List in method parameter list
Hi I am wondering if it is better to use list or arrayList as a method parameter?
for example -
public static void calculate(List<T> list) {}
or
public static void calculate(ArrayList<T> list) {}
I was thinking that it was better to use List because it gives you more options to use a linked list or whatever... but if I am wrong could you tell me why ArrayList is better or why List is better?
Thanks
|
Code to interfaces, code to interfaces, code to interfaces.
What if someone wanted to use your API but pass a different sort of List? Or even not a list at all, but a Collection? Use the most generic interface your API requires.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, list, methods, arraylist, parameters"
}
|
How can i get the data from an http link in PHP?
I have a link, that when opened in a Browser, shows some information in form of text: < Now, I want to use the data, that would be displayed in the Browser on my Website. In the end, I want this to be seen on MY website: { "username": "SpigxtPlugins", "live": false, "age": 573 }
The returned value of the link in the Browser.
|
You can use the following any method:
1. file-get-contents function of php and then use json_decode.
2. Use the curl in php.
Here is the link to know how to decode the json data: json-decode.
Hope the links given here will be helpful to you.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, html"
}
|
Word VBA: How to determine a document newly created and modified?
Does anybody know in Word VBA how to determine:
1. A document is newly created;
2. A document is modified by the user?
I found the Document.Saved property, but it does not help in my case.
Thank you so much!
|
`Document.Path` \- if it is an existing document as against a new one.
What do you mean by "it does not help..."?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "vba, ms word"
}
|
Right To Left text in mono windows forms
I Opened my .net project in monoDevelop to use it on Linux. It works. But I cannot view Arabic fonts in Controls Text in a good format on Ubuntu. I view reverse letters from Left to Right. But Arabic is Right to Left. I changed the font to Tahoma and I used Right to Left Layout but it doesn't work. Just Arabic text in title bar looks good. But Button, Label, TextBox and others have same problems.
What can I do?
|
<
As explained by @Rafael Teixeira, "WinForms in Mono is not actively maintained by the core team anymore, but if volunteers do come forward with well-tested contributions as pull requests these can be merged in...".
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#, .net, winforms, ubuntu, mono"
}
|
Lasagne - Why is the Validation Loss Highlighted Green?
I'm running the MNIST Neural Network example and when training the classifier, the Validation Loss column (and training loss) has some values highlighted in green. If i have the learning rate at 0.01, all are green, however if i increase it to 0.1, only half of them are highlighted.
What does this highlighting mean if anything?
Output example:

* train-loss blue
* val-loss green
* Stop coloring when loss / validation did increase
* Don't start coloring again after this one-time increase
Different learning-rates will effect in different train-loss / val-loss paths and therefore some possible different coloring.
Your example fits well there, as a lower learning-rate is usually more stable (from iteration to iteration) in regards to lowering the loss (more blue, more green).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, neural network, lasagne"
}
|
Переменные MySQL и оператор IN
Как сделать так, чтобы оператор `IN` нормально воспринимал данные которые содержатся в переменной `@ids`?
SELECT @ids:= 63,62,12,243,237;
SELECT * FROM talbe_name WHERE id IN (@ids);
|
Неужели вывод команды `SELECT @ids:= 63,62,12,243,237;` не навел на размышления и не вызвал желания вывести полученную переменную на экран?
И даже неработающий запрос не вызвал желания вывести переменную на экран?
При любых проблемах с кодом программист **обязан** проверять содержимое всех переменных.
Для текущей постановки задачи цифры надо заключить в кавычки, а `IN` заменить на `FIND_IN_SET()`.
Но скорее всего исходная задача решается вообще по-другому, а для этого надо знать, откуда она взялась, но это уже будет отдельный вопрос.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "mysql"
}
|
Is there any way to connect Bitbucket with SonarQube using githook to automatically check pull requests without Jenkins/Bamboo?
I want to connect Bitbucket server (4.14) with SonarQube (6.3.1) to launch a sonar execution when any user create a pull request in Bitbucket.
Is there any way to connect Bitbucket with Sonar and launch the Sonar build scan using githook?
> I know that that the best practice is to launch Sonar from Bamboo or Jenkins but I need a workaround before my company updates Bamboo for support pull request feature.
Thanks!
|
You could try out the SonarQube Stash (BitBucket) plugin.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "sonarqube, bitbucket, githooks, sonarqube scan"
}
|
time format for cat output in r
I am writing to a text file using `cat`
mytime <- structure(
1465667039,
class = c("POSIXct", "POSIXt"),
tzone = "UTC"
)
sink("text.txt")
cat(mytime)
sink()
The output is `1465667039`. I want format as `("%Y-%m-%dT%H:%M:%S", tz = "UTC")` and the output should look like `2016-06-11 17:43:59`
|
Using `as.character(mytime)` makes desired output.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 3,
"tags": "r, date, time"
}
|
What first name for Brizendine surname is shown in this tax record?
I'm looking at the Charlotte County Personal Tax records for 1798 (paywalled) as shown in this image:
, second is Isaac Junior, third is Joshua, but the fourth male is unclear to me. I think it begins with an `I` or a `J` and it appears to be a short name, maybe John?
Here is a close up image of the name:
+(n^2+2)+\cdots +(n^2+n)=(n^2+n+1)+(n^2+n+2)+\cdots +(n^2+2n).\tag{1}$$ This can be done by using the usual formula for the sum of an arithmetic progression.
Maybe simpler is to note that the first term on the right of (1) is $n$ more than the **second** term on the left of (1). And the second term on the right of (1) is $n$ more than the **third** term on the left of (1), and so on.
So the sum of the $n$ terms on the right of (1) is $n^2$ more than the sum of the last $n$ terms on the left of (1). But the first term on the left of (1) is $n^2$. This completes the proof.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 6,
"tags": "sequences and series, arithmetic"
}
|
GFCI outlet goes from red to green randomly
I have GFCI outlets that I occasionally catch glowing red, and they seem to change to green almost instantly shortly afterward. I also finally caught one in the act of going from green to red to green where the red phase lasted for just a second. I just wanted to understand if there is anything of concern with these outlets? They seem to work fine but and they trip when I press Test (light goes out completely), but I can’t seem to find anything online about the light cycling from green to red to green again
|
I would guess that it's a newer GFCI outlet that does self-checks on a regular basis, and I would guess that the brief flashing red indicates that it's doing its self check.
|
stackexchange-diy
|
{
"answer_score": 3,
"question_score": 0,
"tags": "gfci"
}
|
Blocking eternally on Unix
I have a process that does nothing, it just needs to exist to stop a process group ID being reallocated to a new process.
I'm doing this, but wonder if there's a more canonical way to eternally sleep:
loop {
sleep(60 * 60 * 24 * SECOND);
}
|
`pause()` is the answer I was looking for. Thanks for the pointer @darnir!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "unix, portability"
}
|
Merging two columns of fields in MySQL
> **Possible Duplicate:**
> Merge date from one datetime and time from another datetime
How can I physically merge two MySQL column/fields into one column/field without losing any data on it
Specifically I will be combining a DATE and TIME column/field
thanks
|
Add your timestamp field, initialize it with the `timestamp` function, and then once you feel safe, drop the old columns. Something like this:
alter table your_table add timestamp_column timestamp;
update your_table set timestamp_column = timestamp(date_column, time_column);
-- Pause and make sure everything is okay.
-- Take your time, the database will wait.
alter table your_table drop column date_column;
alter table your_table drop column time_column;
alter table your_table modify timestamp_column timestamp not null;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql"
}
|
How to deploy a folder containing .cs extensions which are not part of the project
I'm trying to deploy a portable version of Python with a C# Winforms desktop app and the portable folder contains files with extension .cs which are for Python (part of Tk Interface Extensions I think). In the VS editor I get lots of `Preprocessor directive expected` errors as it believes those files are part of the project.
Essentially everything inside `\tools\` is not part of the project but needs to be copied to the project directory `ProjectFolder\tools\Portable Python 3.2.5.1\.....`
Is there a way to get VS to ignore the folder but still copy the entire contents using `Copy to Output Directory`?
Is there a better way to do this?
|
Open up the properties for that item.
1. Change the build action from "Compile" to "Content".
2. Change "Copy to Otuput" from "Do no Copy" to "Copy if newer" (or copy always, if you really want that).
So it'll go from this:
!enter image description here
to this:
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, winforms, visual studio 2010"
}
|
REGEX (javascript) - Allow alphanumeric characters with special characters not in the first position
I'd like to devise a regex expression that allows alphanumeric characters, as well as other characters as long as they're not in the first position. Examples:
VALID: Test
VALID: Hello123
VALID: 456 Hi
VALID: 456-789
VALID: Hi-777
VALID: 333-Hi
VALID: Hello-There
VALID: What's Up
VALID: Hello#Goodbye
INVALID: -Hello
INVALID: &Goodbye
Here's my starting point, which only allows alphanumeric:
/[a-zA-Z]+/
|
Use `^[A-Za-z0-9]` to require an alphnum character in the first position (immediately following `^`, the start of the string), followed by whatever else you need.
# Specific set permitted -- add all the characters you need...
/^[A-Za-z0-9][A-Za-z-9, +-_&#'"]+$/
# Or anything permitted after the first position
# Use .* instead of .+ if a single character string is permissible.
/^[A-Za-z0-9].+$/
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, regex"
}
|
Can a player replace their pre-generated character with a new character they create, partway through an adventure?
I'm a new DM playing Lost Mine of Phandelver with two other adults and our kids, two 11-year-olds. We started with the pre-generated characters; I'm playing the Dwarf cleric as an NPC.
One of the kids is very interested and wants to create their own character: a Dragonborn ranger with a snake for an animal companion. However, they _really_ don't want to give up the coins, items and EXP they've collected thus far. We'll finish with Tresendar Manor soon and reach level 3.
Would it go against all DM standards/etiquette/etc. to let someone substitute their own character for a pre-generated one midway through an adventure and keep everything if their level is still quite low?
|
## If everyone at the table is ok with it, there's nothing wrong with letting a player have a new character.
Everyone is meant to have fun in these games, and if a player would have more fun with another character, then there is no downside for letting them change except other players being annoyed at it.
There are two ways to handle the changing out of a character - an in-character swap or an out-of-character swap. The in-character swap would require the party going to a town or outpost or similar, and the player's existing character parting ways and the party accepting a new member. In this case the money and items would probably have to be "given" to the party. The out-of-character swap would just be swapping the character and everyone agrees to ignore that any swap happened.
Balance-wise, there shouldn't be any issues with the new character being the same level as the other characters.
|
stackexchange-rpg
|
{
"answer_score": 50,
"question_score": 22,
"tags": "dnd 5e, new gm, player characters, lost mine of phandelver, kids"
}
|
Why does an empty list that is passed to a razor view in ASP.NET MVC Core become null?
Imagine a controller action like:
public async Task<IActionResult> Ask()
{
...
ViewData["MyItems"] = Enumerable.Empty<MyItem>();
return View();
}
And a view like:
@{
var myItems = ViewData["MyItems"] as IEnumerable<MyItem>
}
@foreach (var item in myItems) <-- this throws null reference exception
{
<div>@item.SomeProp</div>
}
|
I forgot to add the following import statement to my view (or to _ViewImports.cshtml) that provides the `IEnumerable`:
@using System.Collections.Generic;
I am using Visual Studio Code and it does not have intellisense on Razor views to warn me about it. You be careful out there; Razor views without intellisense is like walking in a cemetery at night!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "razor, asp.net core mvc"
}
|
Is DbContext an expensive operation?
In C# MVC EF framework, I saw lots of examples that simply creates a new `DbContext` whenever a insert or query is needed, and then close/release it (many use the "using" for auto close/release).
Did some search on this but couldn't find a good answer, but is creating a `DbContext` a very cheap and fast operation?
For example, thinking about a typical MVC application, on the page it has many "components", such as headers, sider bars, main content, etc., and in a non-trivial setup, each component will have its own individual logic and code -- do I suppose to create a new `DbContext` in each of these components? (if yes, will the system auto cache the query result? -- for example, an common use case is that, in each of these component, it needs to query the database for current site wide settings, which is the same row in a table).
|
As noted in "Performance Considerations for Entity Framework 4, 5 and 6" section 9.3 (emphasis mine):
> Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. **Contexts are expected to be short lived and discarded** , and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. **Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts**.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 17,
"tags": "c#, asp.net mvc, entity framework"
}
|
Facebook: Quick Start for App Links Hosting API. Edit existing App links
In Facebook: If I use the "Modify an existing App Link URL". How can I see my existing App Links or do I have to remember the links myself?
Regards
|
Try this tool instead: <
It allows you to add/update/remove app links host urls.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "applinks"
}
|
Compiler check to ensure I'm running in bare-metal and not in a hosted environment
If I'm compiling a C program for bare-metal, I know I can insert things like
#if defined(__linux__)
#error "You're not using a cross-compiler."
#endif`
But, I don't want to check for every operating system. Is there a single check to see if I'm in a hosted environment?
|
If you want to determine that you are building with `-ffreestanding` then make your code check for the `__STDC_HOSTED__` macro. It will be set to 1 for normal code and set to 0 for a freestanding build.
See the GCC info pages or the docs. The relevant quote is
> By default, it acts as the compiler for a hosted implementation, defining ' **STDC_HOSTED** ' as '1' and presuming that when the names of ISO C functions are used, they have the semantics defined in the standard. To make it act as a conforming freestanding implementation for a freestanding environment, use the option '-ffreestanding'; it then defines ' **STDC_HOSTED** ' to '0' and does not make assumptions about the meanings of function names from the standard library, with exceptions noted below.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c, compilation, cross compiling, bare metal"
}
|
Get number after character from string?
I have this function , that check if the input is like that `d1,d7,d65,` etc - means it starts with a "d" and then has a number .
I would like to check if its the structure , then return the number **after the d**.
Whats the most efficient way to do so ? can it be done using `scanf` only ?
|
You can use `sscanf` and check the return value, if it returns 1 then an integer has been read successfully (via `%d`) - and that matches the format you need; otherwise `t` does not have the desired format.
* * *
int read_fmt( char t[], int *n )
{
return sscanf( t, "d%d", n );
}
int main ()
{
char t[] = "d8787";
int n = 0;
if( read_fmt( t, &n ) == 1 )
{
printf( "correct format, n = %d\n", n );
}
else
{
perror( "incorrect format\n" );
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c"
}
|
Comprehending the proof that continuous functions on closed intervals are bounded
Let $f$ be a continuous real-valued function on a closed interval [a,b]. I am misunderstanding a part of the proof of that continuous functions on closed intervals are bounded
Proof: Assume that f is not bounded on [a,b], then to each $n \in \Bbb N$ there exists an $x_n \in [a,b]$ such that $|f(x_n)| > n$. By Bolzano Weierstrass some subsequence of $x_n$, say $x_{n_k}$ converges to some real number $x_o$ which belongs to [a,b]. Since $f$ is continuous at $x_o$ then $lim f(x_{n_k}) = f(x_o)$, but $lim |f(x_{n_k})| = + \infty$, which is a contradiction, thus $f$ is bounded.
I need clarification why $lim |f(x_{n_k})| = + \infty$ since the existence of an $n \in \Bbb N$ such that $|f(x_n)| > n$ does not guarantee an existence of an $N \in \Bbb N$ such that for any $M > 0$ and $k>N$, $|f(x_k)| > M $ (the definition of a limit converging to infinity)
|
Observe that you actually have
$$|f(x_1)|>1\,,\,\,|f(x_2)|>2\,,\,...|f(x_{100})|>100,...$$
Now, who knows what happens with the _infinite sequence_ $\;\\{x_n\\}\subset[a,b]\;$ , but by B-W theorem it has a convergent subsequence $\;x_{n_k}\xrightarrow[k\to\infty]{}x_0\;$ , and $\;x_0\in[a,b]\;$ because of closedness and
finitiness. Again, here you have $\;|f(n_1)|>n_1\;,\;\;|f(n_2)|>n_2>n_1,...$ etc.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "calculus, analysis"
}
|
How to set superscript for expandable parentheses?
The following code compiled with error:
\documentclass{report}
\usepackage{chemfig}
\begin{document}
\schemestart
\chemfig{R-C(=[:60]O)-[:-60]O-H}
\arrow{<=>}
\chemleft[\chemfig{R-C(=[:60]O)-[:-60]O}\chemright]^{-}
\+
\chemfig{H^+}
\schemestop
\end{document}
I'd like to place that minus sign on the upper right corner of the right parenthesis.
|
If you put the corresponding formula inside a `\subscheme` it will get a node name that you can refer to from another tikzpicture with `remember picture,overlay` for which `chemfig` has the shortcut `\chemmove`. Then you can add anything anywhere:
\documentclass{article}
\usepackage{chemfig}
\begin{document}
% \schemedebug{true} % look up and visualize the nodes and node names
\schemestart
\chemfig{R-C(=[:60]O)-[:-60]O-H}
\arrow{<=>}
\subscheme{\chemleft[\chemfig{R-C(=[:60]O)-[:-60]O}\chemright]}
\+
\chemfig{H^+}
\schemestop
\chemmove[red]{
\node[right] at (c3.north east) {top right} ;
\node[right] at (c3.south east) {bottom right} ;
\node[left] at (c3.north west) {top left} ;
\node[left] at (c3.south west) {bottom left} ;
}
\end{document}
,(0,2))}$ range
 name:kReachabilityChangedNotification object:nil];
My question is: Do I have to import this class and the above notification to all the other views as well? Whats the best approach to detect internet connection everywhere in the app?
|
Register this in your data manager class (if you have any) So everytime there is a change datamanager is notified and it can then hand it over to a place you can easily handle it (perhaps a an alert view popup or etc). If you dont have any datamanager class. put this in appdelegate & keep a boolean variable isReachable, so you can check this everytime you make a request.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, nsnotificationcenter"
}
|
Connecting a sign-up page to payment gateway page
I have a signup page, which allows user to provide his information like (name, address, dob, sex, ph # etc etc)
Once the user gives out this info, it gets stored into a MYSQL DB table and the page gets forwarded onto a second page where user can select from the available subscription packages and add them into paypal payment gateway..
This all works now, except that right now there is no way of knowing on whose behalf payment was made except the billing address they provided on payment gateway page which could be different from what they gave at sign up page..
How can i link these pages?
Thanks for help
|
Do you store the billing address as well?
One design you can do is; after signup you store a unique id into a SESSION variable. The unique id can be the id where you store the data from the signup page. Once the user goes to the subscription page and enter their billing address you can either store the billing address in the signup table based on the unique id in the SESSION variable. In that way it will link both the signup record to the billing address
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, payment gateway"
}
|
How to sync Oracle database with SQL Server database other than linked server and SSIS..?
We have an Oracle database for some third party application. But I want sync some data from there to our application which is using a SQL Server database.
Currently using linked server and a SQL Serve Job which will run once every hour, so that data will get refreshed in the SQL Server database. But now we need live sync i.e. when something changes in the Oracle database, those changes need to be synced instantaneously with SQL Server rather than waiting for the SQL Server job to run.
So how can I achieve this? Is there any third party tools (cheap and best in terms of pricing, or if it's open source then good) which will detect and do the changes when changes happen in Oracle database?
|
Have a look at Oracle Data Integrator.
See: <
It has an example doing exactly what you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql server, database, oracle, synchronization"
}
|
Can I "use" Java 8 with Android Development now?
I currently have Java 7 JDK installed. It's been like that for awhile. However, recently, my professor is instructing the class to uninstall Java JDK 7 and install Java JDK 8 instead to be able to work on homework and such.
I've been using Java JDK 7 to write and deploy Android apps without any problems so I'm wondering if it's safe to make the upgrade now the JDK 8? I'm assuming that I won't be needing any Java 8 specific methods or functions in my Android development. So if I stay away from that, will my Android development be at all affected?
On a side note, I haven't been able to find any official documentation that states whether or not Java JDK 8 is safe or not or how to make it safe. Either way, I'm going to have to upgrade to Java 8 soon...
|
If you've been using Java 7 to deploy Android apps then it's certain, up to this point, you haven't used any Java 8 features so I don't see how it would matter.
Follow your instructor's directions and when you do an assignment for school simply select either the JDK or Language Level in the Project Structure.
`CTRL` \+ `ALT` \+ `S`, select `Project`
You can default to the Java 8 SDK but limit it to Java 7's features for your Android apps. Or you can simply set your homework projects to the Java 8 SDK.
_Going out on a limb here assuming Android Studio includes the core settings of Intellij._
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 14,
"tags": "java, android, java 8"
}
|
How to manage application when orientation changes?
I have an application in which I am changing screen orientation. But when I change orientation for the first screen and go to the next screen, the change does not persist.
Attached are images for clearer understanding.
!first screen of view in portrait mode !first screen of view in landscape mode
!second screen of view in landscape mode !second screen of view in portrait mode
The main problem is that when device is rotated then first screen rotates but second does not launch in the new orientation.
It will rotate only when we change orientation after the screen is launched.
How do I fix that?
|
The problem is that when you rotate the device then
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
Method gets called but when you go to the next screen then this method does not get called. if you rotate your device again then that method gets called.
So if you want to change next screen orientation as device current orientation, then check the device's current orientation with `viewDidLoad` method or `ViewWillApper()` method. Then according to that set your current view.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "iphone, uiinterfaceorientation"
}
|
Removing information boxes from google map
I have a google map and I want to remove white info boxes (1 and 2 in the image below). I have tried the following css:
.place-card {
display:none
}
but it doesn't seem to work.

>
> 2. Store packages, pricing, & release dates > click package title > "Edit Package Name" on the right side of this page
>
> 3. Edit Steamworks Settings > Application > under "Application Name and Type"
>
>
|
stackexchange-gamedev
|
{
"answer_score": 61,
"question_score": 58,
"tags": "steam"
}
|
Orchard CMS content item's type could not be changed programmatically
I created a content item's instance as follows:
ContentItem ci = _orchardServices.ContentManager.New("ContentTypeA");
_orchardServices.ContentManager.Create(ci, VersionOptions.Published);
ci.As<SomeContentPart>().SomeAttr = value;
...
_orchardServices.ContentManager.Publish(ci);
In another method I need to change it's content type, and I tried the following without success:
ci.TypeDefinition = _contentDefinitionManager.GetTypeDefinition("ContentTypeB");
ci.ContentType = "ContentTypeB";
When I query the Content Item again, its content type is still "ContentTypeA" instead of "ContentTypeB".
Any ideas?
|
Once a content item has been created, you can't change its content type. Well, in theory you could hack into the database and make it work, but it seems like a much better use of your time to just create a new item and copy the data.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net mvc 4, orchardcms"
}
|
Unity 3d & C#, if gameObject != this
I have this code:
public class Gravity : MonoBehaviour
{
GameObject[] planets;
// Start is called before the first frame update
void Start()
{
planets = GameObject.FindGameObjectsWithTag("Planet");
}
// Update is called once per frame
void Update()
{
foreach (GameObject planet in planets)
{
if (planet != this)
{
//do things
}
}
}
}
I have a problem with "if (planet != this)..." what I expect to occur is that if planets[index] == the gameObject then "planet != this" will return false. But this is not working, how can I fix it?
|
`this` is a keyword which referes to the instance of the current object, in this case a `Gravity` class, so each `GameObject` object is different from a `Gravity` instance. You can do something like this, to access the attached `GameObject`:
foreach (GameObject planet in planets)
{
if (planet != this.gameObject)
{
// Do magic stuff...
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, unity3d, if statement, this"
}
|
Checking existence of lazy loaded child without getting/loading in Fluent NHibernate
This should be easy, but I can't seem to figure it out... How can I check if a child on an entity exists without actually getting or fetching it? The child is lazy loaded right now..
so I have two entities:
class A
{
public virtual int Id { get; set; }
public virtual B Child { get; set; }
}
class B
{
public virtual int Id { get; set; }
public virtual byte[] Blob { get; set; }
}
I want to check for existence of B in an instance of A without actually fetching the large blog... In straight sql I could just check to see if child_id is not null... Is there some way I can query the NHibernate Proxy of B in A?
Thanks!
|
nm - one can just check for a null value. Only if a child exists will there be a proxy.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "nhibernate, fluent nhibernate, proxy, lazy loading, parent child"
}
|
Node.js Accessing parent modules
I am working on a CMS system for Node.js, I have a quick question for those Node.js Pro's
I am creating modules and requiring modules within those modules, but if I have already included this module in the parent module, can I access those required modules?
For Example:
main.js
var fs = require('fs');
var sc = require('second.js');
second.js
var fs = require('fs'); // Is there any way to use the parent modules fs object?
It just seems I am including the same modules in some of my sub modules and rather not do that if possible.
Thanks!
|
It shouldn't matter, since Node caches modules when they're first included (i.e. the side-effects of requiring a module won't be executed a second time). You can force this cache to be cleared (and thus re-execute said side-effects) by tampering with `require.cache`.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "node.js"
}
|
Cannot get rid of first column i.e index in pandas dataframe
Im trying to create a csv file from a dataframe that will look like
time, price, vol
178, 310, 10
299, 510, 11
378, 310, 11
my code gives me this
time, price, vol
1 178 310, 10
2 299, 510, 11
3 378, 310, 11
how can I get rid of the first column i.e. Index 1,2,3
test code
import pandas as pd
data = [[1, 4.5,10.6],[2, 8.8,12.7],[3, 2.2,13.8]]
df = pd.DataFrame(data,columns=['time', 'price','vol'])
df.set_index("time")
print( df)
df.to_csv("test.csv")
|
When you save the file, use `index=False` flag, like this:
df.to_csv("test.csv", index=False)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "python, pandas"
}
|
Delay execution of code on keyup except when enter key is pressed
I am using the following `keyUpDelay` function to delay execution of code by 1 second between pressing keys on `keyup`. How can this be altered so that if the enter key is pressed the timer will finish and execute the code immediately.
var keyUpDelay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('input').keyup(function () { // AUTO SEARCH FUNCTION
keyUpDelay(function () {
// code to delay by 1000 ms except if enter key is pressed
}, 1000);
});
|
How about this
keyUpDelay = (function () {
var timer = keyUpDelay.timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
}; })();
$('input').keyup(function (e) { // AUTO SEARCH FUNCTION
if (e.which==13) {
clearTimeout (keyUpDelay.timer);
cb();
return;
}
keyUpDelay(cb , 1000);
function cb () {
// code to delay by 1000 ms except if enter key is pressed
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Popup window in winform c#
I'm working on a project where I need a popup window. But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer.
So basically I have a button and when you click on it it will open another window that I've designed in the form designer.
I've been doing some googling but I haven't found what I needed yet so I was hoping you guys could help me!
|
Just create another form (let's call it `formPopup`) using Visual Studio. In a button handler write the following code:
var formPopup = new Form();
formPopup.Show(this); // if you need non-modal window
If you need a non-modal window use: `formPopup.Show();`. If you need a dialog (so your code will hang on this invocation until you close the opened form) use: `formPopup.ShowDialog()`
|
stackexchange-stackoverflow
|
{
"answer_score": 44,
"question_score": 35,
"tags": "c#, winforms, popup, window"
}
|
PyWinAuto still useful?
I've been playing with PyWinAuto today and having fun automating all sorts GUI tests. I was wondering if it is still state of the art or if there might be something else (also free) which does windows rich client automation better.
|
pywinauto is great because it's Python.
Perhaps a bit more full featured is AutoIT, which has a COM server that you can automate (from Python using win32com), and some cool tools, like a "Window Info" utility, which will give you the text (title), class, size, status-bar text, and so on for the window currently under the mouse cursor.
There are some cases where pywinauto is a bit harder to use than AutoIt, and seems a little less polished. One example is automating Inno Setup programs. The Inno Setup "setup.exe" program launches a separate application that actually performs the install, and it's a pain to track this down with pywinauto, but AutoIt makes it easy.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 10,
"tags": "python, pywinauto"
}
|
Finding a common matrix of several column full rank matrices to make them invertible
Let $p\ge q$, let $A_1,\dots,A_n\in\mathbb R^{p\times q}$ be matrices such that any nonzero linear combination $k_1A_1+\dots+k_nA_n$ is of rank $q$ (column full rank).
Then can we find a matrix $B\in\mathbb R^{q\times p}$ such that $B(k_1A_1+\dots+k_nA_n)$ is invertible for all $(k_1,\dots,k_n)\neq0$?
For a single matrix we can find $q$ linear independent rows so that a submatrix is invertible. But for several matrices we may not find a common linear independent rows.
My original question is to find a way to reduce a over-determined linear elliptic PDE system (the symbol is injective) to a determined linear elliptic PDE system (the symbol is invertible), just by "deleting some rows in the same time". The condition of first order PDE being elliptic is exactly the assumption of first paragraph.
|
Take $p=q=3$ and $n=2$. Then $\det(A_1+k_2A_2)$ is (when $A_2$ is invertible) a polynomial in $k_2$ of degree $3$; consequently, there is $k_2\in\mathbb{R}$ s.t. $rank(A_1+k_2A_2)<3$. Thus your hypothesis (in your second line) does not work for $p=q$.
Thus we must assume that $p>q$.
For example $p=4,q=3$. If we choose $B\in M_{3,4}$ (with $rank(B)=3$ as required), then $\det(B(A_1+k_2A_2))$ is again a polynomial in $k_2$ of degree $3$ and there is $k_2\in\mathbb{R}$ s.t. $B(A_1+k_2A_2)$ is not invertible.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra, matrices, matrix rank"
}
|
How can I search for a specific user on the People administration page?
I can filter by Role, Permission and status on the people page, is there an easy way to search for one specific user?
|
That's all you can do with core Drupal - it is a little frustrating for sure. :-)
However, there are lots of contrib modules that let you do more, such as
* Advanced User, in which user fields to filter/search by can be configured in the module's settings or
* the simpler User search to People Admin which simply puts the user search box on there for you.
Of course, you can also opt to make yourself a user-based view and create an admin page yourself by using relationships and filters. :-)
Hope one of these helps!
|
stackexchange-drupal
|
{
"answer_score": 7,
"question_score": 7,
"tags": "users, search"
}
|
How do I extract ASCII data from binary file with unknown format, in Windows?
On Windows, what is the best way to convert a binary file where the internal structure is unknown less that its contents are ASCII in nature back to plain text?
Ideally the conversion would produce a "human"-readable version. I think the file should contain something like the following:
Date: 10 FEB 2010
House: 345 Dogwood Drive
Exterior: Brick
|
In Linux/Unix:
$ strings < unknown.dat > ascii-from-unknown.txt
This is of course not so much a "conversion" as a straight up extraction, by just filtering out the non-ASCII bytes. It's useful quite often, though.
In general, without more knowledge of the file's internal format, I don't think you can do much better.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 6,
"tags": "windows, binary, ascii"
}
|
Will laravel reconnect to the database for any where on returned model collection?
If we have a find like this:
$returnedModel = Flight::
with("passengers")
->find(1);
Now if I add a where on `returnedModel` like this:
$returnedModel->passengers()->where("name" , "hamid")->first();
Will `Laravel` reconnect to the database for any where on returned model collection?
I added `DB::getQueryLog()` and there is a query with this where! how can I get this without reconnect to database?
|
You need to access your `passengers` as a property, not a method, by the way you get a Laravel collection already loaded from the DB (thanks to the `with` eager-loading).
$returnedModel->passengers->firstWhere('name', 'hamid');
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "laravel, laravel collection"
}
|
Eek! Where did the stylesheets go?
Since half an hour or so, Meta SO (not reproducable on other SE sites) seem to have lost their header and footer part, i.e. all sites are rendered as
<div id="mainbar" class="ask-mainbar">
being the first line of ` This applies to all pages.
Is that just me?
|
Just created this, couldn't resist..
!enter image description here
|
stackexchange-meta
|
{
"answer_score": 9,
"question_score": 6,
"tags": "bug, status completed"
}
|
Local Branch deleted in github
I have a local branch named `mass-communication-rm` and I have pushed the code to that branch but due to some issue I deleted that branch from local and now again I created the branch with same name so if I push code to that branch so what will happen will it create a separate branch or the code will be pushed to same branch.
|
You don't have to create a new branch with the same name. Just checkout to the branch:
git checkout mass-communication-rm
git is smart enough to create a local branch of `mass-communication-rm` if it only exists as remote branch. The local branch is created automatically and it will track its correspondent remote branch.
This is the safest way to get back the same branch as you deleted; AFAIK.
I understand this doesn't answer your original question as in the post, but I think this answers the root cause pushed you to write the post.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "git, github, version control"
}
|
Debug console text in yellow
so when I debug a program on visual studio community 2019, the debug console text is appearing in yellow, would it be possible to change that color to white? (I might have changed it before, but I don't remember how...).
Here is a picture of the output window:  way to get this information?
P.S. the "Published on" information in the app Details page is the date of the last update you published not the first time the app was published in the Store.
|
You are right, there is no such info on this (maybe you can find out only if you are going to browse your DL history graphs). To view this info open your app page on the Store on your Windows Phone Device, you'll find there the info 'originally released'.
Best regards,
Manuel
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows phone"
}
|
Basic Bash - If/Then with Boolean Operator
As you can see I set up a simple script to ping google(8.8.8.8) that should respond back with "Good Ping"
if [ "ping -c 1 8.8.8.8 | grep 64 | cut -c 1-2" == '64' ]; then echo "Good Ping"; fi
But it never responds with its echo statement
At the same time I can run:
ping -c 1 8.8.8.8 | grep 64 | cut -c 1-2
This resolves to '64' without an issue
I don't understand the top script will never print "Good Ping", could someone explain?
|
The string `ping -c 1 8.8.8.8 | grep 64 | cut -c 1-2` is never equal to 64, but that's what you test for. If you want to test a command, use command substitution:
if [ $(ping -c 1 8.8.8.8 | grep 64 | cut -c 1-2) == 64 ] ; then
echo Good Ping
fi
``...`` can be used instead of `$(...)`.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 1,
"tags": "bash, bash scripting"
}
|
ModuleNotFoundError: No module named 'account.apps.AccountConfigdjango'; 'account.apps' is not a package
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'account'
As a whole, I have two files the code above is from `apps.py`, but it does not work. What and where do I have to import the file `apps.py` to make my code run?
|
in the settings.py you will see a list called INSTALLED_APPS, you pass it there example
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'users.apps.UsersConfig',
]
this taken for users apps.py that look like the following
class UsersConfig(AppConfig):
name = 'users'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, django, django models"
}
|
How do take a Paragraph and and store all sentences in a Array of String
I am new to Java. I would like to separate out all sentences of a paragraph and put it in `String[]`. My code looks like this:
int i =0;
if(str.length()> 40){
int sentences = str.length() - str.replace(".","").length();
Log.d("number of Sentences",String.valueOf(sentences));
strlets = new String[sentences];
for (int count =0;count<sentences;count++){
for (;i<str.length();i++){
char c = str.charAt(i);
if(c == '.'){
break;
}
strlets[count] = strlets[count] + c;
}
}
Log.d("strlets",strlets[1]);
}
This does not give me an output I wanted. I receive only the first sentence.
|
If I understand your question, it can be done in one line. Namely,
String[] sentences = str.split("\\.\\s*");
which will split the input `str` on a literal `.` (and consume any following optional white-space). And, to log it you can use [`Arrays.toString(Object[])`](
Log.d("sentences", Arrays.toString(sentences));
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, android"
}
|
Flexible ACL in ASP.NET
I'm building an application for which I want to use roles managment applicable to individual pages. That is, restrict users' access to pages based on their roles. These roles are stored into the database, as the users. This is the PHP way of doing things and I'm trying to port this to ASP.NET
What I need is that someone can point me to the right resources to look at to acomplish the above task. Until now I have not been able to find what I am looking for.
Thank you.
|
I think you should checkout the ASP.NET membership provider model:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "c#, asp.net, forms authentication, acl"
}
|
How can I find out the actual rpms my dc motor at any given moment?
In my next project it will be very helpful to monitor the speed of my dc motor. How can I accomplish this?
|
In addition to the cornucopia of methods that burst forth from Russell's answer you could consider to add yet another to that rich bounty- if you have sufficient off time in your maximum PWM duty cycle you may be able to harness the back EMF of the motor itself as a tachometer signal. This has the advantage of being sensorless. It can be a suitable method for motors that are permanent magnet or that have a separate field winding. There must be sufficient time for the energy stored in the rotor inductance to die down, after which you can simply sample the voltage with an ADC.
A detailed description of this method can be found here. The back EMF is proportional to the RPM of the motor, and of the same polarity as the applied voltage (assuming a PM type or fixed field voltage) when measured at the terminals.
|
stackexchange-electronics
|
{
"answer_score": 2,
"question_score": 1,
"tags": "dc motor"
}
|
How do i uniquely print out the elements of a list inside a dictionary
I want to know how i can uniquely print out the elements of each list inside the dictionary without printing duplicates. Sorry i am quite new to programming. I am reading Python Crash Course 2nd edition and want to add a little bit of a challenge to my code.
favorite_languages = {
'jen': ['python', 'c'],
'mark': ['c'],
'tom': ['ruby', 'haskell'],
'amy': ['python', 'ruby'],
}
print("Mentioned languages:")
for languages in favorite_languages.values(): # Loop over the dictionaries unique values only
if len(languages) != 1:
languages = set(tuple(languages))
for language in languages:
print("\t",language.title())
|
You can combine the lists in favorite_languages.values() by adding them to a blank list, and taking the set at the end:
print("Mentioned languages:")
languages = []
for language in favorite_languages.values():
languages += language
languages = set(languages)
for language in languages:
print("\t",language.title())
You'll see in PCC that you can combine some of these lines, but for the sake of clarity I've put each step on a different line.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python 3.x, dictionary, nested, nested lists"
}
|
Axios: how to cancel request inside request interceptor properly?
I want to cancel the request if there's no token, so I do like this:
instance.interceptors.request.use(config => {
if (!getToken()) {
console.log("interceptors: no access token");
} else {
config.headers.Authorization = "Bearer " + getToken().accessToken;
return config;
}
});
But in negative scenario there's an error `TypeError: Cannot read property 'cancelToken' of undefined`.
|
You cannot use the token inside the interceptors but instead throw `Cancel`
axios.interceptors.response.use(function (response) {
throw new axios.Cancel('Operation canceled by the user.');
}, function (error) {
return Promise.reject(error);
});
Refer to this post: <
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 28,
"tags": "javascript, axios"
}
|
Active Storage - Abandoned Files
I've messed up and used the same bucket for storage with my development and production environment. My question is what happens if the hash that is created for the file name in production overlaps a hash that was created in development? Is there any check for this? Is there anyway to clean up the abandoned files?
Thanks :)
|
Blob keys are generated using SecureRandom (rails' `has_secure_token`), so it is very unlikely that some file got overwritten. To be completely sure - check for duplicate keys in `active_storage_blobs`, to do that I'd dump that table from production and import it on development under different table name and then `join`ed two tables, if everything is ok - there'll be empty intersection.
Next step is cleanup (actually if there's not that much data from development - it may be cheaper just to forget). For that you'll have to write a script that lists your bucket(that depends on you storage service) and finds these abandoned files - from filename you can reconstruct the key for the blob and then check if that key belongs to production.
Just be sure to double-check that list - there may false positives - files that were just uploaded and not yet written to db.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 5, rails activestorage"
}
|
Parametric typeclass name
Say we have a heterogeneous list
data Nil
data Cons a b
I can write code like this for any typeclass `A`
class AList a
instance AList Nil
instance (A x, AList xs) => AList (Cons x xs)
Now, is there a way to generalize that code so it's parametric in `A`?
Say, like this made up syntax
class List (class A) a
instance List (class A) Nil
instance (A x, List (class A) xs) => List (class A) (Cons x xs)
|
I’m not sure I understand the motivation, but yes, you can express this with GHC’s `ConstraintKinds` extension:
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeclasses #-}
{-# LANGUAGE UndecidableInstances #-}
import GHC.Exts (Constraint)
class List (c :: * -> Constraint) a
data Nil
data Cons a b
instance List c Nil
instance (c x, List c xs) => List c (Cons x xs)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "haskell, typeclass"
}
|
Prove the following fact about a recurrence relation
Consider the following recursive relation: $$T(1)=1$$ $$T(n)=2T\left(\left\lfloor \frac n 2\right\rfloor\right)\text{ for }n\geq 2$$ It is required to show that $$T(n)=2^{\lfloor \log_2 n\rfloor}$$ I tried to solve this problem by considering two cases $n=2^b$, where $b\geq 1$ and $n=a\cdot 2^b$, where $a$ is an odd number. In the first case observe that $$T(2^b)=2\cdot T(2^{b-1})$$ $$=2^2\cdot T(2^{b-2})$$ $$...$$ $$T(2^b)=2^b$$ Also observe that $$2^{\lfloor \log_2 2^b\rfloor}=2^b$$ so we are done for case 1. I am facing difficulty in proving for case 2, when $n=a\cdot 2^b$. Any hints/suggestions will be much appreciated.
|
If $b$ is the largest integer such that $2^b$ divides $n$ with remainder $\geq 0$ then $$b=\lfloor{\log_2n\rfloor}.$$ Also $$\left\lfloor\frac 1 2\left\lfloor \frac n 2\right\rfloor\right\rfloor=\left\lfloor\frac {n} {2^2}\right\rfloor$$ for integer $n$. So $$T(n)=2T\left(\left\lfloor \frac n 2\right\rfloor\right)=2^2T\left(\left\lfloor \frac {n} {2^2}\right\rfloor\right)=\cdots=2^bT(1)=2^b$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "discrete mathematics, recurrence relations, computer science"
}
|
How can get value to PreferenceFragment
I have this code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="
<CheckBoxPreference android:key="notification_settings"
android:text="@string/impostazione"
android:id="@+id/save_check"
android:summary="@string/notification_title"
android:defaultValue="false"
></CheckBoxPreference>
</PreferenceScreen>
now i need to get Checkbox value in FragmentA:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
and now?
|
**Try this way,hope this will help you to solve your problem.**
sharedPreferences.getBoolean("notification_settings",false)
getBoolean()) : required two parameter one is key and another is default value
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 6,
"tags": "java, android, android studio, sharedpreferences"
}
|
How can I loop through a list and change the values in it?
I am trying to run this simple code:
def looping(list_):
for i in list_:
list_[i]=8
return list_
_list=[1,2,3,4,5,6]
print(looping(_list))
I define a function looping(). I pass a list as argument and the function should return an amended list. I want to loop and change all values of the list to 8.
But it says it is wrong why?
|
The `i` in your loop is not the index. It's the value you get from the list.
If you want to access & assign your list items with the index, you want something like this:
def looping(list_):
for i in range(len(list_)):
list_[i]=8
return list_
_list=[1,2,3,4,5,6]
print(looping(_list))
Output:
> [8, 8, 8, 8, 8, 8]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, list"
}
|
Powerset of collection in Clojure
Similar to this question, here's another implementation. Assume the input is already a set.
(defn powerset
[set]
(reduce
(fn [xs x] (concat xs (map #(cons x %) xs)))
[()]
set))
|
There isn't a _whole_ lot here to comment on. I'll just mention a few things:
* _Technically_ , from my quick search of what a powerset is, this function should return sets. That seems petty, but unless it's documented to return a lazy list of lazy lists, users may try to treat the "subsets" as sets (like using them as functions). I'd finish this function off by `map`ping `set` over the list.
* But to do that, you should rename your parameter, as you're shadowing the build-in `set`.
* After doing the above two, it developed quite long lines and became nested. I'd add in some use of `->>`, and put a few of the lines on the next line.
After that, I ended up with:
(defn powerset [base-set]
(->> base-set
(reduce
(fn [xs x]
(concat xs
(map #(cons x %) xs)))
[()])
(map set)))
|
stackexchange-codereview
|
{
"answer_score": 2,
"question_score": 2,
"tags": "clojure, set"
}
|
Set x number of yellow stars on primefaces rating stars
Basicaly I want the user to see has default instead of 5 grey stars 3 yellow ones and 2 grey (for example) and I can't find a way to do that.
<p:rating value="#{ratingView.rating4}" readonly="true" />
It shows 5 grey stars. And I want to show only 2 and 3 yellow.
|
If I understood what you´re trying to do, you just need to assign to your variable an integer value equals to the number of stars you want to display.
@ManagedBean
public class RatingView {
private Integer rating4 = 3;
}
This way you will get your rate to have 3 yellow stars like you wanted. Here is some documentation that can help you in this subject.
PrimeFaces Showcase
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "primefaces"
}
|
Sqlite3 (node.js) returns [object Object]
I am trying to use SQLITE3 to store data for my discord bot and here i need to save a number that goes up each time a command is used. Here is my code: (creating table and setting the value to 0.)
db.run("CREATE TABLE gbanCases ( number INT )")
db.run("INSERT INTO gbanCases (number) VALUES ($number)", {
$number : 0
});
Trying to see what number returns:
var caseNumber = db.run("SELECT number FROM gbanCases")
console.log(caseNumber)
The thing is that caseNumber returns me "[object Object]" and I want it to return the 0 that was setted up earlier. Please help me if you can, i'm still very new to this.
|
Use `db.get()` to get the result of a query, not `db.run()`. The resulting row is passed as an argument to the callback function.
db.get("SELECT number FROM gbanCases", function(err, row) {
if (err) {
throw err;
}
console.log(row.number);
})
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, database, object, node sqlite3"
}
|
Should I resign in between illness (recuperating on leave)
I'm currently on leave from my company as I'm recovering from a severe bout of dengue. Yesterday, I appeared for an interview with another company which has made me an offer I want to accept. Should I immediately inform my earlier company and resign via email/call ? Or should I wait to recover and join back and then resign, after about 1 week.
And I need to join the new company within about 40 days.
I intend to leave my current company which has a notice period of 30 days, as soon as they can release me, even if by paying notice period shortfall, but on amicable terms. Even if I resign today, I plan to attend for about 2 weeks to finish off the remainder of my latest assignment
|
Though it is not always possible, it is good to leave any employment on amicable terms with the employer. One thing you could do is resign now over email stating that your earlier efforts at job hunting has materialized and you are moving to your own city back. Offer them to convert your medical leave into leave without pay. Join after 1 week, talk to HR to buyout your last 1 week of notice, complete your job in 2 weeks and leave with balance pay of 2 weeks and buyout.
This way, no one can actually ask you any questions, you did not work you did not accept pay, you finished your work in 2 weeks, you bought out 1 week of your notice period as per company policy and left.
|
stackexchange-workplace
|
{
"answer_score": 2,
"question_score": -1,
"tags": "new job, resignation, notice period, sickness"
}
|
Heights of 16-month old Oak Seedlings
The heights of 16-month-old oak seedlings are normally distributed with a mean of 31.5 cm and a standard deviation of 10 cm. What is the range of heights between which 75% of the seedlings will grow?
**My solution:** If 75% of the seedlings grow under this range of heights, then the probability must be 0.75 which is the area under my normal distribution curve. Using the invNorm function on my calculator, I find the z-score to be 0.674. I then know that this is 0.674 standard deviations away from the mean, so I multiply 0.674 by 10, and add them and subtract from my mean to find my range.
My answer is wrong and the correct answer is 20 cm to 43 cm. How am I wrong? What am I supposed to do?
Thank you.
|
The error lies in the fact that your calculator's invNorm function finds the $z$-value for which $75$ percent of the normal distribution lies between $-\infty$ and $+z$, not between $-z$ and $+z$. In particular, $50$ percent lies between $-\infty$ and $0$ (obviously, by symmetry) and then another $25$ percent lies between $0$ and $+0.674$. By symmetry, again, that means that only $50$ percent lies between $-0.674$ and $+0.674$. If you sketch this out on a notional graph, that might help you to see this difference better.
If your calculator does not have another similar function, we must reason as follows: We want the value of $z$ such that $75$ percent of the normal distribution lies between $-z$ and $+z$. That means that $37.5$ percent lies between $0$ and $+z$, and therefore that $87.5$ percent lies between $-\infty$ and $+z$. Apply invNorm to $0.875$ and see if that doesn't give you the right answer.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "probability, probability distributions"
}
|
PHP strotime - String to Date - wrong date result
When I try to convert very high dates, such as 2045-01-01, I get another date:
> date("Ymd", strtotime("2045-02-15"));
I obtain a wrong date
> 19700101
but when
> date("Ymd", strtotime("2017-02-15"));
I have the good date
> 20170215
I don't understand why? Someone just explain to me what's going on?
|
that's a unixtimestamp problem (=> < better:
date_parse("2006-12-12 10:00:00");
date_parse_from_format ( 'Ymd' , "2017-02-15" );
or
$date = DateTime::createFromFormat('Ymd', "2017-02-15");
echo $date->format('Y-m-d');
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, date"
}
|
FCC Basic JavaScript: Testing Objects for Properties
guys I am stuck at this for a while now and can't make it work what should I do. the problem is attached to this IMG URL: <
|
use bracket pair `[]` instead of dot `.` notation. `return obj[checkProp]`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript"
}
|
Electric potential of uniformly charged wire
I want to calculate the electric potential of a uniformly charged wire with infinite length. The problem I run into is that one boundary of the integral is $\infty$. That’s what I have so far:
Given the uniform charge density $\lambda$ and $E(r) = \frac{\lambda}{2\pi r \epsilon_0}$.
$$ V(r) := \int_r^\infty \vec E \cdot \vec dr = \frac{\lambda}{2\pi\epsilon_0}[\log(r)]_r^\infty $$
How should I evaluate $\log(\infty)$?
|
By default we usually suppose that the electric field vanishes in infinity, since for a point charge it is KQ/r². We usually stablish V=0 at infinity in order to cancel one of the terms of the integral.
However, when you do have electric charges in the infinity (and that's the case if the wire is infinite), then you cannot say that the potential in the infinite is 0, and so that cannot be your origin of potentials anymore.
On the contrary, you must stablish a new point as reference. That means you have to choose any point you want and set it as V(there)=0. Then, the integral limits must be "from that reference point to the generic r position".
|
stackexchange-physics
|
{
"answer_score": 6,
"question_score": 0,
"tags": "electrostatics, electricity, potential"
}
|
How do i serialize an empty jsonapi object
i have a jsonapi object that i need to serialise into a string.
{\n \"data\" : [\n\n ]\n}
but this causes the error
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]:
Invalid top-level type in JSON write'
this is the code that i am using to convert the json object into a string:
NSError * error;
NSData * jData = [NSJSONSerialization dataWithJSONObject:[notification.userInfo objectForKey:@"data"]
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jString = [[NSString alloc] initWithData:jData encoding:NSUTF8StringEncoding];
Hope someone can help me with this problem.( ** _that does not involve manually removing the \ and \n_** )
|
To convert a json object into string you should first get it into a `NSData` then use the encoding of `NSUTF8StringEncoding` to turn it into a `NSString`.
NSDictionary *jsonDict = {\n \"data\" : [\n\n ]\n}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "objective c, json api"
}
|
Cached taxonomy menu block problem?
I created a taxonomy menu block based on a vocabulary I have. It didn't work how I wanted so I removed it. I have created a view (page) that has the same URL as one of the links in the taxonomy menu block, and that URL displays nothing (which is what happened when it corresponded to a link in the TMB), even though it shouldn't - its preview displays a list of content items. If I modify the view's URL the content displays, if I set it back to what I want it to be it displays nothing.
I've cleared Drupal's cache and even removed the TMB modules, but I still get the same thing.
Am I right to think it's likely to be related to the TMB that I got rid of? And can anyone suggest any steps to getting the content to display on the URL?
Thanks,
Toby
|
I've resolved this, I think, but would be interested to hear if there are alternative solutions. I _think_ the Taxonomy Menu Block was a red herring - it was just using the URL alias for the associated term references, which exist whether or not a TMB is used. My view had the same URL alias, hence the conflict; setting either alias to something else was all that needed to be done.
|
stackexchange-drupal
|
{
"answer_score": 0,
"question_score": 0,
"tags": "views, taxonomy terms, routes"
}
|
Pad list in Python
How can I pad a list when printed in python?
For example, I have the following list:
mylist = ['foo', 'bar']
I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:
', '.join(mylist)
But how can I pad it to four indices with 'x's, so the output is like:
foo, bar, x, x
|
In [1]: l = ['foo', 'bar']
In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'
The `['x'] * (4 - len(l))` produces a list comprising the correct number of `'x'`entries needed for the padding.
**edit** There's been a question about what happens if `len(l) > 4`. In this case `['x'] * (4 - len(l))` results in an empty list, as expected.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "python, list, padding"
}
|
Why does $\iota_4^2 \in H^8(K(\mathbb Z/2,4);\mathbb Z/2)$ not come from $H^8(K(\mathbb Z/2,4);\mathbb Z)$?
In Hatcher's Chapter 5 ( on page 574 (page 57 in the pdf), he states that $\iota_4^2 \in H^8(K(\mathbb Z/2,4);\mathbb Z/2)$ is not in the image of $H^8(K(\mathbb Z/2,4);\mathbb Z)\to H^8(K(\mathbb Z/2,4);\mathbb Z/2)$. The argument for the lower classes ($\iota_4, Sq^2\iota_4, Sq^2Sq^1\iota_4$) which don't come from $H^*(K(\mathbb Z/2,4);\mathbb Z)$ is that the Bockstein homomorphism $Sq^1\colon H^*(K(\mathbb Z/2,4);\mathbb Z/2) \to H^{*+1}(K(\mathbb Z/2,4);\mathbb Z/2)$ applied to those classes is nonzero, so it can't come from $H^*(K(\mathbb Z/2,4);\mathbb Z)$. This argument doesn't work for $\iota_4^2 = Sq^4 \iota_4$ because $Sq^1Sq^4 \iota_4 = Sq^5 \iota_4 = 0$.
How can one argue that $\iota_4^2 \in H^8(K(\mathbb Z/2,4);\mathbb Z/2)$ doesn't come from $H^8(K(\mathbb Z/2,4);\mathbb Z)$? Is it even true?
|
It is true, and follows from results of Browder on the mod 2 Bockstein spectral sequence for $K(\mathbb{Z}/2,4)$. (We can replace $4$ by any even integer $k$ and conclude that $\iota_k^2$ ia not the reduction of an integral class.) An argument is spelled out in Section 3 of
_Grant, Mark; Szűcs, András_ , **On realizing homology classes by maps of restricted complexity**, Bull. Lond. Math. Soc. 45, No. 2, 329-340 (2013). ZBL1270.57068
available in preprint form at < It is based on Theorem 5.5 of
_Browder, W._ , **Torsion in (H)-spaces**, Ann. Math. (2) 74, 24-51 (1961). ZBL0112.14501.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 10,
"question_score": 7,
"tags": "at.algebraic topology, homotopy theory, steenrod algebra"
}
|
Why does my device turn Wi-Fi on by itself?
Similar to Why does HTC Incredible S turn Wi-Fi on by itself?, it seems my Samsung Galaxy Victory will turn on Wi-Fi at random times. It establishes a connection if certain networks are in range (i.e. any open Wi-Fi).
I notice a Wi-Fi setting which allows this phone to keep its Wi-Fi on during sleep, but this is currently disabled.
Is there a way to prevent the device from looking for Wi-Fi networks? If this is specific to Samsung devices, has anyone figured out how to take care of this issue?
|
After some searching, it turns out this feature is provided by the Sprint network (although that doesn't rule out that other carriers/devices may provide similar functionality). The Q&A at community.sprint.com points to the Sprint Connection Optimizer, AKA the "Intelligent Mobile Network and Wi-Fi Setting." This setting **"will automatically connect you to Wi-Fi networks on your device's remembered list."**
This setting can be enabled/disabled by navigating to Settings > More settings > Mobile Networks > Sprint Connections Optimizer.
|
stackexchange-android
|
{
"answer_score": 3,
"question_score": 0,
"tags": "wi fi"
}
|
Limited styles in the Monochrome plot theme
It seems like `PlotTheme -> "Monochrome"` produces up to 8 different dashing styles for `Plot`. I know one way to overcome this is to use `ListLinePlot` and use `PlotMarkers` to produce more combinations. However, I am wondering if there are simpler ways to just assign more dashing styles in the Monochrome theme? For example, as seen below, the styles repeat themselves.
Plot[Evaluate@Table[2 p + y, {p, 0, 1, 0.1}], {y, 0, 4},
PlotTheme -> "Monochrome"]
"}/U',$data,$matches);
echo $matches[0]; //=> target
|
Try like this,
<?php
//If it is valid json then try with json_decode()
$json_string = '{"title":{"rendered":"Marine Corp."}}';
$json_array = json_decode($json_string,1);
echo "For Json Object:\n" . $json_array['title']['rendered']."\n";
//If it is just string pattern then with preg_match()
$re = '/"title":{"rendered":"(.*?)\.?"}/';
$str = '"title":{"rendered":"Marine Corp."}
"title":{"rendered":"Marine Police"}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo "\nFor String: \n";
foreach($matches as $match){
echo $match[1]."\n";
}
?>
**Output:**
For Json Object:
Marine Corp.
For String:
Marine Corp
Marine Police
See PHP demo : <
See REGEX demo : <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php, preg match"
}
|
How can I replace "/>XXXXX"/> with "/> within a selection
I have a CSV file which I am editing with Notepad++. There is a section of about 500 consecutive lines where I want to replace `"/>XXXXX"/>` with `"/>` where XXXXX are numbers.
Is there a way to do a Find/Replace All with Notepad++ on only that section?
|
1. Select your 500 lines where you want to replace something (not start and end of text)
2. Tick _Regular expression_ and **_In selection_** like shown on screenshot
3. Find what: `"/>\d+"/>` (only `\d+` is RegEx and matches all consecutive numeric characters)
Replace with: `"/>`
.
* * *
You can always search the old docs to observe the evolution of some particular function; <
**R2017b** ;
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
This is the library i need but i don't know what's happening:
import android.content.Intents;
Any help will be much appreiated. Thank you.
|
The `Intents` class you're talking about is from the com.google.android.glass.content package.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android, google glass, google gdk"
}
|
Onclick event make working
var shot = document.getElementsByClassName ('sprite');
shot.onclick = function (event) {
alert(1);
}
I have this code and i have this in html
<a href="#" class="sprite" ></a>
But it doesn't work why?
|
You need to call it like,
document.getElementsByClassName('sprite')[0];
in order to select the first element of the returned array of elements. Also include some text in your html in order to see the element and click it,
<a href="#" class="sprite" >test</a>
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript"
}
|
Eclipse with Phonegap. Android dev
So I'm making an android app. I am using Eclipse. When I click on Window along the top and then click Android SDK and AVD Manager a little window pops up saying "Location of the android SDK has not been set up in the preferences". I looked this up and I needed to set the PATH variable. I did this but that little window still pops up.
Thanks
|
Eclipse menu->Window->Preferences->Android(on tree view on the left)->SDK Location on the right->Click Browse and point to your installation android-sdk folder. This is in Eclipse Helios.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "eclipse"
}
|
initializing queue with condition
You have to implement the methods for the class m_sorted_list, which when initialized takes a parameter sorted which is true or false. When the parameter is true the list is sorted in ascending order. When the parameter is false it acts as a normal unbounded queue
that's what I'm given to code
so far, I've done
def __init__(self, m_sorted):
self.__items=[]
self.__size=0
initialization actually wants
–Initialization of the class with parameter which is true or false
seriously, I'm new in Python, I don't really understand what the question is actually want me to do.
can anyone help me what to do?
|
Sorry if I am understanding wrong but the follwoing might help.
class N:
def __init__(self):
self.s = []
def add(self,u):
self.s.append(u)
def check(self):
if sorted(self.s) == True:
print "List is sorted"
else:
print "Not sorted but it will sort now"
return sorted(self.s)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, initialization, queue"
}
|
Do eigenvalues depend on the choice of basis?
Suppose we have a basis $B$ for an endomorphism $f$ that has eigenvalues $\lambda_{1},\dots,\lambda_{k}$.
Do these eigenvalues change or stay the same if we change to another basis $B'$?
|
No, eigenvalues are invariant to the change of basis, only the representation of the eigenvectors by the vector coordinates in the new basis changes.
Indeed suppose that
$$Ax=\lambda x$$
and let consider the change of basis $x=My$ then
$$Ax=\lambda x\implies AMy=\lambda My\implies M^{-1}AMy=\lambda y \implies By=\lambda y$$
|
stackexchange-math
|
{
"answer_score": 32,
"question_score": 28,
"tags": "linear algebra, eigenvalues eigenvectors, change of basis"
}
|
Recursion, pass function as an argument
I want to run a function certain amount of times using recursion, for example: `repeat(console.log('Hello'), 3)` should print Hello 3 times. I tried to implement such function but it prints only one word `Hello`.
function repeat(w, x){
let fun = function(arg){
return arg
}
if (x==1){
return fun(w)
}
else{
return fun(w)+repeat(fun(w), x-1)
}
}
repeat(console.log('Hello'), 3)
|
A few mistakes in your code:
1. You're not passing the function as an argument.
2. You don't need to use `+` to make two functions run after each other. From your original snippet I infer that you're only concerned about the side effects, not the values. So you can just call the functions individually.
It could look something like this:
function repeat(fun, x) {
if(x < 1) return; // we ran out of attempts, terminate
fun(); // side-effect (print to console)
repeat(fun, x - 1); // decrement the counter and attempt to continue
}
repeat(function() { console.log("hello")}, 3);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript"
}
|
Running command on substring of every file
Let's say I've some files like:
samplea.txt
sampleb.txt
samplec.txt
And I want to run some command with this form:
./cmd -foo a.xml -bar samplea.txt
First I've tried to
for file in "./*.txt"
do
echo -e $file
done
But this way it will print every file in a straight line. By trying:
echo -e $file\n
It does not produce the expected (single line for each file). Couldn't even pass through the first part of the problem, that would be running a command on each file (which it could be achieved by find (...) -exec), but what i really wanted to do was extract a substring of each name.
Doing:
echo ${file:1}
won't work since I could only do so after splitting the filenames, to get the "a","b","c" from each one.
I'm sorry if it sounds confusing, but it's my first bash script.
|
Do not quote the wildcard expression. You can use parameter expansion to remove parts of a string:
for file in sample*.txt ; do
part=${file#sample} # Remove "sample" at the beginning.
part=${part%.txt} # Remove ".txt" at the end.
./cmd -foo "$part".xml -bar "$file"
done
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "bash"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.