text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Como criar email em Swift usando MFMailComposerController corretamente?
Estou tendo problemas ao criar um email com MFMailComposerController em Swift. Ao tentar atribuir self a emailController.mailComposerController recebo um erro informando que não posso atribuir TelaFinalViewController (self) para um valor do tipo MFMailComposerViewController.
Escrevi o seguinte código abaixo:
// Teste para possibilidade de envio
if MFMailComposeViewController.canSendMail(){
// Criação do Email
let emailController:MFMailComposeViewController = MFMailComposeViewController()
emailController.mailComposeDelegate = self // Ocorre o erro aqui!
emailController.setSubject(assunto)
emailController.setToRecipients([para])
emailController.setMessageBody(corpoEmail, isHTML: false)
// Demais implementação ...
}
Mensagem de erro:
Cannot assign a value of type "TelaFinalViewController" to a value of
type 'MFMailComposeViewControllerDelegate!'
Procurei em tutoriais e aqui mesmo no Stackoverflow, mas não achei especificamente este uma solução ou explicação para este problema.
Seria um caso de bug?
A:
Certifique-se que sua classe TelaFinalViewController implementa o protocolo MFMailComposeViewControllerDelegate.
Exemplo como a definição de sua classe deve ficar:
class TelaFinalViewController: UIViewController, MFMailComposeViewControllerDelegate
| {
"pile_set_name": "StackExchange"
} |
Q:
shallow nodes and deeper nodes
I found that in some tutorial the breadth first search
the shallow nodes are expanded befor deeper nodes.
I am realy confuse what is the meaning of each of them?
Thank you
A:
Terms "shallow" and "deep" come from visualizing your graph with the starting node at the top: the "depth" of a node is the number of edges that you need to traverse in order to get to that node from the starting node. The statement about BFS tells you that nodes with fewer edges between them and the starting node are discovered before nodes separated from the start by more edges.
| {
"pile_set_name": "StackExchange"
} |
Q:
need improvement for my javascript code function
I am creating a function that seems to work well but I need improvement if someone can help me
expected result:
const x = ['i','like','js']
given => ['i','i-like','i-like-js']
function myFunction(parrams) {
const arr = []
for (let index = 0; index < parrams.length; index++) {
const x = parrams.indexOf(parrams[index])
if (x != 0) {
arr.push(parrams.slice(0, x).join('-'))
}
if (x === parrams.length - 1) {
arr.push(parrams.slice(0, x + 1).join('-'))
}
}
return arr
}
const arrayTest = ['need','improvement','for','my','code']
console.log(myFunction(arrayTest))
A:
In your code x is same as index, you can avoid that. Also made some modifications as well. Please check.
function myFunction(parrams) {
const arr = [];
for (let index = 0; index < parrams.length; index++) {
arr.push(parrams.slice(0, index + 1).join("-"));
}
return arr;
}
const arrayTest = ["need", "improvement", "for", "my", "code"];
console.log(myFunction(arrayTest));
| {
"pile_set_name": "StackExchange"
} |
Q:
IdentityServer4 - I need given_name claim in my API code, but don't have an identity token in my API. How can I get given_name?
I have a mobile client (Android), an API (WebAPI .net Core 3.1) and an IdentityServer4.
I login with my client to IdentityServer and get back an Identity token and a Access Token.
I use the access token to access the API... all good so far.
Now in the API, on the first time only, I need to update a table with the users first and last name plus some other identity stuff, but these claims are not available in the API (because this info is not available in the access token)
My question is, how do I go about getting the user claims from my API code?
I could pass the various claims as string parameters to the API call, but the mobile client is unable to see if this update has taken place, so I would have to pass this information every time I call the API, which is very wasteful as it is only required the first time. I also prefer this to be done without exposing this in an endpoint in my API.
Can anyone suggest how I can get the user (profile) claims of the user with in the API?
Update:
Now I have found an endpoint in IdentityServer that could help, called "userinfo_endpoint" but this needs an Access Token. Can I somehow re-use the Access Token that is used to access the API within my API code?
A:
Yes, you can use the same access token to contact the user info endpoint to get additional user information.
If you were to use JavaScript to access it, it could look like:
//Make a AJAX-call to the user endpoint
$.ajax({
url: "@OpenIDSettings.userinfo_endpoint",
type: 'GET',
headers: { "Authorization": 'Bearer ' + params.access_token }
}).done(function (data) {
$("#userinfo").text(JSON.stringify(data, null, 2));
});
You just set the Authorization header.
You can also add user claims to the access token by providing UserClaims in your ApiScopes or ApiResource definitions, like:
new ApiScope()
{
Name = "shop.admin",
DisplayName = "You can administrate the e-shop systems",
Description = "Full admin access to the e-shop system.",
Emphasize = false,
Enabled = true,
Required = false,
UserClaims = new List<string>
{
//Custom user claims that should be provided when requesting access to this API.
//These claims will be added to the access token, not the ID-token!
"seniority",
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
CoreData iPad application crash
I have made a new split view iPad app using CoreData. All I have done is added a new attribute to the entity which is a string. (The default being timeStamp, date).
This causes the app to crash upon startup just adding it. Why is this so?
I was for example going to play around with it to display text rather than its default date. E.g. changing this line: [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"]; Using a different value other than a date.
A:
It's almost certainly because you already had the app installed on the device, and now that you have changed the Core Data model the existing database has the wrong structure. You can confirm this by looking in the XCode console window after the crash: you should see an exception stack trace and, above that, a message along the lines of "The model used to open the store is incompatible with the one used to create the store." When XCode installs your modified version of the app onto the device, it doesn't overwrite the existing database automatically, which is a pain and regularly catches me out ;-)
You have to uninstall the app from the device after making any changes to the Core Data model, so that it starts with a clean version of the database. There's more info about this aspect of Core Data at Shannon Appelcline's iPhone in Action site.
| {
"pile_set_name": "StackExchange"
} |
Q:
Taking a quick look at DiffOrig, then switching back
I've discovered this great command from the documentation:
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
So I've come up with this:
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis | wincmd p
map <Leader>do :DiffOrig<cr>
map <leader>dc :q<cr>:diffoff!<cr>
The problem is, when I se \dc, it will jump back to the beginning of the file, not where I left it prior to issuing \do. How to fix this?
Please try this yourself, see what the problems are and how to fix them. And tell me how to fix them too :-)
A:
You could try:
command DiffOrig let g:diffline = line('.') | vert new | set bt=nofile | r # | 0d_ | diffthis | :exe "norm! ".g:diffline."G" | wincmd p | diffthis | wincmd p
nnoremap <Leader>do :DiffOrig<cr>
nnoremap <leader>dc :q<cr>:diffoff<cr>:exe "norm! ".g:diffline."G"<cr>
| {
"pile_set_name": "StackExchange"
} |
Q:
tracker auto run on reactive subscription
i"m trying to recompute autorun on collection update ,
i only manage to get it to work when adding autopublish.the code below works perfectly .
Tracker.autorun(function() {
var pages = Posts.find().fetch();
_.each(pages, function(page) {
console.log("react");
if (typeof page.adress !== 'undefined' &&
typeof page.lat !== 'undefined' &&
typeof page.long !== 'undefined') {
var objMarker = {
id: page._id,
lat: page.lat,
lng: page.long,
title: page.name
};
// check if marker already exists
if (!gmaps.markerExists('id', objMarker.id))
gmaps.addMarker(objMarker);
}
});
});
}
what i need is reacting on subscription.
i have this publication defined :
Meteor.publish('allposts', function() {
return Posts.find({});
});
A:
From your code looks like subscribing to the records on the client is missing
try this
remove autopublish package
on server publish records
Meteor.publish('allposts', function() {
return Posts.find({});
});
In the client, subscribe to the records in a reactive computation
Tracker.autorun(function(){
Meteor.subscribe('allposts');
})
Now In the client you can use Posts.find({}) wherever you want it will be reactive
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP str_replace in loop
i have two strings
$xml = '<para aid:pstyle="NL_FIRST">—To the best of our knowledge, the MMSN<emph aid:cstyle="ITALIC"> protocol</emph> is the first multifrequency<emph aid:cstyle="ITALIC"> MAC protocol especially</emph> designed for WSNs, in which each device is equipped with a single radio transceiver and the MAC layer packet size is very small.</para></item><item>';
$tex = '\begin{itemize}\item o the best of our knowledge, the MMSN protocol is the first multifrequency MAC protocol especially designed for WSNs, in which each device is equipped with a single radio transceiver and the MAC layer packet size is very small.\item';
I need to find <emph aid:cstyle="ITALIC"> protocol</emph> This kind of tag and find the same text in $tex and replace the word "protocol" with {it protocol } .
Simply
i need to find this pattern
<emph aid:cstyle="ITALIC"> protocol</emph>
and find the text inside that pattern and replace the same word in $tex.
FYI : Content-wise both are same $tex and $xml.
I used this code
preg_match_all('/<emph aid:cstyle="ITALIC">(.*?)<\/emph>(.*?)\</',$xml,$matches);
for($i=0;$i<count($matches[1]);$i++)
{
$findtext = str_replace("<","",$matches[1][$i].$matches[2][$i]);
$replace = "{\it".$matches[1][$i]."}".$matches[2][$i];
$finaltext = preg_replace('/'.$findtext.'/',$replace,$tex);
}
echo $finaltext;
But it replace only one.
A:
You should change your regex to
preg_match_all('/<emph aid:cstyle="ITALIC">(.+?)<\/emph>/', $xml, $matches);
I tried it on your sample string and it finds both.
Your current regex consumes to much of the string. If you run it on the provided string you will see that it matches more than you intended it to match
string(71) "<emph aid:cstyle="ITALIC"> protocol</emph> is the first multifrequency<"
Since the next "<" is already matched the matcher can not find the next opening tag.
For the loop-part: You are not overwriting $tex but you are using it as the string to work on. So any changes but the last will not be stored.
$finaltext = $tex;
for ($i = 0; $i <count($matches[1]); $i++) {
$finaltext = str_replace($matches[1][$i], '{\it'.$matches[1][$i].'}', $finaltext);
}
echo $finaltext;
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use font:monospace?
It seems it doesn't work if I use font:monospace.
But It's worked for font-family:monospace.
What's the difference beteew font and font-family?
A:
You need to atleast specify font-size while specifying the shorthand property for font along with the family. Otherwise everything will have its own initial values.
See the definition below.
[ [ <‘font-style’> || || <‘font-weight’> || <‘font-stretch’> ]? <‘font-size’> [ / <‘line-height’> ]? <‘font-family’> ] | caption | icon | menu | message-box | small-caption | status-bar
An example:
selector{
font:12px monospace;
}
When specifying shorthand property using font font-size must precede font-family and both are mandatory (the ones in angle brackets and not in square brackets) atleast.
| {
"pile_set_name": "StackExchange"
} |
Q:
Different RegEx from Chrome to Internet Explorer
I have this regex:
var RE_SSN = /^[A-Åa-å0-9,\!\-\?\""\. ]{3,999}$/;
Which I use in a JS-function
function checkSsn(ssn){
if (RE_SSN.test(ssn)) {
javascript:addAppointment(document.forms[0])
alert("YES");
} else {
alert("NO");
}
}
When I type 12345Test in Chrome the regex passes, and thats the point. But in IE the String cannot start with numbers. Seems to me that IE is just made for making my life miserable.. How can I fix this problem?
A:
Your problem is the construction A-Åa-å which is being interpreted differently. IE doesn't think T is in that range.
This may be something to do with the character set detection. Is the script encoded in UTF-8? Does it start with the UTF-8 BOM? If not then adding one will probably help - at least by making the browsers behave the same.
Secondly, I am not sure what your intent is by writing A-Åa-å, but it seems an unusual thing to put into a regex.
I suggest you change the regex to break out the characters into more natural ranges, e.g. to A-Za-zÅå, or expanding the ranges altogether.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Elegantly convert switch+enum with polymorphism
I'm trying to replace simple enums with type classes.. that is, one class derived from a base for each type. So for example instead of:
enum E_BASE { EB_ALPHA, EB_BRAVO };
E_BASE message = someMessage();
switch (message)
{
case EB_ALPHA: applyAlpha();
case EB_BRAVO: applyBravo();
}
I want to do this:
Base* message = someMessage();
message->apply(this); // use polymorphism to determine what function to call.
I have seen many ways to do this which all seem less elegant even then the basic switch statement. Using dyanimc_cast, inheriting from a messageHandler class that needs to be updated every time a new message is added, using a container of function pointers, all seem to defeat the purpose of making code easier to maintain by replacing switches with polymorphism.
This is as close as I can get: (I use templates to avoid inheriting from an all-knowing handler interface)
class Base
{
public:
template<typename T> virtual void apply(T* sandbox) = 0;
};
class Alpha : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyAlpha();
}
};
class Bravo : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyBravo();
}
};
class Sandbox
{
public:
void run()
{
Base* alpha = new Alpha;
Base* bravo = new Bravo;
alpha->apply(this);
bravo->apply(this);
delete alpha;
delete bravo;
}
void applyAlpha() {
// cout << "Applying alpha\n";
}
void applyBravo() {
// cout << "Applying bravo\n";
}
};
Obviously, this doesn't compile but I'm hoping it gets my problem accross.
A:
Well, after giving in to dynamic_cast and multiple inheritance, I came up with this thanks to Anthony Williams and jogear.net
class HandlerBase
{
public:
virtual ~HandlerBase() {}
};
template<typename T> class Handler : public virtual HandlerBase
{
public:
virtual void process(const T&)=0;
};
class MessageBase
{
public:
virtual void dispatch(HandlerBase* handler) = 0;
template<typename MessageType>
void dynamicDispatch(HandlerBase* handler, MessageType* self)
{
dynamic_cast<Handler<MessageType>&>(*handler).process(*self);
}
};
template<typename MessageType> class Message : public MessageBase
{
virtual void dispatch(HandlerBase* handler)
{
dynamicDispatch(handler, static_cast<MessageType*>(this));
}
};
class AlphaMessage : public Message<AlphaMessage>
{
};
class BravoMessage : public Message<BravoMessage>
{
};
class Sandbox : public Handler<AlphaMessage>, public Handler<BravoMessage>
{
public:
void run()
{
MessageBase* alpha = new AlphaMessage;
MessageBase* bravo = new BravoMessage;
alpha->dispatch(this);
bravo->dispatch(this);
delete alpha;
delete bravo;
}
virtual void process(const AlphaMessage&) {
// cout << "Applying alpha\n";
}
virtual void process(const BravoMessage&) {
// cout << "Applying bravo\n";
}
};
int main()
{
Sandbox().run();
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change default setting of vim-clojure-static plugin?
I'm new in clojure programming. I'm using vim editor. I have installed vim-clojure-static plugin to write better code.
But It's not working as I expected. I want two spaces indentation for every special keyword.
For example, Here is core.clj file.
(ns hello.core
(:gen-class)
(:import
(java.io FileNotFoundException)))
(defn -main
[& args]
(println "Hello, World!")
(try (slurp (first args))
(catch FileNotFoundException e (println (.getMessage e)))))
This is defualt indentation. I don't like this. I want my code should look like:
(ns hello.core
(:gen-class)
(:import
(java.io FileNotFoundException)))
(defn -main
[& args]
(println "Hello, World!")
(try (slurp (first args))
(catch FileNotFoundException e (println (.getMessage e)))))
It means, I want two spaces indentation for every special keyword i.e try in given example.
Meanwhile I'm not sure, Whether I have installed *plugin in correct way. Here is my .vim directory structure:
$ tree ~/.vim/
/home/james/.vim/
|-- autoload
| `-- pathogen.vim
`-- bundle
`-- vim-clojure-static
|-- autoload
| `-- clojurecomplete.vim
|-- clj
| |-- dev-resources
| | |-- test-basic-sexp-indent.txt
| | |-- test-inherit-indent.in
| | |-- test-inherit-indent.out
| | |-- test-multibyte-indent.txt
| | |-- test-reader-conditional-indent.in
| | |-- test-reader-conditional-indent.out
| | |-- test-side-effects-in-indentexpr.in
| | `-- test-side-effects-in-indentexpr.out
| |-- project.clj
| |-- src
| | `-- vim_clojure_static
| | |-- generate.clj
| | `-- test.clj
| |-- test
| | `-- vim_clojure_static
| | |-- indent_test.clj
| | `-- syntax_test.clj
| `-- vim
| `-- test-runtime.vim
|-- doc
| `-- clojure.txt
|-- ftdetect
| `-- clojure.vim
|-- ftplugin
| `-- clojure.vim
|-- indent
| `-- clojure.vim
|-- LICENSE.txt
|-- README.markdown
`-- syntax
`-- clojure.vim
16 directories, 23 files
Here is my vimrc file:
$ cat ~/.vimrc
set autoindent
set tabstop=2
set shiftwidth=2
set softtabstop=2
set expandtab
execute pathogen#infect()
syntax on
filetype plugin indent on
can anyone tell me, Where I'm wrong? How can I make autoindent with spaces *two? Thanks.
A:
according to the documentation here: https://github.com/guns/vim-clojure-static,
you need to add the try keyword to the list with a command like
let g:clojure_fuzzy_indent_patterns = ['^with', '^def', '^let', '^try']
I hope it will help, I didn't try it
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Hive jobs with Azkaban?
I would like to use Azkaban for periodic Hive jobs, I have looked through Azkaban documentation, and it seems like by default it doesn't support Hive jobs, do you know how can I use these two together?
I think, I'll have to run Hive jobs as a "command job" available in Azkaban, but maybe someone has worked it out.
I was using Oozie for some time, but It didn't meet my needs.
Thanks.
A:
Right now we don't have an easy way. You can certainly hack into the HiveCliDriver and do it from there, but it's suboptimal... Alternatively, just run it as a command line job. We're using a different system at LI. I hope to add this ability pretty quickly, but not sure when I'll have the chance.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using django-tables2 form to send selection to another form - nothing saves?
I have a django-tables2 form that passes selected model items to a second form. The goal of the second form is to allow a user to edit values that will be applied to all the items. My problem is that the second form fails validation and then the input values don't get saved. How can I link these two forms and allow user input before the form tries to validate? It seems like the POST request goes from the table through the second form -- is there a way to interrupt it or start a second request?
image_list.html:
<form method="post" action="{% url 'ExifReader:delete_image_list' %}">
{% render_table table %}
{% csrf_token %}
<button type="submit" style="margin-right:10px" class="btn btn-primary" name="edit_FAN">Edit Exif</button>
<button type="submit" style="margin-right:10px" class="btn btn-danger" onclick="return confirm('Delete?')" name="delete_images">Delete Images</button>
</form>
Note: The delete_images button works fine.
views.py:
def delete_image_list(request):
if request.method == 'POST':
if 'delete_images' in request.POST:
pks = request.POST.getlist('selection')
# Delete items...
elif 'edit_FAN' in request.POST:
form = EditFANForm()
pks = request.POST.getlist('selection')
imgs = []
for pk in pks:
ex = exif.objects.get(pk=pk)
imgs.append(ex.image_id)
if request.method == 'POST':
print('POST')
for img in imgs:
print(image.objects.get(pk=img))
form = EditFANForm(instance=image.objects.get(pk=img))
if form.is_valid():
print('Valid')
formS = form.save(commit=False)
img.FAN = formS.FAN
fromS.save()
else:
print('ERRORS: ', form.errors)
return render(request, 'ExifReader/edit_fan_form.html', {'form': form, 'pks':pks})
When I click the button for "edit_FAN" from the table view, the EditFANForm renders correctly, I can enter values, get redirected back to the table view, but none of the values are saved. From the print commands I added for tracing the code, I get the following in console:
POST
774
ERRORS: <bound method BaseForm.non_field_errors of <EditFANForm bound=False, valid=False, fields=(FAN;collection;tags)>>
Where "774" is the selected object.
So it looks to me like the form gets to the part where values can be edited (EditFANForm), but the form POSTs before the user can input values, hence the form doesn't validate (but there also aren't any errors?).
Where am I going wrong? How can I save the values from the second form?
Python 3.6.8, Django 2.2.6
A:
I figured out a solution that seems to work fine: add a redirect to another view to process the second form. Messages from django.contrib are used to pass context data to the second view and form (in this case the selected objects from the table).
from django.contrib import messages
def delete_image_list(request):
...
elif 'edit_FAN' in request.POST:
pks = request.POST.getlist('selection')
messages.add_message(request, messages.INFO, pks)
return HttpResonseRedirect(reverse('ExifReader:images_list_edit'))
def images_list_edit(request):
if request.method == 'POST':
...
| {
"pile_set_name": "StackExchange"
} |
Q:
How to plot TEMA indicator with Microsoft Chart Control
I've added two series: Series1 (CandeleStick), Series2 (Line). I've added points and the FinancialFormula:
public Form1() {
InitializeComponent();
chart1.Series[0].Points.Add(24.00, 25.00, 25.00, 24.875);
chart1.Series[0].Points.Add(23.625, 25.125, 24.00, 24.875);
chart1.Series[0].Points.Add(26.25, 28.25, 26.75, 27.00);
chart1.Series[0].Points.Add(26.50, 27.875, 26.875, 27.25);
chart1.Series[0].Points.Add(26.375, 27.50, 27.375, 26.75);
chart1.Series[0].Points.Add(25.75, 26.875, 26.75, 26.00);
chart1.Series[0].Points.Add(25.75, 26.75, 26.125, 26.25);
chart1.Series[0].Points.Add(25.75, 26.375, 26.375, 25.875);
chart1.Series[0].Points.Add(24.875, 26.125, 26.00, 25.375);
chart1.Series[0].Points.Add(25.125, 26.00, 25.625, 25.75);
chart1.Series[0].Points.Add(25.875, 26.625, 26.125, 26.375);
chart1.Series[0].Points.Add(26.25, 27.375, 26.25, 27.25);
chart1.Series[0].Points.Add(26.875, 27.25, 27.125, 26.875);
chart1.Series[0].Points.Add(26.375, 27.125, 27.00, 27.125);
chart1.Series[0].Points.Add(26.75, 27.875, 26.875, 27.75);
chart1.Series[0].Points.Add(26.75, 28.375, 27.50, 27.00);
chart1.Series[0].Points.Add(26.875, 28.125, 27.00, 28.00);
chart1.Series[0].Points.Add(26.25, 27.875, 27.75, 27.625);
chart1.Series[0].Points.Add(27.50, 28.75, 27.75, 28.00);
chart1.Series[0].Points.Add(25.75, 28.25, 28.00, 27.25);
chart1.Series[0].Points.Add(26.375, 27.50, 27.50, 26.875);
chart1.Series[0].Points.Add(25.75, 27.50, 26.375, 26.25);
chart1.Series[0].Points.Add(24.75, 27.00, 26.50, 25.25);
chart1.DataManipulator.IsStartFromFirst = true;
chart1.DataManipulator.FinancialFormula(FinancialFormula.TripleExponentialMovingAverage, "5", "Series1:Y4", "Series2:Y");
}
But I can't get the expected result. Just line on zero level. What I'm doing wrong?
A:
Your data is actually there. You need to adjust Minimum and Maximum for your axis scale and also the axis used for each series: AxisY or AxisY2.
EDIT: For the sake of testing, if you just repeat your own price pattern:
| {
"pile_set_name": "StackExchange"
} |
Q:
Link_to a specific product
New to Rails and trying to figure out how to set-up a link_to that goes to a user's specific property. So in my case, property belongs_to user and user has_many properties. I'm using Devise and CanCan. Just need for the current user to be redirected to their property.
Issue right now is that it tries to redirect to the same property_id as the user_id. (e.g. user/15 gets attempts to redirect to 'property/15' even though when I check the console - let's say the user's property is property/18 - it has a user_id of 15 - so there is an association created that's correct) Just can't figure out how to get the link_to to go to property 18 (example) and not 15.
Appreciate any help!
Users/show
<div class="col-mds-6">
<%= link_to "View Property", property_path(@user), :class => "btn btn-primary btn-lg btn-custom" %>
</div>
Controller/Users
class UsersController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
Route:
resources :properties, :users, :orders, :charges
A:
current user to be redirected to their property
You'd need to use the following:
#app/controllers/properties_controller.rb
class PropertiesController < ApplicationController
def show
@user = current_user.properties.find params[:id]
end
end
#app/views/users/show.html.erb
<% @user.properties.each do |property| %>
<%= link_to property.name, property %>
<% end %>
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt function runJavaScript() does not execute JavaScript code
I am trying to implement the displaying of a web page in Qt. I chose to use the Qt WebEngine to achieve my task. Here's what I did :
Wrote a sample web page consisting of a empty form.
Wrote a JS file with just an API to create a radio button inside the form.
In my code, it looks like this :
View = new QWebEngineView(this);
// read the js file using qfile
file.open("path to jsFile");
myJsApi = file.Readall();
View->page()->runjavascript (myjsapi);
View->page()->runjavascript ("createRadioButton(\"button1\");");
I find that the runJavaScript() function has no effect on the web page. I can see the web page in the output window, but the radio button I expected is not present. What am I doing wrong?
A:
I think you will have to connect the signal loadFinished(bool) of your page() to a slot, then execute runJavaScript() in this slot.
void yourClass::mainFunction()
{
View = new QWebEngineView(this);
connect( View->page(), SIGNAL(loadFinished(bool)), this, SLOT(slotForRunJS(bool)));
}
void yourClass::slotForRunJS(bool ok)
{
// read the js file using qfile
file.open("path to jsFile");
myJsApi = file.Readall();
View->page()->runJavaScript(myjsapi);
View->page()->runJavaScript("createRadioButton(\"button1\");");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
A 'bad' definition for the cardinality of a set
My set theory notes state that the following is a 'bad' definition for the cardinality of a set $x:$ $|x|=\{y:y\approx x\}$ $(y\approx x\ \text{iff} \ \exists\ \text{a bijection}\ f:x\rightarrow y )$
The reason this is a 'bad' definition is since if $x\neq \emptyset$ then $|x|$ is a proper class and I am asked to prove this.
For the moment, let's consider $x$ to be finite. Say $|x|=n$ as $x$ contains a finite number of elements.
But then $x\approx \{n+1,...,n+n\}$ as $|\{n+1,...,n+n\}|=n$ and we can 'keep going up' in this way such that $\bigcup On\subseteq|x|$ and since $\bigcup On = On$ and $On$ is a proper class we must have $|x|$ being a proper class as well.
This argument is certainly not rigourous and I am unfortunately very much stumped on what to do if $x$ not finite.
$\underline{\text{Please correct me if $\ $} \bigcup On \neq On}$
Any feedback is very much appreciated.
A:
Here is a possibly easier approach: show that if $x$ is not empty, then for every $a$ in the universe, there is some $x_a$ such that $a\in x_a$ and $x_a\approx x$.
If $a\in x$, then $x_a=x$. Otherwise, fix some $y\in x$, and consider $(x\setminus\{y\})\cup\{a\}$ as your $x_a$. Now it follows that $\bigcup |x|$ is everything. And everything is not a set.
| {
"pile_set_name": "StackExchange"
} |
Q:
List all commits for a specific directory and its children?
I'm trying to list all commits for a specific directory and all of its children.
I've had a look through some git documentation (https://www.atlassian.com/git/tutorials/git-log) regarding the git log command, but the closest I can seem to get is somehing like:
git log --grep="nameOfPlugin"
But, whilst this is somewhat helpful, it's not reliable enough in this circumstance.
I can also seem to find ways of listing all commits for a specific file, e.g.
git log -- foo.py bar.py
But this isn't helpful unless I iterate through all directories/subdirectories, then compile a list of file paths + names, pass this to git log, then concatenate all duplicate commits (this seems a bit mental to me).
Is there some simple way of doing this that I'm missing?
To give some background
I'm looking for all internal modifications made to a CMS plugin before updating it.
I know this is bad practise etc. etc. but it's sometimes unavoidable (especially when hooks aren't implemented well).
We have kept some brief internal documentation regarding custom modifications made to the plugin, but I don't really trust them. I know we probably could have kept better internal documentation but this circumstance is surely a good reason VCS like git are used?
A:
After a little more tinkering, this turned out to be as easy as:
git log --stat path/to/directory/in-question
The stat parameter gives a list of which files where modified in each commit, the p parameter would also list all changes (which may be useful in some cases).
Should have read the man page properly!
| {
"pile_set_name": "StackExchange"
} |
Q:
Test two variables in the same script
Question :
I'm breaking my teeths under this:
awk -v full=wc -v empty=wp '{
...blablabla...
if ($4==full) stop=yes
if (stop==yes && $4==empty) exit
...blablabla...
}'
The code works well (I mean, I get an output) if I don't declare the two variables full and empty at the beginning, and use instead the values of these in the script. If I only use the first variable in the script, I get the same output. But if I only use the second variable, I get no output at all.
A:
Consider what happens when the variables are expanded. A portion of the awk body goes from:
' ... if ($4=='$full') ...'
to
' ... if ($4==wc) ...'
Since wc is a "bare word", awk thinks it is a variable and substitutes it's value (empty string), so you get this:
' ... if ($4=="") ...'
When you're building your awk script, you need to be aware of quoting strings in awk. You need:
' ... if ($4=="'$full'") ...'
However, it is much more elegant to pass values with awk's -v option as you have done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recursive/Strong Induction
Suppose that $a_0, a_1, a_2, \dots$ is a sequence defined as follows.
$$a_0 = 2, a_1 = 4, a_2 = 6 \text{, and } a_k = 7 a_{k-3} \text{ for all integers $k \ge 3$.}$$
Prove that $a_n$ is even for all integers $n \ge 0$.
A:
Except the basic case is trivial and assuming that the statement holds for each $k \leq n - 1$ you have $a_n = 7a_{n-3} $. By hypothesis $a_{k-3} = 2\gamma$, $\gamma$ integer, so $a_n = 14 \gamma$ which implies that 2 divides $a_n $.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue exporting `express()` and `ws()` objects to other files in Node?
Let's say the entry point of my app is app.js
I want to create a socket connect when the app runs and then export it to other files throughout the application.
Here is a bit of example code
const express = require('express');
const WebSocket = require('ws');
const app = express();
app.use(allTheMiddleWares);
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
module.exports = socket;
Then when I try to access the export from app.js I always end up with an empty object.
I have also tried exporting functions:
module.exports = {
test: () => console.log("why don't I work")
}
However this also returns an empty object.
Thanks in advance for the help.
As a temporary work around to access the socket globally I have set process.WebSocket = new WebSocket.Server({server: app});. I would like to know if there are any glaring issues with this.
A:
Making my comment into an answer since it was your solution.
You are not passing a server to the WebSocket constructor. app is a request handler. It is not a server. app.listen() returns a newly created server object.
Change your code from this:
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
to this:
const server = app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: server});
See code for app.listen() here.
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
See doc for app.listen() here.
The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing Values When a Macro Ends for powerpoint
I'm refering to the following explanation:
https://docs.microsoft.com/en-us/office/vba/word/concepts/miscellaneous/storing-values-when-a-macro-ends
How can I adapt the following code to be used in powerpoint?
Replacing ActiveDocument by ActivePresentaiton doesn't seem to do the trick.
Sub AddDocumentVariable()
ActiveDocument.Variables.Add Name:="Age", Value:=12
End Sub
Sub UseDocumentVariable()
Dim intAge As Integer
intAge = ActiveDocument.Variables("Age").Value
End Sub
A:
How you store the information will depend on how much is to be stored and what you need to do with it later. While I wouldn't recommend using the registry, a text file would make a good permanent record that can be appended to.
Or you can store the information in .Tags:
Sub AddTag()
ActivePresentation.Tags.Add "Name", "12"
End Sub
Sub ReadTag()
MsgBox ActivePresentation.Tags("Name")
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Escritura de arraysList en ficheros de txt java
Estoy intentando escribir un arrayList en un fichero de texto con esta función:
String ruta = "C:\\Users\\usuario\\Desktop\\archivo1.txt";
File f = new File(ruta);
FileWriter fw = new FileWriter(f);
BufferedWriter escritura = new BufferedWriter(fw);
for(int i=0;i<lista.size();i++){
escritura.write(lista.get(i));
escritura.newLine();
}
escritura.close();
}
Es un Arralist integer que contiene los valores 0,1,2,3,4 y lo que me aparece es esto
¿Cuál puede ser el fallo?¿No se puede hacer con bufferedWriter?.
Muchas gracias.
A:
Por lo que veo te falta convertir el valor que obtienes mediante el Lista.get(i) a string, ya que no lo esta tratando como tal puesto que si vemos que son esos simbolos ASCII en valor hexadecimal tenemos que:
NUL 00--SOH 01--STX 02--ETX 03--EOT 04--ENQ 05
Edito: añado el codigo para parsear el int a string cualquiera de los dos valdrá
Integer.toString(Lista.get(i)) o String.valueOf(Lista.get(i))
| {
"pile_set_name": "StackExchange"
} |
Q:
Closest pair of points using mouse clicks
The assignment is to to a closest pair of points using brute force.
I seem to have most everything I need - the frame appears, circles appear where I click, and the closest pairs seem to highlight properly, I say "seems" because this is where my question lies. I need only two circles highlighted at any given time (the closest pair), but previous closest pairs do not de-select/unhighlight.
I hope this is something simple I have overlooked. I have been at this for a while, so it's very possible my mind and eyes are just too tired to pick this problem up. Hopefully, a fresh set of eyes will do me some good.
Any help is greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class AssignmentFour extends JFrame {
private final PointPanel canvas = new PointPanel();
public AssignmentFour() {
JPanel panel = new JPanel();
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
add(new JLabel("<html> Click anywhere within the panel."
+ "<BR> The two closest points will be highlighted.<BR>"
+ "Click the 'x' to exit program. </html>"), BorderLayout.SOUTH);
}//AssignmentFour method
public static void main(String[] args) {
AssignmentFour frame = new AssignmentFour();
frame.setTitle("Closest points");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}//main
class PointPanel extends JPanel {
private int xCoordinate = 200;
private int yCoordinate = 200;
private int radius = 5;
private Graphics g;
double minDist = 999999999;
ArrayList<Point> points = new ArrayList<>();
Point ClosestPoint1, ClosestPoint2;
public final double distBetweenPoints(int x, int y, int a, int b) {
double theDist = 0.0;
theDist = Math.sqrt(Math.pow(a - x, 2) + Math.pow(y - b, 2));
return theDist;
}//distBetweenPoints method
public PointPanel() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
xCoordinate = e.getX();
yCoordinate = e.getY();
Point newCoord = e.getPoint();
points.add(newCoord);
g = getGraphics();
g.setColor(Color.RED);
g.drawOval(xCoordinate, yCoordinate, radius, radius);
//g.dispose();
if (points.size() >= 2) {
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
Point p = points.get(i);
Point q = points.get(j);
int x1 = p.x;
int y1 = p.y;
int a1 = q.x;
int b1 = q.y;
if (distBetweenPoints(x1, y1, a1, b1) < minDist) {
minDist = distBetweenPoints(x1, y1, a1, b1);
ClosestPoint1 = p;
ClosestPoint2 = q;
}//inner if
else {
}//else
}//for 'j'
}// for 'i'
int x2 = ClosestPoint1.x;
int y2 = ClosestPoint1.y;
int a2 = ClosestPoint2.x;
int b2 = ClosestPoint2.y;
g.fillOval(x2, y2, radius, radius);
g.fillOval(a2, b2, radius, radius);
}//if
}//mouseReleased
}//MouseListener
);
}//pointPanel
}//point panel extend
}//assignmentfour class
A:
Don't use getGraphics to perform
Custom painting, this is not how painting in Swing is done
Instead, override the JPanels paintComponent method and put your custom painting within it
Take a look at Performing Custom Painting for more details
| {
"pile_set_name": "StackExchange"
} |
Q:
Pushing object into array causes TypeError
I have my values object
values = {
'student': [{
'field': 'prefix',
'description': 'First name'
}, {
'field': 'suffix',
'description': 'Last name'
}, {
'field': 'student_email',
'description': 'Email address'
}],
'classes': [{
'field': 'course_code',
'description': 'Course code'
}]
}
And I'm trying to get each object within 'student' and 'classes'. Once grabbed I'm trying to create a new object that looks like this
{type:'student', field:'prefix', description:'First Name', key:'school'}
and then push that object into a new array. This is what I have so far...
const array = [];
for(const v in values) {
array.concat(values[v].map(obj => {
console.log(obj); // grabs each obj successfully
array.push({
type: v,
description: obj.description,
field: obj.field,
key: 'school'
});
});
}
Right now its throwing TypeError: Cannot read property 'split' of undefined. What am I doing wrong? Can I not create a new object inside of .map()?
A:
Try this:
var values = {'student':[{'field':'prefix','description':'Firstname'},{'field':'suffix','description':'Lastname'},{'field':'student_email','description':'Emailaddress'}],'classes':[{'field':'course_code','description':'Coursecode'}]};
var out = Object.keys(values).map(function(type) {
return values[type].map(function(item) {
return {
name: type,
field: item.field,
descriptiom: item.description,
key: 'school'
};
});
}).reduce(function(l, r) {
return l.concat(r);
});
console.log(out);
Or, so much nicer with ES6 arrow functions:
var out = Object.keys(values).map((type) =>
values[type].map((item) => ({
name: type,
field: item.field,
descriptiom: item.description,
key: 'school'
})
}).reduce((l, r) => l.concat(r));
| {
"pile_set_name": "StackExchange"
} |
Q:
Mechanics of Chromosomal Crossover
When chromosomal crossover occurs, two matched chromosomes swap matched sections of their chromosomes. My question is: how does the cell select where to to make the break on both chromosomes? Is it based on some attempt to match sequences on the two chromosomes, or purely on distance from the centromere? The mechanics of the former could be achieved by breaking the two strands of each chromosome at different places. The mechanics of the second is a simple walk from the centromere with a random(?) selection of where to cut.
The purpose of this question: if the process is based on distance from the centromere then it would provide an explanation the presence of junk DNA. Successful crossover requires that the number of functioning genes on the two chromosomes not be radically altered in quantity. A failed crossover would result in at least one of the gametes being non-viable, reducing fertility. If crossover is based on centromere distance then the location of genes becomes a factor in the success of a crossover, erecting a fitness barrier between populations with radically different gene placement, even if gene content is identical.
If this is a question without an answer, currently, one way to address it would be to try to cross breed knockout mice that don't have junk DNA with ordinary mice that do. If the fertility of the cross breeding is significantly lower than than knockout with knockout and normal with normal, or if the cross breeds are less fecund, then that would provide evidence for position based crossovers, and a function for junk DNA in the crossover process.
A:
How does the cell select where to to make the break on both chromosomes?
There are proteins that direct the selection of a site where a double strand break will be made on one chromatid.
Crossovers are not randomly distributed: The histone methyltransferase PRDM9 recruits the recombination machinery to genetically determined hotspots in the genome and each incipient crossover somehow inhibits formation of crossovers nearby, a phenomenon called crossover interference. Each chromosome bivalent, including the X-Y body in males, has at least one crossover and this is required for meiosis to proceed correctly.
Credit; Reactome
.
Is it based on some attempt to match sequences on the two chromosomes, or purely on distance from the centromere?
The sequences are matched but not as you have assumed. Following the introduction of a double-strand break in one chromosome the regions around the break are processed (by proteins) and these processed ends invade the opposite chromatid. The formation of a Holliday junction follows, these are the "X" structures between strands in the image below, and they requires base-pairing;
Image credit; EMW2012
| {
"pile_set_name": "StackExchange"
} |
Q:
How to increase vertical tab width for icon visibility and click reach?
I've been trying to increase the width of my tab click range to expand its reach and to be able to view icons.
I've seen a few examples suggesting to create a class with different props. It worked with a horizontal tab but not a vertical one. It would be great if anyone could help out. I've tried also searching for vertical tabs props specifically in material UI with no results, unfortunately. Thanks for helping
Here is how it currently looks:
Code:
import React from "react";
import ReactDOM from "react-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
import { withStyles } from "@material-ui/core/styles";
import Home from './Screens/Home'
import home from './home.svg';
import Contact from './Screens/Contact'
import contact from './contact.svg';
import {Router} from 'react-router-dom'
import Chat from './Screens/Chat'
import chat from './chat.svg';
import Settings from './Screens/Settings'
import settings from './settings.svg'
import Logout from './Screens/Logout'
import logout from './logout.svg';export default class ProfileTabs
extends React.PureComponent {
state = { activeIndex: 0 };
handleChange = (_, activeIndex) => this.setState({ activeIndex });
render() {
const { activeIndex } = this.state;
return (
<nav className= "side-drawer">
<div style={{letterSpacing: 0.7, left: 70, position: "absolute", marginTop: 40}}>
<VerticalTabs value={activeIndex} onChange={this.handleChange}>
<MyTab icon ={<img className= "home" src={home} alt="home" style={{height: 45, left:-35, top:8, position: "absolute"}}/>}
label={<p style={{ textTransform:"capitalize"}}>
Home
</p>}
/>
<MyTab icon ={<img className= "process" src={process} alt="process" style={{height: 45, left:-40, top:4, position: "absolute"}}/>}
label={<p style={{textTransform:"capitalize"}}>
Contact
</p>}
/>
<MyTab icon={<img className= "design" src={design} alt="design" style={{height: 45, left:-40, top:6, position: "absolute"}}/>}
label={<p style={{textTransform:"capitalize"}}>
Chat
</p>}
/>
<MyTab icon = {<img className= "material" src={material} alt="material" style={{height: 45, left:-40, top:5, position: "absolute"}}/>}
label={<p style={{textTransform:"capitalize"}}>
Settings
</p>}
/>
<MyTab icon={
<img className= "printer" src={printer} alt="printer" style={{height: 45, left:-40, top:8, position: "absolute"}}/>}
label={<p style={{textTransform:"capitalize"}}>
Logout
</p>}
/>
</VerticalTabs>
{activeIndex === 0 && <TabContainer><Home/></TabContainer>}
{activeIndex === 1 && <TabContainer><Processes/></TabContainer>}
{activeIndex === 2 && <TabContainer><Designs/></TabContainer>}
{activeIndex === 3 && <TabContainer><Materials/></TabContainer>}
{activeIndex === 4 && <TabContainer><Printers/></TabContainer>}
</div>
</nav>
);
}
}
const VerticalTabs = withStyles(theme => ({
flexContainer: {
flexDirection: "column"
},
indicator: {
display: "none"
}
}))(Tabs);
const MyTab = withStyles(theme => ({
selected: {
color: "White",
borderRight: "none"
}
}))(Tab);
const styles = theme => ({
root: {
minWidth: 100,
},
});
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 9 * 3 }}>
{props.children}
</Typography>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ProfileTabs />, rootElement);
A:
For anyone interested I've solved it:
increase the minWidth on styles.root
and move icons by adding position: "absolute" to their styles
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert Elapsed Time in SQL Server
I want to insert elapsed times using the C# Stopwatch into a SQL Server so we can average the times using a SQL Script.
var stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
var elapsedTime = stopwatch.Elapsed;
I'm inserting the time like this...
cmd.Parameters.Add("@ElapsedTime", SqlDbType.Time);
The data type in the database is ...
ElapsedTime(time(7),null)
Getting this error...
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
I just want to insert the elapsed time in the database like this...
00:01:44.9383728
Here is how I am putting into database...
internal bool TimesToSql(TimeSpan elapsedTime)
{
try
{
const string statement = "INSERT INTO Database.dbo.TestProgress(MachineName, ElapsedTime) " +
"VALUES(@MachineName, @ElapsedTime)";
var conn = new SqlConnection(ConnectionStringLocalDb());
var cmd = new SqlCommand(statement, conn);
var machineName = Environment.MachineName;
cmd.Parameters.Add("@MachineName", SqlDbType.NVarChar);
cmd.Parameters.Add("@ElapsedTime", SqlDbType.Time);
//
cmd.Parameters["@MachineName"].Value = Environment.MachineName;
cmd.Parameters["@ElapsedTime"].Value = elapsedTime;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
return true;
}
catch (Exception exception)
{
_logger.Log(Loglevel.Error, "Boom: {0}", exception.Message);
return false;
}
}
The ultimate goal is to get the average time from let's say x amount of elapsed times, if I can do that using string, then I will format them to strings
A:
What exactly do you want to do with the timespan in the database? If all you want to do is sort and aggregate, you could go for a bigint in the database.
Internally in .NET a TimeSpan is nothing but a long value that stores the number of 'Ticks' (see the .NET source code for TimeSpan) and a bunch of conversions of course to seconds, milliseconds etc.
When you load the value again from the database you can recreate the TimeSpan from the ticks stored in the database. You will not lose precision.
You can even perform aggregate functions (Min, Max, Avg, Sum) on the database values and you will still get valid TimeSpans when you later load the value in C#.
If however you have a requirement to query the database for values of, for example, more than 5 mins, you'd need to do the math of figuring out how to express 5 mins as ticks.
In the source code linked earlier, you'll see that there are 10,000,000 ticks in a second. So it's hardly rocket science ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
In .NET Core, why would I decide to create a library that targets .NET Standard rather than .NET Core?
What would be the advantage of targeting .NET Standard and what would I be missing if I chose to target this over .NET Core?
A:
If you target .NET Standard, you would have an assembly that's compatible with every platform that implements .NET Standard. So .NET 4.5 and up, .NET Core, UWP, Mono, etc.
If you target .NET Core, you get more than just the API's defined in the standard (the standard, for instance, doesn't define any UI stuff, so that's extra in .NET Core), but then your assembly would only be compatible with .NET Core.
In other words, if you want maximum portability, choose .NET Standard. If you want more features and only need to support the .NET Core implementation, choose .NET Core.
| {
"pile_set_name": "StackExchange"
} |
Q:
Expected foo.rb to define Foo - in my case
Fellas! I've run into the
Expected foo.rb to define Foo
problem.
I can't figure out what the hell is the solution. I have run the rails console and asked for that model to have a more detailed errore code. I got this:
irb(main):002:0> c = Card_positions.find(1)
NameError: uninitialized constant Card_positions
from (irb):2
from C:/Programozas/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/
rails/commands/console.rb:44:in `start'
from C:/Programozas/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/
rails/commands/console.rb:8:in `start'
from C:/Programozas/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/
rails/commands.rb:23:in `<top (required)>'
from C:/Programozas/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_req
uire.rb:59:in `require'
from C:/Programozas/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_req
uire.rb:59:in `rescue in require'
from C:/Programozas/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_req
uire.rb:35:in `require'
from script/rails:6:in `<main>'
Solution ideas?
A:
For a table named card_positions, you should be doing CardPosition.find(1).
| {
"pile_set_name": "StackExchange"
} |
Q:
Форматирование вывода в numpy?
Стало интересно, как производится форматирование в numpy as np. При генерации рандомной строки / массива, необходимо оставить два знака после запятой, но хотелось бы сохранить их для дальнейшего вывода.
Собственно сам код:
import numpy as np
def randoms():
return np.random.uniform(65.0, 70.0, 4)
exchange_1 = randoms()
exchange_1_twosigns = []
for i in exchange_1:
x = round(i, 2)
exchange_1_twosigns.append(x)
Код получился длинный и не красивы, я только учусь. Возможно есть решение и проще, но я не смог его подобрать / найти.
Спасибо большое!
A:
Еще можно воспользоваться методом set_printoptions и установить параметр precision, который отвечает за то сколько знаков после запятой выводится.
Это изменит только печать для всех массивов, при этом сам массив будет оставаться с необходимой точностью.
import numpy as np
np.set_printoptions(precision=2)
arr = np.random.random_sample((5))
print(arr)
| {
"pile_set_name": "StackExchange"
} |
Q:
Error in `./a.out': free(): invalid next size (normal) while freeing dynamically allocated 2D array of struct
Basically, I am creating 2D array of struct using calloc(). Then I utilize that array and I free that allocated space, while freeing it I am getting "double free or corruption (!prev)". Code is written in C language.
Code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <fcntl.h>
#include <malloc.h>
#include <unistd.h>
#include <string.h>
#include <float.h>
typedef struct complex_num{
double real;
double imag;
}comp;
void transpose(comp *arr, int height, int width);
void change(comp *arr, int width);
void main(){
int width = 64, height = 64;
int len = width;
comp *fft[len];
for(int i=0; i<len; i++){
fft[i] = (comp *)calloc(len, sizeof(comp));
}
for (int scan=0;scan<height;scan++){
for (int pix=0;pix<width;pix++){
fft[scan][pix].real = 1.0;
fft[scan][pix].imag = 0.0;
}
change(&fft[scan][0], len);
}
transpose(&fft[0][0], len, len);
for(int i=0;i<len;i++){
change(&fft[i][0], len);
}
transpose(&fft[0][0], len, len);
for(int i=0;i<len;i++){
free(fft[i]);
}
}
void transpose(comp *arr, int height, int width){
comp var;
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
if(j>i){
var = *((arr + (i*width)) + j);
*((arr + i*width) + j) = *((arr + j*width) + i);
*((arr + j*width) + i) = var;
}
}
}
}
void change(comp *arr, int width){
for(int i=0; i<width; i++){
(arr + i)->real = 5.0;
(arr + i)->imag = 6.9;
}
}
Error message:
*** Error in `./a.out': double free or corruption (!prev): 0x0000000002095010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f05108a77e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f05108b037a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f05108b453c]
./a.out[0x400880]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f0510850830]
./a.out[0x400509]
======= Memory map: ========
00400000-00401000 r-xp 00000000 00:00 467935 /path/to/a.out
00600000-00601000 r--p 00000000 00:00 467935 /path/to/a.out
00601000-00602000 rw-p 00001000 00:00 467935 /path/to/a.out
02095000-020b6000 rw-p 00000000 00:00 0 [heap]
7f050c000000-7f050c021000 rw-p 00000000 00:00 0
7f050c021000-7f0510000000 ---p 00000000 00:00 0
7f0510610000-7f0510626000 r-xp 00000000 00:00 360788 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f0510626000-7f0510825000 ---p 00000016 00:00 360788 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f0510825000-7f0510826000 rw-p 00015000 00:00 360788 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f0510830000-7f05109f0000 r-xp 00000000 00:00 360750 /lib/x86_64-linux-gnu/libc-2.23.so
7f05109f0000-7f05109f9000 ---p 001c0000 00:00 360750 /lib/x86_64-linux-gnu/libc-2.23.so
7f05109f9000-7f0510bf0000 ---p 000001c9 00:00 360750 /lib/x86_64-linux-gnu/libc-2.23.so
7f0510bf0000-7f0510bf4000 r--p 001c0000 00:00 360750 /lib/x86_64-linux-gnu/libc-2.23.so
7f0510bf4000-7f0510bf6000 rw-p 001c4000 00:00 360750 /lib/x86_64-linux-gnu/libc-2.23.so
7f0510bf6000-7f0510bfa000 rw-p 00000000 00:00 0
7f0510c00000-7f0510c25000 r-xp 00000000 00:00 360690 /lib/x86_64-linux-gnu/ld-2.23.so
7f0510c25000-7f0510c26000 r-xp 00025000 00:00 360690 /lib/x86_64-linux-gnu/ld-2.23.so
7f0510e25000-7f0510e26000 r--p 00025000 00:00 360690 /lib/x86_64-linux-gnu/ld-2.23.so
7f0510e26000-7f0510e27000 rw-p 00026000 00:00 360690 /lib/x86_64-linux-gnu/ld-2.23.so
7f0510e27000-7f0510e28000 rw-p 00000000 00:00 0
7f0510e30000-7f0510e31000 rw-p 00000000 00:00 0
7f0510e40000-7f0510e41000 rw-p 00000000 00:00 0
7f0510e50000-7f0510e51000 rw-p 00000000 00:00 0
7f0510e60000-7f0510e61000 rw-p 00000000 00:00 0
7fffc47c7000-7fffc4fc7000 rw-p 00000000 00:00 0 [stack]
7fffc5242000-7fffc5243000 r-xp 00000000 00:00 0 [vdso]
Aborted (core dumped)
I am compiling my code with GCC version 5.4.0. I don't understand the error message and don't know how to debug it. What should I do to free the array of pointers?
A:
transpose blatantly accesses elements outside of the array bounds.
fft in main is an array of pointers. Each pointer is initialized to point to a block of dynamically allocated memory (via calloc).
It looks like this in memory:
0 1 63
fft: 0 [ 0x0000a000 ] ----> [ real; imag | real; imag | ... | real; imag ]
1 [ 0x0000ff08 ] ----> [ real; imag | real; imag | ... | real; imag ]
.
.
.
63 [ 0x0001041c ] ----> [ real; imag | real; imag | ... | real; imag ]
fft has 64 elements, each of which is a pointer. In this example, fft[0] has the value 0x0000a000, at which address there is another 64-element array (created by calloc), which stores values of type comp (which is a 2-element struct).
Thus *fft[0] is the first comp struct (at address 0x0000a000), *fft[1] is the second comp struct (at address 0x0000a010), *fft[2] is the third comp struct (at address 0x0000a020), etc. Each comp struct takes 16 bytes, so the addresses increase by 16 (0x10). The last element of fft[0], fft[0][63] lives at address 0x0000a3f0.
fft[1] is the second pointer, pointing to a second (unrelated) block of memory (also created by calloc). In this example the instances of comp live at addresses 0x0000ff08, 0x0000ff18, 0x0000ff28, etc.
The same thing happens for all elements of fft, up to fft[63]. In this example the comp instances fft[63][0], fft[63][1], fft[63][2], etc. live at addresses 0x0001041c, 0x0001042c, 0x0001043c, etc.
Now consider what transpose does. It is called like this:
transpose(&fft[0][0], len, len);
It accesses memory like this:
*((arr + (i*width)) + j)
Here arr is the first parameter; its value is &fft[0][0], which is the same as fft[0], which in our example is 0x0000a000.
width is 64. i and j are somewhere between 0 and 63, depending on which loop iteration we're in. Let's assume they're at 63.
Then i*width is 63*64 is 4032, and arr + 4032 is a pointer to the 4033rd element of the array. But wait! There is no such element; arr only has 64 elements.
We're now at memory address 0x00019c00, which is far outside the bounds of fft[0] (recall that its elements only go up to address 0x000a3f0).
But we're not done yet: To this pointer we add j (63), giving 0x00019ff0. And this pointer is what we dereference with *.
Had we written this operation using array notation, it would have looked like
arr[i*width + j]
which more obviously shows that we're accessing element 4095 of a 64-element array.
transpose even writes to this address:
*((arr + i*width) + j) = ...
This modifies memory that your program doesn't own, thus corrupting the internal data structures used by malloc / calloc / free. That's what the error message double free or corruption means: Your code has corrupted data that was needed for free, which can happen by freeing the same pointer twice ("double free") or just writing to memory past the end of your arrays (as in your code).
To fix your code, change transpose to
void transpose(comp **arr, int height, int width) {
for (int i = 0 ; i < height; i++) {
for (int j=0; j < width; j++) {
if (j > i) {
comp var = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = var;
}
}
}
}
and call it as
transpose(fft, len, len);
This way you don't just pass the address of the first sub-array, but the address of the intermediate pointer array (which in turn lets you access any of the 64 sub-arrays).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this IC "MC1MX31LDVMN5D"?
Would you please help me to know this IC.
A:
That is a Freescale i.MX31 "Applications Processor" based on an Arm11 core which apparently has some hardware image processing support.
You can read all about it on Freescale's website.
To an extent, figuring something like this out depends on having enough sense of what is out there to recognize which letters and numbers in the agglomeration are key, and then doing a search on those. So for example, in this case, knowing that "imx" was a processor family.
An "application processor" tends to be a step up from a microcontroller and differ by relying on external memories and often having an MMU. Architecturally it might not be that different from say a trailing edge tablet SoC, and sometimes can run a full operating system like Linux, but is generally much less powerful (ie, slower) and may often be used with a more compact embedded operating system or RTOS.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cohomologies of anticanonical sheaf of blow-up of $\mathbb{P}^2$ in 9 points
Let $\pi:X\to\mathbb{P}^2$ be a blow-up of $\mathbb{P}^2$ in 9 points (in general position for example, but it doesn't matter). Then the canonical divisor of $X$ is equal $K_X=-3\pi^*H+\sum\limits_{k=1}^9E_k$, where $E_k$, $k=1,...,9$ are exceptional divisors. It is known and not hard to compute that $-K_X\sim C$, where $C$ is a proper transform cubic curve on $\mathbb{P}^2$, which passes through that 9 points. I want to compute $H^i(X, \mathcal{O}_X(-K_X))$. By Riemann-Roch, $\chi(\mathcal{O}_X(-K_X))=1$. From the identification of $-K_X$ we need to compute $H^i(X, \mathcal{O}_X(C))$.
Let us write the exact sequence
$$0\to\mathcal{O}_{X}\to\mathcal{O}_{X}(C)\to\mathcal{O}_{C}(C)\to0.$$
But $C\cdot C=K_X\cdot K_X=0$, so the third term is actually $\mathcal{O}_{C}$.
Taking the long exact sequence of cohomologies we obtain
$$0\to H^0(X,\mathcal{O}_{X})\to H^0(X,\mathcal{O}_{X}(C))\to H^0(C,\mathcal{O}_{C})\to0.$$
Thus $\text{dim}\,H^0(X, \mathcal{O}_X(-K_X))=2$. But this result doesn't coincide with the result from Sándor Kovács's answer for the following question:
https://mathoverflow.net/questions/107345/blowing-up-general-k-points-on-the-plane
Where is my mistake?
A:
As you rightly say, $O_C(C)$ is a line bundle of degree zero on $C$, but that doesn't mean it's the trivial bundle. (Remember $C$ is an elliptic curve, so it has lots of non-trivial degree zero line bundles.)
In fact $O_C(C) \simeq O_C$ if and only if the 9 blowup points are the intersection of two cubic curves in the plance, in which case the result $h^0(-K_X)=2$ is completely correct. Otherwise, $O_C(C)$ is a non-trivial degree zero bundle on $C$, in which case $h^0(O_C(C))=0$ and hence $h^0(-K_X)=1$, as you expect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequelize.js: join tables without associations
Is there a way to join tables that don't have associations defined using include in sequelize? This is not a duplicate of this. I am talking about tables that are not associated at all but having columns that I want to join on.
Example:
select * from bank
left outer join account
on account.bank_name = bank.name
The above query will return all records in table bank regardless of the existence of an account record where the specified constraints apply.
In sequelize this would look something like the following, if models bank and account were associated on account.bank_name = bank.name:
bank.findAll({
include: [{
model: account,
required: false,
}]
})
However, what if the models are not associated? Is there a way to write my own custom on section or equivalent:
bank.findAll({
include: [{
model: account,
required: false,
on: {
bank_name: Sequelize.col('bank.name')
}
}]
})
I vaguely remember reading something about this but I cannot seem to find that doc anywhere now. If you can point to the correct section in the docs it would be greatly appreciated.
A:
It seem that while it is possible to define a custom on condition, it is not possible to include relations without defining associations first. This is implied by the documentation wording for findAll method (search for options.include on page):
A list of associations to eagerly load using a left join. Supported is either { include: [ Model1, Model2, ...]} or { include: [{ model: Model1, as: 'Alias' }]} or { include: ['Alias']}. If your association are set up with an as (eg. X.hasMany(Y, { as: 'Z }, you need to specify Z in the as attribute when eager loading Y).
The docs on options.include[].on are even more terse:
Supply your own ON condition for the join.
I ended up solving my problem using Postgres views as a workaround. It is also possible to inject a raw query and bypass sequelize limitations but I would use that only as a development / prototyping hack and come up with something more robust / secure in production; something like views or stored procedures.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete identity value using IDENT_CURRENT()
I have the following table:
CREATE TABLE MyTable
(
ID INT NOT NULL identity(1,1),
Name NVARCHAR(50) NOT NULL
);
I need to delete from MyTable two records: first one with last identity value in the MyTable and second one with last identity value in the current session.
To clarify: it must be done using IDENT_CURRENT('MyTable'), SCOPE_IDENTITY() or maybe @@IDENTITY.
Please help with your suggestions.
A:
You have to use @@IDENTITY to get last identity used in the current session and
IDENT_CURRENT('MyTable') to get last identity used in this table
DELETE FROM MyTable
WHERE ID IN (SELECT IDENT_CURRENT('MyTable'))
OR ID = @@IDENTITY
Read this Article for more info
EDIT1
if you want to delete last identity value found in a table you can use MAX() aggregate function
DELETE FROM MyTable
WHERE ID = (SELECT MAX(ID) FROM MyTable WHERE ID <= @@IDENTITY)
Note: IDENT_CURRENT('MyTable'), SCOPE_IDENTITY() AND @@IDENTITY are not depending on the values stored in tables
| {
"pile_set_name": "StackExchange"
} |
Q:
Parallel threads with TensorFlow Dataset API and flat_map
I'm changing my TensorFlow code from the old queue interface to the new Dataset API. With the old interface I could specify the num_threads argument to the tf.train.shuffle_batch queue. However, the only way to control the amount of threads in the Dataset API seems to be in the map function using the num_parallel_calls argument. However, I'm using the flat_map function instead, which doesn't have such an argument.
Question: Is there a way to control the number of threads/processes for the flat_map function? Or is there are way to use map in combination with flat_map and still specify the number of parallel calls?
Note that it is of crucial importance to run multiple threads in parallel, as I intend to run heavy pre-processing on the CPU before data enters the queue.
There are two (here and here) related posts on GitHub, but I don't think they answer this question.
Here is a minimal code example of my use-case for illustration:
with tf.Graph().as_default():
data = tf.ones(shape=(10, 512), dtype=tf.float32, name="data")
input_tensors = (data,)
def pre_processing_func(data_):
# normally I would do data-augmentation here
results = (tf.expand_dims(data_, axis=0),)
return tf.data.Dataset.from_tensor_slices(results)
dataset_source = tf.data.Dataset.from_tensor_slices(input_tensors)
dataset = dataset_source.flat_map(pre_processing_func)
# do something with 'dataset'
A:
To the best of my knowledge, at the moment flat_map does not offer parallelism options.
Given that the bulk of the computation is done in pre_processing_func, what you might use as a workaround is a parallel map call followed by some buffering, and then using a flat_map call with an identity lambda function that takes care of flattening the output.
In code:
NUM_THREADS = 5
BUFFER_SIZE = 1000
def pre_processing_func(data_):
# data-augmentation here
# generate new samples starting from the sample `data_`
artificial_samples = generate_from_sample(data_)
return atificial_samples
dataset_source = (tf.data.Dataset.from_tensor_slices(input_tensors).
map(pre_processing_func, num_parallel_calls=NUM_THREADS).
prefetch(BUFFER_SIZE).
flat_map(lambda *x : tf.data.Dataset.from_tensor_slices(x)).
shuffle(BUFFER_SIZE)) # my addition, probably necessary though
Note (to myself and whoever will try to understand the pipeline):
Since pre_processing_func generates an arbitrary number of new samples starting from the initial sample (organised in matrices of shape (?, 512)), the flat_map call is necessary to turn all the generated matrices into Datasets containing single samples (hence the tf.data.Dataset.from_tensor_slices(x) in the lambda) and then flatten all these datasets into one big Dataset containing individual samples.
It's probably a good idea to .shuffle() that dataset, or generated samples will be packed together.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble converting JSON to data with Swift
I am trying to learn Swift. One of my projects is to try to retrieve JSON data from an internal web service (a group of Python CGI scripts) and convert it into a Swift object. I can do this easily in Python, but I am having trouble doing this in Swift. Here is my playground code:
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let endpoint: String = "http://pathToCgiScript/cgiScript.py"
let url = NSURL(string: endpoint)
let urlrequest = NSMutableURLRequest(URL: url!)
let headers: NSDictionary = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"]
urlrequest.allHTTPHeaderFields = headers as? [String : String]
urlrequest.HTTPMethod = "POST"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlrequest) {
(data, response, error) in
guard data != nil else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("Error calling script!")
print(error)
return
}
do {
guard let received = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as?
[String: AnyObject] else {
print("Could not get JSON from stream")
return
}
print(received)
} catch {
print("error parsing response from POST")
}
}
task.resume()
I know making a 'POST' to retrieve data may look odd, but that is how the system is set up. I keep on getting:
Could not get data from JSON
I checked the response, and the status is 200. I then checked the data's description with:
print(data?.description)
I got an unexpected result. Here is a snippet:
Optional("<0d0a5b7b 22535441 54555322 3a202244 6f6e6522 2c202242 55535922...
I used Mirror, and apparently the type is NSData. Not sure what to make of this. I have tried to encode the data with base64EncodedDataWithOptions. I have tried different NSJSONReadingOptions as well to no avail. Any ideas?
Update:
I used Wireshark to double check the code in the Playground. Not only was the call made correctly, but the data being sent back is correct as well. In fact, Wireshark sees the data as JSON. The issue is trying to turn the JSON data into a Swift object.
A:
I figured out what was wrong. I was casting to the wrong type. This is the new code:
guard let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [AnyObject]
The JSON was not returning an array of dictionaries but an array of objects.
| {
"pile_set_name": "StackExchange"
} |
Q:
Live editing in Django
Imagine you have an address book card. Normally the fields are displayed as static text, in a specific layout (imagine having multiple phone numbers, emails etc.). When editing it, you want to use the same layout, but with form fields instead of static text. It seems that the normal way of doing this in Django is to use separate views and templates, which forces you to duplicate all of the layout markup (ie, it's not DRY), and to change pages to switch between browsing and editing mode.
It would be nicer if you could switch in and out of editing mode on the fly, using JavaScript to replace the static text with form fields and vice versa, and Ajax to send changes to the server. I'm calling this "live editing", but perhaps there is a better term. At any rate, is there a recommended way of doing this in Django?
I was thinking of rendering, for each field, both a static and an editable version, and using JavaScript to hide and show them as needed. But I also need to update the static fields with new data from the server, and I need to take into account inline forms, and complex fields such as images (where the static display is an <img> tag, and you have to update the src after an upload). And I might also need to add and remove fields or fieldsets dynamically (again, consider inline formsets).
All in all, it'll take a lot of code. Is there an existing solution for Django, or a recommended approach? Otherwise, which JavaScript framework might be most helpful for this?
A:
https://pypi.python.org/pypi/django-inplaceedit#information does exactly what you have asked for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why didn't the hotel's angels become real?
In 6x11 The God Complex, the Doctor and his companions encounter
two weeping angels, that are merely illusions and therefore discarded as harmless.
However, back in 5x04 The Time of Angels, it was established that
"That which holds the image of an Angel becomes itself an Angel".
So, why didn't they become real, or probably more correctly, why didn't the hotel or at least the room effectively become one?
A:
The only right answer is "we don't know." because no one at the hotel bothered to ask or explain it.
But based on the behavior of the angels in "The Time of Angels" there are two possible answers:
They didn't last long enough. Note that the video image of the Weeping Angel did not immediately turn into an angel capable of attacking Amy; it was only after the video had been on repeat for a while that it began to manifest. Similarly, the angel in Amy's eye manifested slowly, lasting well into the next episode without taking her mind over. In other words, we don't know how much time it takes for an image of an angel to become an angel in its own right. The images from the hotel may simply have gone away too fast.
They weren't really images of angels. This requires us to interpret the warning very literally: an image of an actual Weeping Angel will itself become an angel. Note that the image on the video, and the image in Amy's eye, were both images of a previously existing angel that was captured in the image. We don't know if the images from the hotel were images of real angels, or simply generic "computer generated" images based on how Gibbis saw them in his mind. It's possible that the images from the hotel simply didn't count as "images of an angel" on a technicality.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are these sphere-like things on my Camellia azalea tree?
There are about 3 of these sphere things on my Camellia azalea tree/shrub. Can anyone tell me what they are? Are they harmful?
Also, the leaves are browning at the tips and falling. Is that due to not enough water or too much?
Click on pictures for larger size.
A:
They seem to me just fruits.
Here in South of Italy or in islands they often make fruits.
It could seem a parasitic fungus (Exobasidium rhododendri), known here as "afloat Rhododendron".
click for fungus
This parasitic fungus, however, is growing on the leaves, branches and any other part of the plant.
Your "balls" come right from flowers faded. So they seem really fruits.
The leaves seem suffering from Phytophthora ramorum see here
Camellia symptoms are limited to leaf spots, which can vary in size from a half a centimeter in diameter to covering nearly half the leaf, depending on environmental conditions. Lesions are usually on the leaf tip or leaf edge, and can be surrounded by diffuse margins or thick black zone lines. Plants will drop their infected leaves, and the lower part of the plant can defoliate.
Then: less water, shadow, "few fertilizer" for acidophilic plants.
A:
Totally agree that they're fruits, or seed cases - were they Camellia Gall, they'd be protruding from the woody branches, not where flowers have been.
As for the browning, it might be something serious like a phytophthera infection, or it might well be that the plant is in a pot and may have run out of root room and needs a bigger pot, so I'd be checking what's going on with the root ball before fretting about a serious infection for which there is no really effective treatment anyway. Also, given this is a Camellia azalea, about which you have already asked a question, there isn't a huge amount of info about this particular plant (see my previous answer) other than the fact it does much better with sun exposure than the more common forms of Camellia.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java JFrame adding browse button with field
How do I create in Java a GUI to allow a user to enter a directory into a text field and have a browse button next to it, so they can chose the folder easier? I need to do this using JComponents hopefully. Like the last entry shown here: http://www.adobe.com/support/dreamweaver/assets/flashbutton/images/ss5insertdialog.gif
A:
Use a JTextField and JFileChooser
You have a demo here :
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
http://www.exampledepot.com/egs/javax.swing.filechooser/CreateDlg.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Some Sitecore 8 conditions for conditional renderings seem missing in Sitecore 9
I tried to use some of the OOTB conditional rendering rules for personalization I had running in a Sitecore 8 instance, after upgrade/migrate to Sitecore 9 and ran into the fact that some of them no longer work.
I first noticed this with the rule:
where the referrer [operatorid,StringOperator,,compares to] [Referrer,,,specific value]
which is defined in item:
/sitecore/system/Settings/Rules/Definitions/Elements/Visit/Referrer
For some reason, this rule is not working in Sitecore 9
A:
[Answering my own question here]
After some digging I found that this rule, which has as 'Type' definition:
Sitecore.ExperienceAnalytics.Aggregation.Rules.Conditions.ReferrerCondition,Sitecore.ExperienceAnalytics
Actually is nowhere to be found in the Sitecore 9 Sitecore.ExperienceAnalytics assemblies.
So I decided to file a Sitecore support ticket.
The conversation I had was the following:
Hello Joost,
The issue here is that "The rules items were supposed to be removed". Starting from 9.0 Experience Analytics stopped using these rules and they were replaced by the new segmentation rules, So all the rule items and the related types were removed from Experience Analytics libraries but rule items under /sitecore/system/Settings/Rules/Definitions/Elements/Visit/* were not removed.
This has been registered as a bug.
To track the future status of this bug report, please use the reference number 198463. More information about public reference numbers can be found here:
https://kb.sitecore.net/articles/853187
The whole architecture was replaced with the new segmentation rules, So there are no rule items anymore (i.e., items inheriting from rule template defined in /sitecore/templates/System/Rules) instead we created our own rules using our own template which is /sitecore/templates/System/Experience Analytics/Segment. E.g., the rule ‘/sitecore/system/Settings/Rules/Definitions/Elements/Visit/Visit language’ was replaced by the segment ‘/sitecore/system/Marketing Control Panel/Experience Analytics/Dimensions/Visits/By language/All visits by language’
Please refer to the below link for creating a new segment and a custom filter which could help you if you are attempting to use those rules in Experience Analytics (e.g., creating a custom filter that filter customers with the age > 20, Adding this filter to a custom segment which is a child to a dimension ‘/sitecore/system/Marketing Control Panel/Experience Analytics/Dimensions/Visits/By language’ would result in having this segment showing customers with the age > 20 by language.
https://doc.sitecore.net/sitecore_experience_platform/analyzing_and_reporting/analytics/configuring/create_a_custom_report_filter_and_segment
Kind regards,
Hi ***,
thanks that explains that. But it doesn’t explain why all these rules are still available for personalization but don’t seem to work. What should we do to use them in personalization?
thnx
Edited by *** on Monday, May 21, 2018 at 2:50 PM (UTC)
Hi Joost,
Thank you for the update.
What should we do to use them in personalization?
As far as the implementation of those conditions was removed from the code of the Sitecore 9 release and the corresponding condition items will be removed in the next releases, the way you should follow if you want to use the same conditions in personalization rule is to implement your own custom conditions:
To create a custom rule (condition) for personalization and learn about rule engine you can refer to the following posts:
https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/rules-engine-implementations-with-the-sitecore-asp-net-cms
Please do not hesitate to contact us in case you need any additional assistance regarding this issue.
So this means that actually to have these kind of rules, used by for example conditional renderings, we need to implement them ourselves.
It is quiet tricky as these item definitions still exist and show up in your conditions/rule book when creating personalization conditions, but they don't actually work in Sitecore 9.
So far I see that a lot of items under: /sitecore/system/Settings/Rules/Definitions/Elements/Visit
Seem to be defined in the Sitecore.ExperienceAnalytics.Aggregation.Rules.Conditions namespace which no longer exist. There may be more, so if you want to be sure, or if you run into such rules no longer working, make sure to do a quick check on this item/type definition and whether or not it still exists to prevent you from breaking your head on what you are doing wrong in your code/setup.
| {
"pile_set_name": "StackExchange"
} |
Q:
inject dependency into filter for unit test
I am injecting the filter into my tests but I am getting an error because the filter has a dependency on underscore. How can I inject my underscore wrapper into the filter before injecting it into
Error msg:
Error: [$injector:unpr] Unknown provider: _Provider <- _ <- requestedDataFilter
jasmine test:
beforeEach(function () {
module('myApp');
inject(function (_requestedData_) {
requestedData = _requestedData_;
});
});
it("should exist", function () {
expect(angular.isFunction(requestedData)).toBeTruthy();
});
Filter :
angular.
module("myApp").
filter("requestedData", [
"_",
function (_) {
"use strict";
var
getRequestedData = function (index, filters, dataTable) {
var
filter = filters[index],
requestedData;
if (filter.items.length > 0) {
requestedData = _.filter(dataTable, function (row) {
return _.contains(filter.items, row[filter.index]);
});
} else {
requestedData = dataTable;
}
return (++index < filters.length ? getRequestedData(index, filters, requestedData) : requestedData);
};
return getRequestedData;
}]);
A:
Is your underscore wrapper part of your "MyApp" module? If not, make sure you load the module that contains your wrapper into your test.
beforeEach(function () {
module("underscore");//add underscore wrapper module
module("myApp");
inject(function (_requestedData_) {
requestedData = _requestedData_;
});
});
it("should exist", function () {
expect(angular.isFunction(requestedData)).toBeTruthy();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
not able to get result length from ms crm web api call output in js
Below is my code snippet. I am trying to fetch all the Referenced Entities from ManyToOne Relationship of Annotation entity. In the result, I am able to get the object but when I'm trying to get the length of it, its giving "undefined". Please provide your valuable suggestions on this and how can we assign the Referenced Entity to a variable from result.
OR
is there any possibility to retrieve all the entities that are associated with Annotation entity, using Web API Call ( Dynamics 365).
function fetchIt()
{
var req = new XMLHttpRequest();
var webAPICall = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/EntityDefinitions(LogicalName='annotation')?$select=LogicalName&$expand=ManyToOneRelationships($select=ReferencedEntity)";
req.open("GET", webAPICall, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function ()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
alert("results.valuelength: " +results.value.length);
for (var i = 0; i < results.value.length; i++)
{
var referencedEntity = results.value[i]["ReferencedEntity"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
}
A:
You have two problems
You never send your request. You're missing req.send()
It won't be results.value it will be results.ManyToOneRelationships
Then it will work
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple way of aligning text to the top left corner of a cell in a TableView?
I have some text in a cell in a TableView which I would like to appear on the top left corner of the cell.
Aligning the text to the left was simple enough, using:
cell.textLabel?.textAlignment = NSTextAlignment.left
However, all the solutions I have found for aligning the text vertically to the top are very convoluted.
Is there a simple way to do this I am unaware of?
Here is my layout, I do not have customised cells.
A:
Declare the cell as below:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell
// to do: additional code
return cell
}
After that define the UserCell class:
class UserCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
textLabel?.frame = CGRect(x: 0, y: 0, width: textLabel!.frame.width, height: textLabel!.frame.height)
textLabel?.backgroundColor = UIColor.red //only for demonstration
textLabel?.sizeToFit()
//detailtextlabel code
}
}
I think you are looking for the output like below:
| {
"pile_set_name": "StackExchange"
} |
Q:
ENS: how to compute namehash from name in a smart contract?
using Solidity in a smart contract, how is the namehash computed from name ("foo.eth") ?
A:
formal specifications on https://eips.ethereum.org/EIPS/eip-137
function computeNamehash(string _name) public pure returns (bytes32 namehash) {
namehash = 0x0000000000000000000000000000000000000000000000000000000000000000;
namehash = keccak256(
abi.encodePacked(namehash, keccak256(abi.encodePacked('eth')))
);
namehash = keccak256(
abi.encodePacked(namehash, keccak256(abi.encodePacked(_name)))
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
not able to use ssh within a shell script
I have this shell script which ssh to other server, find few specific files(.seq files older than 50 mnts) and writes their name to another file.
#! /usr/bin/bash
while read line
do
#echo $line
if [[ $line =~ ^# ]];
then
#echo $line;
continue;
else
serverIP=`echo $line|cut -d',' -f1`
userID=`echo $line|cut -d',' -f2`
fi
done < sftp.conf
sshpass -p red32hat ssh $userID@$serverIP
cd ./perl
for files in `find -name "*.seq" -mmin +50`
do
#sshpass -p red32hat scp *.seq root@rinacac-test:/root/perl
echo $files>>abcde.txt
done
exit;
#EOF
Now problem is that when I run it.. neither it writes to abcde.txt file nor it is exiting from the remote server. when I manually execute the exit command...it exists saying "perl no such file or directory"... while I have perl sub directory in my home directory..
other thing is when I run the for loop portion of the script on the 2nd server(by directly logging into it) it is working fine and writing to abcde.txt filr...please help...
A:
ssh takes commands either on standard input or as the last parameter. You can therefore do this (very dynamic but tricky to get the expansions right):
ssh user@host <<EOF
some
custom
commands
EOF
or this (less dynamic but can take simple parameters without escaping):
scp my_script.sh user@host:
ssh user@host './my_script.sh'
| {
"pile_set_name": "StackExchange"
} |
Q:
What does 'put some dust on your face' mean?
The Eisbrecher song Fanatica has the line "let me put some dust on your face". I assume this is a literal translation of a German expression, but I can't figure out what it means.
A:
I am not aware of a corresponding German expression, certainly not a common one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript memory leak cleanup in window.unload
Javascript client side application.
Trying to eliminate memory leaks leads to ugly (to say the least) code.
I am trying to clean up in window.unload instead on messing up all the code trying to avoid them.
We use mostly element.onevent=function(){..}; pattern, that results in closure (mostly wanted) and memory leak.
We do not use javascript frameworks.
Are there any ideas on how to clean up properly on exit?
Has anyone do the same or are you trying to avoid them?
A:
The best solution is for you to roll out your own method that manages event handling. Therefore, when attaching an event handler, your method can keep track of all the added events. On unload, it can unregister all the handlers.
I know you said you don't use libraries, but you can use their code as inspiration. Ext-js does that when you use Ext.EventMgr.addListener.
Here's a simple EvtMgr obj that you can use to get started. It's very simplistic, I can't write it all for you here. Feel free to ask questions about things that you'd like and don't know how to do. Also note that I wouldn't use the element.onclick method since you can only add a single handler. I'm doing it that way because you said that's how you do it.
var EvtMgr = (function(){
var listenerMap = {};
// Public interface
return {
addListener: function (evtName, node, handler) {
node["on" + evtName] = handler;
var eventList = listenerMap[evtName];
if (!eventList) {
eventList = listenerMap[evtName] = [];
}
eventList.push(node);
},
removeAllListeners: function() {
for (var evtName in listenerMap) {
var nodeList = listenerMap[evtName];
for (var i=0, node; node = nodeList[i]; i++) {
node["on" + evtName] = null;
}
}
}
}
})();
Also, beware that handlers with closures is not the only way to create leaks. See my comment on this question Javascript memory leaks after unloading a web page
Also, I don't understand why some people are afraid of libraries. jquery is tiny, ext core is too. They can be dangerous if you use them without understanding js. But if your js skills are solid, you save a lot of work by reusing their code. I get under the hood of ext-js every single day when I need to understand how somethings is done. This was how I gave you these few lines of code.
Another think to think about when managing memory leaks is to make sure you remove handlers when removing elements from the DOM (node.innerHTML or any other way). If you do that, you should remove handlers from the nodes you've removed from the DOM. There's some work to get that working but it should be part of your strategy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to add the Stackapplet to panel
I'm running Ubuntu 10.10, and am trying to add the StackApplet to the panel.
The steps I'm following are, just to be sure I'm not doing something obviously wrong:
Right-click on the top panel
Click 'Add to Panel'
Select 'StackApplet' from the menu dialogue that appears.
Doing this causes a small, roughly 1px2, grey square to be added to the panel, but with no indication of why the StackApplet isn't responding/loading. I've tried adding to the panel, then restarting gdm and also adding to the panel and then restarting the system. Neither approach seemed to achieve anything.
I've also completely removed/purged, and then reinstalled, StackApplet via Synaptic in the hope that might fix any dependency issues, to no avail..
Obviously there is further information needed to answer this question, but at this stage I don't know enough about what information might be needed, or, in most cases, how to find it. I'll do my best to add any information requested in comments, though, to try and solve this.
My thanks in advance, for any and all help and guidance anyone can offer...
Questions I've read through prior to asking:
Stack applet was not starting automatically
Don't seem to have the file: ~/.xsession-errors
Didn't have, but did create, the file ~/.config/autostart/stackapplet.desktop with the contents suggested in the accepted answer.
Can't add to panel nor delete panel
Haven't tried reinstalling gnome-panel, yet, mainly because I've read elsewhere that this may cause a world of pain. If that's wrong, I'll happily give it a go, though.
How can I add the Network Manager Applet to the panel after removing?
Tried re-adding the notification area to the panel, which worked (in that it added the notifcation area), but didn't resolve the StackApplet problem.
Edited in response to @EvilPhoenix's answer:
StackApplet is run via a different system. run StackApplet from Applications > Accessories. It will then turn itself on then put itself automatically into the system tray
I don't appear to have StackApplet available in the Accessories menu:
Though I do have StackApplet installed (according, at least, to the Ubuntu Software Centre):
A:
The problem is that you are running an older version of StackApplet that is no longer supported and doesn't quite work as well.
You can find the new version (1.4.1 beta) in the StackApplet PPA.
What are PPAs and how do I use them?
A:
StackApplet is run via a different system. run StackApplet from Applications > Accessories. It will then turn itself on then put itself automatically into the system tray.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ - Finding nearest neighbor using opencv flann
I have two set of points (cv::Point2f): setA and setB. For each point in setA, I want to find its nearest neighbor in setB. So, I have tried two methods:
Linear search: for each point in setA, just simply scan through all points in setB to find nearest one.
Using opencv kd-tree:
_ First I built a kd-tree for setB using opencv flann:
cv::flann::KDTreeIndexParams indexParams;
cv::flann::Index kdTree(cv::Mat(setB).reshape(1), indexParams);
_ Then, for each point in setA I do query to find nearest neighbor:
kdTree.knnSearch(point_in_setA, indices, dists, maxPoints);
Note: I set maxPoints to 1, cause I only need the nearest one.
I do a bit study, and come out with some time complexity for each case:
Linear search: O(M*N)
Kd-Tree: NlogN + MlogN => first term for building kd-tree, second term is for querying
Where M is number of points in setA, and N is for setB. And range of N: 100~1000, range of M: 10000~100000.
So, the kd-tree is supposed to run much faster than the linear search method. However, when I run the real test on my laptop, the result is kd-tree method is slower than linear search (0.02~0.03s vs 0.4~0.5s).
When I do profiling, I got hot spot at knnSearch() function, it takes 20.3% CPU time compares to 7.9% of linear search.
Uhm, I read some online articles, they said to query kd-tree it usually take logN. But I am not sure about how opencv implement it.
Anyone knows what's wrong here? Is there any parameter I should adjust in kd-tree or did I make mistake somewhere in the code or computation?
A:
Taken from the Flann documentation. For low dimensional data, you should use KDTreeSingleIndexParams.
KDTreeSingleIndexParams
When passing an object of this type the index will contain a single kd-tree optimized for searching lower dimensionality data (for example 3D point clouds), in your case 2D points. You can play with the leaf_max_size parameters and profile your results.
struct KDTreeSingleIndexParams : public IndexParams
{
KDTreeSingleIndexParams( int leaf_max_size = 10 );
};
max leaf size: The maximum number of points to have in a leaf for not
branching the tree any more
| {
"pile_set_name": "StackExchange"
} |
Q:
Concatenar varchar2 PLSQL
Possuo 2 tabelas com relacionamento 1 to many e preciso concatenar todos os valores da coluna Nome da tabela 2 em apenas uma coluna do select.
Ex.:
No exemplo, o retorno do que eu preciso seria Maria, João, José
Obs.: O banco é PLSQL.
A:
Jonathan Achei um exemplo bacana desse site
https://social.msdn.microsoft.com/Forums/sqlserver/pt-BR/6177bd7a-e2fc-46f4-9646-8fd1480cf14b/concatenar-valores-de-linhas-em-uma-coluna?forum=520
Tenho a seguinte tabela:
Codigo Cliente Produto
1 Jorge piso
1 Jorge porta
1 Jorge torneira
Preciso que o resultado deste select fique assim:
Codigo Cliente Produto
1 Jorge piso;porta;torneira
-- Concatenando
SELECT CODIGO,
CLIENTE,
COALESCE(
(SELECT CAST(PRODUTO AS VARCHAR(10)) + ';' AS [text()]
FROM TABELA AS O
WHERE O.CODIGO = C.CODIGO
and O.CLIENTE = C.CLIENTE
ORDER BY CODIGO
FOR XML PATH(''), TYPE).value('.[1]', 'VARCHAR(MAX)'), '') AS Produtos
FROM TABELA AS C
GROUP BY CODIGO,CLIENTE;
| {
"pile_set_name": "StackExchange"
} |
Q:
Feature Request : Combined Flair (not Network flair)
At present, there are 2 options for flairs.
Either the site specific flair (OR) The network Flair.
That is if I choose it from StackOverflow,
I can either use this
Or I can use this
So My feature request is Can We have a flair containing only Selected sites?
That is
If I want to only include Stack Overflow and Travel.se,
Then I may put something like this
https://stackexchange.com/users/flair/2824081.png?theme=clean&site=stackoverflow&site=travel
Another Case
If I want to show only Android SE and Meta SE,
I can use
https://stackexchange.com/users/flair/2824081.png?theme=clean&site=android&site=meta.se
A:
If you'd really like to customize flair that finely, you'll need to utilize the API and construct it yourself.
Adding options to a URL like that opens up a huge potential for abuse where users could chew up a lot of our resources creating flair images by just sending a flood of requests with differing options. Sure, flair images are cached for quite a while, but given the number of users and number of sites, it's easy to keep coming up with new ones that need generated. On-the-fly options like this just aren't doable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't read the Fairbank scale weight properly
I tried to connect the scale and retrieve the weight from visual studio 2013, but it's wire that sometimes I can get the exacted weight and sometimes I couldn't. I was not sure what's wrong with the code. Can someone help? My code is listed below
using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
namespace PortDataReceived
{
class PortData
{
public static void Main(string[] args)
{
try
{
string lineOne = "One";
string lineTwo = "Two";
char CarriageReturn = (char)0x0D;
string final = lineOne + CarriageReturn.ToString() + lineTwo + CarriageReturn.ToString();// define the hexvalues to the printer
SerialPort mySerialPort = new SerialPort("COM3");//initiate the new object and tell that we r using COM1
mySerialPort.BaudRate = 9600;
//mySerialPort.Parity = Parity.Odd;
//mySerialPort.StopBits = StopBits.Two;
//mySerialPort.DataBits = 7;
mySerialPort.Parity = Parity.Odd;
mySerialPort.StopBits = StopBits.Two;
mySerialPort.DataBits = 7;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 20;
mySerialPort.WriteTimeout = 50;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
//those r all the setting based on the scale requirement
/*foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
{
Console.WriteLine(port);
}*/
while (true)
{
mySerialPort.Open();
mySerialPort.Write(final);
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
//mySerialPort.Close();
}
catch (System.IO.IOException e)
{
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;
}
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
Console.ReadKey();
}
}
}
A:
Often with serial communication, you have to read multiple times, and concatenate each read, until you finally detect you've read the part that shows you've received it all. Detecting the end may be based on a specific count of bytes received, or it might be looking for a particular byte or sequence of bytes. But it's up to you to make that determination, and to continue reading until that condition is fulfilled. When you first read, there may be characters waiting, but the device has not sent them all yet, so you will have to read again almost immediately after your first read. You're dealing with a stream. The handler event fires when the stream starts, but it doesn't know how long the stream will flow.
This blog post discusses this and some other common serial port issues:
http://blogs.msdn.com/b/bclteam/archive/2006/10/10/top-5-serialport-tips-_5b00_kim-hamilton_5d00_.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
IN and NOT IN clause do not apply
So I have this query:
SELECT m.id, (
SELECT GROUP_CONCAT(
DISTINCT tag_id
ORDER BY tag_id
SEPARATOR '-'
) FROM tagging
WHERE mng_id = m.id
ORDER BY tag_id DESC
) as tags
FROM product m
INNER JOIN tagging tg ON (m.id = tg.mng_id)
WHERE 1
AND tg.tag_id IN (34,20) AND tg.tag_id NOT IN (42)
AND (nme LIKE 'tomo%' OR alt_nme LIKE 'tomo%')
GROUP BY m.id
This query should return records with tag # 34, 20 and do not have tag # 42, the record's name must start with 'tomo'.
But for some reason, it doesn't remove product with tag #42 from the results. Can any one help identify the issue with this query?
A:
If you want records with tags 34 and 20, but not 42, try something like this:
SELECT p.id
FROM product p INNER JOIN
tagging tg
ON p.id = tg.mng_id
GROUP BY p.id
HAVING SUM(tg.tag_id = 34) > 0 AND
SUM(tg.tag_id = 20) > 0 AND
SUM(tg.tag_id = 42) = 0;
If you want the resulting tags, just add group_concat(tg.tag_id).
This seems simpler than your approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
JEE6 REST Service @AroundInvoke Interceptor is injecting a null HttpServletRequest object
I have an @AroundInvoke REST Web Service interceptor that I would like to use for logging common data such as the class and method, the remote IP address and the response time.
Getting the class and method name is simple using the InvocationContext, and the remote IP is available via the HttpServletRequest, as long as the Rest Service being intercepted includes a @Context HttpServletRequest in its parameter list.
However some REST methods do not have a HttpServletRequest in their parameters, and I can not figure out how to get a HttpServletRequest object in these cases.
For example, the following REST web service does not have the @Context HttpServletRequest parameter
@Inject
@Default
private MemberManager memberManager;
@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Member add(NewMember member) throws MemberInvalidException {
return memberManager.add(member);
}
I have tried injecting it directly into my Interceptor, but (on JBoss 6.1) it is always null...
public class RestLoggedInterceptorImpl implements Serializable {
@Context
HttpServletRequest req;
@AroundInvoke
public Object aroundInvoke(InvocationContext ic) throws Exception {
logger.info(req.getRemoteAddr()); // <- this throws NPE as req is always null
...
return ic.proceed();
I would like advice of a reliable way to access the HttpServletRequest object - or even just the Http Headers ... regardless of whether a REST service includes the parameter.
A:
After researching the Interceptor Lifecycle in the Javadoc http://docs.oracle.com/javaee/6/api/javax/interceptor/package-summary.html I don't think its possible to access any servlet context information other than that in InvocationContext (which is defined by the parameters in the underlying REST definition.) This is because the Interceptor instance has the same lifecycle as the underlying bean, and the Servlet Request @Context must be injected into a method rather than the instance. However the Interceptor containing @AroundInvoke will not deploy if there is anything other than InvocationContext in the method signature; it does not accept additional @Context parameters.
So the only answer I can come up with to allow an Interceptor to obtain the HttpServletRequest is to modify the underlying REST method definitons to include a @Context HttpServletRequest parameter (and HttpServletResponse if required).
@Inject
@Default
private MemberManager memberManager;
@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Member add(NewMember member, @Context HttpServletRequest request, @Context HttpServletResponse response) throws MemberInvalidException {
...
}
The interceptor can then iterate through the parameters in the InvocationContext to obtain the HttpServletRequest
@AroundInvoke
public Object aroundInvoke(InvocationContext ic) throws Exception {
HttpServletRequest req = getHttpServletRequest(ic);
...
return ic.proceed();
}
private HttpServletRequest getHttpServletRequest(InvocationContext ic) {
for (Object parameter : ic.getParameters()) {
if (parameter instanceof HttpServletRequest) {
return (HttpServletRequest) parameter;
}
}
// ... handle no HttpRequest object.. e.g. log an error, throw an Exception or whatever
A:
Another work around to avoid creating additional parameters in every REST method is creating a super class for all REST services that use that kind of interceptors:
public abstract class RestService {
@Context
private HttpServletRequest httpRequest;
// Add here any other @Context fields & associated getters
public HttpServletRequest getHttpRequest() {
return httpRequest;
}
}
So the original REST service can extend it without alter any method signature:
public class AddService extends RestService{
@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Member add(NewMember member) throws MemberInvalidException {
return memberManager.add(member);
}
...
}
And finally in the interceptor to recover the httpRequest:
public class RestLoggedInterceptorImpl implements Serializable {
@AroundInvoke
public Object aroundInvoke(InvocationContext ic) throws Exception {
// Recover the context field(s) from superclass:
HttpServletRequest req = ((RestService) ctx.getTarget()).getHttpRequest();
logger.info(req.getRemoteAddr()); // <- this will work now
...
return ic.proceed();
}
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
python reference to a float, int, etc
As I understand it, there are no references in python to ints or floats or similar data. Nevertheless, I am working on a problem where it would be very convenient for me if I could do something like
a=1
b=2
c=3
ref_dict={'field1':ref_to_var_a,'field2':ref_to_var_b,'field3':ref_to_var_c}
and then
def update(field,value):
ref_dict[field]=value
And so if the user called
update('field2',5)
the value of b would become 5.
Is there any way this can be done? Thanks.
In response to arbanert's helpful comment and answer, what I really want to do is -- surprise, surprise -- more complicated. I am building a GUI with wxPython. I have many TextCtrl controls, each of which will set the value of one variable. Of course, I could write one method for each control, or I could write a single method, which would look something like
def handleTextEvent(self,event):
if (event.GetEventObject() == widget1):
a=int(event.GetString)
elif (event.GetEventObject() == widget2):
b= ....
I think you can see why I don't like this either. It would be nice if I could just do one short function like:
def handleTextEvent(self,event):
ref_dict[event.GetEventObject()]=int(event.GetString())
And, yes, I am very new with wxPython.
Thanks!
A:
This is possible, but it's almost always a bad idea.
Assuming a, b, and c are globals:
ref_dict = {'field1': 'a', 'field2': 'b', 'field3': 'c'}
def update(field, value):
globals()[ref_dict[field]] = value
If you really want to, you can even create "reference wrappers":
class GlobalReference(object):
def __init__(self, name):
self.name = name
def get(self):
return globals()[self.name]
def set(self, value):
globals()[self.name] = value
ref_dict = {'field1': GlobalReference('a'), 'field2': GlobalReference('b')}
def update(field, value):
ref_dict[field].set(value)
And if you want to wrap things that aren't in globals, like globals from another module, class attributes, instance attributes, etc.? Create more reference wrapper types:
class NamespaceReference(object):
def __init__(self, namespace, name):
self.namespace, self.name = namespace, name
def get(self):
return getattr(self.namespace, self.name)
def set(self, value):
setattr(self.namespace, self.name, value)
ref_dict = {'field1': GlobalReference('a'), 'field2': NamespaceReference('myobj', 'b')}
Or you can forgo the classes and just store setter functions…
So, if this is a bad idea, what's the right answer?
Without knowing what you're trying to do, it's hard to say, but here are some possibilities:
Use a single dict variable full of values instead of a bunch of separate variables.
Make the variables instance attributes of a class, and pass an instance of that class around.
Use a mutable float-holder object instead of a plain float instance.
For your specific case, I think what you want is the second one. This is standard model-view-controller design. Or, if you don't like MVC, model-template-view or some other variant (you don't really need a controller here).
Your model is a bunch of scattered globals, which is why it's hard to hook it up to the view. The simplest answer is to represent the model as an object. Then give the view (or its controller) a reference to this model, which is trivial, and you're done.
| {
"pile_set_name": "StackExchange"
} |
Q:
getting current URL from popup.hml and send it to external.js
been searching without finding a solution for me,
I need to be able to send and recive current tab URL when the Chrome extension is shown:
this is My popup.html:
<html>
<head>
<style>
div, td, th { color: black; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script>
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
</script>
<script src="http://keepyourlinks.com/API/public/chrome.js"></script>
</head>
<body style="width: 650px;height:600px;margin:0px;paddin:0px;width:100%;">
<span class="keeper">keep</span>
</body>
</html>
An then, in my webiste, on a chrome.js file i try:
$("body").ready(function(){
var url = getURL_please();
$(".keeper").click(function(event) {
event.preventDefault();
window.open("http://keepyourlinks.com/API/public/compartir_link.php?url="+url,'about to keep', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=600');
});
});
But URL is allways: Undefined
Any idea what i'm doing wrong?
Thanks a lot!
A:
HI Toni,
Google Chrome Extensions use an Asynchronous API,
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
The above will always return null. If you want to make it work correctly.
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
var url = tab.url;
// Do what you want here.
});
}
You would need to the windows open after you you fetch the url. One question though, what do you mean "in your website"? You cannot run Chrome Extension JavaScript directly on your website, so I assume via "Content Script" (most likely, just making sure)?
If your using a Content Script, why would you need to use the Extension API? You can just use window.location.href
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript - Replacing a part of string within special characters
I have 2 javascript variables that has values:
var Name = 'John';
var Age = '14';
and another string variable that looks like this:
var message = 'I am **Name** and my age is **Age**';
How can I inject the value of Name and Age variables into the message string to replace the **Name** and **Age** with values 'John' and '14'?
var newmessage = 'I am John and my age is 14';
Is there a javascript function I can use to perform this?
A:
Use String#replace method and get variable from window object (only works when the variable is defined in the global context other ways you need to use eval() method which I don't prefer to use.).
var Name = 'John';
var Age = '14';
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
return window[m1];
});
console.log(newmessage)
Or use an object instead of variables for storing the value so you can get value easily even it's not defined in global context.
var obj = {
Name: 'John',
Age: '14'
};
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
return obj[m1];
});
console.log(newmessage)
A:
Try with simple string.replace() function
var Name = 'John';
var Age = '14';
var message = 'I am **Name** and my age is **Age**';
message = message.replace('**Name**' ,Name).replace('**Age**' , Age);
console.log(message)
| {
"pile_set_name": "StackExchange"
} |
Q:
Which tangent bundles of real and complex projective spaces are trivial?
The tangent bundle of $S^m$ is known to be trivial only for $m=1,3,7$. Can this result be used to deduce that the tangent bundle of projective space $\mathbb{R}P^m$ is also trivial? (Clearly, for $n=1$ this works since $\mathbb{R}P^1\cong S^1$.) More generally:
For which positive integers $m$ is the tangent bundle $T\mathbb{R}P^m$ a trivial bundle?
One can ask the same question about the tangent bundles $T\mathbb{C}P^m$ of complex projective spaces.
A:
A manifold is called parallelisable if it has trivial tangent bundle. So your question is for which positive integers $m$ is $\mathbb{RP}^m$ parallelisable? What about $\mathbb{CP}^m$?
If $T\mathbb{RP}^m$ is trivial, then the total Stiefel-Whitney class $w(T\mathbb{RP}^m)$ is $1$. By Corollary $4.6$ of Milnor & Stasheff's Characteristic Classes, $w(T\mathbb{RP}^m) = 1$ if and only if $m + 1$ is a power of $2$. So the only real projective spaces which can possibly be parallelisable are $\mathbb{RP}^1$, $\mathbb{RP}^3, \mathbb{RP}^7, \mathbb{RP}^{15}, \mathbb{RP}^{31}, \dots$ We still need to determine which of these are actually parallelisable (the condition on the total Stiefel-Whitney class is a necessary condition, but not sufficient as the case of spheres demonstrates).
Theorem $4.7$ of the same book states that if $\mathbb{R}^n$ admits a bilinear map $p : \mathbb{R}^n\times \mathbb{R}^n \to \mathbb{R}^n$ without zero divisors, then $\mathbb{RP}^{n-1}$ is parallelisable. By identifying $\mathbb{R}^2$ with $\mathbb{C}$, we obtain such a bilinear map for $n = 2$ given by the usual multiplication of complex numbers, i.e. $p((a, b),(c, d)) = (ac - bd, ac + bd)$. Similarly, by identifying $\mathbb{R}^4$ with the quaternions $\mathbb{H}$ and $\mathbb{R}^8$ with the octionions $\mathbb{O}$, we obtain such a map for $n = 4$ and $n = 8$. Therefore, $\mathbb{RP}^1$, $\mathbb{RP}^3$ and $\mathbb{RP}^7$ are parallelisable.
What about $\mathbb{RP}^{15}$, $\mathbb{RP}^{31}, \dots$? None of the remaining real projective spaces are parallelisable - this is harder to show. It follows from Kervaire's $1958$ paper Non-parallelizability of the $n$-sphere for $n > 7$.
So, the positive integers $m$ for which $\mathbb{RP}^m$ is parallelisable are $m = 1, 3,$ and $7$.
The parallelisability of $\mathbb{CP}^m$ is much easier to determine: $\mathbb{CP}^m$ is not parallelisable for any positive integer $m$.
As $\mathbb{CP}^m$ is a complex manifold, its tangent bundle is a complex vector bundle and hence has a total Chern class. The total Chern class of $\mathbb{CP}^m$ is $c(T\mathbb{CP}^m) = (1 + a)^{m+1} \in H^*(\mathbb{CP}^m, \mathbb{Z})$. If $T\mathbb{CP}^m$ were trivial, then it would have total Chern class $1$ but this is never the case. More explicitly,
$$c_1(T\mathbb{CP}^m) = (m+1)a \in H^2(\mathbb{CP}^m, \mathbb{Z}) \cong \mathbb{Z}.$$
As $a \neq 0$ and $m \neq -1$, $c_1(T\mathbb{CP}^m) = (m + 1)a \neq 0$.
More generally, any oriented closed manifold which is parallelisable must have Euler characteristic zero. In fact, such an oriented closed manifold which admits a nowhere zero vector field has Euler characteristic zero, see Property $9.7$ of the aforementioned book. The claim then follows from the fact that $\chi(\mathbb{CP}^m) = m + 1 \neq 0$.
A:
When $m$ is even, the Euler characteristic of $\mathbb{RP}^m$ is $1$, so the top Stiefel-Whitney class of its tangent bundle doesn't vanish, and in particular its tangent bundle is not even stably trivial. In general, it's a nice exercise to calculate the Stiefel-Whitney classes of $\mathbb{RP}^m$, and the result you get is that they all vanish iff $m$ is one less than a power of $2$; in all other cases, the tangent bundle again fails to be stably trivial.
But we can do better. If $\mathbb{RP}^m$ has trivial tangent bundle then so does its double cover $S^m$, and this is known to happen iff $m = 1, 3, 7$. It's clear that $\mathbb{RP}^1 \cong S^1$ and $\mathbb{RP}^3 \cong SO(3)$ have trivial tangent bundles; I'm less clear on $\mathbb{RP}^7$.
The argument is even simpler for $\mathbb{CP}^m$: $\mathbb{CP}^m$ is both always orientable and always has nonzero Euler characteristic (namely $m + 1$), so the Euler class of its (oriented) tangent bundle doesn't vanish. Equivalently, by the converse of the Poincare-Hopf theorem, it doesn't admit a nonvanishing vector field.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenCV VideoWriter does not open file
The following code fails to open a VideoWriter object:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
VideoWriter oVideo;
oVideo.open ("381.avi", -1, 30, Size(640,480), true);
if (!oVideo.isOpened()) {
cout << "Could not open the output video for write" << endl;
return -1;
}
return 0;
}
I'm running OpenCV 2.4.9 pre-built with Code::Blocks on Ubuntu 12.04. I've written a number of images using imwrite() on the same location without issue, so I doubt it has to do with permissions. Also I tried CV_FOURCC('X','V','I','D') which did not work.
What am I missing here?
Any help is greatly appreciated.
A:
I reinstalled OpenCV using this amazing script: https://help.ubuntu.com/community/OpenCV
Solved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing session between pages
here is my requirement. I wanted to pass a variable from one html to another html both has php in it. I know the logic is pretty bad. On clicking the button meant for $row['Room_ID'], it needs to go to plugload6.php . In that php, I wanted to get the Room_ID and handle that in a query.
As far as I know, I should do this with onclick listener which calls JS file. In JS file, I should create a session and call the php file. Could you please help me in achieving the same.Please find the code below
Main.html:
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
//$variable=$row['Room_ID'];
$_SESSION['myVar']=$row['Room_ID'];
//echo $row['Room_ID'];
$newval=$_SESSION['myVar'];
echo $newval;
echo "<tr style='border-bottom: ridge;'>";
echo "<td align='center'>";
echo "<a class=".$row['Room_ID']." onclick='plugButton(Room_ID)' href='plugload6.php' class='action-button shadow animate blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
echo "<td>";
echo "<a href='plugload6.php' class='action-button shadow animate blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
echo "</td>";
plugload6.php:
<?php
//connecting to SQL database plug to retrieve the list of plugs
$room=$_SESSION['myVar'];
echo $room;
$conn=mysqli_connect("localhost","root","") or die("failed");
$db=mysqli_select_db($conn,"splug");
$result=mysqli_query($conn,"select Plug_ID from plug where Room_ID='".$room."'") or die("failed to connect database".mysql_error());
//$row=mysqli_fetch_array($result);
//count=1;
I wanted to handle in the form of session which can make my life easier. Please guide me in completing the same.
A:
Make sure that you started the session with session_start();.
Or instead of using PHP session pass the Room_ID at the end of URL as a GET parameter
echo "<a href='plugload6.php?roomId=".$row['Room_ID']."' class='action-button shadow animate blue' style='color: rgb(255,255,255)'>".$row['Room_ID']."</a>";
And than in plugload6.php use
$room = $_GET['roomId'];
to get the room id.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Is Data Programmed to Dream?
I know Data is fully functional in every way, but he's still just an Android. Why is he programmed to dream when he doesn't even need sleep?
A:
When he created Data, Dr Soong evidently believed that dreaming (and by extension, developing a subconscious) were an essential part of an android becoming more human.
Data's capacity to access his dream program has dramatically preceded his ability to understand what these dreams mean. He discovered the program by accident and is, essentially, playing with a tool that he doesn't fully comprehend. Presumably had his mental capabilities developed at a more organic pace, when he started dreaming it would have seemed less shocking.
DATA: An accident in Engineering shut down my cognitive functions for a short period of time, yet I seemed to remain conscious. I saw my
father.
WORF: You are very fortunate. That is a powerful vision.
DATA: If it was a vision, I do not know how to proceed.
TNG: Birthright, Part I
You might also want to note that Soong also created a system that allowed Data to feel emotions, again to allow him to act and be more human-like.
| {
"pile_set_name": "StackExchange"
} |
Q:
Line breaks in Sitecore single line textbox
When I press ENTER in Sitecore single line field textbox it renders TWO linebreaks
<br/><br/>
This issue appears only in Chrome/Firefox. In IE ENTER leads only to one
Can I disable somehow automatic adding of in these browsers?
A:
Issue is caused by Sitecore Intranet.WebEdit.js
Modifiying this piece of code helped with problem:
if (evt.keyCode == 13 && this.activeElement && this.activeElement.contentEditable() && this.activeElement.parameters["linebreak"] == "br") {
try {
if (document.selection != null) {
var sel = document.selection.createRange();
sel.pasteHTML('<br />');
evt.stop();
}
if (!Prototype.Browser.IE) {
evt.srcElement.innerHTML = evt.srcElement.innerHTML + "<br/>";
evt.stop();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android communicating from Service to Clients
I'd like to keep a reference to each client that binds to a started & bound Android service. My service is NOT in a separate process.
I can have multiple clients bound, e.g. - 1 Activity and 2 Fragments. They may all be interested in a combination of different events returning from the Service. Ideally, I'd like to register each client with the Service when they bind and then iterate over each connected client and send them each the message.
Right now I am using the Binder to expose the Service's API to the client, but I am not happy using Broadcasts to send the data from the Service back to the clients. It feels so "loose". Wondering if there was a more concise & structured way of doing so ?
Message Handler is one way, but I feel like I will lose the binder API the clients are currently accessing the service API through.
A:
The Bound Service approach detailed here is appropriate. You don't have to worry about Handlers, or even Intents (once the client is bound).
Referring to the example at the given link: You can simply add functionality on to the LocalService object, e.g.,
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
private Set<MyEventListener> mListeners = new HashSet<>();
/** A MyEventListener (your Activity, Fragment, etc.) calls this in its
* onServiceConnected() method, on the reference it gets from getService(). */
public void registerListener(MyEventListener listener)
{
mListeners.add(listener);
}
public void sendEvent()
{
for(MyEventListener listener : mListeners)
{
listener.onEvent();
}
}
...and so forth. All methods execute synchronously, on the UI thread. All objects (Services and clients (MyEventListener)) are guaranteed to have a lifetime at least as long as the ServiceConnection. Also, the ServiceConnection will not experience an onServiceDisconnected() call until you explicitly unbind, since you're using an in-process service.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why UL and why not OL?
Possible Duplicate:
Why we always use <ul> to make Navigation why not <ol> ?
Why Designers always use ul for menu and many things else and why they don't use ol for menu and etc.
A:
ul means unordered, ol means ordered.
Most people percieve a menu as having no obvious numerical order. If you were marking up a 5 star rating system of something, then ol would be appropriate.
A:
ol implies you want an ordered list, e.g. numbered 1,2,3 or I, II, III. generally for menu navigation you wouldn't want to number your menu items. so instead use a ul and apply CSS to get the layout you want. But often I will use OL e.g. if outputting a numbered list of terms and conditions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with percent encoding in paperclip document.url on s3
I just upgraded my gems and paperclip urls are now encoded properly with %3F for the ? that Amazon likes to use. However, this breaks the links for my users when doing:
<a href="<%= client.document.url %>">Link</a>
Right now I'm manually replacing the %3F with a ? by using gsub, but am wondering whether there is something wrong in my code instead of in the gems or on Amazon's side. My fix:
<%= client.document.url.gsub(/%3F/, "?") %>
Is there something else I could be doing or should know?
A:
Use URI.unescape:
<%= URI.unescape(client.document.url) %>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to parse data from a json list by using Gson?
Now I get a json file with data in this format:
[
[
"name1",
"age1",
"gender1",
url1
],
[
"name2",
"age2",
"gender2",
url2
],
...
]
Now I want to parse it and store them in my database by using Gson, but I don't know how to write the code to do it.
The list may contains about 200,000 small lists, so I don't know if it will take a lot of memory if I just use gson.fromJson() to get the whole json list. Is there a dynamic method to parse each small list in it?
A:
Gson 2.1 introduced a new TypeAdapter interface that permits mixed tree and streaming
serialization and deserialization.
The API is efficient and flexible. See Gson's Streaming doc for an example of combining
tree and binding modes. This is strictly better than mixed streaming and tree modes; with
binding you don't waste memory building an intermediate representation of your values.
Gson has APIs to recursively skip an unwanted value; Gson calls this skipValue().
Source: JAVA - Best approach to parse huge (extra large) JSON file by Jesse Wilson
| {
"pile_set_name": "StackExchange"
} |
Q:
Handle exceptions on multiple running threads Java
I am developing a java app I would like to know how to handle exceptions on multiple running threads. Is there any example? Thanks
A:
If I understood your question correctly, you asking how to detect that thread finished due to unhandled exception.
You need to implement UncaughtExceptionHandler for that. The simplest useful activity you can put in your implementation of handler is to log exception which wasn't caught.
One sample of this, used together with Executor:
final Thread.UncaughtExceptionHandler DEFAULT_HANDLER = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("", e);
}
};
ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(DEFAULT_HANDLER);
return t;
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
throw new RuntimeException("log me");
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the song playing in My Hero Academia season 2 episode 13 at 6:05?
I hear this song in a lot of episodes but I can't seem to find it anywhere! Please help, I know for sure it's in season 2 episode 13 at 6:05
A:
If I have not been wrong with the scene the song is:
Arararara? (あらららら?) by Yuki Hayashi.
It is the twelfth track of the album My Hero Academia Original Soundtrack.
The part that sounds in that scene is from the second 27-29 of the song onwards.
Song in Youtube
| {
"pile_set_name": "StackExchange"
} |
Q:
a special case when modifing the database
sometimes i face the following case in my database design,, i wanna to know what is the best practice to handle this case:::
for example i have a specific table and after a while ,, when the database in operation and some real data are already entered.. i need to add some required fields (that supposed not to accept null)..
what is the best practice in this situation..
make the field accept null as (some data already entered in the table ,, and scarify the important constraint )and try to force the user to enter this field through some validation in the code..
truncate all the entered data and reentered them again (tedious work)..
any other suggestions about this issue...
A:
The best way to go about it is to truncate the data and re - enter it again, but it need not be too tedious an item. Temporary tables and table variables could assist a great deal with this issue. A simple procedure comes to mind to go about it:
In SQL Server Management Studio, Right - click on the table you wish to modify and select Script Table As > CREATE To > New Query Editor Window.
Add a # in front of the table name in the CREATE statement.
Move all records into the temporary table, using something to the effect of:
INSERT INTO #temp SELECT * FROM original
Then run the script to keep all your records into the temporary table.
Truncate your original table, and make any changes necessary.
Right - click on the table and select Script Table As > INSERT To > Clipboard, paste it into your query editor window and modify it to read records from the temporary table, using INSERT .. SELECT.
That's it. Admittedly not quite straightforward, but a well - kept database is almost always worth a slight hassle.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I access azure storage $logs
In the Azure Portal, I've created blob storage as follows:
http://mymedia.blob.core.windows.net/
I've enabled logging by going to mymedia > configure > logging and enabling it.
Unfortunately when I go to:
http://mymedia.blob.core.windows.net/$logs
I get a "resource not found error".
So my question is this. Once I've enabled logging for storage, how do actually access it? :/
Cheers
Pete
A:
I don't believe the $logs container is public by default. Can you use a tool like Cerebrata's Azure Management Studio to open your storage account and view the $logs container?
They won't be under "Blob Containers" node but under "Storage Analytics" --> "Raw Data" node as shown in the screenshot below:
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove multiple classes at once
I have the following html
<div class="row">
<div class="one someclass"></div>
<div class="two someclass"></div>
<div class="three someclass"></div>
</div>
<div class="row">
<div class="one someclass"></div>
<div class="two someclass"></div>
<div class="three someclass"></div>
</div>
And I want remove all one, two, three attribute
I tried
$(function () {
$('div').removeAttr('one', 'two', 'three');
});
but didn't work. I think this is wrong method. What should I do?
A:
removeClass accepts a space-delimited list of the class names to remove, so:
$("div.one, div.two, div.three").removeClass("one two three");
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get image to appear only if my if/else statement is true?
How do I go about spawning a specific image if a particular if/else statement is true?
I keep trying but the src just causes the image to stay on the page and not disappear when the if statement is false.
if (B == "k k"){
//I want my image to appear through this if statement
}else {
//and a separate image to appear if this "else" is true
}
A:
add id to your image
<img id="your-image-id" src="" alt="" >
you can set src on if statement
var img = document.getElementById("your-image-id")
if (B == "k k"){
img.src ="linkto your image"
}else {
img.src ="linkto your another image"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
should Assembly.GetExecutingAssembly().CreateInstance throw an exception here?
I'm pretty new, so this may be a "stupid question," or may not be appropriate here, please advise as appropriate.
I'm exploring some of C#'s features, this week I'm messing about with reflection. I'm confused when I read http://msdn.microsoft.com/en-us/library/145sfyea.aspx, from what I can tell I'm not getting MissingMethodException (No matching constructor was found.) when I think I should.
Question: should this code throw an exception at the noted point?
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Test
{
abstract class Vehicle
{
public string type { get; set; }
}
class Van : Vehicle
{
public Van()
{
System.Console.WriteLine("van!");
this.type = "van";
// ...
}
}
class Program
{
static void Main(string[] args)
{
List<String> things = new List<String>();
things.Add("Van");
things.Add("Car");
List<Vehicle> inventory = new List<Vehicle>();
foreach (String s in things)
{
Vehicle vehicle = Assembly.GetExecutingAssembly().CreateInstance("Test" + "." + s, true) as Vehicle;
if (vehicle != null)
{
inventory.Add(vehicle);
}
else
{
System.Console.WriteLine("Should an attempt to create an instance of"+ "Test" + "." + s+ " have thrown an exception? " );
};
}
Console.Read();
Console.Read();
}
}
}
A:
No. You would get a MissingMethodException if the Test.Car type existed, but did not have a public parameterless constructor. If the type cannot be found at all, null is returned; if the type is found, but a public constructor matching the argument list you have provided cannot be located, then a MissingMethodException is thrown.
From MSDN:
Return Value
Type: System.Object
An instance of the specified type created with the default constructor; or null if typeName is not found.
See this ideone example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are T-Tracks the same size on all brands of roof rack crossbars?
Looking at buying additional accessories or making some for my car's roof rack, which uses Whispbar brand crossbars. I'm wondering if other brands use the same size t-track slots and whether they'd be interchangeable.
A:
No
That's a bit short for an SE answer but it pretty much covers the problem, there are various manufacturer specific sizes and no standard. Some parts providers such as Thule sell accessories and adapters to allow a greater range of compatibility.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validação de campos com Javascript em JSP
function validar() {
var nome = document.getElementById("nome_passageiro").value;
var data = document.getElementById("dt_nascimento").value;
var cpf = document.getElementById("cpf").value;
var modelo = document.getElementById("modelo").value;
var status = document.getElementById("status").find("option[value='"+val+"']");
if (nome == "") {
alert('Preencha o campo com seu nome');
}else if(data==""){
alert('Preencha a data');
}else if(cpf==""){
alert('Preencha o cpf');
}else if(modelo==""){
alert('Preencha o modelo');
}else if(status==""){
alert('Preencha o Status');
}else{
return false;
}
}
<h1>Cadastro de Motoristas</h1>
Nome do Motorista:
<input type="text" id="nome_passageiro" /><br/><br/>
Data de Nascimento:
<input type="text" id="dt_nascimento" /><br/><br/>
CPF:
<input type="text" id="cpf" onkeypress="" /><br/><br/>
Modelo de Carro:
<input type="text" id="modelo" /><br/><br/>
Status:
<input list="status" /><br/><br/>
<datalist id="status">
<option value="-------">
<option value="Ativo">
<option value="Inativo">
</datalist>
<button type="button" onkeypress="validar()">Cadastrar</button>
Estou fazendo uma validação de campos utilizando o Javascript em uma aplicação jsp mas ela não está funcionando.
A:
Basicamente você precisa mudar de onkeypress="validar()" para onclick="validar()" pois a função deve iniciar assim que o usuário clicar no botão.
Mas vale lembrar que você pode explorar muitos pontos de melhoria no seu código:
Remover os <br /> desnecessários, utilize <p> para parágrafos ou <div> se quiser somente agrupar os campos.
Pensando em melhorar a experiência do usuário ao acessar sua página deixe a validação com IF ao invés de ElseIf.
É muito melhor para o usuário ver tudo que ele errou de uma vez do que aos poucos, também é valido deixar alguma indicação na página do que é obrigatório.
Na parte em que <datalist> não entendi muito o bem o que você queria fazer então deixei comentado para evitar o erro no Javascript.
function validar() {
var msgErro = "";
var nome = document.getElementById("nome_passageiro").value;
var data = document.getElementById("dt_nascimento").value;
var cpf = document.getElementById("cpf").value;
var modelo = document.getElementById("modelo").value;
var status = document.getElementById("status").value;
if (nome == "") {
msgErro = msgErro + 'Preencha o campo com seu nome. \n';
}
if(data==""){
msgErro = msgErro + 'Preencha a data. \n';
}
if(cpf==""){
msgErro = msgErro + 'Preencha o cpf. \n';
}
if(modelo==""){
msgErro = msgErro + 'Preencha o modelo. \n';
}
if(status==""){
msgErro = msgErro + 'Preencha o Status. \n';
}
if(msgErro != ""){
alert(msgErro);
return false;
}
}
<h1>Cadastro de Motoristas</h1>
<div>
<label for="nome_passageiro">Nome do Motorista:</label>
<input type="text" name="nome_passageiro" id="nome_passageiro" />
</div>
<div>
<label for="dt_nascimento">Data de Nascimento:</label>
<input type="text" name="dt_nascimento" id="dt_nascimento" />
</div>
<div>
<label for="cpf">CPF:</label>
<input type="text" name="cpf" id="cpf" onkeypress="" />
</div>
<div>
<label for="modelo">Modelo de Carro:</label>
<input type="text" name="modelo" id="modelo" />
</div>
<div>
<label for="status">Status:</label>
<select name="status" id="status">
<option value="">Selecione</option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>
</div>
<div>
</div>
<div>
<button type="button" onclick="validar()">Cadastrar</button>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
nx.draw_networkx shows module matplotlib has no attribute path
I'm trying to learn some Python graph visualization. while running the following piece of code I am encountering this error
AttributeError: module 'matplotlib' has no attribute 'path'
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
FG = nx.from_pandas_adjacency(pandas_df)
nx.draw_networkx(FG, with_labels=True)
Any help would be appereciated, thanks in advance.
A:
For some reason after I close and reopen the spyder it worked.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fix a bug in fixed header with anchor function in my responsive design layout
my responsive design layout
The above link is my responsive design layout.
The height of fixed header is adjusted according to pc, tablet & mobile version. By the same token, the anchor function is adjusted from fixed header. There is a bug in the anchor function. When I narrow the width of a web browser, the header will become higher. The anchor function is not work automatic that I need to click F5 to refresh the web to active that function. How can I fix the bug?
Below is my css & js coding:
var menuContainer = $('header').height();
function scrollToAnchor(anchorName) {
var aTag = $("div[name='" + anchorName + "']");
$('html,body').animate({
scrollTop: aTag.offset().top - menuContainer
}, 'slow');
console.log(anchorName);
}
css coding
#subnav {
height: 100%;
margin-right: auto;
width: 100%;
background-color: #FFFFFF;
font-size: 120%;
}
#submenu ul {
padding: 0;
margin-top: 4px;
margin-right: auto;
margin-left: 0%;
margin-bottom: 0;
width: 650px;
}
#submenu li {
float: left;
}
#submenu li a {
display: inline-block;
padding: 10px 20px;
text-align: center;
text-decoration: none;
font-weight: bold;
border-right: 1px solid #294C52;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
.submenu-active {
background-color: #294C52;
color: #FFFFFF;
}
a {
color: #294C52;
}
A:
Try this:
var menuContainer = $('header').height();
function scrollToAnchor(anchorName) {
var aTag = $("div[name='" + anchorName + "']");
$('html,body').animate({
scrollTop: aTag.offset().top - menuContainer
}, 'slow');
console.log(anchorName);
}
$(window).on('resize', function(event) {
menuContainer = $('header').height();
});
Now depending on when you call the function it should work. If you want it to work automatically on resize call the function inside the event handler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems creating a query to show sub totals with a specific sub query join
I am trying to create a query to list counts for all (US) states in series of joins, so that it shows 0's for all states defined in a table that does not appear in the rest of the data.
This is what I've come up with so far:
SELECT s.StateName,s.StateNum, COUNT(s.StateNum) as [count]
FROM States AS s
INNER JOIN StateIncludeInClueReport as scr ON scr.statenum = s.StateNum
LEFT JOIN Staging_Policy sp ON CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)) = s.StateNum
left JOIN (SELECT MIN(sip.QuoteId)AS QuoteId,sip.rmId FROM Staging_Policy sip GROUP BY sip.RMID) as sq ON sq.QuoteId = sp.QuoteID
INNER JOIN dbo.ResultMaster AS rm ON rm.rmID = sq.RMID
INNER JOIN dbo.CreditReport AS cr ON rm.rmID = cr.rmID AND cr.PolType = 'AUTO 3.0'
GROUP BY CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)), s.StateName, s.StateNum
ORDER BY s.StateNum
But I'm still not seeing an records that don't appear in the rest of the data.
I've created a sqlFiddle with the given scema and sample data.
The current output its:
STATENAME STATENUM COUNT
Kentucky 16 14
Ohio 34 4
The desired output would be:
STATENAME STATENUM COUNT
Arkansas 3 0
Georgia 10 0
Indiana 13 0
Kentucky 16 14
Missouri 24 0
Ohio 34 4
Tennessee 41 0
Texas 42 0
Virginia 45 0
I'm not really a SQL expert and this has really been giving me trouble. Would anyone have some insights into what I'm doing wrong?
A:
I made a few changes to your query, including using LEFT JOIN on most of the joins:
SELECT s.StateName,
s.StateNum,
isNull(COUNT(cr.PolType), 0) as [count]
FROM States AS s
INNER JOIN StateIncludeInClueReport as scr
ON scr.statenum = s.StateNum
LEFT JOIN Staging_Policy sp
ON CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)) = s.StateNum
LEFT JOIN
(
SELECT MIN(sip.QuoteId)AS QuoteId, sip.rmId
FROM Staging_Policy sip GROUP BY sip.RMID
) as sq
ON sq.QuoteId = sp.QuoteID
LEFT JOIN dbo.ResultMaster AS rm
ON rm.rmID = sq.RMID
LEFT JOIN dbo.CreditReport AS cr
ON rm.rmID = cr.rmID
AND cr.PolType = 'AUTO 3.0'
GROUP BY CONVERT(TINYINT,SUBSTRING(sp.ProducerCode,1,2)), s.StateName, s.StateNum
ORDER BY s.StateNum;
See SQL Fiddle with Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Dependency injection with Orleans
I'm not sure how or where to inject dependencies into a Grain. Where's the best place to do this?
If it's not possible, should I set up a container in the WorkerRole.Run method and get instances as I need them?
A:
Since orleans 1.1.0 release, orleans team added "ASP.NET vNext style Dependency Injection for grains", you can see an example of this in here
Also to see how "ASP.NET vNext Dependency Injection" works see here
A:
There is a limited support for DI in the grains. This feature is being promised to be delivered soon , but as in 1.0.9 - there is no traditional constructor injection.
So far you can use (anti-pattern) ServiceLocator using frameworks of your choice (e.g we are using Autofac and CommonServiceLocator for that) for resolving services you want to call inside your grain instance.
For the unit testing - there is a Grain constructor which can be used to construct grain instance with mocks (see more details here )
I'd invite you to the Orleans gitter chat (as via link above) where you can see answers and discussions around some other burning questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the Grid data in ColumnHeaderClick
Sorrry guys, I'm stuck here.
I have a few grids, I also have CollectionViewSource objects associated with those grids.
Now, I'm trying to apply CollectionViewSource.SortDescriptions in ColumnHeaderClick method, and now I have to define almost the same method for each grid.
But the only thing I really need is to obtain in which Grid is happenning.
How to get that, I have no idea. Help me please.
VisualTreeHelper.GetParent didn't work.
A:
Oh.. it's turned out that it's possible to change the SortDesriptions directly in
(((System.Windows.Controls.ListBox)(sender)).Items)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use a regular expression for checking if comment is closed in javascript?
How can I use a regular expression in javascript for checking if a comment is closed in a javascript file?
A:
There is no way to use regular expressions for checking parenthesis.
In order to check if brackets or comment (e.g. /../) are closed, you have to iterate over a string, count the number of opening brackets, and of closing brackets, and to compare.
Example:
function check(str)
{
var paranCount = 0;
for (var i = 0; i < str.length; i++)
{
if (str[i] == '[')
paranCount++;
else if (str[i] == ']')
paranCount--;
if (paranCount < 0) return false;
}
return !paranCount;
}
Note: This only applies to code pieces that do not contain string (for example), though the inline string "asfasdf[[[" is legal inside the code, yet this function will not deem it so.
With the absence of other limitations to the code, you should use a parser library/file, or use the above function as a basis for writing one yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dependence of symbol in regular expressions
I need to parse a line, that can look as one of these:
define a as 5
define b as 5.5
define c as "hello, stackoverflow"
I'm trying to do this with regular expressions.
For this I wrote pattern 'define ([a-zA-Z_]\w*) as ([\w"][\w \.]*[\w"]*)'
My problem that I don't understand is there any way to check: if smth after word as starts with " then it should end with ". Thanks for any comments and suggestions.
A:
I suggest using alternation:
define ([a-zA-Z_]\w*) as ("[^"]+"|[\w.]+)
See the regex demo
The ("[^"]+"|[\w.]+) captures either a quoted substring that has no quotes inside ("[^"]+" - to allow empty "", use * instead of +) -OR- 1+ word characters or dots (matched with [\w.]+).
| {
"pile_set_name": "StackExchange"
} |
Q:
C# add items to list from class then add list items to listbox
I'm a student in a C# class and this is my introductory assignment to Classes, so please bear with me. When the New button is pressed, a CPerson object will be created using the name and phone values and the object will be added to a List<>.
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
}
public partial class Form1 : Form
{
private List<CPerson> PhoneNum = new List<CPerson>(); //<CPerson> or <string>?
public Form1()
{
InitializeComponent();
newbutton.Enabled = false;
changebutton.Enabled = false;
savebutton.Enabled = false;
}
private void newbutton_Click(object sender, EventArgs e)
{
changebutton.Enabled = true;
savebutton.Enabled = true;
PhoneNum.Add(new CPerson { Name = Namebox.Text + " : ", Phone = phonebox.Text });
listBox1.Items.Add(PhoneNum); //text = "Collection"
}
The assignment says "The CPerson ToString() override will be used to display the name and phone number in the listbox" as shown in the above image, which I don't necessarily understand, but I'm guessing I have to use something like this?
CPerson data = new CPerson();
data.ToString();
Either way, as the code is now, all I get in my listbox is "(Collection)". Any help would be appreciated!
A:
That is asking to override the ToString() method. You can do it like this:
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
I did not get right the part of adding to the list, but I assume you can do the following using ToString():
listBox1.Items.Add(data.ToString());
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bind to a specified element of an array to image source in LongListSelector in windows phone 8
I have a model Article. Article has a property ImagePath, and ImagePath is array of Uri string.
In a specified page. I just want to show the first Image of the ImagePath list. So I do it like below and no image displays.
<Image Source="{Binding ImagePath.[0]}" Height="50" Width="50" Grid.Row="0" Grid.Column="0"
VerticalAlignment="Top" Margin="0,7,7,0"
Grid.RowSpan="2">
Other properties display well, anyone can help me on this?
Model is as follow:
public class Article
{
public List<string> ImagePath = new List<string>();
public string Subject;
public string Words;
}
and i have image control in a longlistselector in my xaml
<phone:LongListSelector
x:Name="articleList"
Grid.Row="1"
Margin="0,0,-12,0"
DataContext="{StaticResource viewModel}"
ItemTemplate="{StaticResource ResultItemTemplate}"
ItemsSource="{Binding ArticleCollection}"
ItemRealized="articleList_ItemRealized"
SelectionChanged="LongListSelector_SelectionChanged"
>
</phone:LongListSelector>
<DataTemplate x:Key="ResultItemTemplate">
<Grid Margin="0,6,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle Fill="Gray" Height="50" Width="50" Grid.Row="0" Grid.Column="0"
VerticalAlignment="Top" Margin="0,7,7,0"
Grid.RowSpan="2">
</Rectangle>
<Image Source="{Binding ImagePath.[0]}" Height="50" Width="50" Grid.Row="0" Grid.Column="0"
VerticalAlignment="Top" Margin="0,7,7,0"
Grid.RowSpan="2">
</Image>
<TextBlock Text="{Binding Path=Subject, Mode=TwoWay}" Grid.Row="0" Grid.Column="1"
Foreground="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top"/>
<TextBlock Text="{Binding Path=Words, Mode=TwoWay}" TextWrapping="Wrap"
Grid.Row="1" Grid.Column="1"
VerticalAlignment="Top"
/>
</Grid>
</DataTemplate>
A:
Try using BitmapImage or WriteableBitmap as Another property
public List<String> ImagePath = new List<String>();
public BitmapImage SelectedImage;
And use it like this.
Article ArticleCollection = new Article();
ArticleCollection.BitmapImage = new BitmapImage(new Uri(ArticleCollection.Imagepath[0]));
articleList.ItemsSource = ArticleCollection;
| {
"pile_set_name": "StackExchange"
} |
Q:
Add png in bootstrap button like glyphicon
I want to replace glyphicon-user in bootstrap button with a responsive png, is there any way to do this?
#SignUp-btn{
width: 100% !important;
height: 45% !important;
font-size: 20px;
background-color: #262262;
border-color: #262262;
}
<div class="col-sm-6">
<a href="SignUp" class="btn btn-sq-lg btn-primary" id="SignUp-btn">
<i class="glyphicon glyphicon-user fa-5x"></i>
<br><b> Sign Up</b>
</a>
</div>
See Attached
A:
you can put the image as a background image on the "i" tag. See sample below.
#SignUp-btn + i {
background-image: url(image.png);
text-indent: -9999999999px;
height: 15px;
width: 15px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery - find table row containing table cell containing specific text
I need to get a tr element which contains a td element which contains specific text. The td will contain that text and only that text (so I need text = 'foo' not text contains 'foo' logic).
So I need the equivalent of the following 'pseudo jQuery':
var tableRow = $(table td[text = 'foo']).parent('tr');
Can anyone provide the correct syntax?
A:
You can use filter() to do that:
var tableRow = $("td").filter(function() {
return $(this).text() == "foo";
}).closest("tr");
A:
I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.
$("tr:contains(needle)"); //where needle is the text you are searching for.
For example, if you are searching for the text 'box', that would be:
$("tr:contains('box')");
This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements
A:
$(function(){
var search = 'foo';
$("table tr td").filter(function() {
return $(this).text() == search;
}).parent('tr').css('color','red');
});
Will turn the text red for rows which have a cell whose text is 'foo'.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question on $\aleph_0$-categorical nonhomogeneous structures
Macpherson in a survey of homogeneous structures, states that there are many $\aleph_0$-categorical structures which are not homogeneous. Here homogeneity is the ultrahomogeneity that is defined as every isomorphism between two finite substructures of a structure $M$ can be extended to an automorphism of $M$. $\omega$-homogeneity means that any finite partial elementary mapping can be extended so that its domain includes any given element.
I am confused on this because it is well known that a $\aleph_0$-categorical structure is both atomic and countably saturated, and both atomic and countably saturated structures are $\omega$-homogeneous. This actually means that a $\aleph_0$-categorical structure is ultrahomogeneous. Where is wrong here?
A:
You are confusing several notions of homogeneity. Saturated structures, and therefore also $\aleph_0$-categorical structures, are homogeneous, but not necessarily ultrahomogeneous. This means that every finite partial elementary mapping extends to an automorphism.
$\omega$-homogeneity is in fact an even weaker property: it says that any finite partial elementary mapping can be extended so that its domain includes any given element. However, this is equivalent to the property above for countable structures.
Ultrahomogeneity of $\omega$-saturated structures implies quantifier elimination, hence it is not implied by any standard model-theoretic properties that are invariant by expansion of the language with definable predicates.
In more detail, let me try to deconfuse Macpherson’s terminology by reviewing the relevant properties (using more standard terminology that does not drop the ultra- prefixes) and their connections. In what follows, $M$ is a structure, and $\kappa$ is an infinite cardinal.
$M$ is $\kappa$-homogeneous if for every partial elementary map $f\colon M\rightharpoonup M$ such that $|f|<\kappa$, and for every $a\in M$, there exists a partial elementary map $g\supseteq f$ such that $a\in\operatorname{dom}(g)$.
$M$ is strongly $\kappa$-homogeneous if every partial elementary map $f\colon M\rightharpoonup M$ such that $|f|<\kappa$ extends to an automorphism of $M$.
If $\kappa=|M|$, and $M$ is $\kappa$-homogeneous, it is in fact strongly $\kappa$-homogeneous. Such structures are simply called homogeneous.
$M$ is $\kappa$-ultrahomogeneous if for every partial isomorphism $f\colon M\rightharpoonup M$ such that $|f|<\kappa$, and for every $a\in M$, there exists a partial isomorphism $g\supseteq f$ such that $a\in\operatorname{dom}(g)$.
$M$ is strongly $\kappa$-ultrahomogeneous if every partial isomorphism $f$ such that $|f|<\kappa$ extends to an automorphism of $M$.
$M$ is ultrahomogeneous if it is $\kappa$-ultrahomogeneous (or equivalently, strongly $\kappa$-ultrahomogeneous) for $\kappa=|M|$.
The basic properties are:
If $M$ is $\kappa$-saturated, it is $\kappa$-homogeneous.
If $M$ is atomic, it is $\omega$-homogeneous.
The following are equivalent:
$M$ is $\kappa$-ultrahomogeneous;
$M$ is $\kappa$-homogeneous, and every partial isomorphism $M\rightharpoonup M$ is elementary.
Likewise for strong $\kappa$-ultrahomogeneity.
If $M$ is in a finite relational language, or if it is $\omega$-saturated, the following are equivalent:
Every partial isomorphism $M\rightharpoonup M$ is elementary.
$M$ has quantifier elimination.
Consequently, if $M$ is in a finite relational language, or if it is $\omega$-saturated, the following are equivalent:
$M$ is $\kappa$-ultrahomogeneous.
$M$ is $\kappa$-homogeneous, and $M$ has quantifier elimination.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to understand index shifting
I don't understand index shifting/general rules for Summations.
$S_n := \frac{1}{1+n}+\frac{1}{1+(n+1)}+...+\frac{1}{2n}$.
Finding a Summation formula for this equals either:
$A(n):=\sum_{k=n}^{2n-1} \frac{1}{1+k}$ or $S(n):=\sum_{k=n+1}^{2n} \frac{1}{k}$
I already know the solution if we use
$S(n):=\sum_{k=n+1}^{2n} \frac{1}{k}$.
$S(n+1)=\sum_{k=n+2}^{2n+1} \frac{1}{k} = \sum_{k=n+1}^{2n} \frac{1}{k} + (\frac{1}{2n+2}+\frac{1}{2n+1}-\frac{1}{n+1})$
Can someone try to explain this soluition?
How would the change of indexes look like for this?
$A(n):=\sum_{k=n}^{2n-1} \frac{1}{1+k}$
$A(n+1) = \sum_{k=n+1}^{2n} \frac{1}{1+k} = \sum_{k=n}^{2n-1} \frac{1}{1+k} +( ???)$
Can someone give and try to explain his solution?
A:
If you're having trouble with the shift in summation you can put the "missing" step back in, which should help a little. Starting with your first example, we have:
$$
A(n):= \sum_{k=n}^{2n-1} \frac{1}{1+k} = \sum_{j=??}^{j=??} \frac{1}{j}
$$
and we need to determine what the new limits in the sum are. So, when $k=n$ we have $1/(n+1)$ as the summand, which now needs to be $1/j$. So $j$ must be $n+1$. Likewise, when $k=2n-1$ we have $1/(1+2n-1)=1/(2n)$ in the summand, so $j=2n$. So we transform $A(n)$ into
$$ A(n) = \sum_{j=n+1}^{2n} \frac{1}{j} $$
and then finally we replace $j$ with $k$ to get your version. Reusing the $k$ is a standard mathematical technique, partly to avoid using too much notation and partly to keep the theme of certain elements in the sum present to convey the main idea.
For the second part of your question, the sum is being rewritten with certain of the summation terms written out explicitly. Consider:
$$\sum_{i=1}^{n+1} i = \left(\sum_{i=2}^n i\right) + 1 + (n+1)$$
Here, we've removed the terms $i=1$ and $i=(n+1)$ from the sum and written them explicitly after the sum. That's exactly what's happening for you above.
So:
$$A(n+1) = \sum_{k=n+1}^{2n} \frac{1}{1+k} = \sum_{k=n}^{2n-1} \frac{1}{k+1} + \frac{1}{2n} - \frac{1}{1+n} $$
because we have to add on the "missing" last term $1/(k+1)$ because the index $k$ now only goes as far as $n$ instead of $n+1$, and we subtract the "extra" term $1/n$ because the lower index now goes down to $n$ instead of stopping at $n+1$.
It might help if you set $n$ to be a small value, say $2$ or $3$ and write the sums out in full to see all the terms appear.
| {
"pile_set_name": "StackExchange"
} |
Q:
Node.js create array of arrays
I have a constant variable "client_id" and an array of variables called "device_list".
For example:
client_id = "system1"
device_list = ['dev1' , 'dev2' , 'dev3']
Now i need to combine both variables in order to receive an array like this:
result = [['system1' , 'dev1'],['system1' , 'dev2'],['system1' , 'dev3']]
Thanks in advance!
A:
a simple solution:
const client_id = "system1";
const device_list = ['dev1' , 'dev2' , 'dev3']
const result = device_list.map(device => [client_id, device]);
The map method is part of the array prototype.
It loops through every item in an array, and applies the given callback to each item.
For more information, I find the Mozilla docs extremely useful!:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Another thing to note:
map is NON-mutative, meaning it doesn't affect the array on which it is called, it only returns a new one
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Font Width within VB.net Without Measuring a Control?
I need to display a table in rich text within a form window. It is only a two column table, so tabbing works fine to line everything up (since RichTextBox does not support RTF tables). However, sometimes the tab stops are incorrect because of non-fixed width fonts.
So, I need a way to measure the pixel width of a particular string with a particular font (Arial 10) and space or tab pad to make sure that everything aligns.
I know about the Graphics.MeaureString method, but since this is in a rich text box, I don't have an initilzed PaintEventArgs variable, and that would seem like overkill to create JUST to measure one string.
From MSDN:
Private Sub MeasureStringMin(ByVal e As PaintEventArgs)
' Set up string.
Dim measureString As String = "Measure String"
Dim stringFont As New Font("Arial", 16)
' Measure string.
Dim stringSize As New SizeF
stringSize = e.Graphics.MeasureString(measureString, stringFont)
' Draw rectangle representing size of string.
e.Graphics.DrawRectangle(New Pen(Color.Red, 1), 0.0F, 0.0F, _
stringSize.Width, stringSize.Height)
' Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, _
New PointF(0, 0))
End Sub
So is the best bet just to create a dummy PaintEventArgs instance? If so, what is the best way to do that (since I'll have to call this string measuring method several hundred times)?
Also, I don't really want to have to use a fixed width font - they just don't look as good.
A:
Use this
Dim g as Graphics = richbox.CreateGraphics()
Dim sz as SizeF = g.MeasureString(...)
| {
"pile_set_name": "StackExchange"
} |
Q:
Serialize struct with pointers to NSData
I need to add some kind of archiving functionality to a Objective-C Trie implementation (NDTrie on github), but I have very little experience with C and it's data structures.
struct trieNode
{
NSUInteger key;
NSUInteger count,
size;
id object;
__strong struct trieNode ** children;
__strong struct trieNode * parent;
};
@interface NDTrie (Private)
- (struct trieNode*)root;
@end
What I need is to create an NSData with the tree structure from that root - or serialize/deserialize the whole tree some other way (conforming to NSCoding?), but I have no clue how to work with NSData and a C struct containing pointers.
Performance on deserializing the resulting object would be crucial, as this is an iPhone project and I will need to load it in the background every time the app starts.
What would be the best way to achieve this?
Thanks!
A:
Assuming you need to stick with straight C, because that's how things are already setup, what you'll need to do is actually pretty simple.
Just write a C function to write out your tree to disk, with some assumption about ordering (e.g. you write it our depth first, left to right). For any Objective-C objects, encode them into NSData, and write out the size and bytes of these as part of your stream.
When you read the data back in, simply reconstruct the tree based on your ordering assumptions, and set up the pointers to the children. Unarchive any of the embedded Objective-C objects as appropriate.
You can probably do this with NSCoder somehow, but it might be easier to do the tree reconstruction outside that, as you can recurse down the tree passing whatever arguments you like, which isn't really very easy with NSCoding.
I do have some (Desktop OS X) code that does something very similar to this, without the embedded objects, but it's pretty fiddly, and I can't post it.
One optimisation in that code is to read in the data into an internal buffer, in MB chunks (rather than a small number of bytes at a time, for each struct), and then read the data from that buffer, although I'm not sure that was ever benchmarked, and it may or may not make a significant difference on the iPhone in any case. It looks like there's a similar optimisation for writing as well, which is more likely to be a win, as I understand it (iPhone writes are expensive, or so I've heard).
| {
"pile_set_name": "StackExchange"
} |
Q:
Configuration Compliance auditing for many CentOS 5.x boxes
Current Situation
I have a client with many (200x) CentOS 5.x servers deployed in various web, mail, database and file server roles, and these boxes have been variously administrated to a lessor or greater degree.
All the boxes have EPEL repository included as part of their base-install, and all boxes have cron jobs for "yum -y update" running frequently, and are rebooted when kernels are available. (so they are not in a terrible state)
For network, local and external vulnerabilities - We use a 3rd party firm, who use WebInspect to monitor for external facing ports and vulnerable services and produce various regular reports to my boss. (hence am not looking at Nessus, OpenVAS or network based scanning tools right now, or indeed any vulnerability tools)
New Big Boss in Town - is an ex security compliance dude
The new rules are; that if its not being regularly tested, then its not in compliance, even if it is in compliance etc.
(to be honest, I quite like that rule)
So now I am looking for a way to generate a report of server compliance with some compliance standard for all the boxes regularly.
We have a 117 item list of configuration settings, that is a weaker form of various compliance recommendations, so I am confident that most compliance benchmarks like CIS, EAL3 or the STIG level would be sufficient.
We have chef installed on the CentOS instances, hence I can push out yum based packages, (and I can install from source tarballs, but it will make me cry, on these instances)
Would like to have...
I would like to have a tool that runs locally on each CentOS box and produces a reasonably comprehensive html report regarding configuration compliance (and a massive bonus would be to send email alert for severe problems, but I can script that if required)
Ideally I could generate a weekly report that indicates compliance with 1 or more of the recognised linux server benchmarks.
I am happy to pay for a subscription for the checklist, but I suspect the kind per instance 100 USD licenses I see are going to blow my budget.
Some progress...
I see that SCAP and OVAL have tools in CentOS-base or EPEL, such as
OpenSCAP-utils
ovaldi - oval reference interpreter
NIST provide SCAP content for RHEL desktop, which is kinda close;
http://usgcb.nist.gov/usgcb/rhel_content.html
But I would really like to say, here is a known standard, and here is the report...
Some further progress...
There is a tool called sectool in the fedora repos, but I can't get it to run on CentOS due to a missing python-slip module.
Looks like the last commit on that was a few years back, and the author has gone on to work on the openscap-utils project., also depends on PolicyKit and some other things that are not available on CentOS 5.x boxes.
A:
I haven't used chef, but I have used cfengine quite a bit. So while I don't have specific advice for your environment, I can tell you in general how I've handled it. I expect that you can do something similar with chef, puppet, or whatever.
To start, let me say that in my opinion, if you're using chef (or any other configuration management package) to ONLY push packages, then you're missing out on a lot of functionality that could be making your life easier. The well goes MUCH deeper.
In the environment that I manage, I've set up cfengine to not only install/remove packages, but also to maintain specific (and frequently security-related) settings across all servers, across one or more subgroups of similar servers, or on specific hosts, as needed.
This does a couple of things for me -
First, if I bring up a new server, then as soon as it's added to configuration management all of the common and group-specific settings are automatically applied. This means that I don't have to worry about the base lockdown - it's done automatically for me - and I can focus on locking down the applications that are unique to that server. It's like a self-checking checklist, but better.
Second, I can look at the logs and see the results of the configuration runs on every host, including which settings were verified as correct, and which settings were incorrect and fixed. This lets me keep on top of what's happening, but more importantly for compliance, I can parse that information and generate reports that prove the servers are not only configured as expected, but also verified as correct with every configuration run.
This also has a side effect of letting you know if your configuration changes unexpectedly for whatever reason, whether it's a careless coworker, or an attacker that has compromised your system.
So, while it's probably not the answer you're looking for in the short term, maybe it will give you some ideas to include in your long term plan.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove hyphen from duration format time
I need to remove hyphen from duration format time and i didn't succeed with sed command as i intended to do it.
original output:
00:0-26:0-8
00:0-28:0-30
00:0-28:0-4
00:0-28:0-28
00:0-27:0-54
00:0-27:0-19
Expected output:
00:26:08
00:28:30
00:28:04
00:28:28
00:27:54
00:27:19
I tried with command but i am stucked.
sed 's/;/ /g' temp_file.txt | awk '{print $8}' | grep - | sed 's/-//g;s/00:0/0:/g'
A:
Using sed:
sed 's/\<[0-9]\>/0&/g;s/:00-/:/g' file
The first command s/\<[0-9]\>/0&/g is adding a zero to single digit numbers.
The second command s/:00-/:/g is removing the 0- in front of the number.
| {
"pile_set_name": "StackExchange"
} |
Q:
Executing dynamic list of Actions with parameters
I'm building a list of Actions based on some other data. Each action should do a call to a method, and the list of actions should be performed in parallel. I have the following code that works just fine for parameterless methods:
private void Execute() {
List<Action> actions = new List<Action>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(DoSomething));
}
Parallel.Invoke(actions.ToArray());
}
private void DoSomething() {
Console.WriteLine("Did something");
}
But how can I do something similar where the methods have parameters? The following does not work:
private void Execute() {
List<Action<int>> actions = new List<Action<int>>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(DoSomething(i))); // This fails because I can't input the value to the action like this
}
Parallel.Invoke(actions.ToArray()); // This also fails because Invoke() expects Action[], not Action<T>[]
}
private void DoSomething(int value) {
Console.WriteLine("Did something #" + value);
}
A:
Just keep your actions variable as a List<Action> instead of a List<Action<int>> and both problems are solved:
private void Execute() {
List<Action> actions = new List<Action>();
for (int i = 0; i < 5; i++) {
actions.Add(new Action(() => DoSomething(i))); }
Parallel.Invoke(actions.ToArray());
}
private void DoSomething(int value) {
Console.WriteLine("Did something #" + value);
}
The reason you want Action is becuase you're not passing the parameter when the action is invoked - you're providing the parameter value as part of the delegate definition (note that the delegate parameter is changed to a lambda with no input parameters - () => DoSomething(i)), so it's an Action, not an Action<int>.
A:
There is a pitfall that I ran into when using an indexed forloop with the creation of threads.
When giving the Parameter i directly into the DoSomething method the Output is:
Did something #5
Did something #5
Did something #5
Did something #5
Did something #5
It is probably not what one wants when using a Loop and changing the counting variable. But if you save it temporarily into a new variable like:
class Program
{
private static void Execute()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 5; i++)
{
// save it temporarily and pass the temp_var variable
int tmp_var = i;
actions.Add(new Action(() => DoSomething(tmp_var)));
}
Parallel.Invoke(actions.ToArray());
}
private static void DoSomething(int value)
{
Console.WriteLine("Did something #" + value);
}
static void Main(string[] args)
{
Execute();
Console.ReadKey();
}
}
you actually get the counting variable in its full Beauty:
Did something #0
Did something #2
Did something #3
Did something #1
Did something #4
apparently in C# the variable survives the Loop (I don't know where) and when the thread is executed the Compiler will jump to the line
actions.Add(new Action(() => DoSomething(i)));
and take the value of i which it had when the Loop ended! If you would use i to index a List or array it would always lead to an OutOfBoundsException !
This drove me mad for a week until I figured it out
| {
"pile_set_name": "StackExchange"
} |
Q:
Assign Width of First Letter of Word
I'm trying to set up a plugin and it works pretty good, but I noticed that the first character (F in First) wasn't being assigned the correct width on page load. The plugin allows you to mouseover and it changes to Second word and then on mouseout, changes back to First word & then the first character's width is correct. So I tried this to fix it when it first shows:
var firstltrwdraw = $('span.char1').width(); // this width is actually 39px but it keeps pulling 27
console.log('1st Width Raw: ' + firstltrwdraw);
var firstltrwd = parseFloat(firstltrwdraw);
console.log('1st Width: ' + firstltrwd);
console.log('1st Type: ' + typeof firstltrwd);
$('span.char1').parent().css({'width': firstltrwd + 'px'});
Here's some typ. html:
<div class="lslide_wrap">
<a href="javascript:void(0)" ...>
<span class="sl-wrapper" ...>
<span class="char1 sl-w2" ...>S</span> // first letter of Second
<span class="char1 sl-w1" ...>F</span> // first letter of First
</span>
<span class="sl-wrapper" ...>
... // second letter of each word, etc
...
<span>
</a>
</div>
Here's a demo page: http://www.partiproductions.com/letterslide_test/index.html
Sure would appreciate some help in getting the width from char1 and assigning it to it's parent sl-wrapper.
Thanks, Bill
A:
Had to do with padding - was dynamically being changed had to write script to wait until animation was over and then assign padding which fixed the visual width problem ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
Python decorating class
I'm trying to decorate a class with arguments but cannot get it to work:
This is the decorator:
def message(param1, param2):
def get_message(func):
func.__init__(param1,param2)
return get_message
class where I want to put the decorator
@message(param1="testing1", param2="testing2")
class SampleClass(object):
def __init__(self):
pass
But this is not working , I am getting an error when running this. Does anyone know what the problem ?, I am trying to create a decorator to initialise classes with some values.
A:
I'm having trouble figuring out what you're trying to do. If you want to decorate a class with a decorator that takes arguments, one way to do it is like this.
2020-09-03:
Thank you Maria-Ines Carrera for pointing out that the original code doesn't actually handle classes inheriting from other classes correctly and user2357112 supports Monica for proposing a solution that does work.
# function returning a decorator, takes arguments
def message(param1, param2):
# this does the actual heavy lifting of decorating the class
# it takes the original class, modifies it in place, and returns
# the smae class
def wrapper(wrapped):
the_init = wrapped.__init__
def new_init(self):
self.param1 = param1
self.param2 = param2
the_init(self)
def get_message(self):
return "message %s %s" % (self.param1, self.param2)
wrapped.__init__ = new_init
wrapped.get_message = get_message
return wrapped
return wrapper
class Pizza(object):
def __init__(self):
print "Pizza initialization"
@message("param1", "param2")
class Pizza2(Pizza):
def __init__(self):
print "Pizza2 initialization"
super(Pizza2, self).__init__()
pizza_with_message = Pizza2()
# prints "message param1 param2"
print pizza_with_message.get_message()
This prints the following:
Pizza2 initialization
Pizza initialization
message param1 param2
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.