qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
314,983 | I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use? e.g. assuming a header called `foo.hpp`:
```
#ifndef __FOO_HPP__
...
#ifndef INCLUDED_FOO_HPP
...
#ifndef SOME_OTHER_FORMAT
```
I'm sold on the idea of upper-case #defines but cannot settle on a format for these guards. | 2008/11/24 | [
"https://Stackoverflow.com/questions/314983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | I use
```
#if !defined(FOO_HPP_INCLUDED)
```
I prefer the modern `defined` syntax because it allows || && operators, even if they aren't used here.
Also
```
#ifndef __FOO_HPP__
```
is technically illegal, as leading underscores are reserved. | I'd go with the filepath + the boost `_INCLUDED` suffix plus the nowadays widely supported `#pragma once`
In alot editors (for me its sublime) you can also define some macros/snippets for this.
Here is one that does it for you:
```
<snippet>
<content><![CDATA[
#ifndef ${1:${TM_FILEPATH/(.*\/(include|src))*([^a-zA-Z0-9_]+)*([a-zA-Z0-9_]+)([.])*([a-zA-Z0-9_]+)*/\U$4_$6/ig}_INCLUDED}
#define $1
#pragma once
$0
#endif // $1
]]></content>
<tabTrigger>incguard</tabTrigger>
<description>include guard</description>
</snippet>
```
so `yourproject/include/yourlib/yourfile.hpp`
becomes `YOURLIB_YOURFILE_HPP_INCLUDED`
An additional external source code style checker tool could easily track consistency of your guards this way. |
10,811,439 | I have the following struct:
```
typedef struct _chess {
int **array;
int size;
struct _chess *parent;
} chess;
```
and I have:
```
typedef struct _chess *Chess;
```
Now, I want to create an array of dynamic length to store pointers to the chess struct so I do the following:
```
Chess array [] = malloc(size * sizeof(Chess));
```
This gives me an error: invalid initializer.
And if I drop the [] and do this:
```
Chess array = malloc(size * sizeof(Chess));
```
it compiles without error but when I try to set an element of this array to NULL by doing:
```
array[i]=NULL;
```
I get an error: incompatible types when assigning to type ‘struct \_chess’ from type ‘void \*’
Any idea what am I doing wrong?
Thanks. | 2012/05/30 | [
"https://Stackoverflow.com/questions/10811439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1249740/"
] | There's a lot of `typedef` going on here. Personally I'm against "hiding the asterisk", i.e. `typedef`:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between `foo` and `foo *`.
Many of the answers are also confused about this, I think.
Your allocation of an array of `Chess` values, which are pointers to values of type `chess` (again, a *very* confusing nomenclature that I really can't recommend) should be like this:
```
Chess *array = malloc(n * sizeof *array);
```
Then, you need to initialize the actual instances, by looping:
```
for(i = 0; i < n; ++i)
array[i] = NULL;
```
This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.
If you wanted to allocate space, the simplest form would be:
```
for(i = 0; i < n; ++i)
array[i] = malloc(sizeof *array[i]);
```
See how the `sizeof` usage is 100% consistent, and *never* starts to mention explicit types. *Use* the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.
Of course, the above does a needlessly large amount of calls to `malloc()`; depending on usage patterns it might be possible to do all of the above with just one call to `malloc()`, after computing the total size needed. Then you'd still need to go through and initialize the `array[i]` pointers to point into the large block, of course. | IMHO, this looks better:
```
Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`
for ( int i =0; i < SOME_VALUE; ++i )
{
array[i] = (Chess) malloc(sizeof(Chess));
}
``` |
7,227,163 | I found that last word showed with double quotes. But why?
```
NSDictionary *guide2 = [NSDictionary dictionaryWithObjectsAndKeys:kArr, @"Kate", aArr, @"Ana-Lucia", kArr, @"John", nil];
NSArray *array = [guide2 allKeys];
NSLog(@"%@", [array description]);
```
output:
```
(
John,
Kate,
"Ana-Lucia"
)
``` | 2011/08/29 | [
"https://Stackoverflow.com/questions/7227163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499825/"
] | You could use `python-gstreamer` for playing videos (this works for me on Linux, but it should also work on Windows). This requires [`python-gstreamer`](http://gstreamer.freedesktop.org/modules/gst-python.html) and [`python-gobject`](http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/), I would recommend you to use this all-in-one installer.
Here is the code:
```
import os
import sys
import Tkinter as tkinter
import gobject
import gst
def on_sync_message(bus, message, window_id):
if not message.structure is None:
if message.structure.get_name() == 'prepare-xwindow-id':
image_sink = message.src
image_sink.set_property('force-aspect-ratio', True)
image_sink.set_xwindow_id(window_id)
gobject.threads_init()
window = tkinter.Tk()
window.geometry('500x400')
video = tkinter.Frame(window, bg='#000000')
video.pack(side=tkinter.BOTTOM,anchor=tkinter.S,expand=tkinter.YES,fill=tkinter.BOTH)
window_id = video.winfo_id()
player = gst.element_factory_make('playbin2', 'player')
player.set_property('video-sink', None)
player.set_property('uri', 'file://%s' % (os.path.abspath(sys.argv[1])))
player.set_state(gst.STATE_PLAYING)
bus = player.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', on_sync_message, window_id)
window.mainloop()
``` | Make use of `tkvideoplayer` version>=2.0.0 library, which can help you to play, pause, seek, get metadata of the video etc.
```
pip install tkvideoplayer
```
Sample example:
```py
import tkinter as tk
from tkVideoPlayer import TkinterVideo
root = tk.Tk()
videoplayer = TkinterVideo(master=root, scaled=True)
videoplayer.load(r"samplevideo.mp4")
videoplayer.pack(expand=True, fill="both")
videoplayer.play() # play the video
root.mainloop()
```
An example to create a complete video player is in the GitHub [page](https://github.com/PaulleDemon/tkVideoPlayer/blob/master/examples/sample_player.py)
Refer [documentation](https://github.com/PaulleDemon/tkVideoPlayer/blob/master/Documentation.md) |
8,340,658 | jQuery :
```
*cacheBoolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser.
Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.*
```
my question :
*cached by the browser* **???**
if i have an ASHX handler which returns me :
```
'<div>lalala</div>'
```
will this be saved on the browser temporary Internet Files ?
I dont think so....
so where does it saves it ? | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859154/"
] | jQuery itself does not perform any caching of the AJAX response. Setting `cache: false` serves only to trick the browser into ignoring its own cache by adding a timestamp to the requested URL.
For example, running:
```
$.ajax('/ajax_handler.php', { cache: false });
```
Will result in a request for `/ajax_handler.php?_=1323308900002`.
Any subsequent request will include a newer timestamp at the end, which will cause the browser to ignore cached versions of the file and request a new copy.
So, all setting `cache: true` does is instruct jQuery to *not* append this cache-busting timestamp (the current default anyway), allowing the browser to cache the file as it normally would\*.
In summary: any caching that happens is just regular browser caching, the files will be stored however the browser typically stores its cache.
\* Note that "as it normally would" might mean *not* caching the file! jQuery doesn't do anything to ensure caching, it's up to the browser. If the page sends [certain `Cache-control` or `pragma` headers](https://developer.mozilla.org/en/HTTP_Caching_FAQ#How_are_expiration_times_calculated_%28since_not_every_response_includes_an_Expires_header%29.3F), it simply won't be cached. It would arguably make more sense for jQuery to have a "cacheBust" setting that's the inverse of `cache`, because that's all jQuery can do: attempt to prevent caching. | i think that "cached by the browser" means that if the browser (IE more than others...) intercept the same call twice, never calls the server and just returns whatever the server returned the last time. But if you clear the cache it goes away |
45,626 | Though originally posted as a comment [here](https://money.stackexchange.com/questions/28658/bond-prices-why-is-a-high-yield-sometimes-too-good-to-be-true#comment42640_28688), I don't see an answer. So please allow me to resurrect and broaden this question, to all investment-grade bonds: in other words, '[BBB- or higher by Standard & Poor's or Baa3 or higher by Moody's.](http://en.wikipedia.org/wiki/Bond_credit_rating#Investment_grade)'.
>
> Why should the prices of these
>
> [highly rated bonds from pension funds, mutual funds, etc. because of their investment mandates]
>
> bonds drop? Isn't there always a demand for ... [investment-grade] bonds with more than 10% coupon?
>
>
> | 2015/03/16 | [
"https://money.stackexchange.com/questions/45626",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/-1/"
] | With bonds, it's more about yield to maturity (YTM) than about supply and demand. Or better said, YTM is what is demanded, not so much the credit rating of the issuer. YTM is a function of the price paid for the bond and the interest paid over the life of the bond. The interest is fixed (or at least pre-determined), so an existing bond's YTM can only be adjusted in the marketplace by adjusting the purchase price.
When new bonds are issued with higher rates, investors will demand that the bonds they buy have a competitive YTM. So existing bonds will have to drop their price in order to boost their YTM to match the other bonds on the market. The same effect happens when bond rates fall, just in the opposite direction. | >
> Why should the prices of these [highly rated bonds from pension funds,
> mutual funds, etc. because of their investment mandates] bonds drop?
> Isn't there always a demand for ... [investment-grade] bonds with more
> than 10% coupon?
>
>
>
Beware of 2 assumptions in the questions:
1. Companies can have ratings changed and thus what may start out as an investment-grade bond may end up as a junk bond or did you believe that bonds couldn't have their grades altered?
2. What interest rate environment is there here? There may be a perception that rates may rise in the next few years so that 10% could look small as back in the early 1980s in the US short-term rates were over 20% once in which case a 10% coupon would look rather low in comparison. |
29,063 | Most Atheists I have encountered fall into 2 categories:
1. New Atheists: People who don't believe in God and see religion as an evil to be eradicated given the harm it has caused humanity (i.e. followers of Richard Dawkins, Sam Harris, etc...).
2. "Don't care" atheists: People who don't believe and really don't care what others believe (I think this what is meant by "irreligious" people - but I might be wrong).
My own views don't fall under either of these categories.
On one hand:
* I am not convinced neither by the scriptures of any of the major religions nor by any of the philosophical arguments (ontological, cosmological, etc...) that a supernatural God or gods exists. Nor do I believe that any of the major scriptures have much historical truth in them (any that they might have is purely accidental). In this sense I am squarely an atheist.
On the other hand:
* I do not dismiss the positive role that religion has in peoples lives as easily as most atheists do. For all of the crusades, inquisitions and ISIS's that religion has created, it still plays an important role in many peoples lives. I believe that science can never provide answers to questions of meaning and value (as opposed to factual questions), and yet these questions do need answers.
* I do not buy the existentialist "we can construct our own meaning and values" stance. That would make them too arbitrary. At the very least, very basic principles such as "Killing is bad", "Raping is bad" and "Small children should be loved" need to be transcendent. They are too important to be left to the whims of the Sartres and Camus of the world to construct them.
* I find that religious ritual, and acts such as prayer and meditation to be very useful, maybe even necessary. They add meaning and richness to many people's lives, and it seems very cruel to me for science/reason to strip them of that, without at least trying to offer a substitute (and so far it can't).
None of these views seem to me to be inline with what people think of as Atheism.
My questions:
1. Is someone who subscribes to these views considered an atheist or is there another name for this worldview?
2. Have any prominent atheist philosophers had positive views on religion? What were their reasons?
3. Have any atheist philosophers addressed the idea that religion, even if factually wrong, does serve a purpose and that any system (science or other) that eliminates religion needs to provide a workable substitute? | 2015/10/26 | [
"https://philosophy.stackexchange.com/questions/29063",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/13808/"
] | What you describe as broadly "atheist" is usually called religiously unaffiliated, and described as having or seeking no particular religion. This is much broader than atheism, which asserts denial of god(s), and covers agnostics, atheists, deists, humanists, etc. The views range from sympathetic to religion, but to no particular version of it, to god(s) may or may not exist, if they do they may or may not care about us, if they do we do not have to care about them. The [breakdown in the US](https://en.wikipedia.org/wiki/Irreligion_in_the_United_States) is "68% believe in God, 12% are atheists, 17% are agnostics; 18% consider themselves religious, 37% consider themselves as spiritual but not religious, and 42% considers themselves as neither spiritual or religious; and 21% pray every day and 24% pray once a month".
Your position is close to deism, belief in higher power behind the order of the universe, sometimes metaphorically described as "the god of poets and philosophers", and religious humanism, focusing of religious rituals and beliefs on human needs, interests, and abilities, accompanied by humanistic ethics."Don't care" atheists are probably better characterized as agnostics, like atheists they do not believe in god(s), but unlike them they do not believe in no god(s) either, they certainly do not assert or defend any atheistic claims.
If you want a systematic philosophical outlook for your view may I suggest Immanuel Kant. Like you he rejects intellectual arguments for existence of God, and denies that we can have any specific knowledge of him in the first Critique. But like you he does not leave it at that. "*I had to limit knowledge to clear room for the faith*". In the second and third Critique he argues that we have needs over and above intellectual ones to lead our lives, and rehabilitates moral, religious and artistic expression. Kant's categorical imperative, act according to maxim that you wish to become universal law, certainly underpins transcendent morality.
In a way practical reason can transcend the limitations of intellect (pure reason), but Kant is strategically vague on the status of this transcendence. Officially, he is an agnostic, we do not know and we can never know, only intellect provides knowledge and it is restricted to the empirical. But at the same time knowledge is not everything, and intellect alone is incapable of grasping the fullness of being. One interpretation is that while we can not know we can still hypothesize, and perhaps get glimpses of things in themselves in some aesthetic and spiritual experiences. Another interpretation is that practical reason demands that we structure our lives "as if" God and moral law govern the world. Many agnostic, deist and religiously humanistic beliefs find a natural home in the Kantian system.
The added bonus is that it is fortified against the obvious objection from existentialists, atheists and other skeptics. That higher power sought to guarantee us transcendent meaning and values does not and can not provide any such guarantee. Because it is still us constructing this higher power to construct our own meaning and values, nothing more. We might as well cut out the intermediary. Kantian response is that these spiritual a priori of practical reason are as required for the unity and order of our life experience, as a priori of pure reason are required for the unity and order of our intellectual knowledge. | Believing in a religion will likely change your behaviour, completely unrelated to the question whether your religion is based on a correct or incorrect belief. That change may be positive or negative. Anybody, including an atheist, will appreciate if your behaviour changes in a positive way due to your religion. But if that religious person tries to convince an atheist of their religion, the atheist will likely see this as a negative behaviour.
On the other hand, an atheist may not appreciate that someone believing in a religion bases their life on an incorrect belief. (Or they may not care about what you do with your life, since it is your life).
On the third hand, an atheist grown up among many Christians might enjoy walking to a church on a Sunday, sitting there with lots of other people, listen to someone speaking at the front, singing a few songs with other people - some atheists will enjoy it, some will find it boring, some will dislike it.
All in all, anybody including an atheist will evaluate how religion affects them, and value or not value religion accordingly. Would the world be a better place without Christian / Muslim / Hindu / any other religion or not? Everybody is allowed their own answer to that question.
We should also remember that there are not just atheists, but that there are also religious people who accept only one religion and not others. For example, there is one spectacularly anti-religion person right now who wants to become president of the USA.
And "being sympathetic to religion" is not right: It should be "sympathetic to one specific religion". Different religions affect their believers in different ways. If your religion told you to murder small children, then no atheist, and no believer of any other religion, will be sympathetic to your religion. |
8,618,168 | Is there an "IN" type function like the one used in sql that can be used in excel? For example, if i am writing an If statement in excel and I want it to check the contents of a cell for 5 different words can i write something like:
```
=If(A1=IN("word1","word2","word3","word4","word5"),"YES","NO")
``` | 2011/12/23 | [
"https://Stackoverflow.com/questions/8618168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060293/"
] | You could use MATCH :
```
=MATCH(A1, {"word1","word2","word3","word4","word5"}, 0)
```
which will return the index of the matching item in the array list. The trailing 0 means it should be an exact match. It will return #N/A if it isn't there, so you can tag a `IF(ISNA(` onto the front to make it behave like your "IN":
```
=IF(ISNA(MATCH(A1, {"word1","word2","word3","word4","word5"}, 0)),"NO","YES")
```
Note the change in order of the `"YES"` and `"NO"` | I think an improvement on
```
=IF(OR(A1={"word1","word2","word3","word4","word5"}),"YES","NO")
```
would be to use
```
=IF(OR(A1={"word1","word2","word3","word4","word5"}),A1,"NO");
```
which is more like the SQL's `IN` clause. |
49,914,325 | If I have a class that implements `Serializable` such as:
```
public class Foo implements Serializable {
public String a;
public String b;
}
```
Is using `ObjectOutputStream` to serialize of the object deterministic? | 2018/04/19 | [
"https://Stackoverflow.com/questions/49914325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2317084/"
] | Using `apply` from base R,
```
apply(m2, 2, function(i) apply(m1, 1, function(j) min(j*i)))
```
which gives,
>
>
> ```
> [,1] [,2] [,3] [,4] [,5]
> [1,] 3 6 5 4 3
> [2,] 4 8 10 8 6
> [3,] 5 10 15 12 8
> [4,] 0 0 0 0 0
> [5,] 7 14 21 18 12
>
> ```
>
>
A fully vectorized solution can be,
```
t(matrix(do.call(pmin,
as.data.frame(
do.call(rbind, rep(split(m1, 1:nrow(m1)), each = 5)) * do.call(rbind, rep(split(t(m2), 1:nrow(m2)), 5)))),
nrow(m1)))
``` | We use `expand.grid` to create all possible combinations of row and col pairs. We then use `mapply` to multiply all the row-column combination element wise and then select the `min` from it.
```
mat <- expand.grid(1:nrow(A),1:nrow(B))
mapply(function(x, y) min(matrix_A[x,] * matrix_B[, y]) , mat[,1], mat[,2])
#[1] 3 4 5 0 7 6 8 10 0 14 5 10 15 0 21 4 8 12 0 18 3 6 8 0 12
```
Assuming `matrix_A`, `matrix_B` and `output_matrix` all have the same dimensions we can `relist` the output from `mapply` to get the original dimensions.
```
output_matrix <- mapply(function(x, y) min(matrix_A[x,] * matrix_B[, y]),
mat[,1], mat[,2])
relist(output_matrix, matrix_A)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 3 6 5 4 3
#[2,] 4 8 10 8 6
#[3,] 5 10 15 12 8
#[4,] 0 0 0 0 0
#[5,] 7 14 21 18 12
``` |
17,386,453 | This question have probably been asked here before but i dont know what it and how to properly name it.
Heres my objective:
Im trying to make multiple designs for separate pages. Example I have a homepage design but i also have a separate design for my login page and member are page. I usually use a header.pp and footer.php and put content in between but i dont see how that can be done here.
Example of what im trying to do is <http://instagram.com/> you see how the homepage has its own design then when you hit login it has it own design with no elements from homepage how can i do that and move away from my header and footer design system. | 2013/06/30 | [
"https://Stackoverflow.com/questions/17386453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535596/"
] | Surely just don't use your header and footer temps and make new ones instead, or make a new style sheet for any pages requiring a different design. | You are looking for **templates**. PHP is after all a webpage-template-language so it can be done very easy.
I wrote a simple tutorial a while ago on how to do this on your own.
<http://gustavsvalander.com/how-to-create-your-own-template-engine-using-php-files/>
The function
------------
```
<?php
// Load a php-file and use it as a template
function template($tpl_file, $vars=array()) {
$dir='your-app-folder/view/'.$tpl_file.'.php';
if(file_exists($dir)){
// Make variables from the array easily accessible in the view
extract($vars);
// Start collecting output in a buffer
ob_start();
require($dir);
// Get the contents of the buffer
$applied_template = ob_get_contents();
// Flush the buffer
ob_end_clean();
return $applied_template;
}
}
```
The template
------------
```
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<p><?php echo $content ?></p>
</body>
</html>
```
How to use
----------
```
<?php
require "template.php";
$template_vars = array('title'=>'Test', 'content'=>'This is content');
echo template('header');
echo template('template_for_firstpage', $template_vars);
echo template('footer');
``` |
6,904,139 | I'm using this tutorial to Fake my DbContext and test: <http://refactorthis.wordpress.com/2011/05/31/mock-faking-dbcontext-in-entity-framework-4-1-with-a-generic-repository/>
But i have to change the FakeMainModuleContext implementation to use in my Controllers:
```
public class FakeQuestiona2011Context : IQuestiona2011Context
{
private IDbSet<Credencial> _credencial;
private IDbSet<Perfil> _perfil;
private IDbSet<Apurador> _apurador;
private IDbSet<Entrevistado> _entrevistado;
private IDbSet<Setor> _setor;
private IDbSet<Secretaria> _secretaria;
private IDbSet<Pesquisa> _pesquisa;
private IDbSet<Pergunta> _pergunta;
private IDbSet<Resposta> _resposta;
public IDbSet<Credencial> Credencial { get { return _credencial ?? (_credencial = new FakeDbSet<Credencial>()); } set { } }
public IDbSet<Perfil> Perfil { get { return _perfil ?? (_perfil = new FakeDbSet<Perfil>()); } set { } }
public IDbSet<Apurador> Apurador { get { return _apurador ?? (_apurador = new FakeDbSet<Apurador>()); } set { } }
public IDbSet<Entrevistado> Entrevistado { get { return _entrevistado ?? (_entrevistado = new FakeDbSet<Entrevistado>()); } set { } }
public IDbSet<Setor> Setor { get { return _setor ?? (_setor = new FakeDbSet<Setor>()); } set { } }
public IDbSet<Secretaria> Secretaria { get { return _secretaria ?? (_secretaria = new FakeDbSet<Secretaria>()); } set { } }
public IDbSet<Pesquisa> Pesquisa { get { return _pesquisa ?? (_pesquisa = new FakeDbSet<Pesquisa>()); } set { } }
public IDbSet<Pergunta> Pergunta { get { return _pergunta ?? (_pergunta = new FakeDbSet<Pergunta>()); } set { } }
public IDbSet<Resposta> Resposta { get { return _resposta ?? (_resposta = new FakeDbSet<Resposta>()); } set { } }
public void SaveChanges()
{
// do nothing (probably set a variable as saved for testing)
}
}
```
And my test like that:
```
[TestMethod]
public void IndexTest()
{
IQuestiona2011Context fakeContext = new FakeQuestiona2011Context();
var mockAuthenticationService = new Mock<IAuthenticationService>();
var apuradores = new List<Apurador>
{
new Apurador() { Matricula = "1234", Nome = "Acaz Souza Pereira", Email = "acaz@telecom.inf.br", Ramal = "1234" },
new Apurador() { Matricula = "4321", Nome = "Samla Souza Pereira", Email = "samla@telecom.inf.br", Ramal = "4321" },
new Apurador() { Matricula = "4213", Nome = "Valderli Souza Pereira", Email = "valderli@telecom.inf.br", Ramal = "4213" }
};
apuradores.ForEach(apurador => fakeContext.Apurador.Add(apurador));
ApuradorController apuradorController = new ApuradorController(fakeContext, mockAuthenticationService.Object);
ActionResult actionResult = apuradorController.Index();
Assert.IsNotNull(actionResult);
Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
ViewResult viewResult = (ViewResult)actionResult;
Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(IndexViewModel));
IndexViewModel indexViewModel = (IndexViewModel)viewResult.ViewData.Model;
Assert.AreEqual(3, indexViewModel.Apuradores.Count);
}
```
I'm doing it right? | 2011/08/01 | [
"https://Stackoverflow.com/questions/6904139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492460/"
] | Unfortunately you are not doing it right because that article is wrong. It pretends that `FakeContext` will make your code unit testable but it will not. Once you expose `IDbSet` or `IQueryable` to your controller and you fake the set with in memory collection you can never be sure that your unit test really tests your code. It is very easy to write a LINQ query in your controller which will pass your unit test (because `FakeContext` uses LINQ-to-Objects) but fails at runtime (because your real context uses LINQ-to-Entities). That makes whole purpose of your unit testing useless.
My opinion: Don't bother with faking context if you want to expose sets to controller. Instead use integration tests with real database for testing. That is the only way how to validate that LINQ queries defined in controller do what you expect.
Sure, if you want to call just `ToList` or `FirstOrDefault` on your sets your `FakeContext` will serve you well but once you do anything more complex you can find a trap pretty soon (just put the string *"Cannot be translated into a store expression"* into Google - all these problems will appear only when you run Linq-to-entities but they will pass your tests with Linq-to-objects).
This is quite common question so you can check some other examples:
* [To return IQueryable or not return IQueryable](https://stackoverflow.com/questions/718624/to-return-iqueryablet-or-not-return-iqueryablet)
* [Unit Testing DbContext](https://stackoverflow.com/questions/6766478/unit-testing-dbcontext)
* [ASP.NET MVC3 and Entity Framework Code first architecture](https://stackoverflow.com/questions/5609508/asp-net-mvc3-and-entity-framework-code-first-architecture/5610685#5610685)
* [Organizationally, where should I put common queries when using Entity Framework Code First?](https://stackoverflow.com/questions/5488313/organizationally-where-should-i-put-common-queries-when-using-entity-framework-c/5488947#5488947)
* [Is it possible to stub Entity Framework context and classes to test data access layer?](https://stackoverflow.com/questions/6262588/is-it-possible-to-stub-entity-framework-context-and-classes-to-test-data-access-l/6262724#6262724) | As Ladislav Mrnka mentioned, you should test Linq-to-Entity but not Linq-to-Object. I normally used Sql CE as testing DB and always recreate the database before each test. This may make test a little bit slow but so far I'm OK with the performance for my 100+ unit tests.
First, change the connection string setting with SqlCe in the *App.config* of you test project.
```
<connectionStrings>
<add name="MyDbContext"
connectionString="Data Source=|DataDirectory|MyDb.sdf"
providerName="System.Data.SqlServerCe.4.0"
/>
</connectionStrings>
```
Second, set the db initializer with [DropCreateDatabaseAlways](http://msdn.microsoft.com/en-us/library/gg679506%28v=vs.103%29.aspx).
```
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());
```
And Then, force EF to initialize before running each test.
```
public void Setup() {
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());
context = new MyDbContext();
context.Database.Initialize(force: true);
}
```
*If you are using xunit, call Setup method in your constructor. If you are using MSTest, put TestInitializeAttribute on that method. If nunit.......* |
42,274,398 | i am using `FCM` for push messages and handling all incoming push notification in onMessageReceived. Now the issue is with parsing nested json that comes inside this function `remoteMessage.getData()`
I have following block coming as a push notification in device. content of data payload could be varied here it is dealer later on it can be `productInfo`
```
{
"to": "/topics/DATA",
"priority": "high",
"data": {
"type": 6,
"dealerInfo": {
"dealerId": "358",
"operationCode": 2
}
}
}
```
this how i am parsing it
```
if(remoteMessage.getData()!=null){
JSONObject object = null;
try {
object = new JSONObject(remoteMessage.getData());
} catch (JSONException e) {
e.printStackTrace();
}
}
```
now i am getting data with blackslashes as `remoteMessage.getData()` returns `Map<String,String>` so probably my nested block is being converted in string not sure though.
```
{
"wasTapped": false,
"dealerInfo": "{\"dealerId\":\"358\",\"operationCode\":2}",
"type": "6"
}
```
and if i write `object = new JSONObject(remoteMessage.getData().toString());` then it got failed with following notification
```
{
"to": "regid",
"priority": "high",
"notification" : {
"body": "Message Body",
"title" : "Call Status",
"click_action":"FCM_PLUGIN_ACTIVITY"
},
"data": {
"type": 1,
"callNumber":"ICI17012702",
"callTempId":"0",
"body": "Message Body",
"title" : "Call Status"
}
}
```
*error* i get is
```
> org.json.JSONException: Unterminated object at character 15 of
> {body=Message Body, type=1, title=Call Status, callNumber=ICI17012702,
> callTempId=0}
``` | 2017/02/16 | [
"https://Stackoverflow.com/questions/42274398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405383/"
] | try this code:
```
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.e("DATA",remoteMessage.getData().toString());
try
{
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e("JSON OBJECT", object.toString());
String callNumber = object.getString("callNumber");
//rest of the code
}
}
```
Also make sure your JSON is valid use [This](https://jsonformatter.curiousconcept.com/) | Faced this issue when migrating from GCM to FCM.
The following is working for my use case (and OP payload), so perhaps it will work for others.
```
JsonObject jsonObject = new JsonObject(); // com.google.gson.JsonObject
JsonParser jsonParser = new JsonParser(); // com.google.gson.JsonParser
Map<String, String> map = remoteMessage.getData();
String val;
for (String key : map.keySet()) {
val = map.get(key);
try {
jsonObject.add(key, jsonParser.parse(val));
} catch (Exception e) {
jsonObject.addProperty(key, val);
}
}
// Now you can traverse jsonObject, or use to populate a custom object:
// MyObj o = new Gson().fromJson(jsonObject, MyObj.class)
``` |
15,731,115 | I made a Java program that generate ASCII characters.
Here the following code if you want to try:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class asciiTable implements ActionListener {
private static JButton exebouton;
private JTextArea ecran = new JTextArea();
private JScrollPane scrollecran = new JScrollPane(ecran);
String line = "-------------";
public static void main(String[] args) {
new asciiTable();
}
private asciiTable() {
// Window
JFrame frame = new JFrame("Name");
frame.setBounds(400, 350, 625, 355);
frame.setLayout(null);
Container container = frame.getContentPane();
// Panel
JPanel panneau = new JPanel();
panneau.setLayout(null);
panneau.setBounds(2, 42, 146, 252);
frame.add(panneau);
JLabel nglabel = new JLabel("Click");
nglabel.setBounds(5, 0, 200, 20);
panneau.add(nglabel);
// Button
exebouton = new JButton("Execute");
exebouton.setBounds(4, 18, 138, 47);
exebouton.addActionListener(this);
panneau.add(exebouton);
// Text Area
ecran.setEditable(false);
ecran.setLineWrap(true);
scrollecran.setBounds(150, 42, 467, 252);
container.add(scrollecran);
// Show
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
Object test = e.getSource();
ecran.setText(ecran.getText() + line + '\n'
+ "[ASCII TABLE]" + '\n'
+ line + '\n');
for (int i = 32, j = 0; i <= 800; i++, j++){ // WARNING: Big loop might lag your computer
String putzero = "";
if (i < 100){
putzero = "0";
}
if (j >= 5){
ecran.setText(ecran.getText() + "\n");
j = 0;
}
ecran.setText(ecran.getText() + "[" + putzero + i + "] " + Character.toString ((char) i) + "\t");
}
ecran.setText(ecran.getText() + "\n");
}
}
```
My question is: Why a big loop in Java GUI lags or freezes my computer? Is there a way to improve the speed? | 2013/03/31 | [
"https://Stackoverflow.com/questions/15731115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2117589/"
] | Swing is single threaded. You are performing a resource intensive action in the `EDT` preventing UI updates. Use one of Swing's [concurrency mechanisms](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) to handle this functionality such as a [SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html). | Consider to use a worker thread. After the thread finishes its work you can update the UI synchronously or asynchronously with the SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater() method. The passed Runnable is executed in the UI thread, which enables you to update the UI in that thread. |
6,916,989 | In the Symfony2 documentation it gives the simple example of:
```
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));
```
To simulate a file upload.
However in all my tests I am getting nothing in the $request object in the app and nothing in the `$_FILES` array.
Here is a simple `WebTestCase` which is failing. It is self contained and tests the request that the `$client` constructs based on the parameters you pass in. It's not testing the app.
```
class UploadTest extends WebTestCase {
public function testNewPhotos() {
$client = $this->createClient();
$client->request(
'POST',
'/submit',
array('name' => 'Fabien'),
array('photo' => __FILE__)
);
$this->assertEquals(1, count($client->getRequest()->files->all()));
}
}
```
**Just to be clear.** This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.
**Edit**
I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request.
<https://github.com/symfony/symfony/pull/1891> | 2011/08/02 | [
"https://Stackoverflow.com/questions/6916989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210409/"
] | This was an error in the documentation.
Fixed [here](https://github.com/symfony/symfony-docs/commit/e6027eb):
```
use Symfony\Component\HttpFoundation\File\UploadedFile;
$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);
$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));
```
Documentation [here](http://symfony.com/doc/current/book/testing.html#working-with-the-test-client) | Here is a code which works with Symfony 2.3 (I didn't tried with another version):
I created an `photo.jpg` image file and put it in `Acme\Bundle\Tests\uploads`.
Here is an excerpt from `Acme\Bundle\Tests\Controller\AcmeTest.php`:
```
function testUpload()
{
// Open the page
...
// Select the file from the filesystem
$image = new UploadedFile(
// Path to the file to send
dirname(__FILE__).'/../uploads/photo.jpg',
// Name of the sent file
'filename.jpg',
// MIME type
'image/jpeg',
// Size of the file
9988
);
// Select the form (adapt it for your needs)
$form = $crawler->filter('input[type=submit]...')->form();
// Put the file in the upload field
$form['... name of your field ....']->upload($image);
// Send it
$crawler = $this->client->submit($form);
// Check that the file has been successfully sent
// (in my case the filename is displayed in a <a> link so I check
// that it appears on the page)
$this->assertEquals(
1,
$crawler->filter('a:contains("filename.jpg")')->count()
);
}
``` |
556,388 | I have been archiving mailboxes on our Exchange 2010 server and subsequently deleting large numbers of messages from nearly all mailboxes by setting retention periods on them. I would like to know how much of the database is now just whitespace so that I can gauge how much space will be freed up by defragging it using ESEUTIL.
So, I run:
```
Get-MailboxDatabase -Status | ft Name,DatabaseSize,AvailableNewMailboxSpace
```
But the columns that are returned for both DatabaseSize and AvailableNewMailboxSpace are blank.
I have tried specifying the database using the "-Identity" parameter, but the result is the same.
Am I omitting something necessary? | 2013/11/20 | [
"https://serverfault.com/questions/556388",
"https://serverfault.com",
"https://serverfault.com/users/184167/"
] | The main difference is the route for 0.0.0.0/0 in the associated route table.
A private subnet sets that route to a NAT gateway/instance. Private subnet instances only need a private ip and internet traffic is routed through the NAT in the public subnet. You could also have no route to 0.0.0.0/0 to make it a truly **private** subnet with no internet access in or out.
A public subnet routes 0.0.0.0/0 through an Internet Gateway (igw). Instances in a public subnet require public IPs to talk to the internet.
The warning appears even for private subnets, but the instance is only accessible inside your vpc. | The distinction between "public" and "private" subnets in AWS VPC is determined only by whether the subnet has an Internet Gateway (IGW) attached to it. From [the AWS docs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html):
>
> If a subnet is associated with a route table that has a route to an internet gateway, it's known as a public subnet. If a subnet is associated with a route table that does not have a route to an internet gateway, it's known as a private subnet.
>
>
>
The IGW allows network traffic from the internet to reach endpoints inside the subnet.
To answer your second question:
>
> When I launch a server with a security group that allows all traffic into my private subnet, it displays a warning that it may be open to the world. If it is a private subnet, how can that be?
>
>
>
It appears AWS does not check whether your chosen subnet has a route table with an IGW or not, when displaying that warning. It's a blanket warning they always show when you set up an instance with a security group allowlisting all inbound traffic. They use "may be" (as opposed to "will be") in there to cover their butts, but the warning is only relevant if you are on a public subnet. |
382,110 | I added this script to my startup programs to change my touchpad settings on startup:
```
synclient TapButton2=2 TapButton3=3
```
But this settings don't stay this way after startup.
I changed my script to watch the results:
```
synclient TapButton2=2 TapButton3=3
synclient | grep TapButton > $HOME/tmp/touchpad.txt
```
Results were confusing, touchpad still didn't work the way I want:
```
$ cat ~/tmp/touchpad.txt
TapButton1 = 1
TapButton2 = 2
TapButton3 = 3
```
But when I ran `synclient | grep TapButton` in gnome-terminal **after startup** the output was:
```
$ synclient | grep TapButton
TapButton1 = 1
TapButton2 = 3
TapButton3 = 0
```
I tried adding delays (`sleep 10s`) to my script before and/or after every line, but this didn't help too.
Therefore I assume that there is another program, script or daemon that changes touchpad settings, but I couldn't find which one.
Two questions:
* Which program, script or daemon can change touchpad settings?
* Is there another way to **permanently** change your touchpad settings? Maybe adding such script to startup is not supposed to be working.
Update
------
I tried putting
```
Section "InputClass"
Identifier "touchpad my settings"
MatchIsTouchpad "on"
MatchOS "Linux"
MatchDevicePath "/dev/input/mouse*"
Option "TapButton1" "1"
Option "TapButton2" "2"
Option "TapButton3" "3"
Option "PalmDetect" "on"
EndSection
```
into file `/usr/share/X11/xorg.conf.d/99-my.conf`. It didn't help as well. | 2013/11/25 | [
"https://askubuntu.com/questions/382110",
"https://askubuntu.com",
"https://askubuntu.com/users/99330/"
] | I've got a simple solution...
Just press the windows key and type 'startup'. You will see 'Startup applications'
* click this and then click [ADD]
* give it a name (like mousetap2)
* enter the command in the box... i.e.
```
synclient TapButton2=2 TapButton3=3
```
and that's it...
It will run on startup and configure the trackpad all without pissing about with configuration files. | The best method that have worked for me is to add your changes into Xsession.d, so it will load automatically for all users when you log into X:
(the file doesn't exists, so you can name it whatever you want. The numbers on the left means the order in which it will be executed in comparison with the other files.)
```
sudo nano /etc/X11/Xsession.d/80synaptics
```
Add just the synclient commands in that file:
```
synclient TapButton2=2 TapButton3=3
```
(should be owned by root, with permissions 644)
```
chmod 644 /etc/X11/Xsession.d/80synaptics
``` |
57,747,206 | I have json like this:
```
[
{
"product_variants": [
{
"id": 1669,
"attributes": [
{
"name": "size",
"value": "XXS"
},
{
"name": "color",
"value": "Pink"
}
]
},{
"id": 1670,
"attributes": [
{
"name": "size",
"value": "XS"
},
{
"name": "color",
"value": "Black"
}
]
}
"id": 834,
"name": "Acute Cardigan"
}, ....]
```
how i can sort `product_variants` by closing size. Order must to be by size:
```
SORT_ORDER = ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"]
```
I have only code with output `XXL` etc... If you can give me some advice
```
for product in products:
for product_variant in product.product_variants:
for attribute in product_variant.attributes:
if attribute['name'].lower() in "size":
pring(['attribute']) //print XXL...
``` | 2019/09/01 | [
"https://Stackoverflow.com/questions/57747206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3316855/"
] | You can create a dictionary and map all sizes with a value that will be used as the sorting key:
```
SORT_ORDER = {"S" : 0, "M" : 1, "L" : 2, "XL" : 3, "2XL" : 4, "3XL" : 5, "4XL" : 6, "5XL" : 7, "6XL" : 8}
```
Then you can perform sorting, based on the keys of those values:
```
productVariants = [{"product_variants" : sorted(productVariants[0]['product_variants'], key=lambda elem: SORT_ORDER[elem['attributes'][0]['value']])}]
```
For instance:
```
productVariants = [{"product_variants":[{"id":1669,"attributes":[{"name":"size","value":"M"},{"name":"color","value":"Pink"}]},{"id":1670,"attributes":[{"name":"size","value":"S"},{"name":"color","value":"Black"}]}]}]
SORT_ORDER = {"S" : 0, "M" : 1, "L" : 2, "XL" : 3, "2XL" : 4, "3XL" : 5, "4XL" : 6, "5XL" : 7, "6XL" : 8}
productVariants = [{"product_variants" : sorted(productVariants[0]['product_variants'], key=lambda elem: SORT_ORDER[elem["attributes"][0]['value']])}]
print(productVariants)
```
This will return:
```
[{'product_variants': [{'id': 1670, 'attributes': [{'name': 'size', 'value': 'S'}, {'name': 'color', 'value': 'Black'}]}, {'id': 1669, 'attributes': [{'name': 'size', 'value': 'M'}, {'name': 'color', 'value': 'Pink'}]}]}]
``` | you can use:
```
from pprint import pprint
my_list = [
{
"product_variants": [
{
"id": 1669,
"attributes": [
{
"name": "size",
"value": "XXS"
},
{
"name": "color",
"value": "Pink"
}
]
},{
"id": 1670,
"attributes": [
{
"name": "size",
"value": "XS"
},
{
"name": "color",
"value": "Black"
}
]
},{
"id": 1671,
"attributes": [
{
"name": "size",
"value": "S"
},
{
"name": "color",
"value": "Red"
}
]
}]}]
SORT_ORDER = ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL", "XS", "XXS"]
for item in my_list:
product_variants = item["product_variants"]
item["product_variants"] = sorted(product_variants, key=lambda x: SORT_ORDER.index(x['attributes'][0]['value']))
pprint(my_list)
```
output:
```
[{'product_variants': [{'attributes': [{'name': 'size', 'value': 'S'},
{'name': 'color', 'value': 'Red'}],
'id': 1671},
{'attributes': [{'name': 'size', 'value': 'XS'},
{'name': 'color', 'value': 'Black'}],
'id': 1670},
{'attributes': [{'name': 'size', 'value': 'XXS'},
{'name': 'color', 'value': 'Pink'}],
'id': 1669}]}]
``` |
62,164,311 | I have my `User` struct declared like this. How can we decode an array using `JSONdecoder`?
I get an error of **`typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))`**
```
This is my json data:
// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc
[
{
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com",
"following": [
],
"followers": [
{
"id": "5eca2f451583786f1c0ee1ba",
"fullName": "Udin Rajkarnikar",
"emailAddress": "udin@gmail.com"
}
],
"isFollowing": true
},
[
{
"createdAt": 1590581837003,
"updatedAt": 1590581837003,
"id": "5ece5a4d6e2e801e95365d50",
"text": "I love waterfalls",
"imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
},
{
"createdAt": 1590334928984,
"updatedAt": 1590334928984,
"id": "5eca95d08538288438c63779",
"text": "Creating post from iphone",
"imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
},
{
"createdAt": 1590308888243,
"updatedAt": 1590308888243,
"id": "5eca30181583786f1c0ee1bf",
"text": "asdasd",
"imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
"user": {
"id": "5eca2fa01583786f1c0ee1bc",
"fullName": "Raj Shrestha",
"emailAddress": "raj@yahoo.com"
}
}
]
]
struct User: Decodable {
let id : String
let fullName: String
let emailAddress: String
var isFollowing: Bool?
var followers, following: [User]?
var post: [Post]?
}
struct Post: Decodable {
let id: String
let createdAt: Int
let text: String
let user: User
let imageUrl: String
}
let user = try JSONDecoder().decode([User].self, from: data)
print(user)
``` | 2020/06/03 | [
"https://Stackoverflow.com/questions/62164311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13556327/"
] | The safe solution when using `fgets` would be something like this:
```
if (fgets(pass, sizeof(pass), stdin) != NULL){
int len = strlen(pass);
if (len > 0 && pass[len-1] != '\n'){
int ch;
while ((ch=getchar()) != '\n' && ch != EOF);
}
}
```
Or this:
```
if (fgets(pass, sizeof(pass), stdin) != NULL){
if (strcspn(pass, "\n") == sizeof(pass) - 1){
int ch;
while ((ch=getchar()) != '\n' && ch != EOF);
}
}
```
You need to check if there is a new line character `\n` in the string, if there isn't then there is excess characters left in the `stdin` that must be cleared. | You limited your input variable to 32 characters, so in order to stop it from doing that, simply make pass[32] bigger. |
3,825,498 | I just got a new desktop computer with Windows 7 Pro as the operating system. I installed Visual Studio 2008 on to this new computer and tried to open a previously existing ASP.NET 3.5 solution that displayed perfectly fine on my previous computer (this previous computer used the Windows XP operating system, IIS6, and IE7 browser). However, in Windows7/IE8, I’m receiving the following error:
>
> Server Error in '/' Application.
>
>
>
>
> ---
>
>
> Parser Error Description: An error
> occurred during the parsing of a
> resource required to service this
> request. Please review the following
> specific parse error details and
> modify your source file appropriately.
>
>
> Parser Error Message: The file
> '/MasterPages/MainMaster.master' does not exist.
>
>
> Source Error:
>
>
> Line 1: <%@ Page Language="C#"
> AutoEventWireup="true"
> CodeFile="default.aspx.cs"
> Inherits="\_Default"
> MasterPageFile="~/MasterPages/MainMaster.master"%>
> Line 2:
>
> Line 3: <%@ Register TagPrefix="SBLContent" TagName="SBLContentBlock"
> Src="usercontrols/content.ascx"%>
>
>
> Source File: /SBLWebSite/default.aspx
> Line: 1
>
>
>
>
> ---
>
>
> Version Information: Microsoft .NET
> Framework Version:2.0.50727.4952;
> ASP.NET Version:2.0.50727.4927
>
>
>
Please believe me when I tell you that the file ‘/MasterPages/MainMaster.master’ file does, in fact, exist.
In addition, this file’s location is properly referenced in the code (as indicated in Line 1 above), and as I said, was displayed properly by the browser in my previous computer. It might also be helpful to note that I’ve tried to navigate to other pages in this site, and this browser displays the same message for any and all master pages located in my MasterPages folder.
In summary, for some reason the browser cannot see any pages in the MasterPages folder. Can anybody tell me why I’m getting this error message when the folder and file is exactly where default.aspx says it is?
Thanks in advance! | 2010/09/29 | [
"https://Stackoverflow.com/questions/3825498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187453/"
] | Two things to check:
1. When using "~" in a file path, make sure that the current application deployment believes the root directory is the same as it was before. (I've run into this sometimes moving an app from the VS Development Server and IIS.)
2. Make sure that the user account that the server is running under has permissions to access that directory. Since you just moved the code over from another computer and probably some intermediate storage devices, the security permissions may not be right. | Instead of the "~" I was able to simply change the directory to a relative ".." So, what I originally had that gave me the problem was something like: "~/MasterPage/TheMainMasterPage.master" and this caused me to get the same error message. Changing it to "../MasterPage/TheMainMasterPage.master" fixed everything for me. |
28,500,851 | Here's my array (from Chrome console):

Here's the pertinent part of code:
```
console.log(hours);
var data = JSON.stringify(hours);
console.log(data);
```
In Chrome's console I get `[]` from the last line. I should get `{'Mon':{...}...}`
Here is the minimal amount of JavaScript to reproduce the issue:
```
var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs []
```
I tried some other stuff like
[Convert array to JSON](https://stackoverflow.com/questions/2295496/convert-array-to-json) or [Convert javascript object or array to json for ajax data](https://stackoverflow.com/questions/19970301/convert-javascript-object-or-array-to-json-for-ajax-data) but the problem remains. | 2015/02/13 | [
"https://Stackoverflow.com/questions/28500851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4536489/"
] | Here is the minimal amount of javascript to reproduce the issue
```
var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs []
```
The issue with the above is that, while javascript will be happy to let you late-bind new properties onto `Array`, `JSON.stringify()` will only attempt to serialize the actual elements in the array.
A minimal change to make the object an actual object, and `JSON.stringify` works as expected:
```
var test = {}; // here is thre only change. new array ([]) becomes new object ({})
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs {"11h30":"15h00","18h30":"21h30"}
``` | **Like all JavaScript objects, Arrays can have *properties* with string-based keys like the ones you're using. But only integer keys (or keys that can be cleanly converted to integers) are actually treated as *elements* of an Array**. This is why JSON isn't catching your properties, and it's also why your Arrays are all reporting their length as zero.
**If you really need to use non-integer keys, you should be using plain Objects, not Arrays**. This method has its own gotchas -for example, you need to be careful with for-in loops- but JSON will work the way you expect it to.
```
var hours = {
"Mon" : {
"11h30" : "15h00",
"18h30" : "21h30"
},
"Tue" : {},
"Wed" : {
"11h30" : "15h00",
"18h30" : "21h30"
},
"Thu" : {},
"Fri" : {},
"Sat" : {},
"Sun" : {
"11h30" : "15h00",
"18h30" : "21h30"
},
}
``` |
45,695 | I've bought a bag of small dried and salted fish at my local Chinese market. My guess was that the thingies could be eaten right out of the box, but they are too bony and salty.
I guess they need some kind of desalting and perhaps frying, but not sure what to try.
From the back of the bag drawings and text (thanks Google Translate!) I managed to infer that it's really a snack (ideal beer companion!)
Any ideas on how to prepare/serve them?
 | 2014/07/18 | [
"https://cooking.stackexchange.com/questions/45695",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/2882/"
] | Next time get the really really small ones. Those are best raw. The bigger ones usually are fried first before eating. Then the bones get crunchy and the saltiness is not as prominent.
Others are used for stocks or garnishes, as said before. | Based on my russian experience, this is ready to go snack. Just bite it and drink beer.
I know, my american friends usually scared to try "uncooked" fish, but salty dried fish is good. Also I would recommend you to try salty dried calamari or octopuses.
Cheers! |
119,850 | :-)
We would like to ask a question of general interest, as it might be the case in other studies. It is the first time I stumble upon this situation.
In our research, we have used the wild-type of a microbial strain and mutants for about 7 distinct genes. They were all subjected to different treatments and assessed by the same response variables. The seven genes, however, are not strictly related to each other, so that 3 of them as a group make-up one story, and the other 4 make-up a different one (thereby, two distinct manuscripts). The reason why they were all worked together (the wild-type and the mutants for these genes) were simply logistics and efficiency of resources usage.
One of the authors are concerned with the fact that for both papers with different groups of mutants (hence very different stories), the wild-type controls were the same! Therefore, he is afraid that using the same pictures and data in this case would configure a self-plagiarism issue between the two manuscripts.
Could you please help us on deciding whether this will indeed be an issue, or not?
Thank you very much in advance for your kindness and attention to this matter.
Best regards,
Dr. Leandro. | 2018/11/10 | [
"https://academia.stackexchange.com/questions/119850",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/100535/"
] | It is really hard to judge a case like this. It could be anything from a wonderful academic training situation to extreme abuse. It would depend on a lot of things not stated here. What is the agreement between X and the professor, now and for the future? What does the professor actually do with the time freed by X? Is it to X's benefit in any way - say via joint research? Does the professor have such a stellar academic reputation that anyone standing in his/her aura is bound to be a success. Or, such a stellar reputation that they can get away with abusing students without anyone complaining?
If the professor treats the student like a colleague and they have agreed between them that the extra work will put the student into an excellent position for the future, then all is well. If the situation is delaying the student in some way, or impeding his/her research or future then it should be condemned.
But if you are to step into such a role, you need to make sure that you agree to it and accept whatever tradeoffs there are. If they are to your benefit, then it would be worth considering, though not necessarily accepting.
You should have a conversation with X to see what the long term view is. You should have a conversation with the professor to set appropriate limits and expectations.
One of the extremes, of course is Stephen Hawking. His students were willing to do everything for him. Happy to do it. Thrilled to be there. Even when it was hard. | That sounds like a very unhealthy relationship. Some of the answers on this stack exchange, surprise me. The professor is not always right. It's not alright for the professor to sit back not do his/her job description and force all the work on their student. This doesn't sound right. Even if the student is a TA they are a TA they shouldn't be required to work beyond the hours they are contracted to work. They should not be doing the professor's job. They should be having their own office hours and depending on their contract they should grade and they should lecture on rare occasions. They should not be doing the professor's office hours. The undergraduate students don't pay thousands of dollars a semester/quarter to only attend office hours with a graduate student and not the professor. In addition fixing his resume is what tips the iceberg. They should do their own gritty work. |
64,738,707 | Is there a way I can replace the 2nd character in a cell with an asterisk(`*`)?
Something like this:
```
var name = publicWinners.getRange(i, 1);
name.setValue( → 2nd character = "*" ← );
```
I want to create a list of winners in a contest that can be posted publicly with the winners' personal information partially hidden.
Any help would be greatly appreciated. Thank you! | 2020/11/08 | [
"https://Stackoverflow.com/questions/64738707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14600385/"
] | Use [String.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) :
```js
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const str = "John Doe";
const output = str.replace(/(.{1})./,"$1*");
console.info(output);
```
```html
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
```
* `.` - Any character
* `(.{1})` - Any character repeated 1 time. `{1}` may be removed, but used to quantify previous characters, if you want to replace the third or fourth character. Capture group`$1`
* `.` - Final character to replace with `*` | You can use the [`split()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) and [`join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) methods to manipulate the string.
```
/**
* Replace a character of a string with a new character at the specified position.
* @param {string} word - The word to modify.
* @param {number} index - The character index to modify. Starts from zero.
* @param {string} newChar - The new character that will overwrite the existing character.
* @returns {string}
*/
function replaceCharAt(word, index, newChar) {
return word.split('').map(function(char, charIndex) {
if (charIndex == index) {
return newChar;
}
return char;
}).join('');
}
```
A simple test you can run:
```js
var originals = [
'Sangmyeong',
'Jaedong',
'Sangjin',
'Gueho'
];
originals.forEach(original => console.log(replaceCharAt(original, 1, '*'))); // [S*ngmyeong, J*edong, S*ngjin, G*eho]
function replaceCharAt(word, index, newChar) {
return word.split('').map(function(char, charIndex) {
if (charIndex == index) {
return newChar;
}
return char;
}).join('');
}
``` |
28,059,865 | I wonder why CSS' height can't resize a 'select' element in HTML.
```
<select>
<option>One</option>
<option>Two</option>
</select>
```
and CSS:
```
select {
height: 40px;
}
```
Thanks in advance! | 2015/01/21 | [
"https://Stackoverflow.com/questions/28059865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4460255/"
] | You should use line-height along with. Below fiddle shows you the same.
<http://jsfiddle.net/pckh7spw/>
```
select {
height: 40px;
line-height: 40px;
border: 1px solid #ccc;
width: 200px;
}
``` | if any css overriding this class then use following class
```
select {
height: 40px !important;
line-height: 40px;
border: 1px solid #ccc;
width: 200px;
}
``` |
43,191,342 | I'm trying to set the index of a dataframe from one of the columns in my dataframe. The old index of this dataframe is essentially meaningless.
[](https://i.stack.imgur.com/RAh5M.png)
But when I use `set_index(['Name'])` I add a new column, which isn't the behavior I want. I can't find a way around this:
[](https://i.stack.imgur.com/7oh4t.png)
Thanks! | 2017/04/03 | [
"https://Stackoverflow.com/questions/43191342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2584721/"
] | You are not sending the csrf token in your API call, so thats the culprit.
This should work for you.
```
$.ajax({
url: '/upload_ticket/',
type : "POST", // http method
dataType: 'json',
data : { 'file' : $('#fileinput').val(), 'csrfmiddlewaretoken' : document.getElementsByName('csrfmiddlewaretoken')[0].value }, // data sent with the post request
// handle a successful response
success : function() {
alert('succes');
},
// handle a non-successful response
error : function() {
alert('error');
}
});
```
}; | ```
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '='))
{
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
```
Add after jQuery library including, it always pass csrftoken to your request, you don't need manually pass csrftoken anymore ! |
37,015,563 | I have a class with two members - m1 is a string and m2 is a dictionary.
I want to reset m2 by calling myA.m2.reset() equivalently to self.m2.clear(); and reset m1 by calling myA.m1.reset() equivalently to self.m1 = None.
So how can I implement this reset method in class A?
```
class A(object):
def __init__(self):
self.m1 = None
self.m2 = {}
def reset(self):
"""
if it is m2: self.m2.clear()
elif it is m1: self.m1 = None
"""
myA = A()
myA.m2[1] = 2
``` | 2016/05/03 | [
"https://Stackoverflow.com/questions/37015563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693581/"
] | EDIT: OP I'm very sorry - my suggestion to use descriptors seemed like a good idea, but it isn't going to be enable you to write code like `myA.m2.reset()` in a robust way.
I'll keep this answer here for reference in case it gives you any ideas.
---
This is a job for python [descriptors](https://docs.python.org/3/reference/datamodel.html#implementing-descriptors)!
If I understand, you want to be able to do something like this:
```
myA.some_member.reset()
```
...and have custom behavior depending on what "type" (I use that word loosely) of member it is. You could get this working just fine for the dict-like `m2` member:
```
class ResettableDict(dict):
def reset(self):
self.clear()
class A(object):
def __init__(self):
self.m2 = ResettableDict()
```
The problem you are going to run into, though, is that you cannot do something similar by subclassing `str`, since strings are immutable (i.e., they can't be "cleared" like a `dict`). Furthermore, when you use the assignment operator to give your `ResettableString` member some value, it will cease to be a `ResettableString`. Example:
```
class ResettableString(str):
pass # Just a placeholder for this example
```
Test:
```
>>> myA = A()
>>> myA.m2[1] = 2
>>> type(myA.m2)
<class '__main__.ResettableDict'> # works!
>>> myA.m1 = 'string!'
>>> type(myA.m2)
<class 'str'> # no longer a ResettableString! DOH!!!
```
Python has the capability to "overload" most operators. But you can't write a class that generally overloads the `=` (assignment) operator. What to do?
ANSWER: as I said at the beginning, descriptors! We're going to make a descriptor called `Resettable`. A `Resettable` will have a `reset()` method that reverts the value of the member to the default value.
You'll use it like this:
```
class A(object):
m1 = Resettable('m1', None)
m2 = Resettable('m2', {})
```
Here is `Resettable`:
```
class Resettable(object):
'''A class descriptor that can be reset to its default value.'''
def __init__(self, name, default):
self.default = default
def reset(self):
setattr(self.current_instance, self.name, self.default)
del self.current_instance
def __get__(self, obj, typ):
try:
return getattr(obj, '_%s' % self.name)
except AttributeError:
setattr(obj, self.name, self.default)
return self.default
finally:
self.current_instance = obj
def __set__(self, obj, value):
setattr(obj, '_%s' % self.name, value)
```
A Python descriptor provides a lot of functionality. One of those things is "overloading" of both the `=` (assignment) operator (via the `__set__` method; providing this method is optoinal), and the `.` ("get") operator (via the `__get__` method).
Now when you assign a value to your object members, the default Python get and set behavior is overridden by the behavior provided by the descriptor object.
```
>>> myA = A()
>>> myA.m2[1] = 2
>>> type(A.m2)
<class '__main__.Resettable'> # works!
>>> myA.m1 = 'string!'
>>> type(A.m1)
<class '__main__.Resettable'> # works!!!!!
>>> myA.m2.reset()
>>> myA.m1.reset()
``` | m1 and m2 are members of the class not instances of it.The members of the class cant call on functions of their containing class, the members can only call functions inside their instance. In sinpler context m1 shouldnt be calling myA.reset() .I'm pretty sure you can just call myA.m1.clear(). If you want reset to do it you could have an argument passed in telling the class which variable to clear. |
15,118,830 | I started ZendSkeletonApplication via Composer. I will need for my project PRIVATE repository (Git). How to do it? Skeleton have now .git files so how I can work with my project for example on BitBucket?
Regards | 2013/02/27 | [
"https://Stackoverflow.com/questions/15118830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999468/"
] | The best way to create a ZF2 skeleton project from scratch is to use ZFTool (<http://framework.zend.com/manual/2.1/en/modules/zendtool.introduction.html>). Install it to /usr/local/bin (with executable permissions) and then you can do this:
```
$ zftool.phar create project project_name
```
This will give you a skeleton application in the project\_name folder which is completely git free.
Now create a private repository on BitBucket and follow the instructions for setting up with code already on your disk.
Note that the project created in project\_name has a .gitmodules file. If you're using Composer, you can just delete this file before you add to BitBucket. If you want to use submodules, then its set up with ZF2 as a submodule ready for you to init and update. | Once you forked the [ZendSkeletonApplication](https://github.com/zendframework/ZendSkeletonApplication), you can push the fork to a private repository in your Bitbucket account or on your own servers/network.
You can deploy your own packages/modules on Bitbucket and even [require them via composer](http://getcomposer.org/doc/articles/handling-private-packages-with-satis.md) if you want, but as @Lars stated, it's possible to simply use a [git submodule](http://book.git-scm.com/5_submodules.html) if that's easier for you.
There's also a great presentation by Niels Aderman about [advanced composer usage](http://www.naderman.de/slippy/src/?file=2012-11-22-You-Thought-Composer-Couldnt-Do-That.html) if you're not familiar with the tool. |
489,667 | What is the etymology for the phrase, “God save the king?”
All that I find is a trail back to the song. Yet it seems to me that there must be an origin that goes back into the language. | 2019/03/14 | [
"https://english.stackexchange.com/questions/489667",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/340149/"
] | It isn't incorrect (except that 'I' should always be in upper case). As a sentence on its own, it's probably better with 'saw', but you could say something like "While I was travelling I had seen some beautiful buildings, but the new art gallery in my home town was as fine as any of them". | This is NOT grammatical.
The correct wording should be
>
> While I was travelling, I saw beautiful buildings.
>
>
>
This is because the use of "while" implies doing something at the same time in both clauses of the sentence. "Had been" implies that the buildings were seen before they were travelling.
Please refer to this site for [uses of the past perfect](https://examples.yourdictionary.com/past-perfect-tense-examples.html). |
15,552,590 | I'm using a form that use the following script to calculate the item price including VAT:
```
function calculateTotaleIVA() {
var tot = document.getElementById('totale').value;
document.getElementById('totale_prodotto').value = Math.round(tot*121)/100;
totale_prodotto.value = document.getElementById('totale_prodotto').value.replace(".", ",");
totale.value = document.getElementById('totale').value.replace(".", ",");
}
```
This function works fine but I have a questions. Some times the result is like this:
46,4
I want to see at screen two digits after point decimal like this:
46,40
How can I fix the above function to solve it?
Thanks in advance. | 2013/03/21 | [
"https://Stackoverflow.com/questions/15552590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2195922/"
] | Use [toFixed](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed)
```
(Math.round(tot*121)/100).toFixed(2)
``` | you can use `toFixed(2)` for that
toFixed(No of digits)
```
(Math.round(tot*121)/100).toFixed(2);
```
[see here](http://www.w3schools.com/jsref/jsref_tofixed.asp) |
13,137,030 | I have this date format d-m-y on a string so that 01-01-12 is January, 1st of the year 2012.
Now, I want to convert this to a date object in php, to sort a set of dates, which are stored as string in an array.
Currently, I'm using strtotime and date
```
$keypoints[] = date('d-m-y', strtotime($date_str));
```
But this is sorting the resulting dates as if the format is y-m-d. The question is, how can I set the input format of the strtotime function?
Thanks in advance | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194794/"
] | PHP's strtotime() returns a unix timestamp, which is just a number. Have you considered storing these in your array and sorting like that? You would then convert back to a nice looking date when needed, for example for output. | From the PHP manual page, `strtotime` accepts "A date/time string. Valid formats are explained in [Date and Time Formats](http://www.php.net/manual/en/datetime.formats.php)".
An alternative would be to use [`DateTime::createFromFormat`](http://php.net/manual/en/datetime.createfromformat.php). |
11,949,670 | I've made an upload mechanism and now I want to create a page that lets you view the files you uploaded. I want to show them in the browser however (I only have browser-supported files like images, PDF etc).
My guess is that I can do this by only setting some headers and printing the bytes of the file. But as far as I know, I need to set the `Content-type` header to display the content correctly. How can I get the content-type of a file? Is it the same as the mime-type? | 2012/08/14 | [
"https://Stackoverflow.com/questions/11949670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898423/"
] | Yes its MIME type. Find a list at
<http://en.wikipedia.org/wiki/MIME_type> | You will have to read the contents of the file, print the appropriate headers and echo the contents. If the browser detects that it can display these file types it will display them else it will prompt the user to the save to the local system. The code will be something similar to the snippet specified below:
```
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');
readfile('file1.pdf');
``` |
70,586 | In my party I have a warlock who is partial to illusion magic. At second level, he took the 'Misty Visions' invocation, with the intent of using Silent Image to keep the party shrouded in illusory fog during combat. His logic is that because the party knows it is an illusion, they are never hindered by it, but the enemies are effectively blinded to the players until they manage to discern the illusion. In one instance, this resulted in two party members swinging with advantage on a bugbear who couldn't see them, and who had to use his action on the next turn to inspect the illusion.
In this situation, Silent Image gives most of the benefits of Darkness, a second level spell, without negatively affecting the party, and without costing a spell slot. I don't want to have to tell the player "No, that's too OP," but I'm not sure how to interpret the mechanics in a way that isn't broken.
In short:
**What does RAW say about using Silent Image on top of or between close quarters combatants?**
**How can Silent Image be interpreted/altered such that it can provide some benefit in combat, while maintaining the intended power level?** | 2015/11/01 | [
"https://rpg.stackexchange.com/questions/70586",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/8198/"
] | Cost
----
This is **not** without cost to the warlock; he has chosen to use one of his two invocations to get this thereby forgoing other choices. In addition, he uses an action to cast it and an action to move it; unless your battles are very static he would need to move it a lot. Remember, the most limited resource any creature has is not its spell slots or hit dice; it is its actions, it only gets one per turn. Good players know this and they should be thinking every turn "Is this the *best* thing I can do with my action right now?"
Innovation
----------
This is a very clever and imaginative use of the spell - this is something that you should encourage in your players; not discourage. I have had a wizard use *Silent Image* to create an picture of a hallway that the rogue could walk behind; this not only gave advantage, it also allowed sneak attack against, coincidently, a bugbear.
Disadvantages
-------------
A 15 foot cube of fog rolling towards the bugbear is going to negate surprise (its just not natural) and allow it to make an active perception check to find out where the PCs are in the cloud. The bugbear can then use its action to attack (with disadvantage); following which it can see through the cloud because "Physical interaction with the image reveals it to be an illusion" - sticking your morning star into it qualifies as "physical interaction".
It doesn't work that way, anyhow
--------------------------------
You say: " because the party knows it is an illusion, they are never hindered by it". Where does it say that in the rules?
The relevant text of the spell is:
>
> **Physical interaction** with the image reveals it to be an
> illusion, because things can pass through it. **A creature
> that uses its action** to examine the image can determine
> that it is an illusion with a successful Intelligence
> (Investigation) check against your spell save DC. If a
> creature discerns the illusion for what it is, the creature
> can see through the image.
>
>
>
There are only 2 ways to see through the image, "Physical interaction" or "use your action" **and** make a save. Knowing that it is an illusion doesn't allow you to see through it. | The PhB 254 states:
>
> Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against yo r spell save DC. If a
> creature discerns the illusion for what it is, the creature can see through the image.
>
>
>
He can see through the illusion
-------------------------------
Regarding physical interaction. If the bugbear touches the fog (which is a lot of physical interaction for me) he would immediately be able to see through it. If he throws/shoots to someone something and the projectile passes through the illusion, he would immediatly be able to see through it.
If the bugbear see a lot of proyectiles and missiles coming from an odorless, heathless fog, he would probably run in it, touching the fog and therefor been able to see through it. |
12,520 | Can we call the [greatest integer function](http://mathworld.wolfram.com/FloorFunction.html) as a periodic function with no fundamental period or is it just non-periodic.
Please explain your answer.
---
To my understanding, if we consider $f(x) = [x]$ now, $f(3) = [3] = 3$ and $f(3+0.5) = [3.5] = 3$ So, can't we say that it is periodic (**A constant function is periodic with no fundamental period**) ? But the problem is to derive the fundamental period.
**EDIT:** After checking out some aswer I am quite inquisitive to know is it really necessary to have a fundamental period to call a function periodic? However,If you go by my book it is not. | 2010/11/30 | [
"https://math.stackexchange.com/questions/12520",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/2109/"
] | A function $f(x)$ is "periodic with period $c$", with $c\gt 0$, if $f(x+c) = f(x)$ for all values of $x$. In particular, $f(x+mc) = f(x)$ for all integers $m$, by using induction.
A function is periodic if it is periodic with period $c$ for some $c\neq 0$.
Every periodic function has lots of periods: if $c$ is a period, then so is $mc$ for any positive integer $m$, at the very least; it may have others. So we may be interested in knowing what is the "quickest" that the function starts repeating. For instance, $\tan x$ certainly repeats every $2\pi$, since $\tan(x+2\pi) = \tan(x)$ for all $x$ (either both are defined and equal, or both are undefined); and by the comment above, it will repeat every $2m\pi$ for any integer $m$. But it actually repeats *more often* than every $2\pi$: we know that $\tan(x+\pi) = \tan(x)$ for all $x$. So altough it is true that $\tan(x)$ is periodic with period $2\pi$, it is *also* true that $\tan(x)$ is periodic with period $\pi$.
So we would like to have something more than just a "period"; we would like to be able to talk about the *smallest* possible period. That's what the "fundamental period" is trying to capture:
We say that a periodic function $f(x)$ has "fundamental period" $k$ if and only if $k$ is the smallest positive number such that $f(x)$ is periodic with period $k$. That means that we require:
* $f$ to be periodic with period $k$: so $f(x) = f(x+k)$ for all $x$;
* $k$ to be positive; and
* if $c$ is a positive constant such that $f(x+c) = f(x)$ for all $x$, then $k\leq c$.
So, in general, we would take the set of all positive periods of the function $f$, and look for its minimum (smallest element). The one possible problem is that not every set of positive real numbers has a smallest element, so it may be possible, at least in principle, that a function is periodic but has no fundamental period, because it *does* have periods, but it doesn't have one that is the *smallest* period.
The constant functions, $f(x) = a$ for all $x$, are an example of this pathology: they are periodic, because they satisfy the defintion of being periodic. In order to show that they satisfy the definition, we need to show that there is at least one number $c\gt 0$ such that $f(x)=f(x+c)$ for all $x$. Well, we can take $c=1$, because $f(x) = a = f(x+1)$ for all $x$. So the constant function is certainly periodic. But in fact, for *every* positive number $c$, $f(x+c) = a =f(x)$. That means that if you take *any* $c\gt 0$, then you can rightly say that "$f(x)$ is periodic with period $c$". So if we look at the set of all periods,
$$P=\{ c \in \mathbb{R}\mid c\gt 0\text{ and $f(x)$ is periodic of period $c$}\}$$
then $P=(0,\infty)$. Since the "fundamental period" is supposed to be the *smallest* element of $P$, but $P$ does *not* have a smallest element, then the constant function does *not* have a fundamental period. But it *is* periodic (we just saw it satisfies the definition).
In the case of the greatest integer function, $f$ is not periodic at all. Again, "$f$ is periodic" means "there exists $c\gt 0$ such that $f(x+c)=f(x)$ for all $x$". So the negation of "$f$ is periodic" is "for every $c\gt 0$, there exists at least one $x$ such that $f(x)\neq f(x+c)$."
In order to show that the greatest integer function $f(x)=\lfloor x\rfloor$ is **not** periodic, we need to show that given any $c\gt 0$ (think of it as a candidate for a period), there is at least one point $x$ for which $f(x)\neq f(x+c)$.
So, let $c\gt 0$ be given. I'm going to come up with some point $x$ (which will depend on $c$) with the property that $\lfloor x\rfloor\neq \lfloor x+c\rfloor$. The idea is simply to take a value of $x$ that is before some integer, but once you add $c$ to it you go *above* that integer. Then the greatest integer function will give two different values.
The simplest example to take is $x=-\frac{c}{2}$; this number is negative, so $f(-\frac{c}{2}) = \lfloor -\frac{c}{2}\rfloor\lt 0$; on the other hand, $x+c = -\frac{c}{2}+c = \frac{c}{2}$ is positive, so $f(x+c) = \lfloor \frac{c}{2}\rfloor \geq 0$. Since $f(x)$ is strictly less than $0$ and $f(x+c)$ is at least $0$, $f(x)\neq f(x+c)$. So $f(x)$ is not periodic with period $c$.
But $c$ was an *arbitrary* positive number. That means that we cannot say "$f(x)$ is periodic with period $c$" for *any* positive number, and that means, by definition, that $f(x) = \lfloor x\rfloor$ is **not** periodic. | The answers so far do not catch the fact that the floor function has indeed some built in periodicity: The function $f(x):=\lfloor x\rfloor - x$ is in fact periodic and so can be developped into a Fourier series. "For all practical purposes" one has
$$\lfloor x\rfloor =x-{1\over2} +{1\over\pi}\sum\_{k=1}^\infty{\sin(2\pi k t)\over k},$$
but here the right hand side for $t\in\mathbb Z$ does not produce the correct value. |
62,545 | I’ve been studying Japanese for a while now and came across the following dialogue:
>
> A: 私のこと、知ってるんだ。(So you know about me then?)
>
> B: 知ってるも何も、有名人じゃないか。
>
>
>
I'm not quite sure how to make sense of B's reply. I thought it would translate to something along the lines of "I don't really know anything but you're a celebrity, right?" because of the use of 何も which I know means "nothing." However, the translation provided for B was "Of course I do (know about you), you're a celebrity, right?", which really confused me.
Initially I thought that the 〜も何も was just a combination of the particle も and the word 何も but apparently that doesn't seem to be the case. So my question is, what kind of meaning does「〜も何も」give to「知ってる」and how exactly does it translate to being an affirmation of one's knowledge about something? Can「〜も何も」be used with other words and what meanings would it have in those cases? | 2018/11/01 | [
"https://japanese.stackexchange.com/questions/62545",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/31778/"
] | Look [here](https://hinative.com/ja/questions/29845) for example:
>
>
> >
> > 「~も何も」は1つの例を出して、他のものを類推させるときに使います。
> >
> >
> > 例 挨拶も何も
> >
> >
> >
>
>
> A: 「帰る前にあの人にあいさつしなきゃ」
>
>
> B: 「挨拶も何も、あの人もう帰っちゃったよ!」
>
>
> ⇒挨拶も、会うことも、話をすることもできない
>
>
>
> >
> > 病気になってしまい、勉強も何もない。
> >
> >
> >
>
>
> ⇒勉強も、遊びも、何もできない
>
>
>
In general it is used to give an example out of many and let infer the rest by analogy. Basically, when there is no room for doubt. I suppose you understand Japanese well enough and don't need a translation of the above quotation, let me know otherwise.
So, in your case I think it is used to answer using 知ってる as an example, among other many possible others, because for whatever reason there is no margin for doubt that B knows (here because A seems to be someone famous for example).
Another good example is from the [link](https://lang-8.com/1486973/journals/96618803197205736526647859648046157520) provided also by @ericfromabeno:
>
> 知ってるも何も→疑問の余地なく分かっているという意味かなと思います。
>
>
> A「あのさ、この店知ってる?」
>
>
> B「‘‘知ってるも何も‘‘俺が昔バイトしてたところだよ。」
>
>
>
---
In your case, you can see it like something along the line of "Of course I know. I know very well, or, As a matter of fact, I do more than simply knowing..." (notice this is not a translation, since you already have it, but rather trying to convey the how to interpret 知ってるも何も). | 知ってるも何も carries the idea of "it's not even a question of knowing X" or "I know all about X!"
In English, this might be one situation where we use the phrase "Of course": "Of course I know X."
a quick search found this Q&A on a language blog
<http://lang-8.com/1486973/journals/96618803197205736526647859648046157520>
and I am sure you could find more if you look around. |
95,402 | I am confused in choosing one of the following approaches.
```
\documentclass{article}
\usepackage{siunitx}
%\sisetup{detect-all}
\usepackage{amsmath}
\parindent=0pt\relax
\begin{document}
The following calculation is a trivial example
\[
\begin{aligned}
q &=CV \\
&=\num{3e-20x1000} \\
&=\num{3e-17}
\end{aligned}
\]
The following calculation is a trivial example
\begin{align*}
q &=CV \\
&=\num{3e-20x1000} \\
&=\num{3e-17}
\end{align*}
\end{document}
```
What is the difference between `aligned` in displayed mode and starred `align`?
Edit:
If there is a difference and we have to show the substitution steps above or algebraic operation steps below, which one we have to use based on the internationally adopted convention?
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
The following calculation is a trivial example
\[
\begin{aligned}
a(x+b)^2 - ab^2 &= a(x^2 + 2bx + b^2) - ab^2\\
&= ax^2 + 2abx + ab^2 - ab^2\\
&= ax^2 + 2abx
\end{aligned}
\]
The following calculation is a trivial example
\begin{align*}
a(x+b)^2 - ab^2 &= a(x^2 + 2bx + b^2) - ab^2\\
&= ax^2 + 2abx + ab^2 - ab^2\\
&= ax^2 + 2abx
\end{align*}
\end{document}
``` | 2013/01/26 | [
"https://tex.stackexchange.com/questions/95402",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/19356/"
] | As you've noticed, the `aligned` environment is meant to be part of a larger displayed math environment (which is why you put it in between `\[` and `\]`), while the `align*` environment is a freestanding displayed math environment. For the use you made of them in your example, they're essentially equivalent. The `aligned` environment can be used in many other situations, though, in which `align*` wouldn't work at all.
For example:
```
\begin{displaymath}
\text{A simple example:}
\qquad
\begin{aligned}
q &=CV \\
&=\num{3e-20x1000} \\
&=\num{3e-17}
\end{aligned}
\end{displaymath}
```
or
```
\begin{displaymath}
\begin{aligned}
q &=CV \\
&=\num{3e-20x1000} \\
&=\num{3e-17}
\end{aligned}
\qquad\text{and}\qquad
\begin{gathered}
a = b + c\\
\sin^{2}x + \cos^{2}x = 1
\end{gathered}
\end{displaymath}
``` | it makes no sense to compare `aligned` and `align*`. The first one is used if you want *one* equation number for several lines. This is the reason why `aligned` is used as part of `align` or a similar environment. |
56,245,169 | I was asked to separate access to a particular Jira project by component. e.g. user "a" can see issues created for component "a", but not component "b". conversely, user "b" can see issues created for component "b", but not component "a".
I know that I can limit access to a particular project to one or more users, but I was unaware of a way to filter access to one or more users by component within a Jira project.
Is there any way to limit access to one or more people to a subset (less than all components) of a project?
I did a search for a Jira plugin that might offer this functionality, but did not find what I was looking for.
N/A
N/A | 2019/05/21 | [
"https://Stackoverflow.com/questions/56245169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760868/"
] | ```
DateTime? dateTimeFromTimeStamp(dynamic data) {
Timestamp? timestamp;
if (data is Timestamp) {
timestamp = data;
} else if (data is Map) {
timestamp = Timestamp(data['_seconds'], data['_nanoseconds']);
}
return timestamp?.toDate();
}
Map<String, dynamic>? dateTimeToTimeStamp(DateTime? dateTime) {
final timestamp = Timestamp.fromDate(dateTime ?? DateTime.now());
return {
'_seconds': timestamp.seconds,
'_nanoseconds': timestamp.nanoseconds,
};
}
```
Then use it like this:
```
@JsonKey(
name: "creation_date",
fromJson: dateTimeFromTimeStamp,
toJson: dateTimeToTimeStamp)
DateTime? creationDate;
``` | I have solved my problem by sending my timestamp as a String.
```dart
"timestamp": DateTime.now().toString()
```
Since now my timestamp is in string now so I get the exact timestamp from JSON as a String.
Now what I did was used a flutter plugin called `timeago` to convert it to time ago format for example: "10 mins ago"
```dart
Text(timeago.format(DateTime.parse(timestamp)).toString);
``` |
44,033,111 | So I have an timer and multiple fragments. If the timer is running, there is no problem when switching between fragments. But when the timer finishes `onFinish()` and If the user is in another fragment at that time, the app crashes.
Here are some of the log:
1) `E/RingtoneManager: Failed to open ringtone content://settings/system/notification_sound: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference`
2) `java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.Ringtone.setStreamType(int)' on a null object reference`
And here is my `onFinish()` :
```
@Override
public void onFinish() {
timerTextView.setText("00:00");
timerSeekBar.setEnabled(true);
Log.i("Timer", "Finished!");
// Alarm sound for ending
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone timerEnded = RingtoneManager.getRingtone(getContext(), notification);
timerEnded.setStreamType(AudioManager.STREAM_ALARM);
timerEnded.play();
}
```
As far as I understand, the crash is cause when trying to sound the alarm. How can this be fixed?
Edit: Should have clarified that I want the timer to continue running and finish, even when the user in in another fragment. | 2017/05/17 | [
"https://Stackoverflow.com/questions/44033111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6073708/"
] | I got the same error because I had misspelled 'firebase' as 'firebas'
*firebas: {
apiKey: "...",
authDomain: "project.firebaseapp.com",
databaseURL: "<https://project.firebaseio.com>",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "..."
}* | Make sure there is no gap between `firebase` and `:`.
That is, it should be `firebase:`, not `firebase :`. |
52,182,533 | I am using the built in complex number class `std::complex` from the Standard C++ Library header. I applied a code in a HLS tools. The tool can not access a private member variable of that complex class. Is it possible to make it public or what can i do?
```
Error: /usrf01/prog/mentor/2015-16/RHELx86/QUESTA-SV-AFV_10.4c-5/questasim/gcc-4.7.4-linux_x86_64/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.7.4/../../../../include/c++/4.7.4/complex(222):
error: 'fpml::fixed_point<int, 16u, 15u> std::complex<fpml::fixed_point<int, 16u, 15u> >::_M_real' is private
``` | 2018/09/05 | [
"https://Stackoverflow.com/questions/52182533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9475755/"
] | You have to mock `matchRepositoryImpl.getFootballMatch("4328")` method like this:
```
Mockito.`when`(matchRepositoryImpl.getFootballMatch("4328"))
.thenReturn(Observable.just(OBJECT_YOU_WANT_TO_BE_RETURNED))
```
You can put this mock in `@Before` block, or in particular test. | I don't know if this can help you.
But i let you some of my code when i have a Presenter and PresenterTest.
**Presenter:**
```
...
private void loadRepos() {
disposableManager.add(repoRepository.getTrendingRepos()
.doOnSubscribe(__ -> viewModel.loadingUpdated().accept(true))
.doOnEvent((d, t) -> viewModel.loadingUpdated().accept(false))
.doOnSuccess(__ -> viewModel.reposUpdated().run())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(dataSource::setData, viewModel.onError()));
}
...
```
I observe the changes in the mainThread but in my test i change the scheduler to run it.
And in the PresenterTest i add this to run the tests.
**PresenterTest:**
```
public class TrendingReposPresenterTest {
static {
RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());
}
...
private void initializePresenter() {
presenter = new TrendingReposPresenter(viewModel, repoRepository,
screenNavigator,Mockito.mock(DisposableManager.class),dataSource);
}
```
Here is my disposable manager class to handle the observables.
**DisposableManager**
```
public class DisposableManager {
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
public void add(Disposable... disposables) {
compositeDisposable.addAll(disposables);
}
public void dispose() {
compositeDisposable.clear();
}
}
```
I hope this helps you. But i am not sure if this is your problem |
22,095,667 | Can I use LineID attribute for this?
I hope I could use sink::set\_formatter to do this instead of using
```
__LINE__
```
and
```
__FILE__
```
in each log statement. | 2014/02/28 | [
"https://Stackoverflow.com/questions/22095667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531116/"
] | The solution shown by [Chris](https://stackoverflow.com/a/22770455/1224177) works, but if you want to customize the format or choose which information appears in each sink, you need to use mutable constant attributes:
```cpp
logging::core::get()->add_global_attribute("File", attrs::mutable_constant<std::string>(""));
logging::core::get()->add_global_attribute("Line", attrs::mutable_constant<int>(0));
```
Then, you make a custom macro that includes these new attributes:
```cpp
// New macro that includes severity, filename and line number
#define CUSTOM_LOG(logger, sev) \
BOOST_LOG_STREAM_WITH_PARAMS( \
(logger), \
(set_get_attrib("File", path_to_filename(__FILE__))) \
(set_get_attrib("Line", __LINE__)) \
(::boost::log::keywords::severity = (boost::log::trivial::sev)) \
)
// Set attribute and return the new value
template<typename ValueType>
ValueType set_get_attrib(const char* name, ValueType value) {
auto attr = logging::attribute_cast<attrs::mutable_constant<ValueType>>(logging::core::get()->get_global_attributes()[name]);
attr.set(value);
return attr.get();
}
// Convert file path to only the filename
std::string path_to_filename(std::string path) {
return path.substr(path.find_last_of("/\\")+1);
}
```
The next complete source code create two sinks. The first uses File and Line attributes, the second not.
```cpp
#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/attributes/mutable_constant.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/attributes/mutable_constant.hpp>
namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace expr = boost::log::expressions;
namespace src = boost::log::sources;
namespace keywords = boost::log::keywords;
// New macro that includes severity, filename and line number
#define CUSTOM_LOG(logger, sev) \
BOOST_LOG_STREAM_WITH_PARAMS( \
(logger), \
(set_get_attrib("File", path_to_filename(__FILE__))) \
(set_get_attrib("Line", __LINE__)) \
(::boost::log::keywords::severity = (boost::log::trivial::sev)) \
)
// Set attribute and return the new value
template<typename ValueType>
ValueType set_get_attrib(const char* name, ValueType value) {
auto attr = logging::attribute_cast<attrs::mutable_constant<ValueType>>(logging::core::get()->get_global_attributes()[name]);
attr.set(value);
return attr.get();
}
// Convert file path to only the filename
std::string path_to_filename(std::string path) {
return path.substr(path.find_last_of("/\\")+1);
}
void init() {
// New attributes that hold filename and line number
logging::core::get()->add_global_attribute("File", attrs::mutable_constant<std::string>(""));
logging::core::get()->add_global_attribute("Line", attrs::mutable_constant<int>(0));
// A file log with time, severity, filename, line and message
logging::add_file_log (
keywords::file_name = "sample.log",
keywords::format = (
expr::stream
<< expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d_%H:%M:%S.%f")
<< ": <" << boost::log::trivial::severity << "> "
<< '[' << expr::attr<std::string>("File")
<< ':' << expr::attr<int>("Line") << "] "
<< expr::smessage
)
);
// A console log with only time and message
logging::add_console_log (
std::clog,
keywords::format = (
expr::stream
<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " | " << expr::smessage
)
);
logging::add_common_attributes();
}
int main(int argc, char* argv[]) {
init();
src::severity_logger<logging::trivial::severity_level> lg;
CUSTOM_LOG(lg, debug) << "A regular message";
return 0;
}
```
The statement `CUSTOM_LOG(lg, debug) << "A regular message";` generates two outputs, writing a log file with this format...
```
2015-10-15_15:25:12.743153: <debug> [main.cpp:61] A regular message
```
...and outputs to the console this:
```
2015-10-15 16:58:35 | A regular message
``` | Another possibility is to add line and file attributes to each log record after they are created. This is possible since in newer releases. Attributes added later do not participate in filtering.
Assuming severity\_logger identified with variable logger:
```
boost::log::record rec = logger.open_record(boost::log::keywords::severity = <some severity value>);
if (rec)
{
rec.attribute_values().insert(boost::log::attribute_name("Line"),
boost::log::attributes::constant<unsigned int>(__LINE__).get_value());
... other stuff appended to record ...
}
```
The above would, of course, get wrapped into convenient macro.
Later you can show this attribute using custom formatter for the sink:
```
sink->set_formatter( ...other stuff... << expr::attr<unsigned int>("Line") << ...other stuff... );
```
Unlike previous answer, this approach requires more custom code and can't use off-the-shelf boost logging macros. |
277,202 | Someone told me that he was using `componentDidMount` and `componentDidUpdate` in his `BaseWebPart` class, but looking at the documentation below I realized it shouldn't be possible since it's not a React Component.
[BaseWebPart class](https://docs.microsoft.com/en-us/javascript/api/sp-webpart-base/basewebpart?view=sp-typescript-latest)
Is there something I am missing, what do you need to do in order to be able to use `componentDidMount` and `componentDidUpdate`? Or is it possible that there was some kind of misunderstanding and he did not use `componentDidMount` and `componentDidUpdate` in his `BaseWebPart` class. Is it also best practice to use `componentDidMount` and `componentDidUpdate` instead of the `onInit` provided by the `BaseWebPart` class. | 2020/03/04 | [
"https://sharepoint.stackexchange.com/questions/277202",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/89079/"
] | Below function can be used to get the query string parameters from URL:
```
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
```
You can use it like:
```
var mytext = getUrlVars()["siteUrl"];
```
Okay but when the parameter is missing from the URL the value will be undefined. Here’s how to set a default value to the variable:
```
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
```
Use it like this:
```
var mytext = getUrlParam('siteUrl', _spPageContextInfo.webAbsoluteUrl);
```
**Note**: Here I am passing current site URL as default. But, you can pass any other site URL you want by default if the query string parameter is missing from URL
**Solution for you**:
1. Add `getUrlVars()` and `getUrlParam()` functions in your code.
2. Construct a URL to your form page with `siteUrl` as query string parameter like:
`https://tenant.sharepoint.com/sites/siteName/SitePages/PageName.aspx?siteUrl=<enter the site URL here>`
3. On form page Use your code like below:
```
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
function addEntry() {
var siteUrlFromURLParameter = getUrlParam('siteUrl', _spPageContextInfo.webAbsoluteUrl);
var item = {
"__metadata": { "type": "SP.Data.EntryListItem" },
"SiteURL": siteUrlFromURLParameter,
"Title": $('#inputTitle').val(),
"Entry": $('#inputEntry').val()
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
});
return false;
}
```
**Reference**: [Get URL Parameters With JavaScript](https://html-online.com/articles/get-url-parameters-javascript/). | Per [this community post](https://stackoverflow.com/posts/901144), you can use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility) which is simple and has [decent (but not complete) browser support](https://caniuse.com/#feat=urlsearchparams).
Assuming the value was passed to this page like `https://fullpageurl.aspx?SiteUrl`, then the following should get you what you need:
```
function addEntry() {
const urlParams = new URLSearchParams(window.location.search);
var item = {
"__metadata": { "type": "SP.Data.EntryListItem" },
"SiteURL": urlParams.get('SiteUrl'),
"Title": $('#inputTitle').val(),
"Entry": $('#inputEntry').val()
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getbytitle('" + listName + "')/Items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
});
return false;
}
``` |
54,826,925 | I have 3 layer callbacks like this :
```js
app.post('/', (req, res) => {
var filename = `outputs/${Date.now()}_output.json`;
let trainInput = req.files.trainInput;
let trainOutput = req.files.trainInput;
let testInput = req.files.trainInput;
//first
trainInput.mv(`inputs/${req.body.caseName}/train_input.csv`, function (err) {
if (err) return res.status(500).send(err);
//second
trainOutput.mv(`inputs/${req.body.caseName}/train_output.csv`, function (err) {
if (err) return res.status(500).send(err);
//third
testInput.mv(`inputs/${req.body.caseName}/test_input.csv`, function (err) {
if (err) return res.status(500).send(err);
res.send('success');
});
});
});
});
```
In this case, there are only 3 file uploads. In another case, I have more than 10 file uploads, and it makes 10 layer callbacks. I know it because of JavaScript asynchronous.
Is there any way, with this case, to make a beautiful code? This is because when it 10 layer callbacks, the code looks horizontally weird.
Thanks | 2019/02/22 | [
"https://Stackoverflow.com/questions/54826925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553779/"
] | You can use the following code to make you code look better and avoid callback hell
```
app.post('/', async (req, res) => {
var filename = `outputs/${Date.now()}_output.json`;
let trainInput = req.files.trainInput;
let trainOutput = req.files.trainInput;
let testInput = req.files.trainInput;
try {
var result1 = await trainInput.mv(`inputs/${req.body.caseName}/train_input.csv`);
var result2 = await trainInput.mv(`inputs/${req.body.caseName}/train_output.csv`);
var result2 = await testInput.mv(`inputs/${req.body.caseName}/test_input.csv`);
res.send('success');
}
catch (error) {
res.status(500).send(error);
}
});
``` | You can make the functions return a Promise
I advice to make one function because you do the same thing 3 times. In this case I called the function 'save' but you can call it what ever you want. The first parameter is the file end the second the output filename.
```js
function save(file, output) = return new Promise((resolve, reject) => {
file.mv(`inputs/${req.body.caseName}/${output}`, err =>
if (err) return reject(err)
resolve()
})
Promise.all([
save(req.files.trainInput, 'train_input.csv'),
save(req.files.trainInput, 'train_output.csv'),
save(req.files.trainInput, 'test_input.csv')
])
.then(_ => res.send(200))
.catch(err => res.send(400);
``` |
73,976,821 | I'm a beginner programmer in python and my lecturer wants us to make a program from scratch specifically w hard code.
It was running well previously, but when I tried testing the program earlier, this part of the program started to run an error. It said it cannot run code on a closed file. Can anyone help point out where the problem is?
Thank you so much
```
def temporder():
allmenu = open("allmenu.txt","r")
temporder = open("neworder.txt","a")
entry = str.upper(input("Please enter a valid product code: "))
for lines in allmenu:
code,price = lines.split(",")
if (entry in code):
temporder.write("\n" + code + "," + price)
temporder.close()
allmenu.close()
``` | 2022/10/06 | [
"https://Stackoverflow.com/questions/73976821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20068676/"
] | So it seems like it is a problem with the newest `firebase-tools` version. After downgrading from `11.14.0` to `11.13.0` locally, it worked again (which I recognized thanks to [this comment](https://stackoverflow.com/a/73968883/9150652)).
So to make it run in CI, I just installed `firebase-tools@11.13.0` as a dev-dependency directly into the project and CI ran through fine again. | Per the error, your script is calling two GitHub Actions and one of these is calling `GET https://cloudfunctions.googleapis.com/v1/projects/{project}/locations/-/functions` to list the Functions in the Project. This method requires the (`cloudfunctions`) service to be enabled.
* Either enable the service in the project so that the call succeeds
* Or remove the step in the script that makes the call. |
268,657 | I've been searching around the internet to find out how to derive the reactance formula for capacitors and inductors. But I couldn't really find anything, so I thought why not make a post about it.
I gave it a try myself though, but I could not get rid of the \$sin(\omega t)\$ in the numerator and the \$cos(\omega t)\$ in the denominator. This is what I was left with:
\$X\_c = sin(\omega t)/(C\cdot\omega\cdot cos(\omega t))\$
I tried to convert the \$v(t) = V\_{peak} \* sin(\omega t)\$ to \$V\_{RMS}\$, and the \$i(t)\$ by doing the same procedure, and it sure worked. But I feel like this isn't the right way of doing it. Wikipedia mentioned the use of phasors, but I couldn't really figure out a way to do it.
Thank you in advance,
Mr.Mongoloid | 2016/11/10 | [
"https://electronics.stackexchange.com/questions/268657",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/118358/"
] | The phasor approach is the easiest imo. You simply let V and I become a phasor. Then you replace all of the differential operators by algebraic expressions.
Ive done the capacitor for you
.
Note: in this form do not forget that both I and V are now phasors and V/I is a complex number ofcourse.
Edit: you can notice i made the phase phi = 0. I did this to make things clear, but its value makes no difference. When you take dV/dt the phase phi is never part of that expression anyways... | Capacitor:
I=C \* dv/dt
d/dt=jw=s (shortcut Laplace transform)
I=C \* sV
C=I/sV
1/sC=V/I=Xc
Inductor:
V=L \* di/dt
V=L \* sI
L=V/sI
sL=V/I=Xl |
26,443,394 | Good afternoon. Please tell me this question:
What is the difference of different levels Drill Map in Microstrategy? (UP, DOWN, ACROSS)
Particularly interested in ACROSS. What is it used? The manual says that this is the same as UP ... But then I do not believe it.
Thanks in advance for an explanation. | 2014/10/18 | [
"https://Stackoverflow.com/questions/26443394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3932441/"
] | Optimistic locking means you want multiple threads to be able to edit the same user record.
What's happening in your app is that two (or more) edits are happening to the same user record, and your app is correctly detecting that, and raising the suitable error.
What you would typically do is handle the error:
* For example, you could print a message such as "Sorry, someone else edited this, so your changes were not saved".
* For example, you could code any way to reconcile the edits, such as detecting that one edit changed the person's name, wherease the other edit changed the person's phone number, and then you could code a way to merge these two into one save.
In general, you can also use `user.reload` to fetch a fresh version of the user.
I suggest you first try turning off optimistic locking, while you're learning Rails. Optimistic locking is a great optimization for speed, yet it shouldn't be needed to get a typical Rails & Devise app running successfully.
You asked about what specifically Devise may be doing:
* When a user record is updated, the typical Rails ActiveRecord setup updates a table field `updated_at` with the current timestamp.
* A typical Devise setup of modules such as `trackable` updates the user record with the most recent sign-in and/or sign-out timestamps.
An easy way to watch what's happening is to look at the `lock_version` field:
* When Rails loads a record (e.g. a user) then Rails increments the lock version number.
* When your app saves the user, Rails ActiveRecord compares the user object lock\_version number with the database lock\_version number.
* If the numbers match, then the save succeeds; if the number mismatch, then Rails raises the stale object exception.
Example code:
```
def before_logout
logger.debug current_user.lock_version
current_user.reload
logger.debug current_user.lock_version
current_user.update(security_token: nil)
end
```
Devise and some of its various modules add fields to the `user` table. This is quick and convenient for typical web apps, yet these added fields tend to disrupt caching, locking, persistence, serializing, and the like.
(As an aside, you may want to consider evaluating Devise vs. other security solutions. One in particular that I like is called Sorcery; it provides a toolkit of a handful of methods that you can assemble the way you want. In my personal experience, Sorcery is a great way to learn exactly what each step is doing in your own code, and you can control the caching and locking in the ways that you want.) | I created a very simple module to handle this when is possible to reload to fix the problem. Please note that this is a race condition and you are responsible of what you are saving to the db.
```
module StaleObjHandler
def retry
@staled_retries ||= 5
yield
rescue ActiveRecord::StaleObjectError => e
if @staled_retries.zero?
Rails.logger.error ' Staled object retried 5 times, raising error.'
raise e
end
Rails.logger.error " Staled Object Error for #{e.record} retrying..."
e.record.reload
@staled_retries -= 1
retry
end
module_function :retry
end
```
Then you can just use it like
```
StaleObjHandler.retry { account.update_attribute :balance, account.balance - total }
```
It will try to do it 5 times by default, doing a reload if it fails. |
212,695 | The armoured trains need to be made viable without just removing other aspects of warfare. Tactical pure fusion nukes with a yield of under 75kt are common. The environment of the planet is earth like. There are a few areas that are just barren flat rock & a few very dense megalopolises. Rail infrastructure is plentiful. The primary opponents are varied but the main situation for use is between developed industrial powers. The armoured trains have to be used in direct combat & be heavily armoured. They can carry other vehicles & infantry. The standard rail gauge is 1,600mm. The technology level is near future. What could allow armoured trains to work in this setting? | 2021/09/05 | [
"https://worldbuilding.stackexchange.com/questions/212695",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/73451/"
] | Make the war over what's on the trains
======================================
They're fighting not for land or ideologies, but for things they can only easily move by rail.
Perhaps they're carrying stocks of nuclear fuel or portable reactors, with all the heavy shielding that entails. Perhaps they're moving the nukes themselves, or some other kind of advanced weapon or technology. Things that weigh several tens of tons and would be better captured than destroyed. In addition, they're moving through a neutral country or they're operating under a cold-war style situation where a large scale deployment of forces may be undesirable.
They can't destroy the track or derail the train, as it's the only way to move the thing around and it would cripple their own ability to shift it. Much better to roll up next to it in their own train and hijack the engine. Cue heavily armored attack and defence wagons to assist in and defend against these hijacks. | Justifying Warfare on the Ground
================================
It seems your setting is capable of fusion power, judging by your statement of:
>
> Tactical pure fusion nukes with a yield of under 75kt are common
>
>
>
So the first problem you need to solve is why is warfare being conducted on the ground and not in the air. Fusion power would provide the power necessary for flying battle platforms akin to the helicarriers seen in the Marvel movies. Satelites with high powered lasers would also be entirely feasible with fusion power.
Flight and orbital platforms would give any side a considerable advantage over ground based forces, so why would everyone be using trains or any other ground based force?
A few suggestions to explain this:
* The atmoshpere is covered with high altitude magnetic storms, making flight difficult and target acquisition almost impossible.
* Ground-to-air attacks are significantly more effective than air-to-ground attacks, either through the weaponry used (which would be difficult to justify, as [kinetic bombardment](https://en.wikipedia.org/wiki/Kinetic_bombardment) is extremely potent) or through defensive systems used (eg orbital bombardment shields that are effective against overhead attacks but not so effective against lateral attacks).
* The planet is covered in a shield of somekind, protecting the surface from orbital attacks (which would solve orbital platforms but not flying attack platforms or fighter jets).
* Thin atmosphere, which results in a poor ability to fly conventionally.
Any combination of these factors could give you a situation where ground based combat would be preferable to air based combat. There could be other elements that make air combat unfeasible, but that is almost worth an entire question in itself.
---
Solving the Track Problem
=========================
Next problem you have is the tracks.
Trains require tracks to travel, and the tracks are stationary targets that would require a huge investment to protect. Even if the entire surface of the planet is covered in train tracks, enough bombing would eventually render trains useless.
So I am proposing a train that lays its own tracks as it goes along.
Something like this: <https://www.youtube.com/watch?v=tMXfU8blPMM>
---
Why two rails when one will do?
===============================
Finally, I would recommend moving over to a monorail system, as this would be easier, faster and cheaper to build and maintain than a two rail system.
With the potential for blowing up tracks and disabling your opponents that way, repairing and rebuilding tracks would be critical. If you can repair and rebuild faster than your opponents then you have a significant advantage. Placing a single rail down is easier than placing down two rails an exact distance from each other.
Plus with monorails you have the option of making them maglev compatible, allowing you to send trains down your tracks at speeds far exceeding those of trains that make physical contact with the track. |
1,057 | Should you defend your blinds differently at different stages of a tournament?
Meaning in the early stages should you defend a lot tighter and then get a bit looser as the tournament goes on. The further you go in a tournament the more important it becomes to steal blinds so people will raise/shove a lot lighter. Should you tighten up against this or should you call light as well?
For example early in a 6 seater sit and go blinds are 100/200 and stack sizes are 10000 each. You are in the BB with A10 and the button raises to 600. Should you flat call and see a flop or should you 3-bet knowing that they are probably trying to steal? Or is this a hand you can safely lay down at this stage?
The same situation late on in a tournament the button shoves and you just have him covered are you calling or folding? At this stage they could quite possibly be playing any two cards and just attempting to steal. | 2013/01/23 | [
"https://poker.stackexchange.com/questions/1057",
"https://poker.stackexchange.com",
"https://poker.stackexchange.com/users/745/"
] | **Basically it depends on some factors:**
* the available statistics and notes to the opponents.
* tournament stage
* your stack
* opponent's stack
**General Big Blind behaviour:**
* we tend to defend blinds against the "stealer", who is more loose/agressive than average
* we tend to defend blinds in the late tournament stage
* we tend to defend the blind against the big stack (probably table chipleader) with **premium** hands to make sure that we are ahead of his range. Most likely he will call our raise and try to win on flop/post flop.
* while defending the blind we reraise more to have high fold equity, and raise less if we expect to be payed more on flop
* defend the blind against short stack stealer (M3-M5) at "almost any two". His push range is extremely wide. | In the early stages of a tournament, you want to survive the weeding out of the unfit. Hence, you tend not to defend, unless your hand is reasonably good.
In the later stages of a tournament, you are playing against survivors. Hence you need to play "reasonable" blind hands that offer any hope, and fold only your worst ones.
That said, you defend more against loose raisers than tight ones. |
17,888,758 | I have a different scale ImageView on my real device (phone) and emulator. The emulator displays the image correctly but the real device(phone) doesn't. The image becomes smaller on the device (phone) screen.
this is my java code :
```
...
rootView = (ViewGroup) inflater.inflate(R.layout.arabic_page, container, false);
waraka = (ImageView) rootView.findViewById(R.id.waraka);
...
InputStream istr;
try {
//Search in OBB
istr = getExpansionFile().getInputStream(num_image+".png");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
Drawable draw =new BitmapDrawable(getResources(),bitmap);
waraka.setImageDrawable(draw);
```
and this is my layout code :
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".MainActivity">
<ImageView
android:id="@+id/waraka"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:scaleType="fitCenter"/></RelativeLayout>
``` | 2013/07/26 | [
"https://Stackoverflow.com/questions/17888758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2623854/"
] | JAX-RS is an specification (just a definition) and Jersey is a JAX-RS implementation. | JAX-RS is an specification (just a definition) and Jersey is a JAX-RS implementation. Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. |
6,264,084 | I've got this HTML that I'm trying to style:
```
<div id="menubar">
<menu id="menubarTransportControls">Foobar</menu>
</div>
```
Can anyone explain why this CSS...
```
#menubar menu {
width: auto;
}
```
...takes priority over...
```
#menubarTransportControls {
width: 100%;
}
```
I'm using IE7 with the HTML5 shiv javascript. Thanks | 2011/06/07 | [
"https://Stackoverflow.com/questions/6264084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473141/"
] | `#menubar menu` has higher specificity than `#menubarTransportControls`.
To understand specificity:
* The specs: <http://www.w3.org/TR/CSS21/cascade.html#specificity>
* If you like Star Wars: <http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html>
* Otherwise: <http://css-tricks.com/specifics-on-css-specificity/>
You can use this calculator if you like:
<http://www.suzyit.com/tools/specificity.php>
```
Selector Score (a,b,c,d)
#menubar menu 0,1,0,1
#menubarTransportControls 0,1,0,0
```
Be sure to read some of the above resources to understand what the "Score" means. | it's all about the priory. In css `id` is more powerful then `class & element` for example
`id=100`
```
class=10
element=1
```
so in your example :
```
#menubar menu = 100 + 1 = 101
```
&
```
#menubarTransportControls = 100 = 100
```
so which one is more powreful. for more check this <http://code.google.com/edu/submissions/html-css-javascript/> (CSS Presentation) |
26,782,499 | I am using `<? foreach $posts as $post) ?>` to call out all my posts that are added to database. I actually want to call out 3 of the new added posts to database, not all 20.
How can I do that?
I have read most of the topics, but they didn't work as I tought.
Thank you! | 2014/11/06 | [
"https://Stackoverflow.com/questions/26782499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851363/"
] | This query will do...
```
select * from posts order by id desc limit 3 //hoping posts is your table name
```
`order by id desc` will orde your posts in descending order
`limit 3` will fetch the first 3 data
after getting the data you can use `foreach` to display them
hope this helps... | There's a few methods to limit `$posts`, but if you can't modify that for some crazy reason, you can use:
```
for ($i = 0; $i < 3; $i++) {
if ($i == 0) $post = current($posts);
else $post = next($posts);
// Do stuff with $post
}
``` |
43,013,269 | So basically my program is supposed to create a button in a separate activity each time another button is clicked. However every time I add a button the previous button I added disappears (the buttons move across horizontally).
```
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.LinearLayout;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RelativeLayout;
import java.util.LinkedList;
import android.widget.GridLayout.LayoutParams;
import java.util.Arrays;
public class TestActivity extends AppCompatActivity {
public static int count = 0;
public static int x = 100;
//public static int[] xPos = new int[5];
public static int y = 100;
private boolean stopper = true;
public static int spot = 0;
//public static Button[] buttonArr = new Button[5];
public static LinkedList<Button> buttonList = new LinkedList<Button>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
int b = getIntent().getIntExtra("bob", 0);
//System.out.println(b);
if(b==-11978182){
//System.out.println(buttonList.size());
//for(int i = 0; i<buttonList.size(); i++) {
//RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main);
//Button addButton = new Button(this);
//if(stopper) {
//buttonList.add(addButton);
//stopper = false;
//}
//System.out.println(buttonList.size());
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main);
Button addButton = new Button(this);
addButton.setId(spot);
buttonList.add(addButton);
System.out.println(buttonList.size());
buttonList.get(spot).setText("add");
RelativeLayout layout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(200, 200);
layoutParams.setMargins(100*(spot+1), 100, 100, 100); // left, top, right, bottom
buttonList.get(spot).setLayoutParams(layoutParams);
//RelativeLayout layout = (RelativeLayout) findViewById(R.id.main);
//for(int i = 0; i<buttonList.size(); i++) {
mainLayout.addView(buttonList.get(spot));
mainLayout.addView(layout);
//}
spot = spot + 1;
//}
}
Button galleryButton = (Button) findViewById(R.id.gallery);
galleryButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TestActivity.this,Test2.class);
startActivity(intent);
}
});
}
}
``` | 2017/03/25 | [
"https://Stackoverflow.com/questions/43013269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7765391/"
] | Found the reason causing that. Just like to post a possible solution if anyone else is facing similar problems. It appears that my 'use block caret' box was checked.
Go to file -> Editor -> General -> Appearance -> 'Use block caret' and uncheck it if it's checked.
Otherwise, it might be the issue with the keymapping. Go to File -> Settings -> Keymap, search for enter and make sure that it is mapped to enter. OR, just reset the keymap by clicking the reset button on the same page. | Check if Ideavim OR Vimware is running on the bottom right corner of your Pycharm window. Disable it you will be able to add a new line |
34,504 | Kind of a hard topic to search for, as architect turns up a lot about software architects instead.
After 8 months of PHP self-study, I finally stumbled across the php|architect site. The length of time it took me to find it makes me suspicious of its quality.
3 related questions:
* do professional PHP coders read/care about php|architect?
* is it a good source for PHP beginners?
* assuming yes to either of the above, how far back in the archives to articles remain relevant? (ex: does stuff written about PHP4 still matter?) | 2011/01/07 | [
"https://softwareengineering.stackexchange.com/questions/34504",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/9260/"
] | I have been into PHP development for over 5 years now & I really find the articles very relevant & helpful. It's clearly not aimed at PHP beginners but at the intermediate/expert programmer. | In the past I bought and read PHP Architect magazine thoroughly, then it become increasingly hard to physically find at bookstores and newsstand plus I moved away from core PHP development. Having said that I always found the articles useful and relevant at the time and would occasionally go back a few months to re-read articles.
Haven't looked at a copy in years so I cannot attest to the value of the articles anymore plus I don't think it's available in print format so if your looking to physically have something in your hands your out of luck.
CB |
24,319,558 | On upgrading to Django 1.7 I'm getting the following error message from `./manage.py`
```
$ ./manage.py
Traceback (most recent call last):
File "./manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "/home/johnc/.virtualenvs/myproj-django1.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 427, in execute_from_command_line
utility.execute()
File "/home/johnc/.virtualenvs/myproj-django1.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 391, in execute
django.setup()
File "/home/johnc/.virtualenvs/myproj-django1.7/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/johnc/.virtualenvs/myproj-django1.7/local/lib/python2.7/site-packages/django/apps/registry.py", line 89, in populate
"duplicates: %s" % app_config.label)
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: foo
```
What's the problem and how do I resolve it? | 2014/06/20 | [
"https://Stackoverflow.com/questions/24319558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331/"
] | Well, I created a `auth` app, and included it in `INSTALLED_APP` like `src.auth` (because it's in `src` folder) and got this error, because there is `django.contrib.auth` app also. So I renamed it like `authentication` and problem solved! | In case if you have added your app name in settings.py
example as shown in figure than [IN settings.py](https://i.stack.imgur.com/YEGyV.png) Remove it and Try this worked for me.
give it a try .
This Worked Because settings.py assumes installing it twice and does not allow for migration |
5,540 | We're about to embark on a small Casino-type Flash game and I've been assigned the task of "UX Lead"... Our company is just beginning to integrate and define the concept of UX. Our projects are now starting with a "UX lead" to be the 'user advocate' at project meetings.
I've read *A Project Guide to UX* and read an abundance of UX articles online, but they are all targeted toward websites and desktop software.
Are there any good resources, or does any just have any quick **advice** on how to approach UX for a game? | 2010/08/03 | [
"https://ux.stackexchange.com/questions/5540",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/-1/"
] | **Casino Interfaces**
I'm not in the casino industry anymore, so I'd like to share a few tips. Enjoy.
Casino games are a unique subset of the game industry. The audience for these games may be older. They want graphics that look and behave like classic games.
**The interface must easily allow for purchasing credits**
Since casino gaming are constantly monetized, you may want to have a pop-up that encourages you to choose between ($1, $5, $10, $20, $50, $100, or other).
**Stick with 2D**
The interface should have dimension and depth, but nothing beyond 2D has proven successful. If we're talking class II gaming, 3D has yet to prove it's self. My company had 2 years of waisted development on 3D, and realistic graphics (with nothing to show for it). It confuses the game play and the development expenses skyrocket.
**Old School Nostalgia**
In updating older games, my company had to be careful not to lose the old-school look of the games (which looked like crap), but the gambling audience is nostalgic about it. *I looked to iPhone, Nintendo wii, and Lucky Charms cereal for inspiration.*
**Things that worked**
• 2D Graphics '2D styles prove to work well with extended game play'
• Lower Thirds 'place the GUI along the bottom of screen for easy flow'
• Invest design time in the Progressives 'Numbers turning over sustains excitement'
**Things that didn't work**
• 3D and realistic graphics 'It takes them out of the zone...it's hard to explain'
• HUD style display 'have to have all controls accessible, lower thirds or side'
• Web Style Layouts 'don't even go there'
**Consider**
Usability sketches would save time. Show the game (slots, win line, poker, blackjack, 21, keno etc) and how it fits with the interface. You'll probably need to plan a login, game selection menu, and pop-up for credits.
There's usually not a budget for a UX designer, Commercial Artist, and Sound Engineer, but that's the talent you'll need *just for the design*. The coding, that's a nightmare if you're working with poor architecture. Get the features and requirements upfront and try not to reinvent the wheel in this industry.
Good luck. | Use game mechanics and behavioral effects to motivate your users. [Mental Notes](http://getmentalnotes.com) and Art of Game Design mentioned above are a good starting point. |
16,681 | I'm lucky enough to have been gifted two Trout by a neighbour... and have not had the pleasure of preparing fresh fish before (or at least not unprepared fish).
I've attempted an internet search but haven't found a source that looks reliable to me. | 2011/08/06 | [
"https://cooking.stackexchange.com/questions/16681",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/1159/"
] | Here is a a basic video [tutorial](http://www.youtube.com/watch?v=XKKh6cnhzAY) so you can see the basic steps.
The biggest traps when cleaning fish is failing to remove all the guts, leaving bones in the filet, and not removing all the scales from the fish. You can, if you choose, just gut the fish and cook whole stuffed with some aromatics, which can be really good. This guy will show you [how](http://www.youtube.com/watch?v=cr0xIoM85E0). This works very well with smaller fish like trout assuming your guests are used to it.
So to avoid the pitfalls mentioned above, you need to make sure that the cavity of the fish is
fully empty before you start the filet. You also want to run your hand over the outside of the fish after your rinse of the cavity to make sure that all scales are gone. The best way to keep bones out is start at the spine and let the fishes rib cage guide your knife down and out. If you want to remove the skin (not recommended for trout but other fish have much tougher skins), just put the filet skin-side down and slide your knife along at a ten degree angle.
Oh, and the most important thing? Use a filet knife that is super sharp, you definately don't want to tackle cleaning with out a sharp knife. | Rinse the outside of the fish.
While the fish is uncut, remove the scales. If you have a scaler you can use that, or you can go lightly with a grater or knife against the scales; or your fingernails in the direction of the scales (so you don't hurt yourself, but it'll take a while). Don't forget to scale the top and bottom ***(especially the stomach area- because that is the beginning point of the fillet)*** edges of the fish.
Then, slice from the fish's anus ***(a small hole right below the bottom fin)*** to the chin (up to the gills, bellyside of the fish) to create a fish pocket. Pull out ALL of the guts with your hands. The fish's meat is all stuck to the bones so you don't need to keep anything inside the fish. Some people use the guts, but most throw them out.
I prefer to keep the head on the fish (the eyes are delicious). Also I eat the fins and tail after frying, not sure if it's good for you or not but it tastes good (haha). Wash the fish off, rinsing it inside and out. Get rid of all the blood. You fillet it now, or just get cooking.
YouTube is a pretty good place to search for tutorial videos as well. |
10,462,063 | >
> NOTE: Andrew's response caused me to take yet another look. This feature is buried deep in a large application which has in internal timer. If that timer is *off* I get the wrong behavior described here. If the timer is *on* things work as expected. I don't know why that timer interacts with this table view, but, as I said, it's a large, complex app.
>
>
>
I want the user to be able to select which columns to show. He'll be presented with a set of radio buttons or check boxes, one for each key in the object being displayed. He can check or uncheck a box, and the NSTableView will add or delete a column for that key.
The object being displayed is an NSDictionary. The keys of the dictionary are not known until runtime, so I have to create columns with identifiers at runtime... they are not known at compile time.
Implementing the add functionality went smoothly. I create a column and a header cell, setting the text of the header cell to some value. But the delete is not being so easy. `[myTableView removeTableColumn:col]` deletes the column, but does not deal with the header so nicely. Sometimes the header text is not removed. Sometimes the header text in two columns is removed. Sometimes I end up with two header text strings printed on top of each other.
Clearly I'm missing something. How does one programmatically remove a column and its header? | 2012/05/05 | [
"https://Stackoverflow.com/questions/10462063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619754/"
] | I run on win 7 32 bit.
* open CMD and run :
```
cd "C:\Program Files\Microsoft SQL Server\110\Shared"
```
* Then Run :
```
mofcomp sqlmgmproviderxpsp2up.mof
```
[](https://i.stack.imgur.com/AsUH7.jpg)
**If You run at win 64, the directory is different**
Possible SQL version’s shared directory:
```
SQL 2008: C:\Program Files (x86)\Microsoft SQL Server\90\Shared\
SQL 2008 R2: C:\Program Files (x86)\Microsoft SQL Server\100\Shared\
SQL 2012: C:\Program Files (x86)\Microsoft SQL Server\110\Shared\
SQL 2014: C:\Program Files (x86)\Microsoft SQL Server\120\Shared\
SQL 2017: C:\Program Files (x86)\Microsoft SQL Server\140\Shared\
``` | I got this error too and just for a laugh I decided to run my command line window in administrator mode.
Funnily enough, it worked! Not knowing what your user privilege setup looks like I can't really say that this is a definitive fix for it though |
21,131,578 | I need to find exactly that td row which contains value priview '2'
I know the td row first half id, but it is dynamic: `MovementNumber_M_*` (Where `*` can be from 1 to Milion)
So need to search all rows from `MovementNumber_M_1` to `MovementNumber_M_9999` which contains `MovementNumber_M_*.value=2` and returning directly that td row id which contained that value.
Can you help me? Thanks in advice.
Right and helpfull answers guaranteed ;)
//EDIT
```
function DgIdOnClick (e,r){
var MovementNumber = document.getElementById(e).value;
//alert('MovementNumber: '+MovementNumber+' Type :'+r);
var result = $('[id^="MovementNumber_M_"][value='+MovementNumber+']');
result.each(function(){
alert($(this).attr("id"));
});
}
```
OK value=1 is for init and thats why are alerting all rows but if value is 2 then jq is not finding him WHY ?
The function DgIdOnClick is inicialized @
```
$( document ).ready(function() {
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
var FirstDiagnosis=$( "span[id^='lov_DgId_D_']" );
var SpanBlock=FirstDiagnosis.find('a');
var eventH=SpanBlock.attr( "onclick" );
SpanBlock.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(11)).id,1);"+eventH);
});
```
function DgIdOnClick is on other .js file
If i am alerting IN DgIdOnClick alert(document.getElementById('MovementNumber\_M\_2').value)//MovementNumber\_M\_2 Then value is 2 but jq is not founding it | 2014/01/15 | [
"https://Stackoverflow.com/questions/21131578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915214/"
] | This alerts the ID's of each row containing that value
```
var result = $('[id^="MovementNumber_M_"][value="2"]');
result.each(function(){
alert($(this).attr("id"));
});
```
<http://jsfiddle.net/q8QaG/>
Update:
This alerts the id of all inputs with the value of 2, even on input update
```
$("#button").click(function(){
$('[id^="MovementNumber_M_"]').each(function(){
var value = $(this).val();
if(value == 2){
alert($(this).attr("id"));
}
});
});
```
<http://jsfiddle.net/q8QaG/3/> | ```
$('#TableID').find('td').filter(':contains("SOME_TEXT")');
``` |
32,957,739 | I try to understand what the following sed command will do:
```
sed ‘s/[[:digit:]]+\([[:digit:]]\)/0/g’ myfile
``` | 2015/10/05 | [
"https://Stackoverflow.com/questions/32957739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482864/"
] | It is the **[`addition assignment`](http://www.w3schools.com/js/js_operators.asp)** operator (`+=`) to add a value to a variable.
Depending of the current type of the defined value on a variable, it will read the current value add/concat another value into it and define on the same variable.
For a `string`, you concat the current value with another value
```
let name = "User";
name += "Name"; // name = "UserName";
name += " is ok"; // name = "UserName is ok";
```
It is the same:
```
var name = "User";
name = name + "Name"; // name = "UserName";
name = name + " is ok"; // name = "UserName is ok";
```
For numbers, it will sum the value:
```
let n = 3;
n += 2; // n = 5
n += 3; // n = 8
```
In Javascript, we also have the following expressions:
* `-=` - Subtraction assignment;
* `/=` - Division assignment;
* `*=` - Multiplication assignment;
* `%=` - Modulus (Division Remainder) assignment. | ```
text += "The number is " + i;
```
is equivalent to
```
text = text + "The number is " + i;
``` |
32,113,118 | I have a problem and I can't find solution.
I'm using Razor and it is my VieModel class.
```
public class GroupToExport
{
public GroupToExport()
{
ToExport = false;
}
[DisplayName("Export")]
public bool ToExport { get; set; }
public Group Group { get; set; }
}
public class GroupsToExport
{
public GroupsToExport()
{
//refill list
}
public List<GroupToExport> ExportingGroups { get; set; }
}
```
View:
```
@using (Html.BeginForm("Export", "ElmahGroup", FormMethod.Post, new { id = "toExportForm" }))
{
//some divs
<input type="submit" id="js-export-submit" value="Export" />
@foreach (var item in Model.ExportingGroups)
{
<tr>
<td class="js-export-checkbox">
@Html.CheckBoxFor(modelItem => item.ToExport)
</td>
</tr>
}
//some divs
}
```
Controller:
```
public ActionResult Export(GroupsToExport model)
{
var groupsToExport = model.ExportingGroups.Where(x => x.ToExport).Select(x => x);
throw new System.NotImplementedException();
}
```
After submit "ToExport", in Controller, every group always has value 'false'. Even if all groups are checked.
Can somebody help me? What I'm doing wrong? | 2015/08/20 | [
"https://Stackoverflow.com/questions/32113118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3166192/"
] | You are using Incorrect syntax to Map the values back when they are posted, since the checked value of a checkbox is initialised to false by default, that is the reason why it is always false,use sysntax
```
@for(int i = 0; i < Model.ExportingGroups.Count(); i++)
{
<tr>
<td class="js-export-checkbox">
@Html.CheckBoxFor(modelItem => Model.ExportingGroups[i].ToExport)
</td>
</tr>
}
//some divs
```
This should map back all values you are looking for. | I found this works much better: Leave the foreach loop as is (do not user a counter)
```
@foreach (var item in Model.GroupToExport)
{
```
Then use this Razor format to display a checkbox
```
@Html.CheckBox("Active", @item.ToExport)
```
Simple to use and does not make you change the typical foreach loop. |
34,565 | I'm thinking of getting a nice laptop [thin like Macbook Air, Actually I'm thinking of getting Macbook Air itself]. Question is, how well it will go with Ubuntu.
Being ubuntu user for last 7 years, I cant think of moving away just for great hardware capabilities in AirBook. However, It would be great if Ubuntu 11.04 runs on Airbook smoothly without much of messy.
I would wish to have all Ubuntu 11.04 features to work with Macbook Air.[Video/Audio, Keyboard, Touchpad, etc]. Is there users out here tried and would recommend Macbook Air ?. Any good guide would help as well. | 2011/04/11 | [
"https://askubuntu.com/questions/34565",
"https://askubuntu.com",
"https://askubuntu.com/users/14014/"
] | There is a good discussion on the [Apple Users section of ubuntuforums](http://ubuntuforums.org/showthread.php?t=1603365) which is definitely worth a read through and contains probably the most up to date guide and experiences which others have had. You could also look at:
<http://ebsi4711.blogspot.com/2010/10/ubuntu-on-macbookair31-11.html> | I'm using Ubuntu on a Macbook Air 4,2 (mid 2011), and I'm not sure I'd do it again (buying an Air, despite the nice hardware). Setting up any Linux on an Air is really much hassle, since it cannot boot Linux off an USB stick (mac firmware problems).
If you have an official apple superdrive, using the install CD is supposed to work nice, but without it's too much pain.
---
See <http://cweiske.de/tagebuch/ubuntu-on-macbook-air.htm> for an installation howto and a hardware support table for Ubuntu 11.10. |
10,977,405 | The first two elements of my `tuple`s are computated (see below), but I want them to be 3-`tuple`s rather than 2-`tuple`s with the last element being set to `1`.
```
from itertools import permutations
if __name__ == '__main__':
alphabet='abcdefghijklmnopqrstuvwxyz'
print list(permutations(alphabet,2))
```
[Output](http://ideone.com/jagv6):
```
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('a', 'g'), ('a', 'h'), ('a', 'i'), ('a', 'j'), ('a', 'k'), ('a', 'l'), ('a', 'm'), ('a', 'n'), ('a', 'o'), ('a', 'p'), ('a', 'q'), ('a', 'r'), ('a', 's'), ('a', 't'), ('a', 'u'), ('a', 'v'), ('a', 'w'), ('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('b', 'g'), ('b', 'h'), ('b', 'i'), ('b', 'j'), ('b', 'k'), ('b', 'l'), ('b', 'm'), ('b', 'n'), ('b', 'o'), ('b', 'p'), ('b', 'q'), ('b', 'r'), ('b', 's'), ('b', 't'), ('b', 'u'), ('b', 'v'), ('b', 'w'), ('b', 'x'), ('b', 'y'), ('b', 'z'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('c', 'g'), ('c', 'h'), ('c', 'i'), ('c', 'j'), ('c', 'k'), ('c', 'l'), ('c', 'm'), ('c', 'n'), ('c', 'o'), ('c', 'p'), ('c', 'q'), ('c', 'r'), ('c', 's'), ('c', 't'), ('c', 'u'), ('c', 'v'), ('c', 'w'), ('c', 'x'), ('c', 'y'), ('c', 'z'), ('d', 'a'), ('d', 'b'), ('d', 'c'), ('d', 'e'), ('d', 'f'), ('d', 'g'), ('d', 'h'), ('d', 'i'), ('d', 'j'), ('d', 'k'), ('d', 'l'), ('d', 'm'), ('d', 'n'), ('d', 'o'), ('d', 'p'), ('d', 'q'), ('d', 'r'), ('d', 's'), ('d', 't'), ('d', 'u'), ('d', 'v'), ('d', 'w'), ('d', 'x'), ('d', 'y'), ('d', 'z'), ('e', 'a'), ('e', 'b'), ('e', 'c'), ('e', 'd'), ('e', 'f'), ('e', 'g'), ('e', 'h'), ('e', 'i'), ('e', 'j'), ('e', 'k'), ('e', 'l'), ('e', 'm'), ('e', 'n'), ('e', 'o'), ('e', 'p'), ('e', 'q'), ('e', 'r'), ('e', 's'), ('e', 't'), ('e', 'u'), ('e', 'v'), ('e', 'w'), ('e', 'x'), ('e', 'y'), ('e', 'z'), ('f', 'a'), ('f', 'b'), ('f', 'c'), ('f', 'd'), ('f', 'e'), ('f', 'g'), ('f', 'h'), ('f', 'i'), ('f', 'j'), ('f', 'k'), ('f', 'l'), ('f', 'm'), ('f', 'n'), ('f', 'o'), ('f', 'p'), ('f', 'q'), ('f', 'r'), ('f', 's'), ('f', 't'), ('f', 'u'), ('f', 'v'), ('f', 'w'), ('f', 'x'), ('f', 'y'), ('f', 'z'), ('g', 'a'), ('g', 'b'), ('g', 'c'), ('g', 'd'), ('g', 'e'), ('g', 'f'), ('g', 'h'), ('g', 'i'), ('g', 'j'), ('g', 'k'), ('g', 'l'), ('g', 'm'), ('g', 'n'), ('g', 'o'), ('g', 'p'), ('g', 'q'), ('g', 'r'), ('g', 's'), ('g', 't'), ('g', 'u'), ('g', 'v'), ('g', 'w'), ('g', 'x'), ('g', 'y'), ('g', 'z'), ('h', 'a'), ('h', 'b'), ('h', 'c'), ('h', 'd'), ('h', 'e'), ('h', 'f'), ('h', 'g'), ('h', 'i'), ('h', 'j'), ('h', 'k'), ('h', 'l'), ('h', 'm'), ('h', 'n'), ('h', 'o'), ('h', 'p'), ('h', 'q'), ('h', 'r'), ('h', 's'), ('h', 't'), ('h', 'u'), ('h', 'v'), ('h', 'w'), ('h', 'x'), ('h', 'y'), ('h', 'z'), ('i', 'a'), ('i', 'b'), ('i', 'c'), ('i', 'd'), ('i', 'e'), ('i', 'f'), ('i', 'g'), ('i', 'h'), ('i', 'j'), ('i', 'k'), ('i', 'l'), ('i', 'm'), ('i', 'n'), ('i', 'o'), ('i', 'p'), ('i', 'q'), ('i', 'r'), ('i', 's'), ('i', 't'), ('i', 'u'), ('i', 'v'), ('i', 'w'), ('i', 'x'), ('i', 'y'), ('i', 'z'), ('j', 'a'), ('j', 'b'), ('j', 'c'), ('j', 'd'), ('j', 'e'), ('j', 'f'), ('j', 'g'), ('j', 'h'), ('j', 'i'), ('j', 'k'), ('j', 'l'), ('j', 'm'), ('j', 'n'), ('j', 'o'), ('j', 'p'), ('j', 'q'), ('j', 'r'), ('j', 's'), ('j', 't'), ('j', 'u'), ('j', 'v'), ('j', 'w'), ('j', 'x'), ('j', 'y'), ('j', 'z'), ('k', 'a'), ('k', 'b'), ('k', 'c'), ('k', 'd'), ('k', 'e'), ('k', 'f'), ('k', 'g'), ('k', 'h'), ('k', 'i'), ('k', 'j'), ('k', 'l'), ('k', 'm'), ('k', 'n'), ('k', 'o'), ('k', 'p'), ('k', 'q'), ('k', 'r'), ('k', 's'), ('k', 't'), ('k', 'u'), ('k', 'v'), ('k', 'w'), ('k', 'x'), ('k', 'y'), ('k', 'z'), ('l', 'a'), ('l', 'b'), ('l', 'c'), ('l', 'd'), ('l', 'e'), ('l', 'f'), ('l', 'g'), ('l', 'h'), ('l', 'i'), ('l', 'j'), ('l', 'k'), ('l', 'm'), ('l', 'n'), ('l', 'o'), ('l', 'p'), ('l', 'q'), ('l', 'r'), ('l', 's'), ('l', 't'), ('l', 'u'), ('l', 'v'), ('l', 'w'), ('l', 'x'), ('l', 'y'), ('l', 'z'), ('m', 'a'), ('m', 'b'), ('m', 'c'), ('m', 'd'), ('m', 'e'), ('m', 'f'), ('m', 'g'), ('m', 'h'), ('m', 'i'), ('m', 'j'), ('m', 'k'), ('m', 'l'), ('m', 'n'), ('m', 'o'), ('m', 'p'), ('m', 'q'), ('m', 'r'), ('m', 's'), ('m', 't'), ('m', 'u'), ('m', 'v'), ('m', 'w'), ('m', 'x'), ('m', 'y'), ('m', 'z'), ('n', 'a'), ('n', 'b'), ('n', 'c'), ('n', 'd'), ('n', 'e'), ('n', 'f'), ('n', 'g'), ('n', 'h'), ('n', 'i'), ('n', 'j'), ('n', 'k'), ('n', 'l'), ('n', 'm'), ('n', 'o'), ('n', 'p'), ('n', 'q'), ('n', 'r'), ('n', 's'), ('n', 't'), ('n', 'u'), ('n', 'v'), ('n', 'w'), ('n', 'x'), ('n', 'y'), ('n', 'z'), ('o', 'a'), ('o', 'b'), ('o', 'c'), ('o', 'd'), ('o', 'e'), ('o', 'f'), ('o', 'g'), ('o', 'h'), ('o', 'i'), ('o', 'j'), ('o', 'k'), ('o', 'l'), ('o', 'm'), ('o', 'n'), ('o', 'p'), ('o', 'q'), ('o', 'r'), ('o', 's'), ('o', 't'), ('o', 'u'), ('o', 'v'), ('o', 'w'), ('o', 'x'), ('o', 'y'), ('o', 'z'), ('p', 'a'), ('p', 'b'), ('p', 'c'), ('p', 'd'), ('p', 'e'), ('p', 'f'), ('p', 'g'), ('p', 'h'), ('p', 'i'), ('p', 'j'), ('p', 'k'), ('p', 'l'), ('p', 'm'), ('p', 'n'), ('p', 'o'), ('p', 'q'), ('p', 'r'), ('p', 's'), ('p', 't'), ('p', 'u'), ('p', 'v'), ('p', 'w'), ('p', 'x'), ('p', 'y'), ('p', 'z'), ('q', 'a'), ('q', 'b'), ('q', 'c'), ('q', 'd'), ('q', 'e'), ('q', 'f'), ('q', 'g'), ('q', 'h'), ('q', 'i'), ('q', 'j'), ('q', 'k'), ('q', 'l'), ('q', 'm'), ('q', 'n'), ('q', 'o'), ('q', 'p'), ('q', 'r'), ('q', 's'), ('q', 't'), ('q', 'u'), ('q', 'v'), ('q', 'w'), ('q', 'x'), ('q', 'y'), ('q', 'z'), ('r', 'a'), ('r', 'b'), ('r', 'c'), ('r', 'd'), ('r', 'e'), ('r', 'f'), ('r', 'g'), ('r', 'h'), ('r', 'i'), ('r', 'j'), ('r', 'k'), ('r', 'l'), ('r', 'm'), ('r', 'n'), ('r', 'o'), ('r', 'p'), ('r', 'q'), ('r', 's'), ('r', 't'), ('r', 'u'), ('r', 'v'), ('r', 'w'), ('r', 'x'), ('r', 'y'), ('r', 'z'), ('s', 'a'), ('s', 'b'), ('s', 'c'), ('s', 'd'), ('s', 'e'), ('s', 'f'), ('s', 'g'), ('s', 'h'), ('s', 'i'), ('s', 'j'), ('s', 'k'), ('s', 'l'), ('s', 'm'), ('s', 'n'), ('s', 'o'), ('s', 'p'), ('s', 'q'), ('s', 'r'), ('s', 't'), ('s', 'u'), ('s', 'v'), ('s', 'w'), ('s', 'x'), ('s', 'y'), ('s', 'z'), ('t', 'a'), ('t', 'b'), ('t', 'c'), ('t', 'd'), ('t', 'e'), ('t', 'f'), ('t', 'g'), ('t', 'h'), ('t', 'i'), ('t', 'j'), ('t', 'k'), ('t', 'l'), ('t', 'm'), ('t', 'n'), ('t', 'o'), ('t', 'p'), ('t', 'q'), ('t', 'r'), ('t', 's'), ('t', 'u'), ('t', 'v'), ('t', 'w'), ('t', 'x'), ('t', 'y'), ('t', 'z'), ('u', 'a'), ('u', 'b'), ('u', 'c'), ('u', 'd'), ('u', 'e'), ('u', 'f'), ('u', 'g'), ('u', 'h'), ('u', 'i'), ('u', 'j'), ('u', 'k'), ('u', 'l'), ('u', 'm'), ('u', 'n'), ('u', 'o'), ('u', 'p'), ('u', 'q'), ('u', 'r'), ('u', 's'), ('u', 't'), ('u', 'v'), ('u', 'w'), ('u', 'x'), ('u', 'y'), ('u', 'z'), ('v', 'a'), ('v', 'b'), ('v', 'c'), ('v', 'd'), ('v', 'e'), ('v', 'f'), ('v', 'g'), ('v', 'h'), ('v', 'i'), ('v', 'j'), ('v', 'k'), ('v', 'l'), ('v', 'm'), ('v', 'n'), ('v', 'o'), ('v', 'p'), ('v', 'q'), ('v', 'r'), ('v', 's'), ('v', 't'), ('v', 'u'), ('v', 'w'), ('v', 'x'), ('v', 'y'), ('v', 'z'), ('w', 'a'), ('w', 'b'), ('w', 'c'), ('w', 'd'), ('w', 'e'), ('w', 'f'), ('w', 'g'), ('w', 'h'), ('w', 'i'), ('w', 'j'), ('w', 'k'), ('w', 'l'), ('w', 'm'), ('w', 'n'), ('w', 'o'), ('w', 'p'), ('w', 'q'), ('w', 'r'), ('w', 's'), ('w', 't'), ('w', 'u'), ('w', 'v'), ('w', 'x'), ('w', 'y'), ('w', 'z'), ('x', 'a'), ('x', 'b'), ('x', 'c'), ('x', 'd'), ('x', 'e'), ('x', 'f'), ('x', 'g'), ('x', 'h'), ('x', 'i'), ('x', 'j'), ('x', 'k'), ('x', 'l'), ('x', 'm'), ('x', 'n'), ('x', 'o'), ('x', 'p'), ('x', 'q'), ('x', 'r'), ('x', 's'), ('x', 't'), ('x', 'u'), ('x', 'v'), ('x', 'w'), ('x', 'y'), ('x', 'z'), ('y', 'a'), ('y', 'b'), ('y', 'c'), ('y', 'd'), ('y', 'e'), ('y', 'f'), ('y', 'g'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('y', 'k'), ('y', 'l'), ('y', 'm'), ('y', 'n'), ('y', 'o'), ('y', 'p'), ('y', 'q'), ('y', 'r'), ('y', 's'), ('y', 't'), ('y', 'u'), ('y', 'v'), ('y', 'w'), ('y', 'x'), ('y', 'z'), ('z', 'a'), ('z', 'b'), ('z', 'c'), ('z', 'd'), ('z', 'e'), ('z', 'f'), ('z', 'g'), ('z', 'h'), ('z', 'i'), ('z', 'j'), ('z', 'k'), ('z', 'l'), ('z', 'm'), ('z', 'n'), ('z', 'o'), ('z', 'p'), ('z', 'q'), ('z', 'r'), ('z', 's'), ('z', 't'), ('z', 'u'), ('z', 'v'), ('z', 'w'), ('z', 'x'), ('z', 'y')]
```
Trying to efficiently get to this:
```
[('a', 'b', 1), ('a', 'c', 1), ('a', 'd', 1), ('a', 'e', 1), ('a', 'f', 1), ('a', 'g', 1), ('a', 'h', 1), ('a', 'i', 1), ('a', 'j', 1), ('a', 'k', 1), ('a', 'l', 1), ('a', 'm', 1), ('a', 'n', 1), ('a', 'o', 1), ('a', 'p', 1), ('a', 'q', 1), ('a', 'r', 1), ('a', 's', 1), ('a', 't', 1), ('a', 'u', 1), ('a', 'v', 1), ('a', 'w', 1), ('a', 'x', 1), ('a', 'y', 1), ('a', 'z', 1), ('b', 'a', 1), ('b', 'c', 1), ('b', 'd', 1), ('b', 'e', 1), ('b', 'f', 1), ('b', 'g', 1), ('b', 'h', 1), ('b', 'i', 1), ('b', 'j', 1), ('b', 'k', 1), ('b', 'l', 1), ('b', 'm', 1), ('b', 'n', 1), ('b', 'o', 1), ('b', 'p', 1), ('b', 'q', 1), ('b', 'r', 1), ('b', 's', 1), ('b', 't', 1), ('b', 'u', 1), ('b', 'v', 1), ('b', 'w', 1), ('b', 'x', 1), ('b', 'y', 1), ('b', 'z', 1), ('c', 'a', 1), ('c', 'b', 1), ('c', 'd', 1), ('c', 'e', 1), ('c', 'f', 1), ('c', 'g', 1), ('c', 'h', 1), ('c', 'i', 1), ('c', 'j', 1), ('c', 'k', 1), ('c', 'l', 1), ('c', 'm', 1), ('c', 'n', 1), ('c', 'o', 1), ('c', 'p', 1), ('c', 'q', 1), ('c', 'r', 1), ('c', 's', 1), ('c', 't', 1), ('c', 'u', 1), ('c', 'v', 1), ('c', 'w', 1), ('c', 'x', 1), ('c', 'y', 1), ('c', 'z', 1), ('d', 'a', 1), ('d', 'b', 1), ('d', 'c', 1), ('d', 'e', 1), ('d', 'f', 1), ('d', 'g', 1), ('d', 'h', 1), ('d', 'i', 1), ('d', 'j', 1), ('d', 'k', 1), ('d', 'l', 1), ('d', 'm', 1), ('d', 'n', 1), ('d', 'o', 1), ('d', 'p', 1), ('d', 'q', 1), ('d', 'r', 1), ('d', 's', 1), ('d', 't', 1), ('d', 'u', 1), ('d', 'v', 1), ('d', 'w', 1), ('d', 'x', 1), ('d', 'y', 1), ('d', 'z', 1), ('e', 'a', 1), ('e', 'b', 1), ('e', 'c', 1), ('e', 'd', 1), ('e', 'f', 1), ('e', 'g', 1), ('e', 'h', 1), ('e', 'i', 1), ('e', 'j', 1), ('e', 'k', 1), ('e', 'l', 1), ('e', 'm', 1), ('e', 'n', 1), ('e', 'o', 1), ('e', 'p', 1), ('e', 'q', 1), ('e', 'r', 1), ('e', 's', 1), ('e', 't', 1), ('e', 'u', 1), ('e', 'v', 1), ('e', 'w', 1), ('e', 'x', 1), ('e', 'y', 1), ('e', 'z', 1), ('f', 'a', 1), ('f', 'b', 1), ('f', 'c', 1), ('f', 'd', 1), ('f', 'e', 1), ('f', 'g', 1), ('f', 'h', 1), ('f', 'i', 1), ('f', 'j', 1), ('f', 'k', 1), ('f', 'l', 1), ('f', 'm', 1), ('f', 'n', 1), ('f', 'o', 1), ('f', 'p', 1), ('f', 'q', 1), ('f', 'r', 1), ('f', 's', 1), ('f', 't', 1), ('f', 'u', 1), ('f', 'v', 1), ('f', 'w', 1), ('f', 'x', 1), ('f', 'y', 1), ('f', 'z', 1), ('g', 'a', 1), ('g', 'b', 1), ('g', 'c', 1), ('g', 'd', 1), ('g', 'e', 1), ('g', 'f', 1), ('g', 'h', 1), ('g', 'i', 1), ('g', 'j', 1), ('g', 'k', 1), ('g', 'l', 1), ('g', 'm', 1), ('g', 'n', 1), ('g', 'o', 1), ('g', 'p', 1), ('g', 'q', 1), ('g', 'r', 1), ('g', 's', 1), ('g', 't', 1), ('g', 'u', 1), ('g', 'v', 1), ('g', 'w', 1), ('g', 'x', 1), ('g', 'y', 1), ('g', 'z', 1), ('h', 'a', 1), ('h', 'b', 1), ('h', 'c', 1), ('h', 'd', 1), ('h', 'e', 1), ('h', 'f', 1), ('h', 'g', 1), ('h', 'i', 1), ('h', 'j', 1), ('h', 'k', 1), ('h', 'l', 1), ('h', 'm', 1), ('h', 'n', 1), ('h', 'o', 1), ('h', 'p', 1), ('h', 'q', 1), ('h', 'r', 1), ('h', 's', 1), ('h', 't', 1), ('h', 'u', 1), ('h', 'v', 1), ('h', 'w', 1), ('h', 'x', 1), ('h', 'y', 1), ('h', 'z', 1), ('i', 'a', 1), ('i', 'b', 1), ('i', 'c', 1), ('i', 'd', 1), ('i', 'e', 1), ('i', 'f', 1), ('i', 'g', 1), ('i', 'h', 1), ('i', 'j', 1), ('i', 'k', 1), ('i', 'l', 1), ('i', 'm', 1), ('i', 'n', 1), ('i', 'o', 1), ('i', 'p', 1), ('i', 'q', 1), ('i', 'r', 1), ('i', 's', 1), ('i', 't', 1), ('i', 'u', 1), ('i', 'v', 1), ('i', 'w', 1), ('i', 'x', 1), ('i', 'y', 1), ('i', 'z', 1), ('j', 'a', 1), ('j', 'b', 1), ('j', 'c', 1), ('j', 'd', 1), ('j', 'e', 1), ('j', 'f', 1), ('j', 'g', 1), ('j', 'h', 1), ('j', 'i', 1), ('j', 'k', 1), ('j', 'l', 1), ('j', 'm', 1), ('j', 'n', 1), ('j', 'o', 1), ('j', 'p', 1), ('j', 'q', 1), ('j', 'r', 1), ('j', 's', 1), ('j', 't', 1), ('j', 'u', 1), ('j', 'v', 1), ('j', 'w', 1), ('j', 'x', 1), ('j', 'y', 1), ('j', 'z', 1), ('k', 'a', 1), ('k', 'b', 1), ('k', 'c', 1), ('k', 'd', 1), ('k', 'e', 1), ('k', 'f', 1), ('k', 'g', 1), ('k', 'h', 1), ('k', 'i', 1), ('k', 'j', 1), ('k', 'l', 1), ('k', 'm', 1), ('k', 'n', 1), ('k', 'o', 1), ('k', 'p', 1), ('k', 'q', 1), ('k', 'r', 1), ('k', 's', 1), ('k', 't', 1), ('k', 'u', 1), ('k', 'v', 1), ('k', 'w', 1), ('k', 'x', 1), ('k', 'y', 1), ('k', 'z', 1), ('l', 'a', 1), ('l', 'b', 1), ('l', 'c', 1), ('l', 'd', 1), ('l', 'e', 1), ('l', 'f', 1), ('l', 'g', 1), ('l', 'h', 1), ('l', 'i', 1), ('l', 'j', 1), ('l', 'k', 1), ('l', 'm', 1), ('l', 'n', 1), ('l', 'o', 1), ('l', 'p', 1), ('l', 'q', 1), ('l', 'r', 1), ('l', 's', 1), ('l', 't', 1), ('l', 'u', 1), ('l', 'v', 1), ('l', 'w', 1), ('l', 'x', 1), ('l', 'y', 1), ('l', 'z', 1), ('m', 'a', 1), ('m', 'b', 1), ('m', 'c', 1), ('m', 'd', 1), ('m', 'e', 1), ('m', 'f', 1), ('m', 'g', 1), ('m', 'h', 1), ('m', 'i', 1), ('m', 'j', 1), ('m', 'k', 1), ('m', 'l', 1), ('m', 'n', 1), ('m', 'o', 1), ('m', 'p', 1), ('m', 'q', 1), ('m', 'r', 1), ('m', 's', 1), ('m', 't', 1), ('m', 'u', 1), ('m', 'v', 1), ('m', 'w', 1), ('m', 'x', 1), ('m', 'y', 1), ('m', 'z', 1), ('n', 'a', 1), ('n', 'b', 1), ('n', 'c', 1), ('n', 'd', 1), ('n', 'e', 1), ('n', 'f', 1), ('n', 'g', 1), ('n', 'h', 1), ('n', 'i', 1), ('n', 'j', 1), ('n', 'k', 1), ('n', 'l', 1), ('n', 'm', 1), ('n', 'o', 1), ('n', 'p', 1), ('n', 'q', 1), ('n', 'r', 1), ('n', 's', 1), ('n', 't', 1), ('n', 'u', 1), ('n', 'v', 1), ('n', 'w', 1), ('n', 'x', 1), ('n', 'y', 1), ('n', 'z', 1), ('o', 'a', 1), ('o', 'b', 1), ('o', 'c', 1), ('o', 'd', 1), ('o', 'e', 1), ('o', 'f', 1), ('o', 'g', 1), ('o', 'h', 1), ('o', 'i', 1), ('o', 'j', 1), ('o', 'k', 1), ('o', 'l', 1), ('o', 'm', 1), ('o', 'n', 1), ('o', 'p', 1), ('o', 'q', 1), ('o', 'r', 1), ('o', 's', 1), ('o', 't', 1), ('o', 'u', 1), ('o', 'v', 1), ('o', 'w', 1), ('o', 'x', 1), ('o', 'y', 1), ('o', 'z', 1), ('p', 'a', 1), ('p', 'b', 1), ('p', 'c', 1), ('p', 'd', 1), ('p', 'e', 1), ('p', 'f', 1), ('p', 'g', 1), ('p', 'h', 1), ('p', 'i', 1), ('p', 'j', 1), ('p', 'k', 1), ('p', 'l', 1), ('p', 'm', 1), ('p', 'n', 1), ('p', 'o', 1), ('p', 'q', 1), ('p', 'r', 1), ('p', 's', 1), ('p', 't', 1), ('p', 'u', 1), ('p', 'v', 1), ('p', 'w', 1), ('p', 'x', 1), ('p', 'y', 1), ('p', 'z', 1), ('q', 'a', 1), ('q', 'b', 1), ('q', 'c', 1), ('q', 'd', 1), ('q', 'e', 1), ('q', 'f', 1), ('q', 'g', 1), ('q', 'h', 1), ('q', 'i', 1), ('q', 'j', 1), ('q', 'k', 1), ('q', 'l', 1), ('q', 'm', 1), ('q', 'n', 1), ('q', 'o', 1), ('q', 'p', 1), ('q', 'r', 1), ('q', 's', 1), ('q', 't', 1), ('q', 'u', 1), ('q', 'v', 1), ('q', 'w', 1), ('q', 'x', 1), ('q', 'y', 1), ('q', 'z', 1), ('r', 'a', 1), ('r', 'b', 1), ('r', 'c', 1), ('r', 'd', 1), ('r', 'e', 1), ('r', 'f', 1), ('r', 'g', 1), ('r', 'h', 1), ('r', 'i', 1), ('r', 'j', 1), ('r', 'k', 1), ('r', 'l', 1), ('r', 'm', 1), ('r', 'n', 1), ('r', 'o', 1), ('r', 'p', 1), ('r', 'q', 1), ('r', 's', 1), ('r', 't', 1), ('r', 'u', 1), ('r', 'v', 1), ('r', 'w', 1), ('r', 'x', 1), ('r', 'y', 1), ('r', 'z', 1), ('s', 'a', 1), ('s', 'b', 1), ('s', 'c', 1), ('s', 'd', 1), ('s', 'e', 1), ('s', 'f', 1), ('s', 'g', 1), ('s', 'h', 1), ('s', 'i', 1), ('s', 'j', 1), ('s', 'k', 1), ('s', 'l', 1), ('s', 'm', 1), ('s', 'n', 1), ('s', 'o', 1), ('s', 'p', 1), ('s', 'q', 1), ('s', 'r', 1), ('s', 't', 1), ('s', 'u', 1), ('s', 'v', 1), ('s', 'w', 1), ('s', 'x', 1), ('s', 'y', 1), ('s', 'z', 1), ('t', 'a', 1), ('t', 'b', 1), ('t', 'c', 1), ('t', 'd', 1), ('t', 'e', 1), ('t', 'f', 1), ('t', 'g', 1), ('t', 'h', 1), ('t', 'i', 1), ('t', 'j', 1), ('t', 'k', 1), ('t', 'l', 1), ('t', 'm', 1), ('t', 'n', 1), ('t', 'o', 1), ('t', 'p', 1), ('t', 'q', 1), ('t', 'r', 1), ('t', 's', 1), ('t', 'u', 1), ('t', 'v', 1), ('t', 'w', 1), ('t', 'x', 1), ('t', 'y', 1), ('t', 'z', 1), ('u', 'a', 1), ('u', 'b', 1), ('u', 'c', 1), ('u', 'd', 1), ('u', 'e', 1), ('u', 'f', 1), ('u', 'g', 1), ('u', 'h', 1), ('u', 'i', 1), ('u', 'j', 1), ('u', 'k', 1), ('u', 'l', 1), ('u', 'm', 1), ('u', 'n', 1), ('u', 'o', 1), ('u', 'p', 1), ('u', 'q', 1), ('u', 'r', 1), ('u', 's', 1), ('u', 't', 1), ('u', 'v', 1), ('u', 'w', 1), ('u', 'x', 1), ('u', 'y', 1), ('u', 'z', 1), ('v', 'a', 1), ('v', 'b', 1), ('v', 'c', 1), ('v', 'd', 1), ('v', 'e', 1), ('v', 'f', 1), ('v', 'g', 1), ('v', 'h', 1), ('v', 'i', 1), ('v', 'j', 1), ('v', 'k', 1), ('v', 'l', 1), ('v', 'm', 1), ('v', 'n', 1), ('v', 'o', 1), ('v', 'p', 1), ('v', 'q', 1), ('v', 'r', 1), ('v', 's', 1), ('v', 't', 1), ('v', 'u', 1), ('v', 'w', 1), ('v', 'x', 1), ('v', 'y', 1), ('v', 'z', 1), ('w', 'a', 1), ('w', 'b', 1), ('w', 'c', 1), ('w', 'd', 1), ('w', 'e', 1), ('w', 'f', 1), ('w', 'g', 1), ('w', 'h', 1), ('w', 'i', 1), ('w', 'j', 1), ('w', 'k', 1), ('w', 'l', 1), ('w', 'm', 1), ('w', 'n', 1), ('w', 'o', 1), ('w', 'p', 1), ('w', 'q', 1), ('w', 'r', 1), ('w', 's', 1), ('w', 't', 1), ('w', 'u', 1), ('w', 'v', 1), ('w', 'x', 1), ('w', 'y', 1), ('w', 'z', 1), ('x', 'a', 1), ('x', 'b', 1), ('x', 'c', 1), ('x', 'd', 1), ('x', 'e', 1), ('x', 'f', 1), ('x', 'g', 1), ('x', 'h', 1), ('x', 'i', 1), ('x', 'j', 1), ('x', 'k', 1), ('x', 'l', 1), ('x', 'm', 1), ('x', 'n', 1), ('x', 'o', 1), ('x', 'p', 1), ('x', 'q', 1), ('x', 'r', 1), ('x', 's', 1), ('x', 't', 1), ('x', 'u', 1), ('x', 'v', 1), ('x', 'w', 1), ('x', 'y', 1), ('x', 'z', 1), ('y', 'a', 1), ('y', 'b', 1), ('y', 'c', 1), ('y', 'd', 1), ('y', 'e', 1), ('y', 'f', 1), ('y', 'g', 1), ('y', 'h', 1), ('y', 'i', 1), ('y', 'j', 1), ('y', 'k', 1), ('y', 'l', 1), ('y', 'm', 1), ('y', 'n', 1), ('y', 'o', 1), ('y', 'p', 1), ('y', 'q', 1), ('y', 'r', 1), ('y', 's', 1), ('y', 't', 1), ('y', 'u', 1), ('y', 'v', 1), ('y', 'w', 1), ('y', 'x', 1), ('y', 'z', 1), ('z', 'a', 1), ('z', 'b', 1), ('z', 'c', 1), ('z', 'd', 1), ('z', 'e', 1), ('z', 'f', 1), ('z', 'g', 1), ('z', 'h', 1), ('z', 'i', 1), ('z', 'j', 1), ('z', 'k', 1), ('z', 'l', 1), ('z', 'm', 1), ('z', 'n', 1), ('z', 'o', 1), ('z', 'p', 1), ('z', 'q', 1), ('z', 'r', 1), ('z', 's', 1), ('z', 't', 1), ('z', 'u', 1), ('z', 'v', 1), ('z', 'w', 1), ('z', 'x', 1), ('z', 'y', 1)]
```
(I'm happy for it be nested `list` rather than nested 3-`tuple`) | 2012/06/11 | [
"https://Stackoverflow.com/questions/10977405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438003/"
] | Before `print a`, insert
```
a = [(x, y, 1) for x, y in a]
```
Or, replace
```
list(permutations([alphabet[i],alphabet[i+1]]))
```
with
```
[(alphabet[i], alphabet[i+1], 1), (alphabet[i+1], alphabet[i], 1)]
```
**EDIT**: with your new requirement, the easiest solution is
```
[(x, y, 1) for x, y in permutations(alphabet, 2)]
```
For general length-*k* permutations, that becomes
```
[p + (1,) for p in permutations(alphabet, k)]
``` | My current solution, in case anyone is still interested:
```
[x + (1,) for x in list(permutations(alphabet,2))+[(alpha, alpha) for alpha in alphabet]]
```
Would still be interested if there is a more efficient way of doing this though... |
365,643 | Say I have a data model, which looks like this:
```
public class DataCustomer
{
public virtual System.DateTime CreatedTime { get; set; }
public virtual Guid Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string Surname { get; set; }
public virtual string FaxNumber{ get; set; }
public virtual System.DateTime DateOfBirth { get; set; }
public virtual String Gender { get; set; }
public virtual string UserID { get; set; }
public virtual List<Offers> Offers { get; set; }
}
```
This class is mapped to NHibernate. Now say I have a Domain Model like this:
```
public class DomainCustomer
{
private virtual Guid Id { get; set; }
private virtual String Gender { get; set; }
private virtual DateTime DateOfBirth { get; set; }
public virtual List<Offers> Offers { get; set; }
public DomainCustomer(Guid id, string gender, DateTime dateOfBirth)
{
Id=id;
Gender=gender;
DateOfBirth=dateOfBirth;
}
public void AssignOffers(IOfferCalculator offerCalculator, IList<Offers> offers)
{
//Assign the offers here
}
}
```
Notice that the Data Model looks different to the Domain Model. I believe this is normal practice, however every example I look at online seems to show the Data Model being the same as the domain model.
**Option 1**
The advantage of them being identical is that mapping between the Domain Model and Data Model is very simple i.e. you can do this with AutoMapper:
```
DataCustomer dataCustomer = AutoMapper.Mapper.Map<DataCustomer>(domainCustomer);
```
**Option 2**
The advantage of them being different is that there is less data passed between the data model and domain model and vice versa. Also I think that it makes it slightly clearer i.e. a user/reader of my class knows what fields are needed by the domain model. With this approach; I would only map the members that have changed i.e. offers:
```
customerData.Offers = AutoMapper.Mapper.Map<string>(customerDomain.Offers);
```
**Decision**
Both options use a factory when mapping between CustomerData and CustomerDomain. The question is about the mapping between CustomerDomain and CustomerData using AutoMapper.
Which option is more expected if I am following the principle of least astonishment? | 2018/02/09 | [
"https://softwareengineering.stackexchange.com/questions/365643",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/65549/"
] | A domain model and the data model have a different view of the world and should be expressed in the code.
The domain model should be modeled so that it aligns to the **business** view of the application while the data model is all about manipulating the domain model so that it's easy to be consumed by others for specific view/action related reasons (e.g. REST API, Web Page or Forms app...) | There is no reason why you **must** keep them the same, though it's *desirable*.
Imaging you are storing the info in an array of strings. Your data model would differ completely from your domain model.
Imaging your data model isn't yours (you are using a third-party API). Your business logic might differ from the business logic of that third-party.
The rule of thumb here is: you have to keep your domain models as close to your needs as you can. |
65,028,370 | I've been following [this](http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/) tutorial on rendering to an off-screen texture, but I'm having difficulty creating the render target.
I've registered an error callback function and I'm getting a `GL_DEBUG_TYPE_OTHER` error back with a `GL_DEBUG_SOURCE_API` source, which is getting spat out by `glCheckNamedFramebufferStatus()` with the message:
>
> FBO incomplete: color attachment incomplete[0].
>
>
>
I'm struggling to see what I'm missing here, I've double checked the parameters that I'm passing into the OpenGL functions and tried removing the `glTexParameteri` calls but to no avail.
Any help would be greatly appreciated.
```c
GLuint framebuffer = 0;
GLuint renderedTexture;
GLenum drawBuffers[1] = {GL_COLOR_ATTACHMENTS0};
bool buildOffscreenBuffer()
{
// creating frame & render texture to draw picker buffer to
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glGenTextures(1, &renderedTexture);
glBindTexture(GL_TEXTURE_2D, renderedTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1920, 1080,
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// configuring framebuffer
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
renderedTexture, 0);
glDrawBuffers(1, drawBuffers);
return glCheckNamedFramebufferStatus(framebuffer, GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
}
```
**Update:**
As per [derhass](https://stackoverflow.com/users/2327517/derhass)' [answer](https://stackoverflow.com/a/65030135/11058021), it seems that GL\_RGB isn't required as per the spec. I've tried updating this to GL\_RGBA but I'm getting the same error. Since this may be implementation related, I'll list my card and driver:
Card: RX Vega 56
Driver: [mesa/amdgpu](https://wiki.archlinux.org/index.php/AMDGPU) | 2020/11/26 | [
"https://Stackoverflow.com/questions/65028370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11058021/"
] | As per the GL spec, `GL_RGB` is not in the set of *required renderable formats*, so implementations are free to not support it. Try `GL_RGBA` instead. | Managed to get to the bottom of this. I'd actually fixed the bug in simplifying the example for the post.
```c
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1920, 1080,
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
```
Was actually getting the width and height from a helper function that from a platform layer, however that function returned a `struct {int, int}` that I was storing in a `struct {float, float}` . This resulted in garbage being passed as the width and height to `glTexImage2D`. |
39,834 | Longitudinal axis (x) is the axis orthogonal to its lateral directions (y and z), but what is transverse direction? Is transverse just another term for lateral? | 2021/01/20 | [
"https://engineering.stackexchange.com/questions/39834",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/7336/"
] | The terms *lateral* and *transverse* often get mixed up, because they can refer to the same thing, although this is not necessary.
To my understanding **any lateral is transverse** but the opposite is not necessarily true.
**Transverse axis** is any axis perpendicular to the longitudinal axis
**Lateral axis** (*to my understanding/how I'd use it*) implies being to the side, so in a sense it accounts for gravity. So Lateral axis describes an axis that is perpendicular to the longitudinal and its also perpendicular to the gravity axis (parallel to the horizontal plane).
1. Movements of blocks.
-----------------------
### 1.1. Block moving horizontally
for the following example:
[](https://i.stack.imgur.com/UUefPm.png)
* The longitudinal axis is along the direction of movement so its parallel to X.
* Y an Z can be both termed *transverse axis*.
* Z can be termed *lateral axis*
### 1.2Mass moving vertically
for the following example:
[](https://i.stack.imgur.com/BKg6Vm.png)
* Again The longitudinal axis is along the direction of movement so its parallel to Y.
* X and Z can be both termed *transverse axis*
* X and Z can be termed *lateral axis* (this is a singularity)
### 1.3. mass moving on an incline
In the following example
[](https://i.stack.imgur.com/SbHZZ.png)
* Again the longitudinal axis is along the direction of movement so its **none of the XYZ**
* Y can be termed *transverse axis*
* Y can be termed *lateral axis*
2. Forces
---------
With forces -in my personal experience- there is usually less confusion .
* **Transverse forces:** refer to any force perpendicular to the longitudinal axis
* **Lateral forces:** refer to any force perpendicular to the longitudinal axis and parallel to horizontal plane
So in the following example:
[](https://i.stack.imgur.com/8UepMm.png)
* Transverse forces are: Radial force and lateral force
* Lateral forces are: well... the lateral force | 1. "Transverse" is quite clear, it is an axis that makes 90 degrees to the reference axis. So, if the reference axis is x-axis, both the y and z axes are "transverse" to the x-axis.
2. "Lateral" has a few different meanings and usages:
a) "The lateral distance...", means the horizontal distance between the referenced axis and another axis in parallel.
b) "in the lateral direction", means in the direction transverse to the longitudinal axis of an object.
c) "The lateral force", means a horizontal force, that is acting in direction transverse to the gravity. |
1,150,633 | I have the following JUnit test:
```
@Test
public void testRunLocalhost() throws IOException, InterruptedException {
// Start an AnnouncerThread
final AnnouncerThread announcer = new AnnouncerThread();
announcer.start();
// Create the socket and listen on the right port.
final DatagramSocket socket = new DatagramSocket();
assert(socket != null);
// Create a packet to send.
final DatagramPacket packet = new DatagramPacket(new byte[0], 0, InetAddress.getByName(AnnouncerThread.GROUP), AnnouncerThread.PORT);
assert(packet != null);
// Send the packet.
socket.send(packet);
// Listen for the IP from the server.
final DatagramPacket receivedPacket = new DatagramPacket(new byte[256], 256);
socket.setSoTimeout(2000); // Only wait 2 seconds.
socket.receive(receivedPacket);
socket.close();
// Get localhost's address.
final InetAddress localhost = InetAddress.getLocalHost();
assert(localhost != null);
// Compare the receive IP to the localhost IP.
final String receivedIP = new String(receivedPacket.getData());
if (!receivedIP.startsWith(localhost.getHostAddress())) {
fail("Received IP: '" + receivedIP + "' not the same as localhost: '" + localhost.getHostAddress() + "'");
}
announcer.shutdown();
announcer.join();
}
```
And PMD gives the following violations:
```
Found 'UR'-anomaly for variable 'socket' (lines '36'-'36').
Found 'UR'-anomaly for variable 'localhost' (lines '36'-'36').
Found 'UR'-anomaly for variable 'packet' (lines '36'-'36').
```
Line 36 in my file is the line the method is defined:
```
public void testRunLocalhost() throws IOException, InterruptedException {
```
I don't understand what the violations are saying. Where should I defining those three variables? Why wasn't the AnnouncerThread in the violations? It's declared the same way I've tried re-ordering the declarations to no avail. | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68507/"
] | It does appear to have something to do with the `assert` calls you're making right after allocating those three final variables.
The PMD docs (<http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis>) say:
>
> UR - Anomaly: There is a reference to a variable that was not defined before
>
>
> | That looks rather strange. Interestingly, it occurs for all three variables that are defined for objects allocated via 'new', which you then check for nullness. I would expect the result of 'new' to always be valid/not-null - otherwise an `OutOfMemoryException` should be thrown. Is that the issue, I wonder ? |
64,189,069 | My config is Google Pixel 128gb, android 10, Magisk 20.4 + 8.0.0 manager, have the mysterious problem!
I need to use .bat script, who have some code `adb shell "sh sdcard/airplane.sh"`
But it's not working!
Got error `cmd: Failure calling service activity: Failed transaction (2147483646)`
If I type it in cmd by my hands in 2 lines like: `adb shell` and then `sh sdcard/airplane.sh` it works perfect!
How I can fix this? Someone can help? | 2020/10/03 | [
"https://Stackoverflow.com/questions/64189069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2689175/"
] | comment this line in `validator.js` (`\node_modules\jsonschema\lib\validator.js:111`):
```js
if((typeof schema !== 'boolean' && typeof schema !== 'object') || schema === null){
throw new SchemaError('Expected `schema` to be an object or boolean');
}
``` | In the runtime go to \node\_modules\jsonschema\lib\validator.js. Replace the code on line 106 with
```js
if((typeof schema == 'boolean' && typeof schema == 'object') || schema === null){
``` |
2,388,256 | I have a web based (perl/MySQL) CRM system, and I need a section for HR to add details about disciplinary actions and salary.
All this information that we store in the database needs to be encrypted so that we developers can't see it.
I was thinking about using AES encryption, but what do I use as the key? If I use the HR Manager's password then if she forgets her password, we lose all HR information. If she changes her password, then we have to decrypt all information and re-encrypt with the new password, which seems inefficient, and dangerous, and could go horrifically wrong if there's an error half way through the process.
I had the idea that I could have an encryption key that encrypts all the information, and use the HR manager's password to encrypt the key. Then she can change her password all she likes and we'll only need to re-encrypt the key. (And without the HR Manager's password, the data is secure)
But then there's still the problem of multi-user access to the encrypted data.
I could keep a 'plaintext' copy of the key off site, and encrypt it with each new HR person's password. But then I know the master key, which doesn't seem ideal.
Has anyone tried this before, and succeeded? | 2010/03/05 | [
"https://Stackoverflow.com/questions/2388256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71062/"
] | GnuPG allows documents to be encrypted using multiple public keys, and decrypted using any one of the corresponding private keys. In this way, you could allow data to be encrypted using the public keys of the everyone in the HR department. Decryption could be performed by any one having one of the private keys. Decryption would require both the private key and the passphrase protecting the key to be known to the system. The private keys could be held within the system, and the passphrase solicited from the user.
The data would probably get quite bloated by GnuPG using lots of keys: it has to create a session key for the payload and then encrypt that key using each of the public keys. The encrypted keys are stored alongside the data.
The weak parts of the system are that the private keys need to be available to the system (ie. not under the control of the user), and the passphrase will have to pass through the system, and so could be compromised (ie. logged, stolen) by dodgy code. Ultimately, the raw data passes through the system too, so dodgy code could compromise that without worrying about the keys. Good code review and release control will be essential to maintain security.
You are best avoiding using MySQL's built in encryption functions: these get logged in the replication, slow, or query logs, and can be visible in the processlist - and so anyone having access to the logs and processlist have access to the data. | Another approach is to use a single system-wide key stored in the database - perhaps with a unique id so that new keys can be added periodically. Using Counter Mode, the standard MySQL AES encryption can be used without directly exposing the cleartext to the database, and the size of the encrypted data will be exactly the same as the size of the cleartext. A sketch of the algorithm:
1. The application generates a unique initial counter value for the record. This might be based on some unique attribute of the record, or you could generate and store a unique value for this purpose.
2. The application generates a stream of counter blocks for the record based on the initial counter value. The counter stream must be the same size or up to 1 block larger than the cleartext.
3. The application determines which key to use. If keys are being periodically rotated, then the most recent one should be used.
4. The counter stream is sent to the database to be encrypted: something like
select aes\_encrypt( 'counter', key ) from hrkeys where key\_id = 'id';
5. The resulting encrypted counter value is trimmed to the length of the cleartext, and XORed with the cleartext to produce the encrypted text.
6. The encrypted text is stored.
7. Decryption is exactly the same process applied to the encrypted text.
The advantages are that the cleartext never goes any where near the database, and so the administrators cannot see the sensitive data. However, you are then left with the problem of preventing your adminstrators from accessing the encrypted counter values or the keys. The first can be achieved by using SSL connections between your application and database for the encryption operations. The second can be mitigated with access control, ensuring that the keys never appear in the database dumps, storing the keys in in-memory tables so that access control cannot be subverted by restarting the database with "skip-grants". Ultimately, the only way to eliminate this threat is to use a tamper-proof device (HSM) for performing encryption. The higher the security you require, the less likely you will be able to store the keys in the database.
See [Wikipedia - Counter Mode](http://en.wikipedia.org/wiki/Counter_mode#Counter_.28CTR.29) |
2,098,069 | Can someone look at the linked reference and explain to me the precise statements to run?
[Oracle DBA's Guide: Creating a Large Index](http://download-west.oracle.com/docs/cd/B28359_01/server.111/b28310/indexes003.htm#i1006643)
Here's what I came up with...
```
CREATE TEMPORARY TABLESPACE ts_tmp
TEMPFILE 'E:\temp01.dbf' SIZE 10000M
REUSE AUTOEXTEND ON EXTENT MANAGEMENT LOCAL;
ALTER USER me TEMPORARY TABLESPACE ts_tmp;
CREATE UNIQUE INDEX big_table_idx ON big_table ( record_id );
DROP TABLESPACE ts_tmp;
```
**Edit 1**
After this index was created, I ran an explain plan for a simple query and get this error:
```
ORA-00959: tablespace 'TS_TMP' does not exist
```
It seems like it's not temporary at all... :( | 2010/01/19 | [
"https://Stackoverflow.com/questions/2098069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] | >
>
> ```
> CREATE TEMPORARY TABLESPACE ts_tmp
> TEMPFILE 'E:\temp01.dbf' SIZE 10000M
> REUSE AUTOEXTEND ON EXTENT MANAGEMENT LOCAL;
>
> ```
>
>
This creates a temporary tablespace (an area on disk where the intermediate sort results will be stored). An index is a sorted set of data, and sorting needs lots of space.
"Temporary" here means that the data that is stored is temporary by nature, not that the tablespace itself is temporary. Think of it like of `/tmp` directory in `Unix` or `%TEMP%` folded in `Windows` : the directory / folder itself is permanent, but the data stored within it are temporary.
`REUSE` means do not fail if the file already exists (usually used when the filename points to a raw device, like unformatted disk partition, to avoid `OS` file management overhead). Instead, it will just open the file for writing and fill it with the new data. If not for this clause, the command would fail if the file with the given name existed.
`AUTOEXTEND ON` means "grow the file if required". If you set it to off and `10Gb` will be not enough for the sorting operation, the tablespace will not automatically grow, and the operation will fail.
`EXTENT MANAGEMENT LOCAL` means that the tablespace layout is stored in the tablespace itself (not in the system tables). Not sure about `11g`, but in previous versions of `Oracle` this option was not available for temporary tablespaces.
>
>
> ```
> ALTER USER me TEMPORARY TABLESPACE ts_tmp;
>
> ```
>
>
This makes the user `me` to use the newly created temp tablespace as a temporary storage medium
>
>
> ```
> CREATE UNIQUE INDEX big_table_idx ON big_table ( record_id );
>
> ```
>
>
This just creates the index.
>
>
> ```
> DROP TABLESPACE ts_tmp;
>
> ```
>
>
This drops the temporary tablespace.
Before running the script, figure out the current default tablespace:
```
SELECT temporary_tablespace
FROM dba_users
WHERE username = 'ME'
```
Most probably, it will return `TEMP`.
Before dropping `ts_tmp`, revert the default temp tablespace for the user:
```
ALTER USER me TEMPORARY TABLESPACE temp; -- or whatever the previous query returned.
``` | There is a small secret about oracle, table space, this one only increases in oracle, and will never decrease in size, what they are trying to do here is to avoid this situation, so it creates a temporary table space and use that table space to create the index and then drop it. |
3,782 | By default Kate inserts 2 spaces on Tab press but switches to real tabs starting from the fourth Tab level. Can I disable this and use spaces always, regardless to the depth?
I want this because I use Kate to code Scala, and using space pairs instead of tabs is a convention there. | 2010/11/05 | [
"https://unix.stackexchange.com/questions/3782",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/2119/"
] | Adding to the present answers, an important thing to realize about how aliases work is that all the parameters you type after an aliased command will be used literally at the end. So there is no way to use alias for two commands (piped or not), out of which the first should interpret the parameters. To make it clear, here's an example of something that would not work as expected:
```
alias lsswp="ls -l | grep swp"
```
(an example inspired by [this question](https://unix.stackexchange.com/questions/19926/aliases-interpretation)) this will always use the output of `ls -l` performed in the *current* directory and do a grep on that - so using
```
lsswp /tmp/
```
would be equivalent to `ls -l | grep swp /tmp/` and **not** `ls -l /tmp/ | grep swp`.
For all purposes where the arguments should be used somewhere in the middle, one needs to use a *function* instead of an alias. | You don't have to do anything, actually; aliases do this automatically. For instance:
```
$ alias less="less -eirqM"
$ less foo.txt
```
You will see foo.txt's first page, and `less` will quit at EOF (-e), searches will be case-insensitive (-i), etc. |
57,977,349 | Calling microsoft graph API <https://graph.microsoft.com/v1.0/subscribedSkus> fails with
"code": "Authorization\_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
This is happening if we create a new user in the tenant who is non admin. But while calling this with Admin user it works just fine. Even it works for any microsoft user in the tenant.
This is the below code I used to try.
```
public static async Task TestAadGraph()
{
// using obo token of the user.
var graphToken = await GetTokenAsync(UserId, Token, "https://graph.microsoft.com");
var aadGraphClient = new AadGraphClient(new HttpClient());
var licenseResponse = await aadGraphClient.GetTenantLicenseDetailAsync(graphToken);
foreach (var license in licenseResponse)
{
Console.WriteLine("Sku ID: {0}", license.SkuId);
Console.WriteLine("Sku Part Number: {0}", license.SkuPartNumber);
foreach (var plan in license.ServicePlans)
{
Console.WriteLine("Plan Id: {0}", plan.ServicePlanId);
Console.WriteLine("Plan Name: {0}", plan.ServicePlanName);
}
}
}
public async Task<SubscribedSku[]> GetTenantLicenseDetailAsync(string accessToken)
{
var request = new RequestMessage
{
BearerToken = accessToken,
Endpoint = new Uri("http://graph.microsoft.com/v1.0/subscribedSkus"),
};
var response = await _httpClient.FetchAsync<SubscribedSkusResponse>(request);
return response.Value;
}
public static async Task<T> FetchAsync<T>(this HttpClient httpClient, RequestMessage request, Action<HttpResponseMessage, string> responseCallback) where T : class
{
request.Method = request.Method ?? HttpMethod.Get;
request.MediaType = request.MediaType ?? "application/json";
using (HttpRequestMessage message = new HttpRequestMessage(request.Method,
UrlHelper.AppendParameters(request.Params, request.Endpoint)))
{
if (!string.IsNullOrEmpty(request.BearerToken))
{
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer",
request.BearerToken);
}
if (request.Headers != null)
{
foreach (KeyValuePair<string, string> header in request.Headers)
{
message.Headers.Add(header.Key, header.Value);
}
}
if (!string.IsNullOrEmpty(request.Content))
{
message.Content = new StringContent(request.Content, Encoding.UTF8,
request.MediaType);
}`
using (HttpResponseMessage response = await httpClient.SendAsync(message))
{
string json = await response.Content.ReadAsStringAsync();
if (responseCallback != null)
{
responseCallback?.Invoke(response, json);
}
if (response.IsSuccessStatusCode)
{
if (predictor != null)
{
json = predictor(JToken.Parse(json)).ToString();
}
return JsonConvert.DeserializeObject<T>(json);
}
else
{
throw new WebRequestException(response, json);
}
}
}
}
``` | 2019/09/17 | [
"https://Stackoverflow.com/questions/57977349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6393049/"
] | Let's say you want to search for a date `2019-01-03`.
```
SELECT
id,
group_id
FROM membership
WHERE '2019-01-03' BETWEEN in_group_begin AND IFNULL(in_group_end, CURRENT_DATE);
```
If you have another `users` table which stores details of users and `id` of that table is used in `membership` table using `id` field. You can do following query.
```
SELECT
u.id,
u.name,
u.address,
m.group_id
FROM users u
INNER JOIN membership m ON u.id = m.id
WHERE '2019-01-03' BETWEEN in_group_begin AND IFNULL(in_group_end, CURRENT_DATE);
``` | Assuming there is a table `users` from which you want the user's details returned, join it to your table `tablename` like this:
```
select u.*, t.group_id
from users u inner join (
select
id, group_id, in_group_begin,
coalesce(in_group_end, current_date) in_group_end
from tablename
) t on t.id = u.id and @date between t.in_group_begin and t.in_group_end
```
Replace `@date` with the date you search for. |
2,270,552 | Im getting into Winsocks and is there any reference to tell me what a packet is. Like UDP/TCP Packets? | 2010/02/16 | [
"https://Stackoverflow.com/questions/2270552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69467/"
] | Google is your friend here. If anything is available on the internet it is TCP/IP information.
[This](http://en.wikipedia.org/wiki/Transmission_Control_Protocol) is as good a start as any. When you get really serious [this](http://www.kohala.com/start/tcpipiv1.html) is as close to a classic text as there is. | a packet is small piece of data witch can be transferable over a network.
in it data is packed along with check sum for error checking.
For UDP - you can say it is nothing but broadcasting of messages(Packets) with no acknowledgment.
And For TCP/IP - It is protocol for transferring data over network |
202,575 | You should **believe** me
You should **believe in** me
Both of two are natural ?
When i intend to say that you should trust me | 2019/03/27 | [
"https://ell.stackexchange.com/questions/202575",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/91634/"
] | I don't think we have a standard word to express that idea. It would depend on the body part and the image you want to convey when you describe it.
These are my poor attempts at examples:
>
> Six long graceful toes extended from each of her feet.
>
>
> Bushy black eyebrows sprouted wildly from above his deep brown eyes.
>
>
> A large wart grew out from the tip of her nose.
>
>
> All of her brothers had very large ears protruding from their heads.
>
>
> A long gray beard hung from his chin half-way down to his waist.
>
>
>
For the seraphim wings, I would probably go with "extended from", but others will probably be able to come up with a more creative verb.
After further reflection, I think I might use "emerge":
>
> I could not take my eyes off the huge pair of seraphim wings emerging
> from the her back.
>
>
> | Spawn and or spawned. Seraphim wings spawned forth from her back. |
53,866,169 | I have a JSON model, which I build from a Metadata set.
So I created that JSON array and did the following:
```js
var oModel = new JSONModel({
JSONDataSet: oJSONDataArray
});
this._oFragment.setModel(oModel);
```
In my fragment, I have a table:
```xml
<Table id="tableId" items="{ path:'/JSONDataSet' }">
<columns>
<Column>
<Text text="HeaderColumn1"/>
</Column>
<!-- ... -->
</columns>
<ColumnListItem>
<Text text="{Value1}"/>
<!-- ... -->
</ColumnListItem>
</Table>
```
Now everything works fine on my fragment. In my list, I'll see all that data from my JSON model, but I still receive this weird error in my console:
>
> List Binding is not bound against a list for /JSONDataSet
>
>
>
How can I solve this issue? | 2018/12/20 | [
"https://Stackoverflow.com/questions/53866169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236137/"
] | >
> List Binding is not bound against a list for ...
>
>
>
The above [error occurs only in ODataListBinding.js](https://github.com/SAP/openui5/blob/84de3414276401e2ff03b480b8ae074d31b1ee18/src/sap.ui.core/src/sap/ui/model/odata/v2/ODataListBinding.js#L981-L983) and is thrown when the module fails to find the entityset name within the service $metadata document **or** if the resulting multiplicity is not `"*"`. [source](https://github.com/SAP/openui5/blob/84de3414276401e2ff03b480b8ae074d31b1ee18/src/sap.ui.core/src/sap/ui/model/odata/v2/ODataListBinding.js#L913-L920)
---
In your case, the framework assumes that `JSONDataSet` is some entity set name defined in the $metadata which obviously cannot be found. In order to prevent framework to search for that in $metadata, you'll need to tell that `JSONDataSet` is **not** from the unnamed default model (ODataModel) but from another model (JSONModel).
Try to give it a name, and assign the name in the binding definitions like this:
```js
const oModel = new JSONModel({
JSONDataSet: /*some data*/
});
this._oFragment.setModel(oModel, "anotherModel");
```
```xml
<Table id="tableId" items="{anotherModel>/JSONDataSet}">
<!-- ... -->
<ColumnListItem>
<Text text="{anotherModel>Value1}"/>
<!-- ... -->
</ColumnListItem>
</Table>
```
The framework won't try to resolve `anotherModel>/JSONDataSet` until that model is registered and set to the fragment. The error will be gone since the framework now knows that it's not initializing ODataListBinding but a client ListBinding. | If you take a look at the browser console, probably you have already an error telling you that "the template or factory function was not provided" or something similar.
In the following code, there is something missing
```
<Table id="tableId" items="{ path:'/JSONDataSet' }">
<columns>
.....
<columns>
</Table>
```
if you do `items="{ path:'/JSONDataSet' }"`, it means that you want the items in your list to be created dynamically based on the path `/JSONDataSet` from your model. This path should point to an array of some kind (usually an array of objects). Using UI5 terms, you are trying to use an [aggregation binding](https://ui5.sap.com/#/topic/91f057786f4d1014b6dd926db0e91070).
However, how do you want the items in your Table to be created?
That's why you need to provide a template item, declaring an example item inside your table:
```
<Table id="tableId" items="{ path:'/JSONDataSet' }">
<columns>
.....
<columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier
title="{a}"
text="{b}"/>
<Text
text="{c}" />
</cells>
</ColumnListItem>
</items>
</Table>
```
See more examples in the [UI5 documentation](https://ui5.sap.com/#/entity/sap.m.Table).
In the code above, `a`, `b` and `c` are proprierties found in every object inside you array.
In the end, if you array contains 10 items, 10 rows will be created in your table. If you want to create columns dynamically, just provide a single Column example and use `columns="{ path:'/JSONDataSet'}` instead. |
461,417 | I'm trying to run my junit tests using ant. The tests are kicked off using a JUnit 4 test suite. If I run this direct from Eclipse the tests complete without error. However if I run it from ant then many of the tests fail with this error repeated over and over until the junit task crashes.
```
[junit] java.util.zip.ZipException: error in opening zip file
[junit] at java.util.zip.ZipFile.open(Native Method)
[junit] at java.util.zip.ZipFile.(ZipFile.java:114)
[junit] at java.util.zip.ZipFile.(ZipFile.java:131)
[junit] at org.apache.tools.ant.AntClassLoader.getResourceURL(AntClassLoader.java:1028)
[junit] at org.apache.tools.ant.AntClassLoader$ResourceEnumeration.findNextResource(AntClassLoader.java:147)
[junit] at org.apache.tools.ant.AntClassLoader$ResourceEnumeration.nextElement(AntClassLoader.java:130)
[junit] at org.apache.tools.ant.util.CollectionUtils$CompoundEnumeration.nextElement(CollectionUtils.java:198)
[junit] at sun.misc.CompoundEnumeration.nextElement(CompoundEnumeration.java:43)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.checkForkedPath(JUnitTask.java:1128)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.executeAsForked(JUnitTask.java:1013)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.execute(JUnitTask.java:834)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.executeOrQueue(JUnitTask.java:1785)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.execute(JUnitTask.java:785)
[junit] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
[junit] at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
[junit] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[junit] at java.lang.reflect.Method.invoke(Method.java:597)
[junit] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[junit] at org.apache.tools.ant.Task.perform(Task.java:348)
[junit] at org.apache.tools.ant.Target.execute(Target.java:357)
[junit] at org.apache.tools.ant.Target.performTasks(Target.java:385)
[junit] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
[junit] at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
[junit] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[junit] at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
[junit] at org.apache.tools.ant.Main.runBuild(Main.java:758)
[junit] at org.apache.tools.ant.Main.startAnt(Main.java:217)
[junit] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
[junit] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
```
my test running task is as follows:
```
<target name="run-junit-tests" depends="compile-tests,clean-results">
<mkdir dir="${test.results.dir}"/>
<junit failureproperty="tests.failed" fork="true" showoutput="yes" includeantruntime="false">
<classpath refid="test.run.path" />
<formatter type="xml" />
<test name="project.AllTests" todir="${basedir}/test-results" />
</junit>
<fail if="tests.failed" message="Unit tests failed"/>
</target>
```
I've verified that the classpath contains the following as well as all of the program code and libraries:
```
ant-junit.jar
ant-launcher.jar
ant.jar
easymock.jar
easymockclassextension.jar
junit-4.4.jar
```
I've tried debugging to find out which ZipFile it is trying to open with no luck, I've tried toggling *includeantruntime* and *fork* and i've tried running ant with *ant -lib test/libs* where test/libs contains the ant and junit libraries.
Any info about what causes this exception or how you've configured ant to successfully run unit tests is gratefully received.
ant 1.7.1 (ubuntu), java 1.6.0\_10, junit 4.4
Thanks.
**Update - Fixed**
Found my problem. I had included my classes directory in my path using a fileset as opposed to a pathelement this was causing .class files to be opened as ZipFiles which of course threw an exception. | 2009/01/20 | [
"https://Stackoverflow.com/questions/461417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56679/"
] | It sounds like there is an issue with paths.
Check following error source:
* classpath: print out the classpath variable in a junit test, run it from eclipse and ant, so you can compare them
* Check your project for absolute paths. Probably, ant uses other path prefixes than eclipse.
Some more information would help to help :)
Good luck! | If you are using Ubuntu or Debian, this will make JUnit (and some other libs) always available for Ant:
```
sudo apt-get install ant-optional
``` |
24,032,654 | Given:
I have the following two variables in Javascript:
```
var x = {
dummy1: null
dummy2: null
};
// Return true
var y = {
dummy1: 99,
dummy2: 0
}
// Return false
var y = "";
// Return false
var y = {
dummy1: null
};
// Return false
var y = {
dummy1: null,
dummy2: null,
dummy3: 'z'
}
// Return false
var y = null;
// Return false
var y = ""
```
Can anyone suggest to me how I can check if object `x` has the same field names as `y` ? Note that I am **not** checking the values of the parameters. | 2014/06/04 | [
"https://Stackoverflow.com/questions/24032654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are probably better names for these functions, but this should do it:
```
function hasAllProperties(subItem, superItem) {
// Prevent error from using Object.keys() on non-object
var subObj = Object(subItem),
superObj = Object(superItem);
if (!(subItem && superItem)) { return false; }
return Object.keys(subObj).every(function (key) {
return key in superObj;
});
}
function allPropertiesShared(x, y) {
return hasAllProperties(x, y) &&
hasAllProperties(y, x);
}
``` | Try this:
```
Object.keys(y).every(function (key) {
return key in x;
});
``` |
751,432 | >
> An object mass $1 \, \rm kg$ hangs on a rope length $1 \, \rm m$. The object gets pushed with minimal horizontal velocity required to swing a full vertical circle, i.e.: keeping the rope stretched.
>
>
> What time $t\_c$ does it take to complete that intact circle?
>
>
>
I added conclusion near end.
I have seen similar questions and answers to describe minimal horizontal velocity and variable velocity along the circular swing path, and to compute maximal tension on the rope. They all use conservation of kinetic + potential energy and balance centrifugal force with gravitational force at the top of the circular swing path.
But I have not seen the time described.
I ask because I wonder how that time compares to time $t\_v$ when just pushing the object straight upward with minimal vertical velocity required to reach same top height $2 \, \rm m$ and to come down again.
Because in the first case the minimal velocity is bigger than in the second case, but, in the second case the distance is smaller than in the first case.
So would $t\_c$ be bigger or smaller or equal to $t\_v$ ?
I found (classical exercise: using distance formula for falling object (no rope attached) in time)
$t\_v \simeq 1.3 \, \rm s$
and
$t\_c \simeq 1.2 \, \rm s$
but I am not sure I am reasoning correctly.
On the other hand, times near $1 \, \rm s$ feel realistic to me for both.
As requested: here is my original approach which I was not sure to be correct.
```
>>> import numpy as np
>>> from math import pi, sqrt
# define velocity in function of height
# see https://www.geeksforgeeks.org/motion-in-a-vertical-circle/
>>> def v(h):
... return sqrt(9.81*(5-2*h))
...
# test some values
>>> v(0)
7.003570517957251
>>> v(1)
5.424942396007538
>>> v(2)
3.132091952673165
# f(h) is the (non elliptic) integral of v(h) (Wolfram)
>>> def f(h):
... return -1.04403*(5-2*h)**(3/2)
...
# find average velocity
>>> (f(2)-f(0))/2
5.314290126372764
# find time
>>> (2*pi)/5.314290126372764
1.182318834268865
```
Later, having seen expert answers I replaced height by angle.
code:
```
# import some stuff
>>> import numpy as np
>>> from scipy.integrate import quad
>>> from math import pi, sin, sqrt
# velocity function v
# note h = 1 - sin(x) and v^2 = g * (5 - 2 * h)
>>> def v(x):
... return sqrt((9.81)*(3-2*sin(x)))
...
# test some values
>>> v(-pi/2)
7.003570517957251
>>> v(0)
5.424942396007538
>>> v(pi/2)
3.132091952673165
# values look as expected
# integrate velocity from -pi/2 to +pi/2
>>> res, err = quad(v, -pi/2, pi/2)
>>> print(res)
16.507274579464244
# find average meters per second
>>> res/pi
5.254428692593845
# find time for distance 2pi
>>> print((2*pi)/(res/pi))
1.1957884814453341
```
Note that in both cases $t\_c \simeq 1.2$
I am also not sure how precise numerical integration really is.
So I asked question in this exchange to compare outcome.
**conclusion**: mistake in my approach is to calculate **average** velocity to find time. One must **integrate inverse** of **angle** velocity to find time.
Both given answers are correct. They give $t\_c \simeq 1.289 s$ and so $t\_c$ is a little bit bigger than $t\_v \simeq 1.277 s$. | 2023/02/22 | [
"https://physics.stackexchange.com/questions/751432",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/359072/"
] | While I agree with the other answers regarding work required to initiate current, and no work done by the current, let me add another perspective.
>
> But, if there's no resistance when a current flows through a superconductor, doesn't that mean there's no energy lost as heat? ***That would seem to imply we're adding energy to a system (by getting a current going) without increasing the entropy, which should be impossible — more energy means an increased number of possible microstates of the system, which means the ratio of micro to macro states should increase and hence increase the entropy.*** But I don't see how that can be the case if there's no resistance.
>
>
>
(emphasis mine)
What is *implicit in the argument about the number of microstates, is that there are mechanism, which allows transitions between these microstates.* In particular, in a normal conductor these would be transmission of energy to phonons and other excitations, whereby the energy from the current is diffusing away. Usual thermodynamic arguments imply that such interactions exist, even though they can be neglected, and the the system visits all possible configurations during its time evolution (known as *ergodicity*.)
These arguments do break when there is no relaxation mechanism (as in superconductors) - there is minimum energy required for dissipation to occur, which is reached only when we reach *critical current density* (and as the dissipation occurs, the superconductivity is destroyed.)
Not unrelated case where the thermodynamic arguments fail is when the relaxation mechanisms are too slow for reaching equilibrium within the reasonable time (which is no bigger than the time of the existence of the Universe, but in practice is shorter than the lifetime of a scientist performing the experiment.) This is how *phase transitions* occur, as, e.g., permanent magnetization of a magnet. Phil Anderson has given a valuable discussion of this point in his [More is Different](https://cse-robotics.engr.tamu.edu/dshell/cs689/papers/anderson72more_is_different.pdf) article. | The [second law of thermodynamics](https://en.wikipedia.org/wiki/Second_law_of_thermodynamics) only says that no process can decrease the entropy of the universe (i.e. destroy entropy). An equivalent view is that no process can create exergy. From a field perspective, the divergence of entropy is always positive.
While rough reasoning like you are stating are ways to start, actual candidates for a violation of the second law must amount to the destruction of entropy or creation of exergy. If you believe you have found a candidate for a violation, you should be able to state where that happened (the entropy destruction). I'm not just hand waving here, a second law violation should accompany a theoretical type two perpetual motion machine.
To my understanding, current flowing indefinitely in a superconducting wire is not destroying any entropy. This is not even considering the fact that the "superconductor" may still have a finite resistance, and so slowly generate heat and come to a zero current state.
Idealized processes, like true superconductors, frictionless bearings for flywheels, resistanceless batteries, engines and refrigerators that transfer heat at zero temperature differential, and so on, are not violations of the second law. They are the boundary between possible and impossible processes. In effect, all real processes are irreversible and "reversible" processes are the boundary between real, irreversible processes and impossible processes that violate the second law. I am using the term "boundary" pretty literally here, in reference to phase space. There are also all sorts of processes in phase space that violate the first law, but that those are impossible is not too controversial for people to understand.
To answer your example, a single material conductor that can be at thermal equilibrium with its surroundings and start a current flowing in itself by becoming colder than its surroundings is a second law violation. You can see how this is vastly different than a superconductor. The way I said this is important, because thermocouples are not second law violations. Also note that this example is a theoretical type two perpetual motion machine. Such a conductor could use the energy of the surroundings to run a motor forever in a closed system. For obvious reasons, thermocouple type devices cannot be used to construct a PPM.
Note that rotating bodies in space "rotate forever" and this is not a second law violation (use this example if you don't like the frictionless flywheel someone said elsewhere). A remote astronomical body will rotate forever, no mechanical energy is created by that and there is no second law violation. In reality, it may not rotate forever due to gravity waves, etc. |
13,644,385 | In my php project i have a javascript variable say "addText" which contains the following html content
```
<div class="foxcontainer" style="width:100% !important;">
<h2>FREE IN HOME CONSULTATION</h2>
<ul class="fox_messages">
<li>Invalid field: Your name</li>
<li>Invalid field: Your email</li>
</ul>
<form enctype="multipart/form-data" class="foxform" action="/hima/bigriglawgroup/index.php/about-us#mid_131" method="post">
<!-- mod_foxcontact 2.0.19 GNU/GPLv3 -->
<div class="foxfield">
<input class="invalidfoxtext" value="Your name" title="Your name" style="width:85% !important;display:block;float:none;margin:0 auto !important;" name="_c31f7a92d344f9a5c23d07fd438ba0b6" onfocus="if(this.value==this.title) this.value='';" onblur="if(this.value=='') this.value=this.title;" type="text">
<span class="asterisk"></span>
</div>
<div class="foxfield">
<input class="invalidfoxtext" value="Your email" title="Your email" style="width:85% !important;display:block;float:none;margin:0 auto !important;" name="_4fd8a7bb907c63baca708086b63eb7f0" onfocus="if(this.value==this.title) this.value='';" onblur="if(this.value=='') this.value=this.title;" type="text">
<span class="asterisk"></span>
</div>
<div class="foxfield">
<input class="validfoxtext" value="Phone number" title="Phone number" style="width:85% !important;display:block;float:none;margin:0 auto !important;" name="_68a05eb930e9ce854ed0c2d2d25c14a1" onfocus="if(this.value==this.title) this.value='';" onblur="if(this.value=='') this.value=this.title;" type="text">
</div>
<div class="foxfield">
<textarea rows="" cols="" class="validfoxtext" name="_0ef408e84316ef5737db72a727579f48" title="Notes" style="width:85% !important;height:180px !important;display:block;float:none;margin:0 auto !important;" onfocus="if(this.value==this.title) this.value='';" onblur="if(this.value=='') this.value=this.title;">retret ret ret ret</textarea>
</div>
<div class="foxfield">
<button class="foxbutton" type="submit" style="margin-right:32px;" name="mid_131">
<span>Submit</span>
</button>
</div>
<div class="fox-copyright" style="padding:10px 0 !important;text-indent:0 !important">
<a target="_blank" title="Joomla contact form" href="#" style="display: none !important; display: inline !important; font-size:10px !important;">powered by fox contact</a>
</div>
</form>
</div>
```
here I want to check the string "Invalid field" is present or not in that content. If it's not present I want to do some other functionality.But I don't know How to do this
Does any one know this ? Please help me ASPS.
Thanks in advance | 2012/11/30 | [
"https://Stackoverflow.com/questions/13644385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1866141/"
] | ```
if (addText.indexOf("Invalid field") != -1) { /* it's present */ }
// OR with regex
if (/Invalid field/.test(addText)) { /* it's present */ }
// OR with case-insensitve regex:
if (/Invalid field/i.test(addText)) { /* it's present */ }
``` | you can use `strstr` , document @ <http://www.php.net/manual/en/function.strstr.php>
Thanks |
403,590 | I've updated my repositories on synabtics the upgraded firefox to newer version, when I open it it crashes, while this I was having my hard drive plugged .. so I tried to reboot to fix Firefox crash ..
From that point I can't login, tried many solutions as I can. Additional information could help you solving my problem that my computer reading the unplugged hard drive with its two partions .. tried to unmount it but with no success. | 2017/11/09 | [
"https://unix.stackexchange.com/questions/403590",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/230614/"
] | First, the most important thing: *you can do it.*
Windows configurability is catastrophic, so the best if you start with a Windows pendrive and you extend it with a secondary Linux partition and with a more intelligent bootloader.
Thus, the required steps:
1. Get your Windows boot pendrive from anywhere. In the details, for example <https://superuser.com> can be your friend.
2. It is very important, that the Win should be on the first partition of the USB disk. W$ has the "nice" feature, that partitioned pendrives can see only their first partition on it, and no more. There is no workaround against it without major w$ kernel hacks, what is impossible.
3. So you have a dual-partition pendrive, on its first partition should be the win, and the Linux on the second.
The BIOS will see the pendrive as 0x80 hard disk. But if you plug in to your devel machine, it will be some alternate hard disk (most probably, `/dev/sdb`). It can have a little trouble with the bootloader install:
### LILO
In LILO, you can predefine for the disks, below which bios disk number will they be visible, on this way in the `lilo.conf`:
```
disk = /dev/sda
#bios = 0x80
inaccessible
disk = /dev/sdb
bios = 0x81
#inaccessible
```
The disadvantage of the Lilo is that you have to understand its exact workings much better to avoid the mystical "won't work" problems.
Lilo, as the BIOS tools in general, doesn't see partitions, it reads only a map of sectors. This map can be anywhere on the pendrive.
### Grub
As far I know, grub suspects the boot install drive will be 0x80, what is clear. However, my experience is that the probability of mystical "won't work"-like problems are in the case of grub much higher, despite that it can - theoretically - read into the filesystems on the boot device.
The solution requires an in-depth reconfiguration of grub on a deeper level as the `update-grub`, `grub-install` scripts today do. Prepare for a lot of mystical problems.
### Syslinux/Isolinux
Syslinux wants a FAT or ISO fs for boot, none of them are possible for a recent windows install (wanting NTFS), thus it probably falls out, because it contradicts with the Windows requirement that it wants to boot from the first partition. You may be able to use syslinux in a highly uncommon configuration (3 partitions: 1: windows NTFS, 2: linux ext4, 3: boot fat).
---
I personally would solve such a task on this way:
1. I would get a win-only pendrive image from somewhere
2. I would get an ubuntu live cd
3. I would merge the two that the win would go into the first partition, the Linux into the second,
4. I would throw away the syslinux of the ubuntu live cd and I would boot it with LILO (the syslinux config contains the info, how exactly should you boot the Ubuntu from the pendrive).
5. Finally I would talk my boss/customer to accept that the pendrive will be readonly. If it doesn't work or I would want a perfect solution, then I would clone a minimal ubuntu system. Btw, read-write usable windows system is probably impossible from a pendrive, only install/live/rescue kits are existing. With Linux you can do it, but it requires bonus work. Alternativelly, instead the ubuntu livecd I would suggest to give a try to knoppix. | try [www.easy2boot.com](http://www.easy2boot.com)
Unlimited Windows ISOs, linux ISOs, VHDs, WIMs, .IMA, linux+persistence, Secure boot UEFI, etc.
The USB stick can be prepared using linux or Windows. |
83,684 | This is a follow-up on my previous question about a VBA macro for randomizing a draw from a table. It can be found here:
[Randomizing Civilization 5 team choice](https://codereview.stackexchange.com/questions/83573/randomizing-civilization-5-team-choice)
The code has been improved with the help I got earlier and I now seek even further improvements.
```
Public Enum CivilizationTableColumns
CivilizationName = 1
CivilizationLeader = 2
End Enum
Public Enum TextColumns
PlayerTextColumn = 1
CivTextColumn = 2
End Enum
Public Sub Draw()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
Dim resultsRange As Range
Set resultsRange = GetResultsRange(ws)
resultsRange.ClearContents
Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")
Dim randCiv As String
For noOfPlayers = 1 To GetPlayerNum(ws)
resultsRange.Cells(GetPlayerNameRow(ws, noOfPlayers), PlayerTextColumn).Value = GetPlayerName(noOfPlayers)
For noOfOptions = 1 To GetOptionsNum(ws)
Dim endOfRange As Boolean
endOfRange = False
While Not endOfRange
randCiv = GetCivilizationCaption(GetRandomNum(CivilizationsTable), CivilizationsTable)
For Z = 1 To resultsRange.Rows.Count
If resultsRange.Cells(Z, CivTextColumn) = randCiv Then
Exit For
End If
If Z = resultsRange.Rows.Count Then
endOfRange = True
End If
Next Z
Wend
resultsRange.Cells(GetCivNameRow(ws, noOfPlayers, noOfOptions), CivTextColumn).Value = randCiv
Next noOfOptions
Next noOfPlayers
End Sub
Private Function GetRandomNum(ByVal CivilizationsTable As ListObject) As Integer
GetRandomNum = CInt(Int((CivilizationsTable.Range.Rows.Count - 1) * Rnd())) + 1
End Function
Private Function GetCivilizationCaption(ByVal index As Long, ByVal CivilizationsTable As ListObject)
Set Row = CivilizationsTable.ListRows(index)
civName = Row.Range(ColumnIndex:=CivilizationName)
civLeader = Row.Range(ColumnIndex:=CivilizationLeader)
GetCivilizationCaption = civLeader & " (" & civName & ")"
End Function
Private Function GetPlayerNum(ByVal ws As Worksheet)
GetPlayerNum = ws.Cells(3, 3).Value
End Function
Private Function GetOptionsNum(ByVal ws As Worksheet)
GetOptionsNum = ws.Cells(3, 7).Value
End Function
Private Function GetPlayerName(ByVal noOfPlayers As Integer) As String
GetPlayerName = "Player " & noOfPlayers
End Function
Private Function GetCivNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer, ByVal noOfOptions As Integer) As Integer
GetCivNameRow = (GetOptionsNum(ws) + 2) * (noOfPlayers - 1) + (noOfOptions + 3)
End Function
Private Function GetPlayerNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer) As Integer
GetPlayerNameRow = 3 + (GetOptionsNum(ws) + 2) * (noOfPlayers - 1)
End Function
Private Function GetResultsRange(ByVal ws As Worksheet) As Range
Set GetResultsRange = ws.Range("K1:L50")
End Function
``` | 2015/03/09 | [
"https://codereview.stackexchange.com/questions/83684",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/67710/"
] | Your indentation is generally fine, except the `Draw` procedure isn't indented as it should; everything in a `Sub` block should be indented 1 level, so that this:
```
Next noOfPlayers
End Sub
```
Becomes that:
```
Next noOfPlayers
End Sub
```
I like that you have lots of small functions - that's very good!
However `Draw` could be further broken down; I'm removing the fluff to illustrate:
```
Public Sub Draw()
For
For
While
For
'...
Next
Wend
Next
Next
End Sub
```
That's 4 layers of nested loops! I've seen worse arrow code, but I'd [extract a method](https://github.com/retailcoder/Rubberduck/wiki/Features#refactorings) out of the body of the 2nd `For` loop, to make it look like this:
```
Public Sub Draw()
For
For
ExtractedMethodCall
Next
Next
End Sub
```
Other than that, looks great! | First I'd like to say that this is a vast improvement over your original code. It's nice to see advice given on CR taken to heart and implemented. Well done. Now that it's easier to understand what the code is doing, let's talk about performance.
As @Mat'sMug mentioned in his answer, the code has nested loops 4 levels deep. That's bound to be a performance killer. I think we can solve this by storing some information in a dictionary instead. You'll need to [add a reference to the Scripting Runtime](http://www.ehow.com/how_7495029_add-scripting-runtime-type-library.html) to get access to the dictionary class. (It can be late bound too, but my example will be early bound and require a reference.)
The reason for the deepest loop is so you don't duplicate any civilizations in your results. We can do away with this by storing the possible civilizations in the dictionary and remove each one from the dictionary of possible entries as we use it. Retrieving an item from a dict is an \$O(1)\$ operation, so this should result in an improvement. *Most of the time... [there are other considerations](https://stackoverflow.com/questions/20658774/how-strings-are-stored-in-a-vba-dictionary-structure/20666510#20666510)*.
First we need a way to create a dictionary from your data table, so create a private module level variable.
```
Private Options As Scripting.Dictionary
```
And a method to initialize it.
```
Private Sub InitializeCivilizationDict()
Set Options = New Scripting.Dictionary
Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")
Dim item As ListRow
Dim i As Long
With CivilizationsTable.ListRows
For i = 1 To .Count
dict.Add .item(i).Range(ColumnIndex:=CivilizationName).Value, _
.item(i).Range(ColumnIndex:=CivilizationLeader).Value
Next i
End With
End Sub
```
And a data structure to represent a civilization.
```
Private Type Civilization
Name As String
Leader As String
End Type
```
And a slight change to your `GetRandomNum` function.
```
Private Function GetRandomNum(ByVal max As Integer) As Integer
GetRandomNum = CInt(Int((max) * Rnd())) + 1
End Function
```
Now we implement a way to get a random civilization from the dictionary, and remove it as it gets returned.
```
Private Function GetRandomCivilization() As Civilization
Dim randIndex As Integer
randIndex = GetRandomNum(Options.Count)
Dim result As Civilization
result.Name = Options.Keys(randIndex)
result.Leader = Options.Items(randIndex)
Options.Remove result.Name
GetRandomCivilizationFromDict = result
End Function
```
A new function to format the caption. (This replaces `GetCivilizationCaption`.)
```
Private Function FormatCivilizationCaption(ByVal civName As String, ByVal civLeader As String) As String
FormatCivilizationCaption = civLeader & " (" & civName & ")"
End Function
```
Finally, we'll work these new methods into your `Draw` routine.
```
Public Sub Draw()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
Dim resultsRange As Range
Set resultsRange = GetResultsRange(ws)
resultsRange.ClearContents
Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")
Dim randCiv As String
Dim noOfPlayers As Integer
InitializeCivilizationDict
For noOfPlayers = 1 To GetPlayerNum(ws)
resultsRange.Cells(GetPlayerNameRow(ws, noOfPlayers), PlayerTextColumn).Value = GetPlayerName(noOfPlayers)
Dim noOfOptions As Integer
For noOfOptions = 1 To GetOptionsNum(ws)
Dim civ As Civilization
civ = GetRandomCivilization
resultsRange.Cells(GetCivNameRow(ws, noOfPlayers, noOfOptions), CivTextColumn).Value = FormatCivilizationCaption(civ.Name, civ.Leader)
Next noOfOptions
Next noOfPlayers
End Sub
```
So, we've eliminated one whole loop and moved another out side of the nesting. A significant performance improvement on paper. I didn't bench mark it.
The whole code is below.
```
Option Explicit
Public Enum CivilizationTableColumns
CivilizationName = 1
CivilizationLeader = 2
End Enum
Public Enum TextColumns
PlayerTextColumn = 1
CivTextColumn = 2
End Enum
Private Type Civilization
Name As String
Leader As String
End Type
Private Options As Scripting.Dictionary
Public Sub Draw()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
Dim resultsRange As Range
Set resultsRange = GetResultsRange(ws)
resultsRange.ClearContents
Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")
Dim randCiv As String
Dim noOfPlayers As Integer
InitializeCivilizationDict
For noOfPlayers = 1 To GetPlayerNum(ws)
resultsRange.Cells(GetPlayerNameRow(ws, noOfPlayers), PlayerTextColumn).Value = GetPlayerName(noOfPlayers)
Dim noOfOptions As Integer
For noOfOptions = 1 To GetOptionsNum(ws)
Dim civ As Civilization
civ = GetRandomCivilization
resultsRange.Cells(GetCivNameRow(ws, noOfPlayers, noOfOptions), CivTextColumn).Value = FormatCivilizationCaption(civ.Name, civ.Leader)
Next noOfOptions
Next noOfPlayers
End Sub
Private Sub InitializeCivilizationDict()
Set Options = New Scripting.Dictionary
Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")
Dim item As ListRow
Dim i As Long
With CivilizationsTable.ListRows
For i = 1 To .Count
Options.Add .item(i).Range(ColumnIndex:=CivilizationName).Value, _
.item(i).Range(ColumnIndex:=CivilizationLeader).Value
Next i
End With
End Sub
Private Function GetRandomNum(ByVal max As Integer) As Integer
GetRandomNum = CInt(Int((max - 1) * Rnd()))
End Function
Private Function GetRandomCivilization() As Civilization
Dim randIndex As Integer
randIndex = GetRandomNum(Options.Count)
Dim result As Civilization
result.Name = Options.Keys(randIndex)
result.Leader = Options.Items(randIndex)
Options.Remove result.Name
GetRandomCivilization = result
End Function
Private Function FormatCivilizationCaption(ByVal civName As String, ByVal civLeader As String) As String
FormatCivilizationCaption = civLeader & " (" & civName & ")"
End Function
Private Function GetPlayerNum(ByVal ws As Worksheet)
GetPlayerNum = ws.Cells(3, 3).Value
End Function
Private Function GetOptionsNum(ByVal ws As Worksheet)
GetOptionsNum = ws.Cells(3, 7).Value
End Function
Private Function GetPlayerName(ByVal noOfPlayers As Integer) As String
GetPlayerName = "Player " & noOfPlayers
End Function
Private Function GetCivNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer, ByVal noOfOptions As Integer) As Integer
GetCivNameRow = (GetOptionsNum(ws) + 2) * (noOfPlayers - 1) + (noOfOptions + 3)
End Function
Private Function GetPlayerNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer) As Integer
GetPlayerNameRow = 3 + (GetOptionsNum(ws) + 2) * (noOfPlayers - 1)
End Function
Private Function GetResultsRange(ByVal ws As Worksheet) As Range
Set GetResultsRange = ws.Range("K1:L50")
End Function
``` |
30,613,119 | I was having 2 version of Appium.
One was installed on Windows/Program Files and Other version was .zip extract.
I was not able to start the Appium server and got below error -
```
error: Couldn't start Appium REST http interface listener. Requested port is already in use. Please make sure there's no other instance of Appium running already.
``` | 2015/06/03 | [
"https://Stackoverflow.com/questions/30613119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417546/"
] | Go to Appium(Android windows) setting change to any port number and start server again.
once server is started again change to original port. | appium -a 127.0.0.1 -p 4723
Here the port number is 4723. If the server is up in one port, you can try initializing the server in a different port.
Use the command
appium -a 127.0.0.1 -p (4724 or 4725 or any port number).
It will work |
23,952 | >
> [Genesis 5 (NIV)](http://www.biblegateway.com/passage/?search=Genesis%205)
>
>
> And **Adam** lived one hundred and thirty years, and begot a son in
> his own likeness, after his image, and named him Seth. After he begot
> Seth, the days of Adam were eight hundred years; and **he had sons and
> daughters**. So all the days that Adam lived were nine hundred and
> thirty years; and he died.
>
>
> **Seth** lived one hundred and five years, and begot Enosh. After he begot Enosh, Seth lived eight hundred and seven years, and **had sons
> and daughters**. So all the days of Seth were nine hundred and twelve
> years; and he died.
>
>
> **Enosh** lived ninety years, and begot Cainan. After he begot Cainan, Enosh lived eight hundred and fifteen years, and **had sons and
> daughters**. So all the days of Enosh were nine hundred and five
> years; and he died.
>
>
> **Cainan** lived seventy years, and begot Mahalalel. After he begot Mahalalel, Cainan lived eight hundred and forty years, and **had sons
> and daughters**. So all the days of Cainan were nine hundred and ten
> years; and he died.
>
>
> ......
>
>
>
Genesis 5 lists the genealogy of Adam as Adam, Seth, Enosh, Cainan, Mahalalel, Jared, Enoch, Methuselah, Lamech and Noah. Ten in all. Though each of these men had other sons and daughters, their names are not recorded.
Why are only ten names recorded and the rest are ignored?
Does this imply that these ten men were more important than others? | 2013/12/20 | [
"https://christianity.stackexchange.com/questions/23952",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/3889/"
] | **Noah's Lineage**
Noah was definitely a significant figure, as it was he and his family alone who survived the flood. The purpose appears to be to show Noah's lineage from Adam. Adding in brothers and sisters at each level would be a bit tangential to that purpose.
Enoch was certainly a man of note due to his close relationship with God.
**The Line of Cain**
Genesis 4 tells us about both Cain and Abel, who were indeed brothers of Seth. This chapter also gives us the line of Cain as follows:
Cain > Enoch > Irad > Mehujael > Methushael > Lamech.
Lamech's two wives were Adah and Zillah.
Adah bore Jabal and Jubal.
Zillah bore Tubal-cain and his sister Naamah.
So, we are actually given other names in the line of Cain in Genesis 4, even though both Cain and Lamech were murderers. The line of Noah does seem to be a more righteous line, to be sure.
**The Second Gospel**
There is another interesting idea that has been put forward, specifically that the meanings of the ten names in Noah's lineage have significance--sort of a Second Gospel:
```
Adam Man
Seth Appointed
Enosh Mortal
Kenan Sorrow
Mahalalel The Blessed God
Jared Shall come down
Enoch Teaching
Methuselah His death shall bring
Lamech The despairing
Noah Rest, or comfort
```
Put together, this could be as follows:
>
> Man *is* Appointed Mortal Sorrow. [The Blessed God] [shall come down], teaching. [His death shall bring] *to* [the despairing], [rest (or comfort)].
>
>
> | I was just searching for some infos and found your question, which isn't answered as it seems.
There are only 10 Names, because these are the names of the Firstborn.
Adam being the first king of the Earth, as appointed by the Creator, handed down his right to the "Throne of Elohim" (literally that's what the throne of King David is later called) from the first born to the first born.
First Born 01 = Adam
First Born 10 = Noah
First Born 20 = Abraham
First Born 21 = Isaac >>>> rejected 1st = Ismael >> Arab Nations
First Born 22 = Jakob / Israel >>>> rejected 1st = Esau >> covenant with Ismael
First Born 23 = Judah (Ruben, Simeon, Levi out because of sin) = House of Judah
First Born 24 = Ephraim = House of Israel, lost sheep, Genesis 48 + Romans 11:25
From Adam to Ephraim = 24 elders before the throne of God in Heaven (Revelation)
Second Adam = Elohim's Monogenes (the only begotten son) = Jesus / Jeshua
1 Corinthians 15 / Zacharia 4
Romans 4:1 Abraham is your father by the flesh
Romans 4:13 Abraham is the heir of the earth
Galatians 3:29 : If you are in Christ.. you ARE Abrahams seed (hebrew sera = Sarah = I'sera'el / greek sperma ) and heir.
John 11:54 Jesus therefore walked no more openly among the Jews; but went thence unto a country near to the wilderness, into a city called Ephraim, and there continued with his disciples. |
36,585,575 | Let's say I have this array:
```
let reportStructure = [|(2, 1); (3, 2); (4, 2); (5, 3); (6, 4); (7, 3)|]
```
where the first `int` in a tuple reports to the second `int`.
I can map that really easily with
```
let orgMap = Map.ofArray reporting
```
From there, I could easily get a list of all the ints that report to 2 with
```
orgMap
|> Map.filter (fun _ key -> key = 2)
```
which returns
```
map [(3, 2); (4, 2)]
```
What I'd really like to see, however, is the entire structure, from 2 all the way down. For example, I'd like to find a way that could give me the sample output
```
map [(3, 2); (4, 2); (5, 3); (6, 4); (7, 3)]
```
if I'm looking for person 2 or
```
map [(5, 3); (7, 3)]
```
if I'm interested in person 3.
Can I do this? If so, how? Is there another structure other than a `map` that would be a better way to make this happen?
Thanks in advance for your help. | 2016/04/12 | [
"https://Stackoverflow.com/questions/36585575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4351030/"
] | Since OCaml is close to F# and trying to find Topological sort in F# was not turning up anything useful I looked for OCaml code.
I found [An Introduction to Objective Caml](http://www.cs.columbia.edu/~sedwards/classes/2011/w4115-fall/ocaml.pdf) which had a solution to your problem using Depth First Search and used it as the basis for this answer. Also because you are new to F# you can review the document and see how the code is derived. Oddly I took a look at the remainder of the document after posting this and he has a more advanced version of DFS latter in the document.
Your input is an array `[| |]` but your answer is a list `[]` so I did most of the work as list.
The answers are not in the same order as you had, but they are in the same format.
```
let reportStructure = [|(2, 1); (3, 2); (4, 2); (5, 3); (6, 4); (7, 3)|]
//
// 6 -> 4 -> 2
// 5 -> 3 -> 2 -> 1
// 7 -> 3
// val revStructure : tl:('a * 'b) list -> ('b * 'a) list
let revStructure tl = List.map (fun (a,b) -> (b,a)) tl
// val mem : item:'a -> list:'a list -> bool when 'a : equality
let mem item list = List.exists (fun x -> x = item) list
// val successors : n:'a -> edges:('a * 'b) list -> 'b list when 'a : equality
let successors n edges =
let matching (s,_) = s = n
List.map snd (List.filter matching edges)
// val dist : pred:'a -> succs:'b list -> ('a * 'b) list
let dist pred succs = List.map (fun y -> (pred,y)) succs
// val dfsPairs : edges:('a * 'a) list -> start:'a -> ('a * 'a) list when 'a : equality
let dfsPairs edges start =
let rec dfsPairsInner edges visited start result =
match start with
| [] -> List.rev (revStructure result)
| n::nodes ->
if mem n visited then
dfsPairsInner edges visited nodes result
else
let predecessors = dist n (successors n edges)
let result =
match predecessors with
| [] -> result
| _ -> predecessors @ result
dfsPairsInner edges (n::visited) ((successors n edges) @ nodes) result
dfsPairsInner edges [] [start] []
let revEdges = revStructure (List.ofArray reportStructure)
let result = dfsPairs revEdges 2
// val result : (int * int) list = [(4, 2); (3, 2); (7, 3); (5, 3); (6, 4)]
let result = dfsPairs revEdges 3
// val result : (int * int) list = [(7, 3); (5, 3)]
``` | I like f# puzzles, so I took a stab at this one. I hope that you enjoy.
```
let orgList = [(2, 1); (3, 2); (4, 2); (5, 3); (6, 4); (7, 3)]
let orgMap =
orgList
|> List.fold (fun acc item ->
let key = snd item
match Map.tryFind key acc with
| Some(value) ->
let map' = Map.remove key acc
Map.add(key) (item::value) map'
| None ->
Map.add(key) (item::[]) acc
) Map.empty<int, (int*int) list>
let findReports supervisor =
let rec findReports' acc collection =
match collection with
| head::tail ->
(findReports' (head::acc) tail)
@ match Map.tryFind (fst head) orgMap with
| Some(value) -> (findReports' [] value)
| None -> []
| [] -> acc
findReports' [] (Map.find supervisor orgMap)
findReports 2
|> List.map fst
|> List.distinct
```
returns
```
val it : int list = [3; 4; 5; 7; 6]
```
`findReports 2` returns
```
val it : (int * int) list = [(3, 2); (4, 2); (5, 3); (7, 3); (6, 4)]
```
---
I'll break it down to clarify.
```
let orgList = [ (1, 2); (1, 3); (1, 4); (2, 5); (3, 6); (4, 5); (5, 6); (5, 7) ]
```
We take your list of tuples and create a functional map of boss to ((report,boss) list). This might be known as an adjacency list, which is used for traversing graphs.
```
let orgMap =
orgList
|> List.fold (fun acc item ->
let key = snd item
match Map.tryFind key acc with
```
If there is a list of reports under a boss, add to that list.
```
| Some(reports) ->
let map' = Map.remove key acc
Map.add(key) (item::reports) map'
```
Otherwise, add to an empty list and insert into the dictionary.
```
| None ->
Map.add(key) (item::[]) acc
```
Start with an empty map as an accumulator.
```
) Map.empty<int, (int*int) list>
```
Recurse through the items to find all reports.
```
let findReports supervisor =
let rec findReports' acc collection =
match collection with
```
If there is an item, append it to the accumulator. This is BFS. If you switch the expression before and after the concatenate operator (@), it will become DFS.
```
| head::tail ->
(findReports' (head::acc) tail)
```
Concatenate the current list to the recursive list of reports to reports.
```
@ match Map.tryFind (fst head) orgMap with
| Some(value) -> (findReports' [] value)
| None -> []
```
If at the end of the list, return the list.
```
| [] -> acc
```
Run the recursive function.
```
findReports' [] (Map.find supervisor orgMap)
```
Run the function.
```
findReports 7
```
Return only the reports
```
|> List.map fst
```
Don't report the report twice.
```
|> List.distinct
``` |
4,061 | Who knows one hundred thirty?
-----------------------------
*Please cite/link your sources, if possible. At some point at least twenty-four hours from now, I will:*
* *Upvote all interesting answers.*
* *Accept the best answer.*
* *Go on to the next number.* | 2010/11/21 | [
"https://judaism.stackexchange.com/questions/4061",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/2/"
] | The weight in silver of each plate brought by the nesiim at the chanukas hamishkan | Number of words in *בריך שמיה* (Sort of Tikun for the 130 of Adam) |
52,428,939 | **Only TF native optimizers are supported in Eager mode**
I'm getting this error with every optimiser I have tried in the following:
```
def create_model():
model = tf.keras.models.Sequential([tf.keras.layers.Dense(512,activation=tf.nn.relu, input_shape=(784,)), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ])
opt = tf.train.GradientDescentOptimizer
model.compile(optimizer = opt,
loss=tf.keras.losses.sparse_categorical_crossentropy, metrics= ['accuracy'])
return model
```
So my question is, what is a 'TF native optimizer' please?
Thanks. | 2018/09/20 | [
"https://Stackoverflow.com/questions/52428939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9061457/"
] | This error occur to me when send Date object (for example timestamp in firebse) to React child components.
If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.
You must send that date as string value
```
<p>{timestamp.toString()}</p>
```
should work fine like this. | Had the same error but with a different scenario.
I had my state as
```
this.state = {
date: new Date()
}
```
so when I was asking it in my Class Component I had
```
p>Date = {this.state.date}</p>
```
Instead of
```
p>Date = {this.state.date.toLocaleDateString()}</p>
``` |
1,236,986 | i have code like :
```
<% if @photos.blank? %>
No Pic
<% else %>
<center>
<table>
<tr>
<% @photos.each do |c| %>
<td>
<%= image_tag(url_for({:action => 'image', :id => c.id}),:width =>'20%', :height =>'20%' ) %><br>
<%= link_to "lihat" , {:action => 'show2', :id => c.id} -%>
<% if logged_in? %>
<small> <%= link_to 'Edit', {:action => "edit2", :id => c.id } %></small>
<small> <%= link_to 'Delete', {:action => "delete2", :id => c.id }, :confirm => "apakah anda yakin mau mengapus berita ini?" %></small>
<% end %>
</td>
<% end %>
</tr>
</table>
</center>
<% end %>
```
i want to print my images "if column = 5 " automaticly add
or 5 image per row
output:
[image][image][image][image][image]
what should i do with my code?? please help me | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148641/"
] | There are a couple of ways you could solve the "5 photos on a row" problem, but I think that this is the most expressive: `group` the array of photos into rows of 5 and use nested `.each` loops:
```
rows = @photos.in_groups_of(5)
rows.each do |row|
<tr>
row.each do |photo|
<td>
#display photo here
</td>
end
</tr>
end
```
Be aware that if you don't have 5 photos on your final row, `array#in_groups_of` will pad it with `nil` unless you specify an alternative default. | It looks as though you've run into the problem I mentioned in my original answer:
"Be aware that if you don't have 5 photos on your final row, `array#in_groups_of` will pad it with `nil` unless you specify an alternative default."
Try this:
```
<tr>
<% row.each do |photo| %>
<td>
<% if photo %>
<%= image_tag(url_for({:action => 'image', :id => photo.id}),:width => '10%',:height => '10%' ) %>
<% end %>
</td>
<% end %>
</tr>
``` |
29,086,872 | Hi I have 3 circles in android that show progress, are a custom element (ViewProgressbar) that inherit from relative layout.
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<com.theproject.ui.view.ViewProgressbar
android:id="@+id/vps_history_progress1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:value= "@string/zero"
app:subject = "@string/txt_progress1"
/>
<com.theproject.ui.view.ViewProgressbar
android:id="@+id/vps_history_progress2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:value= "@string/zero"
app:subject = "@string/txt_progress2"
/>
<com.theproject.ui.view.ViewProgressbar
android:id="@+id/vps_history_progress3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:value= "@string/zero"
app:subject = "@string/txt_progress3"
/>
</LinearLayout>
```
The problem I am facing is that in devices with small screen the thrid circle is smaller than the others. I think is related that I am using wrap\_content. Is there a way to force the three circles have the same size?
thank you | 2015/03/16 | [
"https://Stackoverflow.com/questions/29086872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2853555/"
] | I'm not sure I have heard of "good practices" as far as scraping goes but you may be able to find some in the book [PHP Architect's Guide to Web Scraping with PHP](http://www.phparch.com/books/phparchitects-guide-to-web-scraping-with-php/).
These are some guidelines I have used in my own projects:
1. Scraping is a slow process, consider delegating that task to a background process.
2. Background process normally run as a cron job that executing a CLI application or a worker that is constantly running.
3. Use a process control system to manage your workers. Take a look at [supervisord](http://supervisord.org/)
4. Save every scraped file (the "raw" version), and log every error. This will enable you to detect problems. Use Rackspace Cloud Files or AWS S3 to archive these files.
5. Use the [Symfony2 Console tool](http://symfony.com/doc/current/components/console/introduction.html) to create the commands to run your scraper. You can save the commands in your bundle under the Command directory.
6. Run your Symfony2 commands using the following flags to prevent running out of memory: `php app/console scraper:run example.com --env=prod --no-debug` Where app/console is where the Symfony2 console applicaiton lives, scraper:run is the name of your command, example.com is an argument to indicate the page you want to scrape, and the --env=prod --no-debug are the flags you should use to run in production. see code below for example.
7. Inject the Goutte Client into your command like such:
Ontf/ScraperBundle/Resources/services.yml
```
services:
goutte_client:
class: Goutte\Client
scraperCommand:
class: Ontf\ScraperBundle\Command\ScraperCommand
arguments: ["@goutte_client"]
tags:
- { name: console.command }
```
And your command should look something like this:
```
<?php
// Ontf/ScraperBundle/Command/ScraperCommand.php
namespace Ontf\ScraperBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Goutte\Client;
abstract class ScraperCommand extends Command
{
private $client;
public function __construct(Client $client)
{
$this->client = $client;
parent::__construct();
}
protected function configure()
{
->setName('scraper:run')
->setDescription('Run Goutte Scraper.')
->addArgument(
'url',
InputArgument::REQUIRED,
'URL you want to scrape.'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$url = $input->getArgument('url');
$crawler = $this->client->request('GET', $url);
echo $crawler->text();
}
}
``` | You Should take a Symfony-Controller if you want to return a response, e.G a html output.
if you only need the function for calculating or storing stuff in database,
You should create a [Service](http://symfony.com/doc/current/book/service_container.html) class that represents the functionality of your Crawler, e.G
```
class CrawlerService
{
function getText($url){
$client = new Client();
$crawler = $client->request('GET', $url);
return $crawler->text();
}
```
and to execute it i would use a [Console Command](http://symfony.com/doc/current/cookbook/console/console_command.html)
If you want to return a Response use a Controller |
51,188,026 | I try to delete attribute "disabled" in my input area or if I choose another radio button, will add "disabled" in my input. This code doesn't right work:
```js
var radio_3 = document.getElementById("Radio3");
var input_long = document.getElementById("inputLong");
radio_3.addEventListener("change", function() {
if (radio_3.checked) {
input_long.removeAttribute("disabled");
} else {
input_long.setAttribute("disabled");
}
})
```
```html
<div class="form-group col-md-6">
<label for="inputLong">Предпочтительная для Вас длительность конференции?</label>
<div class="custom-control custom-radio">
<input type="radio" id="Radio1" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio1">1 день</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio2" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio2">2 дня</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio3" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio3">Другое</label>
</div>
<input type="text" class="form-control mt-1" id="inputLong" placeholder="" disabled>
</div>
``` | 2018/07/05 | [
"https://Stackoverflow.com/questions/51188026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10005778/"
] | The `change` listener is only on `radio_1` (or, the `#radio_3` `input`) - the listener runs when the radio button is selected, but *not* when some *other* radio button is selected. Add a listener to *each* radio button instead:
```js
var input_long = document.getElementById("inputLong");
const listener = (e) => {
input_long.disabled = e.target.id === 'Radio3'
? false
: true;
};
document.querySelectorAll('input[name="how_long"]').forEach(input => {
input.addEventListener("change", listener);
});
```
```html
<div class="form-group col-md-6">
<label for="inputLong">Предпочтительная для Вас длительность конференции?</label>
<div class="custom-control custom-radio">
<input type="radio" id="Radio1" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio1">1 день</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio2" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio2">2 дня</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio3" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio3">Другое</label>
</div>
<input type="text" class="form-control mt-1" id="inputLong" placeholder="" disabled>
</div>
``` | The change event doesn't trigger when you click on radio 1 and 2. So you would need to register event handlers separately for them.
In the snippet below, I have declared the event handler separately, and bound it to the radio buttons through separate calls to `addEventListener`.
```js
var radio_1 = document.getElementById("Radio1");
var radio_2 = document.getElementById("Radio2");
var radio_3 = document.getElementById("Radio3");
var input_long = document.getElementById("inputLong");
var eventHandler = function() {
if (radio_3.checked) {
input_long.removeAttribute("disabled");
} else {
input_long.setAttribute("disabled", "disabled");
}
};
radio_1.addEventListener("change", eventHandler);
radio_2.addEventListener("change", eventHandler);
radio_3.addEventListener("change", eventHandler);
```
```html
<div class="form-group col-md-6">
<label for="inputLong">Предпочтительная для Вас длительность конференции?</label>
<div class="custom-control custom-radio">
<input type="radio" id="Radio1" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio1">1 день</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio2" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio2">2 дня</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="Radio3" name="how_long" class="custom-control-input">
<label class="custom-control-label" for="Radio3">Другое</label>
</div>
<input type="text" class="form-control mt-1" id="inputLong" placeholder="" disabled>
</div>
```
---
There are ways to simplify the event registration part, such as listening for events on a containing element, and react accordingly. But I have tried to keep it simpler in the snippet above. You can read the following question about event bubbling if you're interested in such an approach: [What is event bubbling and capturing?](https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing#4616720) |
31,921,893 | I have subclassed a button such that I can get basically a button with rounded edges and an icon on the right side.
Nearly got it right, only issue is that the icon is not centered vertically and cannot seem to figure out how I can influence the vertical alignment.
The original image is rectangular and I am using CreateResizableImage with a pre-defined UIEdgeInsets struct as below but what I am seeing is:
[](https://i.stack.imgur.com/imNRi.png)
MY subclass code is:
```
partial class CustomGreyButton : UIButton
{
public CustomGreyButton (IntPtr handle) : base (handle)
{
this.Layer.BorderColor = new CoreGraphics.CGColor (0, 0, 0);
this.Layer.BorderWidth = 1;
this.Layer.CornerRadius = 20;
// top, left, bottom, right
UIEdgeInsets btnEdgeInsets = new UIEdgeInsets (0,44,0,44);
UIImage stretchingButtonImage = new UIImage ("ios_images/grey_btn.png").CreateResizableImage (btnEdgeInsets);
this.SetBackgroundImage (stretchingButtonImage, UIControlState.Normal);
this.SetBackgroundImage (stretchingButtonImage, UIControlState.Selected);
this.SetBackgroundImage (stretchingButtonImage, UIControlState.Highlighted);
this.ClipsToBounds = true;
this.AdjustsImageWhenHighlighted = false;
//this.TitleColor = UIColor.White;
this.SetTitleColor (UIColor.White, UIControlState.Normal);
this.SetTitleColor (UIColor.Black, UIControlState.Highlighted);
this.SetTitleColor (UIColor.Black, UIControlState.Selected);
}
}
``` | 2015/08/10 | [
"https://Stackoverflow.com/questions/31921893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1209947/"
] | The most important thing here is primitives are way way cheaper than object wrappers, in both time and memory complexities.
The pooling feature only becomes relevant if you have to use these primitives in contexts where Object references have to be used (i.e. they have to be wrapped/"boxed" into their object wrappers, google auto-boxing). If you can use them as primitive numbers all the time then it is the most efficient way.
Details:
The Java language treats primitives types (boolean, byte, char, short, int, long, float, double) differently from all other types (which are reference types). The primitives can directly exist on the stack and can be directly manipulated by JVM instructions (there're sets of instructions for each of the primitives). Numerical constants are often directly embeded into JVM instructions, which means no additional memory read is needed to execute these instructions. This structure maps more or less directly to native code on all hardware.
The reference types on the other hand cannot exist on the stack and must be allocated on the heap (this is a Java language design choice). This means each time you use them, instructions has to be added to find the instance, read meta data, invoke a method or get a field before any real operation on the data can be performed.
For example, say you have the function
```
int add(int a, int b) { return a + b; }
```
The body of the function (apart from calling convention) will be simply `iadd`, which translates to 1 instruction on most CPUs.
If you change the `int`s into `Integers`s, the byte code becomes:
```
0: aload_1
1: invokevirtual #16 // Method java/lang/Integer.intValue:()I
4: aload_2
5: invokevirtual #16 // Method java/lang/Integer.intValue:()I
8: iadd
9: invokestatic #22 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
```
which translates to multiple internal function calls and thousands of native instructions.
Random notes:
IIRC, the Java language spec did not define how many bytes will be used to store `short`, `boolean`, etc. The JVM implementation may use more bytes so it aligns everything with the word length of the CPU. It is not unusual to see a boolean stored as a byte or a 32-bit int purely for efficiency purposes. It did say however, that the result of operations on types shorter than `int` all comes out as `int`.
All of these means `short` doesn't really give you any memory savings unless you have very large `short` arrays (which has to be packed without gap in memory).
And if you really, really want to use a pool of `Short`s (the wrapper), the most efficient implementation is an array of size 65536. Here you exchange 4k/8k of memory for very efficient lookups. | I am not quite sure why you need `Short`. Anyways, as a thumb rule always remember that *primitives are always faster and cheaper when compared to their wrappers*. They aren't objects so many JIT optimizations can result in really fast code. Also, Wrappers don't contain cache for all possible values - for example `Integer` has (by default) a cache for -128 to 127. You can extend it, but thats not the point.
If you need to push shorts into a collection, then probably using a cache makes sense (Wrappers already have cache between -128 to 127). Yet, if you want to push millions of numbers, then not using a cache makes more sense. |
6,742,686 | Consider the following example: ([live demo here](http://jsfiddle.net/jESsA/))
HTML:
```
<div id="outer_wrapper">
<div class="wrapper">
<a><img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg" /></a>
</div>
<div class="wrapper">
<a><img src="http://assets.test.myyearbook.com/pimp_images/home_page/icon_smiley.gif" /></a>
</div>
<div class="wrapper">
<a><img src="http://thumbs3.ebaystatic.com/m/mvHqVR-GDRQ2AzadtgupdgQ/80.jpg" /></a>
</div>
<div class="wrapper">
<a><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/718smiley.png/60px-718smiley.png" /></a>
</div>
</div>
```
CSS:
```
#outer_wrapper {
background-color: #bbb;
width: 350px;
}
.wrapper {
display: inline-block;
border: 1px solid black;
width: 90px;
height: 100px;
text-align: center;
margin-right: 20px;
}
a {
display: inline-block;
width: 80px;
height: 80px;
border: 1px solid red;
}
```
The output is:

1. Why the black `wrapper`s are not vertically aligned ? How could I fix that ?
2. The images are horizontally centered in the red boxes. How could I vertically center them ?
Please do not change the HTML, if possible. | 2011/07/19 | [
"https://Stackoverflow.com/questions/6742686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | You can try assigning a `vertical-align` attribute on the `img` tag. Vertical align is relative to the line box which means you need to set the line box as tall as the height of the `a` tag. So these changes are needed in your CSS markup:
```
#outer_wrapper {
overflow: hidden; /* required when you float everything inside it */
}
.wrapper {
/* display: inline-block is not required */
/* text-align: center is not required -- see below */
float: left; /* float all wrappers left */
}
a {
display: block; /* block display required to make width and height behave as expected */
margin-left: 4px; /* shift the block to make it horizontally centered */
margin-top: 9px; /* shift the block to make it vertically centered */
text-align: center; /* center inline content horizontally */
line-height: 80px; /* line height must be set for next item to work */
}
img {
vertical-align: middle; /* presto */
}
```
[Demo here](http://jsfiddle.net/salman/xMV4R/). | You could check this out: <http://www.brunildo.org/test/img_center.html> |
8,556 | >
> The Lord sent fiery serpents among the people and they bit the people, so that many people of Israel died. So the people came to Moses and said, “We have sinned, because we have spoken against the Lord and you; intercede with the Lord, that He may remove the serpents from us.” And Moses interceded for the people. Then the Lord said to Moses, “Make a fiery serpent, and set it on a standard; and it shall come about, that everyone who is bitten, when he looks at it, he will live.” **And Moses made a bronze serpent and set it on the standard; and it came about, that if a serpent bit any man, when he looked to the bronze serpent, he lived.** [**(Numbers 21:6-9)**](http://www.biblegateway.com/passage/?search=Numbers%2021:6-9&version=NASB)
>
>
>
Someone recently told me that this was symbolic, and that the serpent is a symbol for sin, and that this was foreshadowing Jesus becoming sin for us and being lifted up and crucified so that we would live.
My question is, how do we know that this is the right interpretation, and not just an interesting idea that someone had? | 2012/07/18 | [
"https://christianity.stackexchange.com/questions/8556",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1671/"
] | From John 3:14 we know it was a foreshadowing of Christ, but I think the desire for absolute certainty concerning any foreshadowing image or shadow of Messiah party misunderstands the concept of a shadow. A shadow is by definition an obscure and fuzzy outline of a real object. This is why we will find invariably numerous perspectives on any given shadow. With Christ having been revealed we can cheat a bit and take the answer back to the clue but this does not always give us absolute clarity on the circumference on the shadow.
Specifically, your question contains a great answer because Christ was made sin for us. Another answer given that a serpent represents punishment is also good, for Christ was punished for us. From my own preference I would just say that the serpent represents the curse of sin brought on by the Devil, as Christ bore the curse of sin, hell, death, punishment, etc. He was like a brass snake held up to heal us of the 'curse'. Yet I may find that I still prefer how someone else phrases it, further confirming the situation. We are all speaking about the same fuzzy shadow of Christ's work on the cross. There is no perfect magic wording to describe what is a little unclear but many good answers approximate the cast shape. | Moses had to make the image of the fiery snake in bronze and put it on a standard and raise it up. My thoughts from the chapter in John are that the standard was possibly in the shape of a cross with the snake draped over it. The snake represents both Jesus the Christ and the sin he has taken on himself for us.
When we look to the Christ on the cross we are saved from sin and death just as those who were in the wilderness, looked at the image Moses had raised on the standard and were themselves saved from death for their sins. |
23,713 | I have time series $R$, which shows, how `something` changes at the regional level.
I have several time series $U\_i$, which show, how `something` changes at a special unit $I$ level.
There are many units in the region. $R$ has no missing data. Different $U\_i$ have their own missing periods.
**I want to** forecast $U$ after a missing period using information of $R$ and information of $U$ when it was availible.
**My thoghts till now**:
Suppose $R$ is known on interval $[0, 365]$. Suppose $U\_i$ is known on interval $[0,300]$. Let's take $R$ and $U\_i$ both on interval $[0,300]$, take difference between them and trying to predict that difference with linear regression. So for interval $[301,365]$, I will have differences and to restore $U\_i$, I will just have to take out my differences from $R$.
**I don't like my solution**, because:
1. We need a model for each $U\_i$.
2. Because, sometimes data is more sparse and I don't even have a $[0,300]$ known interval, so not able to train regression properly. | 2017/10/12 | [
"https://datascience.stackexchange.com/questions/23713",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/29931/"
] | Not a fully complete answer, but some inputs.
1. Your time series are correlated.
2. I assume that the measure you want to forecast for a region is an aggregation of units forecasts.
To address the first point, I usually use Vector Autoregressive Model (VAR) that forecast all time-series at once (each one being expressed as a regression using the others)
The second point involves the concept of hierarchical forecasting and reconciliation. You can exploit the fact that the regional forecast should/must equal the unit- forecasts. There can be a process to adjust forecasts to take that into account.
There are both packages for VaR and hierarchical reconciliation in R but as far as I know no direct code to handle both at the same time...
You may find this paper providing some details on the proposed approach:
<https://mpra.ub.uni-muenchen.de/76556/1/MPRA_paper_76556.pdf> | Just a thought:
Why wouldn't you do the training on the difference data for 1-250 and test using 251-300 to see if the underlying pattern actually is accurate. If that was the case, you can generalize from 1-300 to 301-365. |
32,112,820 | I have the following SQLDataSource:
```
<asp:SqlDataSource runat="server" ID="MySqlDataSource" ConnectionString='<%$ ConnectionStrings:RmaReportingConnectionString %>'
SelectCommand="SELECT DISTINCT [Team] FROM [Locations] WHERE ([Team] IN (@Teams))">
<SelectParameters>
<asp:Parameter Name="Teams" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
```
In code behind calling it like this:
```
MySqlDataSource.SelectParameters["Teams"].DefaultValue = "'Team 1','Team 2'";
MySqlDataSource.DataBind();
```
The issue is that I am not getting any results and I have a feeling it is due to syntax because if I run the raw SQL without the Parameter it works fine. | 2015/08/20 | [
"https://Stackoverflow.com/questions/32112820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1315427/"
] | For variable height cells you need to implement tableView:heightForRowAtIndexPath: | `UITableView` has delegate method to set that, i.e. `tableView:heightForRowAtIndexPath:`..
If you ask for logical answer, I would say... Display you table as it is on view load.. take a flag which will check for button clicked in `tableView:heightForRowAtIndexPath:` .. keep it to 0 on `viewDidLoad` and load table. change it on button click to 1 and reload table.
```
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (buttonClickedFlag == YES) {
return newHeight;
} else {
return regularHeight;
}
}
``` |
5,208,038 | Let's say I'm given a `void*` memory address and I need to print the bits located in this memory address. How can I do this?
In my processor memory addresses are 32bits as are memory values, also int are 32 bits.
So I thought of doing this:
```
unsigned int value = *memory_address;
```
and then by simple arithmetic (some `mod` and `div` operations) to get the bits of the value saved in `memory_address`.
For example `value mod 2` will give last bit of this value and so on. But from what I can tell (I was expecting different bits) it doesn't work. Any ideas why?
Also, is anyone aware of ready C source code that "does" such this, reads/writes bits from memory? | 2011/03/06 | [
"https://Stackoverflow.com/questions/5208038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646544/"
] | ```
int main() {
int a = 0xFFFF;
void * v = &a; // v points to a
int * aPtr = (int *) v; // aPtr also points to a
int b = *aPtr; // b gets the value aPtr points to, aka a or 0xFFFF
int aBit = (b >> 3) & 1; // aBit now contains bit 3 of the original a value
// toggle the bit
if (aBit) {
b &= ~(1 << 3); // set bit 3 to 0
} else {
b |= (1 << 3); // set bit 3 to 1
}
*aPtr = b; // update original a
}
``` | How about:
```
bool isBit4Set = ((*someAddress) & 0x8 != 0);
(*someAddress) |= 0x8; // Set bit 4
``` |
1,214,876 | This is probably a C++ 101 question: I'm curious what the guidelines are for using `size_t` and `offset_t`, e.g. what situations they are intended for, what situations they are not intended for, etc. I haven't done a lot of portable programming, so I have typically just used something like `int` or `unsigned int` for array sizes, indexes, and the like. However, I gather it's preferable to use some of these more standard typedefs when possible, so I'd like to know how to do that properly.
As a follow-up question, for development on Windows using Visual Studio 2008, where should I look to find the actual typedefs? I've found `size_t` defined in a number of headers within the VS installation directory, so I'm not sure which of those I should use, and I can't find `offset_t` anywhere. | 2009/07/31 | [
"https://Stackoverflow.com/questions/1214876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18529/"
] | `offset_t` isn't mentioned at all in my copy of the C++ standard.
`size_t` on the other hand, is meant simply to denote object or array sizes. A `size_t` is guaranteed to be big enough to store the size of any in-memory object, so it should be used for that. | Dragging an old one back up... offset\_t (which is a long long) is used by Solaris' llseek() system call, and is to be used anywhere you're likely to run into real 64-bit file offsets... meaning you're working with really **huge** files. |
9,633,201 | Can any body tell me what is error in the following paypal ipn response
`Failed
Response = HTTP/1.1 200 OK Date: Fri, 09 Mar 2012 10:47:38 GMT Server: Apache X-Frame-Options: SAMEORIGIN Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=HsLFg9XOmQSJyuFKrL6PkJjTED9fh4Zde3UysJ1YnQ1xmilNeg-Y_zLU2wud8XLDahMpf5S7P120pyejIXzBLm%7chW7sdV0qGBjVkzRfcV539j-CN30UarIFBdY8vcVDymTOAxGTgqxzsM2Bz0ulxMIf5UFURW%7c1331290058; domain=.paypal.com; path=/; HttpOnly Set-Cookie: cookie_check=yes; expires=Mon, 07-Mar-2022 10:47:38 GMT; domain=.paypal.com; path=/; HttpOnly Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; HttpOnly Set-Cookie: navlns=0.0; expires=Thu, 04-Mar-2032 10:47:38 GMT; domain=.paypal.com; path=/; HttpOnly Vary: Accept-Encoding Connection: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 7 INVALID 0`?? | 2012/03/09 | [
"https://Stackoverflow.com/questions/9633201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1138131/"
] | [The IPN response of INVALID means that you have not provided the ***EXACT*** data, to the server the IPN was sent from, as what was sent to you by that server.](https://www.x.com/developers/community/blogs/ppmtsrobertg/securing-your-instant-payment-notification-ipn-script) | I had the same problem. My problem was: I sent a call from the Sandbox Instant Payment Notification (IPN) simulator to my real account. It always came back as `INVALID`. After trying to send it to the sandbox server, it worked!
I think paypal works like this is for security reason. I hope my thing works when all credentials are live. |
54,830,384 | In Laravel 5.7 I am using form request validation:
```
public function rules()
{
return [
'age' => 'integer',
'title' => 'string|max:50'
];
}
```
If I submit a request to my API with this payload:
```
{
"age": 24,
"title": ""
}
```
Laravel returns the error:
```
{
"message": "The given data was invalid.",
"errors": {
"title": [
"The title must be a string."
]
}
}
```
I would expect it to pass the validation, since the title is a string, albeit an empty one. How should the validation be formulated to allow empty strings? | 2019/02/22 | [
"https://Stackoverflow.com/questions/54830384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519497/"
] | You would need `nullable` to allow an empty string
```
public function rules()
{
return [
'age' => 'integer',
'title' => 'nullable|string|max:50'
];
}
``` | The accepted answer does not fix the issue when you have this rule:
```php
return [
"title" => "sometimes|string",
];
```
In this case, you need to specifiy the string is actually "nullable" (even if the `ConvertEmptyStringsToNull` middleware is active, tested on Laravel 8.77.1)
So this one will allow to pass an empty string on the "title" key:
```php
return [
"title" => "sometimes|string|nullable",
];
``` |
4,221,712 | I'm searching a space of vectors of length 12, with entries 0, 1, 2. For example, one such vector is
001122001122. I have about a thousand good vectors, and about a thousand bad vectors. For each bad vector I need to locate the closest good vector. Distance between two vectors is just the number of coordinates which don't match. The good vectors aren't particularly nicely arranged, and the reason they're "good" doesn't seem to be helpful here. My main priority is that the algorithm be fast.
If I do a simple exhaustive search, I have to calculate about 1000\*1000 distances. That seems pretty thick-headed.
If I apply Dijkstra's algorithm first using the good vectors, I can calculate the closest vector and minimal distance for every vector in the space, so that each bad vector requires a simple lookup. But the space has 3^12 = 531,441 vectors in it, so the precomputation is half a million distance computations. Not much savings.
Can you help me think of a better way?
Edit: Since people asked earnestly what makes them "good": Each vector represents a description of a hexagonal picture of six equilateral triangles, which is the 2D image of a 3D arrangement of cubes (think generalized Q-bert). The equilateral triangles are halves of faces of cubes (45-45-90), tilted into perspective. Six of the coordinates describe the nature of the triangle (perceived floor, left wall, right wall), and six coordinates describe the nature of the edges (perceived continuity, two kinds of perceived discontinuity). The 1000 good vectors are those that represent hexagons that can be witnessed when seeing cubes-in-perspective. The reason for the search is to apply local corrections to a hex map full of triangles... | 2010/11/19 | [
"https://Stackoverflow.com/questions/4221712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371435/"
] | 3^12 isn't a very large search space. If speed is essential and generality of the algorithm is not, you could just map each vector to an int in the range 0..531440 and use it as an index into a precomputed table of "nearest good vectors".
If you gave each entry in that table a 32-bit word (which is more than enough), you'd be looking at about 2 MB for the table, in exchange for pretty much instantaneous "calculation".
edit: this is not much different from the precomputation the question suggests, but my point is just that depending on the application, there's not necessarily any problem with doing it that way, especially if you do all the precalculations before the application even runs. | Assuming a packed representation for the vectors, one distance computation (comparing one good vector and one bad vector to yield the distance) can be completed in roughly 20 clock cycles or less. Hence a million such distance calculations can be done in 20 million cycles or (assuming a 2GHz cpu) 0.01 sec. Do these numbers help?
PS:- 20 cycles is a conservative overestimate. |
4,878,932 | For example
```
input{margin:0}body{margin:0;background:white}
```
would be shorter written like this
```
input,body{margin:0}body{background:white}
```
or this
```
input,body{margin:0}body{margin:0;padding:0}
```
would be shorter written like this
```
input,body{margin:0}body{padding:0}
```
**Conclusion** no such tool See the accepted answer.
**A tip to the tool writers**, you **may** want to consider gzip. Sometimes, leaving a few bytes on a second-rate optimization will be shorter in the end because gzip is essentially byte-level deduplication. If there are two identical sections, gzip will reference the earlier one. **Ideally** this would be considered in deciding if certain optimizations should be skipped some or all of the time, and what the order of the selectors and rules should be. | 2011/02/02 | [
"https://Stackoverflow.com/questions/4878932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463304/"
] | If you use visual studio, you could install the [Web Essentials](http://visualstudiogallery.msdn.microsoft.com/6ed4c78f-a23e-49ad-b5fd-369af0c2107f) extension. It has
experimental support for cleaning and merging CSS rules, but not exactly like you subscribed.
It, for one, creates more whitespace, but it does combine css tags, that have (partially) equal styles eg.. | May be the wrong thing, but h[ttp://www.cleancss.com/](http://www.cleancss.com/)? |
12,296,421 | According to [here](http://api.jquery.com/remove/), jquery's remove function should work like so..
```
$('div').remove('selector');
```
Which I'm trying [in this example](http://jsfiddle.net/qwXSw/).
*HTML:*
```
<div class="wrapper">
<p class="unwanted">This should be removed</p>
<p class="retained">This will remain</p>
</div>
```
*JavaScript:*
```
jQuery(document).ready(function($) {
$('div').remove('p.unwanted'); //not working
//$('p.unwanted').remove(); //this works
});
```
It's not working. What am I doing wrong? | 2012/09/06 | [
"https://Stackoverflow.com/questions/12296421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597264/"
] | You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.
If you have this HTML:
```
<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>
```
and then executed this jQuery:
```
$('div').remove('.unwanted');
```
then it would only remove that third `<div>` (the one with the `unwanted` class on it), because it first selects *all* `<div>` elements, and then only removes those that match the selector.
[Example jsFiddle](http://jsfiddle.net/8kmww/) | try this
```
$(document).ready(function() {
$('div').find('p.unwanted').attr('class', '');
});
``` |
149,954 | Is there a way to level up unarmed combat (punching)?
I found a perk but I want to get better and level up! | 2014/01/08 | [
"https://gaming.stackexchange.com/questions/149954",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/65788/"
] | Go to riften and start the thieves guild stuff by working with the guy named brynyolf and doing his quests plant the ring and go to the ratway, in a room with an alchemy table and a lot of floor traps a guy runs up and starts punching you, no matter your race his gloves add 10 damage to your hand to hand. | Alternatively, look at applying one or more of the unarmed mods.
<http://www.nexusmods.com/skyrim/mods/searchresults/?src_order=2&src_sort=0&src_view=1&src_tab=1&src_name=unarmed&page=1&pUp=1> |
2,013,387 | I'm having trouble accessing a class' variable.
I have the functions below in the class.
```
class Profile {
var $Heading;
// ...
function setPageTitle($title)
{
$this->Heading = $title;
echo 'S: ' . $this->Heading;
}
function getPageTitle2()
{
echo 'G: ' . $this->Heading;
return $this->Heading;
}
// ...
}
```
Now when I run the method `$this->setPageTitle("test")` I only get
`G: S: test`
What's wrong with the `getPageTitle2` function? Heading is public btw. Please help!
Thanks guys! | 2010/01/06 | [
"https://Stackoverflow.com/questions/2013387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417012/"
] | If you have "G: S: test"
it means you called getPageTitle2 before setPageTitle !
It looks normal then : I suggest first set then get. | you have to declare the Heading and title out of the function ... i dont know if you already did that
see the order of calling the functions |
17,122,081 | Hello I am creating gaming trophy system and I am still learning pdo. I have two tables in my database
First table ( games ) structure is
```
id, title, thumb, bronze, silver, gold, platinum
```
Second table ( trophies ) structure is
```
id, title, game_id
```
every trophy assigned to a game by ( game\_id ) column
I want to list the games as follow
game name
earned trophies **x** from **total**
the query am using only get the total of the trophies i don't know how to retrieve game trophy data from trophies table
this is my query code
```
$stmt = $db->query('SELECT * FROM trophies ORDER BY id DESC');
$numcat = $stmt->rowCount();
if($numcat == 0)
{
echo "There's No Trophies To Show";
}
else
{
foreach($db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games GROUP BY id DESC") as $row)
{
echo "
<div class='game_row'>
<div class='thumb_box'><img src='../images/thumbs/$row[thumb]' width='87' height='48' alt='$row[title]' /></div>
<div class='info_box'>
<span class='game_name'><a href='trophies.php?action=edit&game_id=$row[id]'>$row[title]</a></span><br />
<span class='game_trophy'>0 Of $row[total] Trophies</span>
</div>
</div>";
}
}
```
I tried to use join and iam sure iam missing something
My query with join
```
foreach($db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC") as $row)
```
the error i got
Warning: Invalid argument supplied for foreach() in the same line | 2013/06/15 | [
"https://Stackoverflow.com/questions/17122081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578920/"
] | You need to do that:
```
$sqlres=$db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC");
while($row=$sqlres->fetch_assoc())
{
echo $row["thumb"];
}
```
In SQL when you do a join you need to specify the table of the field:
```
SELECT g.thumb, g.title, g.id, SUM(t.bronze + t.silver + t.gold + platinum) AS total FROM games g JOIN trophies t ON g.id = t.game_id GROUP BY g.id DESC
``` | Try this:
```
$rows = $db->query("SELECT thumb, title, id, SUM(bronze + silver + gold + platinum) AS total FROM games JOIN trophies ON games.id = trophies.game_id GROUP BY id DESC");
foreach($rows as $r){
echo $r->thumb //etc.
}
```
Your title sql error is because you have two tables with the same field name. You must specify duplicate fields in a standard join like so: games.title, trophies.bronze, etc. etc. ( it's good practice to do it for all, but is only required on tables with the same fields. Hence the ambiguous fields error. - I know. MySQL needs to display better errors. Too bad Oracle bought them up, and hasn't focused on it.
And then, trying running the foreach loop on your sql query after returning the query results so you can use it to iterate through the result rows. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.