id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23538200
|
I am used to work with NServicebus where events (messages) would be an important part of a business process and this of course may never be deleted. I really like the way queues gives me reliable communication where events eventually will be processed in independent applications.
So why is it MS have this max retention period? And why 7 days, because it is a whole week? I really like to understand their reason. I known I could create a Queue-trigger and store them elsewhere.
Also read this feedback voting for this to be changed.
https://feedback.azure.com/forums/217298-storage/suggestions/4134167-infinite-ttl-for-queue-messages?category_id=69698
EDIT: This has now been changed with a new version of WindowsAzure.Storage. This compares the old and new behavior.
//WindowsAzure.Storage 8.7
queue.AddMessage(message); // TTL is 7 days
queue.AddMessage(message, TimeSpan.MaxValue); // Throws The argument 'timeToLive' is larger than maximum of '7.00:00:00'
//WindowsAzure.Storage 9.0
queue.AddMessage(message); // TTL is 7 days
queue.AddMessage(message, TimeSpan.MaxValue); //Expiration Time is now 31.dec 9999
A: Looks like this limitation has been removed with the new C# Storage SDK V9.0.0 which uses new REST API versions, although I cant find any reference to these REST APIs anywhere or anything on the storage blog. https://github.com/Azure/azure-storage-net/blob/master/changelog.txt
I have tested this and it works with V9.0.0 of the Storage SDK, the TTL can be infinite.
| |
doc_23538201
|
<tr th:if="${id &eq; 1 and mobNumber &eq; 1}" height="40" valign="top">
//some code here
</tr>
The thing is this piece of code when written the web page keeps on loading.Can anyone tell me the right way to perform this action.
A: Yo I got it just by replacing &eq; to == and it works excellently.I changed the code to
<tr th:if="${id==1 and mobNumber==1}" height="40" valign="top">
//some code here
</tr>
| |
doc_23538202
|
myControl = (DynamicTable)Page.LoadControl("../inc/DynamicTable.ascx");
Then in my code where I want it to execute the control, I have this:
pnlESDDEnrolled.Controls.Add(myControl);
where pnlESDDEnrolled is the panel I am loading it into for display.
So, I execute the aspx page, it links off to the user control, populates the control, returns back to the aspx page and the page displays with the user control in the middle of it. All is well.
The problem comes in when updates are made on the user control. Keep in mind, that other data is updated on the page as well, and the update button resides on the page, not the control. Anyway, when the update button is pushed, the button_click event is fired on the page, but the updates that I made on the user control are lost. Since the page loaded the user control and then the usercontrol executed the page unload method, the page has no knowledge of the user control anymore. Thus, when the update button on the page is pushed, I guess I am not really sure what happens with the updated data on the user control. All I know is that it is lost. I have been working on this for a huge amount of time, any help would be much appreciated
A: You need to check for IsPostBack in your user control, too.
As your page loads, the Page's Page_Load event starts, then your UserControl's Page_Load will begin, execute, then its events, then controls returns to the page's Page_Load, then all of its events. Of course, if you are using Pre_Init on the page or overriding OnInit in your controls, those events execute before the Page_Load.
So, if you are dynamically creating items on your UserControl, check for IsPostBack and places those events an override OnInit function in the UserControl. Then add your programmatic reference to that UserControl in the Page_Init of the page.
A: I guess while you're talking about user control state these are realised as Properties in the code?
If so, then you're probably going to have to use Viewstate to persist the UserControl's state so that when the page comes back, the UserControl will be re-populated first with what it previously had when it was being rendered. This is as simple as changing any public state properties to use ViewState as the backer.
I'm not a great fan of viewstate, but sometimes it has to be used.
However there may be more at work here - as your instincts are telling you, this might also be a problem with the fact that this usercontrol is loaded dynamically.
In which case, it all depends at which part of the page lifecycle you're doing it. You need to get this control into the page's tree before render (pre-render might be possible), as it's at this point that that page 'captures' its controls collection for the purposes of maintaining state.
Try and move the insertion of this control into the page structure as early as you can in the lifecycle. The earlier the better - so Page_load would be fine.
Equally - it might be you're already doing this - in which case I'd need more information (perhaps a reproducable scenario) in order to help fix it.
| |
doc_23538203
|
I am using Visual Studio 2019. The table would contain:
Sample:
-------------------------------------------------------------------------------------
| Item Code | Item Name | Item Description | Price | In-Stock | Supplier |
-------------------------------------------------------------------------------------
|12345 |Cupboard |a small sized cupboard |Rs.15,000 |15 |ABC Industry |
-------------------------------------------------------------------------------------
|45689 |Chair |a small chair |Rs.10,000 |10 |ABC Industry |
-------------------------------------------------------------------------------------
and so on...
And in the text file the the data above will be stored as
12345|Cupboard|a small sized cupboard|15000|15|ABC Industry
45689|Chair|a small chair|10000|10|ABC Industry
and so on...
Thank you
[shannon]
A: Try this
Dim OPString As String=""
Dim SW As StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filepath, True)
Dim grid as DatagridView = DataGridView1
'print col header names
For i = 1 To grid.Columns.Count
OPString = grid.Columns(i - 1).HeaderText & "|"
Next
SW.WriteLine(OPString)
OPString=""
'Clear the code above if you don't want headers to be added everytime
'print data
For i = 0 To grid.RowCount - 2
For j = 0 To grid.ColumnCount - 1
OPString = grid(j, i).Value & "|"
Next
Next
SW.WriteLine(OPString)
A: You can try this code:
Dim sw As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filepath, True)
Dim str As String = String.Empty
For a As Integer = 0 To DataGridView1.RowCount - 1
str = String.Empty
For b As Integer = 0 To DataGridView1.ColumnCount - 1
str = str & DataGridView1.Rows(a).Cells(b).Value.ToString & "|"
Next
str = str.Substring(0, str.Length - 1)
sw.WriteLine(str)
Next
sw.Close()
A: Assuming there is a DataTable at the source of your DataGridView.
Create as StringBuilder.
Reconstitute the DataTable.
Loop through the rows in the data table turning each row into an object array.
Change the object array to an array of strings with a little Linq.
Join the string array with a pipe and append the line to the string builder.
When the loop finishes save to a text file.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sb As New StringBuilder
Dim dt = DirectCast(DataGridView1.DataSource, DataTable)
For Each row As DataRow In dt.Rows
Dim arr = row.ItemArray
Dim strArr = From element In arr
Select CStr(element)
Dim rowString = String.Join("|", strArr)
sb.AppendLine(rowString)
Next
File.WriteAllText("C:\Users\xxxx\Desktop\MyGrid.txt", sb.ToString)
MessageBox.Show("Finished")
End Sub
| |
doc_23538204
|
I have a class file in the library which i need to inject a service into.
I know i can do it by passing the services in the constructor but I cannot do that.
So I want to know how I can inject a service in a class file with the [Inject] .
I tried inheriting the component class like below but dint work
public class BaseComponent : Component1
{
[Inject]
public IServerProvider ServerProvider { get; set; }
public void Test()
{
var server=ServerProvider.Server; // the serverprovider is null here
//Note:I cannot use the constructor approrach to load
}
}
| |
doc_23538205
|
I am using a tool to do work with the files converting them from one type to another and reloading back to the source.
The batch in it's entirety works fine, but I am needing to get the CSV imported and then the script to loop through its processes for each line in the CSV. As of now, it only uses the last line of the information.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=1-2 delims=," %%a in (Convert.csv) do (
set IPAddress=%%a
set ProjectURL=%%b
)
ECHO Retrieving File
start /wait tool.exe get "ssh %IPAddress%" "%~dp0%IPAddress%\Backup" "%~dp0%IPAddress%\Report\Backup" --ctrl_path="%ProjectURL%"
ECHO Retrieved
Timeout 2 > NUL
ECHO Please wait as we... Convert file after retrieval
ECHO Converting File
start /wait tool.exe convert "%~dp0%IPAddress%\Backup" "%~dp0%IPAddress%\Converted" "%~dp0%IPAddress%\Report\Conversion" "%~dp0HTML.xml" --cnx="%~dp0CNX.xml"
ECHO Converted
Timeout 2 > NUL
ECHO Please wait as we... Push the file
ECHO Pushing File
start /wait tool.exe put "ssh %IPAddress%" "%~dp0%IPAddress%\Converted" "%~dp0%IPAddress%\Report\Placement" --ctrl_path="%ProjectURL%"
ECHO Completed
I understand that this pulls and it shows the variables updating, but I need the rest of the script to run for each line that is read and processed in this manner.
I have tried encompassing the entire script within the For /F loop and it does not seem to wait for the commands within to complete. It blasts through for each line of the CSV and thus does nothing at all.
Is there a looping mechanism to do this within batch?
I did get it to work by putting the entire code section within the loop and changing the variables inline to !IPAddress! and !ProjectURL! respectively, but it seems janky? Is there a cleaner method? This is what I currently have, it works but isn't at all pretty.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=1-2 delims=," %%a in (Convert.csv) do (
set IPAddress=%%a
set ProjectURL=%%b
ECHO Retrieving File
start /wait tool.exe get "ssh !IPAddress!" "%~dp0!IPAddress!\Backup" "%~dp0!IPAddress!\Report\Backup" --ctrl_path="!ProjectURL!"
ECHO Retrieved
Timeout 2 > NUL
ECHO Please wait as we... Convert file after retrieval
ECHO Converting File
start /wait tool.exe convert "%~dp0!IPAddress!\Backup" "%~dp0!IPAddress!\Converted" "%~dp0!IPAddress!\Report\Conversion" "%~dp0HTML.xml" --cnx="%~dp0CNX.xml"
ECHO Converted
Timeout 2 > NUL
ECHO Please wait as we... Push the file
ECHO Pushing File
start /wait tool.exe put "ssh !IPAddress!" "%~dp0!IPAddress!\Converted" "%~dp0!IPAddress!\Report\Placement" --ctrl_path="!ProjectURL!"
ECHO Completed
)
A: SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=1-2 delims=," %%a in (Convert.csv) do (
rem set IPAddress=%%a
rem set ProjectURL=%%b
ECHO Retrieving File
start /wait tool.exe get "ssh %%a" "%~dp0%%a\Backup" "%~dp0%%a\Report\Backup" --ctrl_path="%%b"
ECHO Retrieved
Timeout 2 > NUL
ECHO Please wait as we... Convert file after retrieval
ECHO Converting File
start /wait tool.exe convert "%~dp0%%a\Backup" "%~dp0%%a\Converted" "%~dp0%%a\Report\Conversion" "%~dp0HTML.xml" --cnx="%~dp0CNX.xml"
ECHO Converted
Timeout 2 > NUL
ECHO Please wait as we... Push the file
ECHO Pushing File
start /wait tool.exe put "ssh %%a" "%~dp0%%a\Converted" "%~dp0%%a\Report\Placement" --ctrl_path="%%b"
)
ECHO Completed
That is, simply replace %IPAddress% withe %%a and %ProjectURL% with %%b within the loop. %%a and %%b are simply strings with no magical properties and and in-context within the parentheses defining the do action.
| |
doc_23538206
|
But I've compiled them in Linux and now I am going to work in Windows. Can I just put these compiled files to my project in Windows link them in mk file and use? Does difference between 32 and 64 bit OS play role?
Thanks!
A: As long as your target android platform is the same, it should work.
The .so file generated by Android NDK compiler is native code of the target android platform.
It is just packed into the APK intact, so the OS you use to pack the APK doesn't affect the outcome.
EDIT:
*
*As a commenter suggested, by target platform I meant CPU architectures like ARM, x86 or MIPS
*As to the API level, neither targetSdkVersion nor minSdkVersion doesn't directly affect the native code.
Rather, your code may fail at runtime, if you use higher level API than is available on the actual Android device.
To avoid this safely, you need to set your minSdkVersion according to the NDK API level which was assumed when compiling your .so file.
In other words, files under "<your-ndk-dir>/platforms/android-<NDK-API-level>/arch-<CPU type>/usr/..." should have been looked up by the NDK compiler when you compiled your native code. Identify which level was used, and make sure you have equal or greater number as minSdkVersion.
If you have NDK installed, it's documented in "<your-ndk-dir>/docs/STABLE-APIS.html".
| |
doc_23538207
|
{
displayName: "Name", name: 'ID', field: 'ID', minWidth: 350,
editType: 'dropdown',
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownOptionsFunction: function (rowEntity, colDef) {
return _List;
},
cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scope">{{grid.appScope.PrintName(row.entity.ID)}}</div>'
}
| |
doc_23538208
|
I will try to explain my question with a simple example:
Supposing a language with dynamic typing (like ECMAScript) and the following class structure:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
private update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=0) Throws new Exception("hmmm, that could not happend!");
update();
}
private update(){
this.idB = 5;
}
}
In this very simple example, when i create an object of the class B, B::foo() call the parent A::foo(), which call "update". The object is an instance of B, so the "update" functions called is B::update, after that, in B::foo, the update function is again called (B::update). The final result is that A::update is never called, and idA still 0.
The class A work correctly when used alone, but after to extend it with B, the function foo() fail.
What is the correct solution this problem:
1) Force the class A to call A::update , that mean an ugly code every call to his own function (protect the super-class):
A::foo(){
A::update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
2) B::update is an extension of A::update, so B::update must call itself the parent function (prepare the sub-class, and deal with problems):
B::foo(){
super.foo();
... // Any operation that must be performed between A::update and B::update
}
B::update(){
super.update();
this.idB = 5;
}
But in this case is the A::foo which call update, not the B::foo. That mean others problems.
3) Any other solution.
As a summary:
How to protect the super-class code against polymorphism?
*
*Add protections into the super-class.
*Deal with these problem creating the child-class
*The language must do that! (do not know if it is possible with dynamically typed languages)
I am looking for a very theoretical /canonical solution to this question.
EDITED: to take the problem out of the constructor and clarify some points.
A: It's generally considered a very bad practice to call instance methods, and especially virtual instance methods from within a constructor exactly for this reason (but also for the reason that the object isn't done being "initialized" yet).
3) Any other solution.
Doc, it hurts when I do this.
Then don't do that!
Seriously, if you need to set IdA in the constructor of A, don't do it by calling update, do it by explicitly setting the value of IdA in the constructor for A.
A: The base class should protect itself from harmful overrides. In keeping with the open/close principle, it should be open to extension but closed to modification. Overriding update is a harmful modification of the base class's intended behaviour. In your example, there is no benefit in overriding update because both A::update and B::update are private methods that deal with private variables. There isn't even an expectation that they should be executed together judging by your exception in B::foo. If B::update was named differently, there wouldn't be anything wrong with your implementation. It would probably be OK anyway: since no language I know of will let you override a private method, B::update could hide A::update rather than overriding it.
Depending on the language, you can limit which methods can be overridden in different ways. Some languages require an indicator (a keyword or attribute usually) that a method can be overridden, others to show that it can't. Private methods are generally not overridable, but not all languages have access modifiers at all, and everything is effectively public. In this case you would have to use some kind of convention as suggested by @PoByBolek.
tl;dr: Children have no business with their parents' privates.
A: You're probably not going to like my answer but: convention and disciplin.
Establish conventions for
*
*when it is safe for a child class to override a method without calling the parent class implementation,
*when a child class has to call the parent class implementation of an overridden method,
*when a child class must not override a parent class method.
Document these conventions and stick to them. They should probably be part of your code; either in form of comments or naming conventions (whatever works for you). I could think of something like this:
/*
* @final
*/
function shouldNotBeOverridden() {
}
/*
* @overridable
* @call-super
*/
function canBeOverriddenButShouldBeCalledFromChildClasses() {
}
/*
* @overridable
*/
function canBeOverridenWithoutBeingCalledFromChildClasses() {
}
This may help someone reading your code to figure out which methods he may or may not override.
And if someone still overrides your @final methods, you hopefully have thorough testing ;)
I like this answer to a somewhat similar question regarding python:
You could put a comment in there to the effect of:
# We'll fire you if you override this method.
A: If the language allows one class to call a private method of another class this way, the programmer has to understand and live with that. If I'm understanding your objective, foo and update should be overridden and update should be protected. They would then call the method in the parent class, when necessary. The derived foo method wouldn't need to call update, because calling foo in the parent class would take care of that. The code could work like this:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception("idA not set by update");
}
protected update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
@Override
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=5) Throws new Exception("idB not set by super.foo");
}
@Override
protected update(){
super.Update()
this.idB = 5;
}
}
I changed the exceptions to match expectations.
| |
doc_23538209
|
I have searched a lot how to retrieve it, but so far I found no answer.
Does anyone have any idea how I can do it?
Thanks,
Andrei
A: 1) Find the URL for the NASA picture of the day's image file.
2) run this code:
NSString *NasaUrlStr = @"http:/nasa/imageoftheday.jpg"; // fill in correct path here
NSURL *imageURL = [NSURL URLWithString:NasaUrlStr];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
self.myImageView.image = img;
If you want to get "fancy" you could run the "[NSData dataWithContentsOfURL:imageURL]" in a background thread so you don't stall your user interface while the image is downloading.
| |
doc_23538210
|
CREATE PROCEDURE [dbo].[sp_VendorOverview] (@sortCol nvarchar(50)=NULL)
AS
BEGIN
SET NOCOUNT ON;
select v.Vid, s.Salutation, v.LastName, CONVERT(varchar(100), CAST(v.VAT AS decimal(38,0))) AS VAT
from vendors v
inner join Salutations s
on v.salutation=s.anrede
order by
CASE WHEN @sortCol='LastName' THEN v.LastName
WHEN @sortCol='FirstName' THEN v.FirstName
ELSE NULL
END,
CASE WHEN @sortCol ='VendorNumber' THEN v.VendorNumber
ELSE v.Vid
END
for xml path('VendorBasic'), root('Vendors')
END
When running this sp in SSMS, all is fine, results are as expected.
Not so, however, when trying to read this from C# application like this:
var vendoren = new List<VendorBasic>();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["Vendor"].ConnectionString))
{
var xml = string.Empty;
con.Open();
using (var cmd = new SqlCommand("dbo.sp_VendorOverview", con))
{
if (!string.IsNullOrEmpty(orderby))
cmd.Parameters.AddWithValue("@sortCol", orderby);
using (XmlReader idr = cmd.ExecuteXmlReader())
{
if (idr.Read())
{
xml = idr.ReadOuterXml();
}
idr.Close();
}
con.Close();
}
if (xml != string.Empty)
{
XmlRootAttribute xRoot = new XmlRootAttribute
{
ElementName = "Vendors",
IsNullable = true
};
var engine = new XmlSerializer(typeof(List<VendorBasic>), xRoot);
vendoren = (List<VendorBasic>)engine.Deserialize(new StringReader(xml));
}
}
Deserialization works fine, XmlRoot attribute is set for the VendorBasic class.
I DO get results.
They are just never ordered by anything other than Vid. I have set a break point to check whether the parameter is correctly applied in case I want to order by any other column. It is:
Am I missing something? Am I doing something wrong?
A: You need to tell SqlCommand that you are executing stored procedure and not arbitrary command, by doing
cmd.CommandType = CommandType.StoredProcedure;
Without that it will basically ignore all your parameters and execute procedure with default parameters (null in this case). You might find more info about this in this question: When executing a stored procedure, what is the benefit of using CommandType.StoredProcedure versus using CommandType.Text?.
| |
doc_23538211
|
class SessionsController < Devise::SessionsController
respond_to :json
def create
resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#failure")
sign_in(resource_name, resource)
return render json: { success: true, path: root_path }
end
def failure
return render json: { success: false, errors: ['Login information is incorrect, please try again'] }
end
end
User#active_for_authentication
def active_for_authentication?
super && active_flag == 1 && has_active_subscription?
end
Server Response:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-07-29 15:11:39 -0500
Processing by SessionsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ozQ00tw9rRWExCmlIyIZR07ovnTLab5w0W44cLAKwA4=", "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "commit"=>"Sign In"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."type" IN ('User', 'Athlete', 'Coach') AND "users"."email" = '[email protected]' LIMIT 1
(0.6ms) BEGIN
AccountType Load (0.5ms) SELECT "account_types".* FROM "account_types" WHERE "account_types"."id" = $1 LIMIT 1 [["id", 3]]
AccountType Load (0.7ms) SELECT "account_types".* FROM "account_types" WHERE "account_types"."id" = 3 LIMIT 1
(0.5ms) COMMIT
Completed 401 Unauthorized in 338ms
Started GET "/users/sign_in.json" for 127.0.0.1 at 2013-07-29 15:11:40 -0500
Processing by SessionsController#new as JSON
Completed 200 OK in 13ms (Views: 1.6ms | ActiveRecord: 0.0ms)
For some reason the request in the browser contains a user object with email and password as properties. The failure json doesn't render for whatever reason. Not sure what I am doing wrong
EDIT
#Devise
config.http_authenticatable_on_xhr = false
CoffeeScript:
$(document).on 'ajax:success', '.user_modal_form', (e, data) ->
context = $(this)
if data.success
$('input[type="submit"]', context).hide()
$('.spinner', context).show()
if data.path?
window.location.href = data.path
else
location.reload()
else
e.preventDefault()
if data.errors?
$('.error-messages', context).html(data.errors).parent().show()
else
$('button', context).show()
$('.spinner', context).hide()
$('.alert', context).show()
false
A: Here is what I wound up going with for those who may stumble upon this later down the road...
#config/initializers/devise.rb:
config.http_authenticatable_on_xhr = true
config.navigational_formats = [:"*/*", "*/*", :html, :json]
SessionsController
class SessionsController < Devise::SessionsController
respond_to :json
def create
resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#failure")
sign_in(resource_name, resource)
return render json: { success: true, path: root_path }
end
def failure
return render json: { success: false, errors: ['Login information is incorrect, please try again'] }
end
end
routes
# I have implemented STI (Single Table Inheritance) into my app, therefore I skip sessions and passwords for the :user scope
devise_for :users, skip: :registrations, controllers: { sessions: "sessions", passwords: "passwords" }
UserModel
def active_for_authentication?
super && active_flag == 1 && has_active_subscription?
end
def inactive_message
"Your subscription has been canceled or has expired."
end
CoffeeScript:
$(document).on 'ajax:success', '.user_modal_form', (e, data) ->
context = $(this)
log data
if data.success
$('input[type="submit"]', context).hide()
$('.spinner', context).show()
if data.path?
window.location.href = data.path
else
location.reload()
else
e.preventDefault()
if data.errors?
$('.error-messages', context).html(data.errors).parent().show()
else
$('button', context).show()
$('.spinner', context).hide()
$('.alert', context).show()
false
.on 'ajax:error', '.user_modal_form', (event, xhr, ajaxOptions, thrownError) ->
json = $.parseJSON(xhr.responseText)
$('.error-messages', $(this)).html(json.error).parent().show()
A: Add the following code to your sessions controller to create a failure method on your controller that customizes your json response:
def auth_options
super.merge(recall: "#{controller_path}#failure")
end
def failure
render json: {error: "Login failed"}, status: :unauthorized
end
Apparently the default option for recall is #{controller_path}#new, which I suppose might make sense for html. You can use respond_to in auth_options if you want to restrict this to only json requests.
A: I'm not sure why you're getting an object with login credentials, but Devise handles errors through it's FailureApp - make sure you override it so when the 401 is triggered warden recalls the custom action.
This is done in your devise initializer, config/initializers/devise.rb
Add this to the initializer and restart your server:
config.http_authenticatable_on_xhr = false
config.navigational_formats = [:html, :json]
| |
doc_23538212
|
So far I have tried:
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
for i in range(1,11):
df[Age_'i'] = df['Age']
A: Just use this for loop:
for x in range(0,11):
df['Age_'+str(x)]=df['Age']
OR
for x in range(0,11):
df['Age_{}'.format(x)]=df['Age']
OR
for x in range(0,11):
df['Age_%s'%(x)]=df['Age']
Now if you print df you will get your desired output:
A: you can use .assign and ** unpacking.
df.assign(**{f'Age_{i}' : df['Age'] for i in range(11)})
| |
doc_23538213
|
Problem is that I can't see the whole code so even though I'm not familiar with REGEXP_REPLACE it makes things harder to learn.
The client simplifies the whole coding process, here's a screenshot of the
interface
Filling the text boxes with "^(\w)" and "upper(\1)" respectively makes the first character capitalized, "(\w)$" and "upper(\1)" does the same with the last character.
I've discovered that "\b(\w)" will uppercase the first character of every word, i've tried "\b(\w)%" for the last character but it didn't work, as there is some syntax error, probably...
So, how do I get every last character capitalized?
1:
| |
doc_23538214
|
However, whenever I move the slider to compute the coordinates of the single data point, the plot generates a whole series of points until I stop sliding. I would like to remove this trail of dots and only show the one represented by the stopping position of the slider. Hope this makes sense.
Here is what the graph looks like (erroneously):
Oops, I'm too new to post an image, but I'm sure you get the picture.
Here is a portion of the code in the slider IBAction:
CPTScatterPlot *dotPlot = [[[CPTScatterPlot alloc] init] autorelease];
dotPlot.identifier = @"Blue Plot";
dotPlot.dataSource = self;
dotPlot.dataLineStyle = nil;
[graph addPlot:dotPlot];
NSMutableArray *dotArray = [NSMutableArray arrayWithCapacity:1];
NSNumber *xx = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]];
NSNumber *yy = [NSNumber numberWithFloat:[estMonthYield.text floatValue]];
[dotArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:xx,@"x",yy,@"y", nil]];
CPTMutableLineStyle *dotLineStyle = [CPTMutableLineStyle lineStyle];
dotLineStyle.lineColor = [CPTColor blueColor];
CPTPlotSymbol *yieldSymbol = [CPTPlotSymbol ellipsePlotSymbol];
yieldSymbol.fill = [CPTFill fillWithColor:[CPTColor blueColor]];
yieldSymbol.size = CGSizeMake(10.0, 10.0);
dotPlot.plotSymbol = yieldSymbol;
self.dataForPlot = dotArray;
I've tried to reload the plot with [dotPlot reloadData] and even tried to remove and add back the dotPlot but neither seems to work or, perhaps, I am putting the instructions in the wrong place or wrong sequence.
Any advice would be greatly appreciated.
A: Why are you recreating the scatterplot in the slider action? The only thing you should need to do in that method is update the array that provides the data for the second plot, and call reloadData.
In any case, the reason you're getting the trail is that you keep creating new plots and adding them to the graph. The only code that should be in the slider method is:
NSMutableArray *dotArray = [NSMutableArray arrayWithCapacity:1];
NSNumber *xx = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]];
NSNumber *yy = [NSNumber numberWithFloat:[estMonthYield.text floatValue]];
[dotArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:xx,@"x",yy,@"y", nil]];
self.dataForPlot = dotArray;
[graph reloadData];
A: I figured I was about a line of code away from a solution. As typically happens, I dreamt the solution. First I removed all the NSMutableArray *dotArray, etc, etc code from the slider method. Second I retained the [graph reloadData] in the slider method as Flyingdiver advised. Third, I modified the datasource methods as follows:
#pragma mark - Plot datasource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [dataForPlot count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex: (NSUInteger)index {
NSNumber *num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")];
// Blue dot gets placed above the red actual yields
if ([(NSString *)plot.identifier isEqualToString:@"Blue Plot"]) {
if (fieldEnum == CPTScatterPlotFieldX) {
num = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]]; }
if (fieldEnum == CPTScatterPlotFieldY) {
num = [NSNumber numberWithFloat:[estMonthYield.text floatValue]]; }
}
return num;
}
Once again, thanks a million to Flyingdiver for the clues that solved my mystery. I learned a lot.
| |
doc_23538215
|
I don't want to display the bonusquestion index-numbers in the interface of the quiz, therefore i need to skip every 5th index-number from the range of 100 questions.
I did manage to make a simple calculation which works well when i check it in a loop, but somehow i feel it's a rather dirty solution (ceil). Is there any way of writing this code in a neater or more logical way?
ActionScript:
for (var i:Number = 1; i < 101; i++) {
var displayIndex:Number = Math.ceil((i/5) * 4);
trace("i:" + i + " / " + displayIndex);
}
PHP:
for ($i = 1; $i < 101; $i++) {
echo "i: " . $i . " / displayIndex: " . (ceil(($i/5) * 4) . "<br>");
}
Edit:
Let me try to visualize this
index-number = 1 -> display-number = 1
index-number = 2 -> display-number = 2
index-number = 3 -> display-number = 3
index-number = 4 -> display-number = 4
index-number = 5 -> display-number = none
index-number = 6 -> display-number = 5
index-number = 7 -> display-number = 6
index-number = 8 -> display-number = 7
index-number = 9 -> display-number = 8
index-number = 10 -> display-number = none
etc...
A: try
if($i % 5 != 0) {
// do your stuff
}
else {
// skipped
}
according to expected output:-
for ($i = 1; $i < 101; $i++) {
echo 'index-number = '. $i.' -> display-number ='. (($i % 5 != 0) ? $i : 'none').'<br>';
}
output :-
index-number = 1 -> display-number =1
index-number = 2 -> display-number =2
index-number = 3 -> display-number =3
index-number = 4 -> display-number =4
index-number = 5 -> display-number =none
index-number = 6 -> display-number =6
index-number = 7 -> display-number =7
index-number = 8 -> display-number =8
index-number = 9 -> display-number =9
index-number = 10 -> display-number =none
and so on....
A: Your task is exotic enough, that your decision could to be fair enough for accomplishing it. It's simplifying it enough, yet nobody except you will understand it.
I'd suggest just adding a comment to it. However, there are plenty of other ways, which I cannot say they are more elegant, but maybe are more self-explanatory.
$counter = 1;
for ($i = 1; $i < 21; $i++) {
$displayNum = $counter;
if ($i % 5 == 0) {
$counter--;
$displayNum = "none";
}
echo "index-number = $i -> display-number = $displayNum <br/>";
$counter++;
}
Will result into:
index-number = 1 -> display-number = 1
index-number = 2 -> display-number = 2
index-number = 3 -> display-number = 3
index-number = 4 -> display-number = 4
index-number = 5 -> display-number = none
index-number = 6 -> display-number = 5
index-number = 7 -> display-number = 6
index-number = 8 -> display-number = 7
index-number = 9 -> display-number = 8
index-number = 10 -> display-number = none
index-number = 11 -> display-number = 9
index-number = 12 -> display-number = 10
index-number = 13 -> display-number = 11
index-number = 14 -> display-number = 12
index-number = 15 -> display-number = none
index-number = 16 -> display-number = 13
index-number = 17 -> display-number = 14
index-number = 18 -> display-number = 15
index-number = 19 -> display-number = 16
index-number = 20 -> display-number = none
If you try to minify it with ternary operator, you will end up with code just like yours, which is crypt, rather than explanatory.
You can skip the iteration with continue and adding the desired output before that. The very same result can be achieved by:
$counter = 1;
for ($i = 1; $i < 21; $i++) {
if ($i % 5 == 0) {
echo "index-number = $i -> display-number = none <br/>";
continue; // more explanatory for SKIP THIS ITERATION
}
echo "index-number = $i -> display-number = $counter <br/>";
$counter++;
}
This way you will print none and will skip the execution of the iteration, thus $counter will not increment, and on 6-th iteration it will be 5.
| |
doc_23538216
|
import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'
Error importing tensorflow. Unless you are using bazel, you should
not try to import tensorflow from its source directory; please exit
the tensorflow source tree, and relaunch your python interpreter from
there.
Process finished with exit code 1
I installed it like so python -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl
A: Do not directly import module pywrap_tensorflow in Tensorflow 1.0, instead, please try:
import tensorflow as tf
and when you want to use the pywrap_tensorflow module, try:
tf.pywrap_tensorflow
Good luck!
| |
doc_23538217
|
*
*Is it better to order by id or by date?
*How do I rewrite this sql statement to re-order by date?
SELECT id, comment, DATE_FORMAT(entry_date, '%W %H:%i') FROM comments ORDER BY id DESC LIMIT 10
A: It depends on what you mean by most recent:
If you mean the most recently created record, then (in most cases) by primary key id will work.
If you mean the most recently updated record, then definitely by date.
To sort by date just change the field name: ORDER BY entry_date DESC
A: If you have to be 100% precise to sort for the newest rows, you must use the date field. Sorting for the time field when you want to sort for the newest makes pretty much sense and if indexed, sorting on dates will take the same time than to sort for the id-s.
The values for the id field are only guaranteed to be unique I assume, there is possibly no way to ensure that they are ordered by insertion time. For example the id field can be a cyclic field (6,7,8,-7,-6...), or a later modification on the table is allowed to change the id fields but will not know to preserve their ordering by insertion time, or parallel transactions might decide to insert new rows in a different order on the id and date fields.
| |
doc_23538218
|
foo = function(letter) {
unlist(lapply(1:10, function (number) {paste(letter,number)}))
}
I have a vector of letters cols = c("A", "L", "B") and I would like to create a tibble where each column is foo(letter):
# A tibble: 10 × 3
A L B
<chr> <chr> <chr>
1 A 1 L 1 B 1
2 A 2 L 2 B 2
3 A 3 L 3 B 3
4 A 4 L 4 B 4
5 A 5 L 5 B 5
6 A 6 L 6 B 6
7 A 7 L 7 B 7
8 A 8 L 8 B 8
9 A 9 L 9 B 9
10 A 10 L 10 B 10
The above tibble was made with data_frame("A"=foo("A"), "L"=foo("L"), "B"=foo("B")), but I don't know how to do it for a vector cols of arbitrary length.
I'm certain that this is elementary and can be done without a for loop.
In a rival framework what I'm looking for can be done as
pd.DataFrame({letter: foo(letter) for letter in cols})
A: purrr::map_df is a version of lapply that coerces the result to a tibble. To simplify to a data.frame, the vectors have to be named, for which you can use set_names:
library(purrr)
c("A", "L", "B") %>% set_names() %>% map_df(foo)
## # A tibble: 10 × 3
## A L B
## <chr> <chr> <chr>
## 1 A 1 L 1 B 1
## 2 A 2 L 2 B 2
## 3 A 3 L 3 B 3
## 4 A 4 L 4 B 4
## 5 A 5 L 5 B 5
## 6 A 6 L 6 B 6
## 7 A 7 L 7 B 7
## 8 A 8 L 8 B 8
## 9 A 9 L 9 B 9
## 10 A 10 L 10 B 10
A: We can use lapply
library(dplyr)
tbl_df(setNames(data.frame(lapply(cols, foo)), cols))
# A tibble: 10 × 3
# A L B
# <fctr> <fctr> <fctr>
#1 A 1 L 1 B 1
#2 A 2 L 2 B 2
#3 A 3 L 3 B 3
#4 A 4 L 4 B 4
#5 A 5 L 5 B 5
#6 A 6 L 6 B 6
#7 A 7 L 7 B 7
#8 A 8 L 8 B 8
#9 A 9 L 9 B 9
#10 A 10 L 10 B 10
Or another option is
setNames(tbl_df(matrix(foo(cols), ncol=3, byrow=TRUE)), cols)
# A tibble: 10 × 3
# A L B
# <chr> <chr> <chr>
#1 A 1 L 1 B 1
#2 A 2 L 2 B 2
#3 A 3 L 3 B 3
#4 A 4 L 4 B 4
#5 A 5 L 5 B 5
#6 A 6 L 6 B 6
#7 A 7 L 7 B 7
#8 A 8 L 8 B 8
#9 A 9 L 9 B 9
#10 A 10 L 10 B 10
NOTE: Only dplyr is used. No additional libraries are loaded
| |
doc_23538219
|
There is the following line:
className = (" " + elem.className + " ").replace( rclass, " " );
rclass:
rclass = /[\n\t\r]/g,
In the book "JavaScript The Definitve Guide" from David Flanagan, 6th Edition, on page 438 there are the following sentence:
..., so the HTML class attribute is available to JavaScript code using
the name className. ... and the class attribute holds a
space-separated list of class names.
Why the jQuery coders assume that the class names can also be separated by tabs and line feeds?
A: Lots of web "developers" know almost nothing about what they are doing and thus write crappy code containing e.g. tab- or linefeed-separated class names.
It is a common principle to "be generous when reading but strict when writing", i.e. accept things that do not really follow $standard but never create such things.
| |
doc_23538220
|
$(document).ready(function() {
$('.g:first').before('<div>Hello world!</div>');
});
The element appears to be inserted correctly into the DOM (querying $('.g:first') after insertion gives the new element). However, the element fails to render about half the time. This problem occurs regardless of the run_at property for content scripts in the extension's manifest.
(Also, very infrequently, $('.g:first') does not even return anything because the page has not finished loading in $(document).ready - some of the internal HTML elements are not populated. Not sure if this is related.)
Is this an extension-specific issue? How can it be resolved? Debugging suggestions are also welcome!
| |
doc_23538221
|
Below is a snippet of the code I try to execute:
var file = sc.textFile("ftp://user:pwd/192.168.1.5/brecht-d-m/map/input.nt")
var fileDF = file.toDF()
fileDF.write.parquet("out")
After trying to execute a count on the dataframe, I get following stacktrace (http://pastebin.com/YEq8c2Hf):
org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
TungstenAggregate(key=[], functions=[(count(1),mode=Final,isDistinct=false)], output=[count#1L])
+- TungstenExchange SinglePartition, None
+- TungstenAggregate(key=[], functions=[(count(1),mode=Partial,isDistinct=false)], output=[count#4L])
+- Project
+- Scan ExistingRDD[_1#0]
...
Caused by: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: ftp://user:[email protected]/brecht-d-m/map/input.nt
I would assume that the file would be unreachable, but this is in contradiction with that I am able to retrieve the file via curl:
curl ftp://user:[email protected]/brecht-d-m/map/input.nt
This will print out the specific file on my terminal. I do not see what I am doing wrong in the Scala code. Is there an error in the code snippet I gave above, or is that code totally wrong?
Thanks in advance,
Brecht
Note:
*
*Specifying the whole path (/home/brecht-d-m/map/input.nt) also does not work (as expected, since this also does not work in curl; "server denied you to change to the given directory"). Trying this in Spark, gives the IOException that seek is not supported (http://pastebin.com/b9EB9ru2).
*Working locally (e.g. sc.textFile("/home/brecht-d-m/map/input.nt")) works perfectly.
*File permissions for specific file is set to R+W for all users.
*The file size (15MB) should not be a problem, and it should be able to handle much bigger files.
*Software versions: Scala 2.11.7, Apache Spark 1.6.0, Java 1.8.0_74, Ubuntu 14.04.4
A: I was able to find a workaround. Via the codesnippet below:
import org.apache.spark.SparkFiles
val dataSource = "ftp://user:pwd/192.168.1.5/brecht-d-m/map/input.nt"
sc.addFile(dataSource)
var fileName = SparkFiles.get(dataSource.split("/").last)
var file = sc.textFile(fileName)
I am able to download a file over FTP (with the same URL as from the first code snippet). This workaround will first download the file (via addFile). Next, I retrieve the path to where the file was downloaded. Finally, I use that path to load that file into an RDD.
A: I had the same requirement to fetch remote files using scala. The current answer does not solve the problem for sftp (mostly applicable across companies).
I am using the below scala code to create an inputStream from the file.
I transform it to String. But we can choose to create rdd / save to filesystem a well.
Sharing this incase someone has to use scala.
Entry to import jsch into build.sbt:
libraryDependencies += "com.jcraft" % "jsch" % "0.1.55"
Now create the below method using jsch built-in classes:
import com.jcraft.jsch.{ChannelSftp, JSch, JSchException}
def getRemoteFile: String = {
val jsch = new JSch()
try{
val session = jsch.getSession("devuser", "175.1.6.60", 22)
session.setConfig("StrictHostKeyChecking", "no")
session.setPassword("devpassword")
session.connect()
val channel = session.openChannel("sftp")
channel.connect()
val sftpChannel = channel.asInstanceOf[ChannelSftp]
val output = sftpChannel.get("/tmp/monitoring/greenplum_space_report.txt")
val displayAns = scala.io.Source.fromInputStream(output).mkString
sftpChannel.exit()
session.disconnect()
displayAns
}
catch {
case ex : JSchException => ex.printStackTrace().toString
}
}
| |
doc_23538222
|
CGPathRef NewPathWithRoundRect(CGRect rect, CGFloat cornerRadius)
{
// other work to create ref which is a CGPath
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
CFRelease(ref);
});
}
In the latest version of Xcode I get a warning about not releasing memory properly. The caller takes the value, uses it and then calls CFRelease. I now CFRetain it and also CFRelease it so in order to get the reference count down to zero I am setting this dispatch to run and clean up the reference.
I am not comfortable with this approach. Is there is a better pattern for returning CF objects that were created in the method and need to be returned? Should I create the path outside the method and pass it in as a parameter so it is created and released by the caller?
I have also changed my code to call CGPathRelease which is a little safer. Any suggestions are appreciated.
A: The CoreFoundation policy is that if a function has the word "Create" in it, then the function returns an owning (or retained) object, which the caller is responsible for releasing. So your NewPathWithRoundRect method should be named CreatePathWithRoundRect, and then just drop the delayed CFRelease. The caller will be responsible for releasing it when they're done with it.
| |
doc_23538223
|
Can anyone supply a code snippet to show how to extract each 4 byte integer until the end of the file is reached? Using Python 2.7.
Thanks
A: Check out the NumPy fromfile function. You provide a simple type annotation about the data to be read, and the function efficiently reads it into a NumPy ndarray object.
import numpy as np
np.fromfile(file_name, dtype='<i4')
You can change dtype to reflect size and byte order as well. See here for some examples.
A: You could use struct.unpack():
with open(filename, 'rb') as fileobj:
for chunk in iter(lambda: fileobj.read(4), ''):
integer_value = struct.unpack('<I', chunk)[0]
This uses <I to interpret the bytes as little-endian unsigned integers. Adjust the format as needed; > for big-endian, i for signed integers.
If you need to read a lot of integer values in one go and know how many you need to read, take a look at the array module as well:
from array import array
arr = array('L')
with open(filename, 'rb') as fileobj:
arr.fromfile(fileobj, number_of_integers_to_read)
where you'd need to use array.byteswap() if the endianess of the file and your system didn't match:
if sys.byteorder != 'little':
arr.byteswap()
| |
doc_23538224
|
"Error. An error occurred while processing your request."
I've done all the possible steps in my head, but I have not been able to cope. Please give me a solution.
| |
doc_23538225
|
setTimeout(function(){ res.render("page", {searchArray: searchArray}) }, 7000);
Thats the last line but half the time it renders the page before the array is filled up which causes errors. The amount of time it takes to fill the array depends on the amount of elements the user chooses to search for. Is there a way to only run the render after the array is filled up without having to hardcode a random time like 7000 ?
EDIT:
Here is the full code, had to change the 7,000 to 20,000 because 7000 rendered the page too fast before array fill up
app.post("/search", isLoggedIn, function(req,res){
var searchArray;
queryOptions = {
query: req.body.query,
location: req.body.city + ", " + req.body.state,
radius: '25',
sort: 'date',
limit: req.body.limit
};
searchApi.query(queryOptions).then(res => {
setTimeout(function(){ searchArray = res; console.log("Search array done!") }, 10);
});
setTimeout(function(){ res.render("SearchResults", {searchArray: searchArray}) }, 20000);
});
I want to avoid using settimeout to guess when the previous lines will complete its task.
A: All you have to do is put render into resolved promise. Because the then method is called after the query is finished.
searchApi.query(queryOptions).then(searchArray => {
res.render("SearchResults", {searchArray}) }
});
| |
doc_23538226
|
Trying to pass onPressed Function but getting Error.
Error - The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.
class CircleButton extends StatelessWidget {
CircleButton({required this.icon, required this.onPressed});
final IconData icon;
final Function onPressed; [![Error][1]][1]//Here
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Icon(icon),
onPressed: onPressed,
style: ElevatedButton.styleFrom(
elevation: 6.0,
primary: Color(0xFF4C4F5E),
shape: CircleBorder(),
padding: EdgeInsets.all(15),
),);
}}
A: The Function type is actually a dynamic Function type.
The ElevatedButton expects a void Function to its onPressed method, which there is actually a type that is a typedef for it: VoidCallback
So, replace your Function onPressed with VoidCallback onPressed.
A: Change Function to VoidCallback
class CircleButton extends StatelessWidget {
CircleButton({required this.icon, required this.onPressed});
final IconData icon;
final VoidCallback onPressed; //Change Function to VoidCallback
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Icon(icon),
style: ElevatedButton.styleFrom(
elevation: 6.0,
primary: Color(0xFF4C4F5E),
shape: CircleBorder(),
padding: EdgeInsets.all(15),
),
);
}
}
| |
doc_23538227
|
I am trying to write a function that receives something like an &Vec<i32> and returns somthing that can be converted into an Iterator over i32.
The output contains nothing borrowed from the input. It it my intention that the output has a longer lifetime than the input.
To my newbie eyes, it looks like this should work.
fn error_1<'a, I: IntoIterator<Item=&'a i32>>(_: I) -> impl IntoIterator<Item=i32> + 'static {
vec![1]
}
But, when I test if the output can live longer than the input...
fn test_e1() {
let v = vec![3];
let a = error_1(&v);
drop(v); // DROP v BEFORE a.. should be ok!?
}
I get this error.
error[E0505]: cannot move out of `v` because it is borrowed
--> src/lib.rs:8:10
|
7 | let a = error_1(&v);
| -- borrow of `v` occurs here
8 | drop(v); // DROP v BEFORE a.. should be ok!?
| ^ move out of `v` occurs here
9 | }
| - borrow might be used here, when `a` is dropped and runs the destructor for type `impl IntoIterator<Item = i32>`
Okay - So, rust is worried that a possible Implementation of IntoIterator MIGHT have borrowed "v" ?
Playground Link - broken code
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=41ef3bce0157cc23f824f20eb0651bd9
I tried experimenting with this further...
What absolutely baffles me, is why this next test compiles just fine... It seems to have the same problem, but rust is happy to compile it.
fn fine_1<'a, I: IntoIterator<Item=i32>>(_: &I) -> impl IntoIterator<Item=i32> + 'static {
vec![1]
}
fn test_f1() {
let v = vec![3];
let a = fine_1(&v);
drop(v); // DROP v BEFORE a.. should be ok!?
}
Playground link for tweaked, working code
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7e92549aa4e741c4dd0aae289afcf9db
Could someone help me explain what is wrong with the first code?
How can i specify that the lifetime of the returned type is completely unrelated to the lifetime of the parameter?
Just for fun, another broken example.. this time returning somthing that has nothing to do with Vec.. same error.
fn error_fn<'a, I: IntoIterator<Item=&'a i32>>(_: I) -> impl Fn() + 'static{
|| {}
}
fn test_fn() {
let v = vec![3];
let a = error_fn(&v);
drop(v);
}
I'm not looking to work-around this... I can re-factor the code.
The goal here is to learn... This exposes a gap in my understanding of life-times...
Something that, until very recently, i thought i had nailed :D
Its worth mentioning, that if i change the input to a concrete type, rather than trait impl.. `_: &Vec everything, once again, compiles fine.
It SEEMS to be the life-time on the associated type of the trait, that break everything... I just dont understand why !??
A: impl Trait on return type position implicitly captures generic type parameters. This means it is limited by their lifetimes. As far as I know there is no way to opt this out.
It does not capture lifetime parameters, and so the variant without a use of 'a compiles fine.
This issue provides some details.
On nightly, this can be avoided by using type_alias_impl_trait, as it only captures what explicitly specified for it:
#![feature(type_alias_impl_trait)]
type Res = impl IntoIterator<Item = i32>;
fn error_1<'a, I: IntoIterator<Item = &'a i32>>(_: I) -> Res {
vec![1]
}
Playground.
| |
doc_23538228
|
http://www.5t.torino.it/5t/it/trasporto/arrivi-fermata.jsp
i have to make a Get request and parse the response.. i try with:
var xmlHttp = null;
var theUrl = "http://m.gtt.to.it/m/it/arrivi.jsp?n=876";
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET",theUrl,false);
xmlHttp.send( null );
xmlDoc=xmlHttp.responseXML;
but i don't know the structure of document how i can do to navigate it?
A:
but i don't know the structure of document how i can do to navigate it?
You either walk the tree and poke at the note type and node name of the nodes in it, or you examine the XML document manually in order to learn the structure.
A: It is better to make your Ajax call asynchronous imo by doing:
xmlhttp.open("GET", theUrl, true);
This will prevent your users from interfering an annoying "blocked" period on your website.
If you do so you have to add a onreadystatechange handler so you can parse the incoming data there and display the data you want to display.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status == 200) {
var content = xmlhttp.responseText;
//Parse your content here...
}
}
Clearly you have to know what data you are retrieving to be able to parse it. But for that you can just analyze the responseText and find the elements that always contain your data. Then simply retrieve the values from those <html> tags and display it accordingly.
For instance if you want to retrieve the data in a <label> with id set to arrival-time do:
content.getElementById('arrival-time').innerHTML;
| |
doc_23538229
|
The div to style
<div id="spam_and_ham_mix">
Irrelevant, looooooooong text (--> should be hidden)
<div id="ham">Important stuff (--> should be visible)</div>
</div>
The desired result
I want that only the "important stuff" to show up, while hiding everything else.
1st attempt
#spam_and_ham_mix { display:none; } /* CSS-Weight 100 */
#spam_and_ham_mix #ham { display:block; } /* CSS-Weight 200 */
Result: the div remains completely hidden, showing nothing at all.
2nd attempt
#spam_and_ham_mix { visibility:hidden; } /* CSS-Weight 100 */
#spam_and_ham_mix #ham { visibility:visible; } /* CSS-Weight 200 */
Result: The irrelevant text is invisible, but it still takes the same space as if it were visible (which is in line with the CSS-specification but not the desired result):
Question
What can I do about it?
I am looking for a CSS-only solution (if possible).
A: NOTE - This answer is intended for situations that exist that are not expected to impact search engine optimization (SEO). In other words, print stylesheets and sites/pages where the content is not meant to be crawled by search engines. Doing what's below in those situations may cause a search engine to determine the site is manipulating content, thus possibly negatively affecting search placement or resulting in a ban of some sort. I do not have any evidence this is the case, but be careful if this is your situation.
This seems to work in all the browsers I tested (FF13, Chrome, Opera 12, IE7-9):
#spam_and_ham_mix {
font-size: 0;
}
#ham {
font-size: 15px;
}
http://jsfiddle.net/userdude/kqUUN/
Feels "hacky" (and not as in "-sacky"), but so do negative margins.
Note as well, you have to be careful with specificity:
#spam_and_ham_mix,
#spam_and_ham_mix .ham {
font-size: 0;
}
.ham {
font-size: 15px;
}
http://jsfiddle.net/userdude/kqUUN/1/
.ham as the lone selector will be overridden by the more "specific" selector, ie, other one.
A: Since you mentioned images and such, perhaps approach like this could work for you:
http://jsfiddle.net/lollero/nYFWw/
CSS:
#spam_and_ham_mix {
visibility: hidden;
height: 0px;
position: relative;
overflow: visible;
}
#spam_and_ham_mix #ham {
visibility: visible;
position: absolute;
top: 0px;
left: 0px;
}
HTML ( same as yours ):
<div id="spam_and_ham_mix">
Irrelevant, looooooooong text (--> should be hidden)
<div id="ham">Important stuff (--> should be visible)</div>
</div>
You could set #spam_and_ham_mix { width: 0px; } but then you'd most likely want to give #spam_and_ham_mix #ham a width.
A: Here you go:
http://jsfiddle.net/kqUUN/12/
The only problem there is, you'll have to set the height of the #spam_and_ham_mix manually to whatever you want. Hope this helps.
| |
doc_23538230
|
A: static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().
So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
Read more here
A: If you have a variable which is class-dependant and you try to reference it in a static method it won't compile due to the fact that non-static class variables need an instance to get initialized.
Static elements get initialized automatically into JVM when the class gets loaded - instance variables don't, they're initialized when an instance is created.
Take a look at some Java Docs regarding class variables, it's described in depth in the original Oracle manual. You can start by looking here for example.
| |
doc_23538231
|
{
forest_ranger: "bob",
some_other_data: {},
forests: [
{
forest_id: 'forestA',
trees: [
{
tree_id: 'treeA',
branches: [
{
branch_id: 'branchA',
}
]
}
]
}
],
}
I have that all working properly, but only if I'm reading directly from a collection.
My question is - how can I
a) save forest_ranger and some_other_data "for later"
b) and start the next stage by mapping forests as the array of
documents that are input to the "count all leaves"?
Note - I tried to get just (b) working for starters, but I can't seem to treat "forests" as an array so that the solution in the link above can do its magic.
Then- when that phase is done, extract what was stored in (a) to get the original format back with all the counts.
A: That is the main disadvantage of using $group. You have to explicitly carry forward every non participating fields using either $first or $last like this:
Get the test data with those additional fields from this new MongoPlayground link.
Check the updated query taken from the link:
db.Forests.aggregate([
{ $unwind: "$forests" },
{ $unwind: "$forests.trees" },
{ $unwind: "$forests.trees.branches" },
{
$lookup: {
from: "Leaves",
localField: "forests.trees.branches.branch_id",
foreignField: "branch_id",
as: "forests.trees.branches.leaves"
}
},
{
$addFields: {
"forests.trees.branches.leaf_count": { $size: "$forests.trees.branches.leaves" }
}
},
{
$project: { "forests.trees.branches.leaves": 0 }
},
{
$group: {
_id: {
forest_id: "$forests.forest_id",
tree_id: "$forests.trees.tree_id"
},
forest_ranger: { $first: "$forest_ranger" },
some_other_data: { $first: "$some_other_data" },
leaf_count: { $sum: "$forests.trees.branches.leaf_count" },
branches: { $push: "$forests.trees.branches" }
}
},
{
$group: {
_id: "$_id.forest_id",
forest_ranger: { $first: "$forest_ranger" },
some_other_data: { $first: "$some_other_data" },
leaf_count: { $sum: "$leaf_count" },
trees: {
$push: {
leaf_count: { $sum: "$leaf_count" },
tree_id: "$_id.tree_id",
branches: "$branches"
}
}
}
},
{
$group: {
_id: null,
forest_ranger: { $first: "$forest_ranger" },
some_other_data: { $first: "$some_other_data" },
leaf_count: { $sum: "$leaf_count" },
forests: {
$push: {
leaf_count: { $sum: "$leaf_count" },
forest_id: "$_id",
trees: "$trees"
}
}
}
},
{
$project: { _id: 0 }
}
])
Output:
{
"forest_ranger" : "bob",
"some_other_data" : {
"data" : "Dummy data"
},
"leaf_count" : 4,
"forests" : [
{
"leaf_count" : 3,
"forest_id" : "forestA",
"trees" : [
{
"leaf_count" : 1,
"tree_id" : "treeB",
"branches" : [
{
"branch_id" : "branchB",
"leaf_count" : 1
}
]
},
{
"leaf_count" : 2,
"tree_id" : "treeA",
"branches" : [
{
"branch_id" : "branchA",
"leaf_count" : 1
},
{
"branch_id" : "branchA1",
"leaf_count" : 1
},
{
"branch_id" : "branchA2",
"leaf_count" : 0
}
]
}
]
},
{
"leaf_count" : 1,
"forest_id" : "forestB",
"trees" : [
{
"leaf_count" : 0,
"tree_id" : "treeD",
"branches" : [
{
"branch_id" : "branchD",
"leaf_count" : 0
}
]
},
{
"leaf_count" : 1,
"tree_id" : "treeC",
"branches" : [
{
"branch_id" : "branchC",
"leaf_count" : 1
}
]
}
]
},
{
"leaf_count" : 0,
"forest_id" : "forestC",
"trees" : [
{
"leaf_count" : 0,
"tree_id" : "treeE",
"branches" : [
{
"branch_id" : "branchE",
"leaf_count" : 0
}
]
}
]
}
]
}
| |
doc_23538232
|
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[{
"message":{
"text":"Hello! This is a Messenger bot!"
}
}]
}' "https://graph.facebook.com/v2.6/<PAGE_ID>/thread_settings?access_token=<PAGE_ACCESS_TOKEN>"
This returns the following:
{"error":{"message":"(#100) The parameter setting_type is required","type":"OAuthException","code":100,"fbtrace_id":"B0DKyn9O2KB"}}
Any ideas on how to solve this? Thanks.
A: I had the same problem! Some strange copy/paste error with the cURL command from fb...
It didn't work with cURL, but then I used "Advanced REST client" (Chrome plugin) and I was able to set the Welcome Message.
A: I've tried those exact params with my own page and they worked fine.
Can you try these steps?
*
*Get your page ID and a fresh access token from the Facebook developer console
*Make the request from https://developers.facebook.com/tools/explorer to make sure it isn't a problem with cURL
A: I was having the same issue and the reason was just stupid:
I made copy paste from FB doc and some quotes were wrong. They were ” instead of ".
Open your file in vi or something and search for all quotes so that u can easily understand which are wrong.
A: I had the same issue, i solved it be calling the URL by postman.check image
A: There seems to be a problem with windows cmd interpreting the commands. Can you try the same code using Cygwin. It worked well for me. Cheers
A: this is what works for me
curl --location --request POST 'https://graph.facebook.com/v13.0/your_api_id/messages' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_App_Token' \
--data-raw '{
"messaging_product": "whatsapp",
"preview_url": false,
"recipient_type": "individual",
"to": "33732473829",
"type": "text",
"text": {
"body": "Hello,"
}
}'
I had to specify the access token in the header
| |
doc_23538233
|
Now i'm dealing how to create the form with CTI. A quick overview what kind or relation there are.
Each inspection could have one or more surfaces. Each surface consists of many sub entities, like: surface_leakage, surface_tension or surface_slope. As you could see surface has the CTI with sub entities. Some fields overlap (put them in parent), some don't (put them in child). But in the end I need one form with all the fields grouped by surfaces then by child (maybe Bootrap collapse).
Setting up the relation was not that hard, but to use it into a form is difficult and I'm not sure how I could handle this. See below code with in code two approuches
<?php
class Inspection
{
/**
* @OneToMany(targetEntity="App\Entity\Surface", mappedBy="inspection")
*/
protected $surfaces;
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"surface" = "Surface", "surface_leagage" = "SurfaceLeakage", ...})
*/
class Surface
{
protected $inpection;
protected $description;
}
class SurfaceLeakage extends Surface
{
protected $leakageLevel;
}
// .. other child classes (SurfaceTension, SurfaceSlope, ...)
class InspectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->add('surfaces', CollectionType::class, [
'entry_type' => SurfaceType::class,
]);
}
}
// Approach 1, where each child is added to the SurfaceType
// with this approach data should be mapped false
// This approach ensures that I only have to call SurfaceType once and all fields are loaded, but
// could not make this work with data from DB through CIT.
// Also this method does not allow me to add field description (from parent) to all childTypes
class SurfaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('leakage', SurfaceLeakageType::class, array('mapped' => false));
$builder->add('tension', SurfaceTensionType::class, array('mapped' => false));
// ...
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Surface::class,
]);
}
}
class SurfaceLeakageType extends AbstractType
{
}
// Approach 2, where each childFormType could extend SurfaceType, like below but how to call/create the
// form and handling the data.
// With this approuch i could parent fields to the child
class SurfaceLeakageType extends SurfaceType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('description', TextareaType::class); // field from parent or ...
parent::buildForm($builder, $options);
$builder->add('leakageLevel', IntegerType::class); // own field
// ...
}
}
Then there is form inherit_data
// Approach 3, inherit data, now each child should add this as a field like below,
// but how the only thing I'm doing on InspectionType build Surfaces as collection so
// i think inherit data also doesn't work
class SurfaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('description', TextareaType::class);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'inherit_data' => true,
]);
}
}
class SurfaceLeakageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// inherit fields
$builder->add('leakage', SurfaceType::class, [
'data_class' => SurfaceLeakage::class,
]);
$builder->add('leakageLevel', IntegerType::class); // own field
}
}
Hope someone could help me out
A: I think you are looking for polymorphic forms. Check this bundle https://github.com/infinite-networks/InfiniteFormBundle
A: Another option is by calling the base-type buildForm-function:
class SurfaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('description', TextareaType::class);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Surface::class,
]);
}
}
class SurfaceLeakageType extends AbstractType
{
/**
* @var SurfaceType
*/
private $surfaceType;
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$this->surfaceType->buildForm($builder, $options);
$builder->add('leakageLevel', IntegerType::class); // own field
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => SurfaceLeakage::class,
]);
}
}
| |
doc_23538234
|
var currentImg = 0;
var totalImg = 0;
var stored_year = 0;
var newYear = 0; //the variable i want to edit
$("a.work").click(function(){
var newYear = $(this).html(); // how I want it to be edited
console.log(newYear);
});
$("#next-button").click(function() {
if (currentImg == totalImg) {
currentImg = 0;
}
else {
currentImg++;
}
changeImg();
});
$("#previous-button").click(function() {
if (currentImg == 0) {
currentImg = totalImg;
}
else {
currentImg--;
}
changeImg();
});
function changeImg(galleryYear) {
if (galleryYear === stored_year) {
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
else {
currentImg = 0;
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
$("#gallery-type").html('<img id="gallery-switch" alt="Kyle Breitenbach Art Gallery Icon" src="images/gallery-icon.png" onClick="gallerySwitch('+window.newYear+')">');
stored_year = galleryYear;
}
}
t = 100;
d = 50;
function gallerySwitch(newYear){
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$(".gallery-viewer").fadeOut(t);
$('div.'+newYear).delay(t+d).fadeIn(t); // still not returning a number
} // other than 0.
function switchBack(){
currentImg = parseInt($(this).attr('id'));
alert(currentImg);
$(".gallery-viewer").fadeOut(t);
$("#gallery-control-bar").delay(t+d).fadeIn(t);
$("#gallery-image").delay(t+d).fadeIn(t);
$("#info").delay(t+d).fadeIn(t);
}
var navB = 0;
$("#mobileNav").click(function() {
if (navB == 0) {
$("#mobileMenu").fadeIn(t);
navB++;
}
else {
$("#mobileMenu").fadeOut(t);
navB--;
}
});
$(document).ready(function() {
changeImg(galleryYear);
});
How do I make variables global from within a function?
A: You can have multiple variables with the same name that will shadow each other. Don't add var when you want to use an existing variable.
$("a.work").click(function(){
newYear = $(this).html();
console.log(newYear);
});
A: Just not declare newYear again in the method if you want newYear to take the $('a.work') value:
$("a.work").click(function(){
newYear = $(this).html(); // how I want it to be edited
console.log(newYear);
});
A: You have put var newYear= in the function, this will have created a local version. Make it just newYear =
A: If you create a local variable with the same name as your global it will take precedence:
var newYear = 0;
$("a.work").click(function(){
var newYear = $(this).html(); // This is not your global newYear
}
You'll have to use the fully-qualified name:
var newYear = 0;
$("a.work").click(function(){
var newYear = $(this).html(); // This is not your global newYear
window.newYear = 'This is your global newYear';
}
But code with globals is already hard enough to maintain without duplicate names. I suggest you use unique names.
| |
doc_23538235
|
class MySettingsPage
{
public function __construct() {
add_action( 'admin_menu', 'registration_plugin_menu' );
}
public function registration_plugin_menu() {
add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', 'my_plugin_options' );
}
public function my_plugin_options() {
//callback function
}
}
$settings = new MySettingsPage();
$settings->registration_plugin_menu();
$settings->my_plugin_options();
However, i am getting the error:
Uncaught Error: Call to undefined function add_menu_page()
A: You need to call add_menu_page via a hook e.g. admin_menu. You do hook into admin_menu here:
add_action( 'admin_menu', array($this, 'registration_plugin_menu' ));
But you also call registration_plugin_menu directly here, which will try to run the add_menu_page function immediately - before WP is ready for it:
$settings->registration_plugin_menu();
You don't need that line - it will get called automatically in the constructor.
FYI, you will need to use $this in your add_action call in the constructor because you have it in a class.
Update:
You will also need to use $this in add_menu_page for my_plugin_options, e.g.
add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', array($this, 'my_plugin_options') );
A: Try this
class MySettingsPage
{
public function __construct() {
add_action( 'admin_menu', array($this, 'registration_plugin_menu' ));
}
public function registration_plugin_menu() {
add_menu_page( 'Basic Registration Form', 'Basic Registration Plugin', 'manage_options', 'registration-plugin', array($this,'my_plugin_options') );
}
public function my_plugin_options() {
//callback function
}
}
$settings = new MySettingsPage();
| |
doc_23538236
|
I am trying to make an application(sort of gallery+mail) in which I want to share the image.At longpress
it should open the contacts from where I can select the person from contact and it should take me to the
mailing view. I do not want to do this usung "pushview", but want to just switch the views using "PresentModalViewController"
Now I am getting the addressbook but as soon as I select the contact person instead of displaying the
mailing view it goes back to the homeview.
I even tried dismissing the view after the mailing view is dismissed but the output is still the same..
please help out with this.
what I am doing is as follows:(just merged the two programs given on Xamarin website)
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AddressBookUI;
using MonoTouch.MessageUI;
namespace ChooseContact
{
public partial class ChooseContactViewController : UIViewController
{
public ChooseContactViewController () : base ("ChooseContactViewController", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
ABPeoplePickerNavigationController _contactController;
UIButton _chooseContact;
UILabel _contactName;
_chooseContact = UIButton.FromType (UIButtonType.RoundedRect);
_chooseContact.Frame = new RectangleF (10, 10, 200, 50);
_chooseContact.SetTitle ("Choose a Contact", UIControlState.Normal);
_contactName = new UILabel{Frame = new RectangleF (10, 70, 200, 50)};
View.AddSubviews (_chooseContact, _contactName);
_contactController = new ABPeoplePickerNavigationController ();
_chooseContact.TouchUpInside += delegate {
this.PresentModalViewController (_contactController, true); };
_contactController.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) {
//_contactName.Text = string.Format(e.Person.GetEmails());
_contactName.Text = String.Format ("{0} {1}", e.Person.FirstName, e.Person.LastName);
_contactController.DismissModalViewControllerAnimated (true);
MFMailComposeViewController _mailController;
string[] Emailid = {"[email protected]"};
_mailController = new MFMailComposeViewController ();
_mailController.SetToRecipients (Emailid);
_mailController.SetSubject ("mail test");
_mailController.SetMessageBody ("this is a test", false);
_mailController.Finished += ( object s, MFComposeResultEventArgs args) => {
Console.WriteLine (args.Result.ToString ());
args.Controller.DismissModalViewControllerAnimated (true);
};
this.PresentModalViewController (_mailController, true);
};
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
}
}
A: Try removing this line
_contactController.DismissModalViewControllerAnimated (true);
| |
doc_23538237
|
My git hosting provider only allows up to 2GB worth of data for the entire git repository (including history). I'm using the repository to commit daily database backups every night. Right now the backup is around 400mb and is overwritten every night. After 40 days it finally reached the 2GB limit (due to the commit history). My temporary solution was to rename the current repo to DB Backup - 2 and create a new repo, as they don't have a limit on the number of repos you have, just the total size of a single repo. This is fine, but I don't want to have to do this every month or so. I probably really only need 2 weeks worth of backups. If we don't notice bad data within 2 weeks, then that's on us. So what Git commands would I need to use in order to keep the last x commits and wipe the remaining history? I tried the commands from this post and it works well except that it gets rid of All the history.
| |
doc_23538238
|
//http://iphoneworxx.com/sample-code-ios-iphone-and-ipad
A: All data not stored in the application bundle is preserved during upgrades.
Since the Application bundle is read only on the device you are not able to store any data there. So you should be ok.
A: Files can be saved into the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
And any object (including a few primitives) with NSUserDefaults:
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefauls];
[userDefaults setObject:anObject forKey:@"ObjectKey"];
[userDefaults synchronize];
NSObject* anotherObject = [userDefaults objectForKey:@"ObjectKey"];
| |
doc_23538239
|
USER
user_id | email | password | name | ...
---------------------------------------
CHAT
chat_id | user1_id | user2_id
-----------------------------
MESSAGE
message_id | content | date | user_id | chat_id | ...
------------------------------------------------------
and what I want to do, is to get all the chats the authenticated user have started with an other one, ordered by the date of the messages (from the most recent to the oldest one), plus the information on the user he's talking to.
I'm currently working on the raw SQL request before passing it in Laravel and this it what I try but it doesn't give the waited result :
SELECT user.user_id, user.name, user.surname
FROM user
JOIN chat a
ON user.user_id = a.user1_id
JOIN chat b
ON user.user_id = b.user2_id
WHERE b.chat_id IN
(SELECT chat_id
FROM chat
WHERE user1_id = 1 OR user2_id = 1)
AND user.user_id != 1
----> (I'm testing with the user that has the ID #1)
If anyone could help that would be greatly appreciated.
A: You can use Union to get both results as follows:
select a.user1_id, a.chat_id, user.fname, user.lname
from user
join chat a on a.user2_id = user.user_id and a.user1_id = 1
union
select b.user2_id, b.chat_id, user.fname, user.lname
from user
join chat b on b.user1_id = user.user_id and user2_id = 1
| |
doc_23538240
|
article-api.js (simplified)
articleMiddleware(next) {
return fetch(articleApiListUrl, { headers, method, body })
.then(() => next({ some: 'data'}));
}
This is a simplified version of article-api.js, full code can be seen here:
https://gist.github.com/LukasBombach/7bd9cce28d3a3b905fb8a408b37de3a9
I want to see if next has been called with { some: 'data'}. I use fetch-mock to mock my fetch request
article-api.spec.js (simplified)
describe('article api middleware', () => {
it('creates ARTICLE_SUCCESS when fetching an article has been done', () => {
fetchMock.post('*', { some: 'data' });
return articleMiddleware(next)
.then(expect(next).toBeCalledWith({ some: 'data' }))
.then(() => fetchMock.restore());
});
});
This is a simplified version of article-api.spec.js, full code can be seen here:
https://gist.github.com/LukasBombach/178f591f516fe13c24fb0a4f02c4676c
What I get though is
Expected mock function to have been last called with:
[{ some: 'data' }]
But it was not called.
If you view the full code in the two gists you'll find my code is a little bit different, the error messag there is
expect(received).toBe(expected)
Expected value to be (using ===):
2
Received:
1
This is because of next(action) in line 17 in the first gist calls next (syncroneously) but the next inside the promise never gets called.
A: Here is the solution only using "jest": "^24.8.0", no need to use fetch-mock, you can mock it manually by yourself.
article-api.js:
const fetch = require('node-fetch');
function articleMiddleware(next) {
const articleApiListUrl = 'https://github.com/mrdulin';
const headers = {};
const method = 'get';
const body = {};
return fetch(articleApiListUrl, { headers, method, body }).then(() => next({ some: 'data' }));
}
exports.articleMiddleware = articleMiddleware;
article-api.spec.js:
jest.mock('node-fetch');
const fetch = require('node-fetch');
const { articleMiddleware } = require('./article-api');
describe('articleMiddleware', () => {
it('t1', async () => {
fetch.mockResolvedValueOnce({});
const next = jest.fn();
await articleMiddleware(next);
expect(fetch).toBeCalledWith('https://github.com/mrdulin', { headers: {}, method: 'get', body: {} });
expect(next).toBeCalledWith({ some: 'data' });
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/42676657/article-api.spec.js
articleMiddleware
✓ t1 (9ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
article-api.js | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.131s
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/42676657
| |
doc_23538241
|
Filter Code:
var array = array.js
message.replace(array, "****");
Messaging Code:
if (message && connected) {
$inputMessage.val("");
addChatMessage({
username: username,
message: message
});
socket.emit("new message", message);
}}
My friend is responsible for the Messaging code since he is much more experienced at JavaScript, but he is very busy and can't add it right now so I am trying to.
A: Assuming you have a array to filter which is array you could split your message by white space and then check each word to see if it contains a bad word.
Two methodologies (FYI neither is perfect. both of these solutions have plenty of edge cases/loopholes: I'd recommend a js package that has more thought put into it npm: bad-words, npm: censor-sensor, or npm: swearjar)
Both split the message message.split(' ') and then iterate over each word to see if it needs replacing .map. The first checks to see if the current word is in array and the second sees if array words contain the current word, then if so replace with ****
const array = ['badword', 'nsfw']
let message = 'my message is full of badwords which may be nsfw'
message = message.split(' ').map(word => array.includes(word.toLowerCase()) ? '*****' : word).join(' ')
console.log(message)
message = 'my message is full of badwords which may be nsfw'
message = message.split(' ').map(word => array.some(nsfword=>word.toLowerCase().includes(nsfword)) ? '*****' : word).join(' ')
console.log(message)
| |
doc_23538242
|
*
*I want to create a user
*I want to call get user method (which is on a separate microservice)
constructor(private dataService: DataService) { }
getUser(): Observable<User | null> {
if (!this.retrieve("IsAuthorized") || (this.retrieve("Email") === "" || this.retrieve("Email") === null)) {
return Observable.of(null);
}
return this.getUserByEmail(this.retrieve("Email"))
.do((user: User) => {
this.setCurrentUser(user);
});
}
public createUser(email: string, familyName: string, givenName: string, phoneNumber: string, gender: string): Observable<User | null> {
let createUser = this.dataService.post(this.usersApiUrl, null, {
Email: email, FamilyName: familyName,
GivenName: givenName, PhoneNumber: phoneNumber, Gender: gender
}).map(response => response.json());
return createUser.flatMap((res: Response) => { return this.getUser(); })
}
private setCurrentUser(user: User) {
this.currentUser.next(user);
}
private getUserByEmail(email: string): Observable<User> {
return this.dataService.get(this.usersApiUrl, email).map(response => response.json());
}
this.currentUser is a ReplaySubject<User> = new ReplaySubject<User>(1);
Current behavior: POST (create user) works as expected. GET (this.getUser()) doesn't get called.
P.S: I'm not really interested in create user response because that will only tell me that it succeeded.
Update:
private retrieve(key: string): any {
var item = this.storage.getItem(key);
if (item && item !== 'undefined') {
return JSON.parse(this.storage.getItem(key));
}
return null;
}
Where this.storage is localStorage.
And i subscribe to this in a classic manner:
this.userService.createUser(this.authService.email, this.authService.familyName,
this.authService.givenName, this.authService.phoneNumber, this.authService.gender).subscribe(() => { });
A: If all you do is invoke createUser method, than I think getUser is not firing since nothing is subscribing to it. Add .subscribe() to getUser invocation and see if this helps.
A: Initial attempt was correct from a Rx & client-side point of view.
The problem is related to ASP.NET Core MVC web API where:
[HttpPost]
public void Post([FromBody]CreateUserRequest request)
{
_userService.Create(request);
}
Returns a 200 with empty content instead of 204 (No Content) and that cause stream (rx) failure.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
You can change that to:
[HttpPost]
public IActionResult Post([FromBody]CreateUserRequest request)
{
_userService.Create(request);
return NoContent();
}
| |
doc_23538243
|
def clean_num
@file.each do |line|
number = line[3]
#Would need a .delete for every unwanted character?
clean_number = number.delete(".")
puts clean_number
end
end
What's a more efficient way to delete the other characters mentioned above?
A: You're looking for regular expressions:
clean_number = number.gsub(/[^\d]/, "")
The first argument to gsub is the pattern to find, the second is what to replace each occurrance with.
This replaces everything that isn't a digit ([^\d]) with an empty string ("").
| |
doc_23538244
|
A: The same basic things you would do whenever you need information to be available in PHP from a new request:
*
*Store it in the session. Symfony2 has a great session component for this. Ideal for fleeting data that needs to be saved only while the user is navigating
*Store it in the database. Symfony2 supports Doctrine which makes this very easy. Ideal for permanent storage
Optionally:
*
*Store it on the filesystem. Not recommended unless it's actually a file, but possible as well.
A: In the end, rather than using the session to store data, I created two separate routes to the same controller action. I added an optional argument in the controller action, with a default value only specified in one of the routes. I can then test for that argument's value when the controller runs. In the Twig template that calls this controller action, the path can be generated using either one of these routes, depending on a variable already available.
Bit of a work around, but problem solved!
| |
doc_23538245
|
*
*Visitors - int
*Goal 1 Completions - int
*Goal 2 Completions - int
*Goal N Completions - int
*Transactions Amount - int
*Transactions Revenue - decimal
Here's the table with data, if all of them were int:
id - int
date - date
metric_id - int
metric_amount - int
But Transactions Revenue is decimal, so I have 2 options.
Option 1. Make all of them decimal
id - int
date - date
metric_id - int
metric_amount - decimal
Option 2. Create additional nullable column for Revenue
id - int
date - date
metric_id - int
metric_amount - int
metric_revenue - decimal
Which one is better?
A: You definitely want to have a separate column for each and every attribute of your metrics model.
| |
doc_23538246
|
How to achieve 3D look of nodes similar to this picture: (don't pay attention on diagram itself, this is just illustration of "look" of circles)
A: Here is jsfiddle of the solution. It is based on SVG radial gradients.
For each node, a gradient is defined:
var grads = svg.append("defs").selectAll("radialGradient")
.data(nodes)
.enter()
.append("radialGradient")
.attr("gradientUnits", "objectBoundingBox")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", "100%")
.attr("id", function(d, i) { return "grad" + i; });
grads.append("stop")
.attr("offset", "0%")
.style("stop-color", "white");
grads.append("stop")
.attr("offset", "100%")
.style("stop-color", function(d) { return color(d.cluster); });
Then, instead of line:
.style("fill", function(d) { return color(d.cluster); })
this line is added in the code that creates circles:
.attr("fill", function(d, i) {
return "url(#grad" + i + ")";
})
This produces this effect:(animated gif that I used has some limitations for number of colors, so gradients are not smooth as in real example)
A: Create linear or radial gradient based on your requirement using different colors. Set fill attribute as gradient.
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#0c0")
.attr("stop-opacity", 1);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#c00")
.attr("stop-opacity", 1);
var node = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.style("fill", "url(#gradient)")
.call(force.drag);
| |
doc_23538247
|
Thank you in advance!
A: Just use
android:background="@drawable/your_rectangle_xml_file"
A: Create a rectangle.xml in drawable folder and paste the code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingLeft="20dp"
android:shape="rectangle">
<solid android:color="#000000"></solid>
<corners
android:bottomLeftRadius="@dimen/_5dp"
android:bottomRightRadius="@dimen/_5dp"
android:topLeftRadius="@dimen/_5dp"
android:topRightRadius="@dimen/_5dp"
></corners>
</shape>
after that in your activity use it as like
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text"
android:textColor="#ffffff"
android:textAllCaps="false"
android:background="@drawable/rectangle"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="your image "
android:background="@drawable/rectangle"/>
A: create shame.xml in drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
and in youractivity.xml
<Button
android:id="@+id/btn_Shap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Shape"
android:background="@drawable/shape"/>
| |
doc_23538248
|
Here is my code:
import discord
import random
from discord.ext import commands
client = commands.Bot(command_prefix = ".")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CommandOnCooldown):
return await ctx.send('The command **{}** is still on cooldown for {:.2f}'.format(ctx.command.name, error.retry_after))
pictures =["https://i.imgur.com/LAmHP4K.jpg","https://i.imgur.com/sXS290O.jpg","https://i.imgur.com/Ar7Ihs5.jpg"]
@client.command()
@commands.cooldown(1, 2, commands.BucketType.user)
async def pic(ctx):
embed = discord.Embed(color = discord.colour.red())
random_link = random.choice(pictures)
embed.set_image(url = random_link)
await ctx.send(embed = embed)
client.run("TOKEN")
A: discord.color is the module, discord.Color() is the class. Remember that case sensitivity is very important in python. You need discord.Color.red() because you need the red method of the discord.Color class.
| |
doc_23538249
|
Here is description of what it should do:
It should display a number on one 7-segment display. That number should be increased by one every time someone presses the push button. There is also reset button which sets the number to 0. That's it. Here is VHDL code:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity PWM is
Port ( cp_in : in STD_LOGIC;
inc : in STD_LOGIC;
rst: in std_logic;
AN : out STD_LOGIC_VECTOR (3 downto 0);
segments : out STD_LOGIC_VECTOR (6 downto 0));
end PWM;
architecture Behavioral of PWM is
signal cp: std_logic;
signal CurrentPWMState: integer range 0 to 10;
signal inco: std_logic;
signal temp: std_logic_vector (3 downto 0);
begin
--cp = 100 Hz
counter: entity djelitelj generic map (CountTo => 250000) port map (cp_in, cp);
debounce: entity debounce port map (inc, cp, inco);
temp <= conv_std_logic_vector(CurrentPWMState, 4);
ss: entity decoder7seg port map (temp, segments);
process (inco, rst)
begin
if inco = '1' then
CurrentPWMState <= CurrentPWMState + 1;
elsif rst='1' then
CurrentPWMState <= 0;
end if;
end process;
AN <= "1110";
end Behavioral;
Entity djelitelj (the counter used to divide 50MHz clock):
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity PWM is
Port ( cp_in : in STD_LOGIC;
inc : in STD_LOGIC;
rst: in std_logic;
AN : out STD_LOGIC_VECTOR (3 downto 0);
segments : out STD_LOGIC_VECTOR (6 downto 0));
end PWM;
architecture Behavioral of PWM is
signal cp: std_logic;
signal CurrentPWMState: integer range 0 to 10;
signal inco: std_logic;
signal temp: std_logic_vector (3 downto 0);
begin
--cp = 100 Hz
counter: entity djelitelj generic map (CountTo => 250000) port map (cp_in, cp);
debounce: entity debounce port map (inc, cp, inco);
temp <= conv_std_logic_vector(CurrentPWMState, 4);
ss: entity decoder7seg port map (temp, segments);
process (inco, rst)
begin
if inco = '1' then
CurrentPWMState <= CurrentPWMState + 1;
elsif rst='1' then
CurrentPWMState <= 0;
end if;
end process;
AN <= "1110";
end Behavioral;
Debouncing entity:
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.STD_LOGIC_ARITH.all;
use IEEE.STD_LOGIC_UNSIGNED.all;
ENTITY debounce IS
PORT(pb, clock_100Hz : IN STD_LOGIC;
pb_debounced : OUT STD_LOGIC);
END debounce;
ARCHITECTURE a OF debounce IS
SIGNAL SHIFT_PB : STD_LOGIC_VECTOR(3 DOWNTO 0);
BEGIN
-- Debounce Button: Filters out mechanical switch bounce for around 40Ms.
-- Debounce clock should be approximately 10ms
process
begin
wait until (clock_100Hz'EVENT) AND (clock_100Hz = '1');
SHIFT_PB(2 Downto 0) <= SHIFT_PB(3 Downto 1);
SHIFT_PB(3) <= NOT PB;
If SHIFT_PB(3 Downto 0)="0000" THEN
PB_DEBOUNCED <= '1';
ELSE
PB_DEBOUNCED <= '0';
End if;
end process;
end a;
And here is BCD to 7-segment decoder:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity decoder7seg is
port (
bcd: in std_logic_vector (3 downto 0);
segm: out std_logic_vector (6 downto 0));
end decoder7seg;
architecture Behavioral of decoder7seg is
begin
with bcd select
segm<= "0000001" when "0000", -- 0
"1001111" when "0001", -- 1
"0010010" when "0010", -- 2
"0000110" when "0011", -- 3
"1001100" when "0100", -- 4
"0100100" when "0101", -- 5
"0100000" when "0110", -- 6
"0001111" when "0111", -- 7
"0000000" when "1000", -- 8
"0000100" when "1001", -- 9
"1111110" when others; -- just - character
end Behavioral;
Does anyone see where I made my mistake(s) ?
I've tried that design on Spartan-3 Started board and it isn't working ... Every time I press the push button, I get crazy (random) values. The reset button is working properly.
Thanks !!!!
A: I guess the problem is here:
process (inco, rst)
begin
if inco = '1' then
CurrentPWMState <= CurrentPWMState + 1;
elsif rst='1' then
CurrentPWMState <= 0;
end if;
end process;
When rst='1' you will reset CurrentPWMState. But when inco='1' the you endlessly add 1 to CurrentPWMState. That's something like an asynchronous feedback loop through a latch. You should do something edge sensitive here. Probably you should capture inco using your clock signal, detect a 0->1 change and then add 1.
A: Agree with the previous answer.
A code like this should do the trick:
process (inco, ps, rst)
begin
if rst='1' then
CurrentPWMState <= '0';
prev_inco <= inco; -- This signal captures the previous value of inco
elsif ps'event and ps='1' then
if inco='1' and prev_inco='0' then -- Capture the flank rising.
CurrentPWMState <= CurrentPWMState + 1;
end if;
prev_inco <= inco;
end if;
end process;
I recognize I haven't tried the code (just coded in here) but I think it's ok.
| |
doc_23538250
|
driver.get("https://outlook.office365.com/owa/");
driver.findElement(By.cssSelector("input#userNameInput")).sendKeys("username");
driver.findElement(By.cssSelector("input#passwordInput")).sendKeys("password");
driver.findElement(By.cssSelector("span#submitButton")).click();
driver.switchTo().alert().accept();
Below is the error log:
org.openqa.selenium.NoAlertPresentException: no alert open
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 8.95 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'BLR1-LP6R5XLC2', ip: '10.74.209.87', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_65'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\e3028099\AppData\Local\Temp\scoped_dir11924_9010}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: 0eff339a449a81e2ab5b3733deec9a91
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:661)
at org.openqa.selenium.remote.RemoteWebDriver$RemoteTargetLocator.alert(RemoteWebDriver.java:990)
at regressiontestcase.NewTest.sampleTest(NewTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.remote.AbstractRemoteT[enter image description here][1]estNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
[Chrome Select a Certificate Popup][2]
A: There seems to be an issue with the latest Chrome version.
I've rolled back to the previous stable one and it's working.
Can't tell if it's the chrome driver / selenium framework.
[03/07/2017] [13:02] [OpenQA.Selenium.NoSuchFrameException: no such frame
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.3.9600 x86_64)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteTargetLocator.Frame(Int32 frameIndex)
| |
doc_23538251
|
My problem is when I encrypt the password
Password is
No8ANfBX/0GAWJnF4v0bQwf/4UiJ7qY7rOPfrfB0XMQ=
When I pass this parameter via Rest API,
My password changed to-
No8ANfBX/0GAWJnF4v0bQwf\/4UiJ7qY7rOPfrfB0XMQ=
Image
So when decrypt at server,password is not same.
My code for parameter pass is
public JSONObject A(String userName, String passWord, String version) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
try {
o.put("interface", "AA");
o.put("method", "A");
p.put("userName", mapObject(userName));
p.put("passWord", mapObject(passWord));
p.put("version", mapObject(version));
o.put("parameters", p);
Log.e("Pass",String.valueOf(passWord));
Log.e("Pass",String.valueOf(mapObject(passWord)));
String s = o.toString();
Log.e("Params", String.valueOf(s));
String r = load(s);
Log.e("Params", String.valueOf(r));
result = new JSONObject(r);
} catch (Exception e) {
Log.e("Error is", String.valueOf(e));
}
return result;
}
How could I change not to add extra \ in params?
A: You need to pass your password with UTF-8 formate & also decrypt from server end with UTF-8
So it would be like URLEncoder.encode("No8ANfBX/0GAWJnF4v0bQwf/4UiJ7qY7rOPfrfB0XMQ=", "utf-8")
| |
doc_23538252
|
// Get running processes
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = manager.getRunningAppProcesses();
And I am also trying to use the below code to get all individual process start time in the Android Device from each individual pid- "process id" in the following file directory:"/proc/[PID]/stat" obtained from linux:
public static long getStartTime(final int pid) throws IOException {
final String path = ("/proc/" + pid + "/stat");
final String stat;
final String field2End = ") ";
final String fieldSep = " ";
final BufferedReader reader = new BufferedReader(new FileReader(path));
try {
stat = reader.readLine();
System.out.println("******Stat******"+ stat);
} finally {
reader.close();
}
try {
final String[] fields = stat.substring(stat.lastIndexOf(field2End)).split(fieldSep);
final long processstartTime = .....;
...(change processstartTime from clock tick to seconds & return processstartTime value)...
}
}
I do need to get the process StartTime from the following Linux directory path:"/proc/pid/stat" for each individual running processes in an Android Device. At this point, when I debug the statement for the following Linux directory path:"/proc/[PID]/stat", in the following code line: System.out.println("******Stat******"+ stat);, I am getting the output debug as :
******Stat******642 (flipboard.app) S 2848 2848 0 0 -1 4194624 126020 0 1019 0 2441 632 0 0 20 0 101 0 7040346 1079652352 7233 4294967295 1 1 0 0 0 0 4612 0 38120 4294967295 0 0 17 1 0 0 0 0 0 0 0 0
Furthermore, I do know that the start_time of the process is measure in clock ticks, hence to convert it to seconds, I will need to cal the following as "start_time/hertz".
Now the issue is, How Do I get the Running Process Start Time in "/proc/[PID]/stat"? Can anyone please help? Thanks.
A: loggin of individual process time can be done by this way:
public static long getStartTime(final int pid) throws
IOException {
final long SYSTEM_CLK_TCK= 100; //needed as value in /proc/[PID]/stat file driectory is in clock ticks,100 is used to convert clock ticks to secs
final int fieldStartTime = 20; //column 20 of the /proc/[PID]/stat file driectory
try {
System.out.println("******String path******"+ path);
stat = reader.readLine();
System.out.println("******String stat******"+ stat);
} finally {
reader.close();
}
try {
final String[] fields = stat.substring(stat.lastIndexOf(field2End)).split(fieldSep);
final long startTime = Long.parseLong(fields[fieldStartTime]);
System.out.println("******fieldstarttime based on clock ticks******"+ startTime);
return startTime * msInSec / SYSTEM_CLK_TCK;
}
| |
doc_23538253
| ||
doc_23538254
|
The reason I have posted it here is it is working fine in laptop or pc but the validation is not working on tablet.
Can anyone tell me the reason for this?
function NoSpecialCharacters(evt) {
//this method allows alphabets numbers and some special
//characters like space, backspace, dot, hyphen and underscore
var keyCode = (evt.which) ? evt.which : event.keyCode
if ((keyCode >= 33 && keyCode <= 44) || keyCode == 47 || (keyCode >= 58 && keyCode <= 64) ||
(keyCode >= 123 && keyCode <= 126) || (keyCode >= 91 && keyCode <= 94) || keyCode == 96) {
return false;
}
return true;
}
| |
doc_23538255
|
Edit: I think posting more of the code might help. I'm in so far over my head here I couldn't even really explain it properly. I attempted to hack something together myself but it's not quite working. The important part is the "update the link" section. So let's say that randomlink_i = test1 and it's a string. When I try to pass randomlink_i to the indexOf function I get a -1 for that alert that's just below it. However, if I just pass in 'test1' directly, instead of the variable then I get 0 which is the correct position. Am I way off base here?
var _SERIAL = new Array(
{ done: false, initialized: false, market: '', submarket: '' },
{ done: false, value: '', type: '' },
{ done: [false, false], value: '', initialized: [false, false], visited: [false, false], darkbackground: [false,false] },
{ done: false, value: '' }
);
var _MARKETS = new Array('',
{
title: 'first set',
url: new Array('http://www.test.com/1.html','http://www.test.com/2.html','http: //www.test.com/3.html','http://www.test.com/4.html'),
anchortext: new Array('test1','test2','test3','test4'),
label: 'Register Now!'
},
{
title: 'second set',
url: new Array('http://www.test2.com/1.html','http://www.test2.com/2.html','http://www.test2.com/3.html','http://www.test2.com/4.html'),
anchortext: new Array('test12','test22','test32','test42'),
label: 'Register Now!'
}
)
function initMarket() {
_DEBUG ? debugWrite('initMarket()') : '';
var randomlink_i;
// if there are sub markets
_OPEN_RADIOS[_SERIAL[0].market] ? randomlink_i = randomPop(_MARKETS[_SERIAL[0].market].anchortext[_SERIAL[0].submarket].anchortext) : randomlink_i = randomPop(_MARKETS[_SERIAL[0].market].anchortext);
// update the link on step 3
var marketlinks = $$('#btn_foot a');
marketlinks[0].innerHTML = randomlink_i;
alert(randomlink_i);
alert(typeof(randomlink_i));
var marketlinkposition = _MARKETS[_SERIAL[0].market].anchortext.indexOf(randomlink_i);
alert(marketlinkposition);
marketlinks[0].href = _MARKETS[_SERIAL[0].market].url[marketlinkposition];
alert(_MARKETS[_SERIAL[0].market].url[marketlinkposition]);
// removal of "_counted" attribute
for (var i=0; i<marketlinks.length; i++) {
marketlinks[i]._counted = undefined;
marketlinks[i].removeAttribute('_counted');
}
}
A: I'm not entirely sure what you're asking, but there's an indexOf method in all modern browsers, and IE9+. (If you need to support IE8-, that page also has some code you could use.)
So you could search each anchortext array in each object, like so (I think this is what you wanted, but let me know if I misunderstood):
function getSomeItem(value) {
var i = _MARKETS.length,
current;
while (i) {
i -= 1;
current = _MARKETS[i].anchortext.indexOf(value);
if (current + 1) {
return _MARKETS[i].url[current];
}
}
}
So you would use the above function like so:
getSomeItem('test1'); // returns 'http://www.test.com/1.html'
| |
doc_23538256
|
puzzle1 = raw_input ("The cave has a small golden inscription on the door with a dial for imputting numbers. A puzzle! Would you like to attempt the puzzle?")
#Puzzle 1
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
print ("You press the button on the door. A small dial turns quickly and picks a random number between 1 and 50. Now you must guess the number being told to go 'higher' or 'lower'. You have only 5 tries to guess the random number.")
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
from random import randrange
puzzle1number = randrange(1,51)
puzzle1number2 = raw_input ("What is the first guess? You have 5 tries left.")
if int(puzzle1number2) == puzzle1number:
print ("You did it first try! Lucky you!")
if int(puzzle1number2) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) < puzzle1number:
print ("Higher!")
if int(puzzle1number2) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number3 = raw_input ("What is the second guess? You have 4 tries left.")
if int(puzzle1number3) == puzzle1number:
print ("You did it second try! Great guessing!")
if int(puzzle1number3) < puzzle1number:
print ("Higher!")
if int(puzzle1number3) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) == puzzle1number or int(puzzle1number3) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number4 = raw_input ("What is the third guess? You have 3 tries left.")
if int(puzzle1number4) == puzzle1number:
print ("You did it third try! Great guessing!")
if int(puzzle1number4) < puzzle1number:
print ("Higher!")
if int(puzzle1number4) > puzzle1number:
print ("Lower!")
if int(puzzle1number4) == puzzle1number or int(puzzle1number4) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number5 = raw_input ("What is the fourth guess? You have 2 tries left.")
if int(puzzle1number5) == puzzle1number:
print ("You did it fourth try! That came kind of close.")
if int(puzzle1number5) < puzzle1number:
print ("Higher!")
if int(puzzle1number5) > puzzle1number:
print ("Lower!")
if int(puzzle1number5) == puzzle1number or int(puzzle1number5) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number6 = raw_input ("What is the fifth and final guess? This is your last try!")
if int(puzzle1number6) == puzzle1number:
print ("Finally! Got it on the last go!")
else:
print ("Blast! The small dial clicks and becomes unmovable. Whatever treasure was in there is now locked inside. I wonder why that was a lock?")
breakhold2 += 1
break
if path1 == "2":
while breakhold2 == "0":
if puzzle1.lower in ["No", "no", "n", "N"]:
print ("You decide not to attempt the puzzle.")
breakhold2 += 1
break
A: puzzle1.lower in ['yes', 'no', 'whatever', ...] will always be False.
Use instead puzzle1.lower() in [....].
Check:
answer = 'Yes'
print(answer.lower)
print(answer.lower in ['yes', 'y'])
versus:
answer = 'Yes'
print(answer.lower())
print(answer.lower() in ['yes', 'y'])
| |
doc_23538257
|
I currently have it so a search icon exists in the top right corner. When you click on the icon, it will show you the UISearchController.
The problem is, when I try to do searchController.delegate = self, I get an error saying
Cannot assign value of type 'ParentViewController' to type 'UISearchControllerDelegate'?
I'm assuming since I can't set the delegate, none of the actions are linked, but I can't figure out why it won't let me?
Here's the code I'd like to work. Am I implementing the protocol wrong and just not seeing it, or missing something entirely?
class ParentViewController: ButtonBarPagerTabStripViewController, UISearchResultsUpdating, UISearchBarDelegate {
var searchBarButtonItem: UIBarButtonItem?
override func viewDidLoad() {
searchBarButtonItem = navigationItem.rightBarButtonItem
super.viewDidLoad()
}
func updateSearchResults(for searchController: UISearchController) {
print("update search results")
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
print("search cancelled")
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
print("Filter: " + searchText)
}
@IBAction func startSearchAction(sender: UIBarButtonItem) {
print("Clicked")
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.showsCancelButton = true
searchController.dimsBackgroundDuringPresentation = true
self.navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
navigationItem.setRightBarButton(nil, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| |
doc_23538258
|
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
A: You use Number.prototype.toPrecision() with parameter 2, Number.prototype.toFixed() with parameter 1.
+randomNumber.toPrecision(2);
Alternatively, you can use String.prototype.slice() with parameters 0, 3
+String(randomNumber).slice(0, 3);
A: If you need to set the amount of decimal places in a number, you can use toFixed(X), where X is the amount of decimal places you want to have.
For example,
4.589729345235789.toFixed(1); would result in 4.6.
Keep in mind, this will convert the number into a string.
If you need absolute accuracy and 4.6 is not good enough for you, see this Stackoverflow post, which has this as a more "accurate" method for your case:
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
Notice the {0,2} inside of that, which is the range. You can change it to {0,1} in your case.
| |
doc_23538259
|
use strict "vars";
use warnings;
use feature qw(switch);
use locale;
use POSIX qw(locale_h);
setlocale(LC_ALL, "cs_CZ.UTF-8");
use constant (
ERROR_OK => 0,
ERROR_CMD => 1,
ERROR_INPUT => 2,
ERROR_OUTPUT => 3,
ERROR_INPUT_FORMAT => 4
);
exit ERROR_OUTPUT;
I am still getting error "Argument "ERROR_OUTPUT" isn't numeric in exit at ... "
How can i use constant for exit values instead of directy use of numbers?
A: A use constant directive should use {curly braces}, not (parentheses).
use constant {
ERROR_OK => 0,
ERROR_CMD => 1,
ERROR_INPUT => 2,
ERROR_OUTPUT => 3,
ERROR_INPUT_FORMAT => 4
};
A: Change the parentheses after use constant to curlies.
use constant {
ERROR_OK => 0,
# etc.
};
| |
doc_23538260
|
library(rvest)
library(httr)
url <- "http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_CHECKBOX.html"
session <- html_session(url)
form <- html_form(session)[[1]]
filled_form <- set_values(form, maillist = "checked")
results <- submit_form(session, filled_form)
content(results$response, "text")
An obvious workaround is that clicking the checkbox and submitting the form in a browser shows the value of maillist as "on", but this information might not always be known for other forms.
| |
doc_23538261
|
#!/bin/bash -x
USER_ID=( User1 User2 User3 )
USER_CONF=/opt/test/config.xml
for i in "${USER_ID[@]}"; do
printf '<user><id>ID</id><name><%s/name></user>\n' "$i" >> "$USER_CONF"
done
What I get now in config.xml is:
<company="external">
<enabled>true</enabled>
<users="allowed">
USER_TO_INSERT_HERE
</users>
</company>
<user><id>ID</id><name><User1/name></user>
<user><id>ID</id><name><User2/name></user>
<user><id>ID</id><name><User3/name></user>
What I want to get after the script execution in config.xml is:
<company="external">
<enabled>true</enabled>
<users="allowed">
<user><id>ID</id><name><User1/name></user>
<user><id>ID</id><name><User2/name></user>
<user><id>ID</id><name><User3/name></user>
</users>
</company>
Do you know how can I record the values from the for and write them in a variable then to just sed that var in the code?
I know how to sed it but don't know how to record in the var the values or something like that?
A: First of all, <users="allowed"> in an invalid XML-node. This should probably be something like <users permission="allowed">.
Please use an XML parser like xidel to edit your 'config.xml'.
With "direct element constructors":
$ xidel -s config.xml -e '
x:replace-nodes(
//users,
<users permission="allowed">{
for $user in ("User1","User2","User3") return
<user><id>ID</id><name>{$user}</name></user>
}</users>
)
' --output-node-format=xml --output-node-indent
With "computed constructors":
$ xidel -s config.xml -e '
x:replace-nodes(
//users,
function($x){
element {$x/name()} {
$x/@*,
for $user in ("User1","User2","User3") return
element user {
element id {"ID"},
element name {$user}
}
}
}
)
' --output-node-format=xml --output-node-indent
Output:
<company="external">
<enabled>true</enabled>
<users permission="allowed">
<user>
<id>ID</id>
<name>User1</name>
</user>
<user>
<id>ID</id>
<name>User2</name>
</user>
<user>
<id>ID</id>
<name>User3</name>
</user>
</users>
</company="external">
Playground
A: Lots of great answers over at unix.stackexchange.com.
The canonical answer for this sort of case (NOTE: not for XML in general in all cases, but for a file where there's a TOKEN on a line on it's own to be replaced - which is exactly the case you have given) is -
a) Output the part of the file "up to" the line before the line with the token
b) Output the replacement
c) Output the rest of the file "from" the line after the line with the token
e.g. here's the simple sed variant (which is no where near as elegant as the r option to sed) -
sed -e '/USER_TO_INSERT_HERE/,$ d' source.xml
cat replacement.xml
sed -e '1,/USER_TO_INSERT_HERE/ d' source.xml
| |
doc_23538262
|
import openpyxl, csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from openpyxl.utils import column_index_from_string
output = open('differences.csv', 'w', newline='')
output_writer = csv.writer(output)
wb1, wb2 = '', ''
sheet1, sheet2 = '', ''
column_1, column_2 = '', ''
root = Tk()
root.configure(background='light green')
root.geometry("500x500")
root.wm_title("BananaCell")
e1 = Text(root, width=15, height=1)
e1.pack()
e1.place(x=70, y=150)
e2 = Text(root, width=15, height=1)
e2.pack()
e2.place(x=300, y=150)
column1_entry = Text(root, width=5, height=1)
column1_entry.pack()
column1_entry.place(x=135, y=250)
column2_entry = Text(root, width=5, height=1)
column2_entry.pack()
column2_entry.place(x=385, y=250)
def destroy():
root.destroy()
def ask_for_filename_1():
global wb1
wb1 = askopenfilename(title="Select Workbook 1")
print(str(wb1))
return wb1
def ask_for_filename_2():
global wb2
wb2 = askopenfilename(title="Select Workbook 1")
print(str(wb2))
return wb2
def ask_for_sheet1():
global sheet1
sheet1 = e1.get("1.0", "end-1c")
print(sheet1)
return sheet1
def ask_for_sheet2():
global sheet2
sheet2 = e2.get("1.0", "end-1c")
print(sheet2)
return sheet2
def get_col_1():
global column_1
column_1 = column1_entry.get("1.0", "end-1c")
print(column_1)
return column_1
def get_col_2():
global column_2
column_2 = column2_entry.get("1.0", "end-1c")
print(column_2)
return column_2
filename_button1 = Button(root, text="Workbook 1", width=12, height=2, command=ask_for_filename_1)
filename_button1.pack()
filename_button1.place(x=100, y=100)
filename_button2 = Button(root, text="Workbook 2", width=12, height=2, command=ask_for_filename_2)
filename_button2.pack()
filename_button2.place(x=300, y=100)
col_button1 = Button(root, text="Enter", width=5, height=1, command=get_col_1)
col_button1.pack()
col_button1.place(x=185, y=248)
col_button2 = Button(root, text="Enter", width=5, height=1, command=get_col_2)
col_button2.pack()
col_button2.place(x=435, y=248)
sheet_button1 = Button(root, text="Enter", width=6, height=0, command=ask_for_sheet1)
sheet_button1.pack()
sheet_button1.place(x=15, y=147)
sheet_button2 = Button(root, text="Enter", width=6, height=0, command=ask_for_sheet2)
sheet_button2.pack()
sheet_button2.place(x=430, y=147)
label1 = Label(root, text="Sheet 1 column letter: ", bg="light green")
label1.pack()
label1.place(x=10, y=250)
label2 = Label(root, text="Sheet 2 column letter: ", bg = "light green")
label2.pack()
label2.place(x=260, y=250)
def write_csv(col1, col2, worksheet1, worksheet2):
for (col, col_1) in zip(worksheet1.iter_cols(min_col = column_index_from_string(col1), max_col=column_index_from_string(col1)), worksheet2.iter_cols(min_col = column_index_from_string(col2), max_col=column_index_from_string(col2))):
for (cell, cell_1) in zip(col, col_1):
if cell.value != cell_1.value and cell.row == cell_1.row:
output_writer.writerow(['Sheet 1 value: ' + ' ' + str(cell.value) + ' ' + 'is not equal to ' + ' ' + 'Sheet 2 value: ' + ' ' + str(cell_1.value) + ' ' + 'on row ' + ' ' + str(cell.row)])
dButton = Button(root, text="Exit", width=8, height=1, command=destroy)
dButton.pack()
dButton.place(x=100, y=60)
mainloop()
workbook1 = openpyxl.load_workbook(str(wb1))
workbook2 = openpyxl.load_workbook(str(wb2))
global sheet1
sheet1 = e1.get("1.0", "end-1c")
global sheet2
sheet2 = e2.get("1.0", "end-1c")
worksheet1 = workbook1.get_sheet_by_name(str(sheet1))
worksheet2 = workbook2.get_sheet_by_name(str(sheet2))
col1 = column1_entry.get("1.0", "end-1c")
col2 = column2_entry.get("1.0", "end-1c")
write_csv(col1, col2, worksheet1, worksheet2)
However, when I run the follwing code, I enter the criteria required and end up with the following error: _tkinter.TclError: invalid command name ".71847552".
When I put mainloop() as the last line of the file, I get this error: self.fp = io.open(file, modeDict[mode])
FileNotFoundError: [Errno 2] No such file or directory: '' Can anyone rewrite my code so that it will successfully compile? Any help is great thank you
A: After you destroy the window, which means your code will proceed past mainloop you then attempt to reference widgets with the containing master root which have been destroyed and their associated methods get. This will raise an error if you attempt to do this after the window has been destroyed.
| |
doc_23538263
|
aws sesv2 put-account-details \
--production-access-enabled
--mail-type TRANSACTIONAL
--website-url https://loganairportcar.com
--use-case-description "(1)How do you plan to build or acquire your mailing list?
Ans:- We acquire the mailing list from a contact form, inquiry form, user registration form from https://www.loganairportcar.com/reservation and https://www.loganairportcar.com/contact . From the website end only, when user fill up the forms and submit the form to the website.
(2) How do you plan to handle bounces and complaints?
Ans:- For bounces and complaints we are going to use the AWS SNS.
(3)How can recipients opt out of receiving email from you?
Ans:- We will send the unsubscribe link at the bottom of email with the unsubscribe message explaining detail. After unsubscribe link click from the user end we will remove that email from the subscribed list.
(4)How did you choose the sending rate or sending quota that you specified in this request?
Ans:- As per our email service usages the sending rate or sending quota that the AWS provide will be enough to us at the moment."
--additional-contact-email-addresses [email protected]
--contact-language EN
At the final stage it gives me below error
An error occurred (ConflictException) when calling the PutAccountDetails operation: None
How to fix that
| |
doc_23538264
|
public class CategotiesEqualityComparer : IEqualityComparer<ac_Categories>
{
public bool Equals(ac_Categories x, ac_Categories y)
{
return x.ThumbnailAltText.Trim() == y.ThumbnailAltText.Trim();
}
public int GetHashCode(ac_Categories obj)
{
return obj.ThumbnailAltText.Trim().GetHashCode();
}
}
var catlist = _db.ac_Categories
.Where(c => c.VisibilityId == 0 && c.ThumbnailAltText != null
&& (!c.ThumbnailAltText.StartsWith("gifts/")
&& !c.ThumbnailAltText.StartsWith("email/")
&& !c.ThumbnailAltText.StartsWith("news/")
&& !c.ThumbnailAltText.StartsWith("promotions/")
&& !c.ThumbnailAltText.StartsWith("the-knowledge/")))
.Distinct(new CategotiesEqualityComparer()).ToList();
ERROR:LINQ to Entities does not recognize the method
'System.Linq.IQueryable1[WebMgr.ac_Categories]
Distinct[ac_Categories](System.Linq.IQueryable1[WebMgr.ac_Categories],
System.Collections.Generic.IEqualityComparer`1[WebMgr.ac_Categories])'
method, and this method cannot be translated into a store expression
NOTE:
I am using Database first approach and ac_Categories is created using that...
A: You can't pass an IEqualityComparer comparer into a call to an EF query or likely most IQueryable collections. IQueryable are expression trees, that expression tree gets converted into an underlying query (such as SQL with EF). As such it can't execute your code in SQL.
A normal Distinct() call will work just fine if you want to filter out duplicate identical records as it will perform a SQL distinct. If you it to apply your equality comparer you would have to pull the data into memory then apply your distinct.
| |
doc_23538265
|
How can I add the billing_first_name field to work correctly within my admin widget so it displays all values.
/**
* Add a widget to the dashboard.
*
*/
function wc_orders_dashboard_widgets() {
wp_add_dashboard_widget(
'wc_order_widget_id', // Widget slug.
'Cartlog Orders', // Title.
'wc_orders_dashboard_widget_function' // Display function.
);
}
add_action( 'wp_dashboard_setup', 'wc_orders_dashboard_widgets' );
/**
* Pulls the order information to the dashboard widget.
*/
function wc_orders_dashboard_widget_function() {
$args = array(
'post_type' => 'shop_order',
'post_status' => 'All', //Other options available choose one only: 'wc-pending', 'wc-processing', 'wc-on-hold', 'wc-cancelled', 'wc-refunded', 'wc-failed'
'posts_per_page' => 10 //Change this number to display how many orders you want to see
);
$orders = get_posts( $args );
if( count( $orders ) > 0 ) {
?>
<table width="100%">
<tr>
<th><?php _e( 'Order Id', 'woocommerce' ); ?></th>
<th><?php _e( 'Total', 'woocommerce' ); ?></th>
<th><?php _e( 'Billing Name', 'woocommerce' ); ?></th>
<th><?php _e( 'Status', 'woocommerce' ); ?></th>
</tr>
<?php
foreach ( $orders as $key => $value ) {
?>
<tr>
<td>
<?php
$order = new WC_Order( $value->ID );
// 1. Get the order ID
if ( $order ) {
echo '<a href="'. admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) .'" >' . $order->get_order_number() . '</a>';
?>
</td>
<td>
<?php
// 2. Get the order total
echo esc_html( wc_get_order_status_name( $order->get_total() ) );
}
?>
</td>
<td>
<?php
// 3. Get the billing name
echo esc_html(wc_get_order_status_name($order>get_billing_first_name() ) );
}
?>
</td>
<td>
<?php
// 4. Get the order status
echo esc_html( wc_get_order_status_name( $order->get_status() ) );
}
?>
</td>
</tr>
<?php
}
?></table>
<?php
}
A: You're closing the if statement after you've displayed the order total and then have closing braces duplicated for 3 and 4. You're also passing all of your display values through wc_get_order_status_name() which is only appropriate for the order status.
Getting the latest orders
Before fixing the issues highlighted above, it's worth starting with your method for retrieving the latest orders. You're using get_posts() which may work at the moment but isn't advisable. WooCommerce is moving to custom tables so any code that assumes orders are a post will break in the future. You're better off using the functionality that WooCommerce provides.
$orders = wc_get_orders([
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC',
]);
https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query
A nice benefit of this approach is that you get back an array of WC_Order objects as opposed to posts which then need to be converted.
Displaying orders
foreach ( $orders as $order ) { ?>
<tr>
<td>
<?php printf(
'<a href="%1$s">%2$s</a>',
$order->get_edit_order_url(),
$order->get_order_number()
); ?>
</td>
<td><?php echo $order->get_total(); ?></td>
<td><?php echo $order->get_billing_first_name(); ?></td>
<td><?php echo wc_get_order_status_name( $order->get_status() ); ?></td>
</tr>
<?php }
| |
doc_23538266
|
mdf = dataframe
pdp = mdf[mdf['smoker'] == Cases]
if stat == 'mean':
means = pdp.groupby('day').mean()
return round(means,round_off)
elif stat == 'median':
medians = pdp.groupby('day').median()
return round(medians,round_off)
elif stat == 'min':
mins = pdp.groupby('day').min()
return mins
elif stat == 'max':
maxs = pdp.groupby('day').max()
return maxs
else:
return None
import seaborn as sns
sns.set_theme(style="ticks", palette="icefire")
tips = sns.load_dataset("tips")
Mean_Yes = get_stats_array(tips, Method=None, Cases='Yes', stat='mean', round_off=1)['total_bill']
Mean_No = get_stats_array(tips, Method=None, Cases='No', stat='mean', round_off=1)['total_bill']
Mean_array_Thu = [Mean_Yes[0] , Mean_No[0]]
Mean_array_Fri = [Mean_Yes[1] , Mean_No[1]]
Mean_array_Sat = [Mean_Yes[2] , Mean_No[2]]
Mean_array_Sun = [Mean_Yes[3] , Mean_No[3]]
CASES = ['Yes','No']
qf1 = pd.DataFrame([Mean_array_Thu], columns=CASES).assign(day='Thur')
qf2 = pd.DataFrame([Mean_array_Fri], columns=CASES).assign(day='Fri')
qf3 = pd.DataFrame([Mean_array_Sat], columns=CASES).assign(day='Sat')
qf4 = pd.DataFrame([Mean_array_Sun], columns=CASES).assign(day='Sun')
pdf = pd.concat([qf1, qf2, qf3, qf4])
pdf = pd.melt(pdf, id_vars=['day'], var_name=['CASES'])
plt.figure(1, figsize = (25,10))
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", palette=["m", "g"], data=tips, showmeans=True)
sns.despine(offset=10, trim=True)
ax = sns.lineplot(x='day', y='value', data=pdf, style='CASES',ax=ax,color='black')
I was trying to plot a grouped box plot. I tried initially with an example available in seaborn. (Code attached) The data-format is as pandas dataFrame. First I plotted the box plot and then I tried to obtain the means of each group using groupby option but that somehow wasn't working. So I created another separate dataframe with the mean values and tried plotting those. I was able to get the separate line plots of the means of each group but the positioning was wrong. I have attached a figure of the resulting plot. I think there might be a better way to do this with groupby option but I am not sure how. But mainly I want the resulting line-plots of the means properly aligned with the means as well as the boxes. Can anyone help me with this? Please let me know if any more information has to be provided
Alignment issue with grouped-boxplot and line plot of means of each group as shown in the image below:
| |
doc_23538267
|
For example:
<?php include "quotes.php"; $name='tory'?>
I then want to use this variable name, $name='tory', in my quotes.php file. I'm unsure if I'm going about this the correct way because if I try to use the variable $name in my quotes.php file, it says that "name" is undefined.
Question has been answered. Needed to switch the statements. Thank you all!
A: Assign $name variable before including other files:
<?php
$name='tory';
include "quotes.php";
?>
A: Reverse it:
<?php $name='tory'; include "quotes.php"; ?>
A: You cannot use a variable before it was declared.
In your example, you're including quotes.php before the $name variable declaration, it will never work.
You can do
<?php $name='tory'; include "quotes.php"; ?>
Now, $name exists in "quotes.php"
A: What you're doing isn't necessarily the best way to go about it, but to solve your specific problem, simply define the variable before including the file. Then the variable will be globally scoped and available in the include file.
<?php
$name = 'tory';
include "quotes.php";
?>
A: You need to define $name first before including quotes.php.
A: You have to declare the variable $name before including the file.
<?php
$name = 'tory';
include 'quotes.php';
?>
This makes sense because the file you included will get parsed and executed and then move on with the rest.
A: The statements are executed in sequence. It is as though you had copy-and-pasted the contents of quotes.php at the point in your script where the include statement is found. So at the point where you execute quotes.php, the statement defining $name has not happened yet. Therefore to get the behaviour you want, you should reverse the order of the two statements.
| |
doc_23538268
|
import pyodbc
def show_odbc_sources():
sl = []
source = odbc.SQLDataSources(odbc.SQL_FETCH_FIRST)
while source:
dsn, driver = source
sl.append('%s [%s]' % (dsn, driver))
source = odbc.SQLDataSources(odbc.SQL_FETCH_NEXT)
sl.sort()
print('\n'.join(sl))
if __name__ == '__main__':
show_odbc_sources()
conn = pyodbc.connect(r'driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\username\\Desktop\\E CX DB.accdb;')
cursor = conn.cursor()
Errors That i get:
Excel Files [Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)]
MS Access Database [Microsoft Access Driver (*.mdb, *.accdb)]
Sample Amazon Redshift DSN [Amazon Redshift (x64)]
---------------------------------------------------------------------------
InterfaceError Traceback (most recent call last)
<ipython-input-12-816aa9101ab7> in <module>()
16 show_odbc_sources()
17
---> 18 conn = pyodbc.connect(r'driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\username\\Desktop\\E CX DB.accdb;')
19 cursor = conn.cursor()
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
A:
That is the driver i have which is 32 bit version.
It appears that you are running a 64-bit version of Python, so pyodbc cannot see the 32-bit version of the Access ODBC driver. You'll either need to switch to a 32-bit version of Python or switch to the 64-bit version of the Access ODBC driver.
| |
doc_23538269
|
AutoIndex(app, browse_root=os.path.curdir )
@app.route('/')
def index():
return render_template('index.html');
This serves my static content out of /css and /js nicely, but I can't get / to route to the index function. Instead, the AutoIndex routes / and displays all the files, including my application source code file. I tried setting add_url_rules to False which allowed index to route / but/css and /js are no longer served.
How can I have all subdirectories of my application be autoindexed but still allow the application to handle /?
| |
doc_23538270
|
When I know that they'll all be Cats, I can set the AutoBeanCodex to work easily. When I don't know what types they are, though... what should I do?
I could give all of my entities a type field, but then I'd have to parse each entity before passing it to the AutoBeanCodex, which borders on defeating the point. What other options do I have?
A: Just got to play with this the other day, and fought it for a few hours, trying @Category methods and others, until I found this: You can create a property of type Splittable, which represents the underlying transport type that has some encoding for booleans/Strings/Lists/Maps. In my case, I know some enveloping type that goes over the wire at design time, and based on some other property, some other field can be any number of other autobeans.
You don't even need to know the type of the other bean at compile time, you could get values out using Splittable's methods, but if using autobeans anyway, it is nice to define the data that is wrapped.
interface Envelope {
String getStatus();
String getDataType();
Splittable getData();
}
(Setters might be desired if you sending data as well as recieving - encoding a bean into a `Splittable to send it in an envelope is even easier than decoding it)
The JSON sent over the wire is decoded (probably using AutoBeanCodex) into the Envelope type, and after you've decided what type must be coming out of the getData() method, call something like this to get the nested object out
SpecificNestedBean bean = AutoBeanCodex.decode(factory,
SpecificNestedBean.class,
env.getData()).as();
The Envelope type and the nested types (in factory above) don't even need to be the same AutoBeanFactory type. This could allow you to abstract out the reading/writing of envelopes from the generic transport instance, and use a specific factory for each dataType string property to decode the data's model (and nested models).
| |
doc_23538271
|
string responseFromServer;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
responseFromServer = reader.ReadToEnd();
}
}
}
responseFromServer is a string type variable, contains this "key:value" data:
{"refresh_token":"69d2b7bq95b6sf5b64c55240ed563a52","expires_in":86400,"access_token":"0q761ee1897hd50u2r4fec80f333dd43","token_type":"bearer","x_mailru_vid":"13090076762971691053"}
This string I need to convert to this string array:
refresh_token = 69d2b7bq95b6sf5b64c55240ed563a52
expires_in = 86400
access_token = 0q761ee1897hd50u2r4fec80f333dd43
token_type = bearer
x_mailru_vid = 13090076762971691053
What is the easiest way to implement it?
Thank you in advance.
A: It is a json string. You can use any json serializer. I'll use Json.Net
var result = JsonConvert.DeserializeObject<Result>(json);
public class Result
{
public string refresh_token { get; set; }
public int expires_in { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string x_mailru_vid { get; set; }
}
You can deserialize to a dictionary too.
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Another alternative with built-in JavaScriptSerializer
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(json);
| |
doc_23538272
|
Lock interface:
public interface Lock {
public void requestCS(int pid);
public void releaseCS(int pid);
}
Peterson's algorithm:
public class PetersonAlgorithm implements Lock {
boolean wantCS[] = {false, false};
int turn = 1;
@Override
public void requestCS(int i) {
int j = 1 - i;
wantCS[i] = true;
turn = j;
while (wantCS[j] && turn == j) ;
}
@Override
public void releaseCS(int i) {
// TODO Auto-generated method stub
wantCS[i] = false;
}
}
The two classes should be fine, but when I test it on Eclipse with the code
import java.util.Random;
public class TestMutualExclusive extends Thread {
int myId;
Lock lock;
Random r = new Random();
public TestMutualExclusive(int id, Lock lock) {
myId = id;
this.lock = lock;
}
void nonCriticalSection() {
System.out.println(myId + " is not in CS");
Util.mySleep(r.nextInt(1000));
}
void CriticalSection() {
System.out.println(myId + " is in CS ****");
Util.mySleep(r.nextInt(1000));
}
public void run() {
while (true) {
lock.requestCS(myId);
CriticalSection();
lock.releaseCS(myId);
nonCriticalSection();
}
}
public static void main(String[] args) throws Exception {
int N = Integer.parseInt(args[0]);
TestMutualExclusive t[] = new TestMutualExclusive[N];
Lock lock = new PetersonAlgorithm();
for (int i = 0; i < N; i++) {
t[i] = new TestMutualExclusive(i, lock);
t[i].start();
}
}
}
The only thing came out is
0 is in CS ****
0 is not in CS
Instead of 0 and 1 alternatively entering the critical section. What is the problem?
UPD1: N is the number of threads I want to run
UPD2: Apparently if I add a mySleep function it works, but I still don't know why.
public class PetersonAlgorithm implements Lock {
boolean wantCS[] = {false, false};
int turn = 1;
@Override
public void requestCS(int i) {
int j = 1 - i;
wantCS[i] = true;
turn = j;
while (wantCS[j] && turn == j) Util.mySleep(100);
}
@Override
public void releaseCS(int i) {
// TODO Auto-generated method stub
wantCS[i] = false;
}
}
UPD3: mySleep is a function that takes in time as an argument to stall the thread.
UPD4: the problem was that turn variable is not volatile. After setting it to volatile, now it has two variables entering the critical section at once. How do I fix it?
| |
doc_23538273
|
I will try to describe best What I am struggling with for some hours.
after authentication, when user is being send from server to client, field req.session.passport is set, along with req.user. but when i do next request, no matter is it logout or for example /something/add these fields are undefined.
when authenticating, serializeUser is being called, but deserializeUser not and i dont think it should here, maybe im wrong. as far as I went into debugging the problem, req.login is being called too.
on the next requests it seems that passport isnt doing anything, and i'm out of ideas and anwsers from SO and google. i didnt try the custom callback.
req.session just before sending anwser to client looks like:
Session {
cookie:
{ path: '/',
_expires: 2017-01-11T02:31:49.235Z,
originalMaxAge: 14400000,
httpOnly: false,
secure: false } }
the code on the server side is:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
global.Models.User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
{
usernameField: 'login',
passwordField: 'password',
passReqToCallback: true
},
function(req, login, password, done) {
global.Models.User.logIn({login: login, password: password}, function(err, user){
if(err){
done(err);
}
else{
done(null, user);
}
});
}
));
var app = express();
var router = express.Router();
router.use(cookieParser());
router.use(bodyParser.urlencoded({extended: false}));
router.use(bodyParser.json());
router.use(session({
cookie : {
secure : false,
maxAge : (4 * 60 * 60 * 1000),
httpOnly: false
},
secret: this._config.session.secret,
resave: false,
saveUninitialized: true
}));
router.use(passport.initialize());
router.use(passport.session());
require('./Router')();
app.use(router);
session object here is the express-session. code under is the Router.js required above
var User = require('../Models/User');
var News = require('../Models/News');
var passport = global.Application.getInstanceOf("passport");
function setRoutes(){
router.use(function (req, res, next) {
var log = global.Application.getInstanceOf("logger");
var clientIP = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
log.log("info", req.method + " request from ip: " + clientIP);
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if('OPTIONS' == req.method){
res.sendStatus(200);
}
else{
next();
}
});
router.get('/ping', function(req, res){
res.send('ping');
});
router.get('/login/:login', (req, res) => {
Database.client.query(Database.queries.USER_LOGIN, {login: req.params.login}, {useArray: true},
(err, rows) => {
if(err){
res.send({error: "ERROR_DATABASE"});
}
else{
res.send(rows[0][0]);
}
});
});
router.post('/login', passport.authenticate('local', {session: true}),
function(req, res){
console.log(req.session);
req.session.save();
res.send(req.user);
}
);
router.post('/register', (req, res) => {
User.create(req.body, (err, result) => {
if(err){
res.send({error: "ERROR_DATABASE"});
}
res.send(result);
});
});
router.get('/logout', function(req, res){
console.log(req.session);
req.logout();
res.sendStatus(200);
});
router.post('/cms/article', isAuthenticated, (req, res) => {
res.send("BLA");
});
function isAuthenticated(req, res, next){
console.log(req.user);
console.log(req.session);
console.log(req.session.passport);
if(req.isAuthenticated()){
next();
}
else{
res.send("OK");
}
}
}
module.exports = setRoutes;
A: I have solved the problem.
Explanation:
Cookie was being sent by express to client, but it wasn't saved. For that, it needed change from using $.post to $.ajax with xhrFields option set to {withCredentials: true}.
Aside from that, the problem could also be that, that cookieParser probably need to know cookie secret too now.
| |
doc_23538274
|
Data Extraction API requests are rate limited by number of requests and data download volume per unit of time (hour, day, week, or month). If you exceed the limit, a 403 error occurs.
Someone could tell me more about this limit ? How many call per day/month/year ???
A: Just spoke to webtrends support. The limit is 600 requests per use per hour or 1 Gig per user per hour.
| |
doc_23538275
|
I tried navigating the each but the position of the element in the array.
Json array
A: #each takes an array to iterate over, so passing it media.thumbnails[1] won't work, as that is the second object in the array. Try passing it the array media.thumbnails
A: i hope to solve your problem, otherwise pass me the complete code
<div id="handlebarsDetail"> </div>
<script id="handleMarkup" type="text/x-handlebars-template">
{{#each media.thumbnails}}
<figure>
<img src="{{url}}" />
</figure>
{{/each}}
</script>
var sourceHandlebars = $("#handleMarkup").html();
var templateHandlebars = Handlebars.compile(sourceHandlebars);
$.getJSON("urlFileJson", function (data) {
var $htmlHandlebars = jQuery(templateHandlebars(data));
$("#handlebarsDetail").empty().append($htmlHandlebars);
});
| |
doc_23538276
|
I have that solved, but here's the challenge. The column content have to be scrollable to be on top of the bottom panel when scrolled to the end. Current solution I have is to add a spacer on the bottom of this column. This spacer have the calculated height of the bottom parent. And here's the issue - right now we have calculation done in onSizeChanged which basically results in additional frame needed for the spacer to have correct size.
We did not observe any negative impact of that performance or UX wise. The spacer height calculation never does anything that user can see, but I still want to solve that properly.
AFAIK this can be done using custom Layout, but that seems a little bit excessive for what I want to achieve. Is there another way to do this properly?
Current solution:
@Composable
fun FloatingPanelColumn(
modifier: Modifier = Modifier,
contentModifier: Modifier = Modifier,
contentHorizontalAlignment: Alignment.Horizontal = Alignment.Start,
bottomPanelContent: @Composable ColumnScope.() -> Unit,
content: @Composable ColumnScope.() -> Unit
) {
val scrollState = rememberScrollState()
var contentSize by remember {
mutableStateOf(1)
}
Box(modifier) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(state = scrollState)
.then(contentModifier),
horizontalAlignment = contentHorizontalAlignment,
) {
content()
val contentSizeInDp = with(LocalDensity.current) { contentSize.toDp() }
Spacer(modifier = Modifier.height(contentSizeInDp))
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.onSizeChanged {
contentSize = it.height
}
.wrapContentHeight()
.align(Alignment.BottomStart)
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color(0x00FAFCFF),
Color(0xFFF6F9FB),
)
)
),
content = bottomPanelContent
)
}
}
A: The best way to depend on an other view size during layout is using SubcomposeLayout:
SubcomposeLayout { constraints ->
// subcompose the view you need to measure first
val bottomPanel = subcompose("bottomPanel") {
Column(
// ...
)
}[0].measure(constraints)
// use calculated value in next views layout, like bottomPanel.height
val mainList = subcompose("mainList") {
LazyColumn(
contentPadding = PaddingValues(bottom = bottomPanel.height.toDp())
) {
// ...
}
}[0].measure(constraints)
layout(mainList.width, mainList.height) {
mainList.place(0, 0)
bottomPanel.place(
(mainList.width - bottomPanel.width) / 2,
mainList.height - bottomPanel.height
)
}
}
| |
doc_23538277
|
Conversion to non-scalar type requested
Can anyone help me? I am posting the whole code in the following:-
struct graph{
int v;
int e;
struct graph **admat;
};
void main()
{
int x,i,y,z=1,n;
struct graph *G=(struct graph **)malloc(sizeof(struct graph));
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=(struct graph **)malloc(G->v * sizeof(struct graph *));
for(i=0;i<G->v;i++)
{
G[i]=(struct graph)malloc(G->v * sizeof(int));//here is the main error
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
G[x][y]=z++;
}
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
printf(" %d ",G[x][y]);
}
printf("\n");
}
}
A: This piece of code is the problem :
struct graph *G=(struct graph **)malloc(sizeof(struct graph));
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=(struct graph **)malloc(G->v * sizeof(struct graph *));
for(i=0;i<G->v;i++)
{
G->admat[i]=(struct graph)malloc(G->v * sizeof(int));//here is the main error
}
You should change it to :
struct graph *G = malloc(sizeof(struct graph));
if (G == null)
printf("Error allocating memory");
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=malloc(G->v * sizeof(struct graph *)); // I guess you mean G->admat=malloc(sizeof(struct graph *));
if (G->admat == null)
printf("Error allocating memory");
for(i = 0; i<G->v; i++)
{
G[i] = malloc(G->v * sizeof(int));
if (G[i] == null)
printf("Error allocating memory");
}
should be removed, as you are trying to allocate ints for G, which is a double pointer to struct graph. It does not make any sense.
Also read this link on why you should not cast the result of malloc.
A: Assuming that admat contains 2D matrix data,
here is the code. A new variable z is introduced to store the value z.
#include <stdio.h>
#include <stdlib.h>
struct graph{
int v;
int e;
int z;
struct graph **admat;
};
void main()
{
int x,i,y,z=1,n;
struct graph *G= malloc(sizeof(struct graph));
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=malloc(G->v * sizeof(struct graph *));
for(i=0;i<G->v;i++)
{
G->admat[i]=malloc(G->v * sizeof(struct graph));//here is the main error
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
G->admat[x][y].z=z++;
}
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
printf(" %d ",G->admat[x][y].z);
}
printf("\n");
}
}
| |
doc_23538278
|
In instance, for my SIM card, the USSD will Seem like that '*858*2*phonenumber*3#'
This is my android Code..
String ussd = "*858*000*1" + Uri.encode("#");
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode(ussd))));
I have the permission of uses-permission android:name="android.permission.CALL_PHONE" in the manifest.
Logcat:
10-13 11:43:16.541 16048-16048/com.example.ahmedsharaf.testingthessid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ahmedsharaf.testingthessid, PID: 16048
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3848)
| |
doc_23538279
|
model.fit(trainFeatures, trainLabels)
The issue is that my trainFeatures size is (127, 9, 6, 1), and my trainLabels size is (127,2).
When I returned back to the documentation, especially for fit(X, y, sample_weight=None), it mentioned that:
X : {array-like, sparse matrix}, shape (n_samples, n_features)
y : array-like, shape (n_samples,)
What should I do in order to make my data format suitable to fit?
I tried extracting specific part from the size, like saying for instance:
trainFeatures = (trainFeatures[0],trainFeatures[1]*trainFeatures[2])
thinking that would solve the issue according to the documentation, but that turned into some mess.
Thanks for your kind support.
A: Assuming you are not working with spatially structured data (e.g. images, sounds, time series, etc.), then the order and shape of the features doesn't matter to the model.
If that is the case, then a simple reshape should do the trick:
model.fit(trainFeatures.reshape(127, -1), trainLabels)
In any case, I'd suggest you to drop the fourth dimension with trainFeatures.squeeze().
If you feel that the 9 by 6 structure of the features is important, then you could try using convolutional neural networks (if each sample is, semantically, a grid), or recurrent neural networks (if each sample is a sequence of 9 steps of a 6-dimensional signal).
Cheers
| |
doc_23538280
|
am i missing a setting again?
A: I generally cheat and do it through SQL as I haven't found another method that works consistently. If you know SQL, you just need update the ModuleOrder column in the TabModules table... I think it's best that I don't provide the actual SQL because I don't want people that don't really know SQL running it with incorrect values.
| |
doc_23538281
|
I would like to execute unit-tests with eclipse-plugin packaging, but would like to use the mockito library in addition to JUnit. I have a pomless build and would like to keep it that way. I do not want to add non-PDE files to the build, unless this is unavoidable.
Question: What is the idiomatic/intended/correct way to add this dependency, or any other test-time dependencies?
Note: I am aware of the use of fragments for unit testing. This is not what I am after. I actually want to use the new mechanism, if possible, or hear that this is currently impossible.
For my initial purposes, and given these are intended to be Unit-tests, running non-OSGI would be ok. If there is a means for OSGI as well, that would be great, but I cannot imagine where the platform configuration could be stored.
A: See this tycho discussion, short summary:
*
*you can add Mockito as an optional bundle dependency
*you can add a M2_REPO Classpath variable reference
| |
doc_23538282
|
final String projectUrl = "http://someurl.com"
@BeforeTest
public void setUp() {
Configuration.remote = "http://some.ip.address.129:4444/hub"
}
@Test
public void smallOrderTest() throws FileNotFoundException {
try {
s = new Scanner(new BufferedReader(new FileReader(f.getAbsolutePath())));
while (s.hasNext()) {
open(projectUrl+s.next())
}
} finally {
if (s != null) {
s.close();
}
}
}
What's my question.
When I remove configuration string, I receive nice test on my local environment.
But whet that string is here, test doesn't runs ever, and prints this:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
Need full stack trace?
Question is - what I'm doing wrong? How to solve this? I need to run remote tests, check links string by string from the file, and not on my local environment.
Local OS Linux Mint 17, Selenide 3.4, Selenium 2.53.0, run from Idea,
Remote VM Win7, with Selenium standalone server hub and one node.
Driver standard Firefox.
Fails at "open" command, if I set remote server in Configuration.
java.lang.ClassCastException: java.lang.String cannot be cast to
java.util.Map
at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:251)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:158)
at
com.codeborne.selenide.webdriver.WebDriverFactory.createRemoteDriver(WebDriverFactory.java:61)
at
com.codeborne.selenide.webdriver.WebDriverFactory.createWebDriver(WebDriverFactory.java:36)
at
com.codeborne.selenide.impl.WebDriverThreadLocalContainer.createDriver(WebDriverThreadLocalContainer.java:213)
at
com.codeborne.selenide.impl.WebDriverThreadLocalContainer.getAndCheckWebDriver(WebDriverThreadLocalContainer.java:113)
at
com.codeborne.selenide.WebDriverRunner.getAndCheckWebDriver(WebDriverRunner.java:118)
at
com.codeborne.selenide.impl.Navigator.navigateToAbsoluteUrl(Navigator.java:44)
at com.codeborne.selenide.impl.Navigator.open(Navigator.java:23) at
com.codeborne.selenide.Selenide.open(Selenide.java:51) at
SmallOrder.smallOrderTest(SmallOrder.java:44) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:643) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782) at
org.testng.TestRunner.run(TestRunner.java:632) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:366) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:319) at
org.testng.SuiteRunner.run(SuiteRunner.java:268) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1244) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1169) at
org.testng.TestNG.run(TestNG.java:1064) at
org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:74) at
org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:121) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
A: Initializing RemoteWebDriver requires setting DesiredCapabilities (as can be seen in WebDriver's source code).
I am not a Selenide user, but it seems with version 3.4 this is a bit painful, so you can try upgrading to the latest version and use Configuration.browserCapabilities
Or, if you have no such option, see an example here: https://github.com/codeborne/selenide/issues/444
| |
doc_23538283
|
#WANTS TO MODIFY REFERENCE_OUTPUT_* HERE IN BELOW LINES
set output "REFERENCE_OUTPUT_fun1.png"
set output "REFERENCE_OUTPUT_fun2.png"
set output "REFERENCE_OUTPUT_fun3.png"
set output "REFERENCE_OUTPUT_fun4.png"
-
-
-
#DO NOT WANTS TO MODIFY REFERENCE_OUTPUT_* FOR BELOW LINE
plot '/project/subfolder1/REFERENCE_OUTPUT_fun1.txt' u 1:2 w l axes x1y1 ti "Ref output" lc rgb "red"
and I do have minimum 800+ *.gpl files in dump folder .
I want to dump my generated output png files in separate images folder .
So,
I am trying below command to do so :
sed -i 's/set output "REFERENCE_OUTPUT_*/set output "./images/REFERENCE_OUTPUT_*/g' {} *.gpl
But getting Below Error
Error:
sed: -e expression #1, char 25: unknown option to `s'
Expected Output:
In all *.gpl files this above set output line changes from :
set output "REFERENCE_OUTPUT_fun1.png"
to
set output "./images/REFERENCE_OUTPUT_fun1.png"
UPDATE:
*.gpl file also has :
plot '/project/subfolder1/REFERENCE_OUTPUT_fun1.txt' u 1:2 w l axes x1y1 ti "Ref output" lc rgb "red"
So in above line REFERENCE_OUTPUT_fun1.txt also has name REFERENCE_OUTPUT_fun1 which I do not want to change . So that's the reason I am using set output "REFERENCE_OUTPUT_* which will just modify this set output . . line (in theory)
A: You don't need to match entire string - just replace prefixes
sed -E -i -u 's/(REFERENCE[a-zA-Z_0-9]+\.png)/\.\/images\/\1/g' *.gpl
| |
doc_23538284
|
This is how I am doing it :
var latestServerData = [[String:AnyObject]]() // Global variable
in someFunction{
print(latestServerData)
var dic1 = [String:AnyObject]()
dic1 =latestServerData[4]
dic1["isVisited"] = true as AnyObject
print(dic1)
latestServerData[4] = dic1
print(latestServerData)
}
In print(dic1) I have correct data but its not getting replaced in latestServerData array. What I am doing wrong and what is the correct way. Any explanation with correct approach is appreciated.
Thanks!
A: For me your code is working fine
var latestServerData = [
["name": "Amit", "age": "27", "rollno": 12,"isVisited":true],
["name": "Ananad", "age": "26", "rollno": 10,"isVisited":true],
["name": "Kashyap", "age": "25", "rollno": 11,"isVisited":true],
["name": "Raj", "age": "25", "rollno": 07,"isVisited":true],
["name": "Akshya", "age": "28", "rollno": 13,"isVisited":true]
] as [[String:AnyObject]]
Here it is working for me
var dic1 = [String:AnyObject]()
dic1 = latestServerData[4]
dic1["isVisited"] = false as AnyObject
latestServerData[4] = dic1
It is also working solution
latestServerData[0]["isVisited"] = false as AnyObject
print(latestServerData)
["name": Amit, "age": 27, "rollno": 12, "isVisited": 0], ["name": Ananad, "age": 26, "rollno": 10, "isVisited": 1], ["name": Kashyap, "age": 25, "rollno": 11, "isVisited": 1], ["name": Raj, "age": 25, "rollno": 7, "isVisited": 1], ["name": Akshya, "age": 28, "rollno": 13, "isVisited": 0]]
observe the First and Last object in array . isVisited": 0
| |
doc_23538285
|
Sadly for me, everything is shown on Visual Studio, but VS doesn't support databases on MacOS. I am using Rider - was recommended to me by MacBook user - lecturer. Unfortunately he's not available for this part of course. I am having issue with Rider and MySQL. It doesn't work. Can somebody help me with the setup? Tried to google things out, but it didn't help me.
Sending some screenshots.
btw. if I use SQLlite it works perfectly fine. Thank you so much for your help!
Tried to download Docker - don't know if I was supposed to, and some setups. But it didn't help.
edit. Well on one side I'm glad (that I'm not alone who doesn't know it) but sad, that noone can help me...
| |
doc_23538286
|
I need to make a template for the terms of a certain vocabulary. I created a sub-theme and am trying to use theme_preprocess_page() ( theme_preprocess_taxonomy_term() is somehow never called ).
template.php
function aura_sub2_preprocess_page(&$variables) {
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
$term = taxonomy_term_load(arg(2));
drupal_set_message( 'page__vocabulary__' . $term->vocabulary_machine_name );
$variables['theme_hook_suggestions'][0] = 'page__vocabulary__' . $term->vocabulary_machine_name;
}
}
As you can see I even overwrite the first suggestion for testing purposes but it changes nothing. The page loads as if nothing ever happened.
When I open "mydomain.com/?q=en/myvocabulary/someterm" I get the status message "page__vocabulary__myvocabulary". So far so good but the template suggestions is seemingly ignored.
The template resides in the "theme" directory of that sub-theme. I tried every possible combination of "--" and "__" to no avail. The template only contains this, is that a problem?:
theme/page--vocabulary--myvocabulary.tpl.php
<h1>MYVOCAB TEST</h1>
Cache has been cleared each time, no change. :c
Any ideas?
A: I think it may be because you are adding the suggestion to the start of the array rather than the end.
replace:
$variables['theme_hook_suggestions'][0] = 'page__vocabulary__' . $term->vocabulary_machine_name;
with:
$variables['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
| |
doc_23538287
|
The problem is when going back from the view or putting the application in background. The location services icon does not disappear. Actually i have to delete the application to make it disappear. Even if i manually force close the application it is still there and if i go into settings it is still active in the list of applications using location services.
I've added the relevant code below, what am i missing here?? Thanks in advance!
*.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ***viewController: UIViewController {
IBOutlet MKMapView *theMapView;
}
@property (nonatomic, retain) MKMapView *theMapView;
@end
*.m
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
theMapView.showsUserLocation = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
theMapView.showsUserLocation = NO;
}
- (void)dealloc {
[super dealloc];
[theMapView release];
}
A: I'm just guessing , this might not solve it but try adding self in both statement with self
i.e
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.theMapView.showsUserLocation = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.theMapView.showsUserLocation = NO;
}
A: You can register for notifications when the app goes into and comes out of background and save and restore the user location state respectively:
class MyVCWithAMap: UIViewController {
...
// Track the state of the map user location property when going to background
var trackUserLocation = false
...
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
...
override func viewDidLoad() {
super.viewDidLoad()
...
// Register for notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(appEnteredForeground), name:UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(appEnteredBackground), name:UIApplicationDidEnterBackgroundNotification, object: nil)
}
func appEnteredBackground() {
// Capture map user location state
viewModel.trackUserLocation = mapView.showsUserLocation
mapView.showsUserLocation = false
}
func appEnteredForeground() {
// Restore pre-snooze state
mapView.showsUserLocation = viewModel.trackUserLocation
}
}
| |
doc_23538288
|
Service Injection
The @inject directive may be used to retrieve a service from the Laravel service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class / interface name of the service you wish to resolve:
@inject('metrics', 'App\Services\MetricsService')
<div>
Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>
My code:
1、Service:
NameAndRole.php
class NameAndRole
{
public function nameAndRole() {
$user = \Auth::user();
$username= $user->name;
$role =$user->getRoles();
$slug=$role[0]['slug'];
return compact('username','slug');
}
}
2、view:
sidebar.blade.php
@inject('nameAndRole','App\Services\NameAndRole')
<div>
<h4 >username:{{$username}}</h4>
<h4>slug:{{$slug}}</h4>
</div>
error:
Undefined variable: username (View: D:\wnmp\www\laravel-book\resources\views\partials\sidebar.blade.php) (View: D:\wnmp\www\laravel-book\resources\views\partials\sidebar.blade.php)
A: I got the answer on laracasts.com, I think this is what I want:
class NameAndRole
{
public $username;
public $slug;
public function __construct()
{
$user = \Auth::user();
$this->username = $user->name;
$role = $user->getRoles();
$this->slug = $role[0]['slug'];
}
}
And in the Blade view:
@inject('details', 'App\Services\NameAndRole')
{{ $details->username }}
{{ $details->slug }}
A: You should get variable from method
@inject('nameAndRole','App\Services\NameAndRole')
<div>
<h4 >username:{{$nameAndRole->nameAndRole()['username']}}</h4>
<h4>slug:{{$nameAndRole->nameAndRole()['slug']}}}</h4>
</div>
| |
doc_23538289
|
soup = BeautifulSoup(response)
element_dates = ".ipl-zebra-list ipl-zebra-list--fixed-first release-dates-table-test-only" # css selector (date release table)
select_datesTag = soup.select(element_dates)
result = [i.text for i in select_datesTag]
print(result)
>>>[]
Edit:
Thank you all for trying to help me. As the previous printed result showed as blank, indicating that the information I tried to extract was unsuccessful.
The reason caused that was because of the false label I picked for the "element_dates" css selector, that instead of the ".ipl-..." but actually is ".release-date-item__date".
This is the link of the website I was working on and provided with the fixed line of codes:
import requests
from bs4 import BeautifulSoup
target_url = "https://www.imdb.com/title/tt4154796/releaseinfo"
target_params = {"ref_": "tt_ov_inf"}
response = requests.get(target_url, params = target_params)
response = response.text
soup = BeautifulSoup(response)
element_dates = ".release-date-item__date"
print(element_dates) # successfully printed all the data with element_dates variable.
| |
doc_23538290
|
function insert(AddressSet storage set_, uint256 index_, address valueToInsert_ ) internal returns ( bool ) {
return _insert( set_._inner, index_, bytes32(bytes20(, uint256(valueToInsert_)))); //error is in this line
}
A: If you want to compile your code, you should create a struct data type that only contains a uint.
https://docs.soliditylang.org/en/v0.4.24/frequently-asked-questions.html
| |
doc_23538291
|
What I am looking for is:
I have a Google Form that is linked to a Google Spreadsheet. So every answer of the google form goes to that spreadsheet. These answers are used in a google apps script to create a google doc file (based on the answers of the form).
Now in that Google Form, there are some Yes/No questions. When they choose ‘Yes’ on the FIRST question, the idea is that the google apps script takes a random cell of the FIRST column of a (separate) ‘answer’ sheet.
When they choose ‘Yes’ on the SECOND question, the idea is that the google apps script takes a random cell of the SECOND column of the ‘answer’ sheet. And so on.
When they choose ‘No’ on a question, nothing needs to happen.
Later on, these random chosen answers/cells also needs to be placed in the google sheet. (like the Name and Email)
I’ll show what I have for now:
function autoFillGoogleDocFromForm(e) {
var Timestamp = e.values[0];
var Name = e.values[1];
var Email1 = e.values[2];
var OpenQuestion = e.values[3];
var YesNoQuestion1 = e.values[4];
var YesNoQuestion2 = e.values[5];
var YesNoQuestion3 = e.values[6];
var TemplateResponseFolder = DriveApp.getFolderById("Unique-folder-ID");
var copy = TemplateFile.makeCopy(Name, TemplateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
// replace the value between {{xyz}} by the variable in the google doc.
body.replaceText("{{Name}}", Name);
body.replaceText("{{AchterNaam}}", LastName);
body.replaceText("{{email1}}", Email1);
body.replaceText("{{OpenQuestion}}", OpenQuestion);
body.replaceText("{{YesNoQuestion1}}", YesNoQuestion1);
body.replaceText("{{YesNoQuestion2}}", YesNoQuestion2);
body.replaceText("{{YesNoQuestion3}}", YesNoQuestion3);
doc.saveAndClose();
}
// the script above works fine.
But I really have no idea how to make the ‘random lookup function’ work and store that value as a variable to use it in a google doc.
I’ve been trying with:
function selectRandomCell(searchColumn,resultCellRow,resultCellColumn) {
var ss = SpreadsheetApp.openById("Unique-ID-of-the-answer-sheet");
var range = ss.getSheetByName("Sheet1").getRange("A1:A").getValues();
var values = [];
for (var i = 0; i < range.length; i++) {
if (range[i][0] == "") {
continue;
}
else {
values.push(range[i][0]);
}
}
return values[Math.floor(Math.random() * values.length)]);
}
Please help me. (And sorry for my English)
A: Solution:
function autoFillGoogleDocFromForm(e) {
var Timestamp = e.values[0];
var Name = e.values[1];
var Email1 = e.values[2];
var OpenQuestion = e.values[3];
var YesNoQuestion1 = (e.values[4] === `Yes`) ? selectRandomCell(1) : `No`;
var YesNoQuestion2 = (e.values[5] === `Yes`) ? selectRandomCell(2) : `No`;
var YesNoQuestion3 = (e.values[6] === `Yes`) ? selectRandomCell(3) : `No`;
var TemplateResponseFolder = DriveApp.getFolderById("Unique-folder-ID");
var copy = TemplateFile.makeCopy(Name, TemplateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
// replace the value between {{xyz}} by the variable in the google doc.
body.replaceText("{{Name}}", Name);
body.replaceText("{{AchterNaam}}", LastName);
body.replaceText("{{email1}}", Email1);
body.replaceText("{{OpenQuestion}}", OpenQuestion);
body.replaceText("{{YesNoQuestion1}}", YesNoQuestion1);
body.replaceText("{{YesNoQuestion2}}", YesNoQuestion2);
body.replaceText("{{YesNoQuestion3}}", YesNoQuestion3);
doc.saveAndClose();
}
function selectRandomCell(targetColumn) {
const answerSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(`NAME_OF_YOUR_ANSWER_SHEET`);
const values = answerSheet.getRange(2, targetColumn, answerSheet.getLastRow()-1)
.getDisplayValues()
.flat()
.filter(String);
return values[Math.floor(Math.random() * values.length)];
}
*
*The first change is determining what the Yes/No responses are.
We accomplish this as (e.values[4] === 'Yes') ? selectRandomCell(1) : 'No' which translates to (is this value 'Yes'?) If so, get a random cell from column 1. If not, leave it as 'No'.
*
*The second change is simplifying the selectRandomCell function.
Based on which column number you enter, the function will take all values of that column and select one at random, and return it back for us. If this function is 'called' in our YesNoQuestion variable, the result of this function becomes the value of that variable.
What You Need To Do:
*
*Create or update the sheet that you would like the 'Yes' answers to be selected from. The name of this sheet should be in this Spreadsheet and the name of the sheet must replace NAME_OF_YOUR_ANSWER_SHEET in the selectRandomCell() function.
*If you are not going to use Columns A, B, C (1, 2, 3), update the numbers being 'passed' to in the selectRandomCell() function of the YesNoQuestion variables to match the corresponding column(s). Please also note, the selectRandomCell function is also expecting the first row to be selectable values.
If you get any errors, or need further explanation, just let me know!
| |
doc_23538292
|
This happens with all reports which has russian symbols . What can i do to fix this problem ?
A: Okay , i got the solution . You need to replace your resource-id to eng symbols. But resource-id READ ONLY. You can connect to your jasper database and write this select:
select * from jiresource
you need "name" column. It's varchar(200) by default, but you can increase it as much as you wish. Then you need to find your report name and change it with english symbols. update table and enjoy .
Also if you dont wanna use database, you can create new JRMX file with right name/resource id , but its even more labor intensive .
| |
doc_23538293
|
I want to fetch this date (in my C# application) from EventData but I don't know how time is encoded in bytes array.
| |
doc_23538294
|
I am using Tableau for visualisation. Data in my DataBase are structured by unique keys (+1k rows). I need to filtered value from rows by 2 and more columns (2columns+_filter). And this filtered data must be react to other Filters ("category") on My_Dashboard.
What I used:
Combination from Parameter and Calculation Field.
Parameter - includes data from 2 and more columns (I added it manualy).
Calculation Field - based on Contains(Column1, Parameter) OR... to the last column.
But it doesnot work, because Parameter included data what could be excluded by Filters on My_Dashboard.
Is it possible make a "dynamic filter" what will be select data (rows what inludes "value_1" from range column_1-column_3 after applying Filter - "category1" only.
For example - Input:
rows
column_1
column_2
column_3
column_4
row_key_1
value_1
value_5
category_1
row_key_2
value5
value_1
category_2
row_key_3
value_5
category_1
Output:
rows
column_1
column_4
row_key_1
value_1
category_1
Mayth be it possible with SQL addon/plugin, or something other.
Thanks for your help.
A: I understood how can realise what I want. If you have the same task, what you need:
*
*add two DataBase (or sheets from excel, etc.) and connect them with unique key "first_db_key = second_db_key";
*first DataBase sctuctured by horizontal, 1 row with unique key and a lot of columns with value;
*second DataBase sctuctured by our target column (included all possible values waht we need) and ofcourse rows with "unique key" from "first DataBase" could be repeated (2 or more).
*on you Sheet need to add filter based on "target column" from "second DataBase", after that, add filter to the "Context" and choose "All using this data source" option on "Apply to Worksheets" in context menu (rigth button click on the filter)
*on you Dashboard select to show filter what you added before, and in filter menu choose "All Values in Context" option.
Finaly you are get result what you want.
| |
doc_23538295
|
Does anyone have an idea?
A: It really depends on the widget (Entry, Text, Listbox,...) you are placing on a certain row and column.
In a first part, you define the properties of the object, for example:
list = Listbox(root, borderwidth=0, background='white')
And then you tell tkinter where you want him to place the listbox:
list.grid(row=0, column=1)
Is it clear ?
Please tell me which widget you want to put in your grid, it would be easier to help you!
A: with a bit of digging I found an answer, not the perfect solution, but doesn't matter:
You need to edit the color of the model itself with the command:
setColorAt()
The setcellColor() command still doesn't work.
Have fun and maybe someone can actually make sense of the command: documentation is on this site tkintertable documentation
| |
doc_23538296
|
This image loaded from local assets folder in flutter
A: You can use package https://pub.dev/packages/wallpaper_manager
You can set wallpaper in Home screen or Lock screen
wall paper can from a File or Asset
code snippet
Future<void> setWallpaperFromAsset() async {
setState(() {
_wallpaperAsset = "Loading";
});
String result;
String assetPath = "assets/tmp1.jpg";
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperAsset = result;
});
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:wallpaper_manager/wallpaper_manager.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _wallpaperFile = 'Unknown';
String _wallpaperAsset = 'Unknown';
@override
void initState() {
super.initState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await WallpaperManager.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromFile() async {
setState(() {
_wallpaperFile = "Loading";
});
String result;
var file = await DefaultCacheManager().getSingleFile(
'https://images.unsplash.com/photo-1542435503-956c469947f6');
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromFile(
file.path, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperFile = result;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromAsset() async {
setState(() {
_wallpaperAsset = "Loading";
});
String result;
String assetPath = "assets/tmp1.jpg";
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperAsset = result;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text("Platform Version"),
onPressed: initPlatformState,
),
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text("Set wallpaper from file"),
onPressed: setWallpaperFromFile,
),
Center(
child: Text('Wallpaper status: $_wallpaperFile\n'),
),
RaisedButton(
child: Text("Set wallpaper from asset"),
onPressed: setWallpaperFromAsset,
),
Center(
child: Text('Wallpaper status: $_wallpaperAsset\n'),
),
],
)),
);
}
}
| |
doc_23538297
|
A: To answer your questions:
*
*There's no black and white answer to this. To try my best to explain, think of UITableView as sort of like a visual data array. In fact, most people (myself included) use a source data object like an NSArray or an NSDictionary to provide the display data for a UITableView. All the memory limitations that would apply to these objects (arrays and dictionaries) apply to your UITableView, assuming your UITableView is set up properly and you're using the recommended techniques for reusing cells. What this boils down to is: Is it possible to have a very large UITableView? - Yes. How long though, this I don't know. I've created UITableViews with complex subclassed cells and 200 rows and they worked fine. It depends on how you set up the table and the data source you're using. Bear in mind again that the limitation is due to the data source. Have an extremely large array and eventually your device will throw a memory warning. As a best practice, use pagination. There are tonnes of tutorials online to enable paging on UITableViews. Lazy load your images (if any) if they are being downloaded.
*Yes you can. You can do lots of amazing things if you're creative enough while subclassing UITableViewCells. Otherwise, you can use the standard UITableViewCell as well. There are two labels on there: The textLabel and the detailTextLabel. Use these two to display the data you want.
*Your UITableViewDelegate has a didSelectRowAtIndexPath method which you can implement. As long as your view controller housing the UITableView is set to be it's delegate, it will respond to didSelectRowAtIndexPath.
*Just empty the array you're using as a data source (bear in mind that your numberOfRowsInSection data source method MUST use the array count) and call reloadData on the UITableView
EDIT: The question got edited, so only point 1 from the above 4 points applies to the question :) The others are nice to know though
A: Nothing table-specific, but yes, you will run out.
The most important thing is probably to use dequeueReusableCellWithIdentifier: in your tableView:cellForRowAtIndexPath: delegate method. This basically cuts down memory usage to the number of visible cells (plus one being scrolled into view).
| |
doc_23538298
|
#include<bits/stdc++.h>
using namespace std;
class Bankaccount
{
public:
int accnumber,accbalance;
int display()
{
cout<<"Account number is: "<<accnumber;
cout<<"\nAccount balance is: "<<accbalance;
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
cout<<"Account details of A\n\n"<<a.display()<<endl;
cout<<"\nAccount details of B\n\n"<<b.display();
return 0;
}
A: The function display() should return void in this case. Your version has in its signature that it returns int, but then you don't return anything. This leads to undefined behavior.
Also it is bad practice to use using namespace std and #include<bits/stdc++.h>.
Read up here Why is "using namespace std;" considered bad practice?
And here How does #include <bits/stdc++.h> work in C++?
#include <iostream>
class Bankaccount
{
public:
int accnumber, accbalance;
void display()
{
std::cout << "Account number is: " << accnumber << "\n";
std::cout << "Account balance is: " << accbalance << "\n";
}
};
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
std::cout<<"Account details of A\n\n";
a.display(); // this is how to use display
std::cout<<"\nAccount details of B\n\n";
b.display();
return 0;
}
A: You are inserting to std::cout, among others, result returned from function display
which should be int, but, considering that your function has no return statement everything is possible, basically you are sending undefined value to ostream cout, and that is what garbage is by definition.
A: Your int display() function doesn't return an int so you'll have undefined behaviour after that function has been called. If it had returned an int, that number had been printed, but I suspect that's not what you wanted.
The garbage you see is an int picked from the stack (because display() was supposed to put an int there). It was put the for a reason by some other function, but now it's gone, so anything can happen. To avoid this, you could declare your function void display() - but then you wouldn't be able to stream it, which is what it looks like you want to do.
If you want to be able to stream your objects, you need to define streaming operators to do the job. I've replaced your display() function with an out stream operator (operator<<) here:
#include <iostream>
//#include<bits/stdc++.h> // non-portable, don't use it
// using namespace std; // brings in too much in the namespace
using std::cout; // prefer this or just write std::cout everywhere
class Bankaccount {
public:
int accnumber, accbalance;
friend std::ostream& operator<<(std::ostream& os, const Bankaccount& ba) {
return os << "Account number is : " << ba.accnumber
<< "\nAccount balance is: " << ba.accbalance << "\n";
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
// std::endl is approx. the same as "\n" + std::flush. You don't need flushing.
cout << "Account details of A\n\n" << a << "\n";
cout << "\nAccount details of B\n\n" << b << "\n";
}
A: Most probably this is what you wanted to achieve:
https://wandbox.org/permlink/bpPth9WutHaiU5jQ
#include <bits/stdc++.h>
using namespace std;
class Bankaccount {
public:
int accnumber, accbalance;
std::ostream& display(std::ostream& out) const
{
out << "Account number is: " << accnumber;
return out << "\nAccount balance is: " << accbalance;
}
};
std::ostream& operator<<(std::ostream& out, const Bankaccount& acc)
{
return acc.display(out);
}
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
cout << "Account details of A\n" << a << endl;
cout << "\nAccount details of B\n" << b << endl;
return 0;
}
| |
doc_23538299
|
I am using Jetpack Infinite Scroll. The scroll is working fine but its the posts that are somewhat broken. See Image. My setting in WP Reading is 10 posts per page and I even added 'posts_per_page' => 10, in Jetpack functions.
Please help.. I can't figure out how to fix this.
Thank you.
A: This is because your columns are different heights which is breaking the floats. One solution would be to set all the columns of the divs to the same height. Another one would be to use a jquery plugin called Masonry. Personally I would try to make all the columns equal height, as it would look tidier!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.