id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23529900
|
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
In there it defines a constructor as:
var Person = function(firstName) {
this.firstName = firstName;
}
and
function Student(firstName, subject) {
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
}
Why is the Student constructor not defined as:
var Student = function(firstName, subject) {
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
}
| |
doc_23529901
|
I'm using .Net Framework 4.8, WinForms, Visual Studio 2019, C#.
In my Program.cs file I have written this code.
using System;
using System.IO;
using System.Windows.Forms;
namespace newApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
string location = Application.StartupPath.ToString() + "\\files\\xyz.txt"; //change file name//
if (File.Exists(location))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Signin());
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new createnewuser());
}
}
}
}
But whenever I try to enter a some text in Create a new user form it gives error saying Parameter is not valid.
Error details:
System.ArgumentException
HResult=0x80070057
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.get_Flags()
at System.Windows.Forms.ControlPaint.IsImageTransparent(Image backgroundImage)
at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor, Point scrollOffset)
at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle)
at System.Windows.Forms.Control.OnPaintBackground(PaintEventArgs pevent)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
A: Most probably, there is something wrong with the code in 'Form1'.
Something is going wrong maybe in the OnPaint event(are you using it?) of Form1.
Or some third party tool is passing invalid arguments(are you using that?).
| |
doc_23529902
|
var suggests = ["Action", "ActionScript", "Borland"];
But I need words list from the database. When i get list from database, plugin does not respond. Here is what I am doing:-
Plugin I am using:-
https://github.com/imankulov/asuggest/
Jquery:-
$(document).ready(function() {
var suggests = getList();
var $txt = $('#<%=txtArea.ClientID %>');
$txt.asuggest(suggests);
});
function getList() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajaxService.asmx/autocompletelist",
data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
dataType: "json",
success: function(data) {
return (data.d);
},
error: function(result) {
alert("No Match");
}
});
}
code behind:-
[WebMethod]
public List<string> autocompletelist(int groupUid, int clientUid)
{
//call to database for the list.
//code/
List<string> result = new List<string>();
result.Add("Action");
result.Add("ActionScript");
result.Add("Borland");
return result;
}
Please suggest? Is it something to do with square brackets? How to get that in return from database?
A: An ajax success function is executed asynchronously (it doesn't get fired until a response is received), but you're trying to use its result in a synchronous fashion. So when you call $txt.asuggest(suggests);, nothing happens because suggests has not been populated yet. This is because the ajax request hasn't finished, but your code doesn't know that. The simplest way to fix this is to put the logic for the UI in the success method itself. That way your plugin wont be called until the suggests variable is guaranteed to be populated. Try this:
$(document).ready(function() {
getList();
});
function getList() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajaxService.asmx/autocompletelist",
data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
dataType: "json",
success: function(data) {
var $txt = $('#<%=txtArea.ClientID %>');
$txt.asuggest(data);
},
error: function(result) {
alert("No Match");
}
});
}
A: You can first do it like this alert(suggests),check whether the result was correct,then convert the result to array.
convert json to array:
var dataArray=eval(jsonStr);
for(var i in dataArray)
{
//TODO
}
| |
doc_23529903
|
I tried to log it and this fault is made before email is send to SMTP server. So i think it could be any problem with Heroku server charset setting.
Does anyone have had simillar problem ?
My class:
public Task SendEmailAsync(string SendTo, string subject, string body)
{
using SmtpClient smtpClient = new SmtpClient()
{
Host = "email.active24.com",
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("info@xxx.cz", "xxx")
};
MailMessage message = new MailMessage();
message.From = new MailAddress("info@xxx.cz");
message.To.Add(SendTo);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = $"<h1>{body}</h1>";
message.HeadersEncoding = Encoding.Default;
message.BodyEncoding = Encoding.Default;
message.SubjectEncoding = Encoding.Default;
logger.Info(message.Body);
try
{
smtpClient.Send(message);
}
catch (Exception ex)
{
//TODO handle error
}
return Task.CompletedTask;
}
Thank you in advance :-)
| |
doc_23529904
|
Ok. When I make a button I can add 'markup=1', but it doesn't work with TextInput or same.
Versions: Python 3.7, Kivy 1.10.1, Win7
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
return Button(text = "Hello!",
font_size = 100,
background_color = [.5, 1, 1, 1])
if __name__ == "__main__":
MyApp().run()
Results:
Without markup:
Same code, but using markup:
#Another example:
from kivy.app import App
from kivy.uix.textinput import TextInput
class MyApp(App):
def build(self):
return TextInput(font_size = 25)
if __name__ == "__main__":
MyApp().run()
Result:
Another example rezult:
Log:
| |
doc_23529905
|
<telerik:RadGridView x:Name="xRadGridView"
prismcommands:SelectionChangedCommand.Command="{Binding SelectPersonCommand}"
ItemsSource="{Binding GridItems, Mode=TwoWay}">
</telerik:RadGridView>
I get the error:
'SelectionChangedCommand.Command' property is read-only and cannot be
set from markup.
I can bind to prismcommands:RowEditEndedCommand.Command with no problem.
Is there any chance to bind to SelectionChangedCommand.Command?
I use the same PrismCommands in a Silverlight project and it works there.
namespace RadEventToCommand.WPF.PrismCommands
{
public class RowEditEndedCommandBehavior : CommandBehaviorBase<RadGridView>
{
public RowEditEndedCommandBehavior(RadGridView gridView)
: base(gridView)
{
gridView.RowEditEnded +=new EventHandler<GridViewRowEditEndedEventArgs>(gridView_RowEditEnded);
}
void gridView_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
{
CommandParameter = e;
ExecuteCommand();
}
}
}
--
namespace RadEventToCommand.WPF.PrismCommands
{
public static class SelectionChangedCommand
{
private static readonly DependencyProperty SelectionChangedCommandBehaviorProperty
= DependencyProperty.RegisterAttached(
"SelectionChangedCommandBehavior",
typeof(SelectionChangedCommandBehavior),
typeof(SelectionChangedCommand),
null);
public static readonly DependencyProperty CommandProperty
= DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(SelectionChangedCommand),
new PropertyMetadata(OnSetCommandCallback));
public static readonly DependencyProperty CommandParameterProperty
= DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(SelectionChangedCommand),
new PropertyMetadata(OnSetCommandParameterCallback));
public static ICommand GetCommand(RadGridView gridView)
{
return gridView.GetValue(CommandProperty) as ICommand;
}
public static void SetCommandParameter(RadGridView gridView, object parameter)
{
gridView.SetValue(CommandParameterProperty, parameter);
}
public static object GetCommandParameter(RadGridView gridView)
{
return gridView.GetValue(CommandParameterProperty);
}
private static void OnSetCommandCallback
(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
RadGridView gridView = dependencyObject as RadGridView;
if (gridView != null)
{
SelectionChangedCommandBehavior behavior = GetOrCreateBehavior(gridView);
behavior.Command = e.NewValue as ICommand;
}
}
private static void OnSetCommandParameterCallback
(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
RadGridView gridView = dependencyObject as RadGridView;
if (gridView != null)
{
SelectionChangedCommandBehavior behavior = GetOrCreateBehavior(gridView);
behavior.CommandParameter = e.NewValue;
}
}
private static SelectionChangedCommandBehavior GetOrCreateBehavior(RadGridView gridView)
{
SelectionChangedCommandBehavior behavior =
gridView.GetValue(SelectionChangedCommandBehaviorProperty) as SelectionChangedCommandBehavior;
if (behavior == null)
{
behavior = new SelectionChangedCommandBehavior(gridView);
gridView.SetValue(SelectionChangedCommandBehaviorProperty, behavior);
}
return behavior;
}
}
}
--
namespace RadEventToCommand.WPF.PrismCommands
{
public class RowEditEndedCommandBehavior : CommandBehaviorBase<RadGridView>
{
public RowEditEndedCommandBehavior(RadGridView gridView)
: base(gridView)
{
gridView.RowEditEnded +=new EventHandler<GridViewRowEditEndedEventArgs>(gridView_RowEditEnded);
}
void gridView_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
{
CommandParameter = e;
ExecuteCommand();
}
}
}
--
namespace RadEventToCommand.WPF.PrismCommands
{
public static class RowEditEndedCommand
{
private static DependencyProperty RowEditEndedCommandBehaviorProperty
= DependencyProperty.RegisterAttached(
"RowEditEndedCommandBehavior",
typeof(RowEditEndedCommandBehavior),
typeof(RowEditEndedCommand),
null);
public static DependencyProperty CommandProperty
= DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(RowEditEndedCommand),
new PropertyMetadata(OnSetCommandCallback));
public static DependencyProperty CommandParameterProperty
= DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(RowEditEndedCommand),
new PropertyMetadata(OnSetCommandParameterCallback));
public static ICommand GetCommand(RadGridView gridView)
{
return gridView.GetValue(CommandProperty) as ICommand;
}
public static void SetCommand(RadGridView gridView, object parameter)
{
gridView.SetValue(CommandProperty, parameter);
}
public static void SetCommandParameter(RadGridView gridView, object parameter)
{
gridView.SetValue(CommandParameterProperty, parameter);
}
public static object GetCommandParameter(RadGridView gridView)
{
return gridView.GetValue(CommandParameterProperty);
}
private static void OnSetCommandCallback
(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
RadGridView gridView = dependencyObject as RadGridView;
if (gridView != null)
{
RowEditEndedCommandBehavior behavior = GetOrCreateBehavior(gridView);
behavior.Command = e.NewValue as ICommand;
}
}
private static void OnSetCommandParameterCallback
(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
RadGridView gridView = dependencyObject as RadGridView;
if (gridView != null)
{
RowEditEndedCommandBehavior behavior = GetOrCreateBehavior(gridView);
behavior.CommandParameter = e.NewValue;
}
}
private static RowEditEndedCommandBehavior GetOrCreateBehavior(RadGridView gridView)
{
RowEditEndedCommandBehavior behavior =
gridView.GetValue(RowEditEndedCommandBehaviorProperty) as RowEditEndedCommandBehavior;
if (behavior == null)
{
behavior = new RowEditEndedCommandBehavior(gridView);
gridView.SetValue(RowEditEndedCommandBehaviorProperty, behavior);
}
return behavior;
}
}
}
A: I had the source for the behavior copied over from a Silverlight project. It worked there. For some reason in WPF I need the additional method in SelectionChangedCommand
public static void SetCommand(RadGridView gridView, object parameter)
{
gridView.SetValue(CommandProperty, parameter);
}
I copied the code over to check if I could use a common codebase for Silverlight and WPF.
A: For the RadGridView, we are using the Interaction Triggers. The below code works for us.
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
| |
doc_23529906
|
Let's say I want to count how many instances of "foo:[*whatever*]*whatever else*" exist in a folder; I'd do:
grep -or 'foo:[(.*)]' * | wc -l
and I'd get back "55" (or whatever the count is). But what if I have a file like:
foo:bar abcd
foo:baz efgh
not relevant line
foo:bar xyz
and I want to get count how many instances of foo:bar vs. how many of foo:bazs, etc.? In other words, I'd like output that's something like:
bar 2
baz 1
I assume there's some way to chain greps, or use a different command from wc, but I have no idea what it is ... any shell scripting experts out there have any suggestions?
P.S. I realize that if I knew the set of possible sub-strings (ie. if I knew there was only "foo:bar" and "foo:baz") this would be simpler, but unfortunately there set of "things that can come after foo:" is unknown.
A: You could use sort and uniq -c:
$ grep -orE 'foo:(.*)' * | sort | uniq -c
2 foo:bar
1 foo:baz
| |
doc_23529907
|
Currently, I managed to get haproxy to work with the following configuration:
defaults
log 127.0.0.1 local0
option tcplog
frontend ft_test
mode http
bind 0.0.0.0:8443 ssl crt haproxy.pem
timeout client 120000ms
default_backend bk
backend bk
mode http
cookie JSESSIONID prefix
server s1 vm1:80 cookie JSESSIONID_SERVER_1 check maxconn 32
server s2 vm2:80 cookie JSESSIONID_SERVER_2 check maxconn 32
timeout connect 5000ms
timeout server 120000ms
haproxy.pem is a file I copied from here (for testing purposes): http://blog.exceliance.fr/2012/09/04/howto-ssl-native-in-haproxy/
When I change the port from 80 to 8443 on the VMs, and I try to access https://haproxy.vm.ip:8443 (same as I did with the 80 port), I get a: 502 Bad Gateway error in my browser.
I'm guessing this has something to do with the ssl certificates, but I'm not sure how to solve this (these issues are new to me, and I wasn't able to find much information).
The server.xml for each tomcat VM (they're the same):
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="${catalina.home}/conf/keystore"
keystorePass="password" />
Do I need to use the same certificate here as in the haproxy configuration? I tried that but it doesn't seem to work, and I didn't find an example for haproxy with a keystore file either.
So, help? Ideas? Thanks! :)
A: Had the same issue -
I was never able to get 1.5 to correctly and consistently process SSL traffic without receiving intermittent 502's and 503's.
We ended up using stunnel - http://www.stunnel.org/
Very simple to setup and configure. HAproxy just responds on port 80 and forwards over 443 so that internal traffic remains encrypted.
Here's a sample stunnel.conf file to start from:
sslVersion = all
options = NO_SSLv2
cert=/etc/stunnel/wildcard.pem
setuid = root
setgid = root
pid = /var/run/stunnel.pid
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
output = /var/log/stunnel.log
[service1]
accept = 10.0.0.10:443
connect = 10.0.0.10:80
TIMEOUTclose = 0
[service2]
accept = 10.0.0.11:443
connect = 10.0.0.11:80
TIMEOUTclose = 0
| |
doc_23529908
|
p_text <- qplot(data = mtcars, x = hp, y = disp) +
theme(axis.text.x = element_blank())
p_text + theme(axis.text.x = element_text(colour = "red"))
Similarly, one would expect this code to do the same thing for the grid lines:
p_grid <- qplot(data = mtcars, x = hp, y = disp) +
theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "red"))
However, it only appears to add them back with default colors. Why this strange behavior, and is there a way to add the panel grid lines back in? (My actual example involves overriding various pre-set themes, so just setting the grid lines right away is not an option).
A: If you look at theme_grey you can see that panel.grid.minor and panel.grid.major are both specified. When you specify panel.grid to a specific color, the minor and major grid lines would inherit this if a color wasn't specified for them. But there is.
This works as expected:
p_grid <- qplot(data = mtcars, x = hp, y = disp) +
theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "blue"), #needed to overwrite element_blank
panel.grid.major = element_line(colour = "red"),
panel.grid.minor = element_line(colour = "red"))
and this too:
p_grid + theme(panel.grid = element_line(colour = "red"),
panel.grid.major = NULL,
panel.grid.minor = NULL)
| |
doc_23529909
|
class A {
private:
int x1;
int x2;
....
int xn;
}
I want share some group attributes with other class. Example class B, class C, ... that class B can access x1, x3 for set/get, class C can access x1, x2, xn for set/get.
My solution:
Solution 1: class A is singleton. If class B or class C want to set/get attribute in class A use A::GetInstance() (for example) to set/get attribute. With this solution, you don't care what attribute that class B (or class C) is shared. With my opinion, using singleton must be careful with multi-thread problem.
Solution 2 I use class to shared.
Example
class SharedB {
public
int x1;
int x3;
}
class SharedC {
public
int x1;
int x2;
int xn;
}
class SharedB and class SharedC also will be singleton that class B and class C can use. The advantage of this solution that is i can control what i share. But disadvantage is also use singleton that i think not safe with multi-thread.
So my question is have solution for my problem that's better and thread-safe.
Thank for your answer.
| |
doc_23529910
|
Suppose I have an object with two methods: Delete() and SubmitChanges(). Would it be wise of me to new up the Linq to SQL class in each of the methods, or would a private variable holding the Linq to SQL class - new'ed up by the constructor - be the way to go?
What I'm trying to avoid is a time-out.
UPDATE:
namespace Madtastic
{
public class Comment
{
private Boolean _isDirty = false;
private Int32 _id = 0;
private Int32 _recipeID = 0;
private String _value = "";
private Madtastic.User _user = null;
public Int32 ID
{
get
{
return this._id;
}
}
public String Value
{
get
{
return this._value;
}
set
{
this._isDirty = true;
this._value = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public Comment()
{
}
public Comment(Int32 commentID)
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment != null)
{
this._id = comment.CommentsID;
this._recipeID = comment.RecipesID;
this._value = comment.CommentsValue;
this._user = new User(comment.UsersID);
}
mdc.Dispose();
}
public void SubmitChanges()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null && this._isDirty)
{
comment.CommentsValue = this._value;
}
else
{
Madtastic.Entities.Comment c = new Madtastic.Entities.Comment();
c.RecipesID = this._recipeID;
c.UsersID = this._user.ID;
c.CommentsValue = this._value;
mdc.Comments.InsertOnSubmit(c);
}
mdc.SubmitChanges();
mdc.Dispose();
}
public void Delete()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null)
{
mdc.Comments.DeleteOnSubmit(comment);
mdc.SubmitChanges();
this._isDirty = false;
this._id = 0;
this._recipeID = 0;
this._value = "";
this._user = null;
}
mdc.Dispose();
}
}
}
REFACTORED CODE (according to Grank's spec):
namespace Madtastic
{
public sealed class CommentNew : IDisposable
{
private Madtastic.DataContext _mdc;
private Madtastic.Entities.Comment _comment;
private Madtastic.User _user;
public Int32 ID
{
get
{
return this._comment.CommentsID;
}
}
public String Value
{
get
{
return this._comment.CommentsValue;
}
set
{
this._comment.CommentsValue = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public void Comment(Int32 commentID)
{
this._mdc = new Madtastic.DataContext();
this._comment = (from c in _mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (this._comment == null)
{
this._comment = new Madtastic.Entities.Comment();
this._mdc.Comments.InsertOnSubmit(this._comment);
}
else
{
this._user = new Madtastic.User(this._comment.User.UsersID);
}
}
public void SubmitChanges()
{
this._mdc.SubmitChanges();
}
public void Delete()
{
this._mdc.Comments.DeleteOnSubmit(this._comment);
this.SubmitChanges();
}
void IDisposable.Dispose()
{
this._mdc.Dispose();
}
}
}
A: Depends on to what you refer by a "LINQ-to-SQL class", and what the code in question looks like.
If you're talking about the DataContext object, and your code is a class with a long lifetime or your program itself, I believe it would be best to initialize it in the constructor. It's not really like creating and/or opening a new SqlConnection, it's actually very smart about managing its database connection pool and concurrency and integrity so that you don't need to think about it, that's part of the joy in my experience so far with LINQ-to-SQL. I've never seen a time-out problem occur.
One thing you should know is that it's very difficult to share table objects across DataContext scope, and it's really not recommended if you can avoid it. Detach() and Attach() can be bitchy. So if you need to pass around a LINQ-to-SQL object that represents a row in a table on your SQL database, you should try to design the life cycle of the DataContext object to encompass all the work you need to do on any object that comes out of it.
Furthermore, there's a lot of overhead that goes into instantiating a DataContext object, and a lot of overhead that is managed by it... If you're hitting the same few tables over and over it would be best to use the same DataContext instance, as it will manage its connection pool, and in some cases cache some things for efficiency. However, it's recommended to not have every table in your database loaded into your DataContext, only the ones you need, and if the tables being accessed are very separate in very separate circumstances, you can consider splitting them into multiple DataContexts, which gives you some options on when you initialize each one if the circumstances surrounding them are different.
A: Having now reviewed the code sample you edited to post, I would definitely refactor your class to take advantage of LINQ-to-SQL's built in functionality. (I won't edit my previous comment because it's a better answer to the general question)
Your class's fields appear to be a pretty direct mapping of the columns on the Comments table in the database. Therefore you don't need to do most of what you're doing manually in this class. Most of the functionality could be handled by just having a private member of type Madtastic.Entities.Comment (and just mapping your properties to its properties if you have to maintain how this class interacts with the rest of the project). Then your constructor can just initialize a private member Madtastic.DataContext and set your private member Madtastic.Entities.Comment to the result of the LINQ query on it. If the comment is null, create a new one and call InsertOnSubmit on the DataContext. (but it doesn't make sense to submit changes yet because you haven't set any values for this new object anyway)
In your SubmitChanges, all you should have to do is call SubmitChanges on the DataContext. It keeps its own track of whether or not the data needs to be updated, it won't hit the database if it doesn't, so you don't need _isDirty.
In your Delete(), all you should have to do is call DeleteOnSubmit on the DataContext.
You may in fact find with a little review that you don't need the Madtastic.Comment class at all, and the Madtastic.Entities.Comment LINQ-to-SQL class can act directly as your data access layer. It seems like the only practical differences are the constructor that takes a commentID, and the fact that the Entities.Comment has a UsersID property where your Madtastic.Comment class has a whole User. (However, if User is also a table in the database, and UsersID is a foreign key to its primary key, you'll find that LINQ-to-SQL has created a User object on the Entities.Comment object that you can access directly with comment.User)
If you find you can eliminate this class entirely, it might mean that you can further optimize your DataContext's life cycle by bubbling it up to the methods in your project that make use of Comment.
Edited to post the following example refactored code (apologies for any errors, as I typed it in notepad in a couple seconds rather than opening visual studio, and I wouldn't get intellisense for your project anyway):
namespace Madtastic
{
public class Comment
{
private Madtastic.DataContext mdc;
private Madtastic.Entities.Comment comment;
public Int32 ID
{
get
{
return comment.CommentsID;
}
}
public Madtastic.User Owner
{
get
{
return comment.User;
}
}
public Comment(Int32 commentID)
{
mdc = new Madtastic.DataContext();
comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment == null)
{
comment = new Madtastic.Entities.Comment();
mdc.Comments.InsertOnSubmit(comment);
}
}
public void SubmitChanges()
{
mdc.SubmitChanges();
}
public void Delete()
{
mdc.Comments.DeleteOnSubmit(comment);
SubmitChanges();
}
}
}
You will probably also want to implement IDisposable/using as a number of people have suggested.
A: I assume that you mean holding a value for the DataContext class? Personally, my preference is to default to a "using" clause for anything that is IDisposable (which the DataContext classes are). Instantiating in the constructor and holding a DataContext in a private variable would make that impossible. So to me, I'd put the instantiation in the methods, but more specifically, I'd put instantiation in a using clause so that proper disposal is insured.
A: One of my current projects uses Linq to SQL where we're holding the datacontext as a private field inside of the object. Doing so hasn't been troublesome for the most part, allows for future mocking if I pass in a datacontext in the constructor, and just seems cleaner than opening up multiple datacontexts. Similar to what Jacob mentioned above, we're implementing IDisposable to make sure that the datacontext can reliably be closed down when the object is no longer needed.
A: SqlConnections are pooled by default. You should new them up a bunch to justify that pooling cost!
DataContexts are cheap to make (after the first). You should new them up a bunch to justify that first new-up cost!
| |
doc_23529911
|
Here it is :
SELECT
p.id,
UNIX_TIMESTAMP(p.last_answer_date) AS last_answer_date_timestamp,
p.sender_id,
p.recipient_id,
p.is_read_sender,
p.last_answer_user_id,
p.is_read_recipient,
(SELECT m.read FROM pm_message m WHERE m.conv_id = p.id AND m.user_id != $user_id ORDER BY m.date DESC LIMIT 1) AS read_status,
(SELECT m.content FROM pm_message m WHERE m.conv_id = p.id ORDER BY m.date DESC LIMIT 1) AS last_message,
(SELECT u.username FROM user u WHERE (u.id = p.sender_id OR u.id = p.recipient_id) AND u.id != $user_id LIMIT 1) AS from_username,
(SELECT u.id FROM user u WHERE (u.id = p.sender_id OR u.id = p.recipient_id) AND u.id != $user_id LIMIT 1) AS from_userid,
(SELECT ui.gender FROM user_info ui WHERE (ui.user_id = p.sender_id OR ui.user_id = p.recipient_id) AND ui.user_id != $user_id LIMIT 1) AS from_gender,
(SELECT ph.thumb_url FROM photo ph, user_info ui WHERE ui.main_photo = ph.id AND (ph.user_id = p.sender_id OR ph.user_id = p.recipient_id) AND ph.user_id != $user_id LIMIT 1) AS from_thumb_url
FROM pm_conv p
WHERE p.sender_id = $user_id OR p.recipient_id = $user_id
ORDER BY p.last_answer_date DESC LIMIT 25;
This query gets me the result I want but it's really slow... And I think that the nested selects is the reason why this query is so slow.
Here are the tables structures for this query :
CREATE TABLE IF NOT EXISTS `photo` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`url` varchar(255) DEFAULT NULL,
`thumb_url` varchar(255) DEFAULT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`status` int(11) NOT NULL,
`votes` int(11) DEFAULT '0',
`comments` int(11) DEFAULT '0',
`views` int(11) DEFAULT '0',
`text` text,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `pm_conv` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`sender_id` int(11) NOT NULL,
`recipient_id` int(11) NOT NULL,
`last_answer_date` datetime NOT NULL,
`nb_messages` int(11) NOT NULL,
`is_read_sender` int(11) NOT NULL,
`is_read_recipient` int(11) NOT NULL DEFAULT '0',
`last_answer_user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `recipient_id` (`recipient_id`),
KEY `sender_id` (`sender_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `pm_message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`content` text NOT NULL,
`user_id` int(11) NOT NULL,
`conv_id` int(11) NOT NULL,
`read` int(11) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `conv_id` (`conv_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`encrypt_id` varchar(255) DEFAULT NULL,
`register_date` datetime DEFAULT NULL,
`last_login_date` datetime DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`banned` int(11) DEFAULT NULL,
`banned_reason` text,
`first_step_form` int(11) DEFAULT '0',
`status` int(11) DEFAULT NULL,
`valid_snapchat` int(11) DEFAULT '0',
`introduced_forum` int(11) DEFAULT '0',
`referer` varchar(255) DEFAULT NULL,
`allow_social_featuring` int(11) DEFAULT NULL,
`rank` int(11) DEFAULT NULL,
`fb_id` bigint(20) DEFAULT NULL,
`rate_app_status` int(11) DEFAULT NULL,
`last_activity_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `user_info` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`gender` int(11) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`about` text,
`main_photo` int(11) DEFAULT NULL,
`country` varchar(100) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL,
`relation_type` varchar(30) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`fb_link` varchar(255) DEFAULT NULL,
`twitter_link` varchar(255) DEFAULT NULL,
`youtube_link` varchar(255) DEFAULT NULL,
`instagram_link` varchar(255) DEFAULT NULL,
`app_pref_forum` int(11) DEFAULT NULL,
`app_pref_pm` int(11) DEFAULT NULL,
`app_pref_snapchat_request` int(11) DEFAULT NULL,
`browse_invisibly` int(11) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `main_photo` (`main_photo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Can someone help me to optimize this heavy query?
Thanks!
A: you can see in the explain plan some tables are being accessed by inefficient indexes. try to calculate statistics on all the tables to see if it changes something (using analyze table).
A: You can join user table in order to get username and id at once instead of having two subqueries, probably you can do the same with pm_message, but it's a little trickier since subqueries have different conditions.
I would also combine user and user_info tables into, as I can see they have one-to-one relation, so it doesn't makes sense to store this data in different tables. This would allow you to get rid off 4th subquery and simplify the 5th one.
In some cases it is better to perform several queries instead of one with subqueries.
| |
doc_23529912
|
A: Make sure meta charset is "UTF-8" in the head.
A: There’s one thing that resolves the issue.
*
*Open settings.
*Search for ‘autosave’.
*Set it to ‘afterDelay’.
*Just below that, set the AutoSaveDelay to anything very less like 5 (I have set it to 1)
*Now search for ‘Wait’ in settings.
*In LiveServer > Settings:Wait, set the value very low (e.g. 3). This should help regardless of platforms
| |
doc_23529913
|
I'm planning to do it for two folders and compare the 2 output txt to see if they're identical.
For now I tried that :
@echo off
for /R "F:\Folder1\MyFolder\" %A in (*.*) do echo %~pnA %~zA > output.txt
But for now it seems the recursivity doesn't work in my case cause I obtain :
\Folder\MyFolder\MyFile 23617195
A: try to append the result:
for /R "F:\Folder1\MyFolder\" %A in (*.*) do echo %~pnA %~zA >> output.txt
A: You can also try something like that if you want :
@echo off
Set LogFile=Path_Size.txt
if exist %LogFile% Del %LogFile%
Set Folder=c:\test
(
for /f %%a in ('dir /s /b %Folder%') do (
echo "%%~fa" & Call:GetSize %%a & echo ******************
)
)>>%LogFile% 2>nul
Start "" %LogFile%
pause
:GetSize
(
echo wscript.echo GetSize("%~1"^)
echo Function GetSize(MyFile^)
echo Set fso = CreateObject("Scripting.FileSystemObject"^)
echo Set objFile= fso.GetFile(MyFile^)
echo GetSize = FormatSize(objFile.Size^)
echo End Function
echo '*******************************************************************
echo 'Function to format a number into typical size scales
echo Function FormatSize(iSize^)
echo aLabel = Array("bytes", "KB", "MB", "GB", "TB"^)
echo For i = 0 to 4
echo If iSize ^> 1024 Then
echo iSize = iSize / 1024
echo Else
echo Exit For
echo End If
echo Next
echo FormatSize = Round(iSize,2^) ^& " " ^& aLabel(i^)
echo End Function
echo '*******************************************************************
)>%tmp%\Size.vbs
Cscript /NoLogo %tmp%\Size.vbs
Del %tmp%\Size.vbs
Exit /b
| |
doc_23529914
|
The contents of the file are uploaded to OneDrive without any corruption, but the file name is always "file.extension".
Any type of file brought the same result.
When I check the Operation of Integromat, I found that the file name is "file.extension" at the time of Output of Get a file.
I'm hoping you can point out what I'm doing wrong.
In addition, my colleague tried uploading a file with the same settings as above, and it was successfully uploaded with the correct file name.
Thank you.
A: One way would be to grab the file name from the URL. (I don't have enough reputation to embed images as yet, so hopefully the links will work)
Steps involved might look like this:
Step 1
Step 2
Step 3
Step 4
| |
doc_23529915
|
List<Customer> customers=new List<Customer>();
customers.Add(customer);
DataTable dt = new DataTable();
DataColumn col0= new DataColumn("Customer Id",typeof(int));
DataColumn col1 = new DataColumn("Name", typeof(string));
DataColumn col2 = new DataColumn("Address", typeof(string));
DataColumn col3 = new DataColumn("City", typeof(string));
DataColumn col4 = new DataColumn("State", typeof(string));
DataColumn col5 = new DataColumn("ZipCode", typeof(string));
dt.Columns.Add(col0);
dt.Columns.Add(col1);
dt.Columns.Add(col2);
dt.Columns.Add(col3);
dt.Columns.Add(col4);
dt.Columns.Add(col5);
int i = 0;
foreach (Customer item in customers)
{
DataRow drow = dt.NewRow();
dt.Rows.Add(drow);
dt.Rows[i][col0] = Convert.ToInt32(item.CustomerID);
dt.Rows[i][col1] = item.Name.ToString();
dt.Rows[i][col2] = item.Address.ToString();
dt.Rows[i][col3] = item.City.ToString();
dt.Rows[i][col4] = item.State.ToString();
dt.Rows[i][col5] = item.ZipCode.ToString();
i++;
}
grvCustomer.Visible = true;
grvCustomer.DataSource = dt;
A: The exception is usually raised by the gridview in order to prevent an infinite loop from occurring.
The cause of this is usually one of the following:
*
*Changing the active cell while an operation is being performed on the currently-active cell
*Beginning, ending or cancelling edit mode while a cell edit is
already in-progress
*Any other operation that results in the active cell being changed
while the DataGridView is still using it
Have a look at your handler for the CellValueChanged event and make sure you are not doing any of the above within the handler.
a quick workaround can be use the BeginInvoke. BeginInvoke is an asynchronous call, so gridview change/edit event returns immediately, and the method is executed after that, at that time gridview is no longer using the currently active cell.
this.BeginInvoke(new MethodInvoker(() =>
{
//do something
}));
| |
doc_23529916
|
How do I set this variable? What steps do I need to take? (I've tried searching around for this on Google, but I'm having issues finding anything useful)
A: I think you are trying to store max(date_col) value into a variable.
And I think below statement should work:
SELECT @variable = MAX(date_col) FROM some_table
| |
doc_23529917
|
A: I'm afraid that is not possible directly in SmartGWT. We had a need for custom events too, but having searched for solution for a couple of days we found out it is not possible and had to come up with a different design.
| |
doc_23529918
|
A: You cannot just copy and paste equation (3) as is. What is needed to comply with the matlab syntax is adding parenthesis:
sin(x)^2 + 3 * cos(x)^2
| |
doc_23529919
|
<Drawer_System_1>
<DrawerSystemID>1</DrawerSystemID>
<DrawerSysName>Drawer_System_1</DrawerSysName>
<DrawerSysLocation>North Wall (2nd from left)</DrawerSysLocation>
<Drawers>
<DrawerID>1-01</DrawerID>`enter code here`
<Contents>Contents of Drawer 1-01</Contents>
</Drawers>
<Drawers>
<DrawerID>1-02</DrawerID>
<Contents>Contents of Drawer 1-02</Contents>
</Drawers>
</Drawer_System_1>
My Question
How do I retrieve the values of child and parent XML nodes simultaneously?
I have populated a TreeView control with my XML file, and I want to retrieve certain values (as Strings) between nodes and subnodes as I select them in the control.
My Expected Results
If I select the Drawer_System_1 node or any subnode, I want to retrieve the values between the DrawerSystemID, DrawerSysName, and DrawerSysLocation nodes.
If I select a Drawers node or any subnode, I want to keep the previously mentioned values and also retrieve the values of the DrawerID and Contents nodes.
The value of each node should be displayed in an individual label, but if it's easier to display my requested data in a multi-line text box (or label), that's fine too.
Notes
I am using VB.NET, but if you can think of a solution in C#, that's fine too--I should be able to convert the answer into VB using an online converter.
If necessary, I can re-structure my XML file to make it easier for my program to read.
EDIT: Here's my code so far:
Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Public Class My_LEGO_Elements
Private Sub My_LEGO_Elements_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim serializer As New SimpleXmlSerializer()
Dim data As LEGOElementsData = serializer.DeSerialize(Of LEGOElementsData)(File.ReadAllText("C:\Users\Steven\Documents\Visual Studio 2012\Projects\My_LEGO_Elements\My_LEGO_Elements\Drawer_Systems_5.xml"))
ListBox1.Items.AddRange(data.DrawerSystems.ToArray())
End Sub
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.SelectedValueChanged
Dim drawerSystem As DrawerSystem = CType(ListBox1.SelectedItem, DrawerSystem)
DrawerSysIDLabel.Text = drawerSystem.Id
DrawerSysNameLabel.Text = drawerSystem.Name
DrawerSysLocLabel.Text = drawerSystem.Location
'retrieve specific drawer system image from resources
Dim pictureResource = My.Resources.ResourceManager.GetObject(String.Format("{0}", drawerSystem.Id))
'convert pictureResource to type Image and display in DrawerSysPictureBox
DrawerSysPictureBox.Image = CType(pictureResource, Image)
End Sub 'My_LEGO_Elements_Load
Private Sub ListBox2_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox2.SelectedValueChanged
Dim drawer As Drawer = CType(ListBox2.SelectedItem, Drawer)
DrawerNumberLabel.Text = drawer.Id
DrawerContentsLabel.Text = drawer.Contents
End Sub
End Class 'My_LEGO_Elements
Public Class LEGOElementsData
Public Property DrawerSystems() As List(Of DrawerSystem)
Get
Return _drawerSystems
End Get
Set(ByVal value As List(Of DrawerSystem))
_drawerSystems = value
End Set
End Property
Private _drawerSystems As List(Of DrawerSystem)
End Class
Public Class DrawerSystem
Public Property Id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Private _id As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _name As String
Public Property Location() As String
Get
Return _location
End Get
Set(ByVal value As String)
_location = value
End Set
End Property
Private _location As String
Public Property Drawers() As List(Of Drawer)
Get
Return _drawers
End Get
Set(ByVal value As List(Of Drawer))
_drawers = value
End Set
End Property
Private _drawers As List(Of Drawer)
Public Overrides Function ToString() As String
Return _name
End Function
End Class
Public Class Drawer
Public Property Id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Private _id As String
Public Property Contents() As String
Get
Return _contents
End Get
Set(ByVal value As String)
_contents = value
End Set
End Property
Private _contents As String
End Class
Public Class SimpleXmlSerializer
Public Function Serialize(ByVal objectToSerialize As Object) As String
Dim serializer As XmlSerializer = New XmlSerializer(objectToSerialize.GetType())
Using stream As MemoryStream = New MemoryStream()
Dim namespaces As XmlSerializerNamespaces = New XmlSerializerNamespaces()
namespaces.Add("", "")
serializer.Serialize(stream, objectToSerialize, namespaces)
Using reader As StreamReader = New StreamReader(stream)
stream.Position = 0
Return reader.ReadToEnd()
End Using
End Using
End Function
Public Function DeSerialize(Of T)(ByVal serializedObject As String) As T
Dim serializer As XmlSerializer = New XmlSerializer(GetType(T))
Using reader As StringReader = New StringReader(serializedObject)
Return CType(serializer.Deserialize(reader), T)
End Using
End Function
End Class
I re-structured my XML file as suggested. I got the the drawer systems information to display properly. Is there a way to display information about individual drawers in the second ListBox (or another type of control) upon selecting a drawer system? Also, for some reason my image won't display in the PictureBox.
A: Sounds like an odd way to do it. I would think if you are loading the XML into a TreeView control, you would be storing all the necessary data into the TreeNode.Tag properties, or into some data structure in memory, outside of the TreeView, so that when they select a node, you wouldn't have to go back to the XML to get the data for the child elements. However, if that's what you want to do, here is one way to read that data out of the XML:
Dim xmlText As String = "<Drawer_System_1>...</Drawer_System_1>..."
Dim doc As New XmlDocument()
doc.LoadXml(xmlText)
Dim parentNode As XmlNode = doc.SelectSingleNode("//Drawer_System_1")
Dim drawerSystemID As String = parentNode.SelectSingleNode("DrawerSystemID").InnerText
Dim drawerSysName As String = parentNode.SelectSingleNode("DrawerSysName").InnerText
Dim drawerSysLocation As String = parentNode.SelectSingleNode("DrawerSysLocation").InnerText
The TreeNode.Tag property is simply an Object property which you can set to anything you want. You can set it equal to a string, a list, a data set, your own custom object, or anything else. Whatever makes sense to you, that's what its for. It allows you to store custom data about each node in the tree so that you can access it at a later time (such as when the node is selected). So for instance, if you had your own class like this:
Public Class DrawerSystem
Public ID As String
Public Name As String
Public Location As String
End Class
Then, when you create a `TreeNode' for a drawer system, you could set it's tag like this:
Private Sub AddNode(drawerSystem As DrawerSystem)
Dim node As TreeNode = TreeView1.Nodes.Add(drawerSystem.Name)
node.Tag = drawerSystem
End Sub
Then, in the event when a node is clicked or selected, for instance, you could retrieve that object like this:
Dim drawerSystem As DrawerSystem = CType(e.Node.Tag, DrawerSystem)
Label1.Text = drawerSystem.ID
Label2.Text = drawerSystem.Location
I can't understand exactly why you need to show all the elements in the XML in the same hierarchy in the TreeView. It would seem like a simple list of drawer systems would suffice. Then when an item in the list was selected, you could show all the details about that drawer system in other controls. Also, rather than trying to loop through the XML, I'd recommend just deserializing the XML into a matching data structure. For instance, if you reformatted you XML like this (just to make it more conducive to deserializing):
<LegoElementsData>
<DrawerSystems>
<DrawerSystem>
<Id>1</Id>
<Name>Drawer_System_1</Name>
<Location>North Wall (2nd from left)</Location>
<Drawers>
<Drawer>
<Id>1-01</Id>
<Contents>Contents of Drawer 1-01</Contents>
</Drawer>
<Drawer>
<Id>1-02</Id>
<Contents>Contents of Drawer 1-02</Contents>
</Drawer>
</Drawers>
</DrawerSystem>
</DrawerSystems>
</LegoElementsData>
Then, you could create a matching data structure in your code, such as this:
Public Class LegoElementsData
Public Property DrawerSystems() As List(Of DrawerSystem)
Get
Return _drawerSystems
End Get
Set(ByVal value As List(Of DrawerSystem))
_drawerSystems = value
End Set
End Property
Private _drawerSystems As List(Of DrawerSystem)
End Class
Public Class DrawerSystem
Public Property Id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Private _id As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _name As String
Public Property Location() As String
Get
Return _location
End Get
Set(ByVal value As String)
_location = value
End Set
End Property
Private _location As String
Public Property Drawers() As List(Of Drawer)
Get
Return _drawers
End Get
Set(ByVal value As List(Of Drawer))
_drawers = value
End Set
End Property
Private _drawers As List(Of Drawer)
Public Overrides Function ToString() As String
Return _name
End Function
End Class
Public Class Drawer
Public Property Id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Private _id As String
Public Property Contents() As String
Get
Return _contents
End Get
Set(ByVal value As String)
_contents = value
End Set
End Property
Private _contents As String
Public Overrides Function ToString() As String
Return _id & " - " & _ contents
End Function
End Class
Then, to make your life easier, I'd recommend making your own serializer class that simplifies the process a bit, such as:
Public Class SimpleXmlSerializer
Public Function Serialize(ByVal objectToSerialize As Object) As String
Dim serializer As XmlSerializer = New XmlSerializer(objectToSerialize.GetType())
Using stream As MemoryStream = New MemoryStream()
Dim namespaces As XmlSerializerNamespaces = New XmlSerializerNamespaces()
namespaces.Add("", "")
serializer.Serialize(stream, objectToSerialize, namespaces)
Using reader As StreamReader = New StreamReader(stream)
stream.Position = 0
Return reader.ReadToEnd()
End Using
End Using
End Function
Public Function DeSerialize(Of T)(ByVal serializedObject As String) As T
Dim serializer As XmlSerializer = New XmlSerializer(GetType(T))
Using reader As StringReader = New StringReader(serializedObject)
Return CType(serializer.Deserialize(reader), T)
End Using
End Function
End Class
Then, when you load the data, you could simply do something like this:
Public Class My_LEGO_Elements
Private Sub My_LEGO_Elements_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim serializer As New SimpleXmlSerializer()
Dim data As LegoElementsData = serializer.DeSerialize(Of LegoElementsData)(File.ReadAllText("C:\Users\Steven\Documents\Visual Studio 2012\Projects\My_LEGO_Elements\My_LEGO_Elements\Drawer_Systems_3.xml"))
ListBox1.Items.AddRange(data.DrawerSystems.ToArray())
End Sub
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.SelectedValueChanged
Dim drawerSystem As DrawerSystem = CType(ListBox1.SelectedItem, DrawerSystem)
Label1.Text = drawerSystem.Id
Label2.Text = drawerSystem.Location
Label3.Text = drawerSystem.Name
ListBox2.Items.Clear()
ListBox2.Items.AddRange(drawerSystem.Drawers.ToArray())
End Sub
End Class
| |
doc_23529920
|
Whenever any exception is raised in Spring mvc controller, it should show me an Error Page.
Whenever any exception is raised in Rest Controller, then i have to set the Response Status and exception message in the body.
I've written 2 ExceptionResolvers which handles the exceptions and sets the status code and exception message in it and other one shows the Error page. The one which sets the Status code has order 0 and other one has order as 1. However the problem here is whenever an exception is raised from Web Controller it goes into same ExceptionResolver with order 0 and Http Status code is set in response which messes up everything. In this case instead of application error page, status code and message is displayed to client.
How to handle this situation?
| |
doc_23529921
|
p.s. I know its easy to write a script that would give such output but I'm curious how to do that using jq
Expected output
{
# .[].Name
"/prometheus_prometheus_1": [
[
# .[].Config.ExposedPorts
"9090/tcp"
],
{
# key = .[].NetworkSettings.Networks.<index>
# value = .[].NetworkSettings.Networks[].IPAddress
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}
Input:
[
{
"Id": "c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa",
"Created": "2018-06-12T05:33:19.811448302Z",
"Path": "/bin/prometheus",
"Args": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 13217,
"ExitCode": 0,
"Error": "",
"StartedAt": "2018-06-12T05:33:20.264845701Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:44a4c1c270dcb5e8caf51e3205fa23343cc903f3823eab53ae204f304d16f62a",
"ResolvConfPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hostname",
"HostsPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hosts",
"LogPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa-json.log",
"Name": "/prometheus_prometheus_1",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"prometheus_prometheus-data:/prometheus:rw",
"/home/sebastian/projects/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:rw"
],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "prometheus_internal",
"PortBindings": {},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": [],
"CapAdd": null,
"CapDrop": null,
"Dns": null,
"DnsOptions": null,
"DnsSearch": null,
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "shareable",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": null,
"DeviceCgroupRules": null,
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac-init/diff:/var/lib/docker/overlay2/03c66042305488fea2fe693246e90374743fbb7836ab31e4ee5cdbfbb1c97785/diff:/var/lib/docker/overlay2/80821a00b79334493729e671dfb66cc878aec19fe2d0dfbaf4cde187522b06e8/diff:/var/lib/docker/overlay2/f5071cce5513fb3c465ad883297157271ef48c6f59cd88768068224d850c6903/diff:/var/lib/docker/overlay2/c9a0cc617abb45fbd4572abb41c7281c96bc9d59c109270c7f1ec7a99f5b055b/diff:/var/lib/docker/overlay2/5b425f8a440139a8fdcdd7f7fee8189565e9e00304e96f4cfee86ff6b861e068/diff:/var/lib/docker/overlay2/e85740d997591d2f60bfa61ea0c82a58636bccaaba970e55f12cf0ff24565c70/diff:/var/lib/docker/overlay2/e9c362d971c460b02111122b241888392d77c5b8545ed520c3d74660b16db9b2/diff:/var/lib/docker/overlay2/5001184fc8ddd25204626f419c1530b970cb37f936a196fb1173f2774310085e/diff:/var/lib/docker/overlay2/ed2e676f09a4583f2194e752083a7c95be80131f055891dc39f9fed5560f5a73/diff",
"MergedDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/merged",
"UpperDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/diff",
"WorkDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "volume",
"Name": "prometheus_prometheus-data",
"Source": "/var/lib/docker/volumes/prometheus_prometheus-data/_data",
"Destination": "/prometheus",
"Driver": "local",
"Mode": "rw",
"RW": true,
"Propagation": ""
},
{
"Type": "bind",
"Source": "/home/sebastian/projects/prometheus/prometheus.yml",
"Destination": "/etc/prometheus/prometheus.yml",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
"Hostname": "c2f86bce6844",
"Domainname": "",
"User": "nobody",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"9090/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"Image": "prom/prometheus:v2.3.0",
"Volumes": {
"/etc/prometheus/prometheus.yml": {},
"/prometheus": {}
},
"WorkingDir": "/prometheus",
"Entrypoint": [
"/bin/prometheus"
],
"OnBuild": null,
"Labels": {
"com.docker.compose.config-hash": "b8ff39fd239739ae66051752c1b49b0119862b8f21678fb42400c907d25b1c57",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "prometheus",
"com.docker.compose.service": "prometheus",
"com.docker.compose.version": "1.16.1",
"maintainer": "The Prometheus Authors <prometheus-developers@googlegroups.com>"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "7be77954d0e6990f565a8526b157236140238cabf0954629598ce3bb9aaae885",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"9090/tcp": null
},
"SandboxKey": "/var/run/docker/netns/7be77954d0e6",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"prometheus_internal": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "145c59986c16003f9a3a30e6b671c34b56225d90243fba88fc295c49b4dcfff6",
"EndpointID": "8e3ac8bd4719ea85358c20a8141c37377dd327265916d41ee5d1db6b7496898c",
"Gateway": "172.21.0.1",
"IPAddress": "172.21.0.4",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:15:00:04",
"DriverOpts": null
},
"system-information": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "f6e67721cb73da7e8d4eacdb709de240014af9af35e66216e6186300c72de330",
"EndpointID": "2c31369f8175f2b38a5bc966a8306c8f0f11ac4c264e6ce735d00c87b8a6f44f",
"Gateway": "172.28.0.1",
"IPAddress": "172.28.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:1c:00:02",
"DriverOpts": null
}
}
}
}
]
A: jq solution:
jq '.[] | {(.Name) : [(.Config.ExposedPorts | keys),
(.NetworkSettings.Networks | to_entries
| map({(.key): .value.IPAddress}) | add)
]
}' input
The output:
{
"/prometheus_prometheus_1": [
[
"9090/tcp"
],
{
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}
| |
doc_23529922
|
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I use this function to get image from url as a bitmap. For a large image bitmap return null. How can ı solve this?
A: Try this:
private Bitmap getBitmap(String image_link)
{
URL website;
try {
website = new URL(image_link);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
InputStream is = connection.getInputStream();
if(req_width == 0)
{
return BitmapFactory.decodeStream(is);
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
is.close();
connection = (HttpURLConnection) website.openConnection();
is = connection.getInputStream();
options.inSampleSize = calculateInSampleSize(options, req_width, req_height);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(is, null , options);
} catch (Exception e) {
return null;
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
A: Code modified. See if this works
If the bitmap is null, this code will replace it with another sample bitmap.
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
if(bitmap == null){
imageBitmap =
BitmapFactory.decodeResource(context.getResources(),R.drawable.your_sample_image);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
| |
doc_23529923
|
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:padding="@dimen/activity_horizontal_margin"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.android.volley.toolbox.NetworkImageView
android:layout_width="match_parent"
android:layout_height="400dp"
android:scaleType="fitCenter"
android:id="@+id/imageViewHero" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:text="Name"
android:paddingRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textViewName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow>
<TextView
android:text="Publisher"
android:paddingRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textViewPublisher"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Image"
android:id="@+id/buttonUpload" />
</TableRow>
</TableLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
| |
doc_23529924
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyApplication.App_Code
{
public class DateTextBox : TextBox
{
protected override void OnPreRender(EventArgs e)
{
//this is what iwant to do :
//((TextBox)sender).Attributes.Add("placeholder", "dd/mm/yyyy");
base.OnPreRender(e);
}
}
}
I need to add a "placeholder" attribute to the textbox control on prerender, but i'm not sure about how to reference the sender textbox control.
A: You just use this:
this.Attributes.Add("placeholder", "dd/mm/yyyy");
A: The current instance is your textbox. Use this.Attributes?
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Attributes.Add("placeholder", "dd/mm/yyyy");
}
A: you don't need sender here. your class instance itself represents the text box.
so simply use :
Attributes.Add("placeholder", "dd/mm/yyyy");
remember, this automatically considered. so above statement is same as :
this.Attributes.Add("placeholder", "dd/mm/yyyy");
A: An Addition on @kind.code you need to write attributes.add after
protected override void OnPreRender(EventArgs e)
{
// Run the OnPreRender method on the base class.
base.OnPreRender(e);
// Add Attributs on textbox
this.Attributes.Add("placeholder", "dd/mm/yyyy");
}
Another Option
I think you not need to do all this override of Textbox
you can write simple ..as
<asp:TextBox ID="TextBox1" runat="server" placeholder="dd/mm/yyyy" ></asp:TextBox>
| |
doc_23529925
|
06-26 22:44:26.590 1136-1136/com.ivywire.ideastem E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.ivywire.ideastem.IdeasDbAdapter.createIdea(IdeasDbAdapter.java:78)
at com.ivywire.ideastem.IdeaAddActivity$1.onClick(IdeaAddActivity.java:44)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
So I tried taking out some parts
Idea idea = new Idea(name, summary);
databaseHandler.createIdea(idea);
when taken out it works. This is the full activity code.
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
public class IdeaAddActivity extends Activity {
IdeasDbAdapter databaseHandler;
private EditText ideaName;
private EditText ideaSummary;
private Button addButton;
String name;
String summary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ideaadd);
ideaName = (EditText) findViewById(R.id.ideaName);
ideaSummary = (EditText) findViewById(R.id.ideaSummary);
addButton = (Button) findViewById(R.id.addIdeaButton);
name = ideaName.getText().toString();
summary = ideaSummary.getText().toString();
databaseHandler = new IdeasDbAdapter(this);
addButton.setOnClickListener(addListener);
}
private OnClickListener addListener = new OnClickListener(){
public void onClick(View view){
Idea idea = new Idea(name, summary);
databaseHandler.createIdea(idea);
sendToMain(view);
}
};
public void sendToMain(View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.idea_add, menu);
return true;
}
}
This is the IdeasDbAdapter class:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class IdeasDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_SUMMARY = "summary";
private static final String TAG = "IdeasDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "Brainstorm";
private static final String SQLITE_TABLE = "Ideas";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_NAME + "," +
KEY_SUMMARY + ");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public IdeasDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public IdeasDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createIdea(Idea idea) {
String name = idea.getName();
String summary = idea.getSummary();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_SUMMARY, summary);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllIdeas() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchIdeasByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_SUMMARY},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_SUMMARY},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllIdeas() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_SUMMARY},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Line 78 that was referred in the nullpointer exception was
return mDb.insert(SQLITE_TABLE, null, initialValues);
If anybody could give me tips since I'm fairly confused and searching as best as I can, I'd appreciate it.
A: I dont Know the string on your others code
but look at my code and see what you have to do
addactivity:
saveBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
memo = new Memo();
memo.setHeadLine(headLineTxt.getText().toString());
memo.setFullMemo(fullMemoTxt.getText().toString());
memo = datasource.createMemo(memo);
finish();
}
});
IdeasDbAdapter:
public Memo createMemo(Memo memo) {
//Used to store data like : COLUMN_NAME , VALUE.
ContentValues values = new ContentValues();
values.put(COLUMN_HEAD_LINE, memo.getHeadLine());
values.put(COLUMN_FULL_MEMO, memo.getFullMemo());
//Insert new memo and get the id of it.
long insertId = database.insert(TABLE_NAME, null,
values);
I Hope it help you.
A: I was looking for a nice tutorial that explain how to create a good SQLite Database and Content providers for it. I found this one and I think that if you follow it, you will have a good architecture and no problems accessing, deleting or upgrading your data:
http://www.vogella.com/articles/AndroidSQLite/article.html#todo
| |
doc_23529926
|
My controller looks like this:
class ExampleController < ApplicationController
def list_email_labels
# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = "Application Name"
service.authorization = authorize
# Show the user's labels
user_id = "me"
@labels = service.list_user_labels user_id
end
def authorize
token_store = Google::Auth::Stores::FileTokenStore.new file: "token.yaml"
scope = Google::Apis::GmailV1::AUTH_GMAIL_READONLY
client_id = Google::Auth::ClientId.from_hash auth_hash
authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store, "/auth/google_oauth2/callback")
user_id = "me"
credentials = authorizer.get_credentials(user_id, request)
if credentials.nil?
redirect_to authorizer.get_authorization_url(login_hint: user_id, request: request), allow_other_host: true
end
credentials
end
def callback
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
redirect target_url
end
def auth_hash
{
"web" => {
"client_id" => [CLIENT_ID],
"project_id" => [PROJECT_ID],
"auth_uri" => 'https://accounts.google.com/o/oauth2/auth',
"token_uri" => 'https://oauth2.googleapis.com/token',
"auth_provider_x509_cert_url" => 'https://www.googleapis.com/oauth2/v1/certs',
"client_secret" => [CLIENT_SECRET],
"redirect_uris" => ['http://localhost:3000/auth/google_oauth2/callback']
}
}
end
end
When I run this, I get an error Google::Apis::AuthorizationError in ExampleController#list_email_labels.
The error references this line:
@labels = service.list_user_labels user_id
in the list_email_labels action.
It seems that rails ignores the redirect_to in the authorize action.
Any help is much appreciated.
A: statements after redirect_to in your controller gets executed. to terminate the execution immediately after redirect_to use return
redirect_to example_url and return
| |
doc_23529927
|
Any help or tip will be warmly welcomed.
A: Yes of Course, You can use it with relative layout. Use it as background of your RelativeLayout. I also used it in my project.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/top_header_bg_repeat"
android:gravity="center">
top_header_bg_repeat.xml (in drawable folder)
----------------------------------------------
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/top_header"
android:tileMode="repeat"
android:dither="true"/>
Set Bitmap in ImageView
----------------------
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/top_header_bg_repeat"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/top_header_bg_repeat"/>
A: Create an XML file named background in Drawable folder
background.xml
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/imagename"
android:tileMode="repeat" />
In your Relative Layout add the above XML as background
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:background="@drawable/background" />
A: Yes, its possible. Define your repeating image as Drawable (bitmap) with android:tileMode="repeat" in XML and use it as background of your RelativeLayout.
A: In all requests exists one small problem if you image will be great and smaller what size your layout, image will not resize, only repeat by X.
For repeat by Y you can do it only programmly.
I solve my problem like this (set gravity fill)
drawable bg for image
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/table_cells_bg_img"
android:tileMode="repeat" android:gravity="fill" />
and on layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="@dimen/table_cell_height">
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="@dimen/table_cell_height"
android:scaleType="fitXY"
android:src="@drawable/table_cells_bg"/>
<TextView
android:id="@+id/txtActivityTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/avatarImage"
android:text="TextView"
android:textColor="@color/white"
android:textSize="@dimen/font_size_middle" />
</RelativeLayout>
And table_cells_bg_img it's image with width=1px and height = 1px
and etc of layout, so now your image it's like background and it's will resized for any size of parent layout
Try, maybe help. To be cleared in my case i need tiled background image to full size of tablecell repeated by X coordinate (like i can do it on iOS). So i solve it like i describe.
| |
doc_23529928
|
private void openDialog() {
this.display = getUI().getDisplay();
this.shell = new Shell( this.display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL );
this.shell.setLayout( new GridLayout() );
Image image = createImage( this.display, "resources/loading.gif" );
Label label = new Label( this.shell, SWT.NONE );
label.setImage( image );
this.shell.open();
}
private Image createImage( Display display, String resourceName ) {
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream( resourceName );
if( inputStream == null ) {
throw new IllegalArgumentException( "Resource not found: " + resourceName );
}
try {
return new Image( display, inputStream );
} finally {
try {
inputStream.close();
} catch( IOException exception ) {
// TODO handle exception
}
}
}
A: Currently it is not possible to display an animated gif. Tabris will improve support for image display so that feature could be added in the future.
| |
doc_23529929
|
Possible Duplicate:
Dealing with commas in a CSV file
I wrote myself a CSV parser it works fine until I hit this record:
B002VECGTG,B002VECGTG,HAS_17131_spaceshooter,"4,426",0.04%,"4,832",0.03%,0%,1,0.02%,$20.47 ,1
The escaped , in "4,426" and in "4,426" brake my parser.
This is what I am using to parse the line of text:
char[] comma = { ',' };
string[] words = line.Split(comma);
How do I prevent my program from breaking?
A: I suggest using a CSV parser instead of trying to parse by yourself.
There are some nuances to parsing CSV correctly, as you have already found out.
There are many third party ones (and several of these are free), and even one built into the Visual Basic namespace - the TextFieldParser in the Microsoft.VisualBasic.FileIO namespace.
A: You can't just split on comma. To implement a proper parser for that case, you need to loop through the string yourself, keeping track of whether you are inside quotes or not. If you are inside a quoted string, you should keep on until you find another quote.
IEnumerable<string> LineSplitter(string line)
{
int fieldStart = 0;
for(int i = 0; i < line.Length; i++)
{
if(line[i] == ',')
{
yield return line.SubString(fieldStart, i - fieldStart);
fieldStart = i + 1;
}
if(line[i] == '"')
for(i++; line[i] != '"'; i++) {}
}
}
A: It is possible to use a Regex:
List<List<String>> rows = new List<List<String>>();
MatchCollection matches = Regex.Matches(input, @"^(?:(?:\s*""(?<value>[^""]*)""\s*|(?<value>[^,]*)),)*?(?:\s*""(?>value>[^""]*)""\s*|(?<value>[^,]*))$", RegexOptions.Multiline);
foreach(Match row in matches)
{
List<String> values = new List<String>();
foreach(Capture value in row.Groups["value"].Captures)
{
values.Add(value.Value);
}
rows.Add(values);
}
I do not suggest that it is the best solution, but for small files (a couple of rows) it probably isn't too bad.
| |
doc_23529930
|
Given array of denominations coins[], array of limit for each coins limits[] and number amount, return minimum number of coins needed, to get the amount, or if it's not possible return null. Additionally fill array change with number of each coin used in the solution.
This is my solution:
public static int? Dynamic(int amount, int[] coins, int[] limits, out int[] change)
{
int[] minCoins = new int[amount + 1];
int[,] coinsUsedToAmount = new int[coins.Length, amount + 1];
minCoins[0] = 1;
for (int j = 0; j < amount; ++j)
{
if (minCoins[j] == 0)
{
continue;
}
for (int i = 0; i < coins.Length; ++i)
{
if (coinsUsedToAmount[i, j] >= limits[i])
{
continue;
}
int currAmount = j + coins[i];
if (currAmount <= amount
&& (minCoins[currAmount] == 0
|| minCoins[currAmount] > minCoins[j] + 1))
{
minCoins[currAmount] = minCoins[j] + 1;
for (int k = 0; k < coins.Length; ++k)
{
coinsUsedToAmount[k, currAmount] = coinsUsedToAmount[k, j];
}
coinsUsedToAmount[i, currAmount] += 1;
}
}
}
if (minCoins[amount] == 0)
{
change = null;
return null;
}
change = new int[coins.Length];
for(int i = 0; i < coins.Length; ++i)
{
change[i] = coinsUsedToAmount[i, amount];
}
return minCoins[amount] - 1;
}
But it doesn't work in general.
My issue is that for example in such case:
amount = 141,
coins = new int[] { 2, 137, 65, 35, 30, 9, 123, 81, 71 }
limits = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 }
Optimal solution is:
change = new int[] { 1, 0, 1, 1, 1, 1, 0, 0, 0 }
And my algorithm gives null as the result. In the other words it fails, whenever on some way up I would have to use less optimal solution than it's possible, and then, at the end, I don't have necessary coins.
So, in this example my algorithm makes a mistake in following step:
minCoins[132] = (9 + 123) // 2 coins
But it should be:
minCoins[132] = (2 + 65 + 35 + 30) // 4 coins
because then I can use 9 and have 141.
I have been coming back to this problem for a few weeks now and I still can't solve it. I had seen numerous solutions to similar problems on this and other sites, but none of them helped me.
A: Friend of mine helped me solve it. The idea is that we go from the amount to 0 and try to use all the nominal of each coins possible - that way we won't end up using certain coins at the beginning, and then we wouldn't have possibility to use them for amount.
/// <summary>
/// Method used to resolve minimum change coin problem
/// with constraints on the number of coins of each type.
/// </summary>
/// <param name="amount">Amount of change to make, e.g. 13</param>
/// <param name="coins">Available types of coins, e.g. {1, 2, 3, 5}</param>
/// <param name="limits">Number of available coins of specific type, e.g. {1, 5, 3, 2}</param>
/// <param name="change">Number of coins of each type used to make the change, e.g. {0, 0, 1, 2}</param>
/// <returns>
/// Minimal number of coins needed to make the change
/// (equal to sum of change array entries), e.g. 3
/// </returns>
/// <remarks>
/// coins[i] - nominal value of the coin of i-th type
/// limits[i] - number of available coins of i-th type (denomination)
/// change[i] - number of coins of i-th type used in the solution
///
/// If available `coins` and `limits` does not allow to make provided `amount` of change
/// then `change` should be set to `null`, and method should also return `null`.
///
/// Tips/requirements:
/// The size of work memory of the algorithm should (must) be
/// proportional to the value of product: `amount*(coins.Length)`
/// (that is O(amount*(coins.Length))
/// </remarks>
public static int? Dynamic(int amount, int[] coins, int[] limits, out int[] change)
{
int[][] coinsUsed = new int[amount + 1][];
for (int i = 0; i <= amount; ++i)
{
coinsUsed[i] = new int[coins.Length];
}
int[] minCoins = new int[amount + 1];
for (int i = 1; i <= amount; ++i)
{
minCoins[i] = int.MaxValue - 1;
}
int[] limitsCopy = new int[limits.Length];
limits.CopyTo(limitsCopy, 0);
for (int i = 0; i < coins.Length; ++i)
{
while (limitsCopy[i] > 0)
{
for (int j = amount; j >= 0; --j)
{
int currAmount = j + coins[i];
if (currAmount <= amount)
{
if (minCoins[currAmount] > minCoins[j] + 1)
{
minCoins[currAmount] = minCoins[j] + 1;
coinsUsed[j].CopyTo(coinsUsed[currAmount], 0);
coinsUsed[currAmount][i] += 1;
}
}
}
limitsCopy[i] -= 1;
}
}
if (minCoins[amount] == int.MaxValue - 1)
{
change = null;
return null;
}
change = coinsUsed[amount];
return minCoins[amount];
}
| |
doc_23529931
|
(browser target is ie10 and up). The below incorrectly keeps the image ratio and at 100% width so that if fails to match the height of the parent.
The current html is just an img inside a div tag
<div class="banner">
<img class="img-fluid" src="somepic.jpg" />
</div>
Where the css classes used are:
.banner {
content: "";
position: absolute;
width: 100%;
top: 0;
left: 0;
height: 780px;
}
and img-fluid is a bootstrap(4) class with
img-fluid {
max-width: 100%;
height: auto;
}
A: Use a background-image instead, there are a couple interesting behaviours that can be used to achieve different results.
Here's my take:
.banner {
content: "";
position: absolute;
width: 100%;
top: 0;
left: 0;
height: 780px;
background-image:url('somepic.jpg');
background-size:cover;
}
The key here is background-size:cover;, it will make sure the image stretches to cover the full width and height while keeping its ratio. That means on very wide screens, it will be made larger, cutting some height. But on thinner resolutions you'll get the desired output.
| |
doc_23529932
|
Here is the method that I created to do this:
public IEnumerable<SelectListItem> GetBranches(string username)
{
using (var objData = new BranchEntities())
{
IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
}).Distinct(new Reuseablecomp.SelectListItemComparer());
return objdataresult;
}
}
Here is the class I am using:
public static class Reuseablecomp
{
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
}
Nothing is returned and I get the error below. When I try a basic query without Distinct, everything works fine.
{"The operation cannot be completed because the DbContext has been disposed."}
System.Exception {System.InvalidOperationException}
Inner exception = null
How can I return distinct data for my dropdown?
A: Technically, your problem can be solved simply by appending .ToList() after your Distinct(...) call. The problem is that queries are evaluated JIT (just in time). In other words, until the actual data the query represents is needed, the query is not actually sent to the database. Calling ToList is one such thing that requires the actual data, and therefore will cause the query to be evaluated immediately.
However, the root cause of your problem is that you are doing this within a using statement. When the method exits, the query has not yet been evaluated, but you have now disposed of your context. Therefore, when it comes time to actually evaluate that query, there's no context to do it with and you get that exception. You should really never use a database context in conjuction with using. It's just a recipe for disaster. Your context should ideally be request-scoped and you should use dependency injection to feed it to whatever objects or methods need it.
Also, for what it's worth, you can simply move your Distinct call to before your Select and you won't need a custom IEqualityComparer any more. For example:
var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
});
Order of ops does matter here. Calling Distinct first includes it as part of the query to the database, but calling it after, as you're doing, runs it on the in-memory collection, once evaluated. The latter requires, then, custom logic to determine what constitutes distinct items in an IEnumerable<SelectListItem>, which is obviously not necessary for the database query version.
| |
doc_23529933
|
This is my countdowntimer
public void bonus(){
mEndTime = System.currentTimeMillis() + timeleftinmillis;
Log.i("timeadd", String.valueOf(mEndTime));
countDownTimer=new CountDownTimer(timeleftinmillis,1000){
@Override
public void onTick(long l) {
timeleftinmillis=l;
updateTimer();
}
@Override
public void onFinish() {
mrunning=false;
updateButtons();
}
}.start();
mrunning=true;
bonusmoney.setText( String.valueOf(clickcount));
updateButtons();
}
Here is where i am converting time in minutes and seconds
public void updateTimer (){
long min = (timeleftinmillis/1000) / 60;
long sec = (timeleftinmillis/1000) % 60;
String timeformat = String.format(Locale.getDefault(),"%02d:%02d",min,sec);
timerbonusview.setText(timeformat);
}
This is my OnStart() method
@Override
public void onStart() {
super.onStart();
SharedPreferences prefs = getContext().getSharedPreferences("prefs", MODE_PRIVATE);
timeleftinmillis = prefs.getLong("millisLeft", timeinmillis);
mrunning = prefs.getBoolean("timerRunning", false);
updateTimer();
updateButtons();
if (mrunning) {
mEndTime = prefs.getLong("endTime", 0);
Log.i("endtime", String.valueOf(mEndTime));
timeleftinmillis = mEndTime - System.currentTimeMillis();
Log.i("timeleft", String.valueOf(timeleftinmillis));
if (timeleftinmillis < 0) {
timeleftinmillis = 0;
mrunning = false;
Log.i("timebonus", "less than zero");
updateTimer();
updateButtons();
} else {
bonus();
}
}
}
This is my onStop() method
@Override
public void onStop() {
super.onStop();
SharedPreferences prefs = getContext().getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("millisLeft", timeleftinmillis);
editor.putBoolean("timerRunning", mrunning);
editor.putLong("endTime", mEndTime);
editor.apply();
if (countDownTimer != null) {
countDownTimer.cancel();
}
}
updating buttons here
private void updateButtons() {
if (mrunning) {
dailyearningsbtn.setVisibility(View.INVISIBLE);
}else {
dailyearningsbtn.setVisibility(View.VISIBLE);
}
}
A: For running tasks after app is killed consider using background services in android
| |
doc_23529934
|
In Eclipse 3.0 plug-in runtime objects
are not globally managed and so are
not generically accessible. Rather,
each plug-in is free to declare API
which exposes the plug-in runtime
object (e.g., MyPlugin.getInstance()
In order for the other components of my system to access these objects, I have to do the following:
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
, which is overly verbose IMO.
Since MyPlugin provides global access, wouldn't it be easier for me to just provide global access to the objects it manages as well?
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
Any thoughts?
(I'm actually asking because I was reading about the whole "Global variable access and singletons are evil" debates)
A:
Any thoughts?
Yes, for the current use-case you are examining, you could marginally simplify your example code by using statics.
But think of the potential disadvantages of using statics:
*
*What if in a future version of Eclipse Plugin objects are globally managed?
*What if you want to reuse your configuration classes in a related Plugin?
*What if you want to use a mock version of your configuration class for unit testing?
Also, you can make the code less verbose by refactoring; e.g.
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P1);
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P2);
becomes
MyConfig config = MyPlugin.getInstance().getConfig();
... = config.getValue(MyPlugin.CONFIGKEY_P1);
... = config.getValue(MyPlugin.CONFIGKEY_P2);
A: You suggest that
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
is too verbose and
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
might be better. By that logic, wouldn't:
getMyConfigValue(MyPlugin.CONFIGKEY_SOMEPARAMETER):
be better yet (Maybe not shorter, but simpler)? I'm suggesting you write a local helper method.
This gives you the advantage of readability without bypassing concepts that were crafted by people who have been through the effort of fixing code that was done the easy/short/simple way.
Generally globals are pretty nasty in any situation. Singletons are also an iffy concept, but they beat the hell out of public statics in a class.
Consider how you will mock out such a class. Mocking out public statics is amazingly annoying. Mocking out singletons is hard (You have to override your getter in every method that uses it). Dependency Injection is the next level, but it can be a touch call between DI and a few simple singletons.
| |
doc_23529935
|
In details:
*
*I followed the tutorial from Jetbrain to build a mobile multiplatform project. Everything works fine.
*Then I implemented inside the common module a ktor client to request an api (jsonplaceholder). I added all the required dependencies and everything seems good. All references are resolved, I have no errors.
*But when I compile my project with make Project then all the dependencies added to get ktor and so on cannot be resolved.
I guess I have a problem with the configuration of my project, when I run ./gradlew androidDependencies it seems that there is a problem with SharedCode since it is sometimes marked in the command´s output as \--- :SharedCode.
The build.gradle for the project is:
buildscript {
ext.kotlin_version = '1.3.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.0-rc01'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
The build.gradle.kts for the common SharedCode module is:
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
}
kotlin {
//select iOS target platform depending on the Xcode environment variables
val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
::iosArm64
else
::iosX64
iOSTarget("ios") {
binaries {
framework {
baseName = "SharedCode"
}
}
}
jvm("android")
val serializationVersion = "0.20.0"
val ktorVersion = "1.3.2"
sourceSets["commonMain"].dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serializationVersion")
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-json:$ktorVersion")
implementation("io.ktor:ktor-client-serialization:$ktorVersion")//Kotlinxserializer
}
sourceSets["androidMain"].dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib")
}
}
val packForXcode by tasks.creating(Sync::class) {
val targetDir = File(buildDir, "xcode-frameworks")
/// selecting the right configuration for the iOS
/// framework depending on the environment
/// variables set by Xcode build
val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
val framework = kotlin.targets
.getByName<KotlinNativeTarget>("ios")
.binaries.getFramework(mode)
inputs.property("mode", mode)
dependsOn(framework.linkTask)
from({ framework.outputDirectory })
into(targetDir)
/// generate a helpful ./gradlew wrapper with embedded Java path
doLast {
val gradlew = File(targetDir, "gradlew")
gradlew.writeText("#!/bin/bash\n"
+ "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
+ "cd '${rootProject.rootDir}'\n"
+ "./gradlew \$@\n")
gradlew.setExecutable(true)
}
}
tasks.getByName("build").dependsOn(packForXcode)
And the build.gradle for the android app is:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.mpp.mpptest"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation project(':SharedCode')
}
Do you know what I am doing wrong?
I read Building Multiplatform Projects with Gradle but it did not help.
The only working project that I found is from KaMPKit. I have set my build.gradle(.kts) files as they are in KaMPKit (see the branch Set_build_gradle_as_KaMPKit) but the `unresolved references´ problem remains.
A: I fixed my problem. The error came because I did not declare the plugin android.lybrary.
Even if it is not necessary to fix the problem, I have decided to switch my build.gradle files to kotlin DLS, I rewrote all the build.gradle and I made the following changes for the shared module:
*
*I created a AndroidManifest.xml
*I added the com.android.library plugins
*I added a block android
At the end the build.gradle.kts for the shared module looks like this:
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
id("kotlinx-serialization")
id("com.android.library")
}
android {
compileSdkVersion(29)
defaultConfig {
minSdkVersion(Versions.min_sdk)
targetSdkVersion(Versions.target_sdk)
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
}
kotlin {
//select iOS target platform depending on the Xcode environment variables
val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
::iosArm64
else
::iosX64
iOSTarget("ios") {
binaries {
framework {
baseName = "SharedCode"
}
}
}
jvm("android")
sourceSets["commonMain"].dependencies {
implementation(kotlin("stdlib-common", Versions.kotlin))
implementation(Deps.Ktor.commonCore)
implementation(Deps.Ktor.commonJson)
implementation(Deps.Coroutines.common)
implementation(Deps.Ktor.commonSerialization)
}
sourceSets["androidMain"].dependencies {
implementation(kotlin("stdlib", Versions.kotlin))
implementation(Deps.Coroutines.jdk)
implementation(Deps.Ktor.androidSerialization)
}
sourceSets["iosMain"].dependencies {
implementation(Deps.Ktor.iosSerialization)
}
}
val packForXcode by tasks.creating(Sync::class) {
val targetDir = File(buildDir, "xcode-frameworks")
/// selecting the right configuration for the iOS
/// framework depending on the environment
/// variables set by Xcode build
val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
val framework = kotlin.targets
.getByName<KotlinNativeTarget>("ios")
.binaries.getFramework(mode)
inputs.property("mode", mode)
dependsOn(framework.linkTask)
from({ framework.outputDirectory })
into(targetDir)
/// generate a helpful ./gradlew wrapper with embedded Java path
doLast {
val gradlew = File(targetDir, "gradlew")
gradlew.writeText("#!/bin/bash\n"
+ "export 'JAVA_HOME=${System.getProperty("java.home")}'\n"
+ "cd '${rootProject.rootDir}'\n"
+ "./gradlew \$@\n")
gradlew.setExecutable(true)
}
}
tasks.getByName("build").dependsOn(packForXcode)
All dependency version numbers come from a Dependencies.kt files (see KaMPKit)
All dependencies are now resolved.
| |
doc_23529936
| ||
doc_23529937
|
The logon script has the line to set user environment variables but the variables don't look like being applying immediately from the result of set command on command prompts.
I've been looking at the behavior through process monitor while logging on to the new session.
And finally I have found the newly created variables need to be associated with RegenerateUserEnvironment function on shell32.dll.
I'm able to look at the correct result of set command after RegenerateUserEnvironment is called.
So I was wondering whether we had a way to trigger RegenerateUserEnvironment function and it needs to be executed on powershell.
Can you shed some light on this?
Best Regards,
Haewon
| |
doc_23529938
|
What are your thoughts abou this problem? Code is same as documented in the firebase mesaging quickstart sample
A: I changed one of firebase notification scripts code. There was an unexpected bug which is sending the notification two times. I can send you the files. Meanwhile, this is my firebase-messaging.sw.js (I hided the keys).
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
importScripts("firebase-messaging.js");
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
* New configuration for app@pulseservice.com
*/
firebase.initializeApp({
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
// Customize notification here
let url = payload.data.notification_url;
const notificationTitle1 = payload.notification.title;
const notificationOptions1 = {
body: payload.notification.body,
icon: "",
data: { url: payload.data.notification_url },
image: payload.notification.image
};
return self.registration.showNotification(notificationTitle1, notificationOptions1);
});
self.addEventListener("notificationclick", function (event) {
let url = event.notification.data.url;
event.notification.close();
event.waitUntil(
clients.matchAll({ type: "window" }).then(windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && "focus" in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
The file I changed is firebase-messaging.js and saved it into the sites static files with the changes I made. Let me know if you need it.
| |
doc_23529939
|
So after the form is submitted, I want to prevent the current page (updates.php) to redirect to another page (test.php).
I am trying to do this with Jquery Ajax, but in this point, I am open to any solution.
updates.php:
<form action="test.php" method="post">
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary">
</div>
</form>
test.php:
<?php
$id = $_POST['id'];
$username = $_POST['name'];
$comment = $_POST['subject'];
if(!empty($username) || !empty($comment))
{
$conn = mysqli_connect('localhost','Admin','admin123','website');
if(!$conn)
{
echo "Connection Error: " . mysqli_connect_error();
}
else
{
$INSERT = "INSERT INTO comments (id, name, comment) VALUES (?,?,?)";
$stmt = $conn -> prepare($INSERT);
$stmt -> bind_param("iss", $id, $username, $comment);
$stmt -> execute();
}
}
else { echo "All fields are required"; die();}
?>
Whatever I did I couldn't stop test.php to open.
A: Try this as your updates.php file instead:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function submitWithAjax(){
var name = document.getElementById("name").value;
var id = document.getElementById("id").value;
var subject = document.getElementById("subject").value;
$.post( "test.php", {name: name, id: id, subject: subject})
.done(function(data) {
alert( "Data Loaded: " + data );
});
}
</script>
</head>
<body>
<form>
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" onclick="event.preventDefault();submitWithAjax();">
</div>
</form>
</body>
</html>
| |
doc_23529940
|
Creation of chart:
chartRange = xlsSheet.Range[xlsSheet.Cells[1, 1], xlsSheet.Cells[array.GetLength(0), array.GetLength(1)]];
chartPage.SetSourceData(chartRange, Excel.XlRowCol.xlRows);
chartPage.ChartType = Excel.XlChartType.xl3DColumn;
chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet, oOpt);
Changing color:
Excel.Series series = (Excel.Series)chartPage.SeriesCollection(1);
Excel.Point pt = series.Points(2);
pt.Format.Fill.ForeColor.RGB = (int)Excel.XlRgbColor.rgbPink;
Problem: Nothing will change inside the chart, but there is also no error. Just showing this random colors on the bars.
A: In this case the order of the statements is important:
chartRange = xlsSheet.Range[xlsSheet.Cells[1, 1], xlsSheet.Cells[array.GetLength(0), array.GetLength(1)]];
chartPage.SetSourceData(chartRange, Excel.XlRowCol.xlRows);
Excel.Series series = (Excel.Series)chartPage.SeriesCollection(1);
Excel.Point pt = series.Points(2);
pt.Format.Fill.ForeColor.RGB = (int)Excel.XlRgbColor.rgbPink;
chartPage.ChartType = Excel.XlChartType.xl3DColumn;
chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet, oOpt);
worked for me
| |
doc_23529941
|
I validated the ids match and are unique, but I am new to HTML/JavaScript so I am blind to what I am missing.
function displayLink() {
document.getElementById("link").innerHTML = URL;
}
var site = document.getElementById("site").value;
var prodtest1 = document.getElementById("test").value == "True" ? "-test.com/" : "-prod.com/";
var prodtest2 = document.getElementById("normal").value == "True" ? "test/" : "prod/";
var isBasic = document.getElementById("basic").value == "True" ? "AuthMethod=normal" : "html/public/";
var isHtml5 = document.getElementById("html").value == "True" ? "login.aspx" : "default.aspx";
var URL = Href = "https://" + site + prodtest1 + prodtest2 + isBasic + isHtml5;
<div>
<!-- Start Inputs -->
<Form class="input">
<input type="text" placeholder="site" id="site">
<br>
<input type="checkbox" id="test">
<label for="test">TEST</label>
<input type="checkbox" id="normal">
<Label for="normal">normal</Label>
<input type="checkbox" id="html">
<label for="html">html</label>
</Form>
<button type="Button" onclick='displayLink()'>Generate Link</button>
<!-- Inputs End -->
</div>
<!-- Display URL Result -->
<div id="URL">
<br>
<a id=Link HREF="Link">
</div>
A: Your code has some things wrong with it that I noticed:
*
*There's no element with an id of "basic"
*You don't have "Link" in quotes in your link at the bottom, you need to put these types of things in quotes
*Your variable naming isn't consistent, that might be something to decide on so that your code is a bit more readable.
*Because the URL is generated outside of the onClick() function, clicking the button multiple times with, say, different checkboxes activated or a different site entered into the input would have no effect.
*Even though the browser will usually let you get away with writing your elements like <input type="checkbox" id="html">, you should really have a closing / at the end of your elements. I.e. <input type="checkbox" id="html" /> This is the syntax for a "self-closing" HTML element, you'll want to add that slash to the end.
*You'll have a better time checking if an input box is checked by just doing document.getElementById("element").checked
Have patience with yourself and just make sure you pay attention to these things when you write code. If you "fixed" all of these things (Notice "fixed" is in quotes because there are many correct ways of writing this code) it would look like this:
Html:
<div>
<!-- Start Inputs -->
<Form class="input">
<input type="text" placeholder="site" id="site" /><br>
<input type="checkbox" id="test" />
<label for="test">TEST</label>
<input type="checkbox" id="normal" />
<label for="normal">normal</label>
<label for="html">html</label>
<input type="checkbox" id="html" />
</Form>
<button type="Button" onclick='displayLink()'>Generate Link</button>
<!-- Inputs End -->
</div>
<!-- Display URL Result -->
<div id="URL">
<br>
<a id="link" HREF="" /> <!-- You don't need HREF="" here, but I left it to make it clear it started out as a blank string. -->
</div>
JavaScript:
function displayLink() {
var siteInput = document.getElementById("site").value;
var prodTest1 = document.getElementById("test").checked ? "-test.com/" : "-prod.com/";
var prodTest2 = document.getElementById("normal").checked ? "test/" : "prod/";
// These is no element in your code with an ID of "basic" so this variable has been omitted.
var isHtml5 = document.getElementById("html").checked ? "login.aspx" : "default.aspx";
var URL = "https://" + siteInput + prodTest1 + prodTest2 + isHtml5;
console.log(URL)
var linkElement = document.getElementById("link");
linkElement.innerHTML = URL;
linkElement.href = URL;
}
A: For the checkbox type of input, the checked attribute will return a boolean value of true or false for you to use with your ternary conditions.
var prodtest1 = document.getElementById("test").checked ? "-test.com/" : "-prod.com/";
More information is available in the MDN docs
| |
doc_23529942
|
<img src="path/to/img.jpg" id="img">
<script>
var img = document.getElementById('img');
var imgURL = "/path/to/new_img.png";
img.addEventListener('error', refresh);
img.src = imgURL;
function refresh(e) {
img.src = imgURL;
if(e.type !== "error") img.removeEventListener('error', refresh);
};
</script>
The last statement e.type !== error still falls within the error function and thus remains false. I need something i can call on if the event does not generate error. Somewhat like onsuccess if there's anything like that.
A: The opposite, for this specific case, is the load event indicating that the image loaded. I'm rather surprised to not find documented on MDN.
var img = document.getElementById('img');
var imgURL = "/path/to/new_img.png";
img.addEventListener('error', refresh);
img.addEventListener('load', refresh); // ***
img.src = imgURL;
then
function refresh(e) {
img.src = imgURL;
if (e.type !== "error") {
img.removeEventListener('error', refresh);
img.removeEventListener('load', refresh);
}
}
You might add some timeout and/or delay logic there, since otherwise this will constantly re-request the image until/unless it succeeds (which it may never do, if the URL is invalid).
| |
doc_23529943
|
library(quantmod)
getSymbols("AAPL;MSFT;YHOO")
closePrices <- merge(Cl(AAPL),Cl(MSFT),Cl(YHOO))
I am still new to R and need some assistance reproducing this Excel function. My first thought was to split the function into numerator and denominator, and then compute the index:
dailyDiff <- abs(diff(closePrices,1))
numerJ <- diff(closePrices,10)
denomJ <- as.xts(rollapply(dailyDiff,11, sum))
idx <- abs(numerJ/denomJ)
This was great because the values for each portion were accurate, but are aligned by incorrect dates for denomJ. For example, the tail of numerJ goes to 6/21/2012, while the tail of denomJ goes to 6/14/2012.
The output that I am looking for is:
*
*6/21/2012 = .11
*6/20/2012 = .27
*6/19/2012 = .46
*6/18/2012 = .39
*6/15/2012 = .22
A: It's hard to tell exactly what your problem is without exact data, but the problem appears to be with rollapply. rollapply will only apply the function to whole intervals unless the argument partial is set to TRUE. Consider the following example
require(zoo)
#make up some data
mat <- matrix(1:100,ncol=2)
colnames(mat) <- c("x1","x2")
dates <- seq.Date(from=as.Date("2010-01-01"),length.out=50,by="1 day")
zoo.obj <- zoo(mat,dates)
#apply the funcitons
numerJ <- diff(zoo.obj,10) #dates okay
denomJ <- rollapply(zoo.obj,11, sum,partial=TRUE) #right dates
denomJ2 <- rollapply(zoo.obj,11,sum) #wrong dates
index <- abs(numerJ/denomJ) #right dates
A: You can use a combination of diff and either runSum or rollapplyr
#Get the data
library(quantmod)
getSymbols("AAPL")
I think this is what you're trying to do (note the use of the lag argument to diff.xts, and the n argument to runSum)
out <- diff(Cl(AAPL), lag=10) / runSum(abs(diff(Cl(AAPL))), n=11)
tail(out['/2012-06-21'])
# AAPL.Close
#2012-06-14 -0.1047297
#2012-06-15 0.2176938
#2012-06-18 0.3888185
#2012-06-19 0.4585821
#2012-06-20 0.2653782
#2012-06-21 0.1117371
Edit
Upon closer review of your question, I do not understand why rollapplyr is not the answer you're looking for. If I take your code, exactly as is, except I change rollapply to rollapplyr, it looks to me like it's exactly the output you're looking for.
dailyDiff <- abs(diff(closePrices,1))
numerJ <- diff(closePrices,10)
denomJ <- as.xts(rollapplyr(dailyDiff,11, sum))
idx <- abs(numerJ/denomJ)
# AAPL.Close MSFT.Close YHOO.Close
#2012-06-14 0.1047297 0.03826531 0.06936416
#2012-06-15 0.2176938 0.35280899 0.25581395
#2012-06-18 0.3888185 0.33161954 0.31372549
#2012-06-19 0.4585821 0.47096774 0.34375000
#2012-06-20 0.2653782 0.32644628 0.23750000
#2012-06-21 0.1117371 0.18997912 0.10256410
Also, note that both numerJ and denomJ both end on the same date if you use rollapplyr (which is the same as using rollapply with align="right")
end(numerJ); end(denomJ)
#[1] "2012-07-20"
#[1] "2012-07-20"
Yahoo Bug
Maybe the problem you're seeing is the yahoo bug where sometimes -- for example, right now -- yahoo duplicates the last (chronologically speaking) row of data. If so, try deleting the duplicated row before attempting to use the data for your calculations.
tidx <- tail(index(closePrices), 2)
if(tidx[1] == tidx[2]) {
closePrices <- closePrices[-NROW(closePrices), ]
}
| |
doc_23529944
|
I store the Collection ID as a param and the array as the body. I have console logged the array so I know it has the ID's I want to delete and correctly passes them to the service.
What should my server side function look like with mongoose? This is my best attempt.
//DELETE COLLECTION LOCATIONS
collectionRouter.post('removeLocation/:id', function(req, res, next) {
Collection.update(
{_id: req.params.id},
{$pull: {locations: {_id: {$in:req.body}}}},
function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Locations Removed',
obj: result
});
});
});
Here is my Collection.Service
removeCollectionLocation(collection: Collection, locations: string[]) {
let body = locations;
const headers = new Headers({
'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.post('http://localhost:3000/collection/removeLocation/' + collection._id + token , body, {headers: headers})
.map((response: Response)=> response.json())
.catch((error: Response)=> Observable.throw(error.json()));
}
Thank you everyone.
A: You can Do Something like this -
removeCollectionLocation(collection: Collection, locations: string[]) {
let body = locations;
const headers = new Headers({
'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.post('http://localhost:3000/collection/removeLocation/' + collection._id + token , body, {headers: headers})
.map((response: Response)=> response.json())
.catch(error => Observable.of(`Bad Promise: ${error}`));
}
| |
doc_23529945
|
*
*Why do third party notifications providers such as OneSignal, Pusher & PubNub are based on Firebase Cloud Messaging?
*Can't they send notifications independently without relying on Firebase. why pay more to third party providers when FCM does the work for free?
A: Firebase is a Brand of Services
First, Firebase is a brand that encompasses more than just 1 thing. For example, there is Firebase the realtime database, and there is FCM (Firebase Cloud Messaging) which is the current incarnation of GCM (Google Cloud Messaging) which came from the original product, C2DM (Cloud to Device Messaging).
PubNub and others are push gateway providers
Second, third party realtime messaging services are not push notification services, rather they offer push notification gateways to the push services: APNS for iOS and FCM for Android.
PubNub Realtime Messaging & Mobile Push Notifications
In PubNub's case (my employer), we provide a realtime messaging service (publish, subscribe and much more) and if you provide a valid APNS and/or FCM payload, we will not only deliver that realtime message to active subscribers, we will also send a mobile push notification to the devices that are properly registered for them on that channel you published the message to. This allows the message to be delivered when the app on the device is either not active (background) or not running and therefore, no active connection to PubNub unless it is running in a background service). Now you can have an active connection to PubNub in the background with proper implementation and permissions from the owner of the device (easier on Android than on iOS which also has a review process that rejects apps that don't qualify as valid background service apps).
For Your Consideration
If you did not use a service such as PubNub or one of the other realtime messaging vendors or a push notification specific service like Urban Airship, you would have to implement your own server-based push notification service which is possible but might be more work than you would expect especially if it needs to scale, be secure, robust, etc.
The real question you should ask is do you need realtime messaging in your app or just push notifications and to what level of scalability where it is worth paying a third party for all that goodness.
| |
doc_23529946
|
Thank you
A: If you have your "some number" beforehand
you may be able to reduce the program output
by using the Magic Set feature.
https://souffle-lang.github.io/magicset
| |
doc_23529947
|
I'm basically trying to update the status of every document under items to "closed" in case their hash field is not in a list of hashes provided.
db.getCollection('projects').update({
name: 'test',
'issues.hash': { $nin: [
'8ff28fcc9cbf10c9b690bb331e5609efbd3c526be4f536ebca02cc51bd63eac7',
'd5368ad5658ec11103796255d127d26da7f3324cdedbd124bdd5db50812d588e',
'37298229097785ebc9d419cc1a3f13e0d090a15ceb9a8e6bea3505366902556d',
'fad290f2ddd0e097e4098c3b2c3d65611406cf208a3f86924d45c7736393b44b'
]}
},
{
$set: { "issues.$.status": "closed" }
}
)
This is the data:
{
"_id" : ObjectId("611bb4d2ee06769a5f6d906d"),
"name" : "test",
"issues" : [
{
"_id" : ObjectId("611bb4d20b2fb200167aa588"),
"status" : "open",
"hash" : "8ff28fcc9cbf10c9b690bb331e5609efbd3c526be4f536ebca02cc51bd63eac7"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa589"),
"status" : "open",
"hash" : "3b83e469049e46b16d3471a188d3f5e3ddbf6b296995a71765bbf17b7289e6ea"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58a"),
"status" : "open",
"hash" : "bef5f50628b669b9930b89cdc040361b9c8cc2b4aab3c2059c171786d38d507e"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58b"),
"status" : "open",
"hash" : "1b4a91eb5de97d6ad7493b6e1ffa48a2a648084b4af7b37916c723533a07c37c"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58c"),
"status" : "open",
"hash" : "bb64ba7b2612856dcd95c3ac2fad3f7368e5d463168545b12f4c869af56b55b7"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58d"),
"status" : "open",
"hash" : "1d5fc04739b10414dea8d327998df4f200f47ce57da243bd578d4ae102f2d670"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58e"),
"status" : "open",
"hash" : "d5368ad5658ec11103796255d127d26da7f3324cdedbd124bdd5db50812d588e"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa58f"),
"status" : "open",
"hash" : "37298229097785ebc9d419cc1a3f13e0d090a15ceb9a8e6bea3505366902556d"
},
{
"_id" : ObjectId("611bb4d20b2fb200167aa590"),
"status" : "open",
"hash" : "fad290f2ddd0e097e4098c3b2c3d65611406cf208a3f86924d45c7736393b44b"
}
]
}
And the is my result:
Updated 0 record(s) in 12ms
Thank you!
A: You can use arrayFilters, like this:
db.collection.update({
"name": "test"
},
{
"$set": {
"issues.$[elem].status": "closed"
}
},
{
"multi": true,
"arrayFilters": [
{
"elem.hash": {
"$nin": [
"8ff28fcc9cbf10c9b690bb331e5609efbd3c526be4f536ebca02cc51bd63eac7",
"d5368ad5658ec11103796255d127d26da7f3324cdedbd124bdd5db50812d588e",
"37298229097785ebc9d419cc1a3f13e0d090a15ceb9a8e6bea3505366902556d",
"fad290f2ddd0e097e4098c3b2c3d65611406cf208a3f86924d45c7736393b44b"
]
}
}
]
})
Here is the working example: https://mongoplayground.net/p/8wZkmlBgKiq
A: You have to use arrayFilters in this way:
db.collection.update({
"name": "test"
},
{
"$set": {
"issues.$[element].status": "closed"
}
},
{
"arrayFilters": [
{
"element.hash": {
"$nin": [
"8ff28fcc9cbf10c9b690bb331e5609efbd3c526be4f536ebca02cc51bd63eac7",
"d5368ad5658ec11103796255d127d26da7f3324cdedbd124bdd5db50812d588e",
"37298229097785ebc9d419cc1a3f13e0d090a15ceb9a8e6bea3505366902556d",
"fad290f2ddd0e097e4098c3b2c3d65611406cf208a3f86924d45c7736393b44b"
]
}
}
]
})
Example here.
Note that update query has the format: update(query, update, options) (Check the docs).
So with your find query mongo doesn't find anything. Check this example.
This is why you are telling mongo: "Give me a DOCUMENT where name is test and issues array NOT contains a field called hash with these values".
So, as mongo search by the whole document, there is no any document where hash value is not on the $nin array.
As another example to exaplain better: Check this example where hash value is 1. In this case, find query works because it matches two conditions:
*
*There is a field name with value test
*There is not any field hash into issues with values into $nin array.
| |
doc_23529948
|
Here is my code
<script type="text/javascript">
var currURL = window.location.href;
$(document).ready(function () {
var hasFilters = currURL.split('?')[1];
alert(hasFilters);
if (hasFilters) {
abc(currURL);
}
});
</script>
When I am running this script in IE9 at that time, in alert showing "undefined" while at other browser in alert shows concate string for currurl for ex : "abc=def:ijk!!a!!".
So I want to do same in IE9.
Maybe somebody can point me to the right answer?
Thx
A: Better yet: window.location object has search property which is what you're trying to find.
http://www.w3schools.com/jsref/obj_location.asp
window.location.search: Sets or returns the querystring part of a URL
Why [1] might not be working...
This is working in IE for me here as long as you have ?x=y at the end. split returns an array and for an index that doesn't exist you will get undefined. Let's look at two test cases:
window.location.href: index.html?x=y
split: 'index.html', 'x=y'
[0] = index.html
[1] = x=y
window.location.href: index.html
split: 'index.html'
[0] = index.html
[1] (etc) = undefined
I think the issue is that in IE you're not including the ? part of the URL. I doubt it is a bug in the browser.
| |
doc_23529949
|
Trying to route between components mentioned below by taking it as params but not able to
garage.ts is the defined model
export class Garage{
geo_coordinates: string;
mobile_number: number;
image: string;
garage_name: string;
address: string;
pin: number;
email: string;
owner_name: string;
type: string;
city: string;
state: string;
tag: string;
rating: number;
about: string;
working_day: string;
working_hours: number
}
data.service.ts is the service where the api is defined
import { Injectable } from '@angular/core';
import { Garage } from './garage';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
G_url = 'xxxxxxx';
constructor(private _http: HttpClient) { }
getGarage(){
return this._http.get<Garage[]>(this.G_url);
}
}
this is how the api looks
[
{
"mobile_number": "78676754565",
"garage_name": "SRI GANPATI MOTORS",
"address": "abohar",
"pin": null,
"email": "hjhjhjhh",
"owner_name": "cccgcgc",
"type": "BIKE",
"city": null,
"geo_coordinates": "12.9797482,77.63484319999999",
"state": "Punjab",
"tag": "PREMIUM ",
"image": "https://s3.ap-south-1.amazonaws.com/gp-master-data/default-logo/garage-default-logo.png",
"rating": 5,
"about": null,
"working_day": null,
"working_hours": null
}
]
the problem im facing is while routing; the pin which is declared as null in the api, the console throws the error mentioned in the title
This is the path ive defined, i want to route the values from MapviewComponent to GarageDetailComponent
app-routing.module.ts
{
path: 'map',
component: MapViewComponent
},
{
path: 'garage/:garage_name/:address/:about/:rating/:type/:mobile_number/:email/:tag/:owner_name/:pin/:image',
component: GarageDetailComponent
},
map-view.component.ts, here the onSelect() takes care of the routing between the two components wherein ive tried doing a null check but didnt work
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { Garage } from '../garage'
import { DataService } from '../data.service';
import { Router } from '@angular/router'
@Component({
selector: 'app-map-view',
templateUrl: './map-view.component.html',
styleUrls: ['./map-view.component.scss'],
})
export class MapViewComponent implements OnInit {
garages$: Garage[];
constructor(
private ngZone: NgZone,
private dataService: DataService,
private router: Router
) {
}
ngOnInit()
{
return this.dataService.getGarage()
.subscribe(data => this.garages$ = data);
}
onSelect(list){
list.pin = (list.pin || null).toString()
console.log(list.pin)
this.router.navigate(['garage', list.garage_name, list.address, list.about, list.rating, list.type, list.mobile_number, list.email, list.tag, list.owner_name,list.pin,list.image])
}
}
garage-detail.component.ts
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import { NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap'
@Component({
selector: 'app-garage-detail',
templateUrl: './garage-detail.component.html',
styleUrls: ['./garage-detail.component.scss'],
providers:[NgbRatingConfig]
})
export class GarageDetailComponent implements OnInit {
public t;
public y;
public ab;
public r;
public p;
public mb;
public mid;
public g;
public own;
public pn;
public img;
constructor(private route: ActivatedRoute){
}
ngOnInit(): void{
let title = this.route.snapshot.paramMap.get('garage_name');
let add = this.route.snapshot.paramMap.get('address');
let about = this.route.snapshot.paramMap.get('about');
let rating = this.route.snapshot.paramMap.get('rating');
let type = this.route.snapshot.paramMap.get('type');
let mob = this.route.snapshot.paramMap.get('mobile_number');
let em = this.route.snapshot.paramMap.get('email');
let tag = this.route.snapshot.paramMap.get('tag');
let owner = this.route.snapshot.paramMap.get('owner_name');
let pn = this.route.snapshot.paramMap.get('pin');
let image = this.route.snapshot.paramMap.get('image');
this.t = title;
this.y = add;
this.ab = about
this.r = rating;
this.p = type;
this.mb = mob;
this.mid = em;
this.g = tag;
this.own = owner;
this.pn = pn
this.img = image
}
}
A: In this way you cannot navigate if some params is null. You can try QueryParams from angular route there's possible navigate with params null
{
path: 'garage',
component: GarageDetailComponent
},
onSelect(list){
this.router.navigate(['garage'],{ queryParams:{
garage_name: list.garage_name,
address: list.address,
about: list.about,
rating: list.rating,
type: list.type,
mobile_number: list.mobile_number,
email: list.email,
tag: list.tag,
owner_name: list.owner_name,
pin: list.pin,
image: list.image
}
})
}
ngOnInit(): void{
let title = this.route.snapshot.queryParamMap.get('garage_name');
let add = this.route.snapshot.queryParamMap.get('address');
let about = this.route.snapshot.queryParamMap.get('about');
let rating = this.route.snapshot.queryParamMap.get('rating');
let type = this.route.snapshot.queryParamMap.get('type');
let mob = this.route.snapshot.queryParamMap.get('mobile_number');
let em = this.route.snapshot.queryParamMap.get('email');
let tag = this.route.snapshot.queryParamMap.get('tag');
let owner = this.route.snapshot.queryParamMap.get('owner_name');
let pn = this.route.snapshot.queryParamMap.get('pin');
let image = this.route.snapshot.queryParamMap.get('image');
this.t = title;
this.y = add;
this.ab = about
this.r = rating;
this.p = type;
this.mb = mob;
this.mid = em;
this.g = tag;
this.own = owner;
this.pn = pn
this.img = image
}
| |
doc_23529950
|
They have mentioned here
that we can set two callbacks onMessageSent or onSendError but i couldn't find the implementation there.
A: The implementation of these methods are very simple, you can just add these methods to your extension of FirebaseMessagingService.
@Override
public void onMessageSent(String msgId) {
super.onMessageSent(msgId);
Log.d(TAG, "Message sent: " + msgId);
}
@Override
public void onSendError(String msgId, Exception e) {
super.onSendError(msgId, e);
Log.e(TAG, "Error sending upstream message: " + e);
}
Note though that to optimize battery, these callbacks are batched, so you may not get the callback till a few messages are sent.
| |
doc_23529951
|
This is not a problem at all, I know how to create such view, but I have a problem in the SQL Server Management Studio. To return the xml through view, I have to add an alias for the result column. However when I do that, I can't preview the returned xml in additional window in the SSMS any more.
e.g
When I'm not using the alias, in the result, the data this is a link which I can click to show the formatted xml in additional window:
With alias I can't do that:
I have a big xml in result, so I need the functionality to preview them. How can I do that?
A: You have to cast this to xml type.
| |
doc_23529952
|
and a Weblogic Server That has the identity provider using SAML 2.0 Federation Service
how can we authenticate APEX Application as service provider with the Weblogic IDP SAML 2.0
I've been searching and reading on the internet but has not come up with a good guide or solution.
Thank you in advance
| |
doc_23529953
|
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
A: so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.
as far as your code reads, what you're actually sending is this:
{[1, 2]:[1, 2]}
which is invalid JSON.
if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:
$.ajax({
url: "backend/retriveData.php",
data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
type:"post",
success: function(response) {
console.log(response);
}
});
A: Because you are echoing the print_r() (which in and of itself is a type of echo) you're returning a value for the truthiness of the print_r(). Change the line to this
print_r($_POST['usedAnswers']);
| |
doc_23529954
|
I've got the following in vimrc:
" This is needed because $MANPATH wasn't set in my environment
let $MANPATH=substitute(system("manpath"),"\n","","")
if (match(expand("%:p:h"),$MANPATH) == -1)
echo ("manpath is: ".$MANPATH)
echo ("path is: ".expand("%:p:h"))
echo ("match: ".match(expand("%:p:h"),$MANPATH))
" Load NERDTree here
endif
When I run vim normally, it works as expected:
andrey@Andrey-P:~$ vim file.txt
manpath is: /usr/local/man:/usr/local/share/man:/usr/share/man
path is: /home/andrey
match: -1
However, opening a man page returns this:
andrey@Andrey-P:~$ man vim
manpath is: /usr/local/man:/usr/local/share/man:/usr/share/man
path is: /usr/share/man
match: -1
One would expect this to be a fairly straightforward match to make, but it doesn't seem to work. Can anyone help?
A: It looks like you've got the arguments to match() the wrong way around. The first argument should be the expression to be searched ($MANPATH in your case) and the second argument should be search pattern.
See :help match() for a full description of the function.
| |
doc_23529955
|
focus() and select() does not work
Using html and plain javascript
A: If I understand correctly, use addEventListener() to achieve the effect you want
<input type="number" id="input" />
<script>
document.getElementById('input').addEventListener('focus', function() {
console.log('input focus')
})
document.getElementById('input').addEventListener('select', function() {
console.log('input select')
})
</script>
A: I have confirmed this issue in chrome (using select()).
I found this Mozilla website. It suggests this: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
In browsers where it is not supported, it is possible to replace it
with a call to HTMLInputElement.setSelectionRange() with parameters 0
and the input's value length:
I haven't tested this with input type=number, but I believe it SHOULD work. Probably. Maybe :)
-- Edit --
I just tested this. It is working for me with focus()
| |
doc_23529956
|
My University.h:
#ifndef UNIVERSITY_H
#define UNIVERSITY_H
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#include "Department.h"
#include "Student.h"
#include "Course.h"
#include "Faculty.h"
#include "Person.h"
class University
{
friend ostream& operator<< (ostream& os, const vector<Department>& D);
friend ostream& operator<< (ostream& os, const Department& department);
protected:
vector<Department> Departments;
vector<Student> Students;
vector<Course> Courses;
vector<Faculty> Faculties;
static bool failure;
static bool success;
public:
bool CreateNewDepartment(string dName, string dLocation, long dChairID);
bool ValidFaculty(long dChairID);
};
#endif
My University.cpp:
#ifndef UNIVERSITY_CPP
#define UNIVERSITY_CPP
#include<string>
#include<vector>
#include<iostream>
using namespace std;
#include "University.h"
ostream& operator<<(ostream& os, const vector<Department>& D);
ostream& operator<<(ostream& os, const Department& department);
bool University::failure = false;
bool University::success = true;
bool University::CreateNewDepartment(string dName, string dLocation, long dChairID)
{
if((dChairID != 0) && (ValidFaculty(dChairID)== University::failure))
{
Department D(dName, dLocation, dChairID);
Departments.push_back(D);
for (int i = 0; i < Departments.size(); i++)
cout << Departments;
return University::success;
}
return University::failure;
}
bool University::ValidFaculty(long dChairID)
{
for (int i = 0; i < Faculties.size(); i++)
{
if (Faculties[i].ID == dChairID)
return University::success;
}
return University::failure;
}
ostream& operator<<(ostream& os, const vector<Department>& D)
{
for (int i = 0; i < D.size(); i++)
os << D[i] << endl;
os << "\n";
return os;
}
ostream& operator<< (ostream& os, const Department& department)
{
department.Print(os);
return os;
}
#endif
My Department.h:
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include<vector>
#include<string>
#include<iostream>
using namespace std;
class Department
{
friend class University;
friend ostream& operator<< (ostream& os, Department& department);
protected:
long ID;
string name;
string location;
long chairID;
static long nextDepartID;
public:
Department();
Department(string dName, string dLocation, long dChairID);
void Get();
void Print(ostream& os)const;
};
#endif
My Department.cpp:
#ifndef DEPARTMENT_CPP
#define DEPARTMENT_CPP
#include<iostream>
#include<string>
using namespace std;
#include "Department.h"
long Department::nextDepartID = 100;
Department::Department()
{
ID = nextDepartID++;
name = "Null";
location = "Null";
chairID = 0;
}
Department::Department(string dName, string dLocation, long dChairID):name(dName), location(dLocation), chairID(dChairID)
{
ID = nextDepartID++;
}
void Department::Get()
{
}
void Department::Print(ostream& os)const
{
os << "\n";
os << ID << endl;
os << name << endl;
os << location << endl;
os << chairID << endl;
os <<"\n\n";
}
ostream& operator<< (ostream& os, const Department& department)
{
department.Print(os);
return os;
}
#endif
Now everything can be seen that pertains only to this problem. The only error I receive now is that void value is not being ignored.
Snippet of error:
University.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Department&)’:
University.cpp:53: error: void value not ignored as it ought to be
Department.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Department&)’:
Department.cpp:42: error: void value not ignored as it ought to be
FINAL EDIT:
Thanks to everyone that helped me. I definitely have a better understanding of operator overloading now...especially when it deals with printing vectors of user-defined types!
A: The complaint was that while your function to iterate over and print the vector contents may have been correct, the actual object contained by the vector did not have an operator<< specified.
You need to have one.
If you already have a method called Print() in your Department class, you could simply create an overload for operator<< as follows:
std::ostream& operator<<(std::ostream& os, const Department& department) {
os<<department.Print();
return os;
}
I had prepared the following code before you posted your update. Maybe it can help you.
#include<iostream>
#include<vector>
#include<string>
class Department {
public:
Department(const std::string& name)
: m_name(name) { }
std::string name() const {
return m_name;
}
private:
std::string m_name;
};
// If you were to comment this function, you would receive the
// complaint that there is no operator<< defined.
std::ostream& operator<<(std::ostream& os, const Department& department) {
os<<"Department(\""<<department.name()<<"\")";
return os;
}
// This is a simple implementation of a method that will print the
// contents of a vector of arbitrary type (not only vectors, actually:
// any container that supports the range-based iteration): it requires
// C++11.
template<typename T>
void show(const T& container) {
for(const auto& item : container) {
std::cout<<item<<std::endl;
}
}
int main() {
std::vector<Department> deps = {{"Health"}, {"Defense"}, {"Education"}};
show(deps);
}
Compile with g++ example.cpp -std=c++11 -Wall -Wextra (I used OS X 10.7.4 and GCC 4.8.1) to get:
$ ./a.out
Department("Health")
Department("Defense")
Department("Education")
| |
doc_23529957
|
<button onClick={(e) => this.handleClick(e)}>
or
<button onClick={this.handleClick.bind(this)}>
creates a new function each time. And it is said it is a problem. But what exactly is a problem?
The docs says:
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering.
But isn't it wrong concept?
1) First, this itself is a problem, even if it is not passed down to to a lower component. Because when this is rendered to a virtual DOM tree, it is compared to the previous virtual DOM tree, and seeing it is a different click handler, it needs to update the actual DOM -- either by changing the onclick attribute or by removeEventListener() and addEventListener() to change the handler. Usually we don't want to update the actual DOM, as it is much more expensive than the virtual DOM.
2) Second, no matter it is passed down to lower components, the lower components will re-render anyway. UNLESS if the lower components are PureComponent or are optimized by React.memo(). But if they are just Component, the lower components are re-rendered anyway. So this conveys a wrong concept. It can cause actual DOM update in lower components, but this is covered in (1) already, and is true regardless of whether it is passed down the lower components.
3) One possibility is that changing the event listener is not as costly as other actual DOM operations, so the concern is if the click handler is passed down to lower components and the components use a PureComponent or React.memo to not re-render when the props didn't change, and passing in a new handler will cause the lower components to re-render. But this is the case only if lower components are not the regular Component.
So the actual problem is about needing to cause an update to the actual DOM.
And the word "re-render" above doesn't mean an update to actual DOM. "re-render" means making a virtual DOM tree, either by the render() of a class component, or by a function component returning React elements just like render(). (just to make sure we are talking about the same thing).
| |
doc_23529958
|
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
login_count = models.PositiveIntegerField(default=0)
class Supplier(User):
company_name= models.CharField(max_length=30)
company_domain=models.CharField(max_length=30)
class Meta:
verbose_name = 'supplier'
verbose_name_plural = 'suppliers'
class Worker(User):
ACCOUNT_TYPE = (
('1', 'Admin'),
('2', 'Regular'),
)
is_hub_manager = models.BooleanField(default=False)
account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE)
class Meta:
verbose_name = 'worker'
verbose_name_plural = 'workers'
I also created an authenetication endpoint using Django rest framework. Surprisingly when I authenticate the admin everything works well. When I create a supplier and try to authenticate them. They always return invalid credentials. Here are my API views
from rest_framework.generics import GenericAPIView
from .serializers import UserSerializer
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from django.contrib import auth
import jwt
class LoginView(GenericAPIView):
serializer_class = UserSerializer
def post(self, request):
data = request.data
username = data.get('username', '')
password = data.get('password', '')
user = auth.authenticate(username=username, password=password)
if user:
auth_token = jwt.encode({'username': user.username}, settings.JWT_SECRET_KEY)
serializer = UserSerializer(user)
data = {'user': serializer.data, 'token': auth_token}
return Response(data, status=status.HTTP_200_OK)
# SEND RES
return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
What could I be doing wrong?
A: The first thing, you should check AUTH_USER_MODEL keyword in setting file.
E.g. AUTH_USER_MODEL = '<module>. User'.
Regarding your case, the root cause is not yet custom your authenticate() method in your backend. You defined Supplier and Worker which are inherited from the User class.
Also, you can refer to this link for detail.
| |
doc_23529959
|
class AbstractCar:
def __init__(self):
self.engine = self.engine_class()
def __init_subclass__(cls, *, engine_class, **kwargs):
super().__init_subclass__(**kwargs)
cls.engine_class = engine_class
class I4Engine:
pass
class V6Engine:
pass
class Compact(AbstractCar, engine_class=I4Engine):
pass
class SUV(AbstractCar, engine_class=V6Engine):
pass
Now I want to derive another class from one of those derived classes:
class RedCompact(Compact):
pass
The above does not work, because it expects me to re-provide the engine_class parameter. Now, I understand perfectly, why that happens. It is because the Compact inherits __init_subclass__ from AbstractCar, which is then called when RedCompact inherits from Compact and is subsequently missing the expected argument.
I find this behavior rather non-intuitive. After all, Compact specifies all the required arguments for AbstractClass and should be usable as a fully realized class. Am I completely wrong to expect this behavior? Is there some other mechanism that allows me to achieve this kind of behavior?
I already have two solutions but I find both lacking. The first one adds a new __init_subclass__ to Compact:
class Compact(AbstractCar, engine_class=I4Engine):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(engine_class=I4Engine, **kwargs)
This works but it shifts responsibility for the correct working of the AbstractCar class from the writer of that class to the user. Also, it violates DRY as the engine specification is now in two places that must be kept in sync.
My second solution overrides __init_subclass__ in derived classes:
class AbstractCar:
def __init__(self):
self.engine = self.engine_class()
def __init_subclass__(cls, * , engine_class, **kwargs):
super().__init_subclass__(**kwargs)
cls.engine_class=engine_class
@classmethod
def evil_black_magic(cls, **kwargs):
AbstractCar.__init_subclass__(engine_class=engine_class, **kwargs)
if '__init_subclass__' not in cls.__dict__:
cls.__init_subclass__ = evil_black_magic
While this works fine for now, it is purest black magic and bound to cause trouble down the road. I feel like this cannot be the solution to my problem.
A: Indeed—the way this works in Python is counter-intuitive—I agree with you on your reasoning.
The way to go to fix it is to have some logic in the metaclass. Which is a pity, since avoiding the need for metaclasses is exactly what __init_subclass__ was created for.
Even with metaclasses it would not be an easy thing—one would have to annotate the parameters given to __init_subclass__ somewhere in the class hierarchy, and then insert those back when creating new subclasses.
On second thought, that can work from within __init_subclass__ itself. That is: when __init_subclass__ "perceives" it did not receive a parameter that should have been mandatory, it checks for it in the classes in the mro (mro "method resolution order"—a sequence with all base classes, in order).
In this specific case, it can just check for the attribute itself—if it is already defined for at least one class in the mro, just leave it as is, otherwise raises.
If the code in __init_subclass__ should do something more complex than simply annotating the parameter as passed, then, besides that, the parameter should be stored in an attribute in the new class, so that the same check can be performed downstream.
In short, for your code:
class AbstractCar:
def __init__(self):
self.engine = self.engine_class()
def __init_subclass__(cls, *, engine_class=None, **kwargs):
super().__init_subclass__(**kwargs)
if engine_class:
cls.engine_class = engine_class
return
for base in cls.__mro__[1:]:
if getattr(base, "engine_class", False):
return
raise TypeError("parameter 'engine_class' must be supplied as a class named argument")
I think this is a nice solution. It could be made more general with a decorator meant specifically for __init_subclass__ that could store the parameters in a named class attribute and perform this check automatically.
(I wrote the code for such a decorator, but having all the corner cases for named and unamed parameters, even using the inspect model can make things ugly)
| |
doc_23529960
|
TableA
colA colB colC colD colE
a b x y z
b c d f h
c d f w v
v f f f f
to update colA with value from colE
TableA
colA colB colC colD colE
z b x y z
h c d f h
v d f w v
f f f f f
A: This is too simple:
update tableA set colA = colE;
A: Try to use this code:
update TableA
set colA = colE;
A: Update table like this
update tableA set
colA = colE;
it will update as you want
A: update [table]
set [colA] = [colE]
should work for you :) try on some test data before live data though
| |
doc_23529961
|
await page.evaluate(function() {
var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) console.log(links[i].href);
});
However I would like to do this with page.$$ and I'm unsure how you would do this. I'm trying to do everything without the need for page.evaluate because it seems entirely unnecessary. Puppeteer has lots of cool gadgets I'm trying to get a grasp with.
A: The documentation for what you're looking for is here: https://github.com/puppeteer/puppeteer/blob/v5.4.1/docs/api.md#pageselector-1 You can take that example and adjust it to your needs.
It'd be:
const linksHrefs
= await page.$$eval('a', links => links.map(link => link.getAttribute('href')));
console.log(linksHrefs);
| |
doc_23529962
|
type = **someWayToDeduceTheObjectType()**
fields = type.getDeclaredFields()
System.out.println("The type of the object is : " + type);
System.out.println("The fields of this type of class is : " + fields);
}
Is it possible to infer the object type of a passed object from a generic reference type?
If not, what is the reason?
I assume this is not possible, because of the existence of casting, but I can't pinpoint the exact reason.
EDIT: I'm not referring to instanceof operator here. Assume I don't have a list of Types to compare with.
A: It's quite possible - you just call getClass():
public static void printType(Object o){
type = o.getClass();
fields = type.getDeclaredFields()
System.out.println("The type of the object is : " + type);
System.out.println("The fields of this type of class is : " + fields);
}
| |
doc_23529963
|
{"content":["info":{"tid":(uint)123,"pid":(int)456}],"header":{"test":"hello"}}
For compare two this string with python json, I need to format this string, because it decoded wrong using python json, it can run right if (unit)123 were "(uint)123". Now I have written code using c, the bellow:
void dofile(char *filename)
{
FILE *f;
long len;
char *data;
char *head;
char *ptr;
char *value;
f=fopen(filename,"rb");
fseek(f,0,SEEK_END);
len=ftell(f);
fseek(f,0,SEEK_SET);
data=(char*)malloc(len+1);
fread(data,1,len,f);
data[len]='\0';
fclose(f);
head = data;
ptr = data;
while (*ptr)
{
if (*ptr++ == '\\')
continue;
int l = 1;
if (*ptr=='\"' && *++ptr==':' && *++ptr=='(')
{
value = ptr;
while (*ptr++ != ')' && *ptr && ++l)
;
ptr++;
len++;
if (*ptr == '-')
{
ptr++;
l++;
}
while(*ptr >= '0' && *ptr <= '9' && *ptr && ++l)
{
ptr++;
}
char *tmp = (char*)malloc(len+2);
memcpy(tmp, head, value-head);
memset(tmp+(value-head), '\"', 1);
memcpy(tmp+(value-head)+1, value, ptr-value);
memset(tmp+(ptr-head)+1, '\"', 1);
memcpy(tmp+(ptr-head)+2, ptr, len-(ptr-head));
len += 2;
ptr = tmp + (ptr-head)+2;
free(data);
data = tmp;
head = data;
}
}
f = fopen(filename, "wb");
fwrite(data, len-1, 1, f);
fclose(f);
printf("%s\n", data);
free(data);
}
OK, it is OK, but has it problem? Because I think that I use many mem function.
| |
doc_23529964
|
Its like this:
<div class='userprofile'>
<?php
include_once('profile.php')
?>
</div>
Now I want to edit this profile, by using some page like "editprofile.php".
The user should click on "EditProfile" button visible on top of his profile, and then on the same page (without redirecting), he can edit his profile.
How to implement this ?
A: You can use Jquery For This
<div class='userprofile'>
<?php
include_once('profile.php')
?>
</div>
<div class='editprofile'>
<?php
include_once('editprofile.php')
?>
</div>
By default give editprofile class display none property
.editprofile
{
Display:none;
}
and when user clicks on "EditProfile" Button With Jquery Hide the Div width class "userprofile" and show the div with class"editprofile"
$('userprofile').css('Display','None');
$('editprofile').css('Display','block');
OR
$('editprofile').css('Display','inline-block');
Whichever property you want use it
Note : I am using css properties to hide the dive you can also use the simple hide and show function.
Let me know if you want the full code for this if you are not good with jquery
| |
doc_23529965
|
The man pages installed on the system itself are outdated.
Is there a way to replace the systems current man pages with the given tar ball or make them more accessible, such that I can search through them and use less to read them?
A: You can just untar them and then point man at specific files. E.g:
$ cd man-pages-6.00
$ man man3/printf.3
This will open the man page in your pager.
You can also set the MANPATH environment variable to point to this location; then man will use it by default:
$ cd man-pages-6.00
$ export MANPATH=$PWD
$ man printf
This will replace the system man pages, so that running man for a command not included in the tar archive will fail:
$ man ls
No manual entry for ls
You can get the best of both worlds by telling man to search the unpacked tar archive first, and then search the system man pages:
$ cd man-pages-6.00
$ export MANPATH=$PWD:
$ man ls
That trailng : in MANPATH=$PWD: means "use the default path".
| |
doc_23529966
|
site.com/user/?id=3
But i don't want to do like this. I want GitHub-like urls, like this:
site.com/user/UserName/
Also, i need to allow URL continutation to specify which 'action' is requested, like subscribe, or comments, and parameters, for specified username:
site.com/user/Admin/comments/32
site.com/user/Admin/virtual/path/
which should be a simple rewrite to physical path: `/user/index.php'.
I am newbie in PHP, but i know basics of mod_rewrite and .htaccess, and i still don't understand how can i determine which user (Admin) and what action (comments) is requested by URL, in my PHP script index.php.
Please teach how can i reach this URL syntax for my site? Or better, how to redirect /user/Admin/comments to physical /user/comments.php..
*
*How to set up such dynamic rewriting with saving the username/action for php script?
*How script can access user name and action (comments, 32) requested by URL
*How should i rename my question, because this title seems to be incorrect.
Sorry for long text, i am new in clean PHP scripting, Thanks!
A: If you really want to do it yourself and that's fine if you do, this is an example of what you will need to do. I understand not everyone needs or wants to use a framework.
First lets say your user URL is this like Github example.
http://www.yoursite.com/user/dmitrij
Then to for your .htaccess you will need a rewrite rule like this.
RewriteEngine On
# check to make sure the request is not for a real file
RewriteCond %{REQUEST_FILENAME} !-f
# check to make sure the request is not for a real directory
RewriteCond %{REQUEST_FILENAME} !-d
#route request to index.php
RewriteRule ^user/([^/]+)/? /user/index.php?id=$1 [L]
Then if you want to show comments, your URL can look like this
http://www.yoursite.com/user/dmitrij/comments/32
Then it you can use .htaccess
RewriteEngine On
# check to make sure the request is not for a real file
RewriteCond %{REQUEST_FILENAME} !-f
# check to make sure the request is not for a real directory
RewriteCond %{REQUEST_FILENAME} !-d
#route request to index.php
RewriteRule ^user/([^/]+)/comments/([0-9]+)/? /user/index.php?id=$1&comment_id=$2 [L]
Then you can put them all together in your .htaccess file for both URL's.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)/comments/([0-9]+)/? /user/index.php?id=$1&comment_id=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)/? /user/index.php?id=$1 [L]
Then in your index.php you will check the $_GET request. This is a very simple example.
<?php
$username = $_GET["id"];
$com_id = $_GET["comment_id"];
print_r($username);
exit;
?>
Make sure mod_rewrite is enabled on the server and AllowOverride All is set in your vhost or config file.
You can do whatever you want with the values in $_GET. You will have to ensure username is unique in your database. You can also add more rewrites for different URL's too, which I wont cover here.
This should get you a good start.
A: Use either a URL-Rewrite-Engine or start programming with an MVC framework like symfony or cakePHP, there the functionality is included
A: Like the answer above - you need to enable mod_rewrite and then provide the mapping pattern inside your .htaccess file.
I believe you also have to ensure that your Virtual Host is configured to
`Allow Override ALL`
This page provides good details - scroll down to the part entitled "How to Rewrite urls".
http://www.smashingmagazine.com/2011/11/02/introduction-to-url-rewriting/
| |
doc_23529967
|
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.println("Enter the Number");
int num = a.nextInt();
System.out.println("Enter the base for the given number");
int base = a.nextInt();
converting(num,base);
public static int converting(int num , int base) {
String sum="";
while(num > 0) {
int rem = 0;
rem = num % base;
num = num / base;
sum = rem + sum;
}
System.out.println(sum);
}
}
}
for my above java code,am getting compier error saying:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method converting(int, int) is undefined for the type ConvertingNumber
void is an invalid type for the variable converting
Syntax error on token "(", ; expected
Duplicate local variable num
Syntax error on token ",", ; expected
Duplicate local variable base
Syntax error on token ")", ; expected
at aj.ConvertingNumber.main(ConvertingNumber.java:12)
Please anyone help me out in solving this. Thanks in advance.
A: converting method should be out side from the main method
package aj;
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
System.out.println("Enter the Number");
int num=a.nextInt();
System.out.println("enter the base for the given number");
int base=a.nextInt();
converting(num,base);
}
//This method should be out side the main method
public static void converting(int num , int base) {
String sum="";
while(num>0) {
int rem=0;
rem=num%base;
num=num/base;
sum=rem+sum;
}
System.out.println(sum);
}
}
A: I have Corrected Your code..
package aj;
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
System.out.println("Enter the Number");
int num=a.nextInt();
System.out.println("enter the base for the given number");
int base=a.nextInt();
ConvertingNumber .converting(num,base);
//converting(num,base);
}
public static int converting(int num , int base)
{
int sum=0;
while(num>0)
{
int rem=0;
rem=num%base;
num=num/base;
sum=rem+sum;
}
//System.out.println(sum);
return sum;
}
}
| |
doc_23529968
|
The first file is parser.py:
from collections import OrderedDict
import csv
import json
import requests
import time
from collections import defaultdict
def load_matrices():
# code...
def get_sorted_tuples(matrix, country, code_to_name, size=20):
# code...
The second is b.py:
from collections import OrderedDict
import json
from geojsontosvg import lolatoxy
from parser import get_sorted_tuples, load_matrices
import math
When I run b.py, I get this error:
from parser import get_sorted_tuples, load_matrices
ImportError: cannot import name get_sorted_tuples
What's wrong with the code?
A: The problem here is that Python has a module named parser in standard library, and that's what you're actually trying to import from. You have two options:
*
*Rename parser.py to something else.
*If both files are inside a package, do relative import in b.py:
from .parser import get_sorted_tuples, load_matrices
| |
doc_23529969
|
I followed the following steps to achieve the fallback:
*
*Added exceptions for the mobile devices. Navigated to the Magento administrative area -> System -> Configuration -> Design -> Themes. Clicked on the Add Exceptions buttons besides the Templates, Skin and Layout labels.
*Entered the following line in the Matched Expression field:
iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini
*In the Value field entered iphone and saved the changes.
It worked like a charm for all my pages except for the category and product pages. I checked the Category settings under Manage Categories and the design of these pages seems to be handled in the Custom Design tab.
How do I make my exceptions overide this setting?
A: I Thought the field in custom design had to be populated with one of the themes from the drop down. Apparently you can leave it on --Please Select-- and it will still save without errors.
The exceptions work perfectly know, DOH!
| |
doc_23529970
|
Num Percent
5 9.44
4 19.7
4 10.64
4 10.81
4 10.97
4 11.35
3 13.18
3 24.54
3 24.99
3 12.95
3 13.17
3 24.29
3 13.81
3 13.93
3 27.87
3 13.26
2 41.41
2 34.19
2 41.6
2 19.31
2 34.4
2 38.72
2 18.16
2 36.28
2 18.95
2 18.49
I would like to plot the data such that, along with the plot of 'num'(x) and 'percent'(y), the mean at every point of the x axis (2,3,4,5) is added to the plot and a regression line based on the mean series is plotted.
A: Calling your data frame DF
MeansByNum <- tapply(DF$Percent, DF$Num, mean) #Create an array of means by Num
NewDF <- data.frame(cbind(Num = as.numeric(as.vector(names(MeansByNum))),
Percent = as.numeric(MeansByNum)))
plot(Percent~Num, DF)
points(NewDF$Num, NewDF$Percent, col="red")
abline(lm(Percent~Num, NewDF))
| |
doc_23529971
|
And my c++ code :
#include <iostream>
#include <SDL/SDL.h>
#include <GL/glew.h>
#include <GL/glu.h>
#define WIDTH 500
#define HEIGHT 500
static float angle = 0.0f;
static void eventListener(SDL_Event *pEvent, bool *pContinue)
{
while (SDL_PollEvent(pEvent))
{
switch(pEvent->type)
{
case SDL_QUIT:
*pContinue = false;
break;
case SDL_KEYDOWN:
switch (pEvent->key.keysym.sym)
{
case SDLK_ESCAPE:
*pContinue = false;
break;
}
break;
}
}
}
#undef main
int main(void)
{
SDL_Event myEvent;
bool isAlive = true;
SDL_Init(SDL_INIT_VIDEO);
SDL_WM_SetCaption("Simple SDL window", NULL);
SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_OPENGL);
while (isAlive == true)
{
eventListener(&myEvent, &isAlive);
}
SDL_Quit();
return (0);
}
I don't understand this message which is not precise. However my x64 SDL libraries linked to my project seems to be correct because the compilation is ok. So I wonder what's happening here. Does anyone already have encountered the same problem ?
A: Just googled for your error message, and it says that this error code (0x0c000007b) means INVALID_IMAGE_FORMAT.
This means that either you are mixing 32 and 64 bit binaries or you have corrupted binaries. Try to place you binary and your dependencies at the same folder and run the application. If the error continues, than one of your libraries must be corrupted. Else, it was a problem with the Windows loading a library for a different platform of your compiled binary.
| |
doc_23529972
|
This is inside script tags in the View :
function DeleteRoom(id, IDarray) {
$.ajax({
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ IDarray,
type: "DELETE",
dataType: 'json',
data: IDarray, //data that will be passed to the array (?)
traditional: true, //if I get it right, this serializes the array
success: function (data) {
... }
});
}
This is the API
public void DeleteRoom (int id, [FromUri] int[] IDarray)
This only reads the first element in the array from database, and so it deletes only the first element. It's like I'm passing Int! Then the browser crashes (stop script) and I get this error
DELETE .../api/Room/RemoveRoomWithDevices?RoomId=2392&userDevicesId=1549
204 No Content 62ms
XML Parsing Error: no element found Location: moz-nullprincipal
Is the url syntax wrong? Or else, is there suggestions to make this work?
A: You can use JSON.stringify()
here is your url
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ JSON.stringify(IDarray)
Btw why you are using again a data attribute in ajax call..? Since you have included data array in the url.
| |
doc_23529973
|
i have N outside-divs, with variable, dynamic height.
every outside-div will have ONE inside-div, which should be at the bottom of the outside div.
so, using the trick with position absolute like in How do I align an inner div with the bottom of an outer div? is not possible.
I made a jsfiddle for you to play around:
http://jsfiddle.net/xSTtp/4/
HTML:
<div class="outside">
<div class="inside">
xyz
</div>
</div>
<div class="outside">
<div class="inside">
xyz
</div>
</div>
CSS:
.outside {
/* the height will be dynamic, 100px is just for the demo */
height: 100px;
border: 1px solid green;
}
.inside {
border: 1px solid red;
/* not working*/
/* display: table-cell;
vertical-align: bottom;
*/
/* i want the red at the bottom of the green, not in the page */
position: absolute;
bottom: 0;
}
Thanks
Joerg
A: Why is position: absolute; bottom: 0; not possible?
The wrapper div or parent div needs to have a position: relative; or position: absolute; for it to position the child at the bottom.
.outside {
position: relative;
border: 1px solid green;
}
.inside {
position: absolute;
border: 1px solid red;
bottom: 0;
}
A: http://jsfiddle.net/xSTtp/6/ If you know the height of the parent div, you can just specify top: [parent height-child height]
| |
doc_23529974
|
import jaydebeapi as jdba
def get_hive_jdbc_con():
driver="org.apache.hive.jdbc.HiveDriver"
conn_url="jdbc:hive2://tlgdhadlap12.r-office.com:10000/default"
auth_lst=["un","pw"]
conn = jdba.connect(driver,conn_url,auth_lst,"c:/app/hive-jdbc-1.2.1000.2.6.4.0-91-standalone.jar")
return conn
get_hive_jdbc_con()
error is return:
Traceback (most recent call last):
File "C:/../PycharmProjects/untitled/venv/Scripts/GilaTest", line 10, in <module>
get_hive_jdbc_con()
File "C:/../PycharmProjects/untitled/venv/Scripts/GilaTest", line 7, in get_hive_jdbc_con
conn = jdba.connect(driver,conn_url,auth_lst,"c:/app/hive-jdbc-1.2.1000.2.6.4.0-91-standalone.jar")
File "C:\..\PycharmProjects\untitled\venv\lib\site-packages\jaydebeapi\__init__.py", line 68, in connect
connection = gateway.jvm.DriverManager.getConnection(*driver_args)
File "C:\..\PycharmProjects\untitled\venv\lib\site-packages\py4j\java_gateway.py", line 1160, in __call__
answer, self.gateway_client, self.target_id, self.name)
File "C:\..\PycharmProjects\untitled\venv\lib\site-packages\py4j\protocol.py", line 324, in get_return_value
format(target_id, ".", name, value))
py4j.protocol.Py4JError: An error occurred while calling z:java.sql.DriverManager.getConnection. Trace:
py4j.Py4JException: Method getConnection([class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String, class java.lang.String]) does not exist
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:339)
at py4j.Gateway.invoke(Gateway.java:276)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Unknown Source)
Thanks for any help!
Gila
| |
doc_23529975
|
I realized that this was because eval's default environment is parent.frame(). Is there a good reason for this? I would expect it to be the same as, say, assign, that is, the current environment.
Here is an example (per Gabor's request):
fnFoo = function() {
# assign 10 variables
for(i in 1:10) assign(paste('v', i, sep = ''), rnorm(10))
# find the variables by name and evaluate them
Map(sum, lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)), eval))
}
# test that eval is unable to find a variable declared in the function scope
fnFoo()
However, changing the function to
fnFoo = function() {
# assign 10 variables
for(i in 1:10) assign(paste('v', i, sep = ''), rnorm(10))
# find the variables by name and evaluate them
# Map(sum, lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)), eval))
Map(sum, lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)), function(x) eval(x, envir = environment())))
}
# now it works
fnFoo()
works.
Thanks.
A: Your problem is that you are being too clever with your lapply in conjuction with eval. Let's expand what is happening.
lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)), eval)
is equivalent to
lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)),
function(x) eval(x))
However, a separate scope gets created for function(x) eval(x), which no longer has v1, v2, etc. in its immediate environment. Thus, you want to tell eval in conjunction with lapply to use the correct environment:
lapply(parse(text = grep('v', ls(envir = environment()), value = TRUE)),
eval, envir = environment())
By the way, another approach is
apply(sapply(grep('v', ls(envir = environment()), value = TRUE), get, envir = environment()), 1, sum)
| |
doc_23529976
|
I've written a chunk of code which isn't working correctly. What I'm trying to do is pass an array as an argument to a function so when I return from the function I can continue using the array. My below code gives me a SEG fault or an 'Illegal Instruction' Error, it's random. If someone could give some adive if this is how one passes an array to a function.
struct message sMsg[nodeCount];
/* get contents into an array */
getFile(file, sMsg);
void getFile (FILE *file, struct message sMsg*) {
.....
}
A: Change
void getFile (FILE *file, struct message sMsg*)
to
void getFile (FILE *file, struct message *sMsg)
But this will not SEGFAULT, its a compile time error.
A: It will be more correct to declare the function the following way specifying the third parameter
void getFile (FILE *file, struct message *sMsg, size_t n );
and call it as
getFile( file, sMsg, nodeCount );
| |
doc_23529977
|
A: I've managed to do it by creating a selection list that's a copy of the list-items in your combo-box.
Here's some code. Assume the combo is called c and the frame is called f. This works even if you have a widget directly under your combo.
def var hSL as handle no-undo. /* Mandatory variable definition in your program */
on ' ' of c do:
create selection-list hSL
assign frame = frame f:handle
col = c:col in frame f
row = c:row in frame f + 1
list-items = c:list-items in frame f
visible = yes
sensitive = true
triggers:
on return persistent run piChoose.
on leave persistent run piLeave.
end triggers.
apply 'entry' to hSL.
end.
procedure piChoose:
assign c:screen-value in frame f = hSL:Screen-value.
assign c.
apply 'leave' to self.
end procedure.
procedure piLeave:
delete object hSL no-error.
end procedure.
Note if you're using list-item-pairs, then the LIST-ITEM-PAIRS attribute should be used where I'm using list-items.
Hope that helps!
| |
doc_23529978
|
So First, I followed some instructions to reset the adb in DDMS, AND then it gives me "adb failed to start, make sure the plugin is properly configured".
After reading some other solutions, I kill the adb.exe in my task manager, but it became alive again after 2 seconds.
I have restart my eclipse and pc couple of times, still no luck.
anyone know whats the problem? I am using win8, don't know if it the problem...
A: You can solve this issue by following below mentioned steps
*
*Go to Task Manager and kill adb.exe from Process tab
*Go to DDMS->Devices tab in eclipse and select option Reset adb.
*Your emulator will come in Online and can go further.
If this should not work, try restarting Eclipse and the emulator, and try the steps again.
| |
doc_23529979
|
A: The page which needs to update depending on database contents must poll the DB every so often. Javascript is a client-side technology and is not designed for directly interacting with back-end servers.
The javascript would look like this (using jquery):
$.post("/webroot/checkForChanges.php",
{ currentNumber: currNumString },
function(dat){
$(dat).find('link').each( function() {
$('#linksTable').append(""+$(this).text()+"");
});
});
This will make a POST request to the page you will write (checkForChanges.php) with the variable named currentNumber who has a value which is the string representation of the number of links currently in the table (count these however you like).
the function(dat) part of the code is the callback function that is run when the request completes (which is when the php page has finished processing and the resulting text has been received into the browser).
I will come back to what this is doing when I have explained what the PHP page is doing.
You haven't told us anything about your database structure, but since you are successfully allowing people to add links you must have a sequence defined somewhere which keeps track of an integer id for the link (so that every link can be given a unique id in the database). I'll assume you've called this 'links-count'
You should create a simple php page with the following pseudo-code:
//open a database connection
$DB = connect( name, user, password );
//receive value
$currNum = $_POST['currentNumber'];
//check to see if sequence number has incremented since last time:
$seqNum = query( "SELECT currval('links-count')" );
if ($seqNum == $currNum){
exit(0);
} //if they are the same, just exit the page without writing anything
//otherwise, carry on... get the result of your query (for new links)
//and loop through, echoing return data
$newEntries = query("SELECT url FROM links WHERE id > ".$currNum);
echo "<newlinks>";
while ( $result = fetch_result( $newEntries ) ) {
echo "<link><a>".$result."</a></link>";
}
echo "</newlinks>";
The output returned by this page will be an xml document with a node for each link which contains the HTML you want to put in your table cell.
Now we can go back to the callback function in the $.post request in your client-side java code:
function(dat){
$(dat).find('link').each( function() {
$('#linksTable').append(""+$(this).text()+"");
});
});
dat is the returned text, wrap it as a jquery object and then find the collection of tags named 'link'. for each 'link' tag returned by the php page, execute a function which appends a new table row to the linksTable which contains the data inside the link tags.
A: You can have an active javascript on the separate page that basically polls the db for changes or you can have a callback function do this after a successful submission. I'm not exactly sure what is going here so I do not really know what to recommend.
| |
doc_23529980
|
ID | Employee_ID | Date | InOutMode
-------+-------------+---------------------+-----------
70821 | 104 | 2019-10-11 19:00:00 | 0
70850 | 104 | 2019-10-12 07:01:00 | 1
if i'm going to separate the IN and OUT it suppose to be like this:
ID | Employee_ID | IN | OUT
-------+-------------+---------------------+-----------
70821 | 104 | 2019-10-11 19:00:00 | 2019-10-12 07:01:00
What happens is, i don't know if my queries were wrong. the TIME-OUT is not 2019-10-12 but 2019-10-11 same as the TIME-IN it looks like this:
ID | Employee_ID | IN | OUT
-------+-------------+---------------------+-----------
70821 | 104 | 2019-10-11 19:00:00 | 2019-10-11 07:01:00
A: Try this,
DECLARE @Temp_Table Table
(
Empoyee_id int,
[Date] datetime,
[InOutMode] bit
)
INSERT INTO @Temp_Table
(
Empoyee_id,[Date],[InOutMode]
)
SELECT 104,'20191011 09:30',1
UNION ALL
SELECT 104,'20191011 19:30',0
UNION ALL
SELECT 104,'20191012 09:30',1
UNION ALL
SELECT 104,'20191012 12:30',0
UNION ALL
SELECT 104,'20191012 19:00',0
UNION ALL
SELECT 104,'20191013 09:30',1
UNION ALL
SELECT 104,'20191013 07:30',0
UNION ALL
SELECT 104,'20191014 09:30',1
SELECT Empoyee_id,[Date],[In],IIF([In]>[Out],null,[Out]) as [Out]
FROM
(
SELECT Empoyee_id,CAST([Date] AS DATE) AS [Date],
MIN(IIF(InOutMode=1,[Date],NULL)) AS [In] ,
MAX(IIF(InOutMode=0,[Date],NULL)) AS [Out]
FROM @Temp_Table
GROUP BY Empoyee_id,CAST([Date] AS DATE)
)A
A: Try this:
;
WITH Ins as (
Select *
FROM HR_DTR_Device
WHERE InOutMode = 0
),
Outs as (
Select *
FROM HR_DTR_Device
WHERE InOutMode = 1
)
SELECT Ins.ID,
Ins.Employee_ID,
Ins.Date as [In],
(
SELECT Min(Outs.Date)
FROM Outs
WHERE Ins.Employee_ID = Outs.Employee_ID
AND Outs.Date > Ins.Date
) as [Out]
FROM Ins
WHERE Ins.Employee_ID = '104'
What this does:
*
*Separates the Ins and the Outs, as if they were separate data sources. Using Common Table Expressions allows you, in effect, to pre-define subqueries and give them names.
*For each record in the Ins, looks for the smallest date from the Outs that is still larger than the In date. (This assumes that your records are complete, and that you can't ever have two Ins in a row because someone forgot to clock out.)
*Doesn't make any assumptions about when the Out date happens, just that it's later than the In date (by definition). That way, you don't have to worry about whether the employee left later the same day or early the next day (if you have employees working different shifts.)
*Will also show any entries where the employee clocked in but has not yet clocked out.
I think your big error was here:
(SELECT MAX(Date) FROM HR_DTR_Device XX
WHERE InOutMode = 1
AND XX.Employee_ID = AA.Employee_ID
AND CAST(XX.Date AS DATE) = CAST(AA.Date AS DATE)) AS 'Out'
You are returning the largest date for that employee that is on the same calendar date (and is an Out). But, if the employee works until the next morning, the date will have changed!
You could fix this by changing your test to this:
CAST(DATEADD(d, -1, XX.Date) AS DATE) = CAST(AA.Date AS DATE)
... but then it will ONLY work for employees who worked overnight, whereas my solution simply finds the next time the employee clocked out after they clocked in, regardless of whether it's the same day, the next day, or the next week!
If you like this solution, please mark it as your accepted solution. Thank you.
| |
doc_23529981
|
See file structure below:
In below screen shot skips folder is empty I have moved all the files outside skips folder. Initially in user-app folder there were only 3 files
1) skips folder
2) .git
3) README.md
A: Possible fix for EPERM error is:
Solution 1:
npm cache clean --force
OR
Solution 2:
cd android
Gradlew clean
Try any one of the above and EPERM error will be fixed.
| |
doc_23529982
|
function isAllowedOrigin({ req, baseUrl }) {
const allowedOrigins = [new URL(baseUrl.replace(/\/$/g, ""))];
const origin = new URL(req.headers.origin);
const foundOrigin = allowedOrigins.find((allowedOrigin) => {
allowedOrigin.port = origin.port;
return allowedOrigin.origin === origin.origin;
});
return foundOrigin;
}
These are the headers
const headers = {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
};
if (isAllowedOrigin({ req, baseUrl })) {
headers["Access-Control-Allow-Origin"] = req.headers.origin;
}
I could also have a local allowed ports for each micro service
A: The best answer is from the Open Web Application Security Project (OWASP) CORS Page
A bad server configuration of the CORS headers may expose your users to Cross site scripting (XSS).
In your example, a malicious user could send a string in origin that lets you crash new URL('hello') // this throws an error
To support multiple env you could change the allowedOrigins based on the process.env.NODE_ENV, assuming you will have one route for dev, one for test and so on: this lets you check dynamically the ports for dev and strict for production.
For a large server farm, it is used the match of the root domain usually.
| |
doc_23529983
|
jmeter -n -t nature.jmx -l nature.jtl
I tried running this command using RUN and CMD
CMD ["jmeter", "-n"," -t nature.jmx -l nature1.jtl"]
RUN "jmeter -n -t nature.jmx -l nature.jtl"
RUN jmeter -n -t nature.jmx -l nature.jtl
but none of the above command works. i keep getting the below error:
C:\Program Files\Docker\docker.exe: Error response from daemon:
container 02323b3d347904331938b0d27c639975899284b06a0e2f377350
833b55f1ef46 encountered an error during CreateProcess: failure in a
Windows system call: The system cannot find the file spec ified. (0x2)
extra info: {"ApplicationName":"","CommandLine":"jmeter -n -t
nature.jmx -l nature1.jtl","User":"","WorkingDirec
tory":"C:\jmeter\apache-jmeter-3.1\bin","Environment":{"JAVA_HOME":"C:\ojdkbuild","JAVA_OJDKBUILD_SHA256":"7e7384636054001
499ba96d55c90fc39cbb0441281254a1e9ac8510b527a7a46","JAVA_OJDKBUILD_VERSION":"1.8.0.131-1","JAVA_OJDKBUILD_ZIP":"java-1.8.0-ope njdk-1.8.0.131-1.b11.ojdkbuild.windows.x86_64.zip","JAVA_VERSION":"8u131","JMETER_HOME":"C:/jmeter/apache-jmeter-3.1","SET":"P ATH=C:ProgramDataOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C
:ojdkbuildbin;C:/jmeter/apache-jmeter-3.1bin;"},"EmulateConsole":false,"CreateStdInPipe":true,"CreateStdOutPipe":true,"CreateS
tdErrPipe":true,"ConsoleSize":[0,0]}. PS C:\Users\Administrator>
Any advise on this would be helpful. Thanks in advance. Please find my docketing:
Experimental: false
PS C:\Users\Administrator>
Trying build the image using the below Dockerfile
FROM microsoft/windowsservercore
# $ProgressPreference: https://github.com/PowerShell/PowerShell/issues/2138#issuecomment-251261324
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ENV JAVA_HOME C:\\ojdkbuild
RUN $newPath = ('{0}\bin;{1}' -f $env:JAVA_HOME, $env:PATH); \
Write-Host ('Updating PATH: {0}' -f $newPath); \
# Nano Server does not have "[Environment]::SetEnvironmentVariable()"
setx /M PATH $newPath;
# https://github.com/ojdkbuild/ojdkbuild/releases
ENV JAVA_VERSION 8u131
ENV JAVA_OJDKBUILD_VERSION 1.8.0.131-1
ENV JAVA_OJDKBUILD_ZIP java-1.8.0-openjdk-1.8.0.131-1.b11.ojdkbuild.windows.x86_64.zip
ENV JAVA_OJDKBUILD_SHA256 7e7384636054001499ba96d55c90fc39cbb0441281254a1e9ac8510b527a7a46
RUN $url = ('https://github.com/ojdkbuild/ojdkbuild/releases/download/{0}/{1}' -f $env:JAVA_OJDKBUILD_VERSION, $env:JAVA_OJDKBUILD_ZIP); \
Write-Host ('Downloading {0} ...' -f $url); \
Invoke-WebRequest -Uri $url -OutFile 'ojdkbuild.zip'; \
Write-Host ('Verifying sha256 ({0}) ...' -f $env:JAVA_OJDKBUILD_SHA256); \
if ((Get-FileHash ojdkbuild.zip -Algorithm sha256).Hash -ne $env:JAVA_OJDKBUILD_SHA256) { \
Write-Host 'FAILED!'; \
exit 1; \
}; \
\
Write-Host 'Expanding ...'; \
Expand-Archive ojdkbuild.zip -DestinationPath C:\; \
\
Write-Host 'Renaming ...'; \
Move-Item \
-Path ('C:\{0}' -f ($env:JAVA_OJDKBUILD_ZIP -Replace '.zip$', '')) \
-Destination $env:JAVA_HOME \
; \
\
Write-Host 'Verifying install ...'; \
Write-Host ' java -version'; java -version; \
Write-Host ' javac -version'; javac -version; \
\
Write-Host 'Removing ...'; \
Remove-Item ojdkbuild.zip -Force; \
\
Write-Host 'Complete.';
#CMD ["java","-version"]
# Install jmeter
RUN mkdir C:\jmeter
RUN cd /jmeter
RUN powershell.exe Invoke-WebRequest -usebasicparsing http://ftp.ps.pl/pub/apache/jmeter/binaries/apache-jmeter-3.1.zip -OutFile c:/apache-jmeter-3.1.zip
RUN powershell.exe Expand-Archive -Path C:\apache-jmeter-3.1.zip -DestinationPath C:/jmeter
#RUN mkdir C:/jmeter/apache-jmeter-2.13/apache-jmeter-3.1/jmeter-plugins
#RUN cd C:/jmeter/apache-jmeter-2.13/apache-jmeter-3.1/jmeter-plugins
#RUN Invoke-WebRequest -usebasicparsing https://jmeter-#plugins.org/downloads/file/JMeterPlugins-ExtrasLibs-1.4.0.zip
#RUN Expand-Archive -Path C:/jmeter/apache-jmeter-2.13/apache-jmeter-#3.1/jmeter-plugins -DestinationPath C:/jmeter/apache-jmeter-2.13/apache-#jmeter-3.1/jmeter-plugins
# Set Jmeter Home
ENV JMETER_HOME C:/jmeter/apache-jmeter-3.1
# Add Jmeter to the Path
ENV PATH $JMETER_HOME/bin:$PATH
COPY nature.jmx C:\\jmeter\\apache-jmeter-3.1\\bin\\nature.jmx
WORKDIR C:\\jmeter\\apache-jmeter-3.1\\bin
RUN jmeter -n -t nature.jmx -l nature.jtl
| |
doc_23529984
|
The header has a basic structure
<div class="top">
</div>
<div class="header-wrapper">
<div class="header-left"><img src="/assets/images/lawmen1.png" alt="Law and Lawson Attorney at Law Lawyers City State"></div>
<div class="header-right">
<ul>
<li><i class="fa fa-location-arrow fa-2x"></i>250 W. Main Street Suite 2510<br>City, State 90210</li>
<li><i class="fa fa-mobile fa-2x"></i>(555) 555-555</li>
<li><i class="fa fa-fax fa-2x"></i>(555) 555-5555</li>
</ul>
</div>
</div>
And here is the css
@import '1-tools/-tools-index';
.top{
width:100%;
height: 30px;
background-color: #1A1A1A;
}
.header-wrapper{
@include outer-container;
padding-bottom: 2.5em;
.header-left{
@include span-columns(4);
height: 200px;
img{
display:block;
margin: 0 auto;
padding: 2.8em;
height:285px;
width:325px;
}
}
.header-right{
margin-top:2.5em;
height: 200px;
@include span-columns(8);
ul{
li{
font-family: Garamond;
color: grey-color-dark;
font-size: 1.1em;
}
}
i{
padding:0.2em;
height: 50px;
width:50px;
color: #d3bc5f;
}
}
}
So, you can see that I've not purposefully used float: left in the css.
However, you can see in the screenshot of inspect element that Jekyll has generated float: left in the main.scss
Is the syntax that I'm using in the css affecting this? Such as . .
<div class = "outside">
<div class = "left"></div>
<div class = "right"></div>
</div
.outside {
.left {
}
.right {
}
}
Is it okay to nest the css like that?
A: This come from the _sass/1-tools/neat/grid/_span-columns.scss file.
By reading the doc we learn that we can remove the float and the display property to table-cell by doing a :
@include span-columns(8, 'table');
| |
doc_23529985
|
<select class="btn btn-default col-md-1" name="fw_dropdown" id="fw_dropdown" multiple="multiple" required="required">
@foreach (var fw in Model.FWIndex)
{
<option value="@fw">@fw</option>
}
</select>
after I add the required attribute, the form is able to display a message that the field is not selected. However, when I proceed to select the field, the message kept showing, which seems that the selected value cannot be received. When I reload the project and select the required field, I am able to proceed with the submit query.
How do I fix this?
A: Seems that the required attribute only works for select class in IE when multiple selection is not enabled (I'm using bootstrap multiselect).
Instead I write a function in the submit button to achieve validation.
<script>
$(document).ready(function(event){
$("form").submit(function(event){
var fw=$("#fw_dropdown").val();
if(fw=="" || fw==null){
alert("Please select FW!");
//prevent form submission
event.preventDefault();
}
//allow form submission only when if is not true
});
})
</script>
To generate the form in the web application I used the html helper.
@using (Html.BeginForm("Query", "Actuals"))
That's why "form" is used instead of form id
| |
doc_23529986
|
#pragma once
namespace foo
{
int bar;
int funct1();
}
head.cpp
#include "head.h"
int foo::funct1()
{
return bar;
}
main.cpp
#include <iostream>
#include "head.h"
int main()
{
foo::bar = 1;
std::cout << foo::funct1() << std::endl;
return 0;
}
Error LNK2005 "int foo::bar" (?bar@foo@@3HA) already defined in head.obj
I don't understand what is going on. I tried looking for the answer but everyone's questions are so specific to their code and don't even look close to the problem that I am having.
I am not including .cpp files into main. I am not redefining anything. I am literally just assigning 1 to the variable then returning it with a function in the same namespace. How is it being defined multiple times?
A: The header head.h is included in two compilation units head.cpp and main.cpp. So the variable bar is defined twice. You could declare the variable without its definition the following way
#pragma once
namespace foo
{
extern int bar;
int funct1();
}
and then define it in some cpp module.
A: This foo namespace-level bar declaration:
namespace foo
{
int bar;
}
is actually a definition.
To make it a declaration, mark the bar as extern in head.h:
namespace foo
{
extern int bar;
}
Then define it in head.cpp:
int foo::bar = 0;
A: head.h is included in both main.cpp and head.cpp.
So the variable is defined twice.
Possible Solution: make it inline. The "extern" solutions are also good, although older in approach.
namespace foo
{
inline int bar;
}
A:
How is it being defined multiple times?
It is defined once in head.cpp and once in main.cpp. That is a total of two times. This violates the one definition rule, which states that there may only be one definition for every variable.
int bar;
This is a definition of a variable. You've included it into two translation units.
A variable can be declared without definition in an extern declaration:
extern int bar;
Replace the definition with such declaration, and put the definition into exactly one translation unit.
A:
I am not redefining anything. I am literally just assigning 1 to the variable
You're redefining the variable!
head.cpp has one via #include "head.h", and main.cpp has one via #include "head.h".
You need to merely declare it (unusual but not too strange) in the header:
extern int bar;
…then define it in one translation unit. This is just like what you do with static class members (albeit with slightly different syntax).
Since C++17, you may do this by instead plopping the inline keyword on to your definition.
Alternatively, avoid mutable globals…
A: Do carefully note that foo is not a class, but a namespace. When you declare a free variable in the header file:
int bar;
And then #include this header file multiple times (into different CPP files, causing multiple translation unit compilations), you'd get a linker error. Everyone knows it.
And, you'd add extern attribute at the declaration, and define the variable elsewhere in one of the CPP/C file.
Putting a global variable into a namespace is nothing but giving the global variable a different name. Think if foo::bar as foo__NS__bar, and hence you must add extern in the header and define foo::bar at some locatoin.
Note that this is different from a non-static member variable of a class. A class variable doesn't need to be defined/declared this way since the class is a type. Each instantiated variable of class-type would have a separate copy of the variable.
Further to that, when you add a static variable in the class, you are giving that logically global variable another name. Thence, you must have that static-variable defined one of the CPP file.
| |
doc_23529987
|
I have a list of deployment and using for_each on deployment. Based on string condition I need to add a sidecar.
Briefly, I need to write a condition to add a sidecar image.
Something like it:
${substr(each.key, 0, 3) == "tst" ? 1 : 0 }
Is there a way to achieve that?
Here is my deployment tf:
resource "kubernetes_deployment" "x" {
for_each = data
metadata {
name = each.key
labels = {
app = each.key
name = each.key
}
namespace = var.namespace
}
spec {
replicas = 1
selector {
match_labels = {
app = each.key
}
}
template {
metadata {
labels = {
app = each.key
name = each.key
}
}
spec {
service_account_name = "default"
container {
image = each.value
image_pull_policy = "Always"
name = each.key
}
// I need a condtion to create the second container
container {
image = "sidecar_image"
image_pull_policy = "Always"
name = "sidecar-container"
port {
name = "default-port"
container_port = 50050
}
}
restart_policy = "Always"
}
}
}
}
A: You could use a dynamic block for the second container block in order to make it conditional. For example, consider the following piece of code:
dynamic "container" {
for_each = var.is_test ? [1] : []
image = "sidecar_image"
image_pull_policy = "Always"
name = "sidecar-container"
port {
name = "default-port"
container_port = 50050
}
}
Note that the condition will require some more attention but I think this should be enough to get you started.
A: In general you can see the nuances around conditional nested blocks in this answer. To tailor this to your specific situation though:
dynamic "container" {
for_each = range(substr(each.key, 0, 3) == "tst" ? 1 : 0)
content {
image = "sidecar_image"
image_pull_policy = "Always"
name = "sidecar-container"
port {
name = "default-port"
container_port = 50050
}
}
}
This assumes well-formed data keys in your for_each meta-argument value for the resource as provided in your question.
One immediate issue I note with your conditional is that the substring from index 0 to 3 will contain four values, and you are testing against a string with three characters. You probably wanted to do:
substr(each.key, 0, 2)
or perhaps also:
can(regex("^tst", each.key))
but either way your provided conditional will always return false.
| |
doc_23529988
|
const { spawn } = require('child_process');
const child_process = spawn('rails c');
child_process.stdout.on('data', function (data) {
console.log('stdout', data.toString());
});
child_process.stderr.on('data', function (data) {
console.log('stderr', data);
});
child_process.on('close', function (code) {
console.log('close', code);
});
Upon opening the console, i wanted to execute this script in the rails console
user_id = 1624522827
Sharding.get_shard(user_id) do
account = UserList::User.find(user_id).make_user
end
How to achieve this in nodejs. My intention is to create a cli that runs script inside rails console.
A: I think what you want is rails runner instead of console. Either pass it a line of ruby code or a filename. It will run in the rails environment, not just the ruby irb environment.
A: The ruby console is for humans. I wouldn't try and pipe input into it.
A better idea is to use a rake task and then call that with
bundle exec rake task:subtask
guide for rake tasks
All your code should go in the rake task and then you can call it from nodejs using just the filepath.
| |
doc_23529989
|
But the issue I have is that I do not want the JS front-end to handle the tokenization of the CC details but I want the front-end to send the CC data to the back-end and the back-end will then use the payment gateway API to tokenize the CC data and store it instead of the real CC data.
Since the CC data enters the back-end is is considered processing of the CC data(not storage) which means I have to handle PCI compliance in a way.
So I am wondering if there is some easy way to avoid doing some over-complicated code/infrastructure changes in order to be compliant?
A: If you don't want to have to qualify for SAQ C/D then you cannot send your customer's PAN to your server, period. It has to go to your payment gateway first, and then you can take whatever payload they give you and send it to your server.
Since I am more familiar with their services, I can describe the two ways Braintree handles this:
1) Drop-in UI - With this method, you'll create a div on your payment page and add a little javascript in your frontend code that converts the node into a payment form. Once they fill out the payment form, the information will sent directly to Braintree, and they will return a payment nonce to you that you can safely send to your server without any PCI concerns.
2) Hosted Fields - The options to style the Drop-in UI are a bit limited, so if you need the ability to add custom fields that you have full control to style and place on your page as you want, then you are looking for hosted fields. It basically creates a series of iframes on your page that you can style like regular HTML inputs, and then when your customer fills them out and clicks "submit," the data is once again submitted to Braintree first, and you get a payment nonce back that you can send to your backend API and do whatever you'd like.
Just to make sure I've been clear though - there is currently no way to send plaintext credit card information to your server without having to fulfill the more rigorous PCI SAQ levels.
| |
doc_23529990
|
So, i want to terminate extension process from its host app or somehow to communicate with the extension to change its variables.
Is it possible?
A: There is no way to terminate the extension from the host app. It is better to design the extension to observe data changes from the host app and reload itself in a timely manner.
For a tutorial on how to reload data in the extension see: http://www.glimsoft.com/06/28/ios-8-today-extension-tutorial/
| |
doc_23529991
|
I want to overwrite all channels on the server!
So my code is:
message.channel.updateOverwrite(muterole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false,
READ_MESSAGE_HISTORY: true,
TALK: false})
Thank you in advance!
A: You could use the each() function to iterate (loop) through each channel in the current guild and perform the action(s), as utilised below:
// iterate a function through every channel in a server
message.guild.channels.cache.each((channel) => {
channel.updateOverwrite(muterole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false,
READ_MESSAGE_HISTORY: true,
TALK: false});
});
| |
doc_23529992
|
and it prints the results to the command line based on the specs.
Instead, I want to type something like this in the command line C:\java Proj3 "C:\class\Java\boatnames.txt" "C:\class\Java\results.txt"
so the args come from the file specified and the results are printed in a text file instead of on the screen. I changed the println's to printf's, but that's it so far. I deleted all my other failed attempts at this. I even tried creating another class called createfile.java that had private Formatter x; and some openFile, closeFile, and addRecords methods, but if I move the output over there and try to put it in addRecords, it doesn't know what the variable i is, and I'm guessing there must be a simpler way where I don't have to create that createfile class.
Here is my code(I didn't include the other classes since all I need to do is replace the args from the command line with args from a txt file in the command line):
import java.util.*;
import java.io.*;
import java.lang.*;
import java.swing.*;
public class Proj3 {
public static void main(String args[]) {
Boat[] Boats;
char firstChar;
char secondChar;
int i;
Boats = new Boat[args.length];
for (i = 0; i < args.length; i++) {
firstChar = args[i].toUpperCase().charAt(0);
secondChar = args[i].toUpperCase().charAt(1);
if ((firstChar == 'B') || (firstChar == 'C') || (firstChar == 'N')) {
Boats[i] = new SailBoat();
} else {
Boats[i] = new RaceBoat();
}
Boats[i].setName(args[i]);
if ((secondChar == 'A') || (secondChar == 'E')) {
Boats[i].goFast();
} else {
Boats[i].goSlow();
}
}
for (i = 0; i < args.length; i++) {
System.out.printf("Boat number " + (i + 1) + " - \n");
System.out.printf(" ");
Boats[i].printBoat();
System.out.printf(" ");
Boats[i].whatIsBoatState();
}
}
}
A: The simplest way is to use an existing library to read the file in. A very-commonly used library is apache commons-io, which has the FileUtils.readLines() utility method.
import org.apache.commons.io.FileUtils;
// pass the filename is to your program on the command line
List<Sting> lines = FileUtils.readLines(new File(args[0]));
for (String line : lines) {
// use "line" instead of args[i] in your current code
...
}
A: Right now, the top-level program logic is contained in one monolithic main() method. To make life easier, you should break it down into logical pieces and implement each piece in a separate method. For instance, your main() method might look something like this:
public static void main(String[] args) {
ArrayList<Boat> boats = getBoats(args[0]);
PrintStream out = getOutputStream(args[1]);
printBoats(boats, out);
out.close();
}
Then you need to write the support routines:
private ArrayList<Boat> getBoats(String inputFileName) {
...
}
PrintStream getOutputStream(String outputFileName) {
...
}
void printBoats(ArrayList<Boat> boats, PrintStream output) {
...
}
You will probably have to make it all a little more complicated to deal with I/O exceptions (missing files, write permissions, etc.). You'll also have to modify the methods Boat.printBoat() and Boat.whatIsBoatState() to take a PrintStream argument.
A: follow this
java-Passing argument into main method
obtain the files base don absolute path and obtain the file object then read the file object to pickup the content.
A: I've not tested this, but I've not tested it any great detail
public static void main(String[] args) {
if (args.length == 2) {
String inFileName = args[0];
String outFileName = args[1];
File inFile = new File(inFileName);
if (inFile.exists()) {
try {
List<Boat> boats = new ArrayList<Boat>(25);
// Read the "boats" file...
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(inFile));
String text = null;
while ((text = br.readLine()) != null) {
char firstChar = text.toUpperCase().charAt(0);
char secondChar = text.toUpperCase().charAt(1);
Boat boat = null;
if ((firstChar == 'B') || (firstChar == 'C') || (firstChar == 'N')) {
boat = new SailBoat();
} else {
boat = new RaceBoat();
}
boat.setName(text);
if ((secondChar == 'A') || (secondChar == 'E')) {
boat.goFast();
} else {
boat.goSlow();
}
boats.add(boat);
}
} finally {
try {
br.close();
} catch (Exception e) {
}
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(outFileName, false));
for (int index = 0; index < boats.size(); index++) {
bw.write("Boat number " + (index + 1) + " - ");
bw.newLine();
bw.write(" " + boat.toString() + " " + boat.getBoatState());
}
bw.flush();
} finally {
try {
bw.close();
} catch (Exception e) {
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
The other problem is, you're going to need to provide some additional functionality to your Boat class
Namely, I used boat.toString() which needs to return the value Boat.printBoat() was printing and boat.getBoatState() which needs to return the value that Boat.getBoatState() was printing
| |
doc_23529993
|
No problem with the filename, but im having problem with having this output:
filename+sha1\n
For every each of them. I can guess it`s because of os.walk in some way but im not that expert ATM.
txt = open('list','w')
for dirpath, dirnames, filenames in os.walk(dir_path):
text = str(filenames)
for tag in ("[", "]", " ","'"):
text = text.replace(tag, '')
text = str(text.replace(',','\n'))
for i in filenames:
m = hashlib.sha1(str(text).encode('utf-8')).hexdigest()
txt.write(text+" "+str(m)+"\n")
txt = txt.close()
Thanks
A: Change:
txt = open('list','w')
to:
txt = open('list','a')
You are using "w" which overwrites any previous content. You need "a", which appends to the existing file without overwriting.
A: What looks like a potential issue is that you are converting filenames, which is a list of each individual file in the current folder, into a string and then performing replacements on that list. I assume what you intended to do instead was replace within each filename string those special tags. Try the below.
txt = open('list','w')
for dirpath, dirnames, filenames in os.walk(dir_path):
for text in filenames:
text = re.sub('[\[\]," "]',"",text)
m = hashlib.sha1(str(text).encode('utf-8')).hexdigest()
txt.write(text+" "+str(m)+"\n")
txt = txt.close()
As requested, if you dont' want to use re, just do what you had originally done:
text = 'fjkla[] k,, a,[,]dd,]'
for badchar in '[]," "]':
text = text.replace(badchar,"")
| |
doc_23529994
|
It was very easy to create a Flex consumer client and I wish to create the same in .NET
(In other words how to connect a MessageAdapter to MessageAdapter?)
Many Thanks,
Dudi
A: I'm using the NetConnection object and works fine for me. Check the documentation page:
using FluorineFx.Net;
...
NetConnection netConnection = new NetConnection();
netConnection.OnConnect += new ConnectHandler(netConnection_OnConnect);
netConnection.NetStatus += new NetStatusHandler(netConnection_NetStatus);
netConnection.Connect("rtmp://localhost:1935/HelloWorld");
...
void netConnection_OnConnect(object sender, EventArgs e)
{
//The NetConnection object is connected now
netConnection.Call("serverHelloMsg", new ServerHelloMsgHandler(), "some text");
}
...
void netConnection_NetStatus(object sender, NetStatusEventArgs e)
{
string level = e.Info["level"] as string;
}
...
//Our result handler object
public class ServerHelloMsgHandler : IPendingServiceCallback
{
public void ResultReceived(IPendingServiceCall call)
{
object result = call.Result;
}
}
| |
doc_23529995
|
UnboundLocalError: local variable 'usedWord' referenced before assignment
Here's my code for the reference:
def message_translate():
for message in r.get_unread():
message_text = message.body.lower()
messageList = message_text.split()
for word in message_text:
if word in fullLangNames:
usedWord = word
index = fullLangNames.index(word)
transLang = supportedLangs[index]
elif word in abbrevLangNames:
usedWord = word
index = abbrevLangNames.index(word)
transLang = supportedLangs[index]
finalized_message_text = message_text.replace("/u/pleaseTranslate", "") and message_text.replace(usedWord, "")
translation = (translator.translate(finalized_message_text, lang_from = 'en', lang_to = transLang))
callback = (transMessage % translation)
message.mark_as_read
Now I don't understand why I'm getting that error, or what the error is telling me. I apologize if this is an easy fix, though I've looked around and haven't found anything of significant use.
Thanks and I appreciate the help!
A: It looks to me that the problem is in the finalized_message_text. You should initialize usedWord = "" before the for loop. That should fix it. Or add the final Else statement to initialize usedWord = ""
| |
doc_23529996
|
My function looks like this:
function backup_Eventtable() {
$this->load->dbutil();
$prefs = array(
'tables' => array('MYTABLE'), // Array of tables to backup.
'ignore' => array(), // List of tables to omit from the backup
'format' => 'txt', // gzip, zip, txt
'filename' => 'mybackup.sql', // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
'add_insert' => TRUE, // Whether to add INSERT data to backup file
'newline' => "\n" // Newline character used in backup file
);
$backup =& $this->dbutil->backup($prefs);
//I tried it with and without the next 2 Lines.
$this->load->helper('file');
write_file('/uploads/EventBackup/mybackup.sql', $backup);
}
I just checked the appache error log and found this line:
[Fri Mar 07 14:28:37 2014] [error] [client 192.168.242.116] PHP Fatal error: Call to undefined method CI_DB_mysql_driver::backup() in /var/www/html/kaufleuten/admin/system/application/models/eventmodel.php on line 764, referer: http://devzh2.energy.local:8093/admin/events/edit/4002
database.php looks like this:
$active_group = "default";
$active_record = TRUE;
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "myusername";
$db['default']['password'] = "mypassword";
$db['default']['database'] = "kaufleuten_typo3";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "/var/www/html/kaufleuten/admin/cache";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
A: I had to enable the Codeigniter Log in the config.php. ($config['log_threshold'] = 2;) There I found the Error Log:
ERROR - 2014-03-07 15:33:35 --> Severity: Warning --> fopen(uploads/EventBackup/mybackup.sql): failed to open stream: No such file or directory /var/www/html/kaufleuten/admin/system/helpers/file_helper.php 90
Changing the Path to:
write_file('/var/www/html/kaufleuten/uploads/EventBackup/mybackup.sql', $backup);
resolved the Problem.
| |
doc_23529997
|
My problem: I build this DLL, I load it from the proprietary application, and I get a pop-up reporting the following error:
Exception Type:FileNotFoundException
Details: could not load file or assembly 'FSharp.Core,
Version=4.4.1.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its
dependencies. The system cannot find the file specified.
This seems to be fundamentally different from Brent Tranberg's StackOverflow question where he was at least able to get the dependencies loaded; they just complained at him afterwards. Here the dependencies are not even being loaded. So the problem is (I think) that the NuGet package is not getting globally installed and it's also not getting copied into the build output, and as a consequence the proprietary application doesn't ever know about it. The only helpful thing I have found so far online has been telling me that apparently what I'm trying to do is an antipattern: F# libraries are apparently only ever supposed to be used from F# applications which can define what version of F# Core they bind to; they are never supposed to actually include the F# Core library itself.
I must be misunderstanding something here because that sounds crazy to me. On .NET, DLLs are a much bigger deal than just "a library of F# code that I can call from my F# application": they are a core interoperability construct that multiple different languages can use to talk to each other. How do I include this F# dependency in a library which is not destined for an application that knows anything about F# code at all?
Should I violate the part of the guidelines before and "assume FSharp.Core is in the GAC" -- and if so, how the heck do I start doing that? (I am warned that "VS2017 doesn’t install FSharp.Core to the GAC" by the same source.) Or, I mean, is there a nice way to statically link this code since the dynamic linking is not working? Is there a way to convert a NuGet PackageReference into a Reference so that I can add <Private>true</Private> so that it is included in the DLL folder? What other options do I have?
(I have since tried the latter and it does not actually copy the needed DLL into the build folder. I have also tried adding the Fsharp.Core DLL directly as a "Dependency" -- still no dice. It does work if I copy it over every time I build but this seems like a very flimsy approach to a deeper problem that Visual Studio could not possibly be having.)
A: (Warning: self-answer, workaround)
Some more Googling eventually led to a very tangential thread about NuGet being confused about the version of .NET Core, which would otherwise be unhelpful except that one of the major developers (Kevin Ransom) says that the reference to FSharp.Core is being implicitly included because "there is no need for the majority of projects to explicitly reference FSharp.Core". I suppose F# libs being used from C# is not "the majority," but if this is not supported at all I am very surprised. However he has a suggestion for people who do want to explicitly reference it, and that worked for me as a workaround for this issue.
So my workaround looks like this:
*
*Close Visual Studio 2017.
*Open <ProjectName>.fsproj in a separate text editor.
*In the leading <PropertyGroup> add Kevin Ransom's suggestion, <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference>.
*Track down the relative path to FSharp.Core.dll; in my case it was in ..\..\..\..\.nuget\packages\fsharp.core\4.2.3\lib\net45\FSharp.Core.dll
*Add that to the project as an ItemGroup holding a Private Reference (this lives in parallel to the PropertyGroup). That reference therefore for me looks like this:
<ItemGroup>
<Reference Include="FSharp.Core">
<HintPath>..\..\..\..\.nuget\packages\fsharp.core\4.2.3\lib\net45\FSharp.Core.dll</HintPath>
<Private>true</Private>
</Reference>
</ItemGroup>
I did not need to delete a <PackageReference> that NuGet Core had added.
*Save that file, reopen the solution in Visual Studio 2017, and rebuild.
*Then FSharp.Core.dll magically appeared in my build folder with my own .dll file.
If this is an awful workaround please let me know in comments! I am really new to all of this and at that wit's-end stage of "Dammit VS just put this stupid file in that stupid directory already!" so if the above steps are a bit desperate, that's why.
| |
doc_23529998
|
If I have a telnet client that supports multiple connections already running in its own process, how do I get a PHP script that fires off when the client-browser asks to be able to communicate with the client?
For instance, I want the PHP script to be able to tell the already running process which client it is and receive any new data from the telnet process.
A: For PHP, your talking about interfacing through the shell right? It would all depend on the telnet client you are trying to hook up with, and what CLI options it supports. Opening a stream to this would probably require having each telnet session outputting its' STDIO to a text file, and then having PHP read that text file and displaying the 'difference'.
With Fsockopen() in PHP, you really don't need to interface with another program though, you can run socket commands directly in PHP and get the results there.
PHP:Fsockopen
A: I'd create a telnet client that runs as a daemon process. It would be responsible for creating and maintaining the telnet session and buffers any received data.
Your PHP script could then use a TCP connection, or a Unix socket to communicate with your telnet client daemon process using the PHP sockets API.
Jim.
A: Even if the connection needs to be persistent?
edit: nevermind, I think I have an idea.
I'll be writing the client part myself, but if it could also act as a server that PHP makes calls to by connecting to it and giving relevant data to so that it can find out which connection the user needs... by George I think I've got it!
edit2: That's what Jim said. Thanks Jim.
| |
doc_23529999
|
for example given 21-12-2017 i want to get
next business day -> 22-12-2017 / 22-12-2017
next weekend -> 23-12-2017 / 24-12-2017
next week business days->25-12-2017 / 29-12-2017
days until end of month ->22-12-2017 / 31-12-2017
How should I go about this? I already have a calendar table but I don't know how to do these without using subselects for each column
The calendar table looks like this
Date DayOfWeek MonthStartDate MonthEndDate MonthLength IsWeekend
2017-12-21 4 2017-12-01 2017-12-31 31 0
A: example on how to use your calendar table
select top 1 next_business_day = [Date]
from calendar
where [Date] > '2017-12-21'
order by [Date]
select top 2 next_weekend = [Date]
from calendar
where [Date] > '2017-12-21'
and IsWeekend = 1
order by [Date]
for next week business days, if you can add a week no to you calendar table, it will be easier
A: This uses my Calendar table, as I started working before you posted some of your (plus I needed something to test against).
One thing I noticed, is you state "next week business days" however, is 20171225 - 20171229 therefore correct? The 25th is is Christmas day (not many places consider that day is a Business day).
Any way, you'll need to edit for your Calendar table, but let me know if this works:
DECLARE @Date Date = '20171221'
SELECT TOP 1
FIRST_VALUE([date]) OVER (ORDER BY DD.[Working Day] DESC, DD.Date) AS NextWorkingDay,
FIRST_VALUE([date]) OVER (ORDER BY CASE [Day Name] WHEN 'Saturday' THEN 0 ELSE 1 END ASC, DD.Date) AS WeekendStart,
DATEADD(DAY, 1,FIRST_VALUE([date]) OVER (ORDER BY CASE [Day Name] WHEN 'Saturday' THEN 0 ELSE 1 END ASC, DD.Date)) AS WeekendEnd,
FIRST_VALUE([date]) OVER (ORDER BY CASE [Day Name] WHEN 'Monday' THEN 0 ELSE 1 END ASC, DD.Date) AS NextWeekStart,
DATEADD(DAY, 4,FIRST_VALUE([date]) OVER (ORDER BY CASE [Day Name] WHEN 'Monday' THEN 0 ELSE 1 END ASC, DD.Date)) AS NextWeekEnd,
DATEADD(Day, 1, @Date) AS EndStart,
DATEADD(DAY, -1, (DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date)+1, 0))) AS MonthEnd
FROM DimDate DD
WHERE DD.Date > @Date;
I notice you don't have a Day name in your Calendar Table. I'd recommend adding this. Otherwise you'll need to change my references to [Day Name] to DATENAME(WEEKDAY,[Date]) however, that will slow down the performance.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.