source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0009654485.txt"
] | Q:
XDEBUG works with URL but not with Cookie set
my XDEBUG environment is setup and is working in most cases. I am working on a simple REST based web service which I can debug fine if I pass across the URI in the following format
POST http://192.168.1.121:8888/QDOSStatsLogger/statLogger.php?XDEBUG_SESSION_START=ECLIPSE_DBGP HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, */*
Host: 192.168.1.121:8888
Content-Length: 295
Expect: 100-continue
When I try do the exact same thing with cookies set, it fails to start the debugger
This is what goes over the wire in the cookie situation (as seen in fiddler)
POST http://192.168.1.121:8888/QDOSStatsLogger/statLogger.php HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, */*
Host: 192.168.1.121:8888
Cookie: XDEBUG_SESSION_START=ECLIPSE_DBGP
Content-Length: 295
Expect: 100-continue
My output from phpInfo looks like the following with respect to xdebug. Am I missing something obvious?
xdebug.auto_trace Off Off
xdebug.cli_color 0 0
xdebug.collect_assignments Off Off
xdebug.collect_includes On On
xdebug.collect_params 0 0
xdebug.collect_return Off Off
xdebug.collect_vars Off Off
xdebug.coverage_enable On On
xdebug.default_enable On On
xdebug.dump.COOKIE no value no value
xdebug.dump.ENV no value no value
xdebug.dump.FILES no value no value
xdebug.dump.GET no value no value
xdebug.dump.POST no value no value
xdebug.dump.REQUEST no value no value
xdebug.dump.SERVER no value no value
xdebug.dump.SESSION no value no value
xdebug.dump_globals On On
xdebug.dump_once On On
xdebug.dump_undefined Off Off
xdebug.extended_info On On
xdebug.file_link_format no value no value
xdebug.idekey tony ECLIPSE_DBGP
xdebug.manual_url http://www.php.net http://www.php.net
xdebug.max_nesting_level 100 100
xdebug.overload_var_dump On On
xdebug.profiler_aggregate Off Off
xdebug.profiler_append Off Off
xdebug.profiler_enable Off Off
xdebug.profiler_enable_trigger Off Off
xdebug.profiler_output_dir /tmp/xdebug/ /tmp/xdebug/
xdebug.profiler_output_name cachegrind.out.%p cachegrind.out.%p
xdebug.remote_autostart Off Off
xdebug.remote_connect_back Off Off
xdebug.remote_cookie_expire_time 3600 3600
xdebug.remote_enable On On
xdebug.remote_handler dbgp dbgp
xdebug.remote_host localhost localhost
xdebug.remote_log no value no value
xdebug.remote_mode req req
xdebug.remote_port 9000 9000
xdebug.scream Off Off
xdebug.show_exception_trace Off Off
xdebug.show_local_vars Off Off
xdebug.show_mem_delta Off Off
xdebug.trace_enable_trigger Off Off
xdebug.trace_format 0 0
xdebug.trace_options 0 0
xdebug.trace_output_dir /var/tmp/ /var/tmp/
xdebug.trace_output_name trace.%c trace.%c
xdebug.var_display_max_children 128 128
xdebug.var_display_max_data 512 512
xdebug.var_display_max_depth 3 3
Thanks in advance
A:
Documentation states:
When the URL variable XDEBUG_SESSION_START=name is appended to an URL
Xdebug emits a cookie with the name "XDEBUG_SESSION" and as value the
value of the XDEBUG_SESSION_START URL parameter.
so cookie is called XDEBUG_SESSION, but your HTTP client seems to be passing cookie with another name:
Cookie: XDEBUG_SESSION_START=ECLIPSE_DBGP
|
[
"stackoverflow",
"0042634339.txt"
] | Q:
Multiplying lists together
Been working on a small class project to make a blackjack game. I realize that there are a billion how to's on this, but I'm trying to understand coding and build my own...that being said, I've messed up a lot. This conundrum is confusing to me though...while setting up my deck, I tried this:
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
decks = []
for suit in suits:
for rank in ranks:
decks += (rank, suit)
print decks
I get the expected outcome of the two lists ordering together:
['ace', 'spades', 'two', 'spades', 'three', 'spades', 'four'...]
However, when I try to combine them into a dictionary as follows:
b = dict(zip(decks[1::2], decks[0::2]))
print b
I get: {'hearts': 'King', 'clubs': 'King', 'spades': 'King', 'diamonds': 'King'} Why does it only do the King values?
When I tried to rectify with the following code:
spade = ['spades']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
spades = []
for rank in ranks:
spades += (rank, spade)
print spades
I got this as the output:
['ace', ['spades'], 'two', ['spades'], 'three', ['spades'],...]
So what gives? Help a noob out! My intention was to create a deck somewhat elegantly through lists, append values to the cards, create a dictonary and use the values to calculate scores...and trying to understand Python coding better!
Thanks!
A:
You can use a list comp to create a deck of cards like [[rank,suits]]. And dict() creates an object from only 2 values [value1,value2]. The reason you keep getting {'hearts': 'King', 'clubs': 'King', 'spades': 'King', 'diamonds': 'King'} is because a dict has unique {key:value} pairs and the last item to be assigned those keys is King in the ranks array.
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
print [(rank, suit) for suit in suits for rank in ranks]
solution
You can make the keys to the dick the ranks and the values an array of the (rank,suit) with the same rank
card_dict = {}
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
deck = [(rank, suit) for suit in suits for rank in ranks]
map(
lambda rank: card_dict.update(
{
rank: filter(lambda card: rank in card, deck)
}
), ranks
)
print card_dict
result
{
'King': [('King', 'spades'), ('King', 'hearts'), ('King', 'clubs'), ('King', 'diamonds')],
'seven': [('seven', 'spades'), ('seven', 'hearts'), ('seven', 'clubs'), ('seven', 'diamonds')],
'Queen': [('Queen', 'spades'), ('Queen', 'hearts'), ('Queen', 'clubs'), ('Queen', 'diamonds')],
'ace': [('ace', 'spades'), ('ace', 'hearts'), ('ace', 'clubs'), ('ace', 'diamonds')],
'ten': [('ten', 'spades'), ('ten', 'hearts'), ('ten', 'clubs'), ('ten', 'diamonds')],
'nine': [('nine', 'spades'), ('nine', 'hearts'), ('nine', 'clubs'), ('nine', 'diamonds')],
'six': [('six', 'spades'), ('six', 'hearts'), ('six', 'clubs'), ('six', 'diamonds')],
'two': [('two', 'spades'), ('two', 'hearts'), ('two', 'clubs'), ('two', 'diamonds')],
'three': [('three', 'spades'), ('three', 'hearts'), ('three', 'clubs'), ('three', 'diamonds')],
'four': [('four', 'spades'), ('four', 'hearts'), ('four', 'clubs'), ('four', 'diamonds')],
'five': [('five', 'spades'), ('five', 'hearts'), ('five', 'clubs'), ('five', 'diamonds')],
'Jack': [('Jack', 'spades'), ('Jack', 'hearts'), ('Jack', 'clubs'), ('Jack', 'diamonds')],
'eight': [('eight', 'spades'), ('eight', 'hearts'), ('eight', 'clubs'), ('eight', 'diamonds')]
}
or if you map by suits instead of ranks
{
'clubs': [('ace', 'clubs'),
('two', 'clubs'),
('three', 'clubs'),
('four', 'clubs'),
('five', 'clubs'),
('six', 'clubs'),
('seven', 'clubs'),
('eight', 'clubs'),
('nine', 'clubs'),
('ten', 'clubs'),
('Jack', 'clubs'),
('Queen', 'clubs'),
('King', 'clubs')
],
'diamonds': [('ace', 'diamonds'),
('two', 'diamonds'),
('three', 'diamonds'),
('four', 'diamonds'),
('five', 'diamonds'),
('six', 'diamonds'),
('seven', 'diamonds'),
('eight', 'diamonds'),
('nine', 'diamonds'),
('ten', 'diamonds'),
('Jack', 'diamonds'),
('Queen', 'diamonds'),
('King', 'diamonds')
],
'hearts': [('ace', 'hearts'),
('two', 'hearts'),
('three', 'hearts'),
('four', 'hearts'),
('five', 'hearts'),
('six', 'hearts'),
('seven', 'hearts'),
('eight', 'hearts'),
('nine', 'hearts'),
('ten', 'hearts'),
('Jack', 'hearts'),
('Queen', 'hearts'),
('King', 'hearts')
],
'spades': [('ace', 'spades'),
('two', 'spades'),
('three', 'spades'),
('four', 'spades'),
('five', 'spades'),
('six', 'spades'),
('seven', 'spades'),
('eight', 'spades'),
('nine', 'spades'),
('ten', 'spades'),
('Jack', 'spades'),
('Queen', 'spades'),
('King', 'spades')
]
}
shuffling
import random
random.shuffle(deck)
print deck
|
[
"stackoverflow",
"0046344250.txt"
] | Q:
Sql Server 2012 enterprise "sa" login failed. Error: 18456
SQL server 2012. Windows 10 Professional.
I enabled "sa" user account, and the authentication mode is set to "windows authentication and SQL server authentication". I set the password for "sa user account". but I cannot login into it. Error: 18456.
I can successfully login into windows authentication.
"sa" system administrator account status enabled.
I found many duplicate questions, but none solved the issue.
A:
You need to configure the authentication mode of your SQL-Instance to "mixed" (SQL Server and Windows Authentication Mode.).
If you just changed it you need to restart the SQL-Server service.
Here's the MS-documentation and here an SO-answer.
|
[
"stackoverflow",
"0034683214.txt"
] | Q:
Windows client for Bonobo git server
Is there a working client for Bonobo Git Server like Source Tree?
Anyone install and configure it?
A:
Github & Source Tree would do just fine. It is just a Git server just like any other.
|
[
"serverfault",
"0000164105.txt"
] | Q:
How to catchall email to a single user mailbox in postfix
I am new to postfix, i need to configure it so that any incoming email to my server will be delivered to a local user account(/etc/passwd). My server will not have any virtual domains($mydestination) listed anywhere, i just need to catchall unknown mails to local user account.
i have seen some topic related to this configuration using luser_relay and local_receipients_maps. but i don't now how to use them, if you have time, can you please tell me how to use that? I am using postfix on centos 5.5 server
Thanks in advance.
A:
If everything is setup ok.. you can add the following in your main.cf
luser_relay = username
local_recipient_maps =
More Info
Replace username with the recipient's user name or complete address, e.g. john or [email protected]
|
[
"stackoverflow",
"0018154315.txt"
] | Q:
Excel process not closing
I've got this C# program that never closes the Excel process. Basically it finds the number of instances a string appears in a range in Excel. I've tried all kinds of things, but it's not working. There is a Form that is calling this method, but that shouldn't change why the process isn't closing. I've looks at suggestions by Hans Passant, but none are working.
EDIT: I tried the things mentioned and it still won't close. Here's my updated code.
EDIT: Tried the whole Process.Kill() and it works, but it seems like a bit of a hack for something that should just work.
public class CompareHelper
{
// Define Variables
Excel.Application excelApp = null;
Excel.Workbooks wkbks = null;
Excel.Workbook wkbk = null;
Excel.Worksheet wksht = null;
Dictionary<String, int> map = new Dictionary<String, int>();
// Compare columns
public void GetCounts(string startrow, string endrow, string columnsin, System.Windows.Forms.TextBox results, string excelFile)
{
results.Text = "";
try
{
// Create an instance of Microsoft Excel and make it invisible
excelApp = new Excel.Application();
excelApp.Visible = false;
// open a Workbook and get the active Worksheet
wkbks = excelApp.Workbooks;
wkbk = wkbks.Open(excelFile, Type.Missing, true);
wksht = wkbk.ActiveSheet;
...
}
catch
{
throw;
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (wksht != null)
{
//wksht.Delete();
Marshal.FinalReleaseComObject(wksht);
wksht = null;
}
if (wkbks != null)
{
//wkbks.Close();
Marshal.FinalReleaseComObject(wkbks);
wkbks = null;
}
if (wkbk != null)
{
excelApp.DisplayAlerts = false;
wkbk.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wkbk);
wkbk = null;
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
/*
Process[] processes = Process.GetProcessesByName("EXCEL");
foreach (Process p in processes)
{
p.Kill();
}
*/
}
}
}
A:
Here is an interesting knowledge base on the subject of office apps staying open after a .NET app disconnects from them.
Office application does not quit after automation from Visual Studio .NET client
The code examples are all in the link (vb.net sorry). Basically it shows you how to correctly setup and tear down the office app so that it closes when you're finished with it.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject is where the magic happens.
EDIT: You need to call the FinalReleaseComObject for each excel object that you've created.
if (excelWorkSheet1 != null)
{
Marshal.FinalReleaseComObject(excelWorkSheet1);
excelWorkSheet1 = null;
}
if (excelWorkbook != null)
{
Marshal.FinalReleaseComObject(excelWorkbook);
excelWorkbook = null;
}
if (excelApp != null)
{
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
|
[
"gis.stackexchange",
"0000002901.txt"
] | Q:
assign unique id to point features
The MassGIS parcel standard (http://www.mass.gov/mgis/ParstndrdVer1_5_1.pdf) utilizes a concatenation of the whole number portion of x- and y-coordinates to create a unique id (LOC_ID) for features. I'm considering doing the same for a point feature class. I like the consistent methodology, but perhaps I'm overlooking something. Is there a standard or best practice for creating unique ids for point features?
A:
If you use that id for something like as a foreign key in relation to another table your whole database will get in big trouble if you have to move a point for some reason. Probably you then will have to keep the id even if it not describes the xy-coordinates any more.
As a unique key is often the best to have something not telling anything about the data, because most data might change.
/Nicklas
A:
Adding on from Nicklas answer and my comment.
I would say the most used convention and most recommended is just to use a auto-incrementing ID, eg start at 1 and just keep going. No logic and simple.
If you have a distributed system, or don't like auto-incrementing numbers, you could use a GUID. Most databases will handle creating this kind of ID for you. However they are a pain for a user to enter manually, for searching etc, so just keep that in mind.
The other option is to use some kind of hash of the data but I would not recommend this. It would mean that would you need to write an algorithm to do this for you, you can't always ensure uniqueness, they also tend to be a pain to enter for searching.
These are just my opinions, but from personal experience, trust me, never use business data in IDs.
A:
Follow up question: Is it best to create and maintain the unique id in the DBMS (SQL Server) or in the GIS software (ArcGIS)?
I'd strongly suggest checking for uniqueness inside the DBMS. That's one of the many strengths of DBMSs. It also allows you to access your data with different GIS software that probably wouldn't be aware of the unique constraints.
|
[
"stackoverflow",
"0055648867.txt"
] | Q:
How to pass a component as input to another component?
I'm using ngx-bootstraps modal component, and I want to dynamically pass its components to display. I'm not sure how to do this.
I'm using the following example, components as content:
https://ng-bootstrap.github.io/#/components/modal/examples
I can't pass it with @Input() since it's not an instance of a variable.
import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ActualContentComponent} from 'path/path/path';
//TODO: Fix hard important of a component
@Component({
selector: 'srd-modal',
templateUrl: './srd-modal.component.html',
styleUrls: ['./srd-modal.component.css']
})
export class SharedModalComponent implements OnInit {
constructor(private modalService: NgbModal) {}
open() {
const modalRef = this.modalService.open(ActualContentComponent);
modalRef.componentInstance.name = 'content';
}
ngOnInit() {
}
}
The above example works, however, I have a hard reference to the 'ActualContentComponent'. I'd prefer to avoid a giant switch to see what component to actually open (by passing in the name of the component).
EDIT:
I found out I can actually pass the component with @Input()
@Input()
public component;
constructor(private modalService: NgbModal) {}
open() {
const modalRef = this.modalService.open(this.component);
modalRef.componentInstance.name = this.buttonTitle;
}
I was under the assumption that this wouldn't be possible according to some search results. I was wondering what data-type I should use for component though.
EDIT 2: I guess Type according to https://angular.io/api/core/Type
A:
Maybe you can pass the component type in the open method ?:
open(component: Type) {
const modalRef = this.modalService.open(type);
modalRef.componentInstance.name = 'content';
}
|
[
"stackoverflow",
"0036067280.txt"
] | Q:
Rails - Paperclip dont save user avatar
I installed paperclip gem to manage users avatars in app but when I trying to change user default avatar it doesn't change. I don't getting any errors and the form is saved correctly. It seems to photo isn't uploaded.
What am I doing wrong? I'm newbie and I cant figure it out.
Model:
class User < ActiveRecord::Base
has_many :posts
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/avatar.gif"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
end
Controller:
class UsersController < ApplicationController
def create
@user = User.create( user_params )
end
def update
@user = User.find(params[:id])
@user.update_attribute(:avatar, params[:user][:avatar])
end
private
# Use strong_parameters for attribute whitelisting
# Be sure to update your create() and update() controller methods.
def user_params
params.require(:user).permit(:avatar)
end
end
Edit view:
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<form>
<div class="form-group">
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, class: "form-control" %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div class="field">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "off", class: "form-control" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off", class: "form-control" %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "off", class: "form-control" %>
</div>
<%= image_tag @user.avatar.url(:medium) %>
<%= form_for @user, url: users_path, html: { multipart: true } do |form| %>
<%= form.file_field :avatar %>
<% end %>
<br>
<div class="actions">
<%= f.submit "Update", class: "btn btn-success" %>
</div>
<% end %>
</div></form>
<p><%= button_to "Delete my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete, class: "btn btn-danger" %></p>
My routes:
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
categories GET /categories(.:format) categories#index
topics GET /topics(.:format) topics#index
POST /topics(.:format) topics#create
new_topic GET /topics/new(.:format) topics#new
edit_topic GET /topics/:id/edit(.:format) topics#edit
topic GET /topics/:id(.:format) topics#show
PATCH /topics/:id(.:format) topics#update
PUT /topics/:id(.:format) topics#update
DELETE /topics/:id(.:format) topics#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
root GET / categories#index
Record from DB:
User Load (1.7ms) SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation [#<User id: 3, email: "[email protected]", encrypted_password: "$2a$10$/oH53eNleU4rc87OSYVtsANt...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2016-03-17 11:10:39", last_sign_in_at: "2016-03-17 11:10:39", current_sign_in_ip: "::1", last_sign_in_ip: "::1", created_at: "2016-03-17 11:10:39", updated_at: "2016-03-17 11:10:39", avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil, avatar_updated_at: nil>]>
A:
Thank you for suggestions @max and @Kuba. Everything is working now. I just added following code to application_controller.rb:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit( :email, :password) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit( :email, :password, :current_password, :avatar) }
end
end
|
[
"stackoverflow",
"0054383127.txt"
] | Q:
CN1 I18n force a language
I'm getting english frases like "done" and "continue" in CN1's built in components.
How may I force those labels to change to spanish? I mean, even if the phone is in english.
Thanks!
A:
Check out this video: https://www.codenameone.com/how-do-i---localizetranslate-my-application-apply-i18nl10n-internationalizationlocalization-to-my-app.html
You would need to define a resource bundle that includes the Strings "Done" and "Continue" within it and map them to your language. Then install that bundle in the UIManager.
|
[
"stackoverflow",
"0027087894.txt"
] | Q:
iOS TestFlight build notification e-mails repeatedly not being received
We're building an iOS app in iOS 8 using Apple's version of TestFlight (integrated with iTunes Connect, of course). However, the system regularly refuses to send the "new build" notification e-mails to internal testers. In order to get build notification e-mails, I have to remove users from the internal testers group and re-invite them. Even when I have done this, the build notification e-mail (although it lists the desired version of the app) doesn't actually trigger an update in my TestFlight iOS app.
Points to note:
I have the Connect and TestFlight apps installed on my phone.
This has worked in the past with earlier versions of the app.
I have found other similar questions on Stack Overflow such as this and this one, but none of them seem to deal with the "this happens to me repeatedly" problem. Besides, most of them seem to suggest "remove all internal testers, disable beta testing on the app, then re-add them all" which is not a sustainable solution when we'd like to release multiple new builds per day through our continuous integration system.
Does anyone have any ideas?
ETA: I found an Apple Developer Forums thread on the subject. Not much help but it might be in future.
A:
I had the same issue, Making changes to the "What to Test" field in the Build page and saving caused notifications to go out instantly for me.
When you upload a new build wait for a bit (I wait an hour) for all the processing to finish, then add the What to Test info and hit save. This seems to work for me quite well.
|
[
"stackoverflow",
"0008472839.txt"
] | Q:
ASP.NET Telerik control styling with jQuery
I have a radTextBox with CssClass="mandatory".
In jQuery I have the next thing:
$(".mandatory").focusout( function () {
if($(this).val() == "") $(this).css("border", "1px solid #ff0000");
});
The problem is that on focusout, my style is "overwritten" by the classes that the control has by default on different events.
I've also tried in jQuery the next thing:
$(".mandatory").focusout( function () {
if($(this).val() == "") $(this).addClass("mandatoryErr");
});
But still nothing, the class is immediately removed after it was added.
So how can I add style to teleriks control using jQuery?
A:
The easiest way to accomplish this would be to hook into the various styling options you have on the client using the Client-side API of the RadTextBox. Here's a snippet that takes essentially your initial code and applies it to the RadTextBox API:
<script type="text/javascript">
function ChangeBorder () {
var textBox = $find("<%= RadTextBox1.ClientID %>");
if (textBox.get_value() == "") {
textBox.get_styles().EnabledStyle[0] += "border-color: #ff0000";
textBox.updateCssClass();
}
else {
//revert back to old CSS
}
}
</script>
<telerik:RadTextBox ID="RadTextBox1" runat="server" ClientEvents-OnBlur="ChangeBorder">
</telerik:RadTextBox>
The important items to get out of this is that we are subscribing to a client-side event of the RadTextBox (OnBlur). Then we access the RadTextBox client-side object, check if the value is "" or not and then access the styles of the RadTextBox object. There are several different styles, but it seems as if you're looking for the EnabledStyle. To directly apply some CSS just use the first element of the style array. Alternatively you can apply a CSSClass:
textBox.get_styles().EnabledStyle[1] += " mandatoryErr";
Where you will be accessing the second element in the styles array. Here you can have mandatoryErr be (for example):
<style>
.mandatoryErr
{
border-color: #ff0000 !important;
}
</style>
The !important tag is just there to increase the specificity of the CSS rule, otherwise it will not be applied (if you're using the built-in styles).
If you are looking for more information on all of this, the linked documentation articles should help. You can also use the Chrome Dev Tools and FireBug to inspect the textBox variable above and see what the _styles property holds :)
|
[
"stackoverflow",
"0028871951.txt"
] | Q:
can we develop native ios apps with responsive?
I want informatin about how to make native IOS app which should be responsive design?
If it is possible then how to make it. If it is not possible then how to make it possible with other way.
I have information about:
PhoneGap but i want to use native
swift framework.
In between 1) and 2) which one should best and perfcet way to make resposive design?
A:
To create responsive layout, you need to use autolayout / constraint.
Reference: http://blog.revivalx.com/2014/10/22/swift-autolayout-tutorial/
If you want to use native, you can integrate native functionality with hybrid application with develop a custom cordova plugin.
Reference: http://blog.revivalx.com/2014/03/11/ios-adding-native-functionality-to-hybrid-application-with-apache-cordova-plugin/
So far phonegap not support swift yet. It's support only for objective-c (iOS). If you want you need to create a bridging header to communicate between swift and objective-c.
Reference: http://blog.revivalx.com/2014/12/30/bridging-between-swift-and-objective-c-in-the-same-project/
Let me know for more clarification.
|
[
"stackoverflow",
"0029045567.txt"
] | Q:
The pagination issue of using Octopress with Github pages
I used Octopress to setup my blog with Github pages. Everything is OK. But I can't fix the pagination issues. Specifically, if I click the "older" link on my first blog page, it can't find the right page.
My Blog site is :
http://www.enlangtech.com/blog/
And the corresponding repository is : https://github.com/sherlocktowne/sherlocktowne.github.io
Could you help me to fix it! Thanks!
A:
Your not using the right variable for previous and next links.
It's <a href="{{paginator.next_page_path}}"> and <a href="{{paginator.previous_page_path}}">.
See Jekyll paginator documentation.
|
[
"stackoverflow",
"0015650455.txt"
] | Q:
Broken CSS - box with corner images
EDIT:
Used code from Tim and it worked!!!
The only question I have is how to make my header to be independent of the rest of the body and strech across the screen as in template image without any padding from the top and sides?
Here is the design template:
design template
Here is an updated code html + css:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rounded Corner Tutorial</title>
<style type="text/css">
body{padding: 10px; background-color: #e8e8e8; font-family: Arial, Helvetica, sans-serif; font-size:12px;}
h1{padding: 0px; margin: 0px;}
#container{
margin:0px auto;
border:0px solid #bbb;
padding:0px;
}
.white-box{width: 180px; margin: 0px;}
#main-header {
border:1px solid #bbb;
height:80px;
padding:10px;
background:#FFF
}
#main-content {
margin-top:10px;
padding-bottom:10px;
}
#main-body {
margin-left:10px;
width:666px;
height:150px;
}
#main-footer {
margin-top:10px;
margin-bottom:10px;
padding:10px;
border:1px solid #bbb;
}
.box {
padding: 8px;
border: 1px solid silver;
-moz-border-radius: 8px;
-o-border-radius: 8px;
-webkit-border-radius: 5px;
border-radius: 8px;
background-color: #fff;
}
.box1 {
width: 200px;
float: left;
}
.box2 {
margin-left: 224px;
}
</style>
</head>
<body>
<div id="container">
<div id="main-header">Main Header</div>
<div id="main-content">
<div class="box box1">
left
</div>
<div class="box box2">
<p>Main Bbody 1...</p>
</div>
</div>
<div id="main-footer">Main Footer</div>
</div>
</body>
</html>
A:
Use border-radius and ditch the images. It will make your life much easier and will look sharp on displays with high pixel density (unlike a GIF).
Demo: http://jsfiddle.net/QXqzd/1/
Browser Support: http://caniuse.com/#feat=border-radius
More examples: http://muddledramblings.com/table-of-css3-border-radius-compliance/
Important Part
.box {
padding: 8px;
border: 1px solid silver;
-moz-border-radius: 8px; /* older versions of FF */
border-radius: 8px; /* IE9+, Webkit, etc. */
background-color: #fff;
}
All CSS
I created a rough CSS stylesheet to match your template.
body {
background-color: #eee;
}
.box {
padding: 8px;
border: 1px solid silver;
-moz-border-radius: 8px;
border-radius: 8px;
background-color: #fff;
}
.box1 {
width: 200px;
float: left;
}
.box2 {
margin-left: 224px;
}
HTML
<div class="box box1">
left
</div>
<div class="box box2">
right
</div>
|
[
"stackoverflow",
"0017698952.txt"
] | Q:
Cannot install Ruby DevKit on Windows 8
Please help me, I am desperate.
I am encountering the following error when installing different gems:
Building native extensions. This could take a while...
ERROR: Error installing bson_ext:
ERROR: Failed to build gem native extension.
...
For this reason I want to install the Ruby DevKit. I am using the proper version (Ruby 1.9.3-p429 with DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe).
I followed the proper steps:
ruby dk.rb init
ruby dk.rb review => yes, C:\Ruby193 is appearing in config.yml
ruby dk.rb install => here comes my problem. When I execute the command (in an elevated cmd), I only get these two messages:
[INFO] Updating convenience notice gem override for 'C:/Ruby193'
[INFO] Installing 'C:/Ruby193/lib/ruby/site_ruby/devkit.rb'
After that I try to verify that the DevKit is installed correctly, so I run:
gem install json --platform=ruby
and I still get the same error as at the beginning (ERROR: Failed to build gem native extension.)
Please, help!
P.S. Some additional info: when I go to C:\Ruby193\bin gcc.bat, make.bat, and sh.bat are not present, which is probably at the root of my problem...
A:
change your system path to add devkit
|
[
"stackoverflow",
"0060272649.txt"
] | Q:
Is this the correct way to use ConfigureAwait(false)?
I am building a WPF application and calling this custom event.
The question here is should I call ConfigureAwait(false) at everywhere? As you can see now that I am calling it 2 times. Or even 3 times in second approach with double ConfigureAwait(false) in the same line.
// First approach
void RaiseProcessEvent(object sender, EventArgs e)
{
Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
}
// Second approach
void RaiseProcessEvent(object sender, EventArgs e)
{
Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
}
// This function is in a singleton class
public async Task ProcessMethod()
{
var result = await GetInstance.GetFinalResultFromHttpClientAsync().ConfigureAwait(false);
}
A:
The question here is should i call ConfigureAwait(false) at everywhere?
Generally speaking, ConfigureAwait(false) should be used if the method does not need to resume on its calling context. The decision of whether or not to use ConfigureAwait(false) should be made on a per-method basis, and should either be used for every await in that method, or it should not be used for every await in that method.
More pragmatically, ConfigureAwait(false) should be used in code that is intended for reuse, possibly in different contexts. Application code seldom needs to use ConfigureAwait(false), although there have been situations I've encountered where it was necessary to prevent having a bunch of continuations interrupting the UI thread.
as you can see now that i am calling 2 time. or even 3 times in second approach with double configure(false) in the same line.
In those cases, the ConfigureAwait(false) is meaningless. Here's why:
//first approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
ConfigureAwait configures an await. It does not configure a task. Since the task returned from Task.Run is never awaited, this ConfigureAwait does nothing.
//second approach
Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
The false part of ConfigureAwait(false) is for the continueOnCapturedContext parameter. So ConfigureAwait(false) is saying "this method does not need to continue on the captured context". But in this case, the async delegate is being run on the thread pool (that's what Task.Run does), so you know that there's no context to capture anyway.
Side note 1: When using Task.Run to call an asynchronous method, it's common to elide the async and await keywords. E.g.: Task.Run(() => APIManager.GetInstance.ProcessMethod());. So the ConfigureAwait(false) question becomes moot anyway because there's no await anymore.
Side note 2: Discarding the task returned from Task.Run means that the code is doing fire-and-forget, which is almost always a terrible mistake. Among other things, this means that any exceptions are silently swallowed. It is almost always better to use await:
async void RaiseProcessEvent(object sender, EventArgs e)
{
await Task.Run(() => APIManager.GetInstance.ProcessMethod());
}
Now there's an await for the task returned from Task.Run, so it's appropriate to ask the question at this point: should this await be using ConfigureAwait(false)? Opinions can vary here, but I would say no, because this is clearly application-level code (a UI event handler), and most developers would assume code running an event handler would be on the UI thread (even if there was an await previously in that method). So for maximum maintainability I would not use a ConfigureAwait(false) in a UI event handler method, unless I had to add it for performance reasons.
|
[
"stackoverflow",
"0017721742.txt"
] | Q:
cant fetch data thru drop down value
i have a SELECT box in which value was populated from database, below is the code
<select name="ea_name" id="ea_name">
<option value="" selected="selected">Please Select...</option>
<?php
require 'include/DB_Open.php';
$sql = "SELECT ea_name FROM ea_error ORDER BY ea_name";
$myData = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($myData)){
echo "<option value=\"$ea_name\">" . $row['ea_name'] . "</option>";
}
include 'include/DB_Close.php';
?>
</select>
now i have a jquery so that when SELECT value changes it would pull up the data from db and populate it to a textarea
$("#ea_name").on("change", function() {
$.ajax({
url: "retrieve.php",
type: "POST",
data: {
ea_name: $(this).val()
},
success: function(data) {
$("#results").html(data);
}
});
});
});
});
here is my query now,
<?php
require 'include/DB_Open.php';
$ea_name = $_POST['ea_name'];
$sql="SELECT * FROM ea_error WHERE ea_name = '" . $ea_name . "'";
echo $sql;
$myData = mysql_query($sql) or die(mysql_error());
//to count if there are any results
$numrow = mysql_num_rows($myData) ;
if($numrow == 0)
{
echo "No results found.";
}
else
{
echo '<fieldset><legend><strong>Information</strong></legend>
<table width="619" border="0" align="center">
<tr><th scope="row">Error</th></tr>
<tr><th scope="row">Resolution</th></tr>
<tr><th scope="row">Contact/s</th></tr>';
while($info = mysql_fetch_array($myData))
{
echo "<form action='retrieve.php' method='post'>";
echo "<tr>";
echo "<td align='center'>" . "<textarea readonly=readonly name=error cols=75 rows=10> " . $info['error'] . "</textarea></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'>" . "<textarea readonly=readonly name=resolution cols=75 rows=10> " . $info['resolution'] . "</textarea></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'>" . "<textarea readonly=readonly name=contacts cols=75 rows=10> " . $info['contacts'] . "</textarea></td>";
echo "</tr>";
echo "</form>";
}
}
echo "</fieldset>";
include 'include/DB_Close.php';
?>
i've added echo $sql; so i can see the output and here is what im getting: SELECT * FROM ea_error WHERE ea_name = ''No results found.
i tried to view the source and im seeing this:
Notice: Undefined variable: ea_name in C:\xampp\htdocs\XXX\view_transactions.php on line 75
Switches
line 75 refers to this echo "<option value=\"$ea_name\">" . $row['ea_name'] . "</option>";
i need help in understanding and fixing this error...im new to php coding...thanks
A:
$ea_name is not defined anywhere that dont have any value I think your looking for this one
echo "<option value=\"$row['ea_name']\">" . $row['ea_name'] . "</option>";
|
[
"avp.stackexchange",
"0000025241.txt"
] | Q:
How to stack three videos side by side with ffmpeg
I'd like to combine three videos into one vertically stacked video. The three videos have different width and height.
I can combine them horizontally successfully with this command:
ffmpeg -i s1.mp4 -i s2.mp4 -i temp.mp4 -filter_complex "[1:v][0:v]scale2ref=oh*mdar:ih[1v][0v];[2:v][0v]scale2ref=oh*mdar:ih[2v][0v];[0v][1v][2v]hstack=3,scale='2*trunc(iw/2)':'2*trunc(ih/2)';[0:a:0][1:a:0][2:a:0] amix=inputs=3:duration=first:dropout_transition=0,dynaudnorm" final.mp4
How can I modify this command to stack them vertically?
A:
For vertical stacking, the widths have to be equalized.
[1:v][0:v]scale2ref=iw:ow/mdar[1v][0v];[2:v][0v]scale2ref=iw:ow/mdar[2v][0v];[0v][1v][2v]vstack=3
|
[
"stackoverflow",
"0036744907.txt"
] | Q:
Can I change the design of the textarea resize handle in CSS?
Normally, the textarea can be resized both ways by dragging a little triangular handle in the bottom right corner. Once I disable horizontal resizing by setting textarea { resize: vertical; }, the textarea can only be resized up or down while dragging the same little triangle-shaped handle. But it doesn't seem very intuitive as the trianglular handle suggests that I should be able to resize the textarea along both axes.
I noticed that StackOverflow has a modified resize handle on this very textarea I am typing my question into. It intuitively implies only vertical resizing and it looks cute. If you click Ask Question, you will see it at the bottom of the textarea box. My guess is it is modified using jQuery. But can the looks of the resize handle be changed using simple CSS?
A:
Actually, the HTML part for SO answer textarea is:
<div class="wmd-container">
<div class="wmd-button-bar" id="wmd-button-bar"> .... </div>
<textarea data-min-length="" tabindex="101" rows="15" cols="92" name="post-text" class="wmd-input processed" id="wmd-input"></textarea>
<div class="grippie" style="margin-right: 0px;"></div>
</div>
The div .grippie is just a SVG image with an handler set to listen on your click&drag action, using the cursor offset in height to set the height of the textarea dinamically.
Check this if you want to know more about it
|
[
"stackoverflow",
"0060358250.txt"
] | Q:
A function that reverses a string using a loop
def main():
print(reverseString("Hello"))
def reverseString(string):
newString=""
for i in range(len(string)-1,-1):
newString+=string[i]
print newString
main()
I tried running this code but nothing is printed and I don't know what the problem is.
A:
This is missing the step of -1 in the range():
for i in range(len(string)-1, -1, -1):
Without the step the for loop immediately exits, leaving newstring as ''.
BTW: you are not returning anything from reverseString() so:
print(reverseString("Hello"))
Will print None, which I assume is not wanted. You probably want to:
return newString
in reverseString().
|
[
"webapps.stackexchange",
"0000018659.txt"
] | Q:
Any plugin to control GMail message editor with keyboard?
I want to use GMail's various rich-text capabilities with the keyboard. For example, I want to type Ctrl + M to indent, Ctrl + Shift + M to dedent, and do all the other actions (like adding a link or changing font) without touching the mouse.
Is that possible? Is there some Chrome extension that does this?
A:
No plugins needed now.
Ctrl+[ = Indent More
Ctrl+] = Indent Less
|
[
"stackoverflow",
"0051823603.txt"
] | Q:
using odata in react-native
I'm trying to use an odata library in a little react-native test app but the list doesn't fill when the data returns.
const CONST_REST_WS_HOST = "DELETED";
const CONST_REST_WS_URL = "http:" + "//" + CONST_REST_WS_HOST + "/odata/";
var o = require('odata');
class Feed extends Component {
[EDIT - Added in setup of initial state
constructor(props) {
super(props);
this.state = { products: null };
}
[EDIT - Added in part loading the data]
componentWillMount() {
this.oProductHandler = o(CONST_REST_WS_URL + 'Products');
this.oProductHandler.take(20).get(function (data) {
this.setState({ products: data });
}.bind(this));
}
render() {
return (
<ScrollView>
<List>
<ListItem key="1" title="Sample Item" /> // THIS APPEARS IN LIST
{
this.state && this.state.products && this.state.products.map((item) => {
console.log(item.ItemCode); // THIS STUFF APPEARS
<ListItem
key={item.ProductId} // I DON'T SEE THESE THINGS
title={item.ItemCode}
/>
})
}
</List>
</ScrollView>
);
}
}
EDIT - added in parts of package.json
"odata": "^0.4.0",
"odata-query": "5.0.0",
"react": "16.3.1",
"react-dom": "16.3.0",
"react-native": "0.55.4",
"react-native-elements": "^0.18.5",
In the view I see the List and I see the first list item "Sample Item". I also see the items in the console.
The data service is working, I built it myself and it's working in other projects. It's working in this project as well since I can see the item codes in the console. So with the item.ItemCode showing up in the console, why don't they show up in the list? Does the reaction to the state change run in a different context? I've been looking around for a couple of days and they all appear to follow this pattern.. fill in the data, setState, render gets re-run and component gets filled. All that seems to be working or the log would be empty. So what gives here?
EDIT added more code and these details
I added in more items requested in comments and the package info just in case versions are playing a part. This code is now the whole class, that's all there is to it. I've also tried putting the ScrollView and the List inside a conditional if (this.state && this.state.products) { so that the list and the list items are in the same
Mike
A:
I think you just need to add return in the map closure :
{
this.state && this.state.products && this.state.products.map((item) => {
console.log(item.ItemCode); // THIS STUFF APPEARS
return (<ListItem
key={item.ProductId} // I DON'T SEE THESE THINGS
title={item.ItemCode}
/>);
})
}
|
[
"stackoverflow",
"0028834284.txt"
] | Q:
Creating update trigger in SQL Server
I need to delete rows from Table A with row ids same as those rowId's which were updated in Table B. so, I am assuming I need to create an after update trigger.
For example: if time column in rows with row ID 1, 2, 3 was updated of Table B, then Table A should delete rows with row ID 1, 2 and 3.
This is what I have tried:
CREATE TRIGGER trgAfterUpdate ON [dbo].[Patients]
FOR UPDATE
AS
DECLARE @row INT
SELECT @row = (SELECT RowId FROM Inserted)
IF UPDATE (ModifiedAt)
DELETE FROM dbo.CACHE
WHERE Cache.RowId = @row
GO
However, if there was a batch update, trigger would be fired only once. How do I delete all rows from dbo.Cache with rowid same as those updated in dbo.Patients ?
A:
inserted is a table that contains all the updates; you can just use it as such.
CREATE TRIGGER trgAfterUpdate ON [dbo].[Patients]
FOR UPDATE
AS BEGIN
SET NOCOUNT ON;
IF TRIGGER_NESTLEVEL() > 1 RETURN;
IF UPDATE([ModifiedAt])
DELETE dbo.Cache WHERE RowID IN (SELECT RowID FROM inserted)
END
Note that I'm using SET NOCOUNT ON to ensure the trigger doesn't return any extra result and a TRIGGER_NESTLEVEL() check to prevent problems with recursion (not a problem for a single trigger, but a good idea in general).
|
[
"stackoverflow",
"0042866916.txt"
] | Q:
How to search for a word or phrase in SQL Server 2014 Tables?
I have multiple tables (say TableA, TableB, TableC) which have columns to store values in 6 languages. There are thousands of rows in each of these tables in SQL Server 2014.
What is the best way to search for a word or phrase or search string in these three tables (the search string can be found in any column of these tables) ?
Do I create separate views for each language for each of these tables (6 x 3 = 18 views) and then create full-text index on the views ?
I also need to get the table name and column name in which the search string is found in the tables as I need to pass the table name and column name to other stored procedure for further processing.
Create TableA (
AID int,
LanguageID int,
ACol1 nvarchar(100),
ACol2 nvarchar(100));
Create TableB (
BID int,
LanguageID int,
BCol1 nvarchar(100),
BCol2 nvarchar(100),
BCol3 nvarchar(100));
Create TableC (
CID int,
LanguageID int,
CCol1 nvarchar(100),
CCol2 nvarchar(100),
CCol3 nvarchar(100),
CCol4 nvarchar(100));
A:
I used the below link as a basis for this requirement.
https://social.technet.microsoft.com/wiki/contents/articles/24169.sql-server-searching-all-columns-in-a-table-for-a-string.aspx
|
[
"stackoverflow",
"0030444586.txt"
] | Q:
Crypt function outputting two different values depending on PHP version
Using the password "testtest" and the hash "KFtIFW1vulG5nUH3a0Mv" with the following code results in different hashes depending on the PHP version (as shown in the image below):
$salt = "KFtIFW1vulG5nUH3a0Mv";
$password = "testtest";
$key = '$2a$07$';
$key = $key.$salt."$";
echo crypt($password, $key);
Output 1 (PHP v.5.3.0 - 5.4.41, 5.5.21 - 5.5.25, 5.6.5 - 5.6.9): $2a$07$KFtIFW1vulG5nUH3a0Mv$.0imhrNa/laTsN0Ioj5m357/a8AxxF2q
Output 2 (PHP v.5.5.0 - 5.5.20, 5.6.0 - 5.6.4): $2a$07$KFtIFW1vulG5nUH3a0Mv$e0imhrNa/laTsN0Ioj5m357/a8AxxF2q
Here is an example of the problem:
http://3v4l.org/dikci
This is a massive issue if crypt is being used to hash passwords for a login, as depending on PHP version the hash will be different. Anybody understand what this issue is from and how to deal with it?
A:
This is not so much an issue as you may think.
First you should note, that your code is not absolutely correct, BCrypt requires a 22 character salt, but you provided a 20 character salt. This means that the terminating '$' (which is not necessary btw) will be seen as part of the salt, as well as the first letter of your password. The $ is not a valid character for a BCrypt salt though.
Another thing to consider is that not all bits of character 22 are used, this is due to the encoding, ircmaxell gave a good explanation about this. So different salts can result in the same hash, you can see this well in this answer. How different implementations handle this last bits of the character 22 could theoretically change. As long as the crypt function can verify the password with both hashes there is no problem.
The generation of the salt with its pitfalls is one of the reasons, why the functions password_hash() and password_verify() where written, they make the password handling much easier.
|
[
"stackoverflow",
"0049902715.txt"
] | Q:
ion-cards aligned in horizontal order?
Is it possible to have the ion-cards aligned next to each other rather than in down to down fashion?
I want the cards in horizontal rather in vertical order.
A:
You wrap ion-card in ion-row>ion-col
<ion-row>
<ion-col col-4>
<ion-card>Hello1</ion-card>
</ion-col>
<ion-col col-4>
<ion-card>Hello2</ion-card>
</ion-col>
<ion-col col-4>
<ion-card>Hello3</ion-card>
</ion-col>
</ion-row>
|
[
"stackoverflow",
"0044886544.txt"
] | Q:
Cannot Read $_SESSION data for redirection
I want to read $_SESSION data on a page so that if it does not match with the data on that page, the page redirects to another page. However, the page gets redirected EVERY time, no matter what the $_SESSION data is. I tried to debug with var_dump($_SESSION), but everything came out to be right. Please Help!
My Page1.php:
<?php
$me=strtoupper($_POST[username]);
$_SESSION["user"]=$me; // var_dump shows this value is "ADAM"
?>
My Page2.php:
<?php
$me="ADAM";
if($_SESSION["user"]!=$me){
header("location: ../index.php");
die;
}
?>
A:
I don't see that you're using session_start() anywhere. You need to use that on each and every page that you want to use the $_SESSION global.
A:
I figured out that I was missing out on session_start() at the beginning of my scripts. Here are my codes now:
My Page1.php:
<?php
session_start();
$me=strtoupper($_POST[username]);
$_SESSION["user"]=$me; // var_dump shows this value is "ADAM"
?>
My Page2.php:
<?php
session_start();
$me="ADAM";
if($_SESSION["user"]!=$me){
header("location: ../index.php");
die;
}
?>
|
[
"stackoverflow",
"0015318271.txt"
] | Q:
Random barely randomming
I'm trying to make a program that switches the location of button1 whenever it gets pressed. For some odd reason, random isn't randomming so well. Button1 just keeps going along the same diagonal line that's slanted at -45 degrees.
public void button1_Click(object sender, EventArgs e)
{
int tempX, tempY;
Random but1X = new Random();
tempX = but1X.Next(10, 500);
Random but1Y = new Random();
tempY=but1Y.Next(60,490);
button1.Location = new Point(tempX, tempY);
}
I've heard that the reason for this is because I keep making a new instance of random whenever button1 gets pressed but when I've tried putting the random code in a method, I still get the same results. Any idea how I can get this button to actually move randomly, rather than just going up and down the slide?
A:
Try without instantiating it for every random value you want:
public void button2_Click(object sender, EventArgs e)
{
int tempX, tempY;
Random rnd = new Random();
tempX = rnd.Next(10, 500);
tempY = rnd.Next(60,490);
button1.Location = new Point(tempX, tempY);
}
I tested this with two buttons and it works well with random distribution.
|
[
"stackoverflow",
"0003618326.txt"
] | Q:
jQuery / Javascript - run AJAX request after X seconds
so I have this code:
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function(){
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
setTimeout('myajax()', 10000);
}
myajax();
});
I wanted the ajax() request above to run 10 seconds after the page was loaded, so I used setTimeout, but it doesn't work :(
the ajax thingy runs right after the page loads, not 10 secs after...
what am I doing wrong?
A:
$('input.myinput').each(function(){
var id = $(this).val();
var myajax = function() {
$.ajax({
url: ajax_url,
type: "GET",
data: ({
code: id
}),
beforeSend: function() { },
error: function(request){ },
success: function(data) { alert(data); }
});
//if you need to run again every 10 seconds
//setTimeout(myajax, 10000);
};
setTimeout(myajax, 10000);
});
|
[
"superuser",
"0001423727.txt"
] | Q:
Microsoft Word page numbering keeps resetting to 0 after section break
I have a Word document with two sections and page numbers throughout. The second section is not linked to the previous, since I have other footer elements which would misalign if they were linked. I have set the second section to continue page numbering from the previous section, but each time I save and reopen the document, the numbering in section 2 has reset to page 0.
Is this a bug or is there another setting I should know about?
A:
I had exactly this problem today. Page number kept restarting to 0 in a new section. It didn't matter if next section was linked or not to the previous. No solution from forums worked (even macro for not restarting numbering at section from this thread).
The solution that worked for me was accepting tracked changes just before, at and after the section and then setting page numbers to continue from previous section one more time. My section was probably inserted in track changes mode and Word couldn't handle it for some reason.
|
[
"stackoverflow",
"0006798327.txt"
] | Q:
Calculating the mean of values in tables using formulae [R]
I know commands like xtabs and table allow a user to do cross-tabulation
For example the following command generates a pivot table that shows the number of cars that have the same number of gears and cylinders.
> xtabs(~cyl+gear, data = mtcars)
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
>
We can extend the formula so it could show the sum of the horse power for the cars in each bin
> xtabs(hp~cyl+gear, data = mtcars)
gear
cyl 3 4 5
4 97 608 204
6 215 466 175
8 2330 0 599
>
I am now wondering, is it possible to calculate the mean of horse powers for cars in each bin? for example something like this xtabs(mean(hp)~cyl+gear, data = mtcars)
A:
You can do it in one line using cast from the reshape library
cast(mtcars, cyl ~ gear, value = 'hp', fun = mean)
A:
One interesting response that I received from r-help is as following:
> attach(mtcars)
> tapply(hp,list(cyl,gear),mean)
3 4 5
4 97.0000 76.0 102.0
6 107.5000 116.5 175.0
8 194.1667 NA 299.5
>
A:
(Moving my comment to a response, so I can better edit it.)
I'm not sure how to do it with xtabs (which I've never used before), but here are a couple of ways of doing it using the reshape and plyr packages.
> x = melt(mtcars, id = c("cyl", "gear"), measure = c("hp"))
> cast(x, cyl ~ gear, mean)
> x = ddply(mtcars, .(cyl, gear), summarise, hp = mean(hp))
> cast(x, cyl ~ gear)
|
[
"stackoverflow",
"0023810133.txt"
] | Q:
Node JS Nested Functions And Variable Scope
Is there a way to pass the variables down to a nested callback without passing them to each function along the way unnecessarily? The problem is that I need to call getValueFromTable1 to get one value of the database. Take that result and add another variable from the original list and send that to a getValueFromTable2 to get the second piece of information from the database, and then finally take that result2 with the userID from the top level function and use that to do a DB insert.
I know I could do a more complex DB query with joins and such so that I get all my information at once and then just call one function, but my "getValueFromTable1" and "getValueFromTable2" are generic functions that get a set of data from the database that I can reuse in more than one place hence why I am trying to do it this way.
The problem I get is that node JS doesn't have the itemList in scope when i call
itemList[i].item2
And I am not passing item2 into function2 because function2 does not need it for its own purpose and it would make it take a variable it doesn't need.
doDatabaseInsert(itemList, userID) {
for(var i=0; i < itemList.length; i++) {
getValueFromTable1(itemList[i].item1, function(results) {
getValueFromTable2(results, itemList[i].item2, function(results2) {
//Finally do stuff with all the information
//Do DB insert statement with userID, and results2 into table 3
}
}
}
}
A:
You can't do that with a regular for loop because you are referencing i from inside an asynchronous callback, where the value of i is already itemList.length because the for loop finished long ago.
Try this instead:
itemList.forEach(function(item) {
getValueFromTable1(item.item1, function(results) {
getValueFromTable2(results, item.item2, function(results2) {
//Finally do stuff with all the information
//Do DB insert statement with userID, and results2 into table 3
});
});
});
|
[
"stackoverflow",
"0056869374.txt"
] | Q:
Aliasing a command and using it in the same line of code
I was wondering if you could alias a command, and use it in the same line of code, see this example:
alias php=/opt/plesk/php/5.6/bin/php; php -v;
I want this to output PHP 5.6.
alias php=/opt/plesk/php/7.3/bin/php; php -v;
and I want this to output PHP 7.3. However, what I get is this:
php -v
# outputs 5.6
alias php=/opt/plesk/php/5.6/bin/php; php -v;
# outputs 5.6
alias php=/opt/plesk/php/7.3/bin/php; php -v;
# outputs 5.6
php -v
# outputs 7.3
I've tried the && operator but it has the same outcome.
I'm wanting to use this in a gitlab continuous integration script, which executes a script through ssh -t by passing a string. However I am calling several php functions and I dont want to paste the full php path every time:
ssh -v -tt $SSH_HOST_NAME "__my_php_commands_here__"
A:
I think the command line is being parsed, and aliases applied, before anything is executed. However, you can do it with shell functions. I don't have PHP, but I have several Perl versions to test with:
$ perl -v |grep version # V
This is perl 5, version 26, subversion 2 (v5.26.2) built for x86_64-cygwin-threads-multi
$ perl(){ /usr/bin/perl "$@" ; } ; perl -v |grep version
This is perl 5, version 26, subversion 3 (v5.26.3) built for x86_64-cygwin-threads-multi
# ^
So defining the pass-through function
perl(){ /usr/bin/perl "$@" ; }
changes how the word perl is interpreted later in the command line. Note that you do need the ; before } — see this answer.
For your use case, I would recommend using a different name to avoid confusion. E.g.:
currphp(){ /opt/plesk/php/5.6/bin/php "$@" ; } ; currphp -v
currphp(){ /opt/plesk/php/7.3/bin/php "$@" ; } ; currphp -v
|
[
"stackoverflow",
"0023975767.txt"
] | Q:
Creating dot-function for android calculator
Im doing a small project, gathering some random calculator codes from the net and improving them to learn java and android development...
So, Im currently trying to implement a dot-function for this calculator code, but it doesn't work as it's supposed to. Instead of adding a dot, it adds the value 46 (why 46??). Could you help me to create a functional dot-function?
Java code:
package com.example.Elof_Calculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public String str ="";
Character op = 'q';
double i,num,numtemp;
EditText showResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showResult = (EditText)findViewById(R.id.result_id);
}
public void btn1Clicked(View v){
insert(1);
}
public void btn2Clicked(View v){
insert(2);
}
public void btn3Clicked(View v){
insert(3);
}
public void btn4Clicked(View v){
insert(4);
}
public void btn5Clicked(View v){
insert(5);
}
public void btn6Clicked(View v){
insert(6);
}
public void btn7Clicked(View v){
insert(7);
}
public void btn8Clicked(View v){
insert(8);
}
public void btn9Clicked(View v){
insert(9);
}
public void btn0Clicked(View v){
insert(0);
}
public void btndotClicked(View v){
insert('.');
//error
}
public void btnplusClicked(View v){
perform();
op = '+';
}
public void btnminusClicked(View v){
perform();
op = '-';
}
public void btndivideClicked(View v){
perform();
op = '/';
}
public void btnmultiClicked(View v){
perform();
op = '*';
}
public void btnequalClicked(View v){
calculate();
}
public void btnclearClicked(View v){
reset();
}
private void reset() {
// TODO Auto-generated method stub
str ="";
op ='q';
num = 0;
numtemp = 0;
showResult.setText("");
}
private void insert(int j) {
// TODO Auto-generated method stub
str = str+Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str);
}
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num;
}
private void calculate() {
// TODO Auto-generated method stub
if(op == '+')
num = numtemp+num;
else if(op == '-')
num = numtemp-num;
else if(op == '/')
num = numtemp/num;
else if(op == '*')
num = numtemp*num;
showResult.setText(""+num);
}
}
XML code for the dot-button:
<Button
android:id="@+id/Btndot_id"
style="?android:attr/buttonStyleSmall"
android:layout_width="70dp"
android:layout_height="64dp"
android:background="@drawable/buttonstyle1"
android:gravity="center_vertical|center_horizontal"
android:text="."
android:textColor="@android:color/white"
android:textSize="22sp"
android:onClick="btndotClicked"
/>
Here is the java function and code for the dot-function specifically, which is the main error:
public void btndotClicked(View v){
insert('.');
}
So, how should the code for the dot-function be?
All help is appreciated :))
A:
The problem is that your insert function has the signature void insert(int j)
In Java an implicit widening conversion will take place, if you use a char primitive type when an int type is expected. So for example this is valid Java:
int dot = '.';
However, the value of the int variable dot will now be 46 which happens to be the integer that corresponds to the bit pattern that is used to represent '.'.
What you can do, is change your insert function to accept String parameters and add an overload for int parameters. You will also need to change your logic around num since you can now have floating point numbers.
private void insert(int value) {
insert(Integer.toString(value));
...
num = Double.parseDouble(str);
}
private void insert(String value) {
...
}
...
public void btndotClicked(View v){
insert("."); // inserting a String instead of a char
}
|
[
"stackoverflow",
"0042729164.txt"
] | Q:
Azure Stream Analytics: "Stream Analytics job has validation errors: The given key was not present in the dictionary."
I burned a couple of hours on a problem today and thought I would share.
I tried to start up a previously-working Azure Stream Analytics job and was greeted by a quick failure:
Failed to start Streaming Job 'shayward10ProcessLogs'.
I looked at the JSON log and found nothing helpful whatsoever. The only description of the problem was:
Stream Analytics job has validation errors: The given key was not present in the dictionary.
Given the error and some changes to our database, I tried the following to no effect:
Deleting and Recreating all Inputs
Deleting and Recreating all Outputs
Running tests against the data (coming from Event Hub) and the output looked good
My query looked as followed:
SELECT
dateTimeUtc,
context.tenantId AS tenantId,
context.userId AS userId,
context.deviceId AS deviceId,
changeType,
dataType,
changeStatus,
failureReason,
ipAddress,
UDF.JsonToString(details) AS details
INTO
[MyOutput]
FROM
[MyInput]
WHERE
logType = 'MyLogType';
Nothing made sense so I started deconstructing my query. I took it down to a single field and it succeeded. I went field by field, trying to figure out which field (if any) was the cause.
See my answer below.
A:
The answer was simple (yet frustrating). When I got to the final field, that's where the failure was:
UDF.JsonToString(details) AS details
This was the only field that used a user-defined function. After futsing around, I noticed that the Function Editor showed the title of the function as:
udf.JsonToString
It was a casing issue. I had UDF in UPPERCASE and Azure Stream Analytics expected it in lowercase. I changed my final field to:
udf.JsonToString(details) AS details
It worked.
The strange thing is, it was previously working. Microsoft may have made a change to Azure Stream Analytics to make it case-sensitive in a place where it seemingly wasn't before.
It makes sense, though. JavaScript is case-sensitive. Every JavaScript object is basically a dictionary of members. Consider the error:
Stream Analytics job has validation errors: The given key was not present in the dictionary.
The "udf" object had a dictionary member with my function in it. The UDF object would be undefined. Undefined doesn't have my function as a member.
I hope my 2-hour head-banging session helps someone else.
|
[
"photo.stackexchange",
"0000026165.txt"
] | Q:
For the same number of shots, does continuous shooting wear out a shutter or other mechanical parts faster than single shots?
Does continuous shooting subject a shutter or other mechanical parts to more wear and tear than single shooting, assuming the same number of shots are taken? In other words, does firing x shots at 4 fps or faster wear out said parts than firing x shots at 1 fps?
A:
I think the realistic answer is that without spending tens of thousands of your preferred currency to set up a proper test environment and test a whole bunch of different cameras there's no real way to know.
Presumably the manufacturers test each model of camera to get an idea of how long they will last under continuous use (although I imagine that only the high end manufacturers test properly) and that figure, after suitable massaging, is the one they release to the public.
Edit for pedantry: If a camera will take, for example, 100,000 exposures before breaking then if they are continuous at, again for example, 5 frames per second then the camera will break after approx five or so hours. If the same camera is used to take one shot a day then the camera will break many years later.
Thus, technically, a camera used continuously will break 'faster', i.e. before, one used intermittently regardless of any other factors...
|
[
"stackoverflow",
"0011422113.txt"
] | Q:
Show placeholder text in empty input fields
How it is possible that during onfocus (on input field) input default value seen like it is disabled but on input field could be written anything like default value isn't exists ?
here is simple html =>
<input type="text" id="x">
and javascript =>
document.getElementById("x").onfocus = function(){
this.style.opacity = 0.5;
}
but I couldn't do what I want.
A:
With "HTML5", new functionality and attributes have been introduced for form-Elements (such as built-in form-validation for example)
One of those is the placeholder - attribute. It shows a specified text on empty input-Fields that will be hidden, after a user starts to fill text in the field.
The HTML-Markup looks like this:
<input type="text" name="first_name" placeholder="Fill in your name">
This feature is not supported by all browsers yet (you can check compatibility on caniuse.com
In your code, you can check for compatibility with a simple function:
var placeHolderSupport = ('placeholder' in document.createElement('input'));
For older browsers, you would need to write a fallback JavaScript - Function, that reads this attribute and implement the behaviour yourselve. There are some blog-posts about this around the web, like one from David Walsh, that could help you with this.
edit:
I stumbled over this gist by Hagenburger (according blog-post), that should implement the behaviour you want to achieve for old browsers too. Note: it's jQuery - code, not sure if you are using it, but even if not, it should give you an idea, what to do.
So, given the compatibility - check from above:
if(!placeHolderSupport){
//gist code here (not sure if i'm allowed to copy this into my answer)
}
Like that, the native placeholder-implementation of the browser would be used, if it exists, otherwise, the JavaScript-function would take care of this.
update 09/11/2012
SO-User and Moderator ThiefMaster just pointed out a better and newer jQuery-plugin by Mathias Bynens, that already has built-in check for placeholder - support. Surely a better way to implement the placeholder-fallback than the gist I posted:
jQuery Placeholder at github
|
[
"serverfault",
"0000568473.txt"
] | Q:
How to find which server is sending files to my shared folder
I have a server where is shared folder e.g. shared_folder.
Another server in the same domain is sending files into this folder (it is probably a scheduled task)
unknown_server -> copy files -> my_server/shared_folder
How to find the unknown_server if I'm not sure when the replication runs (if I knew it, I could see the session in computer management)?
A:
If you open computer management (right click on 'my computer', choose manage) then expand Shared Folders, then sessions, you can see the sessions open on that server. It should show either the name or IP address of the connected system, and the username it is using to connect.
|
[
"serverfault",
"0000119840.txt"
] | Q:
Windows Server 2008: specifying the default IP address when NIC has multiple addresses
I have a Windows Server which has ~10 IP addresses statically bound. The problem is I don't know how to specify the default IP address.
Sometimes when I assign a new address to the NIC, the default IP address changes with the last IP entered in the advanced IP configuration on the NIC. This has the effect (since I use NAT) that the outgoing public IP changes too.
Even though this problem is currently on Windows Server 2008.
How can you set the default IP address on a NIC when it has multiple IP addresses bound?
There is more explication on my problem.
alt text http://www.nmediasolutions.com/_images/probleme/ip.png
Here is the output of ipconfig:
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
IPv4 Address. . . . . . . . . . . : 192.168.99.49(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.51(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.52(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.53(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.54(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.55(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.56(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.57(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.58(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.59(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.60(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.61(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.62(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.64(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.65(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.66(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.67(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.68(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.70(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.71(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.100(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.108(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.109(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.112(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
IPv4 Address. . . . . . . . . . . : 192.168.99.63(Duplicate)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.99.1
If I do a pathping there is the answer, the first up is the 99.49, also if my default IP address is 99.100
Tracing route to www.l.google.com [72.14.204.99]
over a maximum of 30 hops:
0 Machine [192.168.99.49]
There is the routing table on the machine:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 192.168.99.1 192.168.99.49 261
10.10.10.0 255.255.255.0 On-link 10.10.10.10 261
10.10.10.10 255.255.255.255 On-link 10.10.10.10 261
10.10.10.255 255.255.255.255 On-link 10.10.10.10 261
192.168.99.0 255.255.255.0 On-link 192.168.99.49 261
192.168.99.49 255.255.255.255 On-link 192.168.99.49 261
192.168.99.51 255.255.255.255 On-link 192.168.99.49 261
192.168.99.52 255.255.255.255 On-link 192.168.99.49 261
192.168.99.53 255.255.255.255 On-link 192.168.99.49 261
192.168.99.54 255.255.255.255 On-link 192.168.99.49 261
192.168.99.55 255.255.255.255 On-link 192.168.99.49 261
192.168.99.56 255.255.255.255 On-link 192.168.99.49 261
192.168.99.57 255.255.255.255 On-link 192.168.99.49 261
192.168.99.58 255.255.255.255 On-link 192.168.99.49 261
192.168.99.59 255.255.255.255 On-link 192.168.99.49 261
192.168.99.60 255.255.255.255 On-link 192.168.99.49 261
192.168.99.61 255.255.255.255 On-link 192.168.99.49 261
192.168.99.62 255.255.255.255 On-link 192.168.99.49 261
192.168.99.64 255.255.255.255 On-link 192.168.99.49 261
192.168.99.65 255.255.255.255 On-link 192.168.99.49 261
192.168.99.66 255.255.255.255 On-link 192.168.99.49 261
192.168.99.67 255.255.255.255 On-link 192.168.99.49 261
192.168.99.68 255.255.255.255 On-link 192.168.99.49 261
192.168.99.70 255.255.255.255 On-link 192.168.99.49 261
192.168.99.71 255.255.255.255 On-link 192.168.99.49 261
192.168.99.100 255.255.255.255 On-link 192.168.99.49 261
192.168.99.108 255.255.255.255 On-link 192.168.99.49 261
192.168.99.109 255.255.255.255 On-link 192.168.99.49 261
192.168.99.112 255.255.255.255 On-link 192.168.99.49 261
192.168.99.255 255.255.255.255 On-link 192.168.99.49 261
224.0.0.0 240.0.0.0 On-link 192.168.99.49 261
224.0.0.0 240.0.0.0 On-link 10.10.10.10 261
255.255.255.255 255.255.255.255 On-link 192.168.99.49 261
255.255.255.255 255.255.255.255 On-link 10.10.10.10 261
I think my route should look like:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 192.168.99.1 **192.168.99.100** 261
10.10.10.0 255.255.255.0 On-link 10.10.10.10 261
10.10.10.10 255.255.255.255 On-link 10.10.10.10 261
10.10.10.255 255.255.255.255 On-link 10.10.10.10 261
192.168.99.0 255.255.255.0 On-link 192.168.99.100 261
192.168.99.49 255.255.255.255 On-link 192.168.99.100 261
192.168.99.51 255.255.255.255 On-link 192.168.99.100 261
192.168.99.52 255.255.255.255 On-link 192.168.99.100 261
192.168.99.53 255.255.255.255 On-link 192.168.99.100 261
192.168.99.54 255.255.255.255 On-link 192.168.99.100 261
192.168.99.55 255.255.255.255 On-link 192.168.99.100 261
192.168.99.56 255.255.255.255 On-link 192.168.99.100 261
192.168.99.57 255.255.255.255 On-link 192.168.99.100 261
192.168.99.58 255.255.255.255 On-link 192.168.99.100 261
192.168.99.59 255.255.255.255 On-link 192.168.99.100 261
192.168.99.60 255.255.255.255 On-link 192.168.99.100 261
192.168.99.61 255.255.255.255 On-link 192.168.99.100 261
192.168.99.62 255.255.255.255 On-link 192.168.99.100 261
192.168.99.64 255.255.255.255 On-link 192.168.99.100 261
192.168.99.65 255.255.255.255 On-link 192.168.99.100 261
192.168.99.66 255.255.255.255 On-link 192.168.99.100 261
192.168.99.67 255.255.255.255 On-link 192.168.99.100 261
192.168.99.68 255.255.255.255 On-link 192.168.99.100 261
192.168.99.70 255.255.255.255 On-link 192.168.99.100 261
192.168.99.71 255.255.255.255 On-link 192.168.99.100 261
192.168.99.100 255.255.255.255 On-link 192.168.99.100 261
192.168.99.108 255.255.255.255 On-link 192.168.99.100 261
192.168.99.109 255.255.255.255 On-link 192.168.99.100 261
192.168.99.112 255.255.255.255 On-link 192.168.99.100 261
192.168.99.255 255.255.255.255 On-link 192.168.99.100 261
224.0.0.0 240.0.0.0 On-link 192.168.99.100 261
224.0.0.0 240.0.0.0 On-link 10.10.10.10 261
255.255.255.255 255.255.255.255 On-link 192.168.99.100 261
255.255.255.255 255.255.255.255 On-link 10.10.10.10 261
How can I be sure the IP address used in the image (supposed to be the default IP address) will be use by my server as the default address?
A:
With Server 2008 Service Pack 2 (not R2), or Vista SP2 and MS hotfix KB975808 there is a solution, although a bit clumsy. You would remove all the addresses you DON'T want as a source, then re-add each one at the command line using
Netsh int ipv4 add address <Interface Name> <ip address> skipassource=true
The hotfix enables the "Skip As Source" flag.
For a deeper dive on how different Windows versions select source IPs, see this TechNet blog post.
A:
There isn't such as thing as a "Default IP" for a network interface; rather your systems routing table defines which logical interface should be used when communicating with other devices.
It sounds like what you'd like to do is configure a default route. This would cause all conversations initiated by this machine to be made from a specific IP.
Use route add to add a default gateway
|
[
"stackoverflow",
"0004662193.txt"
] | Q:
How to convert from System.Drawing.Color to System.Windows.Media.Color?
How can I convert between these two color types?
A:
You can see examples of both of the conversion directions below:
Drawing.Color to Windows.Media.Color
// This is your color to convert from
System.Drawing.Color color;
System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B);
Windows.Media.Color to Drawing.Color
// This is your color to convert from
System.Windows.Media.Color color;
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
A:
For frequent use i suggest helper like this:
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
namespace ColorHelper
{
public static class ColorExt
{
public static SWMColor ToSWMColor(this SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
public static SDColor ToSDColor(this SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
}
}
A:
... or use @Rion Williams answer as an extension:
public static System.Windows.Media.Brush ToBrush(this System.Drawing.Color color)
{
return new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B));
}
|
[
"stackoverflow",
"0056321542.txt"
] | Q:
plsql works in Sql Developer, but not in a liquibase change ORA-06550 PLS-00103
I have the following code that has no issue running in SQL Developer, but when I put inside a liquibase change and run it I get an error.
DECLARE
seqval NUMBER;
BEGIN
SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
END;
and the changeset for it:
<changeSet author="Cristian Marian (cmarian)" id="2019-05-24-171101 Fix Items sequence - creting">
<sql>
DECLARE
seqval NUMBER;
BEGIN
SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
END;
</sql>
</changeSet>
The error looks like this:
Reason: liquibase.exception.DatabaseException: ORA-06550: line 2, column 27:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
:= . ( @ % ; not null range default character
[Failed SQL: DECLARE
seqval NUMBER] (Liquibase Update failed.)
A:
Liquibase will try to split up the "script" inside the <sql> tag by the default statement delimiter which is ;. For a PL/SQL block this is obviously wrong, as the whole block needs to be treated as single statement.
To achieve that, use splitStatements attribute in the <sql> tag:
<sql splitStatements="false">
DECLARE
....
END;
</sql>
|
[
"stackoverflow",
"0017239095.txt"
] | Q:
Writing non-indentation sensitive code in Python
(I am a beginner) Python normally uses indentation to specify the nesting level of code lines. Is there any other way to do this?
A:
No, the Python developers are very resistant to this, as it would mean changing one of the core foundations on which Python was based. Just try from __future__ import braces.
>>> from __future__ import braces
SyntaxError: not a chance (<pyshell#30>, line 1)
Indeed, "not a chance" :-)
|
[
"stackoverflow",
"0007588274.txt"
] | Q:
Convention For Gem with Common Name
I recently authored a gem called 'setting' (found here). The extends ActiveRecord with a module named 'Setting'. I understand that gems are supposed to use the namespace they are named, however when testing this caused collisions with ActiveRecord models with the same name (a Setting model). Does a standard exist for creating a private module namespace? I don't need users of the gem to ever access the module outside the extension in ActiveRecord. Do I have any options outside of picking a less common name?
A:
Since you're writing an Active Record extension, you could place your module inside the ActiveRecord namespace:
module ActiveRecord
module Setting
end
end
Other than that, no, there's no practical namespace solution for gems with very common names.
|
[
"stackoverflow",
"0049564030.txt"
] | Q:
Kotlin Pass Object Class as Parameter Initialize
I need to pass as parameter SQLiteDatabase class/object to let execSQL act. In SQL_User , is included with extended SQLiteOpenHelper.... But how I initialize that on DatabaseActivity
I think I don't understand at all what's the way to go with this...
class DatabaseActivity : Activity {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Sql_User(this, "Users", null, 1)
// Here I get an error on ??, anything I think could works doesn'ts
if (db != null) { Sql_User.insert( «??» , "1", "DefaultUser") }
}
}
class Sql_User : SQLiteOpenHelper {
companion object {
fun insert(p0: SQLiteDatabase?, p1: String, p2: String){ p0!!.execSQL("INSERT INTO Users ( id_user, username ) VALUES ('${p1}, '${p2}')")
}
...
}
The error I get on that line, any parameter I pass is ... Classifier SQLiteDatabase does not have a companion object, and thus must be initialized here
A:
Your db variable is of type SQLOpenHelper not SQLiteDatabase. To get a database from the helper, you need to call the getWritableDatabase method (or writeableDatabase property in kotlin) to get a database.
So for you, something like --
Sql_User.insert(db.writeableDatabase , "1", "DefaultUser")
|
[
"math.stackexchange",
"0002100082.txt"
] | Q:
Lemma of Gronwall
Let $T \in \mathbb R^+\cup \{\infty\}$, $t_o \in [0,T)$, $a,b \in L^\infty(t_0,T)$ and $\lambda \in L^1(T_0,t)$, $\lambda(t) \geq 0$ for almost all $t \in (t_o,T)$. From the inequality $$a(t) \leq b(t) + \int_{t_0}^t\lambda(s)a(s)ds \,\,\,\,\,$$ a.e. in $(t_o,T)$ it follows $$a(t) \leq b(t) + \int_{t_0}^t e^{\phi(t)-\phi(s)}\lambda(s)b(s) \,ds$$ for almost all $t\in (t_0,T)$ where $\phi(s):=\int_{t_o}^s \lambda(\tau)\,d\tau$.
Is there a counterexample for the case that $\lambda$ is negative? And what changes about the implication if $t<t_o$?
A:
Here's a simple example of what happens when $\lambda$ is not non-negative.
Take $t_0 =0$, $T=\infty$, and $b(t) =1$ and $\lambda(t) =-1$ for all $t \ge 0$. Further assume we have the equality
$$
a(t) = b(t) + \int_0^t \lambda(s) a(s) ds = 1 - \int_0^t a(s) ds
$$
for $t \ge 0$. Write $F(t) = \int_0^t a(s) ds$. Then the equality reads
$$
F'(t) = 1 - F(t) \Rightarrow (e^t F(t))' = e^t \Rightarrow F(t) = 1- e^{-t}.
$$
Plugging back in shows that $a(t) = e^{-t}$.
Now let's consider the RHS of the Gronwall inequality. We compute
$$
b(t) + \int_0^t e^{\phi(t)-\phi(s)} \lambda(s) b(s) ds = 1 - e^t \int_0^t e^{-s} ds = 2 - e^{t}.
$$
The inequality then holds if and only if
$$
e^{-t} = a(t) \le b(t) + \int_0^t e^{\phi(t)-\phi(s)} \lambda(s) b(s) ds = 2- e^{t}
$$
for all $t \ge 0$, which is equivalent to
$$
\cosh(t) \le 1 \text{ for all }t \ge 0,
$$
a contradiction.
For your second question I can't really give a good answer, as it's not clear to me what you want to assume. Are we supposed to assume that the first inequality also holds for $t < t_0$? If not, then we have no information about $a$ before $t_0$, so how could we say anything about the function?
|
[
"meta.superuser",
"0000013338.txt"
] | Q:
Is there a way to contact person who commented on my topic
I have a question about my Super User post: How to create inbound rule which only accept Local Lan in win7 firewall
One guy has commented on my topic to want me to clarify something, and I checked what he asked and gave my detail information,but when I tried to recomment and even @ this guy, maybe he just forgot my topic, no reply anymore, I was eager to get answer for this topic, so Is there a way to contact the person who commented my topic and get answer from him if he can give answer to my topic?
A:
If user doesn't choose to disclose contact details in his or her profile, there's no built-in way in the Stack Exchange platform to contact them other than using an @ comment on that post.
|
[
"electronics.meta.stackexchange",
"0000002462.txt"
] | Q:
Notification of new replies and contacting users via mail
When I reply to someone on here and he is not immediately watching the page, I don't get an reply at all.
Even though I put my email in here I don't get any notifications about replies and so don't other members.
Also I cannot contact other members there's no "contact me" link.
So I want
Notification via email as a standard if a comment or reply was made
A contact-me link on every user's page to contact him via mail or private message.
A:
By default, the StackExchange sends users very little email. You can change the settings by clicking on the StackExchange menu on the top left of the screen, and selecting "email settings" at the bottom of the box that pops up. This should email you any time something pops up in your StackExchange inbox. By default, if something is in your inbox, a red dot appears over the StackExchange logo on the top left.
Here are a few ways that something can end up in your inbox:
Someone posts an answer to your question
Someone posts a comment on a question or answer you own
Someone mentions you using the @user tag in a comment thread where you posted a comment
Someone mentions you using the @user tag in chat
One of the reasons StackExchange does not promote private communication is that it potentially hides information needed to solve questions (or prevents answers from being written). Another major reason is that it turns SPAM into a public problem that the community can monitor and address.
A:
I really wouldn't want to give other users the ability to send me email without my consent. When you answer a bunch of questions on a email list, forum, or here, too many people think they have the right to use you as their private unpaid consultant. I get enough emails as it is where people have dug out my address. I don't want it to be even easier.
There is no reason these messages need to be private. I just delete them without reply because I don't want to engage in a private dialog. Too many people can't seem to understand that there is absolutely no upside for people to privately help someone without getting paid.
In case you think I'm just making this up, here is a recent typical such message:
Dear Olin,
I saw that you have programmed bootloaders that can be upgraded
remotely via internet.
I am currently using Microchip's USB HID bootloader for PIC32MX
series of microcontrollers.
The bootloader works okay with the PIC32UBL.exe program provided, but
I would like to do away with the user having to install a program,
and simply have the device update via a web page using javascript or
some widely browser supported language. This would be for code
updates and also for programming user changeable parameters. I would
guess someone has done something like this.
A few questions:
1) Is this possible?
2) What would you suggest as the simplest method?
3) Can this be done without implementing a TCPIP stack (i.e. via a
browser rather than through a dedicated IP address)?
4) If this is possible, and you have done it or parts of it, do you
have any code that you would be willing to share, or can you at least
point me in the right direction?
Thanks!
TC
This came from "[email protected]". Note the complete lack of any reason this shouldn't have been posted to the appropriate forum or whatever. This guy doesn't even identify himself, and seems to want free help, but for me to do it privately just for him.
The above is quite typical, and probably happens a couple of times a month now. If you let the unwashed masses send private messages to any other user, it would happen much more often and get really annoying.
|
[
"stackoverflow",
"0038711953.txt"
] | Q:
Return null to avoid unknown exceptions from a method in C#
I have the following method that opens a Excel workbook and returns it to be used in another method.
private Excel.Workbook openWorkbook()
{
// Get excel file path returns the file path of the excel workbook if it exists, otherwise returns null.
List<string> filePaths = getExcelFilePath();
if (filePaths != null)
{
return excel.Workbooks.Open(filePaths[0]);
}
return null;
}
As you can see, I'm returning null to avoid a try-catch for a non-exixtent workbook when I call this from another method. Is it bad practice to do this. I do a similar thing in the following method which is supposed to return a list:
private List<string> getSOsToDelete()
{
// rawData is private variable in the class. If the workbook was not open this worksheet is set to null in another method similar to openWorkbook() above.
if (rawData != null)
{
List<string> ToDeleteSOs = new List<string>();
for (int i = rawData.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row; i > 1; i--)
{
if (rawData.Cells[i, 7].Value2.ToString() != "B2B" || rawData.Cells[i, 7].Value2.ToString() != "" || rawData.Cells[i, 8].Value2.ToString() != "Trns-Inc" || rawData.Cells[i, 8].Value2.ToString() != "")
{
string SONumber = rawData.Cells[i, 3].Value2.ToString();
ToDeleteSOs.Add(SONumber);
}
}
return ToDeleteSOs;
}
return null;
}
If not so, what is the best way to write methods like these? For part 2 I guess I could return an empty list and check for length. I'm not sure which is better. However, for first method, I'm really not sure what to return if the file doesn't exist.
A:
I think there is no hard and fast rule for this. But I would return null from first method as returning a null where there is no workbook seems meaning full as null represent no object but from second method empty list would be a batter option as with list we used to use Count before using it instead of null or iterate over list etc. This also goes with convention like ToList will return list of zero elements instead of returning null.
Return null to avoid unknown exceptions from a method in C#
There could be different way to tell the caller method that error occurred in called method and exception is one of those and widely adopted. You can document the method to tell when kind of exception are expected from the method. Lets look at documentation of String.Substring Method (Int32, Int32) on MSDN. The documentation mentions that this method could through ArgumentOutOfRangeException when startIndex plus length indicates a position not within this instance, or startIndex or length is less than zero, MSDN
|
[
"stackoverflow",
"0042248342.txt"
] | Q:
Yes/No prompt in Python3 using strtobool
I've been trying to write an elegant [y/n] prompt for scripts that I'll be running over command line. I came across this:
http://mattoc.com/python-yes-no-prompt-cli.html
This is the program I wrote up to test it (it really just involved changing raw_input to input as I'm using Python3):
import sys
from distutils import strtobool
def prompt(query):
sys.stdout.write("%s [y/n]: " % query)
val = input()
try:
ret = strtobool(val)
except ValueError:
sys.stdout.write("Please answer with y/n")
return prompt(query)
return ret
while True:
if prompt("Would you like to close the program?") == True:
break
else:
continue
However, whenever I try to run the code I get the following error:
ImportError: cannot import name strtobool
Changing "from distutils import strtobool" to "import distutils" doesn't help, as a NameError is raised:
Would you like to close the program? [y/n]: y
Traceback (most recent call last):
File "yes_no.py", line 15, in <module>
if prompt("Would you like to close the program?") == True:
File "yes_no.py", line 6, in prompt
val = input()
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
How do I go about solving this problem?
A:
The first error message:
ImportError: cannot import name strtobool
is telling you that there's no publically visible strtobool function in the distutils module you've imported.
This is because it's moved in python3: use from distutils.util import strtobool instead.
https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool
The second error message deeply confuses me -- it seems to imply that the y you input is trying to be interpreted as code (and therefore complains that it doesn't know about any y variable. I can't quite see how that'd happen!
... two years pass ...
Ahh, I get it now... input in Python 3 is "get a string from the keyboard", but input in Python 2 is "get a string from the keyboard, and eval it". Assuming you don't want to eval the input, use raw_input on Python 2 instead.
|
[
"askubuntu",
"0000340331.txt"
] | Q:
Ubuntu 12.04 Lts not booting
I installed ubuntu 12.04 LTS and it was working properly. I didnt use for one month and now when i boot it the screen becomes blank with a cursor blinking on it. What is the problem?
A:
Reconfiguring Lightdm can fix your problem
Press CTRL+ALT+F1 when blank screen appears.
If tty1 CLI appears then login with your user name and execute following commands
sudo dpkg-reconfigure lightdm
then chose lightdm from the list, and restart your system:
sudo reboot now
If this doesn't work then you have to follow following methods.
Installing GDM (a display manager like lightdm) can fix your problem:
Method 1:
This method works when you are able to go to at least the command line interface.
Press CTRL+ALT+F1 or CTRL+ALT+F2 when your system starts and starts freezing or black screen appears. It will let you to use Command Line Interface. Then login using your username and password, and try following commands:
$ sudo apt-get install gdm
$ sudo dpkg-reconfigure gdm
then selected gdm from the list, and restarted your system:
$ sudo reboot
Your system will be restarted with a login screen which will let you to access your system.
Method 2: If 1st didn't work for you then you can try this method. But it would be very long for you:
Here are the steps how to install using 2nd method
Go to following link and download gdm for Ubuntu 12.04.2 amd64. (chose ubuntu
proposed universe out of three listed there.)
http://pkgs.org/download/gdm
Put the *.deb file just installed to any pendrive.
Then login in save mode or Recovery Mode. After a lot of text displayed in black
screen one window will come which list some options. First go to option Grub, it
will mount your file system in read/write mode. Then chose root option in order
to login as root. Then go to the pendrive where you saved the deb file. The drive
should be listed in in /media. I am assuming that you saved the file in gdm
directory inside pendrive (pendrive is the name of your pendrive)
# cd /media && ls
(which will list your pendrive if you don't get pendrive
folder then go to Mount Pendrive Section at last, then come back here and continue to next step.)
# cd /media/pendrive/gdm
(go to gdm directory where .deb file is saved.)
# dpkg -i *.deb
(installing gdm)
While installing gdm one window will come which will ask your to chose lightdm or gdm
from the list. Chose gdm. If this window doesn't appear then try following command:
# dpkg-reconfigure lightdm
(chose gdm) Then finally execute following command:
# reboot (reboot your system)
Mount Pendrive Section
Mounting pendrive while working in recovery mode.
Run this command:
# fdisk -l
Find your device in the list, it is probably something like /dev/sdb1. Then execute other commands one by another:
# mkdir /media/pendrive
Run this command if your pendrive is formatted in FAT/FAT32.
# mount -t vfat /dev/sdb1 /media/pendrive -o uid=1000,gid=1000,utf8,dmask=027,fmask=137
Or this command if your pendrive is formatted in NTFS
# mount -t ntfs-3g /dev/sdb1 /media/pendrive
Hope it will work for you.. For any further assistance please reply..
|
[
"stackoverflow",
"0039189383.txt"
] | Q:
One summary for multiple test files using python unittest
I wanna make automated testing for my python project but I'm not sure about the correct way to use unittest module.
All of my test files are currently in one folder and have this format:
import unittest
class SampleTest(unittest.TestCase):
def testMethod(self):
# Assertion here
if __name__ == "__main__":
unittest.main()
Then I run
find ./tests -name "*_test.py" -exec python {} \;
When there are three test files, it outputs
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
It printed one summary for each test file. So the question is what can I do to make it print only one test summary, eg Ran 5 tests in 0.001s?
Thanks in advance
And I don't want to install any other module
A:
You are invoking Python multiple times, and each process does not have any knowledge about rest of them. You need to run Python once and use unittest discover mechanism.
Run in shell:
python -m unittest discover
Depending on what is your project structure and naming conventions you may want to tweak discovery params, e.g. change --pattern option, as described in help:
Usage: python -m unittest discover [options]
Options:
-h, --help show this help message and exit
-v, --verbose Verbose output
-f, --failfast Stop on first fail or error
-c, --catch Catch Ctrl-C and display results so far
-b, --buffer Buffer stdout and stderr during tests
-s START, --start-directory=START
Directory to start discovery ('.' default)
-p PATTERN, --pattern=PATTERN
Pattern to match tests ('test*.py' default)
-t TOP, --top-level-directory=TOP
Top level directory of project (defaults to start
directory)
While you said I don't want to install any other module, I'd still recommend using another test runner. There are quite few out there, pytest or nose to name a few.
|
[
"magento.stackexchange",
"0000298994.txt"
] | Q:
How to upgrade magento ver 2.3.1 to 2.3.3
I'm in live, need to upgrade Magento 2.3.1 to 2.3.3.
Please let me know, how to upgrade this version without any disturbance of my website.
A:
Please take your database & code backup first after that performs an update task.
Connect Your SSH and then go to your project root and run below command
composer require magento/product-community-edition 2.3.3 --no-update
After that run
composer update
Once this command execution is completed run reindexer and cache command.
You can read detail info here: https://www.mageplaza.com/devdocs/upgrade-magento-2.html
above steps working fine, otherwise follow these step by step (Manually):
cp composer.json composer.json.bak
cp composer.lock composer.lock.bak
Update in Composer.json -> 2.3.1 to 2.3.3
and changes in Composer.lock (2.3.1 -> 2.3.3)
php bin/magento maintenance:status
php bin/magento maintenance:enable
3) composer update
4) rm -rf var/ pub/static/ generated/*
5) php bin/magento setup:upgrade
6) php bin/magento setup:di:compile
6) php bin/magento setup:static-content:deploy -f
8) php bin/magento cache:clean
9) php bin/magento cache:flush
10) php bin/magento indexer:reindex
php bin/magento maintenance:disable
Hope this will help.
|
[
"math.stackexchange",
"0001973179.txt"
] | Q:
Test function vanishing at origin, divided by x is still a test function?
Given an infinitely differentiable function on the real line that vanishes at the origin, divide it by x. Clearly the result is differentiable, but I think it is also infinitely differentiable--is there an easy way to prove this?
A:
Hint: $f(x)=x\int_0^1 f'(xt)\, dt.$
|
[
"stackoverflow",
"0004854035.txt"
] | Q:
How do I detect a touch on a UIBezierPath and move a ball along that?
How do I move a ball along a specific UiBezierPath? Is that possible?
I've tried everything including doing a hit test using
-(BOOL)containsPoint:(CGPoint)point onPath:(UIBezierPath*)path inFillArea:(BOOL)inFill
How do I detect a touch along a path?
A:
Firstly ... it is an absolute fact that:
there is, definitely, NO method, provided by Apple,
to extract points from a UIBezierPath.
That is an absolute fact as of February 2011, in the latest OS, and everything just on the horizon. I've spoken to the relevant engineers at Apple about the issue. It's annoying in many game programming contexts, but that's the fact. So, it could be that answers your question?
Secondly: don't forget it's as easy as pie to animate something along a UIBezierPath. There are numerous answers on SO, for example How can I animate the movement of a view or image along a curved path?
Thirdly: Regarding finding out where touches happened, if that's what you're asking, as Cory said, this is a hard problem! But you can use CGContextPathContainsPoint to find out if a point (or touch) was on a path of a given thickness.
After that, assuming we are talking about cubics, you need to find points and likely velocities (a.k.a. tangents) along a bezier.
Here is the exact, total code to do that: Find the tangent of a point on a cubic bezier curve (on an iPhone). I pasted it in below, too.
You will have to implement your own MCsim or iteration to find where it hit, depending on your situation. That's not so hard.
(Fourthly -- as a footnote, there's that new thing where you can progressively draw a bezpath, probably not relevant to your question but just a note.)
For the convenience of anyone reading in the future, here is the summary from the linked question of the two "handy" routines...
Finally, here in the simplest possible fashion are the two routines to calculate equidistant points (in fact, approximately equidistant) and the tangents of those, along a bezier cubic:
CGFloat bezierPoint(CGFloat t, CGFloat a, CGFloat b, CGFloat c, CGFloat d)
{
CGFloat C1 = ( d - (3.0 * c) + (3.0 * b) - a );
CGFloat C2 = ( (3.0 * c) - (6.0 * b) + (3.0 * a) );
CGFloat C3 = ( (3.0 * b) - (3.0 * a) );
CGFloat C4 = ( a );
return ( C1*t*t*t + C2*t*t + C3*t + C4 );
}
CGFloat bezierTangent(CGFloat t, CGFloat a, CGFloat b, CGFloat c, CGFloat d)
{
CGFloat C1 = ( d - (3.0 * c) + (3.0 * b) - a );
CGFloat C2 = ( (3.0 * c) - (6.0 * b) + (3.0 * a) );
CGFloat C3 = ( (3.0 * b) - (3.0 * a) );
CGFloat C4 = ( a );
return ( ( 3.0 * C1 * t* t ) + ( 2.0 * C2 * t ) + C3 );
}
The four precalculated values, C1 C2 C3 C4, are sometimes called the coefficients of the bezier. (Recall that a b c d are usually called the four control points.) Of course, t runs from 0 to 1, perhaps for example every 0.05. Simply call these routines once for X and separately once for Y.
Hope it helps someone!
A:
there is a method in bezierpath class called containsPoint: .. refer: http://developer.apple.com/library/ios/#documentation/2ddrawing/conceptual/drawingprintingios/BezierPaths/BezierPaths.html
and you can detect weather the touch point is in bezier path object or not. I have used this with my own method by which a user can easily detect a touch on the bezier path (not inside or out sied if a circle or close path is there).
This code lets user select a bezier path drawing object on touch of it and a dashed line with animation appears on it. hope it helps someone.
Here is code from my own project:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if([[self tapTargetForPath:path] containsPoint:startPoint]) // 'path' is bezier path object
{
[self selectShape:currentSelectedPath];// now select a new/same shape
NSLog(@"selectedShapeIndex: %d", selectedShapeIndex);
break;
}
}
// this method will let you easily select a bezier path ( 15 px up and down of a path drawing)
- (UIBezierPath *)tapTargetForPath:(UIBezierPath *)path
{
if (path == nil) {
return nil;
}
CGPathRef tapTargetPath = CGPathCreateCopyByStrokingPath(path.CGPath, NULL, fmaxf(35.0f, path.lineWidth), path.lineCapStyle, path.lineJoinStyle, path.miterLimit);
if (tapTargetPath == NULL) {
return nil;
}
UIBezierPath *tapTarget = [UIBezierPath bezierPathWithCGPath:tapTargetPath];
CGPathRelease(tapTargetPath);
return tapTarget;
}
-(void)selectShape:(UIBezierPath *)pathToSelect
{
centerline = [CAShapeLayer layer];
centerline.path = pathToSelect.CGPath;
centerline.strokeColor = [UIColor whiteColor].CGColor;
centerline.fillColor = [UIColor clearColor].CGColor;
centerline.lineWidth = 1.0;
centerline.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:5], nil];
[self.layer addSublayer:centerline];
// showing animation on line
CABasicAnimation *dashAnimation;
dashAnimation = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];
[dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
[dashAnimation setToValue:[NSNumber numberWithFloat:30.0f]];
[dashAnimation setDuration:1.0f];
[dashAnimation setRepeatCount:10000];
[centerline addAnimation:dashAnimation forKey:@"linePhase"];
}
A:
This is a really hard problem. You'll need to determine the point on the path closest to the touched point, which is a complicated math problem. This is the best thing I could find using a quick Google search. (Beware: the code is in BASIC.)
http://www.tinaja.com/glib/bezdist.pdf
I admit, I'm tempted to write this myself. It'd be very useful, and I like a challenge.
|
[
"stackoverflow",
"0004907272.txt"
] | Q:
how to fill a table with array elements in jquery?
i have a table in html like this:
<table id="someTable">
<tr>
<td>
<span></span>
</td>
</tr>
<tr>
<td>
<span></span>
</td>
</tr>
<tr>
<td>
<span></span>
</td>
</tr>
</table>
i have an array someArray with three values in it. I want to iterate through the array and set each array items to a span on each row.
i tried a jquery code like this
$('#someTable tr').each(function(i) {
$(this + 'td:first span').html(someArray[i]);
});
the problem is it is setting the last value on the array to all the span's how to fix it?
A:
Use .find(). Appending a selector to this will not work:
$('#someTable tr').each(function(i) {
$(this).find('td:first span').html(someArray[i]);
});
|
[
"english.stackexchange",
"0000045328.txt"
] | Q:
Human Face Divine
I recently read that there is a grammatical construct known as a Miltonic Structure, after John Milton. It said that the structure consists of an adjective + noun + adjective, like "human face divine" from Paradise Lost, book III:
"Or flocks, or herds, or human face divine;"
I searched but found no singular construct such as this called Miltonic Structure. Are you familiar with this structure? Is it called this? Does it have another name?
A:
To me it looks like a combination of two modifiers: (adj noun) and (noun adj). Sometimes (for poetic reasons) adjectives are placed after the noun (this also happens with certain adjectives, such as elect in president elect). So here we have human face, which is further modified by a post-positioned adjective:
((human face) divine) => "divine human face"
I'm not very well-versed in either Blake or Milton, but from a linguistic point of view it does not look like a specific structure to me.
UPDATE: "Miltonic structure" seems to refer to the verse patterns, rather than grammar, see http://www.theodora.com/encyclopedia/s2/sonnet.html:
Hence this critic, like William Sharp, divides all English sonnets into four groups: (I) sonnets of Shakespearean structure; (2) sonnets of octave and sestet of Miltonic structure; (3) sonnets of contemporary structure, i.e. all sonnets on the Petrarchan model in which the metrical and intellectual "wave of flow and ebb" (as originally formulated by the present writer in a sonnet on the sonnet, which has appeared in most of the recent anthologies) is strictly observed, and in which, while the rhyme-arrangement of the octave is invariable, that of the sestet is free; (4) sonnets of miscellaneous structure.
(my emphasis)
|
[
"math.stackexchange",
"0000861021.txt"
] | Q:
Fibrewise product
I have recently started studying fibrewise topology.
It is not clear to me what is the difference between the normal product space and the fibrewise product space over a topological space B.
I am following James book and it defines it as a subset of the normal product space.
Thanks for your help
A:
Let $X,Y$ be topological spaces. Then, of course, their product $X\times Y$ is the cartesian product of the underlying sets $U(X),\ U(Y)$ of $X$ and $Y$ respectively, equipped with the coarsest topology making both projections of $U(X)\times U(Y)$ onto the factors continuous. With this definition, $X\times Y$, together with the projections $p_{X},\ p_{Y}$ satisfies the following universal property: given any pair of continuous functions $(h\colon Z\to X,\ k\colon Z\to Y)$, there exists a unique continuous map $(h,\ k)\colon Z\to X\times Y$ such that $p_{X}\circ (h,k)=h$ and $p_{Y}\circ (h,k)=k$. (The proof of this claim is an easy, but mandatory, exercise).
Now, suppose to have a couple of continuous functions $f\colon X\to Z$ and $g\colon Y\to Z$ into the same topological space $Z$. Then you know the definition of $X\times_{Z}Y$ for this pair of map as the set
$$U(X\times_{Z}Y):=\{(x,y)\in U(X)\times U(Y):\ f(x)=g(y)\}$$
endowed with the subspace topology inherited by the product topology given on $X\times Y$. Note that $X\times_{Z}Y$ comes together with two continuous map $\pi_{X}\colon X\times_{Z}Y\to X$ and $\pi_{Y}\colon X\times_{Z}Y\to Y$, which are the restrictions of $p_{X}$ and $p_{Y}$ respectively. The triple $(X\times_{Z}Y,\ \pi_{X},\ \pi_{Y})$ is such that $f\circ \pi_{X}=g\circ \pi_{Y}$ and satisfies the following unviversal property: given any triple $(W,\ h\colon W\to X,\ k\colon W\to Y)$ such that $f\circ h=g\circ k$, there is a unique continuous map $t\colon W\to X\times_{Z}Y$ such that $p_{X}\circ t=h$ and $p_{Y}\circ t=k$. (Again, prove this!)
It follows, that in general the two concept of product and fibered product are distinct, that is, $X\times Y$ is not homeomorphic to $X\times_{Z}Y$. (As, more generally, a subspace of a topological space is not homeomorphic to the whole topological space, of course). For example, consider a continuous map $f\colon X\to Y$ and the identity map $1_{Y}\colon Y\to Y$. Then the fibered product $X\times_{Y} Y$ with rispect to these maps is just the graph of $f$ (look at the definitions!), which, of course, is not homemorphic to $X\times Y$ in general.
Note however that, if you take the only possible (continuous) map $f\colon X\to\{0\}$ and $g\colon Y\to\{0\}$, you can see that $X\times_{\{0\}} Y=X\times Y$. So, if you want, fibered products generalise products, as the latter can be recovered as particular instances of the former.
Hope this helps somehow.
|
[
"math.stackexchange",
"0002940705.txt"
] | Q:
Periodic solutions of ODE
I need to solve this problem, and I'm having some trouble.
Let $f(t,x)$ satisfy the hypothesis of Picard's Theorem in the strip $-\infty<t<\infty$, $a \le x \le b$, and suppose $f$ is periodic int $t$ with period $T$. If
$f(t,a)>0$, and $f(t,b)<0$, $\forall t \in \mathbb R$,
show that this implies that the equation $\dot {x} = f(t,x)$ has a periodic solution of period $T$.
Hint: First that any solution $x(t)$ satisfying $x(0)=x_0$, $a\le x_0\le b$ is defined for $0 \le t \le T$ and takes on values betwenn $a$ and $b$. Then show there exists such a solution satisfying $x(0)=x(T)$ and that its periodic is the required solution.
I know that if $x(t)$ is between $a$ and $b$, then the domain of $x$ is $\mathbb R$ (since the graphic of $x$ is not contained in any compact). But I cannot prove that $a\le x(t) \le b$.
And I could not prove the existence of a $x_0$ satisfying $x(0)=x(T)$.
A:
Suppose $x(0)=x_0\in(a,b)$. Then $a<x(t)<b$ for all $t>0$. Suppose that $x(t)>b$ for some $t>0$. Then there exists $s\in(0,t)$ such that $x(s)=b$. Let $\tau$ be the infimum of all such $s$. Then, since $x(t)<b$ for $t<\tau$, we have $x'(\tau)\ge0$. On the other hand, $x'(\tau)=f(\tau,x(\tau))=f(\tau,b)<0$, arriving to a contradiction. Similarly, we see that $x(t)>a$. If $x(0)=b$,since $x'(0)=f(0,b)<0$, $x(t)<b$ for$t$ close to $0$ and the previous argument applies.
Continuity of the map $x_0\to x(T)$ follows from the continuous dependence of solutions on initial data. This map takes $[a,b]$ into itself, and the intermediate value theorem proves that it has a fixed point.
|
[
"stackoverflow",
"0035154203.txt"
] | Q:
SQLSTATE[42000]: Syntax error or access violation: 1064 Symfony 2.7.3 application
i get the below error when i try to create my product entity:
An exception occurred while executing 'INSERT INTO products (code, name, description, order, stock, entry, created, manufactured, expire, opening_quantity, purchase_price, opening_price, price, visible, discontinue, view, about, brand_id, groups_id, measurement_id, gender_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [432211, "trolly bag", "description", 0, 2, "2016-02-01 15:02:57", "2016-02-01 15:02:57", "2011-03-08", "2016-09-12", 2, 100, 100, 100, 1, 0, 0, "about", 2, 2, null, null]:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, stock, entry, created, manufactured, expire, opening_quantity, purchase_p' at line 1
Product Entity:
enter code here namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="products")
* @ORM\HasLifecycleCallbacks
* @ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
*/
class Product
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="integer")
*/
protected $code;
/**
* @ORM\Column(type="string", length=100)
*/
protected $name;
/**
* @ORM\Column(type="text")
*/
protected $description;
/**
* @ORM\Column(type="integer")
*/
protected $order;
/**
* @ORM\Column(type="integer")
*/
protected $stock;
/**
* @ORM\Column(type="datetime")
*/
protected $entry;
/**
* @ORM\Column(type="datetime")
*/
protected $created;
/**
* @ORM\Column(type="date")
*/
protected $manufactured;
/**
* @ORM\Column(type="date")
*
*/
protected $expire;
/**
* @ORM\Column(type="integer")
*/
protected $openingQuantity;
/**
* @ORM\Column(type="integer")
*/
protected $purchasePrice;
/**
* @ORM\Column(type="integer")
*/
protected $openingPrice;
/**
* @ORM\Column(type="integer")
*/
protected $price;
/**
* @ORM\Column(type="smallint")
*/
protected $visible;
/**
* @ORM\Column(type="smallint")
*/
protected $discontinue;
/**
* @ORM\Column(type="integer")
*/
protected $view;
/**
* @ORM\Column(type="text")
*/
protected $about;
/**
* @ORM\ManyToOne(targetEntity="Brand", inversedBy="product")
* @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
*/
protected $brand;
/**
* @ORM\ManyToOne(targetEntity="Group", inversedBy="product")
* @ORM\JoinColumn(name="groups_id", referencedColumnName="id")
*/
protected $group;
/**
* @ORM\ManyToOne(targetEntity="Measurement", inversedBy="product")
* @ORM\JoinColumn(name="measurement_id", referencedColumnName="id")
*/
protected $measurement;
/**
* @ORM\ManyToOne(targetEntity="Gender", inversedBy="product")
* @ORM\JoinColumn(name="gender_id", referencedColumnName="id")
*/
protected $gender;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* @param integer $code
* @return Product
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* @return integer
*/
public function getCode()
{
return $this->code;
}
/**
* Set name
*
* @param string $name
* @return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
* @return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set order
*
* @param integer $order
* @return Product
*/
public function setOrder($order)
{
$this->order = $order;
return $this;
}
/**
* Get order
*
* @return integer
*/
public function getOrder()
{
return $this->order;
}
/**
* Set stock
*
* @param integer $stock
* @return Product
*/
public function setStock($stock)
{
$this->stock = $stock;
return $this;
}
/**
* Get stock
*
* @return integer
*/
public function getStock()
{
return $this->stock;
}
/**
* Set entry
*
* @param \DateTime $entry
* @return Product
*/
public function setEntry($entry)
{
$this->entry = $entry;
return $this;
}
/**
* Get entry
*
* @return \DateTime
*/
public function getEntry()
{
return $this->entry;
}
/**
* Set created
*
* @param \DateTime $created
* @return Product
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set manufactured
*
* @param \DateTime $manufactured
* @return Product
*/
public function setManufactured($manufactured)
{
$this->manufactured = $manufactured;
return $this;
}
/**
* Get manufactured
*
* @return \DateTime
*/
public function getManufactured()
{
return $this->manufactured;
}
/**
* Set expire
*
* @param \DateTime $expire
* @return Product
*/
public function setExpire($expire)
{
$this->expire = $expire;
return $this;
}
/**
* Get expire
*
* @return \DateTime
*/
public function getExpire()
{
return $this->expire;
}
/**
* Set openingQuantity
*
* @param integer $openingQuantity
* @return Product
*/
public function setOpeningQuantity($openingQuantity)
{
$this->openingQuantity = $openingQuantity;
return $this;
}
/**
* Get openingQuantity
*
* @return integer
*/
public function getOpeningQuantity()
{
return $this->openingQuantity;
}
/**
* Set purchasePrice
*
* @param integer $purchasePrice
* @return Product
*/
public function setPurchasePrice($purchasePrice)
{
$this->purchasePrice = $purchasePrice;
return $this;
}
/**
* Get purchasePrice
*
* @return integer
*/
public function getPurchasePrice()
{
return $this->purchasePrice;
}
/**
* Set openingPrice
*
* @param integer $openingPrice
* @return Product
*/
public function setOpeningPrice($openingPrice)
{
$this->openingPrice = $openingPrice;
return $this;
}
/**
* Get openingPrice
*
* @return integer
*/
public function getOpeningPrice()
{
return $this->openingPrice;
}
/**
* Set price
*
* @param integer $price
* @return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* @return integer
*/
public function getPrice()
{
return $this->price;
}
/**
* Set visible
*
* @param integer $visible
* @return Product
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* @return integer
*/
public function getVisible()
{
return $this->visible;
}
/**
* Set discontinue
*
* @param integer $discontinue
* @return Product
*/
public function setDiscontinue($discontinue)
{
$this->discontinue = $discontinue;
return $this;
}
/**
* Get discontinue
*
* @return integer
*/
public function getDiscontinue()
{
return $this->discontinue;
}
/**
* Set view
*
* @param integer $view
* @return Product
*/
public function setView($view)
{
$this->view = $view;
return $this;
}
/**
* Get view
*
* @return integer
*/
public function getView()
{
return $this->view;
}
/**
* Set about
*
* @param string $about
* @return Product
*/
public function setAbout($about)
{
$this->about = $about;
return $this;
}
/**
* Get about
*
* @return string
*/
public function getAbout()
{
return $this->about;
}
/**
* Set brand
*
* @param \AppBundle\Entity\Brand $brand
* @return Product
*/
public function setBrand(\AppBundle\Entity\Brand $brand = null)
{
$this->brand = $brand;
return $this;
}
/**
* Get brand
*
* @return \AppBundle\Entity\Brand
*/
public function getBrand()
{
return $this->brand;
}
/**
* Set measurement
*
* @param \AppBundle\Entity\Measurement $measurement
* @return Product
*/
public function setMeasurement(\AppBundle\Entity\Measurement $measurement = null)
{
$this->measurement = $measurement;
return $this;
}
/**
* Get measurement
*
* @return \AppBundle\Entity\Measurement
*/
public function getMeasurement()
{
return $this->measurement;
}
/**
* Set gender
*
* @param \AppBundle\Entity\Gender $gender
* @return Product
*/
public function setGender(\AppBundle\Entity\Gender $gender = null)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* @return \AppBundle\Entity\Gender
*/
public function getGender()
{
return $this->gender;
}
/**
* Set group
*
* @param \AppBundle\Entity\Group $group
* @return Product
*/
public function setGroup(\AppBundle\Entity\Group $group = null)
{
$this->group = $group;
return $this;
}
/**
* Get group
*
* @return \AppBundle\Entity\Group
*/
public function getGroup()
{
return $this->group;
}
}
Controller:
namespace AppBundle\Controller\admin;
use AppBundle\Entity\Product;
use AppBundle\Form\Type\ProductType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
class ProductController extends Controller
{
/**
* @Route("/admin/product/create/{group_id}", name="create group product")
*/
public function groupProductCreateAction(Request $request,$group_id)
{
$Group = $this->getDoctrine()->getRepository('AppBundle:Group');
$group = $Group->findOneById($group_id);
$product = new Product();
$form = $this->createForm(new ProductType(), $product)
->add('save', 'submit', array(
'label' => 'Save',
'attr'=>array('class'=>'btn btn-md btn-info')
));
$form->handleRequest($request);
if ($form->isValid()) {
$openingStock = $product->getOpeningQuantity();
$openingPrice = $product->getPrice();
$product->setOrder(0);
$product->setStock($openingStock);
$product->setEntry(new \DateTime());
$product->setCreated(new \DateTime());
$product->setOpeningPrice($openingPrice);
$product->setDiscontinue(0);
$product->setView(0);
$product->setGroup($group);
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('create category group',
array('category_id' => $group_id, )));
}
return $this->render('admin/product.html.twig', array(
'form' => $form ->createView(),
));
}
A:
I'm sorry to say but ORDER is a reserved word. Check this out Mysql Reserved word
|
[
"stackoverflow",
"0023957364.txt"
] | Q:
ajax different forms same page
I have two forms on the same page I have taken an upload script (can't remember where from) which works fine, but it is called when both forms are submitted, I would like it to determine which form was submitted and do something different for the second form.They both need to have the complete:function
FORM1
<form action="upload.php" name="upform" method="post" enctype="multipart/form-data" onsubmit="return disuload();">
<label for="ftp_upload" id="uloadlfile">Select a file: </label><input type="file" name="ftp_upload" id="uloadfile"></br>
<label for="ftp_upcomm" id="uloadlcomm" class="percent">Comments: </label><input type="text" name="ftp_upcomm" size="34" id="uloadcomm"></br>
<label id="uloadlimit">Maximum upload size: <?php echo ini_get('post_max_size'); ?></label></br>
<input type="submit" id="uloadsub" value="Upload">
</form>
FORM2
<form method="post" name="NewFolder">
<label for="ftp_nfolder">Folder name: </label><input type="text" name="ftp_nfolder" size="30"></br>
<input type="submit" value="Create">
</form>
SCRIPT
(function() {
var bar = $('.bar');
var percent = $('.percent');
$('form').ajaxForm({
beforeSend: function() {
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal + ' uploaded, Please wait...');
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal + ' uploaded, Please wait... ');
},
complete: function(xhr) {
bar.width("0%");
location.reload();
percent.html(xhr.responseText);
}
});
})();
A:
You are using
$('form')
which will work for each form element in your document. You can either:
Add ajaxForm for specific forms separately, like:
$('form[name="NewFolder"']).ajaxForm({ //...
$('form[name="upform"]').ajaxForm({ //...
or
2. Determine the name of form inside callback:
//(...)
complete: function(xhr) {
if ('NewForm' === this.name) {
//... do something
} else {
//Somethingelese
}
//(...)
|
[
"math.stackexchange",
"0000492025.txt"
] | Q:
A strange little number - $6174$.
Take a 4 digit number such that it isn't made out the same digit $(1111, 2222, .. . $ etc$)$ Define an operation on such a four digit number by taking the largest number that can be constructed out of these digits and subtracting the smallest four digit number. For example, given the number $2341$, we have,
$4321 - 1234 = 3087$
Repeating this process with the results (by allowing leading zeroes) we get the following numbers:
$8730 - 0378 = 8352$
$8532 - 2358 = 6174$
What's more interesting is that with $6174$ we get
$7641 - 1467 = 6174$
and taking any four digit number we end up with 6174 after at most 7 iterations. A bit of snooping around the internet told me that this number is called the Kaprekar's constant. A three digit Kaprekar's contant is the number 495 and there's no such constant for two digit numbers.
My question is, how can we go about proving the above properties algebraically? Specifically, starting with any four digit number we arrive at 6174. I know we can simply test all four digit numbers but the reason I ask is, does there exist a 5 digit Kaprekar's constant? Or an $n$-digit Kaprekar's constant for a given $n$?
A:
Note: For fun and curiosity I avoid a programming language and stick to algebraic expressions with the intention to feed this through Gnuplot:
The basic operation is
$$
F(n) = F_+(n) - F_-(n)
$$
where $F_+$ maps to the maximum digit number and $F_-$ maps to the minimum digit number.
We only consider the case of base $10$ non-negative $4$ digit numbers
$$
(d_3 d_2 d_1 d_0)_{10} = \sum_{k=0}^3 d_k \, 10^k
$$
To provide $F_+$ and $F_-$ we need a way to sort a set of four digits.
This can be done by applying $\min$ and $\max$ functions
$$
\begin{align}
\min(a, b) &:= \frac{a + b - |a - b|}{2} \\
\max(a, b) &:= \frac{a + b + |a - b|}{2}
\end{align}
$$
like this: We start with calculating intermediate values $s_k$, $t_k$
$$
\begin{matrix}
s_0 = \min(d_0, d_1) \\
s_1 = \max(d_0, d_1) \\
s_2 = \min(d_2, d_3) \\
s_3 = \max(d_2, d_3)
\end{matrix}
\quad\quad
\begin{matrix}
t_0 = \min(s_0, s_2) \\
t_1 = \max(s_0, s_2) \\
t_2 = \min(s_1, s_3) \\
t_3 = \max(s_1, s_3)
\end{matrix}
$$
and then get
$$
d^+_0 = t_0 \quad\quad
d^-_0 = t_3 \\
d^+_1 = \min(t_1, t_2) \quad\quad
d^-_1 = \max(t_1, t_2) \\
d^+_2 = \max(t_1, t_2) \quad\quad
d^-_2 = \min(t_1, t_2) \\
d^+_3 = t_3 \quad\quad
d^-_3 = t_0
$$
where $d^+_k$ are the digits sorted to maximize and $d^-_k$ are the digits sorted to minimize. One can visualize this as a sorting network
d0
\
\ min: s0 --> min: t0 ----> dp0 dm3
/ max: s1 ^ max: t1
/ \ / \
d1 \/ \ min: dp1 dm2
d2 /\ / max: dp2 dm1
\ / \ /
\ min: s2 v min: t2
/ max: s3 --> max: t3 ----> dp3 dm0
/
d3
For example
$$
\begin{align}
d^-_2
&= \min(t_1, t_2) \\
&= \min(\max(s_0, s_2), \min(s_1, s_3)) \\
&= \min(\max(\min(d_0, d_1), \min(d_2, d_3)), \min(\max(d_0, d_1), \max(d_2, d_3)))
\end{align}
$$
which is a complicated term but otherwise still a function of the $d_k$.
Then we need a way to extract the $k$-th digit:
$$
\pi^{(k)}\left( (d_3 d_2 d_1 d_0)_{10} \right) = d_k
$$
this can be done by the usual
$$
\pi^{(3)}(n) = \left\lfloor \frac{n}{1000} \right\rfloor \\
\pi^{(2)}(n) = \left\lfloor \frac{n - 1000\, \pi^{(3)}(n)}{100} \right\rfloor \\
\pi^{(1)}(n) = \left\lfloor \frac{n - 1000\, \pi^{(3)}(n) - 100\, \pi^{(2)}(n)}{10} \right\rfloor \\
\pi^{(0)}(n) = n - 1000\, \pi^{(3)}(n) - 100\, \pi^{(2)}(n) - 10\, \pi^{(1)}(n)
$$
Rewriting this for Gnuplot gives:
min(a,b) = (a + b - abs(a - b))/2.0
max(a,b) = (a + b + abs(a - b))/2.0
dp0(d0,d1,d2,d3) = min(min(d0,d1),min(d2, d3))
dp1(d0,d1,d2,d3) = min(max(min(d0,d1),min(d2,d3)),
min(max(d0,d1),max(d2,d3)))
dp2(d0,d1,d2,d3) = max(max(min(d0,d1),min(d2,d3)),
min(max(d0,d1),max(d2,d3)))
dp3(d0,d1,d2,d3) = max(max(d0,d1),max(d2, d3))
pi3(n) = floor(n / 1000.0)
pi2(n) = floor((n-1000*pi3(n))/ 100.0)
pi1(n) = floor((n-1000*pi3(n)-100*pi2(n))/ 10.0)
pi0(n) = n-1000*pi3(n)-100*pi2(n)-10*pi1(n)
fp(n) = dp0(pi0(n),pi1(n),pi2(n),pi3(n)) +
10*dp1(pi0(n),pi1(n),pi2(n),pi3(n)) +
100*dp2(pi0(n),pi1(n),pi2(n),pi3(n)) +
1000*dp3(pi0(n),pi1(n),pi2(n),pi3(n))
dm0(d0, d1, d2, d3) = dp3(d0,d1,d2,d3)
dm1(d0, d1, d2, d3) = dp2(d0,d1,d2,d3)
dm2(d0, d1, d2, d3) = dp1(d0,d1,d2,d3)
dm3(d0, d1, d2, d3) = dp0(d0,d1,d2,d3)
fm(n) = dm0(pi0(n),pi1(n),pi2(n),pi3(n)) +
10*dm1(pi0(n),pi1(n),pi2(n),pi3(n)) +
100*dm2(pi0(n),pi1(n),pi2(n),pi3(n)) +
1000*dm3(pi0(n),pi1(n),pi2(n),pi3(n))
f(x) = fp(x) - fm(x)
This works quite nice:
gnuplot> print fp(3284), fm(3284)
8432.0 2348.0
But it turns out that using the graphics is not precise enough to identify fixed points.
In the end one needs a computer programm to check all numbers $n \in \{ 0, \ldots, 9999 \}$ for a proper fixed point from $\mathbb{N}^2$.
Note: The $\mbox{equ}$ function was used to set the arguments with repeated digits to zero.
eq(d0,d1,d2,d3) = (d0 == d1) ? 0 : (d0 == d2) ? 0 : (d0 == d3) ? 0 :
(d1 == d2) ? 0 : (d1 == d3) ? 0 : (d2 == d3) ? 0 : 1
equ(n) = eq(pi0(n),pi1(n),pi2(n),pi3(n))
Update: Maybe one can do it better, the calculation precision is good enough:
gnuplot> print fp(6174), fm(6174), f(6174)
7641.0 1467.0 6174.0 # <- fixed point!
gnuplot> print fp(6173), fm(6173), f(6173)
7631.0 1367.0 6264.0
gnuplot> print fp(6175), fm(6175), f(6175)
7651.0 1567.0 6084.0
Update: This seems to work:
gnuplot> set samples 10000
gnuplot> plot [0:9999] [0:1] abs(f(x)*equ(x) - x) < 0.1
Note: The algebraic expressions I used made analysis not easier, the terms are too unwieldy to give the insight to determine the fixed points. It boiled down to to trying out every argument and checking the function value via a computer.
|
[
"stackoverflow",
"0047036909.txt"
] | Q:
How to split php string into parts
How to split this string "#now my time #Cairo travel #here" to become in array like that
Array ( [0] => #now [1] => my time [2] => #Cairo [3] => travel [4] => #here )
A:
https://secure.php.net/manual/en/function.explode.php
$array = explode(" ", $yourString)
|
[
"stackoverflow",
"0039024990.txt"
] | Q:
jquery each() and js array not working as expected
I have this code in html:
<div class="box-content">
<span>
<h4 id="title">title1</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title2</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title3</h4>
<h5 id="texto"></h5>
</span>
....
</div>
and I need to populate that structure using an array as follows
$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
var i = 0;
$('.box-content').children().each(function(){
var tmp = itemBoxValues1[i];
$('.box-content').children().children("h5").text(" id: "+i+" val "+tmp);
i++;
});
});
but it doesn't work as I expected because in all <h5> elements print this:
<span>
<h4 id="title">title n </h4>
<h5 id="texto">id: 35 val 23</h5>
</span>
I don't understand why it's happen. Thanks.
A:
Try this:
$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
var i = 0;
$('.box-content').children().each(function(){
var tmp = itemBoxValues1[i];
$(this).children("h5").text(" id: "+ i +" val "+ tmp);
i++;
});
});
Update
Inside each, you need to find children of current span, so you need to use $(this), this $('.box-content').children().children("h5") will return all h5 tags
Also you can use following to save some lines of your code:
var itemBoxValues1 = ["text1", "text2", "text3"];
$('.box-content > span').each(function(i, span){
$(span).children("h5").text(" id: "+ i +" val "+ itemBoxValues1[i]);
});
|
[
"stackoverflow",
"0007237241.txt"
] | Q:
how to convert characters like these,"a³ a¡ a´a§" in unicode, using python?
i'm making a crawler to get text html inside, i'm using beautifulsoup.
when I open the url using urllib2, this library converts automatically the html that was using portuguese accents like " ã ó é õ " in another characters like these "a³ a¡ a´a§"
what I want is just get the words without accents
contrã¡rio -> contrario
I tried to use this algoritm, bu this one just works when the text uses words like these "olá coração contrário"
def strip_accents(s):
return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
A:
Firstly, you have to ensure that your crawler returns HTML that is unicode text (Eg. Scrapy has a method response.body_as_unicode() that does exactly this)
Once you have unicode text that you cant make sense of, the step of going from unicode text to equivalent ascii text lies here - http://pypi.python.org/pypi/Unidecode/0.04.1
from unidecode import unidecode
print unidecode(u"\u5317\u4EB0")
The output is "Bei Jing"
|
[
"stackoverflow",
"0019392382.txt"
] | Q:
Need mutator methods how do I do them
I am doing a UML and I am not quite sure how to do these mutator methods I am supposed to do this:
+turnOn(): void //sets on to true
+turnOff(): void //sets on to false
+channelUp(): void //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void //increases the volume by 1 if on and less than maximum
+volumeDown(): void //decreases volume by 1 if on and greater than 0
+toString( ): String //returns the current state(instance variable values)
my code right now: (keep in mind the mutator part isn't right)
public class TV {
private int volume;
private int channel;
private boolean on;
private int maxVolume;
private int maxChannel;
TV() {
volume = 1;
channel = 1;
on = false;
maxVolume = 1;
maxChannel = 1;
}
public int getChannel() {
return channel;
}
public int getVolume() {
return volume;
}
public boolean isOn() {
return on;
}
public int getMaxChannel() {
return maxChannel;
}
public int getMaxVolume() {
return maxVolume;
}
public void setChannel(int i) {
if (isOn() && i >= 1 && i <= maxChannel) channel = i;
}
public void setVolume(int i) {
if (isOn() && i >= 0 && i <= maxVolume) volume = i;
}
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setMaxVolume(int i) {
maxVolume = i;
}
// + turnOn() * * This is where the mutator methods begin I need help here * *
// if (channel == maxChannel) channel = 1;
// else channel++;
//if (channel == 1) channel = max;
//else channel--;
// if (volume == maxVolume) volume = 1;
// else channel++;
//if (volume == 1) volume = max;
// else channel--;
public string toString() {
return "channel: " + channel + "\nvolume: " + volume +
"\non: " + on + "\nmax Channel: " + maxChannel +
"\nmax Volume: " + maxVolume;
}
}
A:
Sample methods:
public void turnOn() {
this.on = true;
}
public void channelUp() {
if (on) {
if (channel == maxChannel) {
channel = 1;
}
else {
channel++;
}
}
}
public void volumeDown() {
if (on && volume > 0) {
volume--;
}
}
Other methods follows the same logic.
Strings in java are objects, so your toString method signature should read public String toString().
|
[
"stackoverflow",
"0030753933.txt"
] | Q:
authentication ruby valid_password error
I'm new to ROR. I tried for simple login with email and password. I can't authenticate the password. It's repeated question, and my error is not yet cleared with old questions. My code is
user = User.find_by_email(params[:email])
user.valid_password?(params[:password])
if @user = User.find_by_email(params[:user][:email]).valid_password?(params[:user][:password])
#render :json=> user.as_json(:status=>'success', :Message=>'Sucessfully Registered', :username=>user.username ), :status=>201
render :json=> {userDetails: [{:status=>'Success',:Message=>'Successfully Signed in', :username=>@user.name, :useremail=>@user.email, :usermobile=>@user.mobile_no }]}, :status=>200
else
render :json=> {:status=>'Failure',:message=>'Invalid Credentials'}, :status=>422
:message=>'Sucessfully Singed in', :auth_token=>user.authentication_token, :email=>user.email), :status=>201
end
I'm facing the below error
undefined method `valid_password?' for nil:NilClass
could anyone tell me what i'm doing incorrectly?
A:
change the if line to
if (@user = User.find_by_email(params[:user][:email])) && @user.valid_password?(params[:user][:password])
|
[
"serverfault",
"0000323716.txt"
] | Q:
Linux kernel module file size
I'm trying to update the kernel on a CentOS 6 machine with a vanilla 3.1.0-rc10 kernel. It seems to work, except the modules that get created are significantly larger in size than those that come from the distro RPM. Thats an issues, because the mkinitrd command ends up creating a initram file that is 100M (because of the some of all the modules inside) in size. Grub takes forever to load and decompress a 100M initram file at boot.
In short:
I downloaded the kernel code.
Copied the running kernel config from/boot/config-2.6.xxx to .config in my kernel code dir.
ran make oldconfig and accepted the defaults
ran make && make modules_install
ran mkinitrd /boot/initramfs-3.1.0-rc10.x86_64.img 3.1.0-rc10
The resulting /boot/initramfs-3.1.0-rc10.x86_64.img is 100M in size.
Its clearly because the size of the modules is so much larger; picking the qla4xxxx you can see my compiled version is 3.6M vs the distros 116K. This is the case for all the modules.
[root@localhost ~]# ls -lh /lib/modules/2.6.32-71.el6.x86_64/kernel/drivers/scsi/qla4xxx/qla4xxx.ko
-rwxr--r--. 1 root root 116K May 19 23:37 /lib/modules/2.6.32-71.el6.x86_64/kernel/drivers/scsi/qla4xxx/qla4xxx.ko
[root@localhost ~]# ls -lh /lib/modules/3.1.0-rc10+/kernel/drivers/scsi/qla4xxx/qla4xxx.ko
-rw-r--r--. 1 root root 3.6M Oct 21 12:57 /lib/modules/3.1.0-rc10+/kernel/drivers/scsi/qla4xxx/qla4xxx.ko
I've done this before without issue; what am I overlooking here?
A:
Run strip --strip-unneeded on the module to remove extraneous symbols. If that doesn't do it, run size on both modules to see where the difference lies. Note that this makes debugging somewhat more difficult.
|
[
"stackoverflow",
"0030722609.txt"
] | Q:
How can the set Device Language change a heading?
I have the word "Color" in a heading at the top of an html page. For users with a device set to British English, I want the text to change to "Colour". How can I achieve this? (with minimal Javascript if possible)
A:
If you give your heading an ID so it looks something like this:
<h1 id="myColorHeading">Color</h1>
you can do it like this:
var el = document.getElementById('myColorHeading');
el.innerHTML = el.innerHTML.replace('Color', 'Colour');
|
[
"math.stackexchange",
"0001039570.txt"
] | Q:
Function differentiable on $(a,b)$ but not continuous on $ [a,b]$
Is there any function $f$ which is differentiable on an open interval $(a,b)$ but is not continuous on (and also cannot be extended continuously to) the closed interval $[a,b]$?
A:
$$\Large\dot{}\!\!\underline{\qquad\qquad\qquad}\!\!\Large\dot{}$$
$$$$
A:
$$f(x)=\frac1{(x-a)(x-b)},\qquad f(a)=f(b)=0.$$
A:
The easiest function I can think of is
$$f(x)=\begin{cases}\sqrt x&,\;\;x\in (0,1]\\{}\\18&,\;\;x=0\end{cases}$$
|
[
"stackoverflow",
"0029663825.txt"
] | Q:
How do I disable iphone 3.5" screen Xcode
I am trying to submit my app to the app store, but it says my build allows 3.5" in screens. I can't figure out how to disallow 3.5" screen in my build :) Any insight would be great. Been googling forever trying to find a solution, but for some reason I can't! Thank you
A:
Nope, you can not disallow 3.5" screens. I don't know why you should do that but inside Xcode, you could check for the screen's height programmatically and if it is 480 then make a welcome screen or something where you can state that the app does not run on that device.
Also, if you don't mind waiting, I bet iOS 9 will support iPhone5+ only which eliminates the 3.5" screens.
Hope that helps :)
|
[
"vi.stackexchange",
"0000021774.txt"
] | Q:
open coc-definition in new split in coc
I am using coc.vim in neovim. coc.vim suggests the following mapping for jumping to the definition of a class/method.
nmap <silent> gd <Plug>(coc-definition)
If there is only a single matching definition, pressing gd will immediately open the definition in the current window.
If there are multiple matches, coc shows a preview window with the list of matching files. It is possible to scroll through the results with j/k. Pressing tab displays the following prompt, for opening the current selection.
Choose action:
[o]pen, (p)review, (q)uickfix, (t)abe, (d)rop, (v)split, (s)plit:
Is the above prompt a standard part of vim or is it part of coc.vim?
Is it possible to force this prompt, even if there is only a single hit?
If not, how can I force vim to open coc-definition in a new vertical split?
A:
I inject my own way of opening files in CoC with:
let g:coc_user_config = {}
let g:coc_user_config['coc.preferences.jumpCommand'] = ':SplitIfNotOpen4COC'
Then the command is defined in my lh-vim-lib plugin to search if the buffer is already opened or not. Having more control is possible.
To use the prompt already provided by CoC, you may have to search in its source code.
|
[
"stackoverflow",
"0010571145.txt"
] | Q:
mysql distinct statement not working
$query = "SELECT DISTINCT t.task_id, e.url,e.error_id, p.page_rank, e.scan_status, e.url_is_route,e.url_is_route,e.forbidden_word,e.google_host_fail,e.google_cache_fail,e.google_title_fail,e.robots_noindex_nofollow,e.xrobots_noindex_nofollow,e.title_fetch_warn,e.h1_fail,e.h2_fail,e.h3_fail,e.h1_warn,e.h2_warn,e.h3_warn
FROM `error_report` AS e
INNER JOIN task_pages AS t ON t.task_id=e.task_id
INNER JOIN `pages` AS p ON p.page_id=t.page_id
WHERE t.task_id=" . $this->task_id ;
I want the query to be distinct only by t.task_id. The problem is that when I add more fields..the query isnt distinct anymore. Is there still a way to select distinct by t.task_id only?
A:
instead of distinct use group by
$query = "SELECT t.task_id, e.url,e.error_id, p.page_rank, e.scan_status, e.url_is_route,e.url_is_route,e.forbidden_word,e.google_host_fail,e.google_cache_fail,e.google_title_fail,e.robots_noindex_nofollow,e.xrobots_noindex_nofollow,e.title_fetch_warn,e.h1_fail,e.h2_fail,e.h3_fail,e.h1_warn,e.h2_warn,e.h3_warn
FROM `error_report` AS e
INNER JOIN task_pages AS t ON t.task_id=e.task_id
INNER JOIN `pages` AS p ON p.page_id=t.page_id
WHERE t.task_id=" . $this->task_id
."group by t.task_id";
|
[
"stackoverflow",
"0038551488.txt"
] | Q:
Working with ceylon import-jar
How can I import a library from maven central into a project with the ceylon import-jar command?
Please show the full command.
E.g. for "joda-time-2.9.4.jar" from "http://repo.maven.apache.org/maven2/" into a local directory.
I guess it must be:
./ceylon-1.2.3/bin/ceylon import-jar --rep "http://repo.maven.apache.org/maven2/" --verbose --out localdir "joda-time:joda-time/2.9.4" "joda-time-2.9.4.jar"
But as far as I can see the tool is not working (ceylon versions 1.2.2 and 1.2.3).
Working with maven central is essential.
This question is linked with The ceylon copy tool because both tools present me with a riddle.
A:
I understand you are asking about the ceylon import-jar tool specifically, but would like to offer a different solution that is easier if your goal is to import a jar from a remote repository.
I would suggest you use the Ceylon Gradle Plugin, which I wrote.
It knows how to grab dependencies from repositories (including JCenter and Maven Central, but many others), and it will run the ceylon -import-jar tool for you automatically.
Full Example:
Run the following command to create a new test project (enter simple for the folder name):
ceylon new simple --module-name=com.athaydes.test --module-version=1.0
Enter the new project name and have a look at what's in it (minimum Ceylon project):
cd simple
tree # or use Finder, Window Explorer or whatever
You'll see this:
└── source
└── com
└── athaydes
└── test
├── module.ceylon
├── package.ceylon
└── run.ceylon
Edit module.ceylon so it has the following contents (add whatever dependencies you want):
module com.athaydes.test "1.0" {
native("jvm")
import joda_time.joda_time "2.9.4";
}
Notice the name of the module must be a valid Ceylon identifier! So, the Gradle plugin replaces invalid characters with _, generating a valid Ceylon identifier from the Maven artifact name.
Create a build.gradle file at the root of the project so the Gradle plugin can work, with the following contents:
plugins {
id "com.athaydes.ceylon" version "1.2.0"
}
repositories {
jcenter()
}
ceylon {
module = "com.athaydes.test"
flatClasspath = false
importJars = true
forceImports = true // necessary to bypass optional dependencies issues in Maven poms
}
dependencies {
ceylonCompile "joda-time:joda-time:2.9.4"
}
We must declare this dependency here as a normal Maven dependency so Gradle knows where to get the Jars from.
Done... now just run importJars:
gradle importJars
Or, to just see the actual command generated (will not actually run it):
gradle -P get-ceylon-command importJars
Here's the generated command:
ceylon import-jar
--force
--descriptor=/Users/renato/programming/experiments/ceylon-gradle/simple/build/module-descriptors/joda_time_2.9.4.properties
--out=/Users/renato/programming/experiments/ceylon-gradle/simple/modules
--rep=aether:/Users/renato/programming/experiments/ceylon-gradle/simple/build/maven-settings.xml
--rep=/Users/renato/programming/experiments/ceylon-gradle/simple/modules
joda_time.joda_time/2.9.4
/Users/renato/.gradle/caches/modules-2/files-2.1/joda-time/joda-time/2.9.4/1c295b462f16702ebe720bbb08f62e1ba80da41b/joda-time-2.9.4.jar
The jars will be imported to the default location, modules (but you can configure that):
── build
│ ├── dependency-poms
│ │ └── joda-time-2.9.4.pom
│ ├── maven-repository
│ │ └── joda-time
│ │ └── joda-time
│ │ └── 2.9.4
│ │ ├── joda-time-2.9.4.jar
│ │ └── joda-time-2.9.4.pom
│ ├── maven-settings.xml
│ └── module-descriptors
│ └── joda_time_2.9.4.properties
├── build.gradle
├── modules
│ └── joda_time
│ └── joda_time
│ └── 2.9.4
│ ├── joda_time.joda_time-2.9.4.jar
│ ├── joda_time.joda_time-2.9.4.jar.sha1
│ └── module.properties
└── source
└── com
└── athaydes
└── test
├── module.ceylon
├── package.ceylon
└── run.ceylon
Now you can run the Ceylon code with the runCeylon task (or just run if there's no other task with this name):
gradle run
NOTE:
Unfortunately, actually importing the specific Jar you chose into the Ceylon repo is impossible with its original name... because in Ceylon, joda-time is an illegal identifier... so you need to change the name of the module when imported by Ceylon. The Gradle plugin does it for you.. but you need to know what the valid identifier will be to be able to write the import statement in the module file (you can just let the plugin run and it will tell you what the name will be).
A much simpler approach
If you want to avoid the complexity of this approach, you can just use the default Gradle plugin approach to NOT import Maven jars into the Ceylon repository and just use the simple Java classpath (which means you relinquish using the Ceylon modules system!).
If you do that, your build.gradle file will look like this:
plugins {
id "com.athaydes.ceylon" version "1.2.0"
}
repositories {
jcenter()
}
ceylon {
module = "com.athaydes.test"
}
And the module.ceylon file:
module com.athaydes.test "1.0" {
native("jvm")
import "joda-time:joda-time" "2.9.4";
}
Notice that we don't need to mess up with the dependency name using this approach. From Ceylon 1.2.3, you should prepend the dependency with the maven: qualifier to avoid warnings.
That simple!
|
[
"physics.stackexchange",
"0000361926.txt"
] | Q:
How do holographic mirrors work?
I found this hologram on a book.
Apart from the usual rainbow colors, it sported a convex mirror effect on it.
Here, you can see my phone's reflection in the tiny circles.
It would be interesting to know how they make mirror like reflections on a plane flat holographic sticker?
Maybe we could use these holographic mirrors as a substitute for the ordinary spherical mirrors which are difficult to manufacture and handle, too?
A:
Those circular regions are actually Fresnel reflectors consisting of thin concentric grooves whose faces are tilted as if formed from a parabolic mirror sliced into thin rings and "accordioned" down onto a surface. They can be made holographically, diamond ruled, or made using a microlithographic process.
|
[
"stackoverflow",
"0038262500.txt"
] | Q:
Android Volley get json Object from error responses ( !=200)
I have a bit nonstandard situation where server sends in case of error responses (500, 404, ..) also json Object inside of response. But I have a problem to get it in Volley. Is there any way how to parse it from headers ?
A:
HTTP error codes should not have data in the returned response
you can as suggested before, extend Volley's Request and override the parseNetworkResponse and pass on the data if needed or do anything that is reqired.
p.s. remember that it runs off the UI thread but is blocking a network thread, so you can do heavy parsing but should probably only figure out if this is a success or error and let the rest of the chain take care of parsing.
You can also write your own ErrorListener and figure out what to do upon the different types of errors reponses
|
[
"mathematica.stackexchange",
"0000029229.txt"
] | Q:
Initialization Cells in CDF
I am wanting to run about 15 pages of initialization cells in a CDF, but can't seem to do so. I have set the InitializationCellEvaluation to True and InitializationCellWarning to False, but it doesn't work in the CDF. (works just fine in the .nb) I saw something about the NotebookDynamicExpression, but I wasn't sure how to run a ton of code through it.
Are there any alternatives? I use no Manipulate or Dynamic functions in my code either.
For example...
GenerateDisplayShotsFor :=
Quiet[Button[
Style["GENERATE", Bold, FontFamily -> "Terminal", 20,
Background -> LightBlue],
CreateWindow[
DocumentNotebook[DisplayShotsFor, WindowTitle -> "Shots For",
WindowFrame -> "ModelessDialog",
Background -> RGBColor[48/240, 164/240, 220/240],
Editable -> False, TextAlignment -> Center ,
WindowFloating -> False,
WindowMargins -> {{0, Automatic}, {Automatic, 0}}]]]];
A:
It's probably a good idea to look at this question more more information about writing CDF-happy notebooks. In brief, Initialization cells won't function properly in the CDF format. For example if we have the following initialization cell:
a = 1;
And subsequent cell that is not an initialization cell
Manipulate[b + x, {x, 1, 10, 1}]
Manipulate[a + x, {x, 1, 10, 1}, Initialization :> (a = 1;)]
The first Manipulate will not evaluate b when exported in CDF format. All of your initialization needs to go in the Initialization option of Manipulate in this case. As mentioned in the question references above, this seems to be the easiest way to get initialization into a CDF, even if Manipulate is not being used.
|
[
"stackoverflow",
"0020704613.txt"
] | Q:
Comparing two Arrays using NSPredicate and returns the repeated character
NSArray *MainArray = [NSArray arrayWithObjects:@"A", @"U", @"U", @"U", nil]; // Array already stored
NSArray *SubArray = [NSArray arrayWithObjects:@"A", @"U", nil]; // Array I passed during runtime
using these two array, I need to get the U U from MainArray.
The concept is that I have to delete the A U from MainArray, which I passed during runtime.
SampleOutput :
U U
A:
You can use this approach:
NSMutableArray *mainMutableArray = [NSMutableArray arrayWithArray:MainArray];
for (id instance in SubArray) {
NSUInteger position = [mainMutableArray indexOfObject:instance];
if (position != NSNotFound) {
[mainMutableArray removeObjectAtIndex:position];
}
}
MainArray = [NSArray arrayWithArray:mainMutableArray];
|
[
"stackoverflow",
"0037949907.txt"
] | Q:
Jetty wants Jersey, but I'm not using it
Building a relatively simple jetty app, following the instructions here:
http://www.eclipse.org/jetty/documentation/9.4.x/maven-and-jetty.html
I'm not using Jersey, but mvn jetty:run complains about
Provider com.sun.jersey.server.impl.container.servlet.JerseyServletContainerInitializer not found
My pom.xml does not include any reference to Jersey. In fact, it is quite simple:
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jettyVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.0.1</version>
</dependency>
What is making jetty look for Jersey?
A:
Well, after much machination, and gnashing of teeth, I think I stumbled about the answer. Whilst learning about maven, I was playing with shaded uber-jars. I had compiled one of the packages as an uper-jar, and installed it. When maven put it all together, it added a bit too much and broke my dependencies. Removing the shaded jar for local installation and just using it for distribution worked just fine.
|
[
"stackoverflow",
"0031157696.txt"
] | Q:
Login With Tumblr in UIWebView
I am using tumbler login authentication via oauth. I am following this url: http://codegerms.com/login-with-tumblr-in-uiwebview-using-xcode-6-part-3/
for login authentication and get Access token and Secret Key for Tumblr API in iOS via login in UIWebview.
I am using this block of code.
- (void)viewDidLoad {
[super viewDidLoad];
// clientID = @"Tjta51N6kF6Oxmm1f3ytpUvMPRAE1bRgCgG90SOa0bJMlSlLeT";
// secret = @"lrlQPNx3Yb1nRxp4qreYXvUURkGUmYCBoQacOmLTDRJAc7awRN";
clientID = @"sdF0Y6bQoJYwfIB1Mp7WECwobAgnq5tmkRjo7OXyKHDg3opY7Y";
secret = @"qJNGrRjyriZBeBhcgJz0MAcD9WAYXUW1tLbLrbYE4ZclzAUH9g";
redirect = @"tumblr://authorized";
[self.WebView setBackgroundColor:[UIColor clearColor]];
[self.WebView setOpaque:NO];
[self connectTumblr];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connectTumblr {
consumer = [[OAConsumer alloc]initWithKey:clientID secret:secret];
NSURL* requestTokenUrl = [NSURL URLWithString:@"http://www.tumblr.com/oauth/request_token"];
OAMutableURLRequest* requestTokenRequest = [[OAMutableURLRequest alloc] initWithURL:requestTokenUrl
consumer:consumer
token:nil
realm:nil
signatureProvider:nil] ;
OARequestParameter* callbackParam = [[OARequestParameter alloc] initWithName:@"oauth_callback" value:redirect] ;
[requestTokenRequest setHTTPMethod:@"POST"];
[requestTokenRequest setParameters:[NSArray arrayWithObject:callbackParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init] ;
[dataFetcher fetchDataWithRequest:requestTokenRequest
delegate:self
didFinishSelector:@selector(didReceiveRequestToken:data:)
didFailSelector:@selector(didFailOAuth:error:)];
}
- (void)didReceiveRequestToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
requestToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSURL* authorizeUrl = [NSURL URLWithString:@"https://www.tumblr.com/oauth/authorize"];
OAMutableURLRequest* authorizeRequest = [[OAMutableURLRequest alloc] initWithURL:authorizeUrl
consumer:nil
token:nil
realm:nil
signatureProvider:nil];
NSString* oauthToken = requestToken.key;
OARequestParameter* oauthTokenParam = [[OARequestParameter alloc] initWithName:@"oauth_token" value:oauthToken] ;
[authorizeRequest setParameters:[NSArray arrayWithObject:oauthTokenParam]];
// UIWebView* webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
// webView.scalesPageToFit = YES;
// [[[UIApplication sharedApplication] keyWindow] addSubview:webView];
// webView.delegate = self;
[self.WebView loadRequest:authorizeRequest];
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"scheme: %@",[[request URL] scheme]);
if ([[[request URL] scheme] isEqualToString:@"tumblr"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:@"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:@"oauth_verifier"]) {
verifier = [keyValue objectAtIndex:1];
break;
}
}
if (verifier) {
NSURL* accessTokenUrl = [NSURL URLWithString:@"https://www.tumblr.com/oauth/access_token"];
OAMutableURLRequest* accessTokenRequest = [[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
consumer:consumer
token:requestToken
realm:nil
signatureProvider:nil];
OARequestParameter* verifierParam = [[OARequestParameter alloc] initWithName:@"oauth_verifier" value:verifier];
[accessTokenRequest setHTTPMethod:@"POST"];
[accessTokenRequest setParameters:[NSArray arrayWithObject:verifierParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
delegate:self
didFinishSelector:@selector(didReceiveAccessToken:data:)
didFailSelector:@selector(didFailOAuth:error:)];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(@"webView error: %@",error);
// ERROR!
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[spinner setHidden:NO];
[spinner startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[spinner setHidden:YES];
[spinner stopAnimating];
}
- (void)didReceiveAccessToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
accessToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSString *OAuthKey = accessToken.key; // HERE YOU WILL GET ACCESS TOKEN
NSString *OAuthSecret = accessToken.secret; //HERE YOU WILL GET SECRET TOKEN
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Tumblr Token"
message:OAuthSecret
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
Every thing is working fine but when logged in then
if ([[[request URL] scheme] isEqualToString:@"tumblr"]) {
}
should called in shouldStartLoadWithRequest delegate method
but the given condition is not satisfied. so that I am unable to verify oauth_verifier and unable to get accessToken.
Please Advice Thanks.
A:
You must be use https instead of http for every url of Tumblr.It will work perfectly.
Thanks.
|
[
"stackoverflow",
"0031718345.txt"
] | Q:
JavaScript unable to access same object method after object.create(baseObject)
I am new to javascript. I have written some code by incorporating suggested answers. Now the code block is working in once scenario and not working in other scenario.
<script langugage="JavaScript">
var baseObject = {
name:"sunrise",
age:39,
printProperties:function(){
console.log("Base class-> Name:Age:"+this.name+":"+this.age);
}
}
baseObject.printProperties();
console.log(baseObject);
/* This code block works fine */
var derivedObject2=Object.create(baseObject);
derivedObject2.education="M.C.A"
derivedObject2.printProperties=function(){
console.log("Derived -> Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
}
derivedObject2.printProperties();
console.log(derivedObject2);
/*
derivedObject.__proto__ = baseObject;
derivedObject.printProperties(); // Works fine
*/
/* This code block does not work */
var derivedObject=Object.create(baseObject,{
education:{value:"MCA"},
//education:"MCA",
printProperties:function(){
console.log("Derived -> Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
return this;
}
});
derivedObject.printProperties(); // Getting error here,
console.log(derivedObject);
</script>
Here is my error:
Error: Uncaught TypeError: derivedObject.printProperties is not a function
A:
Use Object.create()
var baseObject = {
name:"sunrise",
age:39,
printProperties:function(){
console.log("Name:Age:"+this.name+":"+this.age);
}
}
then
var derivedObject=Object.create(baseObject);
derivedObject.education="M.C.A"
derivedObject.printProperties=function(){
console.log("Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
}
derivedObject.printProperties();
now the derivedObject will inherit all the properties of the base object
edit
you can do this
var derivedObject=Object.create(baseObject,{
education:{value:"MCA"},
printprop:function(){}
});
Object.create() abstracts most of the complexity that is associated with the prototypes
|
[
"stackoverflow",
"0011279532.txt"
] | Q:
Code to display an image won't work with different java editors
I need your help!
I am switching to netbeans and have been having some major problems.
After about 6 hours I finally figured out how to get the image to show in netbeans.
Is there a way to write the code where it will work in JGrasp and netbeans?
The working code for netbeans is
menuPic = new javax.swing.JButton();
menuPic.setIcon(new javax.swing.ImageIcon(getClass().getResource("image/w2.png")));
and the working code for JGrasp is
menuPic = new JButton();
ImageIcon bottompic = new ImageIcon("image/w2.png");
JButton menuPic = new JButton(bottompic);
I hate JGrasp but thats what my teacher uses to grade, so I want to be able to write it in netbeans and copy and paste the code to JGrasp and it be able to work.
Any help would be greatly appreciated!!
solved this but now i have another problem
ok that worked but now my JOptionPane picture isn't loading in netbeans
The code i used in JGrasp is
final ImageIcon icon1 = new ImageIcon("image/money.gif");
JOptionPane.showMessageDialog(null, " blah blah", "Text", JOptionPane.INFORMATION_MESSAGE, icon1);
and if i wanted to show an image in JOptionPane.showInputDialog would it be the same as putting on in JOptionPane.showMessageDialog ?
Thanks
A:
The "NetBeans" code will work in JGrasp as long as your image files are located in the right location -- in an image subdirectory off of the directory that holds the class files. By the way, it's not NetBeans-specific code; it's nothing but Java code, pure and simple.
|
[
"tridion.stackexchange",
"0000002386.txt"
] | Q:
Is it necessary to add an impersonation user record to TRUSTEES?
This is the first time to post a question to StackExchange.
Could you please help me about configuration of LDAP?
Now I'm configuring LDAP at Tridion 2013 on Windows 2008.
I have already done the followings according to Tridion installation manual.
changed Authentication settings of IIS.
modified a web.config file which was located in the web\ subfolder.
modified a web.config file which was located in the web\WebUI\WebRoot subfolder.
modified a web.config file which was located in the webservices subfolder.
configured a Directory Services
deselected 'GroupSync Enabled' to disable group synchronization because I'm setting up development environment.
changed a User Type of the impersonation user setting to 'Directory Service'.
applied LDAP configuration changes by restarting IIS, COM+ and Windows services.
After that, I could login Tridion Content Management Console, but there was error message in message center of TCME.
Access is denied for the user NT AUTHORITY\NETWORK SERVICE.
There was the following error in event log.
Access is denied for the user NT AUTHORITY\NETWORK SERVICE.
Component: Tridion.ContentManager.CoreService
Errorcode: 770
User: NT AUTHORITY\NETWORK SERVICE
StackTrace Information Details:
場所 Tridion.ContentManager.Security.AuthorizationManager.LoadAccessToken(String userName, IEnumerable`1 mappedGroupUris, IEnumerable`1 claimSets)
場所 Tridion.ContentManager.Security.AuthorizationManager.LoadAccessToken(String userName, String impersonationUserName)
場所 Tridion.ContentManager.Session..ctor(String userName, String impersonationUserName)
場所 Tridion.ContentManager.CoreService.CoreServiceBase.Impersonate(String userName)
場所 SyncInvokeImpersonate(Object , Object[] , Object[] )
場所 System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
場所 Tridion.ContentManager.CoreService.CoreServiceInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
場所 System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
場所 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
場所 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
場所 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
So I added an impersonation user record 'NT AUTHORITY\NETWORK SERVICE' to TRUSTEES table. As a result, the error message disappeared. But Tridion said 'Welcome, NT AUTHORITY\NETWORK SERVICE' although I logged in as administrator user.
Is it necessary to add an impersonation user record to TRUSTEES? If answer is 'No', why does not Tridion say 'Welcome, Tridion Content Management Administrator'?
I have already checked this post Unable to Initialize TDSE object when using LDAP, but I couldn't resolve this problem.
Could you please help me, again?
A:
The impersonation user does not have to be added to the TRUSTEES table, but rather in the SDL Tridion Configuration MMC Snap In. That's way easier anyway. ;)
You can read about this in the manual and here as well. (login required)
The short version is:
Start the SDL Tridion MMC Snap-in by selecting Programs > SDL Tridion > SDL Tridion Content Manager configuration in the Microsoft Windows Start menu.
In the SDL Tridion MMC Snap-in, right-click on the Impersonation User icon and select New Impersonation User.
Under Windows User, enter the name of the impersonation user used by the Web site. This impersonation user is associated with the NETWORK SERVICE account, and can be configured in the SDL Tridion MMC Snap-in.
|
[
"stackoverflow",
"0058200401.txt"
] | Q:
Finding duplicate array in 2d array and adding number to tuple
I have an array :
a = [[(1,2), (3,4)], [(4,5),(3,4)]]
# Stores list of x,y coordinates
and an array:
b = [(1,2), (3,4)]
Now, I want to replace in a where it has an equivalent of b with y coordinate + 2.
Since here a has an equivalent of b in:
[(1,2), (3,4)]
I want to replace in a such that it becomes:
a = [[(1,4), (3,6)], [(4,5),(3,4)]]
How could I do this?
I know there exists a method with numpy such that:
np.where(a == b) , do something;
but not sure how could I use it in this case.
A:
With numpy
a[(a==b).all(1).all(1),:,1] +=2
|
[
"stackoverflow",
"0014485158.txt"
] | Q:
Algorithm Efficiency
So this is a question in my homework....
Given that the efficiency of an algorithm is n3, if a step in the algorithm takes 1 ns (10-9) seconds), how long does it take the algorithm to process an input of size 1,000?
Here is MY question: How do I figure this out? PLEASE DO NOT POST THE ANSWER. Help me learn how to figure this out for myself.
A:
You define n to be 1000. Thus, you need n3 steps, each one of them taking 1 ns. Multiply the two and you have the answer.
General idea: if an algorithm needs f(n) number of steps and one step takes t then you need t * f(n) for the algorithm.
|
[
"stackoverflow",
"0025849382.txt"
] | Q:
Validation in ViewModel not working
I have ViewModel which contains some proprty of class. Code below.
public class ViewModel
{
public Doctor VmDoctor { get; set; }
public Patient VmPatient { get; set; }
public List<Visit> VmVisit { get; set; }
public List<Hours> hours { get; set; }
public List<Hours> hours2 { get; set; }
public Schedule schedule { get; set; }
public bool BlockBtn { get; set; }
public Test test { get; set; }
}
In this case important property is Patient VmPatient. This is a model which has been generated by Database Model First. He has validation.Code below.
public partial class Patient
{
public Patient()
{
this.Visits = new HashSet<Visit>();
}
public int PatientID { get; set; }
[Required(ErrorMessage = "Podaj imię.")]
public string name { get; set; }
[Required(ErrorMessage = "Podaj nazwisko.")]
public string surname { get; set; }
[Required(ErrorMessage = "Podaj pesel.")]
[RegularExpression(@"^\(?([0-9]{11})$", ErrorMessage = "Nieprawidłowy numer pesel.")]
public string pesel { get; set; }
[Required(ErrorMessage = "Podaj miasto.")]
public string city { get; set; }
[Required(ErrorMessage = "Podaj kod pocztowy.")]
public string zipCode { get; set; }
[Required(ErrorMessage = "Podaj e-mail.")]
[EmailAddress(ErrorMessage = "Nieprawidłowy adres e-mail")]
public string email { get; set; }
[Required(ErrorMessage = "Podaj telefon komórkowy.")]
[RegularExpression(@"^\(?([0-9]{9})$", ErrorMessage = "Nieprawidłowy numer telefonu.")]
public string phone { get; set; }
public virtual ICollection<Visit> Visits { get; set; }
}
and i have Main Index where return my ViewModel because, display two Models in the same View. Code below
public ActionResult Index(int id)
{
ViewModel _viewModle = new ViewModel();
schedule = new Schedule();
if(Request.HttpMethod == "Post")
{
return View(_viewModle);
}
else
{
idDr = id;
_viewModle.schedule = schedule;
_viewModle.BlockBtn = _repository.BlockBtn(schedule);
_viewModle.VmDoctor = db.Doctors.Find(idDr);
_viewModle.hours = _repository.GetHours();
foreach (var item in _viewModle.hours)
{
_viewModle.hours2 = _repository.GetButtonsActiv(item.hourBtn, item.count, idDr, schedule);
}
}
if (_viewModle == null)
{
return HttpNotFound();
}
return View(_viewModle);
}
inside View Index i display my objects and rendered partial _FormPatient.Code below.
@model Dentist.Models.ViewModel
<div class="container-select-doctor">
<div class="row">
<div class="text-left">
<div class="row">
<div class="content">
<div class="profileImage">
<div class="imageContener"><img style="margin:1px;" src="@Url.Content("~/Images/" + System.IO.Path.GetFileName(@Model.VmDoctor.image))" /></div>
</div>
<div class="profileInfo">
<div class="profileInfoName">@Model.VmDoctor.name @Model.VmDoctor.surname</div>
<div class="profileInfoSpeciality">@Model.VmDoctor.specialty</div>
</div>
</div>
</div>
</div>
@ViewBag.firstDay<br />
@ViewBag.lastDay<br />
<div class="text-middle">
<div class="content">
<div id="partialZone">
@Html.Partial("_TableSchedule")
</div>
</div>
</div>
<div class="text-right">
<div class="content">
@Html.Partial("_FormPatient")
</div>
</div>
</div>
</div>
and last step is form which has been rendered inside Main Index by @Html.partial.code below
@model Dentist.Models.ViewModel
@using (Html.BeginForm("Create","Patient"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<font color="red">@ViewBag.Pesel</font>
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.VmPatient.email, htmlAttributes: new { @class = "control-label col-md-2" }, labelText: "E-mail:")
<div class="col-md-10">
@Html.TextBoxFor(model => model.VmPatient.email, new { htmlAttributes = new { @class = "form-control" } })
@*<input class="form-control" id="email" name="email" type="text" value="">*@
@Html.ValidationMessageFor(model => model.VmPatient.email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.VmPatient.phone, htmlAttributes: new { @class = "control-label col-md-2" }, labelText: "Telefon kom.:")
<div class="col-md-10">
@Html.TextBoxFor(model => model.VmPatient.phone, new { maxlength = 9 })
@*<input class="form-control" maxlength="9" id="phone" name="phone" type="text" value="" />*@
@Html.ValidationMessageFor(model => model.VmPatient.phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Please pay attention that this form redirect to another Controller where data will be validate and save to database. Method where data from FORM will be validate and save. code below
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Patient pat)
{
ViewModel vm = new ViewModel();
DentistEntities db = new DentistEntities();
if (ModelState.IsValid)
{
db.Patients.Add(pat);
db.SaveChanges();
}
return RedirectToAction("Index", "Visit", new { id = VisitController.idDr });
}
Conclusion How can i get validation for this form! I have observed that,every time modelstate.isvalid return false.. I dont have any ideas so I would like to ask you for help.
Best regards.
A:
I would suggest that you do this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Patient pat)
{
ViewModel vm = new ViewModel();
DentistEntities db = new DentistEntities();
if (ModelState.IsValid)
{
db.Patients.Add(pat);
db.SaveChanges();
}
vm.VmPatient = pat;
return View(vm);
}
Render the view again, but this time the validation error messages should appear on the page (via the ValidationMessageFor() calls in the view). That, at least you can see why the validation has failed.
Alternatively, you could interrogate the modelstate e.g.
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
string error = error.ErrorMessage;
}
}
|
[
"es.stackoverflow",
"0000080608.txt"
] | Q:
Sustituir varias strings en PHP
Quiero mediante PHP sustituir el resultado de varias variables, cada variable tiene un valor diferente, me gustaría que si un valor me da un resultado sea cambiado por otro.
$descarga1 > Esto me devuelve el valor > Mega.co.nz ó Dropbox.com
$descarga2 > Esto me devuelve el valor > Mediafire.com ó libros.relaxmind.info
$descarga3 > Esto me devuelve el valor > Googledrive.com o Box.net
Para remplazar estoy intentando hacerlo de este modo:
function str_replace($descarga1,$descarga2,$descarga3){
str_replace(
array("Mega.co.nz","Obtén el libro desde Mega.nz"),
array("Dropbox.com", "Obtén el libro desde Dropbox.com"),
array("Mediafire.com","Obtén el libro desde Mediafire.com"),
array("libros.relaxmind.info", "Obtén el libro desde nuestra web"),
array("Googledrive.com","Obtén el libro desde Google Drive"),
array("Box.net", "Obtén el libro desde Box.net"),
);
return $
Hasta aquí me he atorado, Espero haberme dado a entender de la forma correcta, En resumen me gustaría que si $descarga1, $descarga2 o $descarga3alojan un resultado, este sea cambiado por Obtén el libro desde nombre del servidor.
Espero puedan ayudarme, Gracias!.
A:
Propondré una forma un poco más "limpia" , quizá su función deba recibir la lista y el elemento a modificar. teniendo en cuenta la idea que si quiere cambiar 10 valores, ¿ enviará 10 parámetros? , la función tendría la siguiente forma , donde emplearemos la función strtr que acepta como parámetro un array de tipo clave => valor.
function replaceAll($value,$list){
return strtr($value, $list);
}
Para utilizar esta función , debe crear la lista de opciones_completamente adaptable a las opciones que pueda tener_ y pasar la palabra a reemplazar.
$list = array("Mega.co.nz"=>"Obtén el libro desde Mega.nz",
"Dropbox.com"=> "Obtén el libro desde Dropbox.com",
"Mediafire.com"=>"Obtén el libro desde Mediafire.com",
"libros.relaxmind.info"=> "Obtén el libro desde nuestra web",
"Googledrive.com"=>"Obtén el libro desde Google Drive",
"Box.net" => "Obtén el libro desde Box.net");
$descarga1 = "Box.net";
echo replaceAll($descarga1,$list);
$descarga2 = "libros.relaxmind.info";
echo replaceAll($descarga2,$list);
|
[
"stackoverflow",
"0060561866.txt"
] | Q:
ReactJs UseState : insert element into array not updating
I am trying to use React Hooks but somehow my state is not updating. When I click on the checkbox (see in the example), I want the index of the latter to be added to the array selectedItems, and vice versa
My function looks like this:
const [selectedItems, setSelectedItems] = useState([]);
const handleSelectMultiple = index => {
if (selectedItems.includes(index)) {
setSelectedItems(selectedItems.filter(id => id !== index));
} else {
setSelectedItems(selectedItems => [...selectedItems, index]);
}
console.log("selectedItems", selectedItems, "index", index);
};
You can find the console.log result
here
An empty array in the result, can someone explain to me where I missed something ?
A:
Because useState is asynchronous - you wont see an immediate update after calling it.
Try adding a useEffect which uses a dependency array to check when values have been updated.
useEffect(() => {
console.log(selectedItems);
}, [selectedItems])
|
[
"stackoverflow",
"0036763921.txt"
] | Q:
How to lazy load google jsapi charts with angularjs?
I'm having a single page application, but with different tabs.
Only for one tab I want to show a google charts. I don't want to include and load the charts js file jsapi directly, but only if the specific tab is accessed.
Therefore I have to add the js as follows dynamically:
var script = document.createElement('script');
script.src = '//http://www.google.com/jsapi?ext.js';
document.body.appendChild(script);
Problem: how can I detect when the js has been completely loaded, so that I can continue as follows?
if (whenJspaiLoaded()) {
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart); //my custom function
}
A:
As there seems to be no working solution on the net so far, I hope this will help someone in future. Key concept is to delay both the js file loading and the charts component initialization with a callback.
The service to load the js files:
app.service('gchart', ['$window', '$q', '$rootScope', function ($window, $q, $rootScope) {
var deferred = $q.defer();
//run when the jsapi is loaded
$window.callback = function () {
$window.google.load('visualization','1',{
packages: ['corechart'],
callback: function() {
//again having a callback to wait for the visualization to load
$rootScope.$apply(function() {
deferred.resolve();
});
}
});
}
// dynamically adding the js file on page access
var script = document.createElement('script');
script.src = '//www.google.com/jsapi?callback=callback';
document.body.appendChild(script);
return deferred.promise;
}]);
Usage as directive:
app.directive(.., ['gchart', function(.., gchart) {
return {
//...
link: function(scope, elm, attr) {
scope.init = function() {
var viz = new google.visualization.arrayToDataTable(data);
//add options, linechart, draw, whatever
};
// delay the creation until jsapi files loaded
loadGoogleChartAPI.then(function () {
scope.init();
}, function () {
//ignore
});
}
}
}
|
[
"ru.stackoverflow",
"0001148437.txt"
] | Q:
Как получить все атрибуты элемента в selenium?
Вопрос в теме.
Через метод get_attribute(name) можно получить значения атрибута, но нужно знать его название, поэтому метод не подходит.
В качестве примера для опробования предлагаю вывести у элемента input_el все атрибуты:
# pip install selenium
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get('https://ru.stackoverflow.com/')
input_el = driver.find_element_by_css_selector('input.s-input__search')
A:
Решением может быть через javascript, используя метод execute_script(script, *args):
def get_attributes(driver, element) -> dict:
return driver.execute_script(
"""
let attr = arguments[0].attributes;
let items = {};
for (let i = 0; i < attr.length; i++) {
items[attr[i].name] = attr[i].value;
}
return items;
""",
element
)
Весь код:
# pip install selenium
from selenium import webdriver
def get_attributes(driver, element) -> dict:
return driver.execute_script(
"""
let attr = arguments[0].attributes;
let items = {};
for (let i = 0; i < attr.length; i++) {
items[attr[i].name] = attr[i].value;
}
return items;
""",
element
)
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get('https://ru.stackoverflow.com/')
input_el = driver.find_element_by_css_selector('input.s-input__search')
attrs = get_attributes(driver, input_el)
print(attrs)
# {'aria-controls': 'top-search', 'aria-label': 'Поиск', 'autocomplete': 'off',
# 'class': 's-input s-input__search js-search-field ', 'data-action': 'focus->s-popover#show',
# 'data-controller': 's-popover', 'data-s-popover-placement': 'bottom-start', 'maxlength': '240',
# 'name': 'q', 'placeholder': 'Поиск...', 'type': 'text', 'value': ''}
driver.quit()
|
[
"stackoverflow",
"0019202120.txt"
] | Q:
How to compute age from NSDate
I am working on an app that needs to find someones age depending on their birthday. I have a simple NSDate but how would I find this with NSDateFormatter?
A:
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
NSDate *today = [NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear
fromDate:birthdate
toDate:today
options:0];
return ageComponents.year;
}
NSDateFormatter is for formatting dates (duh!). As a rule of thumb, whenever you need to perform some computation on an NSDate you use a NSCalendar and associated classes, such as NSDateComponents.
|
[
"serverfault",
"0000803984.txt"
] | Q:
Exchange 2016 - Unable to Send As for Mail Public Folder
Exchange 2016 using Outlook 2016 client
Created a new Public Folder titled
Mail-enabled the public folder:
Enable-MailPublicFolder -Identity "\PublicFolder"
Added Send As permissions.
Add-ADPermission PublicFolder -User domain\jsmith -Extendedrights "Send As"
Added permissions to receive mail.
Add-PublicFolderClientPermission -identity "\PublicFolder" -User Anonymous -AccessRights CreateItems
Set Hidden from address lists false:
Enable-MailPublicFolder -Identity "\PublicFolder" -HiddenFromAddressListsEnabled $False
The user jsmith is an owner of this public folder. He can add the public folder and the public folder can receive emails but nobody is able to "Send As" the public folder.
Under EAC I have verified that the public folder exists, permissions are in place, and the folder is mail-enabled.
I have tried disabling Mail Settings and re-enabling. I am also completely unable to select "PublicFolder" in my "From" field in OWA. It gives no option to enter a custom name and also doesn't have an option for the PublicFolder. I did add it to my Favorites.
The user receives the message "This message could not be sent. Try sending the message again later, or contact your network administrator. You do not have the permission to send the message on behalf of the specified user. Error is [0x80070005-0x0004dc-0x000524]."
The user has both Send As and Send on Behalf Of permissions.
The issue has lasted more than 24 hours so I am fairly certain that it is not a replication issue.
A:
"The user has both Send As and Send on Behalf Of permissions. "
First, you need to set one or the other. Not both. Therefore remove one.
Does the public folder appear in the GAL? If so, that is how you populate the From field. You cannot just type the address in. If it doesn't appear in the GAL then you need to wait for it to do so. Outlook in cached mode will use the OAB, so you could force the OAB to update
get-offlineaddressbook | update-offlineaddressbook
Wait half an hour then force the client to download the OAB from the Send/Receive menu.
|
[
"english.stackexchange",
"0000232164.txt"
] | Q:
Connecting two relative clauses in one sentence
I would like to write an essay which gives information about the charts but because I am not native English speaker, when I started to write down my essay I came across the similar problems that I do sometimes.
Here my sentence:
Figure 1 and figure 2 show the percentage of people, WHOSE age is between 25-44 and over 65, WHO purchased concert, cinema and theater tickets online over the first three months of 2006 in three countries, WHICH are Australia, the UK, Malaysia.
Here is my questions:
1.How can I give the information of age and of what do people buy in one sentence?
2.Such vital and important information on the figures can be used as indefinite relative clause?
A:
"Figure 1 and figure 2 show the percentage of people whose age is between 25-44 and over, and who purchased concert, cinema and theater tickets online over the first three months of 2006, in three countries, which are Australia, the UK, and Malaysia."
I've omitted the comma after "people", since the sense of the following relative clause is restrictive. I kept the comma after "over" because there is an intonation break here in the pronunciation. I added a comma after "2006", also because of the pronunciation, and to make clearer that the following prepositional phrase goes with the preceding verb phrase that starts with "purchased". The last relative clause is non-restrictive, so it keeps the comma you put after "countries". I added "and" before "Malaysia" (but the preceding comma perhaps should be omitted).
A:
I would simplify it by omitting some of the relative pronouns.
Figures 1 and 2 show the percentage of people age 25 and over who purchased concert, cinema and theater tickets online during the first three months of 2006 in Australia, the UK and Malaysia.
I believe this is clear, concise and grammatically correct.
(is it really necessary to say 25-44 and over, since that includes everyone over 44 as well?)
|
[
"security.stackexchange",
"0000058048.txt"
] | Q:
What is DDOS TCP KILL?
I've recently been introduced to Kali Linux's webkiller tool, located in the websploit category. It works on the concept of Tcpkill.
I don't understand how the DoS attack with Tcpkill works. Can someone explain it in detail?
A:
I think you may be misunderstanding what tcpkill is. tcpkill is not generally used in any sort of DDoS type of attack. It is possible to use it to DoS someone, but that usually involves you being within the same network segment as them, or controlling a part of the network their data transits.
To keep it short, its a packet filter. It is designed to drop packets based on your filter criteria, which can be any of the following:
Source IP
Destination IP
Source Port
Destination Port
Any other tcpdump expression
The idea of webkiller is to deny web service to a user on a controlled network. That may be legitimate control, like a network admin blocking certain services. Or it might be illegitimate control, like an attacker blocking access to facebook to piss someone off.
|
[
"stackoverflow",
"0027059771.txt"
] | Q:
Python regex: replace ignoring empty string
I am trying to replace a given pattern with regular expressions in Python, using re. Here is the piece of Python code I wrote:
import re
fname = './prec.f90'
f = open(fname)
lines = f.readlines()
f.close()
for i, line in enumerate(lines):
search = re.findall('([\d*]?\.[\d*]?)+?[^dq\_]', line)
if search != []:
print('Real found in line #%d: ' %i)
print search
print('The following line:\n %s' %line)
print('will be replace by:')
newline = re.sub('([\d*]?\.[\d*]?)+?[^dq\_]', r'\g<1>d0\g<2>', line)
print('%s' %newline)
And the prec.f90 contains something like that (it is just an example, it does not means that all the strings I want to replace have the form [x]_[yz] = ...;):
x_pr = 0.1; y_pr = 0.2; z_pr = 0.1q0
x_sp = 0.1; y_sp = 0.1d0; z_sp = 0.1q0
x_dp = 0.1; y_dp = 0.1d0; z_dp = 0.1q0
x_qp = .1; y_qp = 0.1d0; z_qp = 0.1q0
x_db = 0.; y_db = 0.1d0; y_db = 0.1q0
My goal is to modify all the pattern like 0.1, .1 and 0., to get something like 0.1d0; I don't want to modify the other patterns. The problem is that re.findall('[\d*]?\.[\d*]?)+?([^dq\_]') matches the pattern I am looking for, but also returns an empty string for the other ones. Therefore, when I run this piece of code, it fails, being unable to replace match the first and second groups in the re.sub() for the empty strings.
I guess one solution would be to ignore empty string in the re.sub, or to have something like a conditional argument in it, but I could not figure out how.
Any help would be appreciated!
A:
I finally came up with this piece of code that is working as intended:
import re
fname = './prec.f90'
f = open(fname)
lines = f.readlines()
f.close()
# If there was no end of the line character (\n) we would need to check if
# this is the end of the line (something like ([^dq\_0-9]|$)
regex = re.compile(r'(\d*\.\d*)([^dq\_0-9])')
for i, line in enumerate(lines):
search = regex.findall(line)
if search != []:
print('Real found in line #%d: ' %i)
print search
print('The following line:\n %s' %line)
print('will be replace by:')
newline = regex.sub(r'\g<1>d0\g<2>', line)
print('%s' %newline)
I first came up with the more complicated regex ([\d*]?\.[\d*]?)+?[^dq\_] because else I always match the first part of any string ending with d, q or _. It seemed to be due to the fact that \d* was not greedy enough; to add 0-9 in the "ignore" set solves the problem.
|
[
"stackoverflow",
"0024809436.txt"
] | Q:
How can i link my jButtons to methods in other class in the same package
Actually I'm working on a game in java and I want to start new game when user would click on the jButton (New Game) that I've created in a class 'Window' under the same package which contains all my game components. Now I want to access the method 'newGame()' defined in class Framework in my buttonActionPerformed() method but without calling the constructor of framework.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Framework f = new Framework();
f.newGame();
}
I'm using this code but it is showing many errors because I have used
this.setContentPane(new Framework());
in the constructor of Window class .This is a part of my framework class
public class Framework extends Canvas {
public Framework ()
{
super();
gameState = GameState.VISUALIZING;
//We start game in new thread.
Thread gameThread = new Thread() {
@Override
public void run(){
GameLoop();
}
};
gameThread.start();
}
private void GameLoop()
{
long visualizingTime = 0, lastVisualizingTime = System.nanoTime();
// This variables are used for calculating the time that defines for how long we should put threat to sleep to meet the GAME_FPS.
long beginTime, timeTaken, timeLeft;
while(true)
{
beginTime = System.nanoTime();
switch (gameState)
{
case PLAYING:
gameTime += System.nanoTime() - lastTime;
game.UpdateGame(gameTime, mousePosition());
lastTime = System.nanoTime();
break;
case GAMEOVER:
//...
break;
case MAIN_MENU:
//...
break;
case OPTIONS:
//...
break;
case GAME_CONTENT_LOADING:
//...
break;
case STARTING:
// Sets variables and objects.
Initialize();
// Load files - images, sounds, ...
LoadContent();
// When all things that are called above finished, we change game status to main menu.
gameState = GameState.MAIN_MENU;
break;
case VISUALIZING:
if(this.getWidth() > 1 && visualizingTime > secInNanosec)
{
frameWidth = this.getWidth();
frameHeight = this.getHeight();
// When we get size of frame we change status.
gameState = GameState.STARTING;
}
else
{
visualizingTime += System.nanoTime() - lastVisualizingTime;
lastVisualizingTime = System.nanoTime();
}
break;
}
// Repaint the screen.
repaint(); // goes to paint component in canvas
timeTaken = System.nanoTime() - beginTime;
timeLeft = (GAME_UPDATE_PERIOD - timeTaken) / milisecInNanosec;
if (timeLeft < 10)
timeLeft = 10; //set a minimum
try {
Thread.sleep(timeLeft);
} catch (InterruptedException ex) { }
}
}
public void newGame()
{
// We set gameTime to zero and lastTime to current time for later calculations.
if(true)
{
BufferedImage blankCursorImg =
new BufferedImage(16, 16,BufferedImage.TYPE_INT_ARGB);
Cursor blankCursor =
Toolkit.getDefaultToolkit().createCustomCursor(blankCursorImg, new Point(0, 0), null);
this.setCursor(blankCursor);
}
gameTime = 0;
lastTime = System.nanoTime();
game = new Game();
}
}
And here is WindowForm.java which contains the main() and the jButtons
package helicopterbattle;
import javax.swing.JFrame;
public class WindowForm extends javax.swing.JFrame {
public WindowForm() {
this.setTitle("Helicopter battle");
if(true) // Full screen mode
{
this.setUndecorated(true);
this.setExtendedState(this.MAXIMIZED_BOTH);
}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates the instance of the Framework.java that extends the Canvas.java and puts it on the frame.
this.setContentPane(new Framework());
initComponents();
jButton1.setBounds(630,490,100,30);
jButton2.setBounds(630,540,100,30);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Framework f = new Framework();
f.newGame();
jButton1.setVisible(false);
jButton2.setVisible(false);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WindowForm().setVisible(true);
}
});
}
public javax.swing.JButton jButton1;
public javax.swing.JButton jButton2;
// End of variables declaration
}
Please help and thanks.
A:
If i understand correctly you want to call newGame() method without creating a new object from Framework class
I think you can achieve this by declare a final variable in WindowForm class before the constructor as follow
private final Framework myFramework = new Framework();
then pass it to setContentPane method
setContentPane(myFramework);
and use the same object inside jButton1ActionPerformed method
myFramework.newGame();
--
An alternative solution is using Singleton design pattern to create a static instance from Framework class and call Framework.getInstance() whenever you want
|
[
"serverfault",
"0000995980.txt"
] | Q:
Windows server 2019 install not showing GUI options
I've downloaded the latest ISO (December 2019) for Windows Server 2019. When I go to install on a new server the list of install options only includes the core non-GUI install options.
How do I install Windows Server 2019 with a GUI (desktop experience) option. All the website I view indicate that there should be four options in the dialog below, where I only see two.
A:
These days Windows server comes not only in different editions but also in different types:
Long-Term Servicing Channel - This is usually the initial release of a server, and it gets monthly security updates, but no new features. It also can not be freely upgraded to a newer version of the server as is the case for Windows 10 clients.
The current version is Windows Server 2019 - 1809
This version has both Server Core and full server (desktop experience).
Semi-Annual Channel
This has two releases each year, in 2019 it had versions 1903 and 1909
This type only comes with Core editions, no desktop experience. If you want a desktop you have to use the last Long-Term Servicing Channel version.
It seems you downloaded 1909 which is the latest Semi-Annual Channel and has no Desktop option.
|
[
"math.stackexchange",
"0001664608.txt"
] | Q:
Inequality with fractions
I have this inequality to solve:
1 / (2 - x) <= x
I worked out the critical values to be 1 and 2.
The answer is x > 2 or x = 1.
The problem I have is what is the inequality read >=
I would get the same critical values but different values for x, which satisfies the inequality. I noticed that with some working out methods, you can lose critical values in the process e.g.
if I did the inequality as follows:
1 / (2 - x) <= x
1 <= x(2 - x)
0 <= -x^2 + 2x - 1
0 <= (1 - x)^2
Hence, I end up with x = 1 being the only critical value.
Are there any rules for the working process for solving the inequality in this situation without losing critical values?
A:
This is occurring because the original function is not defined at $x=2$. Whenever you do a problem like this you need to treat points where the function is undefined (at any step of the manipulation) separately.
I would do the manipulation that you've shown, getting $(x-1)^2\geq 0$, and so $1$ is a point I need to investigate. Additionally, the original fraction was undefined at $x=2$, so I need to investigate that as well. I notice that the inequality holds for $1$ but not for $0.5\pm 1$, and that the inequality holds for $x>2$. Thus the critical points are $\{1,2\}$ and the solution set is $\{1\}\cup\{x\in\mathbb{R}|x>2\}$
|
[
"stackoverflow",
"0035414576.txt"
] | Q:
Multiple inheritance for R6 classes
Actual question
What are my options to workaround the fact that R6 does not support multiple inheritance?
Disclaimer
I know that R is primarily a functional language. However, it does also have very powerful object-orientation built in. Plus: I don't see what's wrong with mimicking OOD principles/behavior when you
know you're prototyping for an object-oriented language such as C#, Java, etc.
your prototypes of apps need to be self-sufficient ("full stack" including DB-backends, business logic and frontends/UI)
you have such great "prototyping technology" like R6 and shiny at your disposal
Context
My R prototypes for web apps need to be both "full stack"/self sufficient and as close as possible to design patterns/principles and dependency injection containers (proof of concept of simple DI in R) used in our production language (C#/.NET).
In that regard, I came to like the use of interfaces (or abstract classes) very much in order to decouple code modules and to comply with the D (dependency inversion principle) of the SOLID principles of OOD (detailed explanation by "Uncle Bob").
Even though R6 does not explicitly support interfaces, I can nevertheless perfectly mimick them with R6 classes that define nothing but "abstract methods" (see example below). This helps me a lot with communicating my software designs to our OO-programmers that aren't very familiar with R. I strive for as little "conceptional conversion effort" on their part.
However, I need to give up my value for inherit in R6Class for that which becomes a bit of a problem when I actually want to inherit from other concrete (as opposed to "abstract-like" mimicked interface classes) because this would mean to define not one but two classes in inherit.
Example
Before inversion of dependency:
Foo depends on concrete class Bar. From an OOD principles' view, this is pretty bad as it leads to code being tightly coupled.
Bar <- R6Class("Bar",
public = list(doSomething = function(n) private$x[1:n]),
private = list(x = letters)
)
Foo <- R6Class("Foo",
public = list(bar = Bar$new())
)
inst <- Foo$new()
> class(inst)
> class(inst$bar)
[1] "Bar" "R6"
After inversion of dependency:
Foo and Bar are decoupled now. Both depend on an interface which is mimicked by class IBar. I can decide which implementation of that interface I would like to plug in to instances of Foo at runtime (realized via Property Injection: field bar of Foo)
IBar <- R6Class("IBar",
public = list(doSomething = function(n = 1) stop("I'm the inferace method"))
)
Bar <- R6Class("Bar", inherit = IBar,
public = list(doSomething = function(n = 1) private$x[1:n]),
private = list(x = letters)
)
Baz <- R6Class("Baz", inherit = IBar,
public = list(doSomething = function(n = 1) private$x[1:n]),
private = list(x = 1:24)
)
Foo <- R6Class("Foo",
public = list(bar = IBar$new())
)
inst <- Foo$new()
inst$bar <- Bar$new()
> class(inst$bar)
[1] "Bar" "IBar" "R6"
> inst$bar$doSomething(5)
[1] "a" "b" "c" "d" "e"
inst$bar <- Baz$new()
[1] "Baz" "IBar" "R6"
> inst$bar$doSomething(5)
[1] 1 2 3 4 5
A bit mor on why this makes sense with regard to OOD: Foo should be completely agnostic of the the way the object stored in field bar is implemented. All it needs to know is which methods it can call on that object. And in order to know that, it's enough to know the interface that the object in field bar implements (IBar with method doSomething(), in our case).
Using inheritance from base classes to simplify design:
So far, so good. However, I'd also like to simplify my design by definining certain concrete base classes that some of my other concrete classes can inherit from.
BaseClass <- R6Class("BaseClass",
public = list(doSomething = function(n = 1) private$x[1:n])
)
Bar <- R6Class("Bar", inherit = BaseClass,
private = list(x = letters)
)
Baz <- R6Class("Bar", inherit = BaseClass,
private = list(x = 1:24)
)
inst <- Foo$new()
inst$bar <- Bar$new()
> class(inst$bar)
[1] "Bar" "BaseClass" "R6"
> inst$bar$doSomething(5)
[1] "a" "b" "c" "d" "e"
inst$bar <- Baz$new()
> class(inst$bar)
[1] "Baz" "BaseClass" "R6"
> inst$bar$doSomething(5)
[1] 1 2 3 4 5
Combining "interface implementation" and base clases inheritance:
This is where I would need multiple inheritance so something like this would work (PSEUDO CODE):
IBar <- R6Class("IBar",
public = list(doSomething = function() stop("I'm the inferace method"))
)
BaseClass <- R6Class("BaseClass",
public = list(doSomething = function(n = 1) private$x[1:n])
)
Bar <- R6Class("Bar", inherit = c(IBar, BaseClass),
private = list(x = letters)
)
inst <- Foo$new()
inst$bar <- Bar$new()
class(inst$bar)
[1] "Bar" "BaseClass" "IBar" "R6"
Currently, my value for inherit is already being used up "just" for mimicking an interface implementation and so I lose the "actual" benefits of inheritance for my actual concrete classes.
Alternative thought:
Alternatively, it would be great to explicitly support a differentiation between interface and concrete classes somehow. For example something like this
Bar <- R6Class("Bar", implement = IBar, inherit = BaseClass,
private = list(x = letters)
)
A:
For those interested:
I gave it a second thought and realized that's it's not really multiple inheritance per se that I want/need, but rather some sort of better mimicking the use of interfaces/abstract classes without giving up inherit for that.
So I tried tweaking R6 a bit so it would allow me to distinguish between inherit and implement in a call to R6Class.
Probably tons of reasons why this is a bad idea, but for now, it gets the job done ;-)
You can install the tweaked version from my forked branch.
Example
devtools::install_github("rappster/R6", ref = "feat_interface")
library(R6)
Correct implementation of interface and "standard inheritance":
IFoo <- R6Class("IFoo",
public = list(foo = function() stop("I'm the inferace method"))
)
BaseClass <- R6Class("BaseClass",
public = list(foo = function(n = 1) private$x[1:n])
)
Foo <- R6Class("Foo", implement = IFoo, inherit = BaseClass,
private = list(x = letters)
)
> Foo$new()
<Foo>
Implements interface: <IFoo>
Inherits from: <BaseClass>
Public:
clone: function (deep = FALSE)
foo: function (n = 1)
Private:
x: a b c d e f g h i j k l m n o p q r s t u v w x y z
When an interface is not implemented correctly (i.e. method not implemented):
Bar <- R6Class("Bar", implement = IFoo,
private = list(x = letters)
)
> Bar$new()
Error in Bar$new() :
Non-implemented interface method: foo
Proof of concept for dependency injection
This is a little draft that elaborates a bit on the motivation and possible implementation approaches for interfaces and inversion of dependency in R6.
A:
Plus: I don't see what's wrong with mimicking OOD principles/behavior when you know you're prototyping for an object-oriented language such as C#, Java, etc.
What’s wrong with it is that you needed to ask this question because R is simply an inadequate tool to prototype an OOD system, because it doesn’t support what you need.
Or just prototype those aspects of your solution which rely on data analysis, and don’t prototype those aspects of the API which don’t fit into the paradigm.
That said, the strength of R is that you can write your own object system; after all, that’s what R6 is. R6 just so happens to be inadequate for your purposes, but nothing stops you from implementing your own system. In particular, S3 already allows multiple inheritance, it just doesn’t support codified interfaces (instead, they happen ad-hoc).
But nothing stops you from providing a wrapper function that performs this codification. For instance, you could implement a set of functions interface and class (beware name clashes though) that can be used as follows:
interface(Printable,
print = prototype(x, ...))
interface(Comparable,
compare_to = prototype(x, y))
class(Foo,
implements = c(Printable, Comparable),
private = list(x = 1),
print = function (x, ...) base::print(x$x, ...),
compare_to = function (x, y) sign(x$x - y$x))
This would then generate (for instance):
print.Foo = function (x, ...) base::print(x$x, ...)
compare_to = function (x, y) UseMethod('compare_to')
compare_to.foo = function (x, y) sign(x$x - y$x)
Foo = function ()
structure(list(x = 1), class = c('Foo', 'Printable', 'Comparable'))
… and so on. In fact, S4 does something similar (but badly, in my opinion).
|
[
"stackoverflow",
"0027676328.txt"
] | Q:
Android threading, background process
I want to add the ipaddress on my Arraylist to update my listview which has its own adapter but i receive an error and it stops my app when it detects a server socket. this codes run on background which is scanning the ipaddress of a subnet and saving the address to PostList class.
public class MainActivity extends Activity {
ListView lv;
ArrayList<PostList> list;
ArrayAdapter<PostList> adapter;
int port = 50000;
String ipadd = "192.168.254.";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.iplist);
scanIP(ipadd,port);
}
private void scanIP(final String ipadd, final int port){
final Handler mHandler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 95; i < 105; i++){
final String ipaddress = ipadd + i;
try {
Socket socket = new Socket(ipaddress,port);
if (socket.isConnected()){
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
out.println("Hey Server im " + ipaddress);
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
insertValue(ipaddress);
}
});
}
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
private void insertValue(String ipaddress) {
// TODO Auto-generated method stub
list.add(new PostList(ipaddress));
adapter = new PostAdapter(MainActivity.this, list);
lv.setAdapter(adapter);
}
}
Logcat error, this error shows up when its get my server ip address
12-28 20:15:17.579: I/System.out(15675): [CDS]connect[/192.168.254.100:50000] tm:90
12-28 20:15:17.580: D/Posix(15675): [Posix_connect Debug]Process com.example.practice_socket :50000
12-28 20:15:17.586: D/ClientActivity(15675): C: Sending command.
12-28 20:15:17.587: D/ClientActivity(15675): C: Sent.
12-28 20:15:17.588: D/AndroidRuntime(15675): Shutting down VM
12-28 20:15:17.588: W/dalvikvm(15675): threadid=1: thread exiting with uncaught exception (group=0x411da9a8)
12-28 20:15:17.589: E/test(15675): Exception
12-28 20:15:17.590: E/AndroidRuntime(15675): FATAL EXCEPTION: main
12-28 20:15:17.590: E/AndroidRuntime(15675): java.lang.NullPointerException
12-28 20:15:17.590: E/AndroidRuntime(15675): at com.example.practice_socket.MainActivity.insertValue(MainActivity.java:95)
12-28 20:15:17.590: E/AndroidRuntime(15675): at com.example.practice_socket.MainActivity.access$0(MainActivity.java:93)
12-28 20:15:17.590: E/AndroidRuntime(15675): at com.example.practice_socket.MainActivity$1$1.run(MainActivity.java:74)
12-28 20:15:17.590: E/AndroidRuntime(15675): at android.os.Handler.handleCallback(Handler.java:725)
12-28 20:15:17.590: E/AndroidRuntime(15675): at android.os.Handler.dispatchMessage(Handler.java:92)
12-28 20:15:17.590: E/AndroidRuntime(15675): at android.os.Looper.loop(Looper.java:153)
12-28 20:15:17.590: E/AndroidRuntime(15675): at android.app.ActivityThread.main(ActivityThread.java:5299)
12-28 20:15:17.590: E/AndroidRuntime(15675): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 20:15:17.590: E/AndroidRuntime(15675): at java.lang.reflect.Method.invoke(Method.java:511)
12-28 20:15:17.590: E/AndroidRuntime(15675): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-28 20:15:17.590: E/AndroidRuntime(15675): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-28 20:15:17.590: E/AndroidRuntime(15675): at dalvik.system.NativeStart.main(Native Method)
A:
Make sure you have instantiated your list object before you call list.add():
list = new ArrayList<PostList>();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.