id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527900
|
TypeError: 'NumpyArrayWrapper' object is not iterable
My code looks like this.
with open('sample.pickle', 'rb') as f:
x, y = pickle.load(f)
x and y are actually the vector representation of words. Which are then stored in the sample.pickle file. Its code is (if it is useful)
with open('sample.pickle','w') as f:
pickle.dump([x,y],f)
I have no idea about the object is not iterable error. Please help if you know anything about it. Thanks in advance.
| |
doc_23527901
|
I scrape https://www.zonaprop.com.ar/casas-venta-capital-federal.html
I want to scrape some info about each house. So I using FOR loop to iterate through the list houses (div.posting-card).
I would like to populate my item with add_css(), but I don't know how to use CSS in that case?
To make it clear.
This is that I'd done before without add_css:
for casa in response.css('div.posting-card'):
item = ZonapropItem()
item['name'] = casa.css(' a.go-to-posting::text').get()
item['direction'] = casa.css('span.posting-location.go-to-posting::text').get()
yield item
And this is the way I would like to do it now:
item = ItemLoader(ZonapropItem(), response)
for casa in response.css('div.posting-card'):
item.add_css('name', '**SOME CSS**')
item.add_css('direction','**SOME CSS**')
yield item.load_item()
Thank you very much!
A: You're pretty close to the right answer:
for casa in response.css('div.posting-card'):
loader = ItemLoader(ZonapropItem(), casa)
loader.add_css('name', 'a.go-to-posting::text')
loader.add_css('direction','span.posting-location.go-to-posting::text')
yield loader.load_item()
Just instantiate item loader inside of the loop and feed there your casa selector.
| |
doc_23527902
|
h: line 1: 1511 Trace/BPT trap node /var/folders/rc/rcFucU9oF5qT5vZE\+tL1JE\+\+\+TI/-Tmp-/execjs20121008-1505-1v364bs.js 2>&1
Started GET "/" for 127.0.0.1 at 2012-10-08 23:45:06 -0700
Processing by TopicsController#index as HTML
Topic Load (0.3ms) SELECT "topics".* FROM "topics" ORDER BY sticky desc
(0.2ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."topic_id" = 4
(0.2ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."topic_id" = 1
(0.2ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."topic_id" = 2
(0.2ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."topic_id" = 3
Rendered topics/index.html.erb within layouts/application (216.9ms)
Completed 500 Internal Server Error in 1479ms
ActionView::Template::Error (dyld: Library not loaded: /opt/local/lib/libssl.1.0.0.dylib
Referenced from: /usr/local/bin/node
Reason: image not found
(in /Users/mm/Sites/authorizationPart1/forum-after/app/assets/javascripts/sessions.js.coffee)):
3: <head>
4: <title>Forum</title>
5: <%= stylesheet_link_tag "application", media: "all" %>
6: <%= javascript_include_tag "application" %>
7: <%= csrf_meta_tag %>
8: </head>
9: <body>
app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb___3636075050981736840_2167808160'
^C[2012-10-08 23:48:50] INFO going to shutdown ...
[2012-10-08 23:48:50] INFO WEBrick::HTTPServer#start done.
Exiting
Gem list
aaronh-chronic (0.3.9 ruby)
abstract (1.0.0)
actionmailer (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
actionpack (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
activemodel (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
activerecord (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
activeresource (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
activesupport (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
acts-as-taggable-on (2.3.3)
acts_as_indexed (0.7.8)
addressable (2.3.2, 2.2.8, 2.2.6 ruby, 2.0.2)
ansi (1.4.3, 1.4.2)
arel (3.0.2 ruby, 2.2.3, 2.0.10, 2.0.8)
awesome_nested_set (2.1.5, 2.1.3)
awesome_print (1.1.0)
babosa (0.3.8, 0.3.7)
backbone-on-rails (0.9.2.1, 0.9.2.0)
bcrypt-ruby (3.0.1 ruby)
binding_of_caller (0.6.8)
bson (1.7.0)
bson_ext (1.7.0)
builder (3.1.3, 3.0.3 ruby, 3.0.2, 3.0.0 ruby, 2.1.2)
bundler (1.2.1, 1.2.0.pre.1)
capybara (1.1.2 ruby)
cargo_wiki (1.0.1)
carrierwave (0.5.8)
childprocess (0.3.5, 0.3.0 ruby)
chunky_png (1.2.6)
coderay (1.0.7, 1.0.5 ruby, 0.9.7)
coffee-rails (3.2.2 ruby, 3.1.1)
coffee-script (2.2.0 ruby)
coffee-script-source (1.3.3 ruby, 1.3.1)
columnize (0.3.6)
commonjs (0.2.6)
compass (0.12.2)
compass-rails (1.0.3)
cucumber (1.2.1, 1.1.4 ruby, 0.10.0)
cucumber-rails (1.3.0, 1.2.1 ruby, 0.3.2)
cucumber-websteps (0.9.0 ruby)
daemons (1.1.9, 1.1.8)
data_mapper (1.2.0, 0.9.11)
data_objects (0.10.9, 0.9.12)
database_cleaner (0.7.0 ruby)
debugger (1.2.0)
debugger-linecache (1.1.2)
debugger-ruby_core_source (1.1.3)
devise (2.1.2, 2.0.4)
diff-lcs (1.1.3 ruby, 1.1.2)
dm-aggregates (1.2.0, 0.9.11)
dm-cli (1.2.0, 0.9.11)
dm-constraints (1.2.0)
dm-core (1.2.0, 0.9.11)
dm-is-tree (1.2.0, 0.9.11)
dm-migrations (1.2.0, 0.9.11)
dm-observer (1.2.0, 0.9.11)
dm-serializer (1.2.2, 0.9.11)
dm-timestamps (1.2.0, 0.9.11)
dm-transactions (1.2.0)
dm-types (1.2.2, 0.9.11)
dm-validations (1.2.0, 0.9.11)
do_mysql (0.10.9)
dragonfly (0.9.12)
dropbox-sdk (1.5.1, 1.1)
eco (1.0.0)
eco-source (1.1.0.rc.1)
ejs (1.1.1, 1.0.0)
erubis (2.7.0 ruby, 2.6.6)
eventmachine (1.0.0, 1.0.0.rc.4, 0.12.10)
exception_notification (2.5.2 ruby)
excon (0.16.4, 0.16.1)
execjs (1.4.0 ruby, 1.3.0)
extlib (0.9.15)
factory_girl (4.1.0, 2.4.2 ruby, 1.3.3)
factory_girl_rails (4.1.0)
faraday (0.8.4 ruby)
fastercsv (1.5.5)
ffi (1.1.5, 1.0.11 ruby)
filters_spam (0.3)
formtastic (2.2.1 ruby, 1.2.3)
friendly_id (4.0.8, 4.0.7)
fssm (0.2.9)
gherkin (2.11.2, 2.7.3 ruby, 2.3.3)
gli (2.3.0)
globalize3 (0.2.0)
gmaps4rails (1.5.5)
guard (1.4.0)
guard-rspec (2.0.0)
haml (3.1.7)
haml-rails (0.3.5)
hashie (1.2.0)
hello-world (1.2.0)
hello_world (0.0.2)
heroku (2.32.8, 2.30.3)
heroku-api (0.3.5, 0.3.4)
hike (1.2.1 ruby)
hirb (0.7.0)
htmlentities (4.3.1)
httpauth (0.2.0, 0.1)
i18n (0.6.1 ruby, 0.6.0 ruby, 0.5.0)
jist (1.0.1)
journey (1.0.4 ruby)
jquery-rails (2.1.3, 2.1.2 ruby, 2.1.1 ruby, 2.0.2, 1.0.19)
jquery-ui-rails (2.0.2, 2.0.0)
json (1.7.5 ruby, 1.7.3, 1.6.6, 1.6.3, 1.4.6)
json_pure (1.7.5)
jwt (0.1.5)
launchy (2.1.2, 2.0.5 ruby)
less (2.2.2)
less-rails (2.2.3)
lesstile (1.1.0, 1.0.1 ruby)
libv8 (3.11.8.3 x86_64-darwin-10, 3.3.10.4 x86_64-darwin-10)
libwebsocket (0.1.5)
listen (0.5.3)
mail (2.4.4 ruby, 2.3.3, 2.2.19, 2.2.15)
market_beat (0.2.0)
method_source (0.8)
methodfinder (1.2.5)
mime-types (1.19 ruby, 1.18, 1.16)
mongo (1.7.0)
mongodb (2.1.0)
multi_json (1.3.6 ruby, 1.2.0, 1.0.4 ruby)
multipart-post (1.1.5 ruby)
netrc (0.7.7)
nokogiri (1.5.5, 1.5.0 ruby)
oauth (0.4.7, 0.4.5)
oauth2 (0.8.0)
omniauth (1.1.1)
omniauth-facebook (1.4.1)
omniauth-oauth2 (1.1.1, 1.1.0)
open_id_authentication (1.1.0 ruby)
orm_adapter (0.4.0, 0.0.7)
paper_trail (2.6.3)
pg (0.14.0)
polyglot (0.3.3 ruby, 0.3.1)
pry (0.9.10, 0.8.3)
pry-doc (0.4.4)
pry-nav (0.2.2 ruby)
pry-rails (0.2.2, 0.2.0)
pry-remote (0.1.6 ruby)
pry-stack_explorer (0.4.7)
rack (1.4.1 ruby, 1.3.6, 1.2.5, 1.2.1)
rack-cache (1.2 ruby)
rack-flash (0.1.2)
rack-mount (0.8.3, 0.6.14, 0.6.13)
rack-openid (1.3.1 ruby, 1.2.0)
rack-protection (1.2.0 ruby)
rack-ssl (1.3.2 ruby)
rack-test (0.6.2, 0.6.1 ruby, 0.5.7)
rails (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
rails3-generators (0.17.6)
rails_autolink (1.0.9)
railties (3.2.8 ruby, 3.2.6, 3.1.3, 3.0.4)
rake (0.9.2.2 ruby, 0.8.7)
rb-fsevent (0.9.2)
rdiscount (1.6.8)
rdoc (3.12 ruby)
redcarpet (2.1.1)
RedCloth (4.2.9 ruby, 4.2.8)
refinerycms (2.0.8, 2.0.5)
refinerycms-authentication (2.0.8, 2.0.5)
refinerycms-blog (2.0.4)
refinerycms-core (2.0.8, 2.0.5)
refinerycms-dashboard (2.0.8, 2.0.5)
refinerycms-i18n (2.0.2, 2.0.0)
refinerycms-images (2.0.8, 2.0.5)
refinerycms-pages (2.0.8, 2.0.5)
refinerycms-resources (2.0.8, 2.0.5)
refinerycms-settings (2.0.2)
rest-client (1.6.7)
rmagick (2.13.1)
routing-filter (0.3.1)
rspec (2.11.0, 2.8.0 ruby, 2.5.0)
rspec-core (2.11.1, 2.8.0 ruby, 2.5.1)
rspec-expectations (2.11.3, 2.8.0 ruby, 2.5.0)
rspec-mocks (2.11.3, 2.8.0 ruby, 2.5.0)
rspec-rails (2.11.0, 2.8.1 ruby, 2.5.0)
ruby-openid (2.2.1, 2.1.8 ruby)
ruby_parser (2.3.1)
rubyzip (0.9.9, 0.9.5 ruby)
sass (3.2.1 ruby, 3.1.20, 3.1.15, 3.1.12 ruby)
sass-rails (3.2.5 ruby, 3.2.3 ruby, 3.1.6)
scrapi (2.0.0, 1.2.0)
selenium-webdriver (2.25.0, 2.17.0 ruby)
seo_meta (1.3.0)
sexp_processor (3.2.0)
simple_form (2.0.3, 2.0.2)
simple_oauth (0.1.9)
sinatra (1.3.3 ruby)
sinatra-static-assets (1.0.4)
slop (3.3.3)
sprockets (2.6.0, 2.1.3 ruby, 2.0.3)
sqlite3 (1.3.6 ruby, 1.3.5 ruby, 1.3.3)
sqlite3-ruby (1.3.3)
stringex (1.4.0)
strong_parameters (0.1.3)
term-ansicolor (1.0.7 ruby, 1.0.5)
therubyracer (0.10.2)
thin (1.5.0, 1.4.1 ruby)
thor (0.16.0 ruby, 0.15.4, 0.14.6)
tidy (1.1.2)
tidy_ffi (0.1.4)
tilt (1.3.3 ruby)
treetop (1.4.10 ruby, 1.4.9)
truncate_html (0.5.5)
turn (0.9.6, 0.8.2)
twitter (4.0.0, 3.7.0)
twitter-bootstrap-rails (2.1.3)
twix (0.0.1)
tzinfo (0.3.33 ruby, 0.3.24)
uglifier (1.3.0 ruby, 1.2.6, 1.2.4)
uuidtools (2.1.3)
warden (1.2.1, 1.1.1)
webrat (0.7.3 ruby)
will_paginate (3.0.3, 3.0.2 ruby, 3.0.pre2)
xml-simple (1.1.1)
xpath (0.1.4 ruby)
yahoo_sports (0.2.1, 0.2.0)
yard (0.8.2.1)
A: To fix the problem I did
brew uninstall node
brew install node
This seems to be a common problem with people who have uninstalled MacPorts. Googling around, I've discovered that people have had to uninstall postgres or mysql as well, depending on the unique circumstances.
A: You should just update yarn:
brew upgrade yarn
and run
yarn install
| |
doc_23527903
|
What really worries me is that I end up having lots of switchMaps.
why?
*
*loader is asynchronous
*I also need to translate the message passing from interceptor to loader service. Translating messages is also asynchronous. In interceptor, I should run the request when loader and translating finishes
What I do in my loader service
public showLoader(message) {
return this.translateService.get(message).pipe(
switchMap((translatedMessage) => {
this.loader$ = from(
this.loadingController.create({ message: translatedMessage })
);
return this.loader$.pipe(
switchMap((loader) => {
return from(loader.present());
})
);
})
);
}
in my interceptor
public intercept(request: HttpRequest<any>, next: HttpHandler) {
return this.loaderService.showLoader("WAITING").pipe(
take(1),
switchMap( ()=>{
so there are already 3 nested switchMaps. And below it, I need 2 or 3 more switchMaps (one for getting tokens from storage and one for something else). Basically end up having 5 switchMaps.
Question: Is nesting all these switchMaps considered an anti-pattern?
A: It's fine to use many switchMap especially when you need asynchronous behaviour, the bad practice is to touch things outside of the data stream.
In your code this.loader$ is an example of it, instead of using variables outside of a stream try to build a pipe that does everything you want inside of itself.
You can even omit from if this.loadingController.create and loader.present are Promise like, switchMap supports Observable, Promise, Array and Iterator.
Your code could be like that
public showLoader(message) {
return this.translateService.get(message).pipe(
switchMap(translatedMessage => this.loadingController.create({message: translatedMessage})),
switchMap(loader => loader.present()),
);
}
| |
doc_23527904
|
go get -u ./...
..this package would stay unchanged (but the rest refreshed normally).
A: Use go modules. It was specifically designed to handle precise version control.
In your package's go.mod you can pin any dependencies to a fixed version e.g.
module example.com/hello
go 1.12
require (
golang.org/x/text v0.3.0 // indirect
rsc.io/quote v1.5.2
rsc.io/quote/v3 v3.0.0
rsc.io/sampler v1.3.1 // indirect
)
You can update individual package versions e.g.:
go get rsc.io/quote/v3@master
Will pull the latest commit version (beyond even any semver tagged version).
You can also hand edit go.mod for extra precision.
P.S. you need go version 1.11 or later for go modules. go 1.13 has modules turned on by default. Earlier versions you have to explicitly enable it via the env var GO111MODULE=ON.
| |
doc_23527905
|
module Api
module V1
class Order < ActiveRecord::Base
has_many :order_lines
accepts_nested_attributes_for :order_lines
end
end
module Api
module V1
class OrderLine < ActiveRecord::Base
belongs_to :order
end
end
In my orders controller, I permit the order_lines_attributes param:
params.permit(:name, :order_lines_attributes => [
:quantity, :price, :notes, :priority, :product_id, :option_id
])
I am then making a post call to the appropriate route which will create an order and all nested order_lines. That method creates an order successfully, but some rails magic is trying to create the nested order_lines as well. I get this error:
Uninitialized Constant OrderLine.
I need my accepts_nested_attributes_for call to realize that OrderLine is namespaced to Api::V1::OrderLine. Instead, rails behind the scenes is looking for just OrderLine without the namespace. How can I resolve this issue?
A: I am pretty sure that the solution here is just to let Rails know the complete nested/namespaced class name.
From docs:
:class_name
Specify the class name of the association. Use it only
if that name can't be inferred from the association name. So
belongs_to :author will by default be linked to the Author class, but
if the real class name is Person, you'll have to specify it with this
option.
I usually see, that class_name option takes the string (class name) as a argument, but I prefer to use constant, not string:
module Api
module V1
class Order < ActiveRecord::Base
has_many :order_lines,
class_name: Api::V1::OrderLine
end
end
end
module Api
module V1
class OrderLine < ActiveRecord::Base
belongs_to :order,
class_name: Api::V1::Order
end
end
end
| |
doc_23527906
|
In both tables I have the column "licensePlate".
In the table cars I have the values: 0000 0001 0002 0003
In the table repair I have the values: 0000 0002 0003.
How can I extract only the value 0001 that is in the table cars but not in repair?
I think I don't use the correct "operator" or something like that:
select car.licensePlate
from car, repair
where car.licensePlate (something) reparir.licensePlate;
A: You should use NOT EXISTS or LEFT JOIN, as in:
select c.licensePlate
from car c
where not exists (select 1 from repair r where c.licensePlate = r.licensePlate;
You specifically should not use NOT IN, because it has strange semantics (that is, acts weird) if the subquery returns a NULL value on any row. When this occurs, then the outer query will return no rows as all.
For this reason, I strongly recommend NOT EXISTS instead of NOT IN with subqueries.
A: You could use the not in operator:
SELECT licensePlate
FROM car
WHERE licensePlate NOT IN (SELECT licensePlate
FROM repair)
A: Using the NOT IN operator should solve your problem. How it would work is:
SELECT CAR.LICENSEPLATE FROM CAR
WHERE CAR.LICNESEPLATE NOT IN (SELECT REPAIR.LICENSEPLATE FROM REPAIR)
When this query would be executed it would be read as:
SELECT CAR.LICENSEPLATE FROM CAR
WHERE CAR.LICNESEPLATE NOT IN (0000,0002,0003)
This is because in any query consisting of sub-query the sub-query is executed first, in this case which is SELECT REPAIR.LICENSEPLATE FROM REPAIR, and the result of the sub-query is passed on to the main query. Which sums up to the query mentioned just above.
Hope it helps. Cheers!
| |
doc_23527907
|
However say Application A needs an immediate response from a service on Application B e.g. Needs the provisioning details of an Order OR Needs an immediate confirmation on some update. Is Messaging the right solution for that from a performance point of view? Normally the client would connect to a MoM on a Queue - then a listener which has to be free will pick up the message and forward to the server side processor - which will process the response and send it back to a Queue or Topic and the requesting client will follow the same process and pick it up. If the message size is big the MoM will have to factor that in as well.
Makes me wonder if Http is a better solution to access such solutions instead of going via messaging route? I have seen lots of applications use MoM like AMQ or TIBCO Rvd to actually use for immediate Request/Response - but is that bad design or is it some fine tuning or setting that makes it same as Http.
A: It really depends on your requirements. Typically messaging services will support one or all of the following:
*
*Guaranteed Delivery
*Transactional
*Persistent (i.e. messages are persisted until delivered, even if the system fails in the interrim)
An HTTP connection cannot [easilly] implement these attributes, but then again, if you don't need them, then I suppose you could make the case that "simple" HTTP would offer a simpler and more lightweight solution. (Emphasis on the "simple" because some messaging implmentations will operate over HTTP).
I don't think Request/Response implemented over messaging is, in and of itself, bad design. I mean, here's the thing.... are you implementing both sides of this process ? If not, and you already have an established messaging service that will respond to requests, all other considerations aside, that would seem to be the way to go... and bypassing that to reimplement using HTTP because of some desgin notion would need some fairly strong reasoning behind it, in my view.
But the inverse is true as well. If you an HTTP accessible resource already, and you don't have any super stringent requirements that might otherwise suggest a more robust messaging solution, I would not force one in where it's not warranted.
If you are commensing totally tabula-rasa and you must implement both sides from scratch..... then..... post another question here with some details ! :)
| |
doc_23527908
|
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QTableView, QPushButton, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
app = QApplication(sys.argv)
app.setStyle("experiment")
tab = QTableView()
sti = QStandardItemModel()
for idx in range(0,3):
sti.appendRow([QStandardItem(str(i)) for i in range(4)])
tab.setModel(sti)
tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
tab.setIndexWidget(sti.index(idx, 3), QPushButton("button"))
tab.show()
sys.exit(app.exec_())
How can i check / detect with cell button was pressed ?
Any guidance is greatly appreciated.
A: You have to connect the clicked signal of the button:
from functools import partial
import sys
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QTableView, QPushButton, QAbstractItemView
app = QApplication(sys.argv)
app.setStyle("experiment")
tab = QTableView()
tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
sti = QStandardItemModel()
tab.setModel(sti)
def on_clicked(index):
print("clicked", index)
for idx in range(0, 3):
sti.appendRow([QStandardItem(str(i)) for i in range(4)])
btn = QPushButton("button")
btn.clicked.connect(partial(on_clicked, idx))
tab.setIndexWidget(sti.index(idx, 3), btn)
tab.show()
sys.exit(app.exec_())
| |
doc_23527909
|
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
A: I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A: A couple of things:
*
*Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
*Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
*Use opendir(), readdir() and closedir() for reading directory contents; and
*Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
A: You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
A: Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
A: Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
A: Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}
| |
doc_23527910
|
I save several classes during the serialization.
I want to know that if a class changes in the future and there is a missing field or an extra field in the saved file, is it possible to inform the user saying that "Field 1 is missing" or "There is an extra field in saved file".
I know that datacontract serializer can deserialize in this kind of situations but i want to know which fields are missing or extra too.
Or should i use another save mechanism in order to provide this? (Some pattern, or should i write custom serializer?)
| |
doc_23527911
|
Any help would be greatly appreciated, thank you.
Here is my codepen.io link:http://codepen.io/theller5567/pen/wWvJjv?editors=1010
the code below is under CompareBasket.prototype.removeItem function
var d = this.el;
var preview = $('[data-idx = "' + items.indexOf(item) + '"]')[0];
console.log(preview);
this.el.removeChild(preview);
this.el = $('.compare-basket');
to add an item to the compare basket click on the plus icon at the top right of product. to remove item click on the small icon at top of page in compare-basket div.
A: @MajediSabuj solved the problem: try $('[data-idx = "' + items.indexOf(item) + '"]').remove();
Still not sure why the original code i had did not work:
var preview = this.el.querySelector('[data-idx = "' + items.indexOf(item) + '"]'); this.el.removeChild(preview);
But it works:)
| |
doc_23527912
|
However, when I run a Dotnet build, it succeeds with no warnings or errors and the project runs.
My project.json:
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.1.0",
"type": "platform"
},
"Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
"Microsoft.EntityFrameworkCore.Design": {
"version": "1.1.0",
"type": "build"
},
"Microsoft.AspNetCore.Mvc": "1.1.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
"Microsoft.Extensions.Configuration.Json": "1.1.0",
"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.1.0",
"Microsoft.Extensions.Logging.Debug": "1.1.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
"Microsoft.AspNetCore.StaticFiles": "1.1.0"
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": "dnxcore50"
}
}
}
Any ideas? I'm really pulling my hair out with this one.
A: In VS Code on Fedora 30 with .NET Core 3.0 I had the same issue after create a worker project with dotnet new worker
First issue was that OmniSharp server didn't find the Sdks folder and the solution was include this line to the ~/.bashrc:
export MSBuildSDKsPath="/usr/share/dotnet/sdk/$(dotnet --version)/Sdks"
then restart VS Code, but C# extension show me some messages like:
The type or namespace name 'Collections' does not exist in the namespace 'System' (are you missing an assembly reference?)
the solution was, first, in the terminal run:
dotnet build
then restart the OmniSharp server using the command palette (Ctrl+Shift+P):
OmniSharp: Restart OmniSharp
then I restart VS Code and the C# extensions and all dependencies are working fine.
A: Sometimes C# for Visual Studio Code (powered by OmniSharp) becomes confused.
Try restarting OmniSharp. Here are two ways:
*
*Close and re-open Visual Studio Code, or
*Open the Command Pallet and type Restart Omnisharp.
OmniSharp tends to become confused if we restore dependencies from the command line instead of from within Visual Studio Code.
A: Ok, I've figured out what was causing the issue. I was referencing the wrong imports for the framework part of the project.json file.
This:
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": "dnxcore50"
}
}
Should be this:
"frameworks": {
"netcoreapp1.1": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
}
I'm on a windows 8 machine, and for some reason "dnxcore50" isn't valid, but "dotnet5.6" and "portable-net45+win8" is. I'm going to keep looking at the why for this question, but I am posting this answer now in case someone else is dealing with this problem.
A: If you get this error, you could be missing a package.
“The type or namespace name 'System' could not be found”
To add a package, you can run this command in the terminal:
dotnet add package
Example: Add Newtonsoft.Json NuGet package to a project:
dotnet add package Newtonsoft.Json
After that, go to the squiggly line, and add the missing reference by clicking on the lightbulb.
You can also install the Nuget Package Manager extension to find out what packages you need. See this answer to find out more:
Install a Nuget package in Visual Studio Code
A: I'm using VS Code in a mac with OmniSharp and mono and the issue was gone after doing the following:
For MacOS and Linux users who have Mono installed, this means you will need to set omnisharp.useGlobalMono to never until a version of Mono ships with MSBuild 16.7.
A: In my case vscode showed this error only for one file. The problem was solved by adding the missing file to the Assembly-CSharp.csproj I'm not sure when files are automatically added and when I do have to do it manually, but it solved this issue.
...
<ItemGroup>
<Compile Include="Assets/Scripts/data/MissingFile.cs" />
...
A: Same issue happened to me lot of times ..
in my case i opened the visual studio code as admin
then run the teriminal command donet buid
if required Restart OmniSharp (ctrl +shift + p)
Then It's working fine !!!
A: Another possible cause of getting errors regarding "using System" is storing the .vscode directory in the git repository (my not adding it to .gitignore).
Opening the solution folder with VSCode can create cross version problems like the above and can be solved simply by deleting the .vscode directory.
| |
doc_23527913
|
I was looking at a formula =Column(SheetNames) that told me there were 16 sheets.
SheetNames is a named range =REPLACE(GET.WORKBOOK(1),1,FIND("]",GET.WORKBOOK(1)),"")
But when i enter the formula bar and/or press CTRL ALT F9 to recalculate it shows #BLOCKED! What could be causing this please. It is not doing this on the original computer.
I don't get this problem when redo the formula and range name in another file so i suspect there must be something within the original file causing the problem.
Regards Peter
A: Get is an old XLM macro language command. These may be blocked on the machine you are using.
From the Microsoft documentation about the #BLOCKED! error:
Functions with XLM macros are blocked Functions with Excel 4.0 (XLM)
macros can't be evaluated for one or more of the following reasons:
Excel 4.0 (XLM) macros are turned off because of macro settings.
Excel 4.0 (XLM) macros aren't supported in current version of Excel.
For more information, see Working with Excel 4.0 macros.
A: Assuming your organization has not mandated they be turned off, Excel 4 macros can be enabled by selecting:
*
*"File" from the Ribbon menuing system
*Selecting "Options" at the bottom of the bar on the left that higher up has things like "Open" and "Print"
*Selecting the last area on the list (also somehow not a menu any more than the Ribbon is...) called "Trust Center"
*Clicking the button at the lower right of the text in the panel to the right labelled "Trust Center Settings"
*Selecting "Macro Settings" from the panel on the left (again, still not a menu...)
*Clicking "Enable Excel 4.0 macros when VBA macros are enabled"
AND
*Making sure VBA macros ARE enabled in the choices provided above
No guarantee that your organization's IP folks haven't found a choice in the Group Policy Editor that turns off your ability to set this up.
Sadly, Excel has not seen fit to provide an in-cell formula to replace GET.WORKBOOK so I cannot offer a substitute.
Since you have the formula in a Named Range, and so all uses in the workbook presumably refer to the Name Range, and all you need do is modify the Named Range, a single step, sort of, in order to spread a new approach into the spreadsheet, an alternative suggests itself. If your organization allows, it should not be hard at all to write the corresponding VBA function into a UDF that you can then reference in the Named Range's formula instead.
However...
It seems likely the "proximate cause" of your current problem is simply the computer you transferred the file to has Excel 4.0 macros turned off. It works on yours so they are turned on on yours and so presumably your organization allows the use of macros, or at least does not forbid them.
But since the problem occurred, it seems it is hit or miss for every computer whether macros (definitely Excel 4.0 macros, and probably also VBA macros) aare turned on or not on any given machine.
Accordingly, subject to your personal knowledge of the personalities of their users, it seems the best approach would be to get each computer owner you send the file to to activate Excel 4.0 macros on their computers as ANY choice, even VBA, would seem to require that conversation, or a similar discussion concerning VBA, take place.
(As an aside, the funny thing is usually when Excel 4.0 macros come up, people go on about you not really wanting an antiquated system in use that MS says they might trash any old time, and that you should replace what it does with some nice VBA macro instead (assuming there is no nice cell-side function provided nowadays, of course). Except, you know, they've been saying that for 20 years now. And VBA stopped developing in something like 2006. So it is antiquated on the same scale the Excel 4.0 macros are antiquated...
No question VBA is better. Just... it's as antique now as the Excel 4.0 macros so... c'mon folks.)
| |
doc_23527914
|
// index.js
const functions = require('@google-cloud/functions-framework');
functions.http('mp4Transcoder', (req, res) => {});
// dev-server.js
#!/usr/bin/env node
const express = require('express')
const app = express()
const router = express.Router()
const func = require('./index')
const bodyParser = require('body-parser')
app.use(bodyParser.raw({ type: 'application/octet-stream' }))
router.post('/transcoder', func.transcode)
router.options('/transcoder', func.transcode)
app.use('/', router)
// start the server
const port = 3030
const http = require('http')
app.set('port', port)
const server = http.createServer(app)
server.listen(port)
// package.json
{
"name": "transcoder-cloud-function",
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0"
}
}
If I copy and paste this code and deploy the cloud function, it works. However, if I zip the three files and try to create uploading the zip file, the deployment fails with "function.js does not exist".
Any ideas of what I could try?
A: If you are trying to deploy an Express app to Cloud Function then you should be passing the Express app instance to the Cloud Function and not use the function as a router. Try refactoring the code as shown below:
// index.js
const functions = require('@google-cloud/functions-framework');
const { app } = require('./dev-server.js');
functions.http('mp4transcoder', app);
// dev-server.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.raw({ type: 'application/octet-stream' }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.send('Hello World!')
})
// app.use('/', router)
exports.app = app
// package.json
{
"name": "transcoder-cloud-function",
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"body-parser": "^1.20.1"
}
}
Then try redeploying the function either by uploading the ZIP file or directly using gcloud CLI:
gcloud functions deploy mp4transcoder --gen2 --trigger-http --runtime=nodejs16
Also checkout Cloud Function for Firebase as its a bit easier to deploy that way.
A: Ok, the answer was simpler than I expected: the zip file had the wrong file structure. Google Cloud is expecting the folder structure zip > your files, not zip > folder > your files, as was the case.
| |
doc_23527915
|
I have built a redis server in a docker container and am using it in cluster mode.
I can access the redis server and ping well.
However, when executing the get/set command, the following error message is output and the connection with the redis is lost.
Could not connect to Redis at 172.19.0.4:6300: Connection failed due to no response from the connected member or connection was lost due to no response from the host.
I would really appreciate it if you could help me with the above problem.
I guessed that the connection and ping were done well, so it was a security-related configuration problem.
So I tried to set the security setting of the redis.conf file to no, but the problem was not solved.
'protected-mode no'
| |
doc_23527916
|
Here's the log: https://pastebin.com/Qf5W6MZU
Any other endpoints in this controller also doesn’t work.
import org.sefglobal.scholarx.exception.BadRequestException;
import org.sefglobal.scholarx.exception.NoContentException;
import org.sefglobal.scholarx.exception.ResourceNotFoundException;
import org.sefglobal.scholarx.exception.UnauthorizedException;
import org.sefglobal.scholarx.model.Mentee;
import org.sefglobal.scholarx.model.Profile;
import org.sefglobal.scholarx.model.Program;
import org.sefglobal.scholarx.service.IntrospectionService;
import org.sefglobal.scholarx.util.EnrolmentState;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/me")
public class AuthUserController {
private final IntrospectionService introspectionService;
public AuthUserController(IntrospectionService introspectionService) {
this.introspectionService = introspectionService;
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public Profile getLoggedInUser(@CookieValue(value = "profileId", defaultValue = "-1") long profileId)
throws ResourceNotFoundException, UnauthorizedException {
return introspectionService.getLoggedInUser(profileId);
}
@GetMapping("/programs/mentee")
@ResponseStatus(HttpStatus.OK)
public List<Program> getMenteeingPrograms(@CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, NoContentException {
return introspectionService.getMenteeingPrograms(profileId);
}
@PutMapping("/mentor/{id}/confirmation")
@ResponseStatus(HttpStatus.OK)
public Mentee confirmMentor(@PathVariable long id,
@CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, BadRequestException {
return introspectionService.confirmMentor(id, profileId);
}
}
A: I found the issue I haven’t included the package.
| |
doc_23527917
|
SELECT [Fm].[Id], [Sdp].[FirstName], [Sdp].[LastName], [Sdp].[SSN],
[Sdp].[StoreName],
case when isnumeric([Sdp].[PostalCode]) = 1 then CONVERT(CHAR(10),[Sdp].[PostalCode])
else '0' end, [Fc].[Id], [Sdp].[Address]
FROM [SRM].[SiteMembers].[DProfile] AS [Sdp]
INNER JOIN [SRM].[SiteMembers].[Member] AS [Sm]
ON [Sdp].[Member_Id] = [Sm].[Id]
INNER JOIN [FRM].[Members].[Member] AS [Fm]
ON [Sm].[UserId] = [Fm].[UserId]
INNER JOIN [SRM].[General].[City] AS [Sc]
ON [Sdp].[City_Id]=[Sc].[Id]
INNER JOIN [FRM].[General].[City] AS [Fc]
ON [Fc].[Title]=[Sc].[Title]
COLLATE SQL_Latin1_General_CP1_CI_AS
Whit this script the Over flow error raised like this:
Msg 248, Level 16, State 1, Line 2
The conversion of the varchar value '4153675759' overflowed an int column.
I ask a question here and I don't want back to past with 2 scripts, So is there any way to check the PostalCode is numeric (and I mean numeric not int) without any error?
A: If you want to check that a (n)(var)char value consists of digits and only digits, then a simply double negative LIKE will work:
PostalCode not like '%[^0-9]%'
which will only be true if there are no non-digits within the string.
A: Use
case
when [Sdp].[PostalCode] like '%[^0-9]%'
then 0 else CONVERT(CHAR(10),[Sdp].[PostalCode]) end
A: Try BIGINT. Each of the numeric datatypes have a range. For example SMAIINT ranges from +32767 till -32768. TINYINT ranges from 0 to 255
| |
doc_23527918
|
class SearchDocument(es.DocType)
# Verblijfsobject specific data
gebruiksdoel_omschrijving = es.String(index='not_analyzed')
oppervlakte = es.Integer()
bouwblok = es.String(index='not_analyzed')
gebruik = es.String(index='not_analyzed')
panden = es.String(index='not_analyzed')
sbi_codes = es.Nested({
'properties': {
'sbi_code': es.String(index='not_analyzed'),
'hcat': es.String(index='not_analyzed'),
'scat': es.String(index='not_analyzed'),
'hoofdcategorie': es.String(fields= {'raw': es.String(in dex='not_analyzed')}),
'subcategorie': es.String(fields={'raw':es.String(index='not_analyzed')}),
'sub_sub_categorie': es.String(fields= {'raw': es.String(index='not_analyzed')}),
'bedrijfsnaam': es.String(fields= {'raw': es.String(index='not_analyzed')}),
'vestigingsnummer': es.String(index='not_analyzed')
}
})
As is clear, it says "not analysed" in the document for most fields. This works OK for the "regular fields". The problem is in the nested structure. There the hoofdcategorie and other fields are indexed for their separate words instead of the unanalysed version.
The structure is filled with the following data:
[
{
"sbi_code": "74103",
"sub_sub_categorie": "Interieur- en ruimtelijk ontwerp",
"vestigingsnummer": "000000002216",
"bedrijfsnaam": "Flippie Tests",
"subcategorie": "design",
"scat": "22279_12_22254_11",
"hoofdcategorie": "zakelijke dienstverlening",
"hcat": "22279_12"
},
{
"sbi_code": "9003",
"sub_sub_categorie": "Schrijven en overige scheppende kunsten",
"vestigingsnummer": "000000002216",
"bedrijfsnaam": "Flippie Tests",
"subcategorie": "kunst",
"scat": "22281_12_22259_11",
"hoofdcategorie": "cultuur, sport, recreatie",
"hcat": "22281_12"
}
]
Now when I retrieve aggregates it has split the hoofdcategorie in 3 different words ("cultuur", "sport", "recreatie"). This is not what I want, but as far as I know I have specified it correctly using the "not analysed" phrase.
Anyone any ideas?
| |
doc_23527919
| ||
doc_23527920
|
now it works like this. you need to display products linked to any entity - seller, category, brand, search phrase. first, a query is executed that sorts the goods by some column - revenue, rating, name, number of sales. then 100 products are selected, information for the final table is calculated based on them. if the next 100 products are needed, then the offset in the sorting query will be executed. A request that receives information on goods counts data for 30 days, plans to increase the period to 90 days. If there are more than 90 thousand products, the request does not have time to be executed or rests on the fact that memory has run out. will portioning help in this case? or how do they cope with such a load?
*
*product
id - int, create_at, status, group_id, pics, is_new, lost_sale
*product_group
id, brand_id, seller_id, name
*product_log
create_at, product_id, price, price_discount, rating, comment, order_count, sales_count, quantity
*category_product
id, category_id, product_id
as an example of sorting - sorts goods by revenue and gets 100 pieces
WITH temp_products AS (SELECT `p`.`id` AS `id`,
`p`.`create_at` AS `create_at`,
`p`.`lost_sale` AS `revenue_lost`,
`pg`.`name` AS `name`,
`b`.`id` AS `brand_id`,
`b`.`name` AS `brand_name`,
`s`.`id` AS `seller_id`,
`s`.`name` AS `salesman_name`,
`s`.`ogrn` AS `salesman_ogrn`,
`s`.`trademark` AS `salesman_trademark`
FROM `product` `p`
LEFT JOIN `product_group` `pg` ON p.group_id = pg.id
LEFT JOIN `seller` `s` ON pg.seller_id = s.id
LEFT JOIN `brand` `b` ON pg.brand_id = b.id
WHERE `pg`.`seller_id` = '414336'),
base AS (SELECT `p`.`id`, `pl`.`create_at`, (pl.price_discount * pl.order_count) AS `revenue`
FROM `temp_products` `p`
join `product_log` `pl` ON p.id = pl.product_id
WHERE `pl`.`create_at` BETWEEN 1659294000 AND 1661886000),
summary AS (SELECT `id`, sum(revenue) AS `revenue` FROM `base` GROUP BY `id`)
SELECT `id`, `revenue`
FROM `summary`
ORDER BY `revenue` DESC
LIMIT 100
collects information on 100 products
WITH products AS (SELECT `p`.`id` AS `id`,
`p`.`create_at` AS `create_at`,
`p`.`lost_sale` AS `revenue_lost`,
`pg`.`name` AS `name`,
`b`.`id` AS `brand_id`,
`b`.`name` AS `brand_name`,
`s`.`id` AS `seller_id`,
`s`.`name` AS `salesman_name`,
`s`.`ogrn` AS `salesman_ogrn`,
`s`.`trademark` AS `salesman_trademark`
FROM `product` `p`
LEFT JOIN `product_group` `pg` ON p.group_id = pg.id
LEFT JOIN `seller` `s` ON pg.seller_id = s.id
LEFT JOIN `brand` `b` ON pg.brand_id = b.id
WHERE `pg`.`seller_id` = '414336'),
logs AS (SELECT `pl`.`product_id` AS `product_id`,
`pl`.`create_at` AS `create_at`,
`pl`.`price` AS `price`,
`pl`.`price_discount` AS `price_discount`,
`pl`.`rating` AS `rating`,
`pl`.`comment` AS `comment`,
`pl`.`order_count` AS `order_count`,
`pl`.`refund_count` AS `refund_count`,
`pl`.`quantity` AS `quantity`,
(pl.order_count * pl.price_discount) AS `revenue`,
row_number() over (partition by product_id order by create_at desc) AS `day`
FROM `product_log` `pl`
WHERE (pl.product_id in (select id from products))
AND (`pl`.`create_at` BETWEEN 1656702000 AND 1661886000))
SELECT `p`.`id` AS `id`,
`p`.`id` AS `sku`,
concat('https://www.wildberries.ru/catalog/', p.id, '/detail.aspx') AS `url`,
`p`.`create_at` AS `create_at`,
`p`.`name` AS `name`,
coalesce(p.brand_id, '') AS `brand_id`,
coalesce(p.brand_name, '') AS `brand_name`,
coalesce(p.seller_id, '') AS `salesman_id`,
coalesce(p.salesman_name, '') AS `salesman_name`,
coalesce(p.salesman_ogrn, '') AS `salesman_ogrn`,
coalesce(p.salesman_trademark, '') AS `salesman_trademark`,
`p`.`revenue_lost` AS `revenue_lost`,
(select price_discount from logs where product_id = p.id and day = 1) AS `price`,
(select round(avg(rating))
from logs
where product_id = p.id
and rating > 0
and create_at between 1659294000 and 1661886000) AS `rating`,
(select comment
from logs
where product_id = p.id
and day = 1) AS `review_count`,
(select quantity
from logs
where product_id = p.id
and day = 1) AS `in_stock`,
(select round(AVG(price_discount))
from logs
where product_id = p.id
and create_at between 1659294000 and 1661886000) AS `price_average`,
(select sum(order_count)
from logs
where product_id = p.id
and create_at between 1659294000 and 1661886000) AS `order_value`,
(select sum(order_count)
from logs
where product_id = p.id
and create_at between 1656702000 and 1659294000) AS `order_prev`,
(select sum(revenue)
from logs
where product_id = p.id
and create_at between 1659294000 and 1661886000) AS `revenue_value`,
(select sum(revenue)
from logs
where product_id = p.id
and create_at between 1656702000 and 1659294000) AS `revenue_prev`,
(SELECT GROUP_CONCAT(order_count)
FROM (SELECT order_count
FROM logs
WHERE product_id = p.id
LIMIT 30) as order_chart
) AS `order_chart`,
(select IF(COUNT(*) > 30, 30, COUNT(*)) AS c
from logs
where product_id = p.id
and create_at between 1659294000 and 1661886000
and quantity > 0) AS `was_on_sale_for_month`
FROM `products` `p`
ORDER BY `revenue_value` DESC
A: Please use different aliases for different tables. I am getting confused over what p refers to.
If the question is about performance,
*
*Get rid seller and brand (and maybe other things), the seem to have no impact on the result.
*If possible, use derived tables instead of CTE; CTE is still in its infancy. I worry that it does not have many optimizations folded in yet.
*In the second query, you can probably do all those SUMs in a single query, rather than scanning the table about 8 times.
Please provide
*
*EXPLAIN SELECT ...
*SHOW CREATE TABLE
| |
doc_23527921
|
I want to use Elasticsearch 5.5.
What versions of Spring Boot and Spring Data Elasticsearch should I use?
Thank you!
A: On this Spring github page https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix, you can find compatible versions of Spring Boot, Spring Data ElasticSearch and ElasticSearch.
Currently supported versions of ElasticSearch are < 5.0.0
Edit: This page I posted is probably outdated. I'm sorry for confusing.
On git project of spring-data-elasticsearch is in README that for using Elasticsearch 5.5.0 you can use Spring data elasticsearch 3.0.x https://github.com/spring-projects/spring-data-elasticsearch
| |
doc_23527922
|
$comment = new Post_comment();
$comment->id_poster = Input::get('id_poster');
$comment->like = "ciao";
$comment->text = Input::get('text');
$comment->id_post = Input::get('post_id');
if ($comment->save()) {
$status = "success";
} else {
$status = $comment->Ardent->errors()->all(); // this not working
}
echo json_encode(array('status' => $status));
A: Just get rid of the ->Ardent segment:
$status = $comment->errors()->all();
Since Ardent extends Eloquent, you don't need to access it that way, all its functionality is in the original class. I guess that you are using that because you followed the package's documentation literally, but when it says
Retrieve all validation errors with Ardent->errors()->all(). Retrieve
errors for a specific attribute using
Ardent->validationErrors->get('attribute').
it really means that you should replace Ardent with your model instance.
| |
doc_23527923
|
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.6</maven.compiler.source>
Still, when I run the application I get an "Unsupported major.minor version" error and I suspect that one of my dependency jars is compiled with a Java version newer than the one I need to support.
My questions:
*
*Is this even possible? I thought Maven would take care of this kind of dependency version problems.
*Is there an easy way to find out the minor/major version of all my dependencies? (Would be awesome if it could be shown when doing mvn dependency:tree for instance.)
A: The problem is that every dependency (maintainer) can decide on it's own which java version is used to compile (1.5, 1.6, 1.7, 1.8 etc) so this is not solvable via Maven. But you can make sure that you don't use dependencies which are using a different Java version than you like to have.
This can be enfored by using Maven Enforcer Plugin by using extra-enforcer-rules:
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version> <!-- find the latest version at http://maven.apache.org/plugins/maven-enforcer-plugin/ -->
<executions>
<execution>
<id>enforce-bytecode-version</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<enforceBytecodeVersion>
<maxJdkVersion>1.6</maxJdkVersion>
<excludes>
<exclude>org.mindrot:jbcrypt</exclude>
</excludes>
</enforceBytecodeVersion>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>extra-enforcer-rules</artifactId>
<version>1.0-beta-5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
[...]
</project>
This will break your build if you have a dependency which is compiled with a different version of JDK than you want to have.
A: To answer your two questions:
Yes, this is possible. Looking at the docs, the <maven.compiler.target> and <maven.compiler.source> properties simply tells Maven which version of javac to use to compile your project. And I quote, for your reference:
Note: Merely setting the target option does not guarantee that your
code actually runs on a JRE with the specified version. The pitfall is
unintended usage of APIs that only exist in later JREs which would
make your code fail at runtime with a linkage error. To avoid this
issue, you can either configure the compiler's boot classpath to match
the target JRE or use the Animal Sniffer Maven Plugin to verify your
code doesn't use unintended APIs.
The magic number after the Unsupported major.minor version error actually tells the version of the JRE the class file is compatible with:
J2SE 8 = 52,
J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
I don't know if there is an easy way to tell the major/minor version of ALL the dependencies (and transitive dependencies) in a project though.
UPDATE: Though I haven't used it before, I wonder the Animal Sniffer Maven plugin will help to sniff out the major/minor version of your dependencies.
| |
doc_23527924
|
I have created an R shiny dashboard app that is quickly getting quite complex. I have over 1300 lines of code all sitting in app.R and it works. I'm using RStudio.
My application has a sidebar and tabs and rather than using modules I dynamically grab the siderbar and tab IDs to generate a unique identifier when plotting graphs etc.
I'm trying to reorganise it to be more manageable and split it into tasks for other programmers but I'm running into errors.
Working Code
My original code has a number of library statements and sets the working directory to the code location.
rm(list = ls())
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
getwd()
I then have a range of functions that sit outside the ui/server functions so are only loaded once (not reactive). These are all called from within the server by setting the reactive values and calling the functions from within something like a renderPlot. Some of them are nested, so a function in server calls a function just in regular app.R which in turn calls another one. Eg.
# Start of month calculation
som <- function(x) {
toReturn <- as.Date(format(x, "%Y-%m-01"))
return(toReturn)
}
start_fc <- function(){
fc_start_date <- som(today())
return(fc_start_date)
}
then in server something like this (code incomplete)
server <- function(input, output, session) {
RV <- reactiveValues()
observe({
RV$selection <- input[[input$sidebar]]
# cat("Selected:",RV$selection,"\r")
})
.......
cat(paste0("modelType: ",input[[paste0(RV$selection,"-modeltype")]]," \n"))
vline1 <- decimal_date(start_pred(input[[paste0(RV$selection,"-modeltype")]],input[[paste0(RV$selection,"-modelrange")]][1]))
vline2 <- decimal_date(start_fc())
.......
Problem Code
So now when I take all my functions and put them into different .R files I get errors indicating the functions haven't been loaded. If I load the source files by highlighting them and Alt-Enter running them so they are loaded into memory then click on Run App the code works. But if I rely on Run App to load those source files, and the functions within them, the functions can't be found.
source('./functionsGeneral.R')
source('./functionsQuote.R')
source('./functionsNewBusiness.R')
source('./ui.R')
source('./server.R')
shinyApp(ui, server)
where ui.R is
source('./header.R')
source('./sidebar.R')
source('./body.R')
source('./functionsUI.R')
ui <- dashboardPage(
header,
sidebar,
body
)
Finally the questions
In what order does R Shiny Dashboard run the code. Why does it fail when I put the exact same inline code into another file and reference it with source('./functions.R')? Does it not load into memory during a shiny app session? What am I missing?
Any help on this would be greatly appreciated.
Thanks,
Travis
A: Ok I've discovered the easiest way is to create a subfolder called R and to place the preload code into that folder. From shiny version 1.5 all this code in the R folder is loaded first automatically.
| |
doc_23527925
|
I'm trying to understand C basic data types automatic type conversions, promotions etc and wonder if I can use printf instead of dummy function to check what happens.
To make my question clearer with an example,
void f1 (int a){}
int main() { f1('c'); return 0; }
helps me understand what will happen if I declare a function with an int argument but pass char type in the call.
I want to know if I can just call
printf("%i", 'c');
for the above purpose.
Also if someone can point to some definitive resources (on web or books) on type representation/conversions/promotion in C, I'll be grateful.
A: No.
Many compilers don't do any type checking on format strings. gcc does, when -Wformat is used, but these checks are separate from those done on assignment.
Parameters to printf are passed as they are. The only conversion may be increasing it to a processor word size (this is how char becomes int) and it doesn't depend on the format string in any way. See Jonathan Leflfer's comment, which explains this more accurately.
A: printf("%i", 'c'); you will get ASCII value of character 'c' which is 99.There are two methods for char to int.
If you just want ASCII value of char simply print char using integer specifier.
If you want to convert a char to integer(Like '0' to 0 or '1' to 1) then you need to do as follows
char a = '4';
int ia = a - '0'; //subtraction of '0'
Just an addition for more clarity, specifier in printf says how much to pop from stack. If it is %d then pop 4 bytes(assuming int of 4 byte) if it is %c, then pop 1 byte etc.
A:
Is printf's conversion specifier equivalent to function declaration as
far as compiler type checking and automatic conversions go?
No. When you pass a char to a variadic function, the value you pass will be promoted to an int. This is regardless of the conversion specifier you use. The C11 standard describes this at §6.5.2.2p7:
The ellipsis notation in a function prototype declarator causes
argument type conversion to stop after the last declared parameter.
The default argument promotions are performed on trailing arguments.
Default argument promotions are defined in §6.5.2.2p6 as a superset of integer promotions:
... the integer promotions are performed on each argument, and
arguments that have type float are promoted to double. These are
called the default argument promotions.
... and integer promotions are defined in §6.3.1.1p2:
If an int can represent all values of the original type (as restricted
by the width, for a bit-field), the value is converted to an int;
otherwise, it is converted to an unsigned int. These are called the
integer promotions.
To make my question clearer with an example,
void f1 (int a){}
int main() { f1('c'); return 0; }
helps me understand what will happen if I declare a function with an
int argument but pass char type in the call.
No, it doesn't. 'c' is actually an int. If you don't believe me, see for yourself:
#include <stdio.h>
#ifdef __cplusplus
#error "Don't compile C code with a C++ compiler."
#endif
int main(void) {
printf("sizeof 'c': %zu\n", sizeof 'c');
}
A: When you pass 'c' as an argument to the function f1 the ASCII value of alphabet c (99) will be stored into a .So if you modify the f1 function below
void f1 (int a){
printf("\n %d",a); // prints the ascii value of charecter c
printf("\n %c",a); //prints the o/p as c
printf("\n %i",a); //prints the ascii value of charecter c again
}
O/p for the program
99
c
99
You asked
I want to know if I can just call printf("%i", 'c');
Yes you can then there's no need of the implementation of the function f1.
| |
doc_23527926
|
The variable "devices" is just null. Any idea what did I do wrong?
A: RfcommDeviceService.GetDeviceSelector function to help to enumerated paired device.
So, first, you need to pair the device in Windows 10 bluetooth manager or you can add code lines to pair it. And then using FindAllAsync() to get it.
About how to pair device in code, you can reference Device enumeration and pairing sample.
| |
doc_23527927
|
The HTML of the undo button is made up of the following
<a href="" style="vertical-align: middle" class="btn btn-primary btn-sm" ng-show="true" ng-click="executeUndoCommand(transfer)">Undo</a>
The row within the table that contains the Undo button is made up of the following
<tr ng-repeat="transfer in completedTransfersSummary track by $id(transfer)">
<td style="vertical-align: middle" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}" ng-class="
{'highlight' : transfer.transferorBusinessId == CisBusinessID }"
class="highlight">608445</td>
<td style="vertical-align: middle" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}" ng-class="
{'highlight' : transfer.transfereeBusinessId == CisBusinessID }">608446</td>
<td style="vertical-align: middle" nowrap="" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">Merger</td>
<td style="vertical-align: middle" nowrap="" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">19/07/2018</td>
<td style="vertical-align: middle" nowrap="" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">02/01/2018</td>
<td style="vertical-align: middle" nowrap="" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">1.00 entitlements @
€229.27</td>
<td style="vertical-align: middle" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">526461</td>
<td style="vertical-align: middle" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}">2018</td>
<td style="vertical-align: middle" ng-
style="transfer.isDisabled && {color:'#A6A6A6'}"></td>
<td style="vertical-align: middle;" ng-
show="undoWithdrawRoleAssignedToUser">
<div ng-show="transfer.transferorBusinessId ==
CisBusinessID">
<a href="" style="vertical-align: middle"
class="btn btn-primary btn-sm" ng-show="true" ng-
click="executeUndoCommand(transfer)">Undo</a>
<a href="" style="vertical-align: middle"
class="btn btn-primary btn-sm ng-hide" ng-show="false" ng-
click="showUndoModal(transfer)">Undo</a>
<a href="" style="vertical-align: middle"
class="btn btn-default btn-sm" ng-show="true" ng-
click="executeWithdrawCommand(transfer)">Withdraw</a>
<a href="" style="vertical-align: middle"
class="btn btn-default btn-sm ng-hide" ng-show="false" ng-
click="showWithdrawModal(transfer)">Withdraw</a>
<label style="vertical-align: middle" ng-
show="false" ng-style="transfer.isDisabled && {color:'#A6A6A6'}"
class="ng-hide"></label>
<label style="vertical-align: middle" ng-
show="false" ng-style="transfer.isDisabled && {color:'#A6A6A6'}"
class="ng-hide"></label>
</div>
</td>
</tr>
I used the following XPath to highlight the Undo button on the screen
("//tr[td='Merger']//a[@ng-click='executeUndoCommand(transfer)']")
It reuturns the button I requre but also returns 3 hidden buttons, for the test I am running I need to only select the displayed button. The button I requre is the 4th on the list below
$x("//tr[td='Merger']//a[@ng-click='executeUndoCommand(transfer)']")
(4) [a.btn.btn-primary.btn-sm.ng-hide, a.btn.btn-primary.btn-sm.ng-hide,
a.btn.btn-primary.btn-sm.ng-hide, a.btn.btn-primary.btn-sm]
0
:
a.btn.btn-primary.btn-sm.ng-hide
1
:
a.btn.btn-primary.btn-sm.ng-hide
2
:
a.btn.btn-primary.btn-sm.ng-hide
3
:
a.btn.btn-primary.btn-sm
length
:
4
I changed the xpath to the following to attempt to select the displayed button but these are not working
$x("//tr[td='Merger']//a[@ng-click='executeUndoCommand(transfer)' and
@class='btn btn-default btn-sm']")
$x("//tr[td='Merger']//a[@ng-click='executeUndoCommand(transfer)']//a[@ng-
show='true']")
Can anybody suggest a way to hightlight the button I require?
A: Try something similar to this
//a[text()='Undo' and not(contains(@class,'hide'))]
A: I believe this would work for you //tr[td='Merger']//a[@ng-click='executeUndoCommand(transfer)'][@class='btn btn-default btn-sm']
A: Since the A link buttons contain the attributes of either ng-show="true" or ng-show="false", this XPATH selector should work:
//a[text()='Undo' and @ng-show="true"]
| |
doc_23527928
|
button.setVisibility(View.VISIBLE); and button.setVisibility(View.INVISIBLE); to hide and show the button.
here is my code bellow.
public class QuestionActivity extends Activity {
MediaPlayer mySound;
List<Question> quesList;
int qid = 0;
//for help 50/50
int help =0;
int score = 0;
int rnd2 ,rnd1;
ProgressBar progressBar;
private static MyCountDownTimer myCountDownTimer;
// Animation
Animation animFadein;
Question currentQ;
TextView txtQuestion, scored;
Button button1, button2, button3, button4,helpbtn;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public void help (View view){
helpbtn=(Button)findViewById(R.id.helpbtn);
helpbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
help = help -1;
if(help == 0){
helpbtn.setEnabled(false);
}
if (help > 0){
helpbtn.setEnabled(true);
}
String AnswerString = currentQ.getANSWER();
//match DB answer to selected answer, turn it visible if it is correct
if(button1.getText().equals(AnswerString)){
button1.setVisibility(View.VISIBLE);
}
if(button2.getText().equals(AnswerString)){
button2.setVisibility(View.VISIBLE);
}
if(button3.getText().equals(AnswerString)){
button3.setVisibility(View.VISIBLE);
}
if(button4.getText().equals(AnswerString)){
button4.setVisibility(View.VISIBLE);
}
//random hide 2 incorrect answers
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Collections.shuffle(list);
rnd1 = list.get(0);
rnd2 = list.get(1);
/*int answer = 2; // Correct answer
List<Integer> list = new ArrayList<>();
rnd1 = list.get(0);
rnd2 = list.get(1);
for(int i = 1; i<= 4 ; i++) {
if (i != answer) {
list.add(i);
}
}*/
if ((rnd1 == 1) || (rnd2 == 1)){
button1.getText().equals(AnswerString);
button1.setVisibility(View.INVISIBLE);
}
if ((rnd1 == 2) || (rnd2 == 2)){
button2.getText().equals(AnswerString);
button2.setVisibility(View.INVISIBLE);
}
if ((rnd1 == 3) || (rnd2 == 3)){
button3.getText().equals(AnswerString);
button3.setVisibility(View.INVISIBLE);
}
if ((rnd1 == 4) || (rnd2 == 4)){
button4.getText().equals(AnswerString);
button4.setVisibility(View.INVISIBLE);
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qestion);
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all questions
currentQ = quesList.get(qid); // the current question
mySound = MediaPlayer.create(this, R.raw.bensoundcute); // music background
mySound.start();
mySound.setLooping(true);
mySound.setAudioStreamType(AudioManager.STREAM_MUSIC);
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// load the textQuestion animation
animFadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
// the text view in which the question will be displayed
// the 4 buttons,
// the idea is to set the text of 4 buttons with the options from question bank
progressBar = (ProgressBar)findViewById(R.id.progressbar);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
// the text view in which score will be displayed
scored = (TextView) findViewById(R.id.score);
// method which will set the things up for our game
setQuestionView(false);
txtQuestion.setAnimation(animFadein);
txtQuestion.startAnimation(animFadein);
// button click listeners
final MediaPlayer buttonSound = MediaPlayer.create(this, R.raw.play);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonSound.start();
// passing the button text to other method
// to check whether the answer is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(30000, 500);
myCountDownTimer.start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonSound.start();
getAnswer(button2.getText().toString());
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(30000, 500);
myCountDownTimer.start();
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonSound.start();
getAnswer(button3.getText().toString());
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(30000, 500);
myCountDownTimer.start();
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonSound.start();
getAnswer(button4.getText().toString());
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(30000, 500);
myCountDownTimer.start();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
// Create custom dialog object
final Dialog dialog = new Dialog(QuestionActivity.this ,android.R.style.Theme_NoTitleBar_Fullscreen);
// Include dialog.xml file
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
// Set dialog title
// set values for custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textDialog);
text.setText("Everytime you get 5 Correct answer, youre help points increases, use this help points to elemenate 2 incorrect answer");
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
dialog.show();
Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Close dialog
dialog.cancel();
buttonSound.start();
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(100);
myCountDownTimer = new MyCountDownTimer(30000, 500);
myCountDownTimer.start();
}
});
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Question Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
myCountDownTimer.cancel();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
int progress = (int) (millisUntilFinished/300);
Log.v("Log_tag", "Timer Progress " + millisUntilFinished);
progressBar.setProgress(progress);
}
@Override
public void onFinish() {
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
progressBar.setProgress(0);
myCountDownTimer.cancel();
Toast.makeText(getApplicationContext(),
"Times Up!.",
Toast.LENGTH_SHORT)
.show();
if (score > 49){
Intent intent = new Intent(QuestionActivity.this,
Successresult.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
myCountDownTimer.cancel();
startActivity(intent);
finish();
} else {
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
startActivity(intent);
myCountDownTimer.cancel();
finish();
}
}
}
@Override
protected void onPause(){
super.onPause();
mySound.release();
finish();
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user pressed "yes", then he is allowed to exit from application
dialog.dismiss();
onYesClick();
}
private void onYesClick() {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
myCountDownTimer.cancel();
finish();
QuestionActivity.this.finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void getAnswer(String AnswerString) {
myCountDownTimer.cancel();
Log.d("TIMER", "timer canceled");
Log.d("Tag", "score = " + score + ", help = " + help +" remaining");
if(myCountDownTimer != null) {
myCountDownTimer.cancel(); // Stop Timer
}
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
Toast.makeText(getApplicationContext(), "CORRECT!", Toast.LENGTH_SHORT).show();
score++;
scored.setText("Score: " + score + " /100");
if(score % 5 == 0) {
help = help+1;
Log.d("Tag", "score = " + score + ", help = " + help);
Toast.makeText(getApplicationContext(), "Your help Encreases", Toast.LENGTH_SHORT).show();
}
}
else {
Log.d("TIMER", "timer canceled");
myCountDownTimer.cancel();
// if unlucky start activity and finish the game
Toast.makeText(getApplicationContext(), "Sorry! Better luck next time.", Toast.LENGTH_SHORT).show();
if (score > 49){
myCountDownTimer.cancel();
Intent intent = new Intent(QuestionActivity.this,
Successresult.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
myCountDownTimer.cancel();
startActivity(intent);
finish();
}
}
if(qid < 101) {
// if questions are not over then do this
currentQ = quesList.get(qid);
setQuestionView(true);
txtQuestion.setAnimation(animFadein);
txtQuestion.startAnimation(animFadein);
button1 .setVisibility(View.VISIBLE);
button2 .setVisibility(View.VISIBLE);
button3 .setVisibility(View.VISIBLE);
button4 .setVisibility(View.VISIBLE);
}
else {
myCountDownTimer.cancel();
// if unlucky start activity and finish the game
Toast.makeText(getApplicationContext(), "Game Over.", Toast.LENGTH_SHORT).show();
if (score > 49){
Intent intent = new Intent(QuestionActivity.this,
Successresult.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
setQuestionView(false);
startActivity(intent);
finish();
}
}
}
private boolean setQuestionView(boolean b) {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
button4.setText(currentQ.getOPTD());
qid++;
return b;
}
}
A: In this list don't add the number that is the correct answer,
List list = Arrays.asList(1, 2, 3, 4);
i.e: if correct answer is 2 then set List as following
int answer = 2; // Correct answer
List<Integer> list = new ArrayList<>();
for(int i = 1; i<= 4 ; i++) {
if(i != answer) {
list.add(i);
}
}
So when you get random number the answer button will not be hidden
A: I feel you should make the other buttons Visible,while your hiding the reuired button
A: @SanjayHirani is on the right track so I'll go with a modified version of his answer. Try this...
int answer = getAnswerNumber();
List<Integer> list = new ArrayList<>();
for(int i = 1; i<= 4 ; i++) {
if (i != answer) {
list.add(i);
}
}
Collections.shuffle(list);
int rnd1 = list.get(0);
int rnd2 = list.get(1);
I was testing with a reduced version of your code so my getAnswerNumber was a bit different but here's what I think will work for you.
private int getAnswerNumber() {
// returns 1 if none of the button text matches the answer, hopefully this won't happen
int answerNumber = 1;
if (button1.getText().equals(AnswerString)) {
answerNumber = 1;
} else if (button2.getText().equals(AnswerString)) {
answerNumber = 2;
} else if (button3.getText().equals(AnswerString)) {
answerNumber = 3;
} else if (button4.getText().equals(AnswerString)) {
answerNumber = 4;
}
Log.d("Quiz" , "answer no. = " + answerNumber);
return answerNumber;
}
| |
doc_23527929
|
def print_message(text, string)
text.print_line string
end
Ruby will send a message called #print_line to different methods in the rest of my code. These methods will all implement #print_line in different ways. For instance:
class PutsText
def print_line(string)
puts(string + "\n")
end
end
class UpcaseText
def print_line(string)
puts(string.upcase + "\n")
end
end
print_message PutsText.new, "Text"
print_message UpcaseText.new, "uppercase text"
I believe that this is what is called polymorphism.
Now, what I don't understand is that this code also works:
def print_message(text, string)
text.print_line string
end
def print_number(number, float)
number.print_line float
end
class PutsText
def print_line(string)
puts(string + "\n")
end
end
class UpcaseText
def print_line(string)
puts(string.upcase + "\n")
end
end
class PutsNumber
def print_line(float)
puts(float)
end
end
print_message PutsText.new, "Text"
print_message UpcaseText.new, "uppercase text"
print_number PutsNumber.new, (3.56 + 1.27)
Shouldn't the message #print_line be ambiguous for Ruby in different contexts like this?
| |
doc_23527930
|
My program imports a string from a json file, say for example "#python is #great".
I am trying to parse the string so for each occurrence of "#" it prints out the word following until it gets to a non alphanumeric character like a space or "=". So in this example it prints: #python #great
The code I have so far is:
with open("tweet.json") as json_file:
data = json.load(json_file)
#opens my twitter file
def find_all(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
tags = find_all(data, "#")
length = len(tags)
#finds all occurrences of the "#" character
Up until here it all runs fine, but inside this loop it won't work unfortunately.
for x in range (0, length):
items = data[tags[x]:data.find('^\W+$')]
print items
x += 1
It also cuts of the final character too. I'm really stuck on this so any help is appreciated.
A: re.findall(r'#\w+', data)
\w is for matching [A-Za-z_0-9] or all alphanumeric characters.
A: regex seems like the ideal solution here
print re.findall("#[a-zA-Z]+",data)
| |
doc_23527931
|
My current approach involves passing a pointer to a struct:
type goresult struct {
result resultType;
finished bool;
}
which the goroutine writes upon completion. Then it's a simple matter of checking finished whenever convenient. Do you have better alternatives?
What I'm really aiming for is a Qt-style signal-slot system. I have a hunch the solution will look almost trivial (chans have lots of unexplored potential), but I'm not yet familiar enough with the language to figure it out.
A: Select statements allows you to check multiple channels at once, taking a random branch (of the ones where communication is waiting):
func main () {
for {
select {
case w := <- workchan:
go do_work(w)
case <- signalchan:
return
// default works here if no communication is available
default:
// do idle work
}
}
}
For all the send and receive
expressions in the "select" statement,
the channel expressions are evaluated,
along with any expressions that appear
on the right hand side of send
expressions, in top-to-bottom order.
If any of the resulting operations can
proceed, one is chosen and the
corresponding communication and
statements are evaluated. Otherwise,
if there is a default case, that
executes; if not, the statement blocks
until one of the communications can
complete.
A: You can also peek at the channel buffer to see if it contains anything by using len:
if len(channel) > 0 {
// has data to receive
}
This won't touch the channel buffer, unlike foo, gotValue := <- ch which removes a value when gotValue == true.
A: You can use the "comma, ok" pattern (see their page on "effective go"):
foo := <- ch; // This blocks.
foo, ok := <- ch; // This returns immediately.
| |
doc_23527932
|
I defined a function that takes as parameter a rvalue to a unique_ptr like this:
void print(std::unique_ptr<Car>&& car)
{
std::cout << "Car" << car->Get() << std::endl;
}
The class Car is a simple class:
class Car
{
public:
Car(int i) : N(i) { std::cout << "Car" << N << std::endl; }
~Car() { std::cout << "~Car" << N << std::endl; }
int Get() { return N; }
private:
int N;
};
Now if I call the function like this:
std::unique_ptr<Car> car = std::make_unique<Car>(99);
print(std::move(car));
I find that the car object is not destroyed after calling the print() function. Casting to an rvalue does not invoke a move constructor in this case.
However, if I change my function definition like so:
void print(std::unique_ptr<Car> car)
{
std::cout << "Car" << car->Get() << std::endl;
}
Then the car object is no longer valid after calling print(). The parameter of print() is a proper sink parameter.
This is quite interesting since everything I've read says that you should expect an object to be destroyed after using std::move - i.e. its internal resources are no longer valid.
I would be grateful for some better explanation.
A: So the first thing to remember is that std::move is misnamed. It does not ever move anything. It just makes it possible to move a thing by wrapping it in a special kind of reference.
The "move constructor" is the thing that does an actual move. std::unique_ptr<T>(std::unique_ptr &&ref), for example.
Function parameters are copy or move constructed with a preference for move construction.
So, your first attempt just used it as a reference and never moved anything. You could have the same effect with a regular reference (a single &).
The second one does a proper move and after the call car will be nullptr inside the unique ptr. And car will destruct at the end of print.
| |
doc_23527933
|
[root@overcloud-controller-0 ~]# docker ps |grep keep 32837abc03ad
192.168.24.1:4000/tripleoqueens/centos-binary-keepalived:current-tripleo "dumb-init --singl..." 2 hours ago Restarting (0) 58 minutes ago
keepalived
Could you please help me why this keep alived is always restarting ? docker log is attached
Script security disabled Default script uid:gid 0:0
------< SSL definitions >------ Using autogen SSL context Keepalived_vrrp exited with permanent error CONFIG. Terminating
Stopping Stopped Unexpected argument(s): | tee /var/log/keepalived.log
Stopped Keepalived v1.3.5 (03/19,2017), git commit v1.3.5-6-g6fa32f2
Unexpected argument(s): | tee /var/log/keepalived.log
answer file :
templates: /usr/share/openstack-tripleo-heat-templates/
environments:
- environments/network-isolation.yaml
- environments/net-single-nic-with-vlans.yaml
- environments/network-environment.yaml
- environments/ips-from-pool-all.yaml
- environments/scheduler-hints.yaml
- environments/ceph-ansible/ceph-ansible.yaml
- environments/storage-config.yaml
- environments/node-info.yaml
- environments/overcloud_images.yaml
Is there somthing I need to give specific to keepalived ?
| |
doc_23527934
|
This jsFiddle shows behaviour I don't expect: Even though the red box is constrained to the x axis, a droppable's over() handler is still getting called when the pointer enters it, rather than when the dragged element itself intersects it.
Is this a jQueryUI bug? If so, is there a workaround?
$(function() {
$( "#draggable" ).draggable({
axis: 'x' // Constrain drag
});
$( ".over" ).droppable({
tolerance: 'intersect', // Surely should not trigger "over()" unless dragged object itself is over the element??
over: function( event, ui ) {
$( this )
.find( "p" )
.html( "over!" );
}
});
});
A: Seems to be a bug... It looks like the over function is tied to the cursor and not the actual draggable element, seems to occur in a number of other instances as well...
I found a couple of possible workarounds:
*
*Add the containment option to the draggable like so:
Working Example
$(function () {
$("#draggable").draggable({
axis: 'x',
containment: 'parent'
});
$(".over").droppable({
tolerance: 'intersect',
over: function (event, ui) {
$(this)
.find("p")
.html("over!");
}
});
});
*
*Throw the whole thing into a hover function and destroy the draggable when its not being hovered:
Working Example
$(function () {
$("#draggable").hover(function () {
$("#draggable").draggable({
axis: 'x'
});
$(".over").droppable({
tolerance: 'intersect',
over: function (event, ui) {
$(this)
.find("p")
.html("over!");
}
});
}, function () {
$("#draggable").draggable("destroy");
});
});
| |
doc_23527935
|
<?php
if(!isset($_POST['submit-enquiry']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$guest_email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['enquiry-message'];
//Validate first
if(empty($name)||empty($guest_email))
{
echo '<script language="javascript">';
echo 'alert("Name and email are mandatory")';
echo '</script>';
exit;
}
if(IsInjected($visitor_email))
{
echo '<script language="javascript">';
echo 'alert("Bad Email Value")';
echo '</script>';
exit;
}
$email_from = $guest_email;//<== update the email address
$email_subject = "Enquiry from $name";
$email_body = "Name: $name. \n". "Mobile: $mobile .\n". "Message: $message. \n";
$to = "my_email";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $guest_email \r\n";
/ /Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: enquiry.php');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
The html of the fprm:
<div id="enquiry-form">
<form method="post" name="enquiry-form" action="" target="_self">
<span class="short-input" id="name">
<h6>name</h6>
<input type="text" name="name">
</span>
<span class="short-input" id="mobile">
<h6>mobile</h6>
<input type="text" name="mobile">
</span>
<span class="long-input" id="email">
<h6>e-mail</h6>
<input type="text" name="email">
</span>
<span class="long-input" id="enquiry-message">
<h6>enquiry</h6>
<textarea name="enquiry-message"></textarea>
</span>
</div>
<div id="contact-info">
<h2>Contact Details</h2>
</div>
<button type="submit" id="submit-enquiry" name="submit-enquiry">send</button>
</form>
A: try
if( (empty($name)) || (empty($guest_email)) )
for more infos : php operation precedence
A: Try
if( $name=='' || $guest_email=='' )
empty in some cases can lead to unexpected results. My experience led me to say that for a form validation it is better to check if the variable is empty in this way. Then you check the content of the variable (to see for example if it is a valid email) so this is safe enough for me.
If your code still doesn't work then it is necessary to do further investigations.
A: if( empty(trim($name)) || empty(trim($guest_email)) )
| |
doc_23527936
|
For future reference, is it possible to get c++ to print the header search paths it is searching?
My problem is that I keep getting path error problems, as shown below.
And I've tried updating the search paths in xcode for the project as follows:
where cv.h has the following info page:
The code I am trying to run is this:
What am I missing here?
BEFORE YOU MARK AS DUPLICATE:
I've already looked at previous posts on the topic, none of them have been helpful. I'll try to update with pictures etc. so updating path dependencies in xcode is fully covered in the future.
| |
doc_23527937
|
Here is the script:
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = '400,400'
$Form.Text = "Add DXE Mailbox Permissions"
$Form.TopMost = $false
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Text = "Username"
$Label1.AutoSize = $true
$Label1.Width = 25
$Label1.Height = 10
$Label1.Location = New-Object System.Drawing.Point(15, 145)
$Label1.Font = 'Microsoft Sans Serif,10'
$TextBox1 = New-Object System.Windows.Forms.TextBox
$TextBox1.Multiline = $false
$TextBox1.Width = 168
$TextBox1.Height = 20
$TextBox1.Location = New-Object System.Drawing.Point(15, 165)
$TextBox1.Font = 'Microsoft Sans Serif,10'
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = "Check Username"
$Button1.Width = 120
$Button1.Height = 30
$Button1.Location = New-Object System.Drawing.Point(199, 162)
$Button1.Font = 'Microsoft Sans Serif,10'
$Button1.Add_Click($Button1_Click)
$Form.Controls.AddRange(@($Label1, $TextBox1, $Button1))
$Button1_Click = {
$username = $Label1.Text
$Checkuser = Get-ADUser -Identity $username
if ($Checkuser -eq $null) {
$Button1.Text = "Can't Find User"
$button1.ForeColor = "Red"
} elseif ($Checkuser -ne $null) {
$Button1.Text = "Found User"
}
}
[void]$Form.ShowDialog()
I believe the problem I am having is to do with the line $username = $Label1.Text. I am not sure if $Label1.Text should be assigned to a varible, and if so how would I make PowerShell retrive the text that has been entered?
I had a quick look around and I am hoping that there is a way to do this without opening and closing another window.
A: You are referring to a wrong object here:
$username = $Label1.text
That's, em, the label. Of course you should get the value from the TextBox:
$username = $TextBox1.text
A: You need to assign the $Button1_Click action after you've defined it - otherwise you're just assigning $null to the Click event:
<# define controls here ... #>
$Form.controls.AddRange(@($Label1,$TextBox1,$Button1))
$Button1_Click = {
$username = $Label1.text
$Checkuser = Get-ADUser -Identity $username
If($Checkuser -eq $null){
$Button1.Text = "Can't Find User"
$button1.ForeColor = "Red"
}
Elseif($Checkuser -ne $null){
$Button1.Text = "Found User"
}
}
$Button1.Add_click($Button1_Click)
[void]$Form.ShowDialog()
If you want to grab the username from the text box, change $username = $Label1.text to $username = $TextBox1.Text
| |
doc_23527938
|
I've tried POSTing in two approaches:
*
*https://api.trello.com/1/lists/mylistid/cards?key=mykey&token=myToken&name=myName
which results in a 404 but is mentioned here as a suggested but untested response and seems to follow the Trello documentation here.
*https://api.trello.com/1/cards?key=myKey&token=myToken&name=myName based on the documentation here.
Neither works for me. Is the documentation correct or what am I doing wrong?
UPDATE (hoisted from comments)
I had the idList in the JSON which I was passing in but the content type was wrong. I had text/json, it should have been application/json. Option 2 works now.
A: var newCard = {
name: CARD_TITLE,
desc: CARD_DESC,
pos: "top",
idList: TRELLO_BOARD_LIST_ID
};
Trello.post('/cards/', newCard, success, error);
var success = function(successMsg) { /* your actions on success case */}
var error= function(errorMsg) { /* your actions on error case */}
client.js automatically adds app_key + token to url so you dont need to bother about that.
thats is working for me when using trello client.js .
short guide:
https://developers.trello.com/get-started/start-building#connect
Im pretty sure the concept is the same with other languages...
A: Just in case anyone needs Kotlin example (JDK 11 is required) is below.
It requires ObjectMapper (can be mavened from com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1 )
val token = //token
val appKey = //key
val listID = //list ID
val urlCards = "https://api.trello.com/1/cards"
val newCardName = //a name for a new card
val description = //a card description
val queryString = mapOf(
"key" to appKey,
"token" to token,
"idList" to listID,
"name" to newCardName,
"pos" to "top",
"desc" to description
)
val objectMapper = ObjectMapper()
val requestBody: String = objectMapper.writeValueAsString(queryString)
val client = HttpClient.newBuilder().build();
val request = HttpRequest.newBuilder()
.uri(URI.create(urlCards))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.header("content-type","application/json")
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
println(response.body())
| |
doc_23527939
|
I am using the command
\image ./pics/gnu_lic/gplv3_logo.svg
However I cannot see the image
.
├── dox
├── Doxyfile
└── pics
├── gbehistun.png
├── gnu_lic
│ ├── agplv3_logo.png
│ ├── agplv3_logo.svg
│ ├── gfdl_logo.svg
│ ├── gplv3_logo.png
│ └── gplv3_logo.svg
└── meidum
└── tridim_latis.png
A: There are two things one has to do.
First set IMAGE_PATH. In my case I used pics. Then my \image commands should be changed to be
/// \image html gplv3_logo.png
/// \image html gplv3_logo.svg
This will get the images displayed.
| |
doc_23527940
|
Sometimes we need to "completely reset" the DEV server to the latest version of LIVE. I understand I can merge; I can checkout ... but the problem is that in the meantime many files 'may' have been added to DEV ... so what I would want to do is kindoff "completely wipe" DEV, load it with LIVE and send the new update to DEV remote: this way
local DEV == local & remove LIVE (exact copies)
remote DEV = local DEV (and thereby now same as previous)
hmm does that make any sense?
My thinking was to
*
*Reset and sync DEV server with LIVE code? OR to overwrite LIVE -> DEV branche on remote?
*How do I remove all new files that are not in git? (they should be removed)
Otherwise formuluated: how do I sometimes completely reset my DEV server code/branch and make it an exact copy of the LIVE branch (no files more, no files less)
Many many ! thanks
A: First fetch the origin data so it's up to date
git fetch origin
Checkout your DEV branch
git checkout DEV
Then reset it with the branchname you want it to be. Use --hard to overwrite all changes.
git reset --hard origin/LIVE
Then commit the changes
git commit -a -m "Hard reset to LIVE"
then push them
git push origin/DEV
| |
doc_23527941
|
A: I am afraid azure devops doesnot have an out of box option to make Release description required.
However, these is a workaround by using the Invoke Rest Api Gate to check if Release description is given before deploying the releases. Using Gates cannot prevent you from creating the release. It will only stop executing the deployment.
Check below detailed steps:
1, create a service connection to your azure devops organization.
Go Project Setting--> Service connections under Pipelines-->Click new service connection--> select Generic to create a generic service connection.
2,Then Edit the service connection type the information shown in below screenshot. Check here to get a Personal access token.
3, Go the your release definition edit page-->Pre-deployment conditions-->Enable Gates-->Add Invoke Rest Api
4, Edit the Invokde Rest API
Select the generic service connection to your azure devops created in the first step.
Set the fields as below:
*
*URL suffix and parameters: /_apis/release/releases/$(Release.ReleaseId)?api-version=6.1-preview.8
*Success criteria: ne(root['description'],'')
please check here for more information about GET Release rest api.
See below screenshot:
When you create a release. The Gates will be evaluated and check if the release description is set. And will not execute the deployment if the Gate failed.
| |
doc_23527942
|
That part is already working. But I need to know if it's NOT working so that I can alert the user that their message did not go through and keep the posting form open. Here's some pertinent information about my app.
Social.Message = DS.Model.extend({
text: DS.attr("string"),
created: DS.attr("date"),
isPending: DS.attr("boolean"),
posts: DS.hasMany("Social.Post")
});
Social.Post = DS.Model.extend({
text: DS.attr("string"),
status: DS.attr("string"),
created: DS.attr("date"),
message: DS.belongsTo("Social.Message"),
msgStatus: function() {
return ((this.get('status') === 'S') ? true : false);
}.property('status')
});
The lifecycle of a post (status) goes from P (pending) to Q (queued) to S (sent), E (error) is also a possibility, and the status that I'm really looking for. Here's the saveMessage method:
saveMessage: function(text){
var acct = Social.Account.find(this.get("id")),
msg = Social.store.createRecord(
Social.Message,
{
text: text,
created: new Date()
}
);
acct.get("messages").addObject(msg);
Social.store.commit();
Ember.run.later(this, function() {
msg.get('posts').forEach(function(p){
p.reload();
});
}, 1000);
}
You can see that I pause for a second to let the server process, then attempt to reload the Post object with the response from Twitter. Those last few lines are where I think this new code would go, but I'm not sure how to listen to something that might not come back. I'd rather not "wait" for a second, instead it would be nice if the message could just update. Not sure how to accomplish that though.
Thoughts?
A: You need to run your code as a callback after the record is created. This is how:
msg.one('didCreate', function() {
// transition to new route showing data just created
});
Social.store.commit();
This will add a one time call on the record for when it is created. There are also 'didUpdate' and 'didDelete' hooks as well. You need to add these callbacks before the create is called (obviously).
I'm not sure how to handle the error condition as I haven't looked into that yet.
Edit: this is actually broken, per https://github.com/emberjs/data/issues/405, so waiting may be the only option currently.
A: It sounds like you don't want the two-way data binding here and you might benefit from one-way instead. Here is a great full length blog post that explains it a bit more in depth
http://www.solitr.com/blog/2012/06/ember-input-field-with-save-button/
| |
doc_23527943
|
I'm asking this question as I've read that it's deprecated
A: Even if you know exactly where you want to put each widget, you won't know the exact resolution of the devices which will run your application. Some will have empty space left on the screen, while others might not have room to display all your widgets.
Short version: better not use it, there are always better options.
A: In case of absolute layout, your application will adjust itself in every phn ,of any resolution or screen size. But in case of fixed coordinates may be screen size becomes a limitation.
A: It is a very bad practice to use absolute layout coordinates.
Don't use it.
| |
doc_23527944
|
"dependencies": {
"@types/jest": "28.1.4",
"identity-obj-proxy": "3.0.0",
"jest-junit": "14.0.0",
"ts-jest": "28.0.5"
}
The package includes a shrinkwrap file. The intention of this package is to install it in another project where it installs these specific version dependencies.
Now... when I install this package, there are no errors/warnings & it completes successfully, yetI see three inconsistent things happening that's confusing:
*
*two dependencies (identity-obj-proxy & jest-junit) are installed with the expected versions
*one dependency (@types/jest) was already present as an older version (by another dependency in the original project), but the version I'm specifying isn't installed
*one dependency (ts-jest) isn't installed at all
Looking at the verbose NPM install logs, I can see all the expected versions listed for all three types of behaviors above... 75% of them have only my version listed:
71 silly audit '@types/jest': [ '25.2.1', '28.1.4' ],
..
71 silly audit 'identity-obj-proxy': [ '3.0.0' ],
71 silly audit 'jest-junit': [ '14.0.0' ],
..
71 silly audit 'ts-jest': [ '28.0.5' ]
I can get around this by explicitly installing each dependency, but that defeats the purpose of this package as the whole point of it is:
*
*install specific versions of dependencies so the consumer doesn't have to figure out the correct versions to use
*run a postinstall script to make a few tweaks to the project
I've used two versions of the latest NPM (v8), both 8.5.5 & 8.13.2 have the same behavior. At a loss as to why this would happen... no errors, warnings, or other stuff in the logs are giving clues as to why this is happening. Ideas?
A: From what I understand, package resolution algorithms can be a bit unpredictable, and relying on this behavior can cause things to break when upgrading or changing your package manager. That being said, if you want to continue doing things this way but just have a little more control over the resolution, you can use overrides (npm) or resolutions (yarn) in package.json.
However, if I were maintaining this package, I'd prefer to explicitly list these dependencies as peerDependencies to ensure that the dependent package is resolving compatible versions. As of npm 7, npm will try to automatically install peerDependencies for you, but will error if there's a conflict (which you can fix with overrides).
| |
doc_23527945
|
A: *
*Define your datasource in your applicationContext
*Create your dao class that will do your inserts using JdbcTemplate
*Create a service class that calls the insert methods of your dao class
*Annotate the service class with @Transactional
*Add <tx:annotation-driven/> to your applicationContext and define a transactionManager which refers to your datasource.
See reference here and an example here.
| |
doc_23527946
|
Does iMessage extensions API allow to identify what sticker has been assigned to the sent message? If so are there are any limitation - about that the sticker must be the part of the same application or your extension can identify stickers from other extension.
| |
doc_23527947
|
(def classA ["John" "16"])
If I wanted to get information from the vector I would call
(get classA 0) ;; => "John"
(get classA 1) ;; => "16"
Now say I define classB as:
(def classB '(["John" "16"] ["Simon" "17"] ["Peter" "16"]))
How would I get the information "John" out?
Thanks
A: You can use first to get the first vector in the list:
(get (first classB) 0)
Since you want the first item of the inner collection you could use first there too:
(first (first classB))
or just ffirst:
(ffirst classB)
A: You can consider get-in if your input supports index access. E.g.
(def classB [["John" "16"] ["Simon" "17"] ["Peter" "16"]])
(get-in classB [0 0]) => "John"
(get-in classB [1 1]) => "17"
| |
doc_23527948
|
public class test
{
public void start()
{
if (true)
called();
}
internal protected virtual void called()
{
}
}
I want to bring the if (true) under test. My initial idea was to use Moq to Verify that called() was invoked. I ended up with this test:
[TestFixture]
public partial class TestMethodInvocation
{
[Test]
public void TestWithMoqVerify()
{
var mock = new Mock<test>() {CallBase = true};
mock.Object.start();
mock.Verify(t => t.called());
}
}
I had some troubles getting this to work and posted this question where I was adviced not to use Moq to mock the class under test.
So I added a subclass and used a property to test whether the method was called:
public class test2 : test
{
public bool WasCalled { get; set; }
internal protected override void called()
{
WasCalled = true;
}
}
public partial class TestMethodInvocation
{
[Test]
public void TestWithSubclassProperty()
{
var test = new test2();
test.start();
Assert.IsTrue(test.WasCalled);
}
}
Both approaches work but the Moq implementation is effectively half the amount of testing code as I don't need to create a subclass. Is it very bad to use Moq like this, or should I use another framework to do this kind of testing? Or is this the result of a problem in the design of my code?
A: There is a bit of a debate whether you should write tests for call verification, I'm trying to steer clear from them, I'd rather test the external behavior. You'd test something and see if the desired result was achieved, without tapping into the internals. This is of course not always possible.
Now, having said that, I'm going to try to give you an example (the best way I can). Say that we have a class called Greeter - which is supposed to send an annoying SMS to all stackoverflow subscribers. Now, say that for sending the SMS you've written some other infrastructure code somewhere elsewhere (already tested and all). Say that this code will be an implementation of an interface called IMessageService (sorry if my example sucks):
public interface IMessageService
{
void SendSMS(string message);
}
Additionally, say that you have a SubscriberRepository that would get you all the StackOverflow subscribers. Something like:
public interface ISubscriberRepository
{
IEnumerable<Subscriber> GetStackOverflowSubscribers();
}
Here is your Greeter class:
public class Greeter
{
private readonly IMessageService _messageService;
private readonly ISubscriberRepository _subscriberRepository;
public Greeter(IMessageService messageService, ISubscriberRepository subscriberRepository)
{
_messageService = messageService;
_subscriberRepository = subscriberRepository;
}
public void SendGreetingToStackOverflow()
{
IEnumerable<Subscriber> stackOverflowers = _subscriberRepository.GetStackOverflowSubscribers();
foreach (Subscriber overflower in stackOverflowers)
{
_messageService.SendSMS("Hello World!");
}
}
}
You see it's actually using the IMessageService to send the sms. At this point you want to (possibly) test if SendSMS() was called x amount of times. In this case the amount of times should be the same as the amount of StackOverflow subscribers. So your test would look like this:
[Test]
public void SendGreetingToStackOverflow_CallsIMessageServiceSendSMSTwoTimes()
{
var mockMessageService = new Mock<IMessageService>();
var mockSubscriberRepo = new Mock<ISubscriberRepository>();
// we will mock the repo and pretend that it returns 2 subscibers
mockSubscriberRepo
.Setup(x => x.GetStackOverflowSubscribers())
.Returns(new List<Subscriber>() {new Subscriber(), new Subscriber()});
// this is the one we're testing, all dependencies are fake
var greeter = new Greeter(mockMessageService.Object, mockSubscriberRepo.Object);
greeter.SendGreetingToStackOverflow();
// was it called 2 times (for each subscriber) ?
mockMessageService.Verify(
x => x.SendSMS("Hello World!"),
Times.Exactly(2));
}
Again, sorry this is possibly not the BEST example, but it's been a long day and it's the best I can come up with :).
I hope it helps.
A: A minimal example that makes some sense, as close to what are you trying to do as possible would be:
interface Callable
{
void Called();
}
class Test
{
public Test(Callable x)
{
this.callable = callable;
}
public void Start()
{
if (true)
callable.Called();
}
private Callable callable;
}
Then the test would look like this:
[TestFixture]
public partial class TestMethodInvocation
{
[Test]
public void TestWithMoqVerify()
{
var callableMock = new Mock<Callable>();
var test = new Test(callableMock);
test.Start();
callableMock.Verify(t => t.Called());
}
}
Rephrasing my comment:
you shouldn't test internals of the class - test the external behaviour.
A: I believe the real question you are asking is how do you test that the method called is executed within your test class?
To answer that you have to then ask yourself, "How will a test object be different after the method called is executed?" Then, you write a unit test that verifies in an indirect manner that the object test has changed in the way expected.
Along with what everybody else has said, Moq is used in a way to isolate out code that is unimportant for a particular test. In your case, you DO not want to create a mock -- you need to test the actual code!
My answer is that if by calling called has no way for you to see how the test object has changed, then maybe you need to think the logic of what called is doing. Or, you need to apply further operations to test that will expose a different state that is testable.
For example, maybe the expected behavior is:
*
*If foo() is called after called() has been called, Enabled is
true, BUT
*If foo() is called without called() ever being called, Enabled is false.
So, in your test you'll have to perform several operations (like calling foo()) on your class under test before you get it to a externally testable state:
var test = new test();
test.foo();
Assert(test.Enabled, Is.False);
var test = new test();
test.start();
test.foo();
Assert(test.Enabled, Is.True);
| |
doc_23527949
|
vtk_file_name = "data.vtk"
vtk_reader = vtk.vtkPolyDataReader()
vtk_reader.SetFileName(vtk_file_name)
vtk_reader.Update()
polyData = vtk_reader.GetOutput()
decimate = vtk.vtkDecimatePro()
decimate.SetInputData(polyData)
decimate.SetTargetReduction(0.1) #10% reduction
decimate.Update()
While doing this, I get the error message "vtkDecimatePro (0x1007645b0): No data to decimate!". While trying to print the polyData object, it seems to be empty. How can I get the corresponding data?
I am using VTK 6.3 with the Python wrapper installed from Anaconda
| |
doc_23527950
|
Thanks
A: Aside from Jurafsky and Martin's book, Christopher D. Manning and Hinrich Schütze's Foundations of Statistical Natural Language Processing is also widely used. For IR, Manning et al. also wrote Introduction to Information Retrieval which can be read or downloaded online at their site.
A: If you want practical knowledge on how can you work on Natural language you should start implementing it.
I suggest to use NLTK(Natural Language Proecessing Toolkit) with Python. Its easy to implement NLP in python.
You can refer to this link
http://nltk.org/
Or you can try it online on
http://cst.dk/online/pos_tagger/uk/
A: You could read Jurafsky and Martin's Speech and Language Processing (2008 edition), which is the standard textbook in the field. It's long, and has a variety of topics, so I'd suggest reading just the chapters that really apply to your interests.
Further, the best way to learn is almost certainly to actually implement NLP algorithms from scratch. You could pick some standard tasks (language modeling, text classification, POS-tagging, NER, parsing) and implement various algorithms from the ground up (ngram models, HMMs, Naive Bayes, MaxEnt, CKY) to really understand what makes them work. It also shouldn't be too hard to find some free dataset to test your implementations on.
Finally, there are lots of tutorials out there for specific NLP algorithms that are excellent. For example, if you want to build an HMM, I suggest Jason Eisner's tutorial which also covers smoothing and unsupervised training with EM. If you want to implement Gibbs sampling for unsupervised Naive Bayes training, I suggest Philip Resnik's tutorial.
A: Instead of reading a specific book, diving into the sea of papers might be an as good idea. http://www.aclweb.org, for example, contains many topics on NLP. Through those papers, you get references to more papers, some of which are the foundations of a certain branch of NLP. And because they were written by different authors, you are unlikely to be influenced too much by one point of view.
A: If you are a Java developer there is an extensive list of tutorials for how to build components of NLP systems using LingPipe at http://alias-i.com/lingpipe/demos/tutorial/read-me.html. Full disclosure I wrote some of those tutorials and one of the books below.
There are a few books that are more industrially oriented:
1) Natural Language Processing with Java by Richard M Reese
This covers how to do some common tasks with a range of open source toolkits (including LingPipe).
2) Natural Language Processing with Java and LingPipe Cookbook Paperback
by Breck Baldwin, Krishna Dayanidhi
This book is task driven at the level of "get the component built" and covers the major technologies driving most NLP systems that are text driven. It does not cover translation. It goes into more detail than the first book and has broader coverage than the LingPipe tutorials but is sometimes less detailed than the tutorials.
Breck
A: There is a hub for teaching and learning materials called TeLeMaCo. You can find resources for many aspects of NLP, and you can easily add more materials that you have found on the web.
| |
doc_23527951
|
im working on an ipad app using cocos2d objective c and box2d. my question is in relation to box2d and collisions with curves. basically i have circles within a larger circle arena. the smaller circles collide with each other fine but i want to know how to make them collide with the edges of the larger arena circle correctly so that they dont leave the arena and bounce back in. any ideas on how to approach this problem would be great
cheers
A: ok i got it working but im not sure if its the correct way to do it
int sides = 50;
float x_coordPREV=([Arena contentSize].width/2)*cos(0.0);
float y_coordPREV=([Arena contentSize].width/2)*sin(0.0);
x_coordPREV += Arena.position.x;
y_coordPREV += Arena.position.y;
b2BodyDef arenaBodyDef;
arenaBodyDef.position.Set(0,0);
b2Body *arenaBody = _world->CreateBody(&arenaBodyDef);
b2PolygonShape arenaBox;
b2FixtureDef arenaShapeDef;
arenaShapeDef.shape = &arenaBox;
for(float angle=0.0f;angle<(2*M_PI);angle+=(2*M_PI)/sides){
float x_coord=([Arena contentSize].width/2-10)*cos(angle);
float y_coord=([Arena contentSize].width/2-10)*sin(angle);
x_coord += Arena.position.x;
y_coord += Arena.position.y;
arenaBox.SetAsEdge(b2Vec2(x_coordPREV/PTM_RATIO,y_coordPREV/PTM_RATIO),b2Vec2( x_coord/PTM_RATIO,y_coord/PTM_RATIO ));
arenaBody->CreateFixture(&arenaShapeDef);
x_coordPREV = x_coord;
y_coordPREV = y_coord;
}
this creates a circle out of 50 sides and appears to be doing what i want. if anyone has a better way please let me know
ty
A: not sur eif this i what you are looking for but i saw this on a forum:
b2BodyDef edgedef;
edgedef.position.Set(0.f,10.f);
b2Body* edge = world->CreateBody(&edgedef);
b2Vec2 vertices[2];
vertices[0].Set(0.0f, 0.0f);
vertices[1].Set(10.0f, 0.0f);
int32 count = 2;
b2PolygonShape polygon;
polygon.Set(vertices, count);
b2FixtureDef edgefixtureDef;
edgefixtureDef.shape = &polygon;
edge->CreateFixture(&edgefixtureDef);
you could see how you could add more points by sending a larger array
| |
doc_23527952
|
key value
1 a
10 b
2 c
3 d
for(Map.Entry<String,String> entry : treeMapMem.entrySet()) {
String value = entry.getValue();
myMenulistSeqMem.add(value);
}
My problem like this the sorting sequence is fine from 1,2,3 but 10 appear after 1.
A: That's because the default String Comparator uses lexicographical order -- i.e. character by character, as in a dictionary. Since "1" comes before "2", any String starting with "1" will precede any other starting with "2".
You could create your own custom comparator to implement Natural Sorting and supply it to the TreeMap's constructor, but in this case it would be far simpler to just define the map as TreeMap<Integer, String>.
| |
doc_23527953
|
And this is what my data looks like, very basic:
I assigned the symbols to the fields where I want the green or red symbols with this:
status_agged$status[status_agged$current_avg > status_agged$abc_avg] <- 2
status_agged$status[status_agged$current_avg < status_agged$abc_avg] <- 6
I'm lost now where to begin my plotting function to plot all on 1 line. I should be able to get the small things resolved myself, like gridlines and colors.
(And I know this isn't the best use-case for R, but my other tool doesn't have this functionality)
Output of dput(status_agged):
structure(list(category = structure(1:5, .Label = c("Activities Transition",
"Arrival Logistics and Greetings", "Organization of Activity",
"Schedule and Offering", "Space Adequacy"), class = "factor"),
CurrentAvg = c(4, 2.75, 3.86666655540466, 3.79999995231628,
3), ABCAvg= c(3.819841, 3.469858, 3.725926, 3.358, 3.577333
), PLGAvg = c(3.69721, 3.439394, 3.638, 3.306087, 3.454638
), status = c(2, 6, 2, 2, 6)), row.names = c(NA, -5L), class = "data.frame")
A: We may do
status_agged$status <- as.factor(status_agged$status)
ggplot(status_agged, aes(x = "", y = category)) +
geom_point(aes(fill = status, color = status, shape = status), size = 10, show.legend = FALSE) +
scale_shape_manual(values = c("6" = 25, "2" = 24)) + theme_bw() +
scale_fill_manual(values = c("6" = "red", "2" = "green")) +
scale_color_manual(values = c("6" = "red", "2" = "green")) + xlab(NULL)
In addition to what is said in the comments, I set shapes 24 and 25 according to your picture (they have both fill and color aesthetics).
| |
doc_23527954
|
A: I would recommend SQLite. It's a full SQL database engine wrapped in a single dll with no installation or maintenance that just ships with your app and runs in-process. There's a great .NET wrapper that integrates nicely and allows you to create custom functions in .NET.
http://sqlite.phxsoftware.com/
A: If you don't need the power of a relational database and want to simplify translation of your object model for persistence, you should look into DB4O - it's an object database that can run on your client and transparently persist your classes.
A: You can use NHibernate with sqlite or sqlce database. We use sqlce.
A: .Net has strongly typed datasets, which work great for this purpose.
http://msdn.microsoft.com/en-us/library/esbykkzb%28VS.71%29.aspx
A: Even thought you don't want to install another product, you might want to consider SQL Server Compact Edition. Although you do need to install it, it's free, and installs no new Windows services.
The databases themselves are simply a single file per database. LINQ to SQL and LINQ to Entities are still supported, and you can even get a Windows Mobile version.
A: Are you looking for a database-like persistence layer because you want the query power of a database on the client side, or for persistence between application runs, or both?
If you need both, or just the persistence, then any one of the other answers showcasing integrated DB libraries will do (like this one for SQL Lite).
However, if the only thing you need is the ability to perform complex queries against in-memory data then I would highly recommend using plain-ol LINQ-to-Objects, assuming the option is available to you.
| |
doc_23527955
|
oldCars
carId | color | etc // Column Name
1 | red | *
2 | blue | *
3 | teal | *
4 | red | *
carColors
colorId | color | etc // Column Names
1 | blue | *
2 | teal | *
3 | red | *
newCars
carId | colorId | etc // Column Names
I am trying to normalize a database. What I would like to do is insert into newCars each row from oldCars but instead of using just the color name, I want to use the primary key colorId from the carColors table.
The result would look like this...
newCars
carId | colorId | etc // Column Names
1 | 3 | *
2 | 1 | *
3 | 2 | *
4 | 3 | *
This sort of statement seems trivial, but I can't figure it out.
A: It's just a simple JOIN using the color name as the joining condition.
INSERT INTO newCars
SELECT o.carID, c.colorID, o.etc
FROM oldCars AS o
JOIN carColors AS c ON c.color = o.color
| |
doc_23527956
|
I made a few of them on the computer I got the same error. could not figure out this question. sql developer normally opens but then the image begins to fade. not clicked on anything. system is unwieldy. buttons as the picture opens.
The two buttons at the same time seems to be open
A:
thanks you very much...
SQL Developer 4.0.2 install on Windows 7 64 bit screen solution
| |
doc_23527957
|
The application is a JSF 2.0 using maven and Spring 3.0.5.
The code that tries save the file is this:
public class ControladorPopupConfiguracaoImportadorNFe extends ControladorPopup{
private static final long serialVersionUID = 1L;
private ModeloPopupConfiguracaoImportadorNFe modeloPopup;
private ControladorPopupAlerta popupAlerta;
@Override
public void submit() {
Properties propriedades=new Properties();
definirPropriedades(propriedades);
if(salvar(propriedades)){
this.fechar();
popupAlerta.abrir("As novas configurações foram salvas e já estão em uso!");
}else
popupAlerta.abrir("Não foi possível salvar as novas configurações.");
}
private void definirPropriedades(Properties propriedades) {
propriedades.setProperty("recuperadorNFe.usaSsl",modeloPopup.getUsaSsl().toString());
propriedades.setProperty("recuperadorNFe.porta",modeloPopup.getPorta());
propriedades.setProperty("recuperadorNFe.urlImap",modeloPopup.getUrl());
propriedades.setProperty("recuperadorNFe.usuario",modeloPopup.getUsuario());
propriedades.setProperty("recuperadorNFe.senha",modeloPopup.getSenha());
propriedades.setProperty("recuperadorNFe.nomeDaCaixa",modeloPopup.getCaixaEntrada());
propriedades.setProperty("recuperadorNFe.diretorioDeArmazenamento",modeloPopup.getDiretorioDeArmazenamento());
propriedades.setProperty("recuperadorNFe.caixaDestino",modeloPopup.getCaixaDestino());
propriedades.setProperty("recuperadorNFe.horarioRecuperacao",modeloPopup.getHorarioRecuperacao());
}
private synchronized boolean salvar(Properties propriedades) {
try {
FileOutputStream outputStream=new FileOutputStream(modeloPopup.getArquivo());
propriedades.store(outputStream, "SEM COMETÁRIOS");
System.out.println("!!!!!!!!!!!!! - - - "+outputStream.getFD().toString()+" - - - !!!!!!!!!!!!!!");
outputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public void setModelo(ModeloComponenteBasico modelo) {
modeloPopup=(ModeloPopupConfiguracaoImportadorNFe) modelo;
super.setModelo(modelo);
}
public ControladorPopupAlerta getPopupAlerta() {
return popupAlerta;
}
public void setPopupAlerta(ControladorPopupAlerta popupAlerta) {
this.popupAlerta = popupAlerta;
}}
The Spring file that create the object of the class ControladorPopupConfiguracaoImportadorNFe is this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
scope="singleton">
<property name="locations" value="classpath:../propriedades/recuperadorNFe.properties" />
</bean>
<bean id="controladorPopupConfiguracaoImportadorNFe" class="com.hrgi.ui.controladores.popups.ControladorPopupConfiguracaoImportadorNFe"
scope="request">
<property name="modelo" ref="modeloPopupConfiguracaoImportadorNFe"/>
<property name="popupAlerta" ref="controladorPopupAlerta"/>
</bean>
<bean id="modeloPopupConfiguracaoImportadorNFe" class="com.hrgi.ui.modelo.ModeloPopupConfiguracaoImportadorNFe"
scope="session">
<property name="visivel" value="false"/>
<property name="caixaDestino" value="${recuperadorNFe.caixaDestino}"/>
<property name="caixaEntrada" value="${recuperadorNFe.nomeDaCaixa}"/>
<property name="diretorioDeArmazenamento" value="${recuperadorNFe.diretorioDeArmazenamento}"/>
<property name="horarioRecuperacao" value="${recuperadorNFe.horarioRecuperacao}"/>
<property name="porta" value="${recuperadorNFe.porta}"/>
<property name="senha" value="${recuperadorNFe.senha}"/>
<property name="url" value="${recuperadorNFe.urlImap}"/>
<property name="usaSsl" value="${recuperadorNFe.usaSsl}"/>
<property name="usuario" value="${recuperadorNFe.usuario}"/>
<property name="arquivo" value="#{propriedadesImportador.file}"/>
</bean>
<bean id="propriedadesImportador" class="org.springframework.core.io.ClassPathResource"
scope="request">
<constructor-arg name="path" value="../propriedades/recuperadorNFe.properties"/>
</bean>
and this is what happens in tomcat:
...
15/08/2011 15:57:47 com.hrgi.persistencia.cadastro.conversores.ConversorPessoa carregarBeansDeContato
AVISO: Lista de contatos está nula!!
15/08/2011 15:57:58 org.apache.tomcat.util.http.Parameters processParameters
INFO: Parameters: Invalid chunk '=' ignored.
!!!!!!!!!!!!! - - - java.io.FileDescriptor@671ca33b - - - !!!!!!!!!!!!!!
15/08/2011 15:58:02 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/cadastro] has started
15/08/2011 15:58:02 org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
15/08/2011 15:58:02 org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing Root WebApplicationContext: startup date [Mon Aug 15 15:57:10 BRT 2011]; root of context hierarchy
15/08/2011 15:58:02 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3445378f: defining beans [controladorPopupNovoCadastroPessoa,modeloPopupNovoCadastroPessoa,carregadorTipoPessoa,tipoPessoa,controladorPopupCadastroPessoa,modeloPopupCadastroPessoa,carregadorTipoCadastro,tipoCadastro,carregadorTipoBuscaPessoa,tipoBuscaPessoa,controladorPopupBuscaPessoa,modeloPopupBuscaPessoa,controladorSugestaoPessoa,carregadorPessoaEdicao,carregadorCidadesEnderecoEntrega,carregadorCidadesEnderecoFaturamento,carregadorItensSelectEmpresa,controladorRemocaoContato,controladorSelecaoTabelaContatos,linhaSelecionadaTabelaContato,contatoSelecionado,controladorRemocaoEmail,controladorSelecaoTabelaEmail,linhaSelecionadaTabelaEmail,controladorRemocaoTelefone,controladorSelecaoTabelaTelefone,linhaSelecionadaTabelaTelefone,controladorPopupNovoContato,modeloPopupNovoContato,controladorPopupNovoTelefone,modeloPopupNovoTelefone,controladorPopupNovoEmail,modeloPopupNovoEmail,entityManagerFactory,tipoLogradouroDao,ufDao,cidadeDao,empresaDao,cadastroDao,ramoAtividadeDao,contatoDao,emailDao,telefoneDao,funcionarioDao,funcaoDao,nomeApelidoFuncionarioDao,cepDao,bancoDao,febrabanDao,agenciaDao,tipoBancoDao,contaDao,visaoBuscaPessoaDao,visaoListagemEmpresaDao,visaoListagemAgenciaDao,validadorCPF,validadorCNPJ,validadorIE,validadorEmail,validadorSenhaNovo,validadorSenhaMudanca,validadorSenhaAtual,itensSelectUf,itensSelectTipoLogradouro,controladorPopupAlerta,modeloPopupAlerta,controladorPopupConfirmacao,modeloPopupConfirmacao,funcionarioLogado,empresaFuncionarioLogado,enderecoEmpresaFuncionarioLogado,coletorUsuarioLogado,funcionario,pessoaFisica,pessoaJuridica,enderecoEntrega,enderecoFaturamento,carregadorEnderecoFaturamento,carregadorEnderecoEntrega,controladorArmazenamentoFuncionario,controladorArmazenamentoPessoa,controladorArmazenamentoEmpresa,conversorFuncionario,conversorEmpresa,conversorPessoaFisica,conversorPessoaJuridica,conversorEnderecoEntrega,conversorEnderecoFaturamento,conversorContato,novaEmpresa,controladorPopupNovaEmpresa,modeloPopupNovaEmpresa,controladorPopupCadastroEmpresa,modeloPopupCadastroEmpresa,controladorPopupBuscaEmpresa,modeloPopupBuscaEmpresa,controladorSugestaoEmpresa,carregadorEmpresaEdicao,carregadorTipoBuscaEmpresa,tipoBuscaEmpresa,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.core.session.SessionRegistryImpl#0,org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.config.http.UserDetailsServiceInjectionBeanPostProcessor#0,org.springframework.security.filterChainProxy,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager,daoAuthenticationProvider,detalhadorDeUsuarios,passwordEncoder,controladorPopupCadastroFuncionario,modeloPopupCadastroFuncionario,controladorPopupNovoCadastroFuncionario,modeloPopupNovoCadastroFuncionario,carregadorFuncoesFuncionario,controladorPopupMudancaSenha,modeloPopupMudancaSenha,controladorPopupBuscaFuncionario,carregadorFuncionarioEdicao,modeloPopupBuscaFuncionario,controladorSugestaoFuncionario,carregadorTipoBuscaFuncionario,tipoBuscaFuncionario,controladorPopupCadastroAgencia,modeloPopupCadastroAgencia,agencia,conversorAgencia,controladorArmazenamentAgencia,carregadorBancos,controladorPopupNovoCadastroBanco,modeloPopupNovoCadastroBanco,controladorPopupCadastroBanco,modeloPopupCadastroBanco,bancoOficial,itensSelectBancoFebraban,controladorArmazenamentoBanco,conversorBanco,controladorPopupCadastroConta,modeloPopupCadastroConta,conta,armazenadorConta,carregadorEmpresasComCNPJ,carregadorAgencias,controladorPopupConfiguracaoImportadorNFe,modeloPopupConfiguracaoImportadorNFe,propriedadesImportador,importadorNFe,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,organizador,recuperador,imap,conectorImap,movedorEmail,marshaller,conversorEndereco,conversorIdentificacao,conversorEmitente,conversorDestinatario,conversorProduto,formatadorDecimal,formatadorData,conversorICMS,conversorICMS00,conversorICMS10,conversorICMS20,conversorICMS30,conversorICMS40,conversorICMS51,conversorICMS60,conversorICMS70,conversorICMS90,conversorICMSPartilhado,conversorICMSST,conversorIPI,conversorPIS,conversorCOFINS,conversorImposto,conversorTotalizador,conversorItem,conversorTransportadora,conversor INFOrmacoesAdicionais,conversorTransporte,conversorFatura,conversorDuplicata,conversorCobranca,conversorNotaFiscal,formatadorString,geradorDigitoVerificador]; root of factory hierarchy
...
A: That will happen when <Context reloadable="true"> is been set for the webapp. Most IDE's like Eclipse do that by default so that Tomcat will reload (basically: restart) whenever a webapp context resource has been changed. This is useful for development.
Apart from the concrete problem, saving files into webapp context while the webapp is running is really a bad idea due to the following reasons:
*
*All changes get lost whenever you redeploy the WAR file and/or restart the server.
*Not all containers will expand the deployed WAR into a writable folder structure.
You should rather put those files in a fixed file system path outside the webapp and add that path to the webapp's runtime classpath. For example, /var/webapp/conf. You could configure that path externally as a system property and you could add that path to the classpath by specifying it in shared.loader property of Tomcat's /conf/catalina.properties. All other servletcontainers support similar constructs. Just document it properly along the install manual of your webapp.
| |
doc_23527958
|
#recordName{field1=1, field='$1', _='_'}
This matches all the recordName records from a table which has field1 == 1 and also does an implicit binding of field to be used later in MatchBody.
Is there anything similar with maps?
I tried (apart from Google) the following syntax(es):
% ERROR: * 1: only association operators '=>' are allowed in map construction
#{key:=1, key:='$1', _:='_'}
and
% ERROR: * 1: illegal use of variable '_' in map
#{key=>1, key=>$1', _=>'_'}
Is it possible to do it and the syntax is documented somewhere I could not find? Or, is it a wrong way of thinking about maps replacing records?
TIA
EDIT:
Perhaps it isn't supported yet. Just saw this post.
A: 1> M = #{k1 => 1, k2 => 2, k3 => 3}.
#{k1 => 1,k2 => 2,k3 => 3}
2> #{k1:=1,k2:=V} = M.
#{k1 => 1,k2 => 2,k3 => 3}
3> V.
2
4> %% but you cannot do
4> ets:fun2ms(fun(#{key1:=V, key2:=R}) when V == 1 -> R end).
Error: ets:fun2ms requires fun with single variable or tuple parameter
{error,transform_error}
5>
5> %% while it is possible to do
5> ets:fun2ms(fun({V,R}) when V == 1 -> R end).
[{{'$1','$2'},[{'==','$1',1}],['$2']}]
6> %% or
6> rd(foo,{k1,k2}).
foo
7> ets:fun2ms(fun(#foo{k1=V,k2=R}) when V == 1 -> R end).
[{#foo{k1 = '$1',k2 = '$2'},[{'==','$1',1}],['$2']}]
8> %% or even
8> ets:fun2ms(fun(#foo{k1=1,k2=R}) -> R end).
[{#foo{k1 = 1,k2 = '$1'},[],['$1']}]
9>
| |
doc_23527959
|
In a previous project (not using RIA services) that used a standard WCF Class Library I had to create a seperate web application to host the services. When it came to deployment it was obvious that I needed to deploy both the front-end (Silverlight hosting) web app and the server (WCF hosting) web app and everything worked well.
With the WCF RIA Services Class library solution there is only one web app in the solution. I am presuming that since the solution works in VS, the service is somehow being hosted in the same web app that was created for the Silverlight front-end but this is not visibly clear. Anyhow, I deployed the application using Web Deploy (as I have done other apps before) but it does not work. I didn't really expect it to!
Can anyone point me in the right direction?
A: When you link the .web RIA class library projects to your main web project, the services are accessed behind the scenes by URLs like:
http://localhost:2911/ClientBin/RiaServices-Documents-Web-DocumentDomainService.svc/binary/GetDocuments?$take=20&$includeTotalCount=True
The client RIA class library projects just assume a relative URL (relative to the hosting project), so they will work in any Silverlight application.
The only requirement is that you link the RIA service ".Web" project to the website hosting your Silverlight app. That will place the required service relative to the clientbin folder, ready to be consumed.
A: I had not installed RIA on the IIS Server because I received a message that led me to believe that you couldn't do it. However there is a command prompt command to do a special Server install see here msdn.microsoft.com/en-us/library/ff426913(v=VS.91).aspx. It now works by simply deploying the Web project.
| |
doc_23527960
|
XML Format we required as output.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<OTA_HotelAvailRQ xmlns="http://www.opentravel.org/OTA/2003/05">
<POS>
<Source>
<RequestorID MessagePassword= "****" ID= "****" Type="CHM"/>
</Source>
</POS>
<AvailRequestSegments>
<AvailRequestSegment>
<HotelSearchCriteria>
<Criterion>
<HotelRef HotelCode="00008382"/>
<StayDateRange Start="2014-12-10" End="2014-12-29">
</StayDateRange>
</Criterion>
</HotelSearchCriteria>
</AvailRequestSegment>
</AvailRequestSegments>
</OTA_HotelAvailRQ>
Already tried structures of array
*
*$request = array (
array('RequestorID'=>array('MessagePassword'=>'testDataCorp','ID'=>'datacorp','Type'=>'CHM')),
array('HotelRef'=>array('HotelCode'=>'00008164')),
array('StayDateRange'=>array('Start'=>'2016-04-01','End'=>'2016-04-12')));
2.$request = array('Source' => array( 'RequestorID'=>array( 'MessagePassword'=> 'testDataCorp', 'ID'=>'datacorp','Type'=>'CHM') ),array('HotelRef'=>array('HotelCode'=>'00008164')),
array('StayDateRange'=>array('StayDateRange (Start)'=>'2016-04-01','StayDateRange (End)'=>'2016-04-12'))
);
*array(
array('MessagePassword', 'testDataCorp'),
array('ID', 'datacorp'),
array('Type', 'CHM'),
array('HotelCode', '00008164'),
array('StayDateRange(Start)', '2016-04-01'),
array('StayDateRange(End)', '2016-04-12')
);
kindly help me so that i can get the exact ouput.
Thanks & Regards
Sandeep Goel
| |
doc_23527961
|
I have a library that get the spec of my module to create a new module from it. But this new module doesn't have my new function when I want him to have it too.
Here is a simplified example of my situation.
The module test:
def fun1():
pass
And the main code:
import importlib.util
import inspect
import sys
def fun2():
print("It's Work!")
module = importlib.import_module('test')
print(dir(module))
module.fun2 = fun2
module2 = importlib.import_module('test')
print(dir(module2)) # fun2 is present even if I reimport the module
# ---- Managed by the library so I can't modify the following code ----
spec = module.__spec__
lib = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lib)
# ---------------------------------------------------------------------
print(dir(lib)) # fun2 is absent
The line spec.loader.exec_module(lib) loads all functions from the spec of my first module and my function fun1 is present in the lib after that unline fun2.
How can I persist the dynamic function fun2?
Thanks!
| |
doc_23527962
|
At the moment i'm using the TextPattern to get the text from one of these AutomationElements:
TextPattern tp = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);
string text = tp.DocumentRange.GetText(-1).Trim();
But now I want to set a new text in the AutomationElement. I can't find a method for this in the TextPattern class. So I'm trying to use the ValuePattern but I'm not sure if that's the right way to do it:
ValuePattern value = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
value.SetValue(insertText);
Is there an other way to set the text value?
An other question is how can I get an event when the text was changed on a Edit / Document element? I tried to use the TextChangedEvent but i don't get any events fired when changing the text:
AutomationEventHandler ehTextChanged = new AutomationEventHandler(text_event);
Automation.AddAutomationEventHandler(TextPattern.TextChangedEvent, element, TreeScope.Element, ehTextChanged);
private void text_event(object sender, AutomationEventArgs e)
{
Console.WriteLine("Text changed");
}
A: You can use the ValuePatern, it's the way to do it. From my own code :
ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
etb.SetValue("test");
You can register to Event using:
var myEventHandler=
new AutomationEventHandler(handler);
Automation.AddAutomationEventHandler(
SelectionItemPattern.ElementSelectedEvent, // In your case you might want to use another pattern
targetApp,
TreeScope.Descendants,
myEventHandler);
And the handler method:
private void handler(object src, AutomationEventArgs e) {...}
There is also an AutomationPropertyChangedEventHandler (use Automation.AddAutomationPropertyChangedEventHandler(...) in this case) that can be useful.
Based on this sample from MSDN.
| |
doc_23527963
|
<a href="#" onclick="loadContent(...); return false;" class="btn btn-primary">Open</a>
After clicking on a link like this
<a href="somefile.pdf" target="_blank">File</a>
the font-color of the button turns black. Reloading does not help, i have to delete all history data, cache etc.
This problem occurs in Firefox and Chrome, but not in Safari.
Does anybody have an idea what could cause this problem?
I hope it's possible to fix this without overriding the styles of the button.
EDIT
to clarify: the second link is not the same as the first one. So the style of the first button (a styled a-tag) changes after clicking on an other a-tag. In the developer tool it says that the font of the first button should be black, but it is white and therefore invisible, as the button is white, too.
A: It's not possible without overriding the styles of the button. What you're seeing is a:visited at work. You need to override this CSS rule to be the same as the unvisited a in order for the link to look the same both before and after.
| |
doc_23527964
|
In my code I added <CreatePatient> (it's a modal window and it's hidden) only into PatientsToolbar, but in vue-devtools I see this tag also at the bottom.
What such behavior?
Thanks!
| |
doc_23527965
|
psql template1;
drop database target_database;
create database target_database;
\c target_database;
Now, if I do:
\d
target_database has all of the contents of a different database on my system. 43 tables, all populated with data. For example, select count(*) from users returns 1240. The structure and data is exactly the same as another database on my system.
I am not sure where to start looking. Any help is appreciated.
A: The manual:
By default, the new database will be created by cloning the standard system database template1.
Are there, by any chance, the same objects in the default template database?
| |
doc_23527966
|
I've already none a similar function using jquery like this:
$('.articles').append($('#articles-non-attached li'));
var alphabeticallyOrderedDivs = $('.articles li').sort(function(a, b) {
return String.prototype.localeCompare.call($(a).data('title').toLowerCase(), $(b).data('title').toLowerCase());
});
But now I need to use just Javascript.
So far I've got:
var stores_li = document.querySelectorAll('.store-list-item');
//stores_li.sort();
[].slice.call(stores_li).sort(function(a, b) {
var textA = a.getAttribute('data-title').toLowerCase()
var textB = b.getAttribute('data-title').toLowerCase()
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
//return String.prototype.localeCompare.call(textA,textB);
});
<ul>
<li class="store-list-item" data-title="a">Test 1</li>
<li class="store-list-item" data-title="c">Test 3</li>
<li class="store-list-item" data-title="b">Test 2</li>
<li class="store-list-item" data-title="d">Test 4</li>
</ul>
A: You need to append the newly sorted items.
var stores_li = document.querySelectorAll('.store-list-item');
[].slice.call(stores_li).sort(function(a, b) {
var textA = a.getAttribute('data-title').toLowerCase()
var textB = b.getAttribute('data-title').toLowerCase()
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})
.forEach(function(el) {el.parentNode.appendChild(el)});
<ul>
<li class="store-list-item" data-title="a">Test 1</li>
<li class="store-list-item" data-title="c">Test 3</li>
<li class="store-list-item" data-title="b">Test 2</li>
<li class="store-list-item" data-title="d">Test 4</li>
</ul>
This is because the native .sort() method isn't a DOM method; it just sorts any arbitrary list of Array items. So by appending the newly sorted item, it commits the new element order to the DOM.
Note that the simple solution above assumes they all share the same parent.
Here's a version with modern syntax and methods:
var stores_li = document.querySelectorAll('.store-list-item');
Array.from(stores_li).sort((a, b) =>
a.dataset.title.toLowerCase().localeCompare(b.dataset.title.toLowerCase())
)
.forEach(el => el.parentNode.appendChild(el));
<ul>
<li class="store-list-item" data-title="a">Test 1</li>
<li class="store-list-item" data-title="c">Test 3</li>
<li class="store-list-item" data-title="b">Test 2</li>
<li class="store-list-item" data-title="d">Test 4</li>
</ul>
A: var stores_li = document.querySelectorAll('.store-list-item');
var sorted = [].slice.call(stores_li).sort(function(a, b) {
var textA = a.dataset.title.toLowerCase();
var textB = b.dataset.title.toLowerCase();
return textA.localeCompare(textB);
});
| |
doc_23527967
|
http://framework.zend.com/svn/framework/standard/trunk/demos/Zend/Gdata/InstallationChecker.php
Exception thrown trying to access Zend/Loader.php using 'use_include_path' = true. Make sure you include Zend Framework in your include_path which currently contains: .;C:\php\pear;C:\Program Files (x86)\EasyPHP-5.3.6.1\www\workspace\CPS\class\library\Gdata
I don't get it because this:
C:\Program Files (x86)\EasyPHP-5.3.6.1\www\workspace\CPS\class\library\Gdata
Is the correct path to my gData library, and it's suppose to be standalone right?
A: I should had included the root folder so library directly and it's working fine
| |
doc_23527968
|
My user wants the grid to display results in this order:
*
*Awaiting response
*Awaiting payment
*Overdue
*Active
*Inactive
I'm trying to use the following code to achieve this, but it throws an error saying syntax error near the word default.
What is wrong with the order by statement?
Try
sql = "SELECT ContractID, CustAcc, DateStart, DateRenew, Fee, Agreement, OtherDetails, " _
& "DateSent, TimeSent, ReminderName, ReminderEmail FROM dbo.tblContracts " _
& "ORDER BY FIELD(Agreement, 'AWAITING RESPONSE', 'AWAITING PAYMENT', 'ACTIVE', 'INACTIVE')"
conAd = New OleDb.OleDbDataAdapter(sql, con)
conset = New DataSet
conAd.Fill(conset)
ugModules.DataSource = conset
Catch ex As Exception
errorLog(ex.Message, ex.StackTrace)
MsgBox("Failed to retrieve contract information, refer to error log")
End Try
EDIT
After changing my code as per the suggestion from @Solarflare, I've now got the following code;
sql = "SELECT ContractID, CustAcc, DateStart, DateRenew, Fee, Agreement, OtherDetails, " _
& "DateSent, TimeSent, ReminderName, ReminderEmail FROM dbo.tblContracts " _
& "ORDER BY CASE Agreement WHEN 'AWAITING RESPONSE' THEN 1 WHEN 'AWAITING PAYMENT' THEN 2 " _
& "WHEN 'OVERDUE' THEN 3 WHEN 'ACTIVE' THEN 4 WHEN 'INACTIVE' THEN 5 END"
However, the result it not as expected. The result is instead as below
so INACTIVE is mostly at the top, followed by a mix of AWAITING RESPONSE and INACTIVE etc - Why might this be?
A: The ORDER BY should utilize a CASE statement in SQL Server.
| |
doc_23527969
|
i = 32512 (0x7f00); wexitstatus = 127
But, on SunOS I get:
sh: unknowncommand: not found
i = 256 (0x100); wexitstatus = 1
...that extra "sh:" line is annoying :)
(My goal: quiet programmatic determination of whether or not I can do "cc" and/or "gcc" commands.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main (int argc, char **argv)
{
int i;
char buf [1000];
strcpy (buf, "unknowncommand -c foo.c > /dev/null 2>&1");
i = system (buf);
printf ("i = %d (0x%x); wexitstatus = %d\n", i, i, WEXITSTATUS (i));
return 0;
}
A: You could use popen() instead of system() and explicitly capture the output of the process.
A: The which command will find an executable that lives in your PATH variable.
which gcc
which cc
you can use this in your system call.
This is a poor man's version of which:
// performs task similar to which command
// mywhich.c
char **split(char **result, char *w, const char *src, const char *delim)
{
char *p;
w=strdup(src);
int i=0;
for(p=strtok(w, delim); p!=NULL; p=strtok(NULL, delim))
{
result[i++]=p;
result[i]=NULL;
}
return result;
}
char *detect_cc(char *cc, char **argv)
{
char search[PATH_MAX]={0x0};
char resolved[PATH_MAX]={0x0};
char *w=NULL;
int i=0,j=0;
char *result[1024]={NULL}; // set 1024 to appropriate value
char *PATH=getenv("PATH");
*cc=0x0;
split(result, w, PATH, ":");
for(i=0 ; !*cc && result[i]!=NULL; i++)
{
for(j=0; argv[j]!=NULL; j++)
{
sprintf(search,"%s/%s", result[i], argv[j]);
if(realpath(search, resolved)!=NULL)
{
if(access(resolved, X_OK)==0)
strcpy(cc, resolved);
}
}
}
free(w);
return cc;
}
int main(int argc, char **argv)
{
char cc[PATH_MAX]={0x0};
argv++;
detect_cc(cc, argv);
if(*cc)
printf("found: %s\n", cc);
else
printf("Not found in PATH\n");
return 0;
}
usage:
./mywhich gcc cc foo
It stops on the first file found. Doctor the code to suppress messages as you see fit.
A: Here is one simple way to drop the output:
strcpy (buf, "sh -c 'unknowncommand -c foo.c' > /dev/null 2>&1");
i = system (buf);
| |
doc_23527970
|
However, with Android Studio and Gralde, every time when I try to run/debug an app, gradle build would always run, adding an additional 15~45 seconds of delay to the time when the app is launched (and sometimes up to 70 seconds on a 4 year-old HP i7 laptop).
Therefore, the question is: is there any way skip Android Studio's gradle build phase, or at least reduce the amount of time it would take to run/debug?
Note: I've already configured gradle.properties as follows:
org.gradle.parallel=true
org.gradle.daemon=true
org.gradle.configureondemand=true
Edit: My gradle build is probably more complex than most projects, as it has 7 different flavors (will expand to ~20) and 3 build types, and also contain Groovy code to change APK name (insert current date), and automatically insert tasks to increment the version code and version name depending on current buildType. Here's the complete build.gradle (modified to hide customer names):
import java.text.SimpleDateFormat
apply plugin: 'com.android.application'
def appendVersionNameVersionCode(applicationVariants) {
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null) {
def PREFIX = "My_APP_"
if (outputFile.name.endsWith('.apk') && !outputFile.name.startsWith(PREFIX)) {
def names = variant.baseName.split("-");
def apkName = PREFIX+names[0]+"_";
if(names[1].equals(android.buildTypes.debugEx.name)) {
apkName += 'debugEx_'
} else {
apkName += new SimpleDateFormat("YYYYMMdd").format(new Date())
}
if(variant.name.toLowerCase().contains(android.buildTypes.release.name)) {
if (outputFile.name.contains('unsigned')) {
apkName += "-unsigned"
} else {
apkName += "_SIGNED"
}
}
if (!variant.outputs.zipAlign) {
apkName += "-unaligned"
}
apkName += ".apk"
println outputFile.name+" --> " + apkName
output.outputFile = new File(outputFile.parent, apkName)
}
}
}
}
}
def retrieveVersionCode(variantName) {
def manifestFile = file("src/$variantName/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
return Integer.parseInt(matcher.group(1))
}
def retrieveVersionName(variantName) {
def manifestFile = file("src/$variantName/AndroidManifest.xml")
def pattern = Pattern.compile(Pattern.quote("versionName=\"") + "(.*?)"+ Pattern.quote("\""))
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
return matcher.group(1)
}
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
lintOptions {
abortOnError false
absolutePaths false
lintConfig file("lint.xml")
}
defaultConfig {
applicationId "com.app.sportcam"
minSdkVersion 8
targetSdkVersion 21
}
if(project.hasProperty("app.signing")
&& new File(project.property("app.signing")+'.gradle').exists()) {
apply from: project.property("app.signing")+'.gradle';
} else {
println 'Warning, signing credential not found: ' + project.property("app.signing")+'.gradle'
}
buildTypes {
all {
buildConfigField 'String', 'IP', '"192.168.1.1"'
buildConfigField 'String', 'RTSP_IP', '"rtsp://"+IP+"/"'
//debugging
buildConfigField 'boolean', 'DEBUG_DETAILED', 'false'
buildConfigField 'boolean', 'DEBUG_UI_STATE', 'false'
buildConfigField 'boolean', 'INTERNAL_DEBUG', 'false'
buildConfigField 'boolean', 'ENABLE_VIEWSERVER', 'false'
buildConfigField 'boolean', 'INJECT_PTP_PROPERTIES', 'false'
//functional
buildConfigField 'boolean', 'ENABLE_TIME_LIMIT', 'false'
buildConfigField 'boolean', 'HIDE_ACTIONBAR_ON_LANDSCAPE', 'false'
buildConfigField 'boolean', 'ENABLE_VIDEO_DOWNLOAD', 'true'
buildConfigField 'boolean', 'ENABLE_VIDEO_DOWNLOAD_PROGRESS', 'true'
buildConfigField 'boolean', 'ENABLE_VIDEO_DOWNLOAD_CANCEL', 'false'
buildConfigField 'boolean', 'SET_TIME', 'true'
buildConfigField 'boolean', 'SHOULD_SET_CAMERA_MODE_WHEN_TURNING_RECORDING_OFF', 'false'
buildConfigField 'boolean', 'SHOULD_SET_CAMERA_MODE_ON_CONNECTION', 'false'
appendVersionNameVersionCode(applicationVariants)
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
//for customers' testing
debug {
buildConfigField 'boolean', 'ENABLE_TIME_LIMIT', 'true'
}
//for internal testing
debugEx {
buildConfigField 'boolean', 'DEBUG_DETAILED', 'true'
buildConfigField 'boolean', 'INTERNAL_DEBUG', 'true'
buildConfigField 'boolean', 'ENABLE_VIEWSERVER', 'true'
buildConfigField 'boolean', 'INJECT_TEST_PROPERTIES', 'true'
debuggable true
signingConfig signingConfigs.debug
applicationIdSuffix ".debug"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
def time=Calendar.getInstance()
time.add(Calendar.MONTH, 3)
println 'Debug build expiry date='+time.getTime()
productFlavors {
// default BuildConfig variables
all {
buildConfigField 'long', 'TIME_LIMIT', time.getTimeInMillis()+'l'
buildConfigField 'boolean', 'ADD_ABOUT', 'true'
buildConfigField 'boolean', 'FORCE_DEVICE_CHECK', 'false'
buildConfigField 'boolean', 'SHOW_CUR_SELECTION_PREF', 'true'
buildConfigField 'boolean', 'SHOW_CUR_SELECTION_ONSCREEN', 'false'
buildConfigField 'boolean', 'NO_WIFI_SCREEN', 'true'
buildConfigField 'boolean', 'NO_STREAMING', 'false'
buildConfigField 'boolean', 'NO_GALLERY', 'false'
buildConfigField 'boolean', 'INIT_IN_START', 'true'
buildConfigField 'boolean', 'CUSTOM_FUNCTIONS', 'true'
buildConfigField 'boolean', 'ENABLE_TIMEOUT_CONTINUE', 'false'
buildConfigField 'boolean', 'TRANSPARENT_BOTTOM_BAR', 'false'
buildConfigField 'int', 'LOGO_TIMING', '1000'
}
default {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0xFF'
buildConfigField 'boolean', 'ADD_ABOUT', 'false'
applicationId = 'com.app.default'
def variantName='DEFAULT'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_1 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0x0B'
buildConfigField 'boolean', 'FORCE_DEVICE_CHECK', 'true'
applicationId 'com.app.c1'
def variantName='c1'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_2 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0xFF' //TODO not final
buildConfigField 'boolean', 'SHOW_CUR_SELECTION_ONSCREEN', 'true'
applicationId 'com.app.c2'
def variantName='c2'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_3 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0x12'
buildConfigField 'int', 'LOGO_TIMING', '3000'
applicationId = 'com.app.c3'
def variantName='c3'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_4 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0x02'
applicationId = 'com.app.c4'
def variantName='c4'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_5 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0x04'
applicationId = 'com.app.c5'
def variantName='c5'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_6 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0xFF'
applicationId = 'com.app.c6'
def variantName='c6'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
Customer_7 {
//mandatory
buildConfigField 'int', 'CUSTOMER_NAME_PREFIX', '0x14'
buildConfigField 'boolean', 'FORCE_DEVICE_CHECK', 'true'
applicationId = 'com.app.c7'
def variantName='c7'
versionCode retrieveVersionCode(variantName)
versionName retrieveVersionName(variantName)
}
}
sourceSets{
main {
res.srcDirs = ['src/main/res']
}
default {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
}
Customer_1 {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
}
Customer_2 {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
}
Customer_3 {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
res.srcDir 'src/_Strings_/yy'
}
Customer_4 {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
}
Customer_5 {
res.srcDir 'src/_Strings_/xx'
res.srcDir 'src/_Strings_/zz'
}
Customer_6 {
res.srcDir 'src/_Strings_/xx'
res.srcDir 'src/_Strings_/aa'
}
Customer_7 {
res.srcDir 'src/_Strings_/Standard'
res.srcDir 'src/_Strings_/xx'
}
}
}
import java.util.regex.Pattern
def variantNameRegex = Pattern.quote("generate") + "(.*?)"+ Pattern.quote("BuildConfig")
Pattern patternVariantName = Pattern.compile(variantNameRegex);
tasks.whenTaskAdded { task ->
//TODO disables lint
if (task.name.startsWith("lint")) {
println 'Disables lint task: '+task.name
task.enabled = false
}
def m = patternVariantName.matcher(task.name)
if (m.find()) {
def variantName = m.group(1)
def isRelease=false
if (variantName.endsWith('Debug')) {
variantName = variantName.substring(0, variantName.lastIndexOf('Debug'))
} else if (variantName.endsWith('Release')) {
variantName = variantName.substring(0, variantName.lastIndexOf('Release'))
isRelease=true;
} else {
return
}
def taskIncVerCode="increaseVersionCode$variantName"
if(!project.hasProperty(taskIncVerCode)) {
project.task(taskIncVerCode) << {
def manifestFile = file("src/$variantName/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
manifestFile.write(manifestContent)
}
}
task.dependsOn taskIncVerCode
if(isRelease) {
def taskIncVerName="increaseVersionName$variantName"
if(!project.hasProperty(taskIncVerName)) {
project.task(taskIncVerName) << {
def manifestFile = file("src/$variantName/AndroidManifest.xml")
def patternVersionNumber = Pattern.compile("versionName=\"(\\d+)\\.(\\d+)\\.(\\d+)\"")
def manifestText = manifestFile.getText()
def matcherVersionNumber = patternVersionNumber.matcher(manifestText)
matcherVersionNumber.find()
def majorVersion = Integer.parseInt(matcherVersionNumber.group(1))
def minorVersion = Integer.parseInt(matcherVersionNumber.group(2))
def pointVersion = Integer.parseInt(matcherVersionNumber.group(3))
def mNextVersionName = majorVersion + "." + minorVersion + "." + (pointVersion + 1)
def manifestContent = matcherVersionNumber.replaceAll("versionName=\"" + mNextVersionName + "\"")
manifestFile.write(manifestContent)
}
}
task.dependsOn taskIncVerName
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:21.0.0'
compile files('libs/eventbus.jar')
compile files('libs/libGoogleAnalyticsServices.jar')
compile files('libs/trove-3.0.3.jar')
}
Here's the Gradle console output, generated by executing Run twice without any gralde/code modifications:
Executing tasks: [:ptp_app_base:assembleCustomer_6DebugEx]
Parallel execution with configuration on demand is an incubating feature.
Debug build expiry date=Mon Mar 16 10:39:02 CST 2015
Disables lint task: lintVitalCustomer_1Release
Disables lint task: lintVitalCustomer_2Release
Disables lint task: lintVitalDefaultRelease
Disables lint task: lintVitalCustomer_3Release
Disables lint task: lintVitalCustomer_4Release
Disables lint task: lintVitalCustomer_5Release
Disables lint task: lintVitalCustomer_6Release
Disables lint task: lintVitalCustomer_7Release
Disables lint task: lint
Disables lint task: lintCustomer_1DebugEx
Disables lint task: lintCustomer_1Debug
Disables lint task: lintCustomer_1Release
Disables lint task: lintCustomer_2DebugEx
Disables lint task: lintCustomer_2Debug
Disables lint task: lintCustomer_2Release
Disables lint task: lintDefaultDebugEx
Disables lint task: lintDefaultDebug
Disables lint task: lintDefaultRelease
Disables lint task: lintCustomer_3DebugEx
Disables lint task: lintCustomer_3Debug
Disables lint task: lintCustomer_3Release
Disables lint task: lintCustomer_4DebugEx
Disables lint task: lintCustomer_4Debug
Disables lint task: lintCustomer_4Release
Disables lint task: lintCustomer_5DebugEx
Disables lint task: lintCustomer_5Debug
Disables lint task: lintCustomer_5Release
Disables lint task: lintCustomer_6DebugEx
Disables lint task: lintCustomer_6Debug
Disables lint task: lintCustomer_6Release
Disables lint task: lintCustomer_7DebugEx
Disables lint task: lintCustomer_7Debug
Disables lint task: lintCustomer_7Release
ptp_app_base-Customer_1-debugEx.apk --> MY_APP_Customer_1_debugEx_.apk
ptp_app_base-Customer_1-debug.apk --> MY_APP_Customer_1_20141216.apk
ptp_app_base-Customer_1-release.apk --> MY_APP_Customer_1_20141216_SIGNED.apk
ptp_app_base-Customer_2-debugEx.apk --> MY_APP_Customer_2_debugEx_.apk
ptp_app_base-Customer_2-debug.apk --> MY_APP_Customer_2_20141216.apk
ptp_app_base-Customer_2-release.apk --> MY_APP_Customer_2_20141216_SIGNED.apk
ptp_app_base-default-debugEx.apk --> MY_APP_default_debugEx_.apk
ptp_app_base-default-debug.apk --> MY_APP_default_20141216.apk
ptp_app_base-default-release.apk --> MY_APP_default_20141216_SIGNED.apk
ptp_app_base-Customer_3-debugEx.apk --> MY_APP_Customer_3_debugEx_.apk
ptp_app_base-Customer_3-debug.apk --> MY_APP_Customer_3_20141216.apk
ptp_app_base-Customer_3-release.apk --> MY_APP_Customer_3_20141216_SIGNED.apk
ptp_app_base-Customer_4-debugEx.apk --> MY_APP_Customer_4_debugEx_.apk
ptp_app_base-Customer_4-debug.apk --> MY_APP_Customer_4_20141216.apk
ptp_app_base-Customer_4-release.apk --> MY_APP_Customer_4_20141216_SIGNED.apk
ptp_app_base-i3-debugEx.apk --> MY_APP_i3_debugEx_.apk
ptp_app_base-i3-debug.apk --> MY_APP_i3_20141216.apk
ptp_app_base-i3-release.apk --> MY_APP_i3_20141216_SIGNED.apk
ptp_app_base-i5-debugEx.apk --> MY_APP_i5_debugEx_.apk
ptp_app_base-i5-debug.apk --> MY_APP_i5_20141216.apk
ptp_app_base-i5-release.apk --> MY_APP_i5_20141216_SIGNED.apk
ptp_app_base-Customer_7-debugEx.apk --> MY_APP_Customer_7_debugEx_.apk
ptp_app_base-Customer_7-debug.apk --> MY_APP_Customer_7_20141216.apk
ptp_app_base-Customer_7-release.apk --> MY_APP_Customer_7_20141216_SIGNED.apk
:ptp_app_base:preBuild
:ptp_app_base:compileCustomer_6DebugExNdk UP-TO-DATE
:ptp_app_base:preCustomer_6DebugExBuild
:ptp_app_base:checkCustomer_6DebugExManifest
:ptp_app_base:preCustomer_4DebugBuild
:ptp_app_base:preCustomer_4DebugExBuild
:ptp_app_base:preCustomer_4ReleaseBuild
:ptp_app_base:preCustomer_5DebugBuild
:ptp_app_base:preCustomer_5DebugExBuild
:ptp_app_base:preCustomer_5ReleaseBuild
:ptp_app_base:preCustomer_6DebugBuild
:ptp_app_base:preCustomer_6ReleaseBuild
:ptp_app_base:preDefaultDebugBuild
:ptp_app_base:preDefaultDebugExBuild
:ptp_app_base:preDefaultReleaseBuild
:ptp_app_base:preCustomer_3DebugBuild
:ptp_app_base:preCustomer_3DebugExBuild
:ptp_app_base:preCustomer_3ReleaseBuild
:ptp_app_base:preCustomer_7DebugBuild
:ptp_app_base:preCustomer_7DebugExBuild
:ptp_app_base:preCustomer_7ReleaseBuild
:ptp_app_base:preCustomer_1DebugBuild
:ptp_app_base:preCustomer_1DebugExBuild
:ptp_app_base:preCustomer_1ReleaseBuild
:ptp_app_base:preCustomer_2DebugBuild
:ptp_app_base:preCustomer_2DebugExBuild
:ptp_app_base:preCustomer_2ReleaseBuild
:ptp_app_base:prepareComAndroidSupportSupportV42100Library UP-TO-DATE
:ptp_app_base:prepareCustomer_6DebugExDependencies
:ptp_app_base:compileCustomer_6DebugExAidl UP-TO-DATE
:ptp_app_base:compileCustomer_6DebugExRenderscript UP-TO-DATE
:ptp_app_base:generateCustomer_6DebugExBuildConfig
:ptp_app_base:generateCustomer_6DebugExAssets UP-TO-DATE
:ptp_app_base:mergeCustomer_6DebugExAssets UP-TO-DATE
:ptp_app_base:generateCustomer_6DebugExResValues UP-TO-DATE
:ptp_app_base:generateCustomer_6DebugExResources UP-TO-DATE
:ptp_app_base:mergeCustomer_6DebugExResources UP-TO-DATE
:ptp_app_base:processCustomer_6DebugExManifest UP-TO-DATE
:ptp_app_base:processCustomer_6DebugExResources UP-TO-DATE
:ptp_app_base:generateCustomer_6DebugExSources
:ptp_app_base:compileCustomer_6DebugExJava
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:ptp_app_base:preDexCustomer_6DebugEx UP-TO-DATE
:ptp_app_base:dexCustomer_6DebugEx
:ptp_app_base:processCustomer_6DebugExJavaRes UP-TO-DATE
:ptp_app_base:validateDebugSigning
:ptp_app_base:packageCustomer_6DebugEx
:ptp_app_base:zipalignCustomer_6DebugEx
:ptp_app_base:assembleCustomer_6DebugEx
BUILD SUCCESSFUL
Total time: 30.303 secs
The current build script is probably not the most performant, so both tips on how to skip rebuild or speeding up rebuild would be appreciated.
Edit 2: I noticed most of the gradle build time is spent on:
*
*compile[app]Java
*dex[app]
*package[app]
These steps appear to run despite the fact that nothing has changed since the last build.
Edit 3: Original title was "How to skip Gradle build when running/debugging with Android Studio", changed to better reflect the symptom of the issue and the remedy.
A: The cause is stupidity on my part:
I set a BuildConfig field to be the current time in milliseconds, which caused the resulting BuildConfig.java to be different every time Gradle runs, causing the whole compiling/dexing/packaging phases to run.
Edit:
For me the problem was caused by executing script similar to this:
productFlavors {
all {
buildConfigField 'long', 'TIME_LIMIT', System.currentTimeMillis() + 'l'
}
...
}
Since System.currentTimeMillis() would be different every time, it means every time Gradle runs it will find the source code has changed, therefore triggering a cascade of actions. It is solved by changing the script to:
def time = Calendar.getInstance()
time.set(Calendar.HOUR, 1);
time.set(Calendar.MINUTE, 1);
time.set(Calendar.SECOND, 1);
time.set(Calendar.MILLISECOND, 1);
productFlavors {
// default BuildConfig variables
all {
buildConfigField 'long', 'TIME_LIMIT', time.getTimeInMillis() + 'l'
}
...
}
The above script means the exact same time is produced when run in the same day. therefore if nothing else was changed then the previous generated APK will be reused with no recompilation necessary.
| |
doc_23527971
|
How can I implement a blue highlight effect for selected/activated toolbar buttons, like in Xcode 5? Is this being done through a new template image format?
A: OS X and iOS both support "template" images. See:
-[NSImage setTemplate:];
(NSImage Class Reference)
and:
-[UIImage imageWithRenderingMode:];
(UIImage Class Reference)
| |
doc_23527972
|
row 1: <a>aaa</a>
row 2: <a>opis</a>
i would like to extract rows where text contains "opis", others can be empty.
This is how I tried to do that:
SELECT EXTRACTVALUE(DESCRIPTION, '*//A[contains(text(),"opis")]') FROM DATAS D;
It doesn't work...
this is how my table looks like:
CREATE TABLE DATAS
(
ID NUMBER(3) NOT NULL,
DESCRIPTION XMLTYPE NOT NULL
);
I noticed, I switched off brain for a while, this is what I want to achieve:
SELECT DESCRIPTION FROM DATAS D WHERE EXTRACTVALUE(DESCRIPTION, '*//A[contains(text(),"opis")]') IS NOT NULL;
but this query doesn't work.
A: Tag names are case-sensitive, and you don't need the * root, so your first query should be:
SELECT EXTRACTVALUE(DESCRIPTION, '//a[contains(text(),"opis")]') FROM DATAS D;
SQL Fiddle.
And the second should be:
SELECT DESCRIPTION
FROM DATAS D
WHERE EXTRACTVALUE(DESCRIPTION, '//a[contains(text(),"opis")]')
IS NOT NULL;
(I'm pretty sure there are other, possibly better, ways to do this, but this isn't really my area...)
| |
doc_23527973
|
I have the following code
public function configureActions(Actions $actions): Actions
{
$send_acknowledgement_email = Action::new('sendAcknowledgementEmail', 'Send Acknowledgement Email', 'fa fa-send')
->linkToCrudAction('sendAcknowledgementEmail');
return $actions
->add(Crud::PAGE_INDEX, $send_acknowledgement_email)
->add(Crud::PAGE_EDIT, $send_acknowledgement_email)
;
}
public function sendAcknowledgementEmail() //Do I need parameters?
{
//How do I get the Entity?
//What should I return?
}
So far, EasyAdmin detects the custom function but I get an error "The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned null. Did you forget to add a return statement somewhere in your controller?"
How do I continue from here?
A: After browsing through the EasyAdmin AbstractCrudController I came up with the following working code.
*
*In order to get the current object you need the parameter AdminContext
*For my use case I want to return to the CrudController index action, so for that I can do a redirect.
Note: you need to inject the CrudUrlGenerator service in your constructor controller.
public function sendAcknowledgementEmail(AdminContext $context)
{
$participant = $context->getEntity()->getInstance();
// Your logic
$url = $this->crudUrlGenerator->build()
->setController(ParticipantCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return $this->redirect($url);
}
My current function looks like this:
public function sendAcknowledgementEmail(AdminContext $context)
{
$participant = $context->getEntity()->getInstance();
$participant->sendAcknowledgementEmail();
$this->addFlash('notice','<span style="color: green"><i class="fa fa-check"></i> Email sent</span>');
$url = $this->crudUrlGenerator->build()
->setController(ParticipantCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return $this->redirect($url);
}
My current working code
<?php
namespace App\Controller\Admin;
use App\Service\WebinarService;
use EasyCorp\Bundle\EasyAdminBundle\Router\CrudUrlGenerator;
use Symfony\Contracts\Translation\TranslatorInterface;
// ...
class ParticipantCrudController extends AbstractCrudController
{
private CrudUrlGenerator $crudUrlGenerator;
private WebinarService $webinar_service;
private TranslatorInterface $translator;
public function __construct(CrudUrlGenerator $crudUrlGenerator, WebinarService $webinar_service, TranslatorInterface $translator)
{
$this->crudUrlGenerator = $crudUrlGenerator;
$this->webinar_service = $webinar_service;
$this->translator = $translator;
}
// ...
public function sendAcknowledgementEmail(AdminContext $context): Response
{
$participant = $context->getEntity()->getInstance();
try {
$this->webinar_service->sendAcknowledgementEmail($participant);
$this->addFlash('notice', 'flash.email.sent');
} catch (Exception $e) {
$this->addFlash('error', $this->translator->trans('flash.error', ['message' => $e->getMessage()]));
}
$url = $this->crudUrlGenerator->build()
->setController(ParticipantCrudController::class)
->setAction(Action::INDEX)
->generateUrl()
;
return $this->redirect($url);
}
}
A: The v3.x of the bundle is quite new and the documentation is not perfect yet.
Based on Ceochronos answer, here is my implementation for a clone action.
public function configureActions(Actions $actions): Actions
{
$cloneAction = Action::new('Clone', '')
->setIcon('fas fa-clone')
->linkToCrudAction('cloneAction');
return $actions
->add(Crud::PAGE_INDEX, $cloneAction);
}
public function cloneAction(AdminContext $context)
{
$id = $context->getRequest()->query->get('entityId');
$entity = $this->getDoctrine()->getRepository(Product::class)->find($id);
$clone = clone $entity;
// custom logic
$clone->setEnabled(false);
// ...
$now = new DateTime();
$clone->setCreatedAt($now);
$clone->setUpdatedAt($now);
$this->persistEntity($this->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $clone);
$this->addFlash('success', 'Product duplicated');
return $this->redirect($this->get(CrudUrlGenerator::class)->build()->setAction(Action::INDEX)->generateUrl());
}
| |
doc_23527974
| ERROR: type should be string, got "https://www.ibm.com/developerworks/cloud/library/cl-softlayer-go-overview/index.html\nfunc main() {\n sess := session.New()\n service := services.GetVirtualGuestService(sess)\n\n guestTpl := datatypes.Virtual_Guest{\n Hostname: sl.String(\"sample\"),\n Domain: sl.String(\"example.com\"),\n MaxMemory: sl.Int(2048),\n StartCpus: sl.Int(1),\n Datacenter: &datatypes.Location{Name: sl.String(\"sjc01\")},\n OperatingSystemReferenceCode: sl.String(\"UBUNTU_LATEST\"),\n LocalDiskFlag: sl.Bool(true),\n }\n\n guest, err := service.Mask(\"id;domain\").CreateObject(&guestTpl)\n if err != nil {\n fmt.Println(err)\n os.Exit(-1)\n }\n\n fmt.Printf(\"New Virtual Guest created with ID %d\\n\", *guest.Id)\n fmt.Printf(\"Domain: %s\\n\", *guest.Domain)\n}\n\nThe IBM approval mail comes after an hour , and the VM related updates are generated after that mail. \nIs there a way to reduce the time ? Or is the IBM behavior takes longer time ?\nHelp is highly appreciated. \n\nA: I use python for that task and one day I've faced that I need 1 hour per 1 server to create. So there is no technical solution. IBM somehow approves server creating manually.\nI would recommend raise a support ticket to IBM. Now I have average 3 minutes to create a virtual server. \nJust in case try to use servers like B1_1X2X100. To insure that you use standard fast setup.\nGood luck\n"
| |
doc_23527975
|
canvas.drawText(getString(R.string.test1)+c, 30,320, paint);
a need change of "c" to bold...
Thanks...
A: the class Paint has method setTypeface , you can pass a Typeface.
code exmaple:
paint.setTypeface(Typeface.DEFAULT_BOLD);
so if you want change part of text, can draw one by one through change the typeface.
also, you can try use html code like <b>c</b>
A: Canvas.drawText and its various variants do all expect either a String, CharSequence or char[]. All those types do not support Spannable or Stylable objects. Short: It's not possible in the way you want.
You probably can try to implement the suggesstions idiottiger posted.
| |
doc_23527976
|
I would like to get value 'IdPrd' in the selectionchange event function.
var tpl_ram = new Ext.XTemplate(
'<ul>',
'<tpl for=".">',
'<li class="phone">',
'<img width="64" height="64" src="data/catalogo/ramos/imagenes/{IdRm}/{IdRm}.jpg" />',
'<strong>{NomRm}</strong>',
'<span>{DescRm}</span>',
'</li>',
'</tpl>',
'</ul>');
var ramos_dw = new Ext.DataView({
tpl: tpl_ram,
store: ramos_productos,
id: 'ramos_dw',
itemSelector: 'li.phone',
overClass: 'phone-hover',
singleSelect: true,
autoScroll: true,
autoHeight: true,
emptyText: 'SIN RESULTADOS QUE MOSTRAR',
listeners: {
'click': function() {},
selectionchange: {
fn: function(dv, nodes) {
//i want on selection get value 'IdPrd'
var record = nodes[0];
console.log("advert id - " + record.get('IdPrd'))
}
}
}
});
A: It's not clear how your model from your store looks like. But solution would be to get the data object first.
So the code would be:
var recordData = nodes[0].getData();
// keep in mind that user can select more than 1 node --> nodes[0]
console.log("advert id - " + recordData['IdPrd'])
You can also simply put debugger; into your selectionchange function listener and explore how exactly the nodes object which you get in your specific example looks like.
| |
doc_23527977
|
IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(typeof(OfficeDetailsDto), this.Request, this.Configuration.Formatters);
if (result == null)
{
var responseErr = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
throw new HttpResponseException(responseErr);
}
But now I want create a BaseAPIController controller by inheriting ApiController and want to override a base class's method to have the above code so that I don't have to write this code again and again in all my controller classes. It will also make my controller action method thin.
Can anyone give me any suggestion or sample please.
A: ApiController already provides the ability to handle content negotiation out of the box, but you could create your own generic method(s) that you can call from inherited controllers if you really want to customize the content negotiation process.
Your BaseAPIController
public abstract class BaseAPIController : ApiController {
protected virtual HttpResponseMessage NegotiatedContent<T>(HttpStatusCode statusCode, T content) {
var type = typeof(T);
var request = this.Request;
var formatters = this.Configuration.Formatters;
var negotiator = this.Configuration.Services.GetContentNegotiator();
var result = negotiator.Negotiate(type, request, formatters );
if (result == null) {
var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
throw new HttpResponseException(response));
}
return new HttpResponseMessage() {
StatusCode = statusCode,
Content = new ObjectContent<T>(
content, // What we are serializing
result.Formatter, // The media formatter
result.MediaType.MediaType // The MIME type
)
};
}
}
This code is equivalent to the what ApiController provides automatically.
A potential OfficeDetailsController with a much thinner action method
public class OfficeDetailsController : BaseAPIController {
public HttpResponseMessage GetOfficeDetails(int id) {
var item = new OfficeDetailsDto() { Id = id, Name = "Gizmo"};
// what ever else needs to be done to the item
// ...
return NegotiatedContent(HttpStatusCode.Ok, item);
}
}
Here is an example of doing the same thing using ApiController defaults.
public class OfficeDetailsController : ApiController {
public IHttpActionResult GetOfficeDetails(int id) {
var item = new OfficeDetailsDto() { Id = id, Name = "Gizmo"};
// what ever else needs to be done to the item
// ...
return Ok(item);
}
}
| |
doc_23527978
|
Thanks!
A: Figured it out. I just needed to adjust the margins.
| |
doc_23527979
|
Ember.TextField.reopen({
//add some bootstrap specific stuff
attributeBindings: ['data-provide', 'data-items', 'dataSourceBinding:data-source'],
'dataSourceBinding': Ember.Binding.oneWay('App.AddStoreTemplateController.statesArray')
});
I have a router with connectOutlets which attaches my template:
{{view Ember.TextField elementId="state" placeholder="NY/New York" valueBinding="state" data-provide="typeahead" data-items="4" data-source="App.router.addStoreTemplateController.statesArray"}}
My controller:
AddStoreTemplateController: Ember.ArrayController.extend({
statesArray: ['Alabama', 'Washington']
}),
What I expect to see rendered in HTML:
<input id="state" class="ember-view ember-text-field" placeholder="NY/New York" type="text" data-provide="typeahead" data-items="4" data-source="['Alabama', 'Washington']">
What it actually renders in HTML:
<input id="state" class="ember-view ember-text-field" placeholder="NY/New York" type="text" data-provide="typeahead" data-items="4" data-source="App.router.addStoreTemplateController.statesArray">
Typeahead docs
http://twitter.github.com/bootstrap/javascript.html#typeahead
Thanks so much. I really enjoy EmberJS!!
A: After fiddling with this a bit more, I figured out an easy way to do this. It doesn't require a 3rd party library and you can use Ember.TextField to keep your inputs pretty:
I created a new extended TextField object to keep things separate:
Ember.TextFieldTypeahead = Ember.TextField.extend({
//add some bootstrap specific stuff
attributeBindings: ['data-provide', 'data-items', 'data-source'],
'data-source': function(){
return JSON.stringify(["Alabama", "Washington"]);
}.property()
});
Then in my template:
{{view Ember.TextFieldTypeahead elementId="state" placeholder="NY/New York" valueBinding="state" data-provide="typeahead" data-items="4" data-source=on}}
Things worked fine. Only confusing thing to me, and this may be an Ember bug or just my noob status of the framework, is that data-source= in the template can be anything, it still references the function that I declared. just leaving it as "data-source" in the template yields an error on the handlebars build, so I just opted to make the value "on" so I'm not confused in 6 months time when I revisit the code for some reason. Curious.
I'm also guessing I can extend this even more to observe "value" and then on value change populate the 'data-source' property with whatever ajax call my server responds with to satisfy the dynamic requirement.
A: You can also do something like this (when you want to load the data dynamically as you type from the server):
ember-bootstrap
EEPD.EbedMedicationArticleTypeAhead = Bootstrap.Forms.TypeAhead.extend({
init: function () {
this._super();
this.set('idProperty', 'id');
},
valueChanged: function () {
var id = this.get('value');
var self = this;
var label = this.get('_childViews')[1].$()
.val();
if (Ember.empty(label) && !Ember.empty(id)) {
var articleDescription = this.get('item.articleDescription');
self.get('_childViews')[1].$()
.val(articleDescription)
.change();
}
} .observes('value'),
getLabel: function (item) {
return '%@ (%@)'.fmt(Ember.get(item, 'description'), Ember.get(item, 'amount'));
},
getQueryPromise: function (query) {
//get some data from SignalR
return $.connection.ccprCardioArticles.server.getAllByDescriptionLike(query);
}
});
the handlebar will look like this:
{{view EEPD.EbedMedicationArticleTypeAhead
label="Medicament:"
name="articleNumber"}}
Result:
A: For this I wouldn't use the Ember.TextField. You could do something like:
<input ... data-items="4" {{bindAttr data-source="formattedDataSource"}}/>
In your controller:
formattedDataSource: function(){
.. format your states array as a string or dump to json...
}.property()
| |
doc_23527980
|
<Border x:Name="border">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding MessageType}" Value="Error">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Rectangle>
<Rectangle.Style>
<Style TargetType="{x:Type Rectangle}">
<Style.Triggers>
<DataTrigger Binding="{Binding MessageType}" Value="Error">
<Setter Property="Fill" Value="Icon.ico" />
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</Border>
(MessageType is a Enum)
How can i combine this two StyleTrigger into One? Is it possible?
A: Not sure what your parent object is, containing the border. But i assume a DataTemplate, other objects should be work similar.
<DataTemplate>
<Border x:Name="border">
<Rectangle x:Name="rect"/>
<Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding MessageType}" Value="Error">
<Setter TargetName="border" Property="Background" Value="Red" />
<Setter TargetName="rect" Property="Fill" Value="Icon.ico" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
Updated for comments:
<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="myTemplate">
<!-- above template -->
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource myTemplate}"/>
</Grid>
</UserControl>
| |
doc_23527981
|
$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name;
"$usbDriveLetter" + "image.png"
But if I don't use a var and make "G:\" static in the PowerShell script, the image opens just fine.
G:\image.png
So what am I doing wrong here? How do we dynamically open images using ps1 scripts?
A: When combining two strings, you get a string. If you quote the path ("G:\image.png") it will behave the same.
Use Invoke-Item to execute the path:
$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name
Invoke-Item -Path ("$usbDriveLetter" + "image.png")
You may also use the call-operator &:
$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name
& ("$usbDriveLetter" + "image.png")
A: Frode F.'s helpful answer provides effective solutions.
As for when you need &, PowerShell's call operator:
In order to execute a command / open a document that is not specified as an unquoted, literal string, you need &.
That is, & is needed whenever you specify the command name (or path) / document filename (or path):
*
*either: as a quoted string (e.g., "G:\image.png")
*or: as the result of an expression (e.g., ("$usbDriveLetter" + "image.png"); ditto for $(...))
Note:
*
*In the case of opening a document (rather than invoking an executable), you may use Invoke-Item instead of &.
*If you're trying to open a folder path in File Explorer, only Invoke-Item works.
As for why you need &:
PowerShell has two fundamental parsing modes:
*
*argument mode, which works like traditional shells
*expression mode, which works like traditional programming languages.
Running Get-help about_Parsing provides an introduction to these modes.
In short, it is the first token that determines which mode is applied, and in order to execute / open something, it must be parsed in argument mode (in expression mode, the result is simply output); thus, the 1st token must be:
*
*either: a literal, unquoted command/document name or path, as stated.
*or: &, in which case the next argument - which may then be specified as a quoted string or expression - is interpreted as the command / document name or path to execute / open.
| |
doc_23527982
|
My error is:
Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
An exception occurred while executing a Transact-SQL statement or batch.
CREATE FILE encountered operating system error 5 (Access is denied) while attempting to open or create the physical file 'D:\Project\Masoomi\UniversityService\DataBase\Universityservice.mdf'. (Microsoft SQL Server, Error: 5123)
I run as administrator too. My windows is 7 and I installed SQL Server 2008 R2.
My previous windows was 7 and SQL Server 2008 R2.
What shall I do?
A: I shared the mdf,ldf files and problem solved.
A: As another solution I came across this today and was able to resolve it by simply running SQL Server Management Studio as administrator. I am using SQL Server 2008 R2.
| |
doc_23527983
|
A: Regarding your other question Xamarin Forms - How to create custom render to give TableSection the default iOS Footer?, I'm not sure whether you want to add footer to the whole TableView or to each TableSection of TableView.
If you want to add footer to each TableSection, I suggest just to add a customized TextCell as footer in each TableSection since TableSection can have multiple Cell children, but if you want to add footer to TableView, you can for example code like this:
public class TableViewWithFooterRenderer : TableViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control != null)
{
//Add footer to the whole TableView
var lv = Control as Android.Widget.ListView;
var footerview = ((LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService))
.Inflate(Resource.Layout.TableViewFooter, null, false);
lv.AddFooterView(footerview);
}
}
}
}
I created a view for footer, as you can also use other views. My footer view is like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView android:id="@+id/footer"
android:text="This is footer"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_gravity="center" />
</LinearLayout>
Update:
TableView is rendered as ListView in Android platform, since there is no native method in Android platform to directly add footer to each item of ListView, as I suggested, we can manually add a customized TextCell or ViewCell as footer for each item. As you can see from the source code of TableSection, it's a ObservableCollection of objects.
For example:
<TableSection Title="Section 1 Title">
<TextCell Text="TextCell Text" Detail="TextCell Detail"></TextCell>
<ViewCell IsEnabled="False">
<Grid>
<Label Text="This is footer" />
</Grid>
</ViewCell>
</TableSection>
I didn't customized the style of ViewCell here, you may try your style on it.
| |
doc_23527984
|
I'm building Client/Server meetings System
I had a problem "Cannot implicitly convert type 'string' to 'System.Security.Cryptography.RSAParameters'"
I will explain the process quickly
*
*Client Connect to Server
*server send back his public Key
*Client will encrypt the username+his public key By Server public key
I received Server reply ( public key ) but when I tried to encrypt using RSA the error above appeared
This is my Code :
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
// mess is Server response as string
RSAParameters publickey = mess;
rsa.ImportParameters(publickey);
byte[] encryptedData = rsa.Encrypt(StringToByte(uname.Text + "|||" + PUBKEY), true);
A: First of all, ImportParameters() does not accept a string. It is expecting something of type RSAParameters. And it cannot implicitly convert a string to RSAParameter object, and that is why the error is shown.
I believe you haven't fundamentally understood on how RSA works. Or is it technical?
Read the examples provided in here to understand it technically.
What you should be looking for is how to correctly export the public key from the server, and use the same public key to encrypt something in the client end.
As you would have guessed ExportParameters and ImportParameters looks promising. However I had trouble sending it through an SMS (in my project). So what I used was ExportCspBlob and ImportCspBlob. Make sure you specify false to ExportCspBlob so as to not include private key information.
To send it as a string, what I had to do was base64 encode the byte array that was returned from ExportCspBlob. To do the conversion, use the Convert class. The methods you are specifically looking for are ToBase64String and FromBase64String
| |
doc_23527985
|
import os
from subprocess import Popen, PIPE, run
import jaydebeapi
from project_lib import Project
project = Project.access()
abc_connection = project.get.connection(name="abc")
abc_connection = jaydebeapi.connect('com.ibm.db2.jcc.DB2Driver',
'{}://{}:{}/{}:user={};password={};'.format('jdbc:db2',
abc_credentials['host'],
abc_credentials['port'],
abc_credentials['database'], '/project_data/data_asset/ssl_cert.crt',
abc_credentials['username'],
abc_credentials['password']))
curs = abc_connection.cursor()
Any help is appreciated. Thanks.
| |
doc_23527986
|
SELECT Fname, Minit, Lname, Address, Hourly, Sname, Saddress, Dno
FROM (SELECT *
FROM EMPLOYEE, DEPARTMENT, LOCATION
WHERE EMPLOYEE.Dno = DEPARTMENT.Dnumber AND
LOCATION.Store_num = DEPARTMENT.Store_num AND
(Fname='100' OR Lname='100'
OR LOCATION.Store_num ='100' OR Dno='100')) X
All of the OR statements will turn into '?' in mySQL, so for now I'm using 100 which will only work with Store_num. So this should bring up a list of the employees who work at that store.
However, the error I'm getting says: #1060 - Duplicate column name 'Mgr_ssn'
Here are my tables, not sure why they aren't merging correctly.
CREATE TABLE EMPLOYEE
( Fname VARCHAR(15) not null,
Minit CHAR,
Lname VARCHAR(15) not null,
Ssn CHAR(9) not null,
Bdate DATE,
Address VARCHAR(30),
Hourly DECIMAL(5,2),
Mgr_ssn CHAR(9),
Dno INT not null,
Start_date DATE,
Phone CHAR(10),
PRIMARY KEY (Ssn),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) );
CREATE TABLE DEPARTMENT
( Dname VARCHAR(15) not null,
Dnumber INT not null,
Mgr_ssn CHAR(9) not null,
Mgr_start_date DATE,
Phone CHAR(10),
Store_num INT not null,
PRIMARY KEY (Dnumber, Store_num),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Store_num) REFERENCES LOCATION(Store_num)
);
CREATE TABLE LOCATION
( Store_num INT NOT NULL,
Sname VARCHAR(15) NOT NULL,
Saddress VARCHAR(30) NOT NULL,
PRIMARY KEY (Store_num),
UNIQUE (Saddress)
);
A: the problem is here
SELECT * FROM EMPLOYEE, DEPARTMENT, LOCATION
tables EMPLOYEE and DEPARTMENT have both Mgr_ssn column. you need to specify the table in which Mgr_ssn come from, ex
SELECT EMPLOYEE.Mgr_ssn AS `EMP_Mgr_ssn`,
DEPARTMENT.Mgr_ssn AS `DEP_Mgr_ssn`,
.....
FROM EMPLOYEE, DEPARTMENT, LOCATION
an alias would also help you solve it.
so the full query would be
SELECT Fname, Minit, Lname, Address, Hourly, Sname, Saddress, Dno
FROM
(
SELECT LOCATION.*,
Employee.Mgr_ssn AS `EMP_Mgr_ssn`,
DEPARTMENT.Mgr_ssn AS `DEP_Mgr_ssn`,
Employee.Fname,
Employee.Minit,
Employee.Lname,
Employee.Address,
Employee.Hourly,Employee.Dno
FROM EMPLOYEE, DEPARTMENT, LOCATION
WHERE EMPLOYEE.Dno = DEPARTMENT.Dnumber AND
LOCATION.Store_num = DEPARTMENT.Store_num AND
(Fname='100' OR Lname='100'
OR LOCATION.Store_num ='100' OR Dno='100'
)
) X
but this query will also work because you don't Mgr_ssn column
SELECT Fname, Minit, Lname, Address, Hourly, Sname, Saddress, Dno
FROM
(
SELECT LOCATION.*,
Employee.Fname,
Employee.Minit,
Employee.Lname,
Employee.Address,
Employee.Hourly,Employee.Dno
FROM EMPLOYEE, DEPARTMENT, LOCATION
WHERE EMPLOYEE.Dno = DEPARTMENT.Dnumber AND
LOCATION.Store_num = DEPARTMENT.Store_num AND
(Fname='100' OR Lname='100'
OR LOCATION.Store_num ='100' OR Dno='100'
)
) X
*
*SQLFiddle Demo
A: Two of your table contain 'Mgr_ssn' column. To solve above problem change name of one of the column by using following query
select employee.Mgr_ssn as 'give_any_name' .....
| |
doc_23527987
|
val uri = Uri.fromFile(file)
val storage = FirebaseStorage.getInstance()
val pdfRef = storage.reference.child("pdf/${uri.lastPathSegment}")
pdfRef.putFile(uri).addOnFailureListener { e ->
Log.e(TAG, "Couldn't share " + e.message)
}.addOnCompleteListener{
it.addOnCompleteListener {
pdfRef.downloadUrl.addOnSuccessListener { e ->
run {
link = e.toString()
Log.i(TAG,link!!) // Here i get the link to file in firebase storage
}
}
}
}
// Here link gets null
}
i was expecting somehow i can get the link to the file and can use it for sharing intent
A: You are performing an asynchronous call to upload the file, that is correct since any UI blocking action must be performed in background. The variable link will be null until the run code is executed in the background thread.
You need to code inside the run block whatever you want to happen when the link is available.
BTW looks weird what you are doing with the nested addOnCompleteListener, there should be an easier way to code that. You should probably spend time learning how to code with listeners and background threads.
| |
doc_23527988
|
Here is what my .flowconfig has:
[ignore]
.*/node_modules/.*
static/.*
[options]
module.name_mapper='^core/\(.*\)' -> '<PROJECT_ROOT>/core/\1'
and here is some file
/* @flow */
import Dispatcher from 'flux';
import Action from 'core/Action';
const AppDispatcher: Dispatcher<Action> = new Dispatcher();
export default AppDispatcher;
But when I try to run flow check I'm receiving:
core/Dispatcher.js:2
2: import Dispatcher from 'flux';
^^^^^^ flux. Required module not found
Can anyone share their successful experience in setting up the project?
Thanks.
A: This happens because you chose to ignore node_modules, so flow doesn't see flux. You need to remove this line from config or add declarations for flux
| |
doc_23527989
|
Here's the problem: the subordinate Activities are all Standard Launch Mode but in the course of the manufacturing process they have to be opened and closed many times and sometimes these closes will be initiated from outside the subordinate Activity, say, from the thread that talks to the PC. How do I have the main activity of my task close standard launch mode activities that it created so I don't end up spawning lots of duplicate activities?
I can't change the subordinate activities to Singletask or SingleInstance because they don't support onActivityResult().
A: Implement a BroadcastReceiver in your subordinate activities and have the parent send a broadcast when it receives the PC command. You can have diferent broadcasts for each subordinate activity.
In the receiver you just have to do whatever you want (call finish() for example).
A: I think that android:noHistory is what you are looking for:
Whether or not the activity should be removed from the activity stack
and finished (its finish() method called) when the user navigates away
from it and it's no longer visible on screen — "true" if it should be
finished, and "false" if not. The default value is "false". A value of
"true" means that the activity will not leave a historical trace. It
will not remain in the activity stack for the task, so the user will
not be able to return to it.
The correspondent java falt to set into your intent is Intent.FLAG_ACTIVITY_NO_HISTORY.
Intent i = new Intent(...)
i.setFlag( Intent.FLAG_ACTIVITY_NO_HISTORY );
hope this helps
| |
doc_23527990
|
The idea is to produce a single JS file.
Since this is also part of a bigger project with multiple project pages I got a problem where to put the output of the compiler and how to setup.
The ideal setup would be placing the GWT stuff into a single project and incooperate the ouput in a different project. The question is how to do it?
Update:
The current plan is to compile the JavaScript out of GWT using a simple Java application just issuing the GWT compile command and taking the Eclipse auto-build classes as necessary input. After the sources are compiled to java script the application copies the js files (one for every supported browser) to the related destination. This way the once created js files stay static and other developers do not have to deal with GWT related build tasks and we just avoid a necessary maven fight to get things working on build.
Also the GWT project can now depend on the web project making it possible to start the web application and alter its behaviour by adding support to host mode debugging.
Does anyone know a working example?
A: The easiest way, if you build a WAR in the end, is to put the output of GWT in a WAR too that you can use an an overlay in the final WAR module.
Other Maven plugins could do the trick too (dependency:unpack, maven-shade-plugin, etc.)
See https://github.com/tbroyer/gwt-maven-archetypes for examples.
| |
doc_23527991
|
The problem is that the update statistics syntax will not allow me to call a 4-part name.
I would like to do something like this:
UPDATE STATISTICS [linked server].[database].[dbo].[table]
WITH FULLSCAN
GO
But I'm getting an error stating that the max number of prefixes has been exceeded.
Does anyone know how to get around this? I really don't have the option to put this locally on my client database.
ANSWER FOUND
Thanks to everybody who threw their hats at this one but I actually found a really cool workaround for this one and hopefully it can help someone else.
EXEC [linked_server].[database].[sys].[sp_executesql] N'UPDATE STATISTICS [dbo].[table] WITH FULLSCAN'
This can be used for truncation, trigger enable and disable, and other functions of SQL that are not allowed across linked servers.
From what I understand it passes the statement through the linked server rather then the execution.
A: You probably wouldn't want to get around this limitation as it would seem unwise to do across a distributed transaction ;-). But you are in luck. You are already using SSIS. Just have SSIS connect to the proper server and do the UPDATE STATISTICS via that direct / local connection.
Additionally, since you are using SSIS, it has a task for Updating Statistics:
*
*Update Statistics Task (Maintenance Plan)
*Update Statistics Task
| |
doc_23527992
|
When downloading ember with bower, i get the 1.5.1 version.
Afterwards when downloading the ember-data i get:
$ bower install ember-data bower cached
git://github.com/components/ember-data.git#0.0.14 bower validate
0.0.14 against git://github.com/components/ember-data.git#* bower cached git://github.com/components/ember.git#1.0.1 bower
validate 1.0.1 against
git://github.com/components/ember.git#~1.0.0
Unable to find a suitable version for ember, please choose one:
1) ember#~1.0.0 which resolved to 1.0.1 and is required by ember-data#0.0.14
2) ember#~1.5.1 which resolved to 1.5.1 and is required by davidga
Prefix the choice with ! to persist it to bower.json
[?] Answer:
I want to use ember 1.0 beta as i know it from the getting started guide and it works fine with the 1.5.1 version of ember.
How do i tell bower to download the ember-data beta version?
I tried to fix it like the following post How to download ember canary version using bower
but it did not work.
bower install ember-data:"1.0.0-beta.5"
wer ENOTFOUND Package ember-data:1.0.0-beta.5 not found
A: I found the answer according to this link
http://code.tutsplus.com/tutorials/meet-bower-a-package-manager-for-the-web--net-27774
If i want a specific version i have to write # and then the version
bower install ember-data#1.0.0-beta.8
A: bower install ember-data-shim
this command will install ember-data 1.0.0-beta.8
in bower.json:
"ember-data-shim": "1.0.0-beta.8",
| |
doc_23527993
|
angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.4/$injector/modulerr?p0=sport1Feed&p1=Error…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.4%2Fangular.min.js%3A22%3A179)
at angular.js:38
at angular.js:4920
at q (angular.js:403)
at g (angular.js:4880)
at eb (angular.js:4802)
at c (angular.js:1914)
at Sc (angular.js:1935)
at ue (angular.js:1820)
at angular.js:33367
at HTMLDocument.b (angular.js:3431)
My app is defined and invoked in html, same as my controller. What am I doing wrong here?
app.js:
var app = angular.module('testApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap','ui.router']);
ctrl.js:
app.controller('feedCtrl', function($scope, $http) {
$http.get('https://api.myjson.com/bins/13vg19').then(function(res) {
$scope.res = res.data;
console.log($scope.res);
});
});
html:
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My AngularJS App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="app.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="./components/app/app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.4/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/x2js/1.2.0/xml2json.js"></script>
<script src="./components/controller/ctrl.js"></script>
</head>
<body>
<div data-ng-controller="feedCtrl">
</div>
</body>
</html>
What exactly is an error here? I have tried placing ng-app in the body tags, same result. As you can see, app.js is invoked after the angular library.
Thanks.
EDIT: I have just noticed in the console, under Network that the request to the https://api.myjson.com/bins/13vg19 is not being invoked at all.
A: Load the app.js after loading all the dependencies references, your order should be
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.4/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/x2js/1.2.0/xml2json.js"></script>
<script src="./components/app/app.js"></script>
<script src="./components/controller/ctrl.js"></script>
A: This problem means angular could not inject modules to your app. The reasons for that might be that you didn't import them in the HTML or versions mismatch (for example import anguler version x and angular-animate version y). Generally speaking, in angular exceptions messages usually contain a link to angular's site which explains the problem better, in plain text.
As I see this, you imported you js file before you imported the necessary angular files, and you didn't imported at all angular-animate and ui.bootstrap.
| |
doc_23527994
|
int a;
if (UDT::ERROR == (a = UDT::send(*(UDTSOCKET*)sock, buffer, size, 0)))
{
cout << "send: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
else
{
return a;
}
This is the code i use. the value of 'a' is not the same as 'size' at times.
I know this can happen if its non-blocking but i am using blocking send with infinite timeout.
A: If you have a send timeout set, this is probably a timeout. If not, you can consider this an error that is fatal to the connection. You can call getlasterror to find out what went wrong.
A: UDP datagrams are sent entire or not at all. The situation you describe is impossible. Please provide your evidence.
| |
doc_23527995
|
I want code like
www.TestApplication.com?cookieValue=values
A: You cannot share cookies across sites, I'm afraid. This is basic security feature. Otherwise malicious websites could steal your banking session cookies.
| |
doc_23527996
|
= IF(OR(SUMPRODUCT(--((ISERR(SEARCH({"/amp/"},a2)))))>0),FALSE,TRUE)))))))))))))
How would I do that in a calculated column/measure in Power BI?
A: You can use FIND function to search for the /amp/ in the column where the URL is stored. You can define the value to be returned, if the pattern is not found, but not the value in case it is. So you can use IF to be able to freely define "contains" and "do not contains" values.
=IF(FIND("/amp/", 'TableName'[ColumnWithURL], -1) = -1, <value_if_true>, <value_if_false>)
| |
doc_23527997
|
using (var _db = new LuxedecorContext())
{
var items = (from navItem in _db.NavItems
join dealItem in _db.Deal_Items
on navItem.ItemWebCode equals dealItem.ItemWebCode
join mainCategory in _db.Web_MainCategory
on new { A = navItem.Website, B = navItem.MainCategory }
equals new { A = mainCategory.Website, B = mainCategory.Code }
join subCategory in _db.Web_SubCategory
on new { A = navItem.Website, B = navItem.MainCategory, C = navItem.SubCategory }
equals new { A = subCategory.Website, B = subCategory.CodeMain, C = subCategory.Code }
select new
{
SalePrice = navItem.SalePrice,
Vendor = navItem.Vendor,
Promo = navItem.Promo,
Description = navItem.Description,
FreightMax = navItem.FreightMax,
ItemImage = navItem.ItemImage,
ItemImage2 = navItem.ItemImage2,
StrikedPrice = (navItem.RetailPrice ?? 0) * (1 - (navItem.PercentOff ?? 0) / 100) / (1 - navItem.PercentOffShow / 100),
ItemId = navItem.ItemID,
StockQty = navItem.StockQty,
SeoURL = navItem.SeoURL,
DealSequence = dealItem.Sequence,
DealId = dealItem.DealID,
Website = navItem.Website
}).Where(x => x.SeoURL != string.Empty && x.DealId == dealId).GroupBy(x=>x.ItemId).Select(x=>x.FirstOrDefault());
if(onlyAvalaibleItems)
items = items.Where(x => x.StockQty != "0");
switch(sort)
{
case "PriceAsc":
items = items.OrderBy(x => x.SalePrice);
break;
case "PriceDesc":
items = items.OrderByDescending(x => x.SalePrice);
break;
case "DescriptionAsc":
items = items.OrderBy(x => x.Description.Replace(x.Vendor, "").Trim());
break;
case "DescriptionDesc":
items = items.OrderByDescending(x => x.Description.Replace(x.Vendor, "").Trim());
break;
default:
items = items.OrderBy(x=>x.DealSequence);
break;
}
return await items.Select(x => new ProductCollectionItem
{
SalePrice = x.SalePrice,
Vendor = x.Vendor,
Promo = x.Promo,
Description = x.Description,
FreightMax = x.FreightMax,
ItemImage = x.ItemImage,
ItemImage2 = x.ItemImage2,
StrikedPrice = x.StrikedPrice ?? 0
}).ToListAsync();
}
This is SQL, which I've got:
SELECT
[Project4].[C1] AS [C1],
[Project4].[SalePrice] AS [SalePrice],
[Project4].[Vendor] AS [Vendor],
[Project4].[Promo] AS [Promo],
[Project4].[Description] AS [Description],
[Project4].[FreightMax] AS [FreightMax],
[Project4].[ItemImage] AS [ItemImage],
[Project4].[ItemImage2] AS [ItemImage2],
[Project4].[C2] AS [C2]
FROM ( SELECT
1 AS [C1],
CASE WHEN ([Limit1].[C1] IS NULL) THEN cast(0 as decimal(18)) ELSE [Limit1].[C1] END AS [C2],
[Limit1].[Description] AS [Description],
[Limit1].[SalePrice] AS [SalePrice],
[Limit1].[ItemImage] AS [ItemImage],
[Limit1].[ItemImage2] AS [ItemImage2],
[Limit1].[Vendor] AS [Vendor],
[Limit1].[Promo] AS [Promo],
[Limit1].[FreightMax] AS [FreightMax],
[Limit1].[Sequence] AS [Sequence]
FROM (SELECT
@p__linq__0 AS [p__linq__0],
@p__linq__1 AS [p__linq__1],
[Distinct1].[ItemID] AS [ItemID]
FROM ( SELECT DISTINCT
[Extent1].[ItemID] AS [ItemID]
FROM [dbo].[NavItems] AS [Extent1]
INNER JOIN [dbo].[Deal_Items] AS [Extent2] ON [Extent1].[ItemWebCode] = [Extent2].[ItemWebCode]
INNER JOIN [dbo].[Web_MainCategory] AS [Extent3] ON ([Extent1].[Website] = [Extent3].[Website]) AND ([Extent1].[MainCategory] = [Extent3].[Code])
INNER JOIN [dbo].[Web_SubCategory] AS [Extent4] ON ([Extent1].[Website] = [Extent4].[Website]) AND ([Extent1].[MainCategory] = [Extent4].[CodeMain]) AND ([Extent1].[SubCategory] = [Extent4].[Code])
WHERE ( NOT (([Extent1].[SeoURL] = @p__linq__0) AND ((CASE WHEN ([Extent1].[SeoURL] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent2].[DealID] = @p__linq__1)
) AS [Distinct1] ) AS [Project2]
OUTER APPLY (SELECT TOP (1)
[Extent5].[Description] AS [Description],
[Extent5].[SalePrice] AS [SalePrice],
[Extent5].[ItemImage] AS [ItemImage],
[Extent5].[ItemImage2] AS [ItemImage2],
[Extent5].[Vendor] AS [Vendor],
[Extent5].[Promo] AS [Promo],
[Extent5].[FreightMax] AS [FreightMax],
[Extent6].[Sequence] AS [Sequence],
((CASE WHEN ([Extent5].[RetailPrice] IS NULL) THEN cast(0 as decimal(18)) ELSE [Extent5].[RetailPrice] END) * (cast(1 as decimal(18)) - ((CASE WHEN ([Extent5].[PercentOff] IS NULL) THEN cast(0 as decimal(18)) ELSE [Extent5].[PercentOff] END) / cast(100 as decimal(18))))) / (cast(1 as decimal(18)) - ([Extent5].[PercentOffShow] / cast(100 as decimal(18)))) AS [C1]
FROM [dbo].[NavItems] AS [Extent5]
INNER JOIN [dbo].[Deal_Items] AS [Extent6] ON [Extent5].[ItemWebCode] = [Extent6].[ItemWebCode]
INNER JOIN [dbo].[Web_MainCategory] AS [Extent7] ON ([Extent5].[Website] = [Extent7].[Website]) AND ([Extent5].[MainCategory] = [Extent7].[Code])
INNER JOIN [dbo].[Web_SubCategory] AS [Extent8] ON ([Extent5].[Website] = [Extent8].[Website]) AND ([Extent5].[MainCategory] = [Extent8].[CodeMain]) AND ([Extent5].[SubCategory] = [Extent8].[Code])
WHERE ( NOT (([Extent5].[SeoURL] = @p__linq__0) AND ((CASE WHEN ([Extent5].[SeoURL] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent6].[DealID] = @p__linq__1) AND ([Project2].[ItemID] = [Extent5].[ItemID]) ) AS [Limit1]
) AS [Project4]
ORDER BY [Project4].[Sequence] ASC
There is no any relation in the old DB. I'm using most of joins just to cut data which I don't need. I wonder: is this a good way? How can I optimize my query?
A: I always prefer not to use joins for filtering purposes. For two reasons:
*
*Joins may multiply the results (if the joined table is in a 1:n association), so you have to make the results distinct. This may be a compelling reason performance-wise.
*Join conveys that you want to extend the result set by fields from the joined table. Any, on the other hand, (or EXISTS in SQL) exactly conveys what you want: filtering. In other words: use the method that makes your code self-explanatory.
If you only have joins with 1..n-1 associations (which I assume), only the second reason counts, because performance shouldn't differ much. For me the second reason is compelling enough though.
Side note: even though the database doesn't have hard foreign key, I'd strongly recommend you do define associations (navigation properties) in the EF model. If you do that you can use code like
from navItem in _db.NavItems
where navItem.DealItem != null
Or pull the (pseudo) foreign keys into the class model as properties, so you can do
from navItem in _db.NavItems
where navItem.ItemWebCode.HasValue
| |
doc_23527998
|
.root {
@tailwind base;
@tailwind components;
@tailwind utilities;
@tailwind variants;
.exampleClass { }
}
<div className="root">{children}</div>
However, this does not work.
Could you please give me some advice to solve the issue? Thanks in advance.
A: A solution is to generate CSS in two steps.
Step 1: Generate the tailwind CSS into a temporary file.
The src/app.css file:
@tailwind base;
@tailwind components;
@tailwind utilities;
@tailwind variants;
.exampleClass { }
Generating the temporary file:
$ tailwindcss -i ./src/app.css -o ./src/app.tmp.css --watch
Step 2: Use a SCSS file to generate the final CSS.
The src/app.scss file:
.root {
@import "app.tmp";
}
Generating the final file:
$ sass --watch src/app.scss dist/app.css
A: You can use the important property in your tailwind.config.js to set a wrapping class or id.
module.exports = {
important: '#app',
}
See the docs for more information:
https://tailwindcss.com/docs/configuration#selector-strategy
A: One solution is to add a prefix in tailwind.config.js:
module.exports = {
prefix: 'tw-',
}
This would make it so that the Tailwind utility classes can only be referenced if the prefix is added, e.g. tw-m-2, which should (hopefully) prevent any conflicts with the other site styles.
For more details, see: https://tailwindcss.com/docs/configuration#prefix
| |
doc_23527999
|
name="lorem[ipsum_dolor_set-amet-34][1][consectetuer]"
I have regex code below that almost work.
My Code: [\[^.*\]](\d+)
But the result is, it matched the open brace and index < [1 > instead of index < 1 > only.
Any answer is much appreciated.
Thanks in advance. :)
A:
But the result is, it matched the open brace and index < [1 > instead of index < 1 > only.
I think your regex code is ok, but you are using the first index of your match array.
var myString = "name='lorem[ipsum_dolor_set-amet-34][1][consectetuer]'";
var arr = myString.match(/[\[^.*\]](\d+)/);
console.log(arr[0] + " " + arr[1]);
A: You can capture the digits from the square brackets:
var name = "lorem[ipsum_dolor_set-amet-34][1][consectetuer]";
var regex = /\[([0-9]+)\]/;
if (m = name.match(regex)[1]) {
console.log(m);
}
JSFiddle demo.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.