id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_2800
|
To be a bit more clear if someone selects lets say 07/03/2015 from the arrival calendar form field, then I want the next departure field to have 07/05/2015 already in there for them. Hope that makes sense and
Thank you for any help on this.
Sure here is the code: <div class="col-md-4">
<label>Arrival Date *</label>
<input type="date" value="" maxlength="10" class="form-control" name="arrival" id="arrival" required>
</div>
<div class="col-md-4">
<label>Departure Date *</label>
<input type="date" value="" maxlength="10" class="form-control" name="depart" id="depart" required>
</div>
A: You need to parse the value of the date input field into a date object then add two days to that date object.
var departure = document.getElementById('departure').value;
var arrivalTime = Date.parse(departure) + (1000 * 60 * 60 * 24 * 2);
var arrivalDate = new Date(arrivalTime);
// set the value on the input
document.getElementById('arrival').value = arrivalDate.toString('yyyy-MM-dd');
You'll need to get the date into that format or HTML5 will not work. This thread will guide you in the right direction (e.g. useful libraries)
How to format a JavaScript date
A: You can get the current date and just add two day's worth of milliseconds to it. You must handle converting from your desired format to the RFC 3339 date format (YYYY-MM-DD).
input type=date – date input control
"A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0."
Grammar for Date input value
You can view it here (RFC3339 5.6).
date-fullyear = 4DIGIT
date-month = 2DIGIT ; 01-12
date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
; month/year
full-date = date-fullyear "-" date-month "-" date-mday
Code
$(function() {
function parseDate(dateString) {
var parts = dateString.split('/');
return new Date(parts[2], parts[0] - 1, parts[1]);
}
function getFormattedDate(date) {
return date.toISOString().substring(0, 10);
}
function addTime(date, ms) {
return new Date(date.getTime() + ms);
}
var MS_SEC = 1000;
var MS_MIN = MS_SEC * 60;
var MS_HOUR = MS_MIN * 60;
var MS_DAY = MS_HOUR * 24;
var date = parseDate('07/03/2015');
$('#arrival').val(getFormattedDate(date));
$('#departure').val(getFormattedDate(addTime(date, MS_DAY * 2)));
});
label {
display: inline-block;
width: 80px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="arrival">Arrival: </label>
<input type=date id="arrival" />
<br />
<label for="departure">Departure: </label>
<input type=date id="departure" />
A: var date1 = Date.parse('07/05/2015');
date1.setDate(date1.getDate()+2);
now date1 will give 07/05/2015
| |
doc_2801
|
A: The QR code would need to open the companion app on the phone and then the phone would pass the login details to the watch app via WCSession. So in Order to use the camera, you always need a companion app, a watch-only app is not able to access the camera. Thanks to @Paulw11
| |
doc_2802
|
at System.Windows.Forms.ToolStripProgressBar.set_RightToLeftLayout(Boolean value)
Object reference not set to an instance of an object.
Here is the code:
PropertyInfo piRightToLeftLayout = ci.Type.GetProperty("RightToLeftLayout", typeof(bool));
if ((null != piRightToLeftLayout) && piRightToLeftLayout.CanWrite)
{
piRightToLeftLayout.GetSetMethod().Invoke(ci.Value, new object[] { IsRightToLeft() });
}
IsRightToLeft() : returns either true or false.
Please help me to resolve this issue.
A: Why are you doing it by reflection? ToolStripProgressBar.RightToLeftLayout is a public property.
In terms of your NullReferenceException, all the setter does is:
set
{
this.ProgressBar.RightToLeftLayout = value;
}
Which implies, the ProgressBar property is null, which seems odd. I'd like to know what you're doing prior to your call and how ci has been setup.
| |
doc_2803
|
When the page is opened the controller gets the list of persons from the db and binds to the view.
That works fine.
Then the user edits the data and clicks save.
Now I need to submit the edited data of each person to the controller so that the controller can save the edits.
I'm trying to do that using @ModelAttribute ArrayList<Person> as shown below but it's not working.
The arraylist comes empty.
How do I do for the arraylist to come filled with all of the persons objects from the form?
View
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<form action="editperson" method="post">
<th:block th:each="person : ${personBind}">
Name:
<input type="text" th:value="${person.name}" />
</br></br>
Age:
<input type="text" th:value="${person.age}" />
</br></br>
</th:block>
</br></br>
<input type="submit" name="btnSaveEdit" value="Save"/>
</form>
Controller
@RequestMapping(value = "/editperson", params = "btnSaveEdit", method = RequestMethod.POST)
public String saveEditPerson(@ModelAttribute ArrayList<Person> personsList){
//save edit code here
return "editperson";
}
A: Spring MVC with Thymeleaf does indeed use model attributes to store data for the Thymeleaf pages. This guide shows how to load data from a form into the application. Try wrapping the ArrayList inside of a custom object and access the list via that object as a ModelAttribute rather than working with an ArrayList directly.
The saveEditPerson method should probably be named "saveEditPersons" since you are parsing a list of persons rather than just one.
| |
doc_2804
|
I'd like to find a library or method that formats output text, such that it word wraps at
80 columns (or user configurable), and allows user defined indentation.
I know that I could create one, but I suspect that there is already a library available
that does this. I've googled around and I've found pages for iomanip -- which gave me
ideas for creating my own.
I've done a cursory search through the boost libraries, but I didn't really find anything that quite matched.
A: Here it is, search harder next time ;)
2.2.4. Line-Wrapping Filters
http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/tutorial/line_wrapping_filters.html
A: If you're on a POSIX platform, you could look at ncurses or termcap and see if they will accomplish what you need.
A: https://github.com/catchorg/textflowcpp is probably the best way to do this nowadays.
| |
doc_2805
|
Operand data type varchar is invalid for avg operator.
SELECT StaffID, StaffName, LEFT(StaffGender, 1) AS [Staff Gender],
'Rp. ' + CAST ((StaffSalary)AS VARCHAR) [Staff Salary]
FROM MsStaff
WHERE StaffName Like '% %' AND StaffSalary > AVG(StaffSalary)
Update:
I have changed the StaffSalary column to INT datatype, but I get another error:
Msg 147, Level 15, State 1, Line 48
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference."
A: Although it seems to makes sense, you can’t use AVG() like that.
Use a sub-query to find the average:
SELECT ...
FROM MsStaff
WHERE StaffName Like '% %'
AND StaffSalary > (SELECT AVG(StaffSalary) FROM MsStaff)
A: select * from MsStaff where StaffSalary > (select avg(StaffSalary) from MsStaff)
| |
doc_2806
|
The file looks like this:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"ConnectionString": "abc"
}
and I am trying to read the ConnectionString setting like this:
ConfigurationManager.AppSettings["ConnectionString"];
but I get null, and apparently no app settings have been detected at all.
Edit:
Here is what I have now:
startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>();
services.AddMvc();
services.Configure<ConnectionStringSettings>(Configuration);
}
}
ConnectionStringSettings.cs
public class ConnectionStringSettings
{
public string ConnectionString { get; set; }
}
appsettings.json
{
"Logging": {
...
},
"ConnectionStrings": {
"Debug": "abc"
}
}
MyContext.cs
public class MyContext : DbContext
{
string x;
public MyContext() { }
public MyContext(DbContextOptions<MyContext> options)
: base(options) { }
public MyContext(IOptions<ConnectionStringSettings> connectionStringSettings)
{
x = connectionStringSettings.Value.ConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//here I need my connection string
optionsBuilder.UseMySql(connectionString);
}
}
A: For .NET Core 2.x you need to set configuration up in startup as below
public partial class Startup
{
public static IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
...
}
Then access as below
Configuration.GetConnectionString("System")
You should also have your connection strings laid out as below.
"ConnectionStrings": {
"System": "{connection String}"
}
This will allow for multiple strings if required but work even if you only have the one.
EDIT: Once you've got the string, as ColinM says in his answer you need to register the string with a class which you can inject into your classes. In startup as below.
services.AddSingleton<IConnectionStringFactory, ConnectionStringFactory>(serviceProvider => new ConnectionStringFactory(Configuration.GetConnectionString("System")));
Your connection string class...
public class ConnectionStringFactory : IConnectionStringFactory
{
private readonly string _connectionString;
public ConnectionStringFactory(string connectionString)
{
_connectionString = connectionString;
}
public string Invoke()
{
return _connectionString;
}
}
Inject into your class as so...
public class ClassName
{
private readonly IConnectionStringFactory _connectionStringFactory;
public ClassName(IConnectionStringFactory connectionStringFactory)
{
_connectionStringFactory = connectionStringFactory;
}
...
}
Your interface can be as simple as below
public interface IConnectionStringFactory
{
}
You don't need to use an interface but I'd recommend this approach
A: Based on your requirement of setting the connection string in the OnConfiguring override in your context, you can use the following approach.
Update your appsettings.json configuration file to contain a new JSON object for your database options
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"DatabaseOptions": {
"ConnectionString": "<Connection String>"
}
}
Create your model class which your DatabaseOptions configuration will map to
public class DatabaseOptions
{
public string ConnectionString { get; set; }
}
Then update your Startup class' ConfigureServices method to register an instance of IOptions<DatabaseOptions>
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<DatabaseOptions>(Configuration.GetSection("DatabaseOptions"));
}
And finally, update your context constructor to inject your IOptions<DatabaseOptions> instance, ASP.NET Core will handle the dependency injection for you as long as you register your context in the service collection.
public class MyContext
{
private readonly DatabaseOptions databaseOptions;
public MyContext(DbContextOptions<MyContext> options, IOptions<DatabaseOptions> databaseOptions)
: base(options)
{
this.databaseOptions = databaseOptions.Value;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//here I need my connection string
optionsBuilder.UseMySql(databaseOptions.ConnectionString);
}
}
Personally, I don't like naming classes with Options in the name when that class is going to be used with IOptions<T>, but as developers we can spend a large time of coding just thinking of class and variable names, feel free to rename as you please.
A: You should use Configuration in Startup =>
public void ConfigureServices(IServiceCollection services)
{
var section = Configuration.GetSection("ConnectionString");
var value= Configuration.GetValue<string>("ConnectionString")
}
| |
doc_2807
|
[1..10]
will create an array containing {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
Or
[-2..2]
will create {-2, -1, 0, 1, 2}.
Is there any related shorthand for creating an array in F# with a floating-point step? For example, an array like {-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2} where the step is 0.5? Or is using a for or while loop the only way?
A: Yes there is.
[-2.0 .. 0.5 .. 2.0]
This creates
[-2.0; -1.5; -1.0; -0.5; 0.0; 0.5; 1.0; 1.5; 2.0]
Documentation: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/loops-for-in-expression
| |
doc_2808
|
If I drag things around in the Finder, both Xcode and git are in the dark. I have faith that git will figure things out by content when the time comes, but I also notice that there's a difference in the output of git status between doing a git mv and moving the file in the Finder, then adding the deletion and addition operations separately, so I'm assuming there's some difference (even if that difference doesn't end up getting encoded into the content of the commit.) Xcode, on the other hand, is hopeless in the face of this. (You have to manually re-find every single file.)
If I use git mv from the command line, git tracks the move, but I still have to manually reconnect each reference in Xcode (or tear them all out and reimport everything, which is a pain in the ass because many of these files have custom build flags associated with them.)
It appears that there simply isn't a way to cause a file system move from within Xcode.
I've found zerg-xcode and a plug-in for it that claims to sync the file system to mirror the Xcode group structure, but I've not been able to google up anything that goes the other way. I just want a way to move files on the file system and have the two other things (git and Xcode) to keep track of the files across the moves. Is this too much to ask? So far it seems the answer is, "yes".
Yes, I've seen Moving Files into a Real Folder in Xcode I'm asking whether someone's written a script or something that makes this less painful.
A: Actually, by design, Git doesn't track moves. Git is only about content. If any Git tool tells you there was a move (like git log --follow, it's something that was guessed from content, not from metadata).
So you won't lose information if you move files around with another tool then git add the whole folder.
| |
doc_2809
|
$q.all([$http.get('..'),$http.get('..')]).then(function(res) {
// this will never happen if one get fails.
}
A: Simple proof of concept using catch()
var req1 = $http.get('..').catch(function(err){ return err; });
var req2 = $http.get('..').catch(function(err){ return err; });
$q.all([req1,req2]).then(function(results) {
var counts = {pass:0, fail:0}
results.forEach(function(item){
var type = item.status === 200 ? 'pass':'fail';
counts[type]++;
});
alert('Results status =' + JSON.stringify(counts))
});
Because you return something from catch it resolves the initial promise and passes that return down the promise chain (to results array in this case) .
The success callback of $q.all().then will fire as a result
DEMO
| |
doc_2810
|
import os
from lxml import etree
directory_name = "C:\\apps"
file_name = "web.config"
xpath_identifier = '/configuration/applicationSettings/Things/setting[@name="CorsTrustedOrigins"]'
#contents of the xml file for reference:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="Things" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</sectionGroup>
</configSections>
<appSettings/>
<applicationSettings>
<Things>
<setting name="CorsTrustedOrigins" serializeAs="Xml">
<value>
<ArrayOfString>
<string>http://localhost:51363</string>
<string>http://localhost:3333</string>
</ArrayOfString>
</value>
</setting>
</Things>
</applicationSettings>
</configuration>
file_full_path = os.path.join(directory_name, file_name)
tree = etree.parse(file_full_path)
root = tree.getroot()
etree.tostring(root)
xpath_identifier = str(xpath_identifier)
value = root.xpath(xpath_identifier)
#This successfully prints the element I'm after, so I'm sure my xpath is good:
etree.tostring(value[0])
#This is the new xml element I want to replace the current xpath'ed element with:
newxml = '''
<setting name="CorsTrustedOrigins" serializeAs="Xml">
<value>
<ArrayOfString>
<string>http://maddafakka</string>
</ArrayOfString>
</value>
</setting>
'''
newtree = etree.fromstring(newxml)
#I've tried this:
value[0].getparent().replace(value[0], newtree)
#and this
value[0] = newtree
#The value of value[0] gets updated, but the "root document" does not.
What I'm trying to do is to update the "ArrayofStrings" element to reflect the values in the "newxml" var.
I'm kindof struggling to navigate the lxml infos on the web, but I can't seem to find an example similar to what I'm trying to do.
Any pointers appreciated!
A: You should just remove the indexed access on the node:
value[0].getparent().replace(value[0], newtree)
.... to:
value.getparent().replace(value, newtree)
| |
doc_2811
|
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 21403 of the JSON data
http://localhost/c2c/content/scripts/jqueryEngine/jquery.js line 2 > eval
Line 10.
Here its written 21403 column in firebug. How which object's property lies in column 21403 so that I can make correction.
| |
doc_2812
|
dupl
But I'd like to also have different branch in each window.
But when I change branch in the first window, it also changes branch in the second window.
P.S.
I don't need workspace, but I cannot have two opened windows with the same folder.
A: Based on the question tags, it seems you're talking about opening multiple VS-Code windows, each viewing a different version of a file.
The git part of the problem comes down to: how do you have both copies of the file available on disk at the same time?
Probably the best solution is to set up two worktrees. See the docs for git worktree (https://git-scm.com/docs/git-worktree). Then you open one window to each checked out worktree. This allows you to fully interact with each version on its own branch.
If your usage of one version or the other is read-only - i.e. you're referring to one version but working on the other - then it might work to keep your single worktree checked out to the version containing the version you're editing, but then you need to extract a copy of the other version of the specific file. For example
git checkout otherBranch -- path/to/file
mv path/to/file path/to/file.other
git checkout HEAD -- path/to/file
This might seem lighter-weight than setting up a whole second worktree, but you will want to remember to clean up the extra file when you're done with it.
A: Switching branches changes files in your working directory
It’s important to note that when you switch branches in Git, files in your working directory will change. If you switch to an older branch, your working directory will be reverted to look like it did the last time you committed on that branch. If Git cannot do it cleanly, it will not let you switch at all.
enter link description here
| |
doc_2813
|
min 8 chars
min 1 upper
min 1 lower
min 1 numeric
min 1 special char which can ONLY be one of the following:$|~=[]'_-+@. (and the password can contain no other special chars besides these)
It's the exclusion of special characters which is giving me the headache.
I've come up with this but it just does not work:
"^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])**(?(?!.*[^$|~=[\]'_\-+@.])|([^\W\w])).*$**
It resolves everything I enter as invalid.
Whereas this (for the special chars) on its own does work:
"(?(?!.*[^$|~=[\]'_\-+@.])|([^\W\w])).*$"
and I know the first part works, so what am I missing to make them work together?
Alternatively, is there a much simpler way of achieving this?
(.NET environment)
A: If you really want to do that in one regex pattern:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$|~=[\]'[email protected]])[a-zA-Z0-9$|~=[\]'[email protected]]{8,}$
That should do the trick. We require, the lower case, upper case letter, digit and symbol with lookaheads. Note that in the character class, you need to move - to the end or escape it. Otherwise it creates a character range you don't want. Then we use normal matching to ensure that there are only the allowed characters, and at least 8 of them.
However, it's usually a much better approach to do multiple tests. Run these patterns individually:
[a-z] // does the input contain a lower case letter?
[A-Z] // does the input contain an upper case letter?
\d // does the input contain a digit?
[$|~=[\]'[email protected]] // does the input contain one of the required symbols?
[^a-zA-Z0-9$|~=[\]'[email protected]] // are there invalid characters?
where the first 4 should return true and the last one should return false. In addition you can check input.Length >= 8. This makes for much more readable code and will allow you to issue an appropriate error message about which condition is not fulfilled.
In fact, since the last pattern ensures that there are only the desired characters, we can simplify the "there has to be one symbol condition" to [^a-zA-Z0-9] (in both approaches). But I'm not sure whether that makes things more or less readable.
| |
doc_2814
|
from keep_alive import keep_alive
def do_job():
print("Get information from site once everyday starting from 1am")
keep_alive()
while True:
do_job()
time.sleep(86400)
I'm running this code which is just the simplified version of my selenium task where the do_job() function contains the task.
The issue I'm facing is that the keep_alive() server gets pinged every 5 mins and that immediately start the python script from the beginning again ignoring the time. sleep.
How can I make this code run once a day at 1 am ignoring the keep_alive() pinging which is just to keep my server on while am offline.
| |
doc_2815
|
If i write manual the id's it works great.
I have a url like this http://www.mydomain.com/myfile.php?theurl=1,2,3,4,5 (ids)
Now in the myfile.php i have my sql connection and:
$ids = $_GET['theurl']; (and i am getting 1,2,3,4,5)
if i use this:
$sql = "select * from info WHERE `id` IN (1,2,3,4,5)";
$slqtwo = mysql_query($sql);
while ($tc = mysql_fetch_assoc($slqtwo)) {
echo $tc['a_name'];
echo " - ";
}
I am Getting the correct results. Now if i use the code bellow it's not working:
$sql = "select * from info WHERE `id` IN ('$ids')";
$slqtwo = mysql_query($sql);
while ($tc = mysql_fetch_assoc($slqtwo)) {
echo $tc['a_name'];
echo " - ";
}
Any suggestions?
A: When you interpolate
"select * from info WHERE `id` IN ('$ids')"
with your IDs, you get:
"select * from info WHERE `id` IN ('1,2,3,4,5')"
...which treats your set of IDs as a single string instead of a set of integers.
Get rid of the single-quotes in the IN clause, like this:
"select * from info WHERE `id` IN ($ids)"
Also, don't forget that you need to check for SQL Injection attacks. Your code is currently very dangerous and at risk of serious data loss or access. Consider what might happen if someone calls your web page with the following URL and your code allowed them to execute multiple statements in a single query:
http://www.example.com/myfile.php?theurl=1);delete from info;--
A: You can also try FIND_IN_SET() function
$SQL = "select * from info WHERE FIND_IN_SET(`id`, '$ids')"
OR
$SQL = "select * from info WHERE `id` IN ($ids)"
| |
doc_2816
|
A: One option is to use the standard Sys V IPC shared memory. After call to shmget(), use shmctl() to set the permissions. Give read write permission to only one group/user and start the processes which are allowed to access this as the specific user. The shared memory key and IDs can be found using ipcs, and you need trust the standard unix user/group based security to do the job.
Another option is implementing a shared memory driver. Something similar to Android ashmem. In the driver, you can validate the PID/UID of the caller who is trying to access the memory and allow/deny the request based on filters. You can also implement a sysfs entry to modify these filter. If the filters needs to be configurable, again you need to trust the Unix user/group based security. If you are implementing a driver, you will have plenty of security options
| |
doc_2817
|
I was wondering if other people had such an issue and how they solved it?
I am using Exoplayer.
Thanks
A: I found out why it was happening after debugging the layout. it was being caused by extra margin. it had nothing to do with Exoplayer as such.
Thank you.
| |
doc_2818
|
driver.findElement(By.xpath("/html/body/font/strong/em/text()")).getText().contains(message);
but it complains with:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/font/strong/em/text"}
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7600 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 130 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: 'salman-PC', ip: '192.168.1.5', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_131'
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\salman\AppData\Local\Temp\scoped_dir7612_3059}, 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: 9ffe01502a1cd688cd022bf5e7719e42
*** Element info: {Using=xpath, value=/html/body/font/strong/em/text}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at ee.ignite.pages.SelectFromDropDownPage.getText(SelectFromDropDownPage.java:33)
at ee.ignite.steps.SelectFromDropDown_Steps.i_can_see_the_maessage(SelectFromDropDown_Steps.java:32)
at ✽.Then I can see the maessage "Congratulations"(D:/Workspace/IgniteTask/src/features/SelectFromDropDown.feature:9)
it seems that the path
/html/body/font/strong/em/text()
is wrong?
A: *
*Depend on the browser and the performance of your connection the time amount that takes to load the page content will become different.
So, give some time to load them.
In here, if you are using JS with your web page, I'm recommending you to use explicit wait.
Through that, we can define a time amount for web driver to wait until certain requirements to be met before executing the next line of code.
In your case:-
WebDriver webdriver = new FirefoxDriver();
webdriver .get("Your URL");
WebDriverWait wait = new WebDriverWait(webdriver,30);
WebElement element = wait.untill(ExpectedConditions.visibilityOfElementLocated(By.xpath("your X-path")));
*
*according to this example code, your web driver will wait 30 seconds of time until the visible of named object.
A: findElement() method returns WebElement. The xpath "/html/body/font/strong/em/text()" returns String. I'm guessing you received InvalidSelectorException so you tried the xpath "/html/body/font/strong/em/text", according to the stacktrace, which doesn't exists so you got NoSuchElementException.
driver.findElement(By.xpath("/html/body/font/strong/em")).getText();
Should give you the text.
Edit
To give the driver some time to locate the element to prevent timing issues you can set implicit wait
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("/html/body/font/strong/em")).getText();
A: In order to get the text, you need to first store it in some variable which you can print or use as per your need. Below is the sample code.
String t1 = driver.findElement(By.xpath("/html/body/font/strong/em")).getText();
System.out.println(t1);
I checked it on my machine and it is working fine.
| |
doc_2819
|
And when I click Order now, nothing happening.
I searched for the error everywhere, but I couldn't find it.
can you help me !!
this is my error video: https://youtu.be/DU_OOZxyEV0
controller.js
cartApp.controller("cartCtrl", function($scope,$http){
$scope.refreshCart = function (cartId) {
$http.get('/rest/cart/'+$scope.cartId).then(function (data) {
$scope.cart=data;
});
};
$scope.clearCart=function(){
$http.delete('/rest/cart/'+$scope.cartId).then($scope.refreshCart($scope.cartId));
};
$scope.initCartId=function(cartId){
$scope.cartId=cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart=function(productId){
$http.put('/rest/cart/add/'+productId).then(function(data){
$scope.refreshCart($http.get('/rest/cart/cartId'));
alert("product successfully added to the cart")
});
};
$scope.removeFromCart=function(productId){
$http.put('/rest/cart/remove/'+productId).then(function(data){
$scope.refreshCart($http.get('/rest/cart/cartId'));
alert("product successfully removed from the cart")
});
};
});
cart.jsp
<section class="container" ng-app="cartApp">
<div ng-controller = "cartCtrl" ng-init="initCartId('${cartId}')">
<div>
<a class="btn btn-danger pull-left" ng-click="clearCart()"><span class="glyphicon glyphicon-remove-sign"></span>Clear Cart </a>
</div>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr ng-repeat="item in cart.cartItems">
<td>{{item.product.productName}} </td>
<td>{{item.product.productPrice}}</td>
<td>{{item.quantity}}</td>
<td>{{item.totalPrice}}</td>
<td><a href="#" class="label label-danger" ng-click="removeFromCart(item.product.productId)">
<span class="glyhicon glyhicon-romove">Remove</span></a></td>
</tr>
<tr>
<th></th>
<th></th>
<th>Grand Total: </th>
<th>{{cart.grandTotal}}</th>
<th></th>
</tr>
</table>
<a href="<spring:url value="/productList"/> " class="btn btn-default">Continue Shopping</a>
</div>
</section>
product.jsp
<p ng-controller="cartCtrl">
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')">
<span class="glyphicon glyphicon-shopping-cart"></span>Order Now</a>
</p>
Pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
A: 403 means you need to configure Spring security to allow that request
| |
doc_2820
|
This is for sending bulk emails using templates (https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html)
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SimpleEmail/TSendBulkTemplatedEmailResponse.html
SendBulkTemplatedEmailResponse response = client.SendBulkTemplatedEmailAsync(sendBulkTemplatedEmailRequest).Result
SendBulkTemplatedEmailRequest has more than one email addresses and SendBulkTemplatedEmailResponse is returned with individual status for each email as List<BulkEmailDestinationStatus> (https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SimpleEmail/TBulkEmailDestinationStatus.html).
Each BulkEmailDestinationStatus has MessageId and Status (some predefined constants). But not having the email-address for which the status is returned (obviously there are more than one recipients so there are individual status for each recipient.)
With that said, how to figure out mapping from email-address to MessageId or vice-versa?
I am getting confused about what is the use of messageId in BulkEmailDestinationStatus where there is not any associated recipient email-address. Am I missing something very basic here?
A: While I didn't find any resources on this, I'll just leave what I gathered testing this feature, for anyone else that may find this question.
The order of the emails sent (ie. the order of the emails in the Destinations property) is the order of the returned messageIds.
So, using the docs json sample:
{
"Source":"Mary Major <[email protected]>",
"Template":"MyTemplate",
"ConfigurationSetName": "ConfigSet",
"Destinations":[
{
"Destination":{
"ToAddresses":[
"[email protected]"
]
},
"ReplacementTemplateData":"{ \"name\":\"Anaya\", \"favoriteanimal\":\"angelfish\" }"
},
{
"Destination":{
"ToAddresses":[
"[email protected]"
]
},
"ReplacementTemplateData":"{ \"name\":\"Liu\", \"favoriteanimal\":\"lion\" }"
},
{
"Destination":{
"ToAddresses":[
"[email protected]"
]
},
"ReplacementTemplateData":"{ \"name\":\"Shirley\", \"favoriteanimal\":\"shark\" }"
},
{
"Destination":{
"ToAddresses":[
"[email protected]"
]
},
"ReplacementTemplateData":"{}"
}
],
"DefaultTemplateData":"{ \"name\":\"friend\", \"favoriteanimal\":\"unknown\" }"
}
The object sent would be a
(SendBulkTemplatedEmailRequest) request with the following list:
request.Destinations[0].ToAddresses = {"[email protected]"}
request.Destinations[1].ToAddresses = {"[email protected]"}
request.Destinations[2].ToAddresses = {"[email protected]"}
request.Destinations[3].ToAddresses = {"[email protected]"}
And the (SendBulkTemplatedEmailResponse) response would have this list:
response.Status[0].MessageId = "0000000000000000-11111111-2222-3333-4444-111111111111-000000"
response.Status[1].MessageId = "0000000000000000-11111111-2222-3333-4444-222222222222-000000"
response.Status[2].MessageId = "0000000000000000-11111111-2222-3333-4444-333333333333-000000"
response.Status[3].MessageId = "0000000000000000-11111111-2222-3333-4444-444444444444-000000"
Where:
*
*the MessageId "0000000000000000-11111111-2222-3333-4444-111111111111-000000" refers to the email sent to [email protected];
*the MessageId
"0000000000000000-11111111-2222-3333-4444-222222222222-000000"
refers to to the email sent to "[email protected]";
and so on.
| |
doc_2821
|
However, I'm trying to target an element based on a data-* attribute with XPath, and the test chokes on it.
I've used XPathHelper and FirePath and my XPath checks out in both of those extensions:
//html//@data-search-id='images'
That appears to target the correct element.
However, when I add the following to FeatureContext.php
$el = $this->getSession()->getPage()->find('xpath', $this->getSession()->getSelectorsHandler()->selectorToXpath('xpath', "//@data-search-id='images'"));
$el->click();
I get the following error from Behat:
invalid selector: Unable to locate an element with the xpath expression
//html//@data-search-id='images' because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document':
The result is not a node set, and therefore cannot be converted
to the desired type.
A: Your XPath expression is a totally valid expression – it will find all @data-search-id attributes and return true if one of them is 'images', otherwise false.
But you want to click an item, and obviously clicking a boolean value is rather difficult. Query for the item fulfilling the condition instead (thus, move the comparison into a predicate):
//html//*[@data-search-id='images']
Additionally, I'd remove the //html. The HTML node must be the root node anyway, so /html would have been fine (no reason for searching it in all subtree). As you're searching for an arbitrary descendent of it, and this will not be the root node (as <html/> is), omitting it completely does not change the meaning of the XPath expression.
//*[@data-search-id='images']
A: I think the XPath you're looking for is:
//html//*[@data-search-id='images']
| |
doc_2822
|
let myImage = UIImage(named: "myImage.jpg")
Is there an equivalent to this with MSSticker?
let mySticker = MSSticker(named: "mySticker") obviously does not work.
There is MSSticker(contentsOfFileURL: URL, localizedDescription: String but I am unsure how to, if possible, properly implement in a similar fashion to UIImage.
Thanks.
A: No, there is not currently an equivalent. Moreover, you cannot programmatically create stickers from images in an asset catalog either, since those aren't accessible through file URL (pathForResource on the bundle won't generate a path for items in an .xcassets folder).
You need to go old school and drag the images in as a resource like you would any other file you were adding to the project.
A: BJHStudios is right, unfortunately! I recently answered another question that you may want to take a look at. It goes over everything you need to get your stickers onto the BrowserView with the MSSticker(contentsOfFileURL: URL, localizedDescription: String) method.
Link to other question
| |
doc_2823
|
I'm sure the syntax of my py code is correct because the DAG showed up on a windows instance but my setup for airflow within Linux is somehow not correct? Also used python3 script.py to execute.
A: Basically the dags folder's permission's weren't allowing anything to be written into it. I just sudo'd every command or chmod the folder. Also to ensure Airflow was correctly run, I suggest using a YAML file with docker compose to streamline Airflow setup.
| |
doc_2824
|
Ramda Repl
var myObject = {a: 1, b: 2, c: 3, d: 4};
var newObject = R.filter(R.props('a'), myObject);
//var newObject = R.filter(R.equals(R.props('a')), myObject);
console.log('newObject', newObject);
Right now the code above is returning the entire object:
newObject
{"a":1,"b":2,"c":3,"d":4}
What I would like to do is just return a new object with just the 'a' key. Or a new object with the a and b keys.
A: pickBy()
const getOnlyGoods = R.pickBy((_, key) => key.includes('good'));
const onlyGoods = getOnlyGoods({
"very good": 90,
"good": 80,
"good enough": 60,
"average": 50,
"bad": 30,
"": 10,
});
console.log(onlyGoods);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
A: Use pick:
let newObj = R.pick(['a'], oldObj);
If your filtering criteria is more complex than just existence, you can use pickBy to select via arbitrary predicate functions.
A: The answer from Jared Smith is great. I just wanted to add a note on why your code did not work. You tried
R.filter(R.props('a'), {a: 1, b: 2, c: 3, d: 4});
First of all, you pointed to the documentation for prop, but used props. These are different, but related, functions. prop looks like
// prop :: k -> {k: v} -> v
prop('c', {a: 1, b: 2, c: 3, d: 4}); //=> 3
(there is some added complexity regarding undefined.)
props on the other hand takes multiple values
// props :: [k] -> {k: v} -> [v]
props(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> [1, 4]
But neither of these is going to be useful input to filter, which for these purposes we can think of as
// filter :: (k -> Bool) -> {k: v} -> {k: v}
The first parameter to filter is a function from a (string) key to a boolean; it works with Javascript's idea that everything is truth-y except for a few specific values. It will be called with each key in turn. So for example, when deciding whether to include {c: 3}, it calls props('a')('c'), which for another slightly odd reason*, actually works, returning [3], which is treated as truth-y, and the filter function will include {c: 3} in its output. So too every key will be included.
* The reason props('a', obj) works when it really should be props(['a'], obj) is that in JS, strings are close enough to lists, having a length property and indexed values. 'a'.length; ==> 1, 'a'[0]; //=> 'a'. Hence props can treat single-character strings as though they were one-element lists of character strings. But it can be a bit bizarre, too: R.props('cabby', {a: 1, b: 2, c: 3, d: 4}); //=> [3, 1, 2, 2, undefined].
A: Adding to the other answers, there's also omit to filter out specific props.
omit(["a"], { a: 1, b: 2 }) // -> { b: 2 }
| |
doc_2825
|
The url is perfectly working in Safari. User can easily logged in but when I load the url in WKWebView and hit Login Button it stucks there and nothing happens. So far I have no idea what's going wrong as the same site is working fine in Safari App so I expect it to work in WKWebView as well
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
let url = URL.init(string: ".com/app/#/login")
let request = URLRequest.init(url: url!)
webView.load(request)
| |
doc_2826
|
TLDR; How do I use Chrome console to select and pull out some data from a URL?
A: Note: since jQuery is available on this page, I'll just go ahead and use it.
First of all, we need to select elements that we want, e.g. names of the companies. These are being kept on the list with ID startups_content, inside elements with class items in a field with class name. Therefore, selector for these can look like this:
$('#startups_content .items .name a')
As a result, we will get bunch of HTMLElements. Since we want a plain text we need to extract it from these HTMLElements by doing:
.map(function(idx, item){ return $(item).text(); }).toArray()
Which gives us an array of company names. However, lets make a single plain text list out of it:
.join('\n')
Connecting all the steps above we get:
$('#startups_content .items .name a').map(function(idx, item){ return $(item).text(); }).toArray().join('\n');
which should be executed in the DevTools console.
If you need some other data, e.g. company URLs, just follow the same steps as described above doing appropriate changes.
| |
doc_2827
|
The problem is as soon as I use them as const, they are recalculated every next render. But if I put them into state, for some reason they can't see the actual value of other state variables.
const [t, setT] = useState(1);
function clickItem(){
console.log(t)
setT(t + 1)
};
// Case 1:
const randomItems = [Math.random(), Math.random()]
.map(i=><div key={i} onClick={clickItem}>{i}</div>);
// Case 2
const [list, setList] = useState([Math.random(), Math.random()]
.map(i=><div key={i} onClick={clickItem}>{i}</div>));
return (
<>{randomItems}
<hr></hr>
{list}
</>
);
When we click the items from the first list, they increase the "t" variable but change their values with each click.
When we click the items from the second list, they don't change their values but the value of "t" is always 1.
A: You can save the values your want to persist to localStorage and load them into a context variable which will be used by your other components.
A: Problem with first approach is as you said the random numbers are generated on each render, hence on each render your components will have new key, you don't want that usually.
Problem with second one is that, the values you passed to useState as argument will be created only once (well they might be recreated on each render but the result is discarded anyway), hence also the callback you passed to it only sees the value from the first render and only logs 1. Also usually it is not needed to put components in state.
You can generate them once and store in state, just no need to also store the react elements in state, like this:
export default function App(props) {
let [data, setData] = React.useState([
{ id: 0, name: 'John' },
{ id: 1, name: 'Nick' },
]);
return (
<div>
{data.map((x) => (
<div key={x.id}>{x.name}</div>
))}
</div>
);
}
| |
doc_2828
|
The goal is to build functionality such as this (https://www.mapbox.com/mapbox.js/example/v1.0.0/filtering-marker-clusters/)
A: The GeoJSON clustering happens at the source level, so if you want to filter data in the clusters, you will have to filter the GeoJSON itself and then update the source with the filtered data.
map.getSource('sourceName').setData(filteredData)
here is a jsfiddle demonstrating the functionality
disclaimer: I work at Mapbox
| |
doc_2829
|
I am using tensorflow 1.15.
A simple example of what I'm trying to do is as follows:
import numpy as np
import tensorflow as tf
from tensorflow_core.python.keras import Sequential
from tensorflow_core.python.keras.layers import Dense
batch_size = 4
data_size = 16
model_generator = Sequential([Dense(data_size)])
model_generator.compile(optimizer='adam', loss='mae')
model_generator.build((batch_size, data_size))
sess = tf.keras.backend.get_session()
def generator():
while True:
data = np.random.random((batch_size, data_size))
targets = tf.random.uniform((batch_size, 1))
data = model_generator(data, training=False)
data = data.eval(session=sess)
yield (data, targets)
model_train = Sequential([Dense(data_size)])
model_train.compile(optimizer='adam', loss='mae')
model_train.build((batch_size, data_size))
output_types = (tf.float64, tf.float64)
output_shapes = (tf.TensorShape((batch_size, data_size)), tf.TensorShape((batch_size, 1)))
dataset = tf.data.Dataset.from_generator(
generator,
output_types=output_types,
output_shapes=output_shapes,
)
if next(generator()) is not None:
print("Generator works outside of model.fit()!")
model_train.fit(
dataset,
epochs=2,
steps_per_epoch=2
)
The snippet above produces the following error message when .fit() is called.:
2020-01-28 17:35:56.705549: W tensorflow/core/framework/op_kernel.cc:1639] Invalid argument: ValueError: Tensor("dense/kernel/Read/ReadVariableOp:0", shape=(16, 16), dtype=float32) must be from the same graph as Tensor("sequential/dense/Cast:0", shape=(4, 16), dtype=float32).
Traceback (most recent call last):
The code will run normally if the generator does not call the model_generator model. For example:
def generator():
while True:
data = np.random.random((batch_size, data_size))
targets = np.random.random((batch_size, 1))
yield (data, targets)
I believe that the fit call creates its own tensorflow graph which does not include the nodes needed for model_generator. Is there any way to use one model in the generator used for training another model like this? If so, how can I modify the above example to achieve this?
A: I don't think it's possible to have the graph connected between a tf.Dataset and a Keras model. Instead, what you need to do is find some way of creating a single model out of the two.
If the model_generator can be used directly as an input to your model_train, then the easiest way I can think of to do this is to create a Sequential model containing both models. Here's a simple example based on your snippet above. In this example, only model_train will be backpropogated through.
import numpy as np
import tensorflow as tf
from tensorflow_core.python.keras import Sequential, Model
from tensorflow_core.python.keras.layers import Dense, Input
batch_size = 4
data_size = 16
def generator():
while True:
data = np.random.random((batch_size, data_size))
targets = np.random.random((batch_size, 1))
yield (data, targets)
model_generator = Sequential([Dense(data_size)])
# Freeze weights in your generator so they don't get updated
for layer in model_generator.layers:
layer.trainable = False
model_train = Sequential([Dense(data_size)])
# Create a model to train which calls both model_generator and model_train
model_fit = Sequential([model_generator, model_train])
model_fit.compile(optimizer='adam', loss='mae')
model_fit.build((batch_size, data_size))
model_fit.summary()
output_types = (tf.float64, tf.float64)
output_shapes = (tf.TensorShape((batch_size, data_size)),
tf.TensorShape((batch_size, 1)))
dataset = tf.data.Dataset.from_generator(
generator,
output_types=output_types,
output_shapes=output_shapes,
)
model_fit.fit(
dataset,
epochs=2,
steps_per_epoch=2
)
| |
doc_2830
|
I think I didn't missed any single thing for the atoi part. I am using visual studio, and would that be the problem? Shall I change the program??
This is the code:
#include <stdio.h>
#include <stdlib.h>
double arith_seq(double*, int, int);
int main(int argc, char* argv[])
{
double* in;
int num;
num = atoi(argv[1]);
in = (double*)malloc((num+1) * sizeof(double));
if (in == NULL)
{
num = 1;
arith_seq(&in, num, 0.1);
}
//if there is no input
else
{
in[0] = 0;
arith_seq(&in, num, 0.1);
}
//in normal case
printf("My last array element is : %f", in[num - 1]);
//print the last element of the array
free(in);
return 0;
}
double arith_seq(double* parr, int size, int com)
{
for (int i = 1; i < size; i++)
{
parr[i] += parr[i - 1] + com;
}
return *parr;
}
A: There are multiple things wrong.
*
*You access argv[1] without checking argc first to know if there even are any arguments stored in argv
*double arith_seq(double* parr, int size, int com) expects a double pointer as first argument. You are passing a pointer to a double pointer at multiple places (e.g. arith_seq(&in, num, 0.1) in has type double*, you are passing the address of that)
*double arith_seq(double* parr, int size, int com) expects an int as third argument, you are passing a double at multiple places (e.g. arith_seq(in, num, 0.1), 0.1 is not an int). I don't think you want to do that.
*malloc expects a size_t argument, but you are passing (num + 1) * sizeof(double)
. What if (num + 1) is negative? That will lead to some "interesting" behaviour (Think about what unsigned value -1 represents for example).
*You check if malloc returned a NULL pointer (in == NULL), but still go ahead and call arith_seq, which accesses elements of in. You are not allowed to dereference a NULL pointer.
*You refer to in[num-1] as the last array element, but actually in[num] is the last elelement. Remember, you allocated an array of num+1 elelements.
*In arith_seq you do parr[i] += parr[i-1] + com, which is equal to parr[i] = parr[i] + parr[i-1] + com. But parr[i] has not been initialized anywhere in your code and contains garbage data. This garbage data propagates through the entire array in your loop.
I recommend to start over with that code.
I am not exactly sure what you intend to do with the code, so i can't fully fix it (this fixes 1 and 2, for the rest i don't even know what your original intention was), but this atleast doesnt crash:
#include <stdio.h>
#include <stdlib.h>
double arith_seq(double*, int, int);
int main(int argc, char* argv[])
{
double* in;
int num;
if(argc <= 1){
return(1);
}
num = atoi(argv[1]);
printf("%d\n", num);
in = (double*)malloc((num+1) * sizeof(double));
if (in == NULL)
{
return(1);
}
in[0] = 0.0f;
arith_seq(in, num, 0.1);
printf("My last array element is : %f", in[num]);
free(in);
return(0);
}
double arith_seq(double* parr, int size, int com)
{
for (int i = 1; i < size; i++)
{
parr[i] += parr[i-1] + com;
}
return *parr;
}
| |
doc_2831
|
app.service('ScopeService', ['$http', '$q', function($http, $q){
var service = {};
var permsList = [],
codeMapping;
var perms = {
"admin": true,
"dev": true,
"qa": true,
"audit": false,
"general": true,
"grp1": false,
"grp2": false,
"grp3": false,
"grp4": false,
"grp5": true,
"env": "DEV",
"version": "1.6.3"
}
function mapping() {
$http.get('./utils/codeMapping.json').then(function (response) {
codeMapping = response.data.codeMapping;
function findBU(BG) {
return _.find(codeMapping, ['id', Name]).number
}
if (perms.grp1) {
permsList = permsList.concat(findBU('A'));
}
if (perms.grp2) {
permsList = permsList.concat(findBU('B'));
}
if (perms.grp3) {
permsList = permsList.concat(findBU('C'));
}
if (perms.grp4) {
permsList = permsList.concat(findBU('D'));
}
if (perms.grp5) {
permsList = permsList.concat(findBU('E'));
}
if (perms.audit) {
permsList = [];
}
$q.resolve(permsList);
});
}
service.getMapping = function() {
return mapping();
};
service.getMapping().then(function(res) {
console.log(res)
})
return service;
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
So "outside" gives me the data I want but its not working inside the getMapping function.
I think its because of a timing mismatch as service is being called with an empty object before the value of getMapping is being added.
Please help.
A: From what code you provided its a little difficult to tell how you're using this. However, It appears you are not returning a promise, you're returning an array object. Also, I'm not sure why you are chaining another then in on your get request. Try something like this...
Check out a working example here:
http://jsfiddle.net/riegersn/rnd4ujfd/12/
app.service('ScopeService', ['$http', '$q', function($http, $q) {
var service = {};
var permsList = [],
codeMapping;
var perms = {
"admin": true,
"dev": true,
"qa": true,
"audit": false,
"general": true,
"grp1": false,
"grp2": false,
"grp3": false,
"grp4": false,
"grp5": true,
"env": "DEV",
"version": "1.6.3"
}
service.getMappings = function() {
return $http.get('https://jsonplaceholder.typicode.com/users/1').then(function(response) {
/* manipulate your data */
permsList.push('some data!');
console.log(permsList);
return $q.resolve(permsList);
});
}
return service;
}]);
| |
doc_2832
|
struct ContentView: View {
var body: some View {
ScrollView{
GeometryReader { geometry in
VStack{
ForEach(0..<90) { index in
Text("test \(geometry.size.height)")
}
}
}
}
}
}
geometry.size.height is always 10.000.
how can i correct this unexpected result?
Thanks so much!
A: I'm not sure where you're going with this.
GeometryReader reads the size offered to the view, not the size of the view. You can find out how big the view is by putting a GeometryReader in an .overlay of the VStack, because by the time the overlay is created, the size of the VStack will have been established and that size will be offered to the overlay.
struct ContentView: View {
var body: some View {
ScrollView{
VStack{
ForEach(0..<90) { index in
Text("test 000000000000")
.opacity(0)
}
}
.overlay(
GeometryReader { geometry in
VStack {
ForEach(0..<90) { index in
Text("test \(geometry.size.height)")
}
}
}
)
}
}
}
| |
doc_2833
|
There is validation so that they can only connect the dots from 1 and go to 2 (.. n). The issue is that right now is there is no validation that the line is a straight line and I am looking for an algorithm to do this, Here is what I have thought so far
*
*For 2 points (x1,y1) to (x2,y2) get all the coordinates by finding the slope and using the formula y = mx + b
*on touchmove get the x,y co-oridnates and make sure it is one of the points from the earlier step and draw a line else do not draw the line.
Is there a better way to do this or are there any different approaches that I can take ?
A: Edit: I originally misunderstood the question, it seems.
As far as validating the path: I think it would be easier just to have a function that determines whether a point is valid than calculating all of the values beforehand. Something like:
function getValidatorForPoints(x1, y1, x2, y2) {
var slope = (y2 - y1) / (x2 - x1);
return function (x, y) {
return (y - y1) == slope * (x - x1);
}
}
Then, given two points, you could do this:
var isValid = getValidatorForPoints(x1, y1, x2, y2);
var x = getX(), y = getY();// getX and getY get the user's new point.
if (isValid(x, y)) {
// Draw
}
This approach also gives you some flexibility—you could always modify the function to be less precise to accommodate people who don't quite draw a straight line but are tolerably close.
Precision:
As mentioned in my comment, you can change the way the function behaves to make it less exacting. I think a good way to do this is as follows:
Right now, we are using the formula (y - y1) == slope * (x - x1). This is the same as (slope * (x - x1)) - (y - y1) == 0. We can change the zero to some positive number to make it accept points "near" the valid line as so:
Math.abs((slope * (x - x1)) - (y - y1)) <= n
Here n changes how close the point has to be to the line in order to count.
I'm pretty sure this works as advertised and helps account for people's drawing the line a little crooked, but somebody should double check my math.
A: function drawGraphLine(x1, y1, x2, y2, color) {
var dist = Math.ceil(Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
var angle = Math.atan2(y2-y1, x2-x1)*180/Math.PI;
var xshift = dist - Math.abs(x2-x1);
var yshift = Math.abs(y1-y2)/2;
var div = document.createElement('div');
div.style.backgroundColor = color;
div.style.position = 'absolute';
div.style.left = (x1 - xshift/2) + 'px';
div.style.top = (Math.min(y1,y2) + yshift) + 'px';
div.style.width = dist+'px';
div.style.height = '3px';
div.style.WebkitTransform = 'rotate('+angle+'deg)';
div.style.MozTransform = 'rotate('+angle+'deg)';
}
// By Tomer Almog
| |
doc_2834
|
After building my application i get my jar file as xxx-common-0.0.1.jar
this is getting deployed into my artifactory as
http://localhost:8800/artifactory/core-release/com/xxx/xxx-common/0.0.1/xxx-common-0.0.1.jar
That deployment is good,
Here, how can I eliminate version number getting appended " xxx-common-0.0.1.jar " and need it just as " xxx-common.jar "
Kindly help out to overcome this problem guys...
Sorry it didn't worked out
Below is what i gave....
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<finalName>${project.artifactId}</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
executed using
mvn package
and
Installing /home/xxx/build-deploy-tools/.jenkins/jobs/workspace/xxx-common/target/xxx-common.jar to /home/xxx/.m2/repository/com/xxx/xxx-common/0.0.1/xxx-common-0.0.1.jar
Still it pushes as xxx-common-0.0.1.jar
A: In your repository, you cannot ever get rid of the numbers. In your target directory, you can use a finalName element in the configuration of the Maven JAR Plugin.
A: You can define it at the outputFileNameMapping config option for you project.
This option defaults to
${module.artifactId}-${module.version}${dashClassifier?}.${module.extension}
So, in your case, you could change it to
${module.artifactId}.${module.extension}
Reference: http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html
| |
doc_2835
|
This crashes happened only one time on each device but i think that there is some problem. When i open "Open in project" - i don't see where exactly in my project this crash occurs. As i see - this happens when Core Data runs object delete method.
I use Core Data to store cache and each time i receive new data from server - i clear all core data entities one by one and then create new. This is my function to clear cache. (This code is used to have iOS 7 support)
func clearCache() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("CacheItems", inManagedObjectContext: managedObjectContext)
fetchRequest.includesPropertyValues = false
do {
let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
for result in results {
managedObjectContext.deleteObject(result)
}
} catch {
let nserror = error as NSError
NSLog("CoreData erasing error - \(nserror), \(nserror.userInfo)")
}
// checking Cache items count
do {
let fetchRequest = NSFetchRequest(entityName: "CacheItems")
myCacheItems = try managedObjectContext.executeFetchRequest(fetchRequest) as! [CacheItemsClass]
} catch let error as NSError {
print("\(error.localizedDescription)")
} }
| |
doc_2836
|
public String TodayFirst()
{
String time ="";
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY,9);
time = df.format(calendar.getTime());
}
A: java.time
LocalTime now = LocalTime.now(ZoneId.systemDefault());
if (now.isAfter(LocalTime.of(9, 0))) {
System.out.println("It’s past 9");
}
Notice how much clearer it reads than the code in your question.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
*
*In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
*In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
*On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp (with subpackages).
What went wrong in your code?
You need a return statement in your method. Assuming you wanted to return time, the method produces a string like 2018/08/28 09:21:03. The hours have been set to 9, but the minutes and seconds are unchanged from the current time. Also you are producing a similar string for current system time, but not comparing the two.
Links
*
*Oracle tutorial: Date Time explaining how to use java.time.
*Java Specification Request (JSR) 310, where java.time was first described.
*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
*ThreeTenABP, Android edition of ThreeTen Backport
*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
A: For that you should use Alarm Manager.
from here you get how to use Alarm Manage.
Alarm manager work on system clock
This alarm manager will send one broadcast at every 9:00 Am. using that Broadcast you can do for other stuff.
A: You could do as belows:
public String TodayFirst()
{
String time;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY,9);
calendar.set(calendar.MINUTE,0);
calendar.set(calendar.SECOND,0);
time = df.format(calendar.getTime());
return time; //time will be 2018/08/28 09:00:00 if you call the function today
}
| |
doc_2837
|
Visual Studio (2008) always tells me that project A is "out of date," and prompts me to ask if I want to rebuild it, every time I want to run/debug/build/etc. Even immediately after building the entire Solution: I do a successful full build, and then click Build again, and it wants to re-link Project A.
How can I prevent this from happening? Anyone understand what's going on here?
A: I think that the solution is to stop using .obj files from the other project. Instead, factor the code that is common to both A and B projects into own static library C and link both A and B to it.
A: I just had this problem with Visual Studio 2010 (both with and without SP1) and thanks to Ted Nugent I was able to fix it. The trick is to check whether all C++ header files listed in the project still exist, and remove the non-existing ones. Apparently this is a bug in the compiler.
A: Had something similar occur. I was working with code that used the system time and during the debug I was twiddling with it quite a lot. Somehow the files got some bad timestamps. In the build, it shows which files are getting recompiled, so I just opened each, forced a change (add space, delete a space) and then re-saved.
Similar to the old unix "touch".
In one project I had to do the same to its include files. But after 'touching' the files like that, the problem went away.
| |
doc_2838
|
Here is my HTML code
<td class="kt-datatable__cell">
<span style="overflow: visible; position: relative; width: 197px;">
<center>
<div class="dropdown">
<a data-toggle="dropdown" class="btn btn-sm btn-clean btn-icon btn-icon-md" @click="toggleHover(index)"
v-bind:class="{'show': hover[index]}">
<i class="flaticon2-shield"></i>
</a>
<div v-bind:class="{'show': hover[index]}" class="dropdown-menu">
And here is my method that I call using @click
methods: {
toggleHover(index) {
this.hover[index] = !this.hover[index];
}
If I set true for a random position right after I get the data from the server, it shows, but when I try to change this by clicking, nothing happens.
A: It's a reactivity caveat, so you should do :
methods: {
toggleHover(index) {
this.$set(this.hover,index , !this.hover[index]);
}
| |
doc_2839
|
tbl_answers =>
aid
qid
answer
uid
dateposted
emailnotify
namedisplay
status
isbestanswer
tbl_questions =>
qid
question
detail
mcid
cid
uid
answercount
dateposted
status
showname
emailnotify
question_type_id
I tried this:
UPDATE tbl_questions
JOIN (
SELECT id, COUNT(*) AS n
FROM tbl_questions JOIN tbl_answers ON qid = tbl_questions.qid
WHERE answercount = "0"
GROUP BY id
) AS T USING (id)
SET num = n
WHERE n > 0
I woud like to update those question that has got more answers than it's counted in:
tbl_questions => answercount
How can I update the rows which have got more questions than it's counted? (Without php loop)
A: UPDATE tbl_questions
JOIN (
SELECT tbl_questions.qid, COUNT(*) AS n
FROM tbl_questions JOIN tbl_answers ON tbl_answers.qid = tbl_questions.qid
GROUP BY qid
) AS T USING (qid)
SET answercount = n
WHERE n > 0'
| |
doc_2840
|
Let me explain to you with an example,
I have 2 events one is for Monday and another one is for Friday, so when I see the list view it shows only 2 rows (Monday and Friday). But I want that all days will appear and show events with days that have and the days which don't have events should show no event tag.
Any kind of help is appreciable.
| |
doc_2841
|
So far 'CURLOPT_HEADER' has been set to false in my php script (se below), but now I've set it to true so that I can receive the headers and take actions depending on the header. Here I need help.
I actually have two things I need help with (which are connected to each other):
*
*If the connection is working between my API and the sources and I set CURLOPT_HEADER to false in my php script (se below) everything works as supposed. However, if I turn it to true the actual header is sent back with the ajax request as well, which returns in an error: "Uncaught SyntaxError: Unexpected token H" (line 10 in the js code below).
*I don't have a clue on how to handle the error, if the connection is down between my API and the sources, and the API therefore returns '502 Bad Gateway'. I want the php script to send that information back with the ajax request, so it can be handled in the js file.
So, please help me out here. Thanks in advance!
PHP:
$url = 'http://theurl.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
if(!$response) {
// <--- ??
}
curl_close($ch);
echo json_encode($response);
JS:
1. $.ajax({
2. url:'./php/apihandling.php',
3. type:'post',
4. dataType:'json',
5. data:{
6. data: data
7. },
8. success: function(data) {
9. var content = JSON.parse(data);
10. console.log(content);
11. },
12. error: function (xhr, ajaxOptions, thrownError) {
13. console.log(xhr.status);
14. console.log(thrownError);
15. }
16. });
A: You can use to curl_errno check how your API responds to your request, you can also try to use a API "status flag" to avoid errors in your JQuery
...
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
//close the connection
curl_close($ch);
$result["API_status"]=0;
$result["error"]=$info;
//kill the script and echo the json
die(json_encode($result));
}
else
{
$result["API_status"]=1;
curl_close($ch);
$result["response"]=$response;
echo json_encode($result);
}
Now let's give a try to your jquery script
$.ajax({
url: './php/apihandling.php',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function(data) {
//no need for this, datatype is json already
//var content = JSON.parse(data);
if (data["API_status"]) {
alert("wow API is up and healthy");
//do some stuff with the json
$.each(data["response"], function(index, value) {
//loop this
});
} else {
alert("Oh, no. RIP API");
console.log(data["error"]);
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
| |
doc_2842
|
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
Animator anim;
// Start is called before the first frame update
void awake()
{
anim = GetComponent <Animator>();
}
private void OnEnable()
{
Invoke("OnDisable", 2f);
}
private void OnDisable()
{
gameObject.SetActive(false);
}
// Update is called once per frame
public void StartExplosion(string target)
{
Debug.Log("startExplosion");
anim.SetTrigger("OnExplosion");
Debug.Log("startExplosion2");
switch (target)
{
case "doge":
transform.localScale = Vector3.one * 1.2f;
break;
case "dogelonmas":
transform.localScale = Vector3.one;
break;
case "RocketA":
transform.localScale = Vector3.one;
break;
case "RocketB":
transform.localScale = Vector3.one;
break;
case "samo":
transform.localScale = Vector3.one;
break;
case "shiba":
transform.localScale = Vector3.one;
break;
case "jindoge":
transform.localScale = Vector3.one;
break;
}
Debug.Log("startExplosion3");
}
}
Hey guys, I am dying from frustration now, I'd be super grateful if anybody can help.
So I am getting the error "NullReferenceException : Object reference not set to an instance of an object" when it tries to execute anim.SetTrigger in my StartExplosion().
It is extremly frustrating to keep getting this error. As you can see I put a trigger "OnExplosion" for the condition of the explosion, and there is never a type and set up everything correctly I believe.
A: I see that your Animator anim is in a method called: awake(). It is important that you check the capitalization of your methods. I'm guessing you wanted to use the Awake() method that Unity has built-in. However, awake() and Awake() are not the same. Since awake() does not get called when the script instance is loaded, the method awake() never gets used and Animator anim never gets set to anything. To resolve this:
Animator anim;
private void Awake()
{
anim = gameObject.GetComponent<Animator>();
}
| |
doc_2843
|
A: Use YearMonth class:
YearMonth yearMonth = YearMonth.parse("2019-02");
LocalDate startDate = yearMonth.atDay(1); // 2019-02-01
LocalDate endDate = yearMonth.atEndOfMonth(); // 2019-02-28
You can then convert to LocalDateTime e.g. if you need start of day time:
LocalDateTime startDayTime = startDate.atStartOfDay(); // 2019-02-01T00:00
| |
doc_2844
|
I have tried to initialize an object before the ajax call, then assigning the response fron inside the success but that didn't work either.
Any ideas?
Example code
var p = {};
loadLang('en');
function loadLang(code) {
Ext.Ajax.request({
url : '/LoadLanguage.html',
method : 'POST',
params :{'code':code},
timeout : 250,
success : function(response, opts) {
obj = Ext.decode(response.responseText);
p = obj;
},
callback : function(o,s,r)
{
}
});
}
A: var myValue={item:"pie"};
Ext.Ajax.request({
url: 'test.php',
params: {
id: 1
},
success: function(response){
alert(response);
window.myValue.response=response; //yay for global scope.
console.log(window.myValue);//This has to be here,
//else it gets logged before the call gets completed.
}
});
| |
doc_2845
|
class weapon():
def __init__(self, Name, Type, Description):
self.Name=Name
self.Type=Type
self.Description=Description
WEAPONS = { "starterSword":weapon("Starter Sword", "Sword", "A short, stunt steel sword."),
"basicSword":weapon("Basic Sword", "Sword", "A basic steel sword.")
}
And I want to do something like this:
for item in WEAPONS:
print(self.Name)
How would I go about doing it in Python 3?
A: Just iterate over the values:
for item in WEAPONS.values():
print(item.Name)
A: As @MSeifert said. Anyway, iterating over a dictionary gives you the key and value for every item. So this works, too:
for key, value in WEAPONS.items():
print(value.Name)
By the way: Why are you using a dictionary? Since each weapon holds its own name.
A: Best when you write the methods inside the class (OOP) and call them without having to write lots of code e.g.
class weapon():
def __init__(self, Name, Type, Description):
self.Name=Name
self.Type=Type
self.Description=Description
def printDetails(self):
print (self.Name)
WEAPONS = { "starterSword":weapon("Starter Sword", "Sword", "A short, stunt steel sword.").printDetails(),
"basicSword":weapon("Basic Sword", "Sword", "A basic steel sword.").printDetails()
}
Will give you the desired output.
| |
doc_2846
|
One end is copying a C structure into the pipe:
struct EventStruct e;
[...]
ssize_t n = write(pipefd[1], &e, sizeof(e));
The other end reads it from the pipe:
struct EventStruct e;
ssize_t n = read(pipefd[0], &e, sizeof(e));
if(n != -1 && n != 0 && n < sizeof(e))
{
// Is a partial read possible here??
}
Can partial reads occur with the anonymous pipe?
The man page (man 7 pipe) stipulates that any write under PIPE_BUF size is atomic. But what they mean is atomic regarding other writers threads... I am not concerned with multiple writers issues. I have only one writer thread, and only one reader thread.
As a side note, my structure is 56 bytes long. Well below the PIPE_BUF size, which is at least 4096 bytes on Linux. It looks like it's even higher on most recent kernel.
Told otherwise: on the reading end, do I have to deal with partial read and store them meanwhile I receive a full structure instance?
A: As long as you are dealing with fixed size units, there isn't a problem. If you write a unit of N bytes on the pipe and the reader requests a unit of N bytes from the pipe, then there will be no issue. If you can't read all the data in one fell swoop (you don't know the size until after you've read its length, for example), then life gets trickier. However, as shown, you should be fine.
That said, you should still detect short reads. There's a catastrophe pending if you get a short read but assume it is full length. However, you should not expect to detect short reads — code coverage will be a problem. I'd simply test n < (ssize_t)sizeof(e) and anything detected is an error or EOF. Note the cast; otherwise, the signed value will be converted to unsigned and -1 won't be spotted properly.
For specification, you'll need to read the POSIX specifications for:
*
*read()
*write()
*pipe()
and possibly trace links from those pages. For example, for write(), the specification says:
Write requests to a pipe or FIFO shall be handled in the same way as a regular file with the following exceptions:
*
*There is no file offset associated with a pipe, hence each write request shall append to the end of the pipe.
*Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.
Or from the specification of read():
Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.
So, the write() will write atomic units; the read() will only read atomic units because that's what was written. There won't be a problem, which is what I said at the start.
| |
doc_2847
|
var count: String? {
get { viewCountLabel.text }
set {
viewCountLabel.text = newValue
viewsTitleLabel.text = newValue == "1" ? "View" : "Views"
}
}
and a convenience init like:
convenience init(count: String) {
self.init()
self.count = count
}
This view conforms to UIViewRepresentable as the following:
extension ViewCountView: UIViewRepresentable {
typealias UIViewType = ViewCountView
func makeUIView(context: Context) -> UIViewType {
UIViewType(frame: .zero)
}
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<UIViewType>) {}
}
This works on the target as expected.
- Question: How should I pass the count to the preview in live view?
I tried to pass the count on the initializer of the preview like the following but it doesn't work. I think I should pass the count in the form of Context somehow.
struct ViewCountView_Previews: PreviewProvider {
static var previews: some View {
Group {
ViewCountView(count: "0")
ViewCountView(count: "12m")
ViewCountView(count: "41234")
}
}
Please Note That since I need more than 1 preview, I can't write values statically inside makeUIView or updateUIView.
A: Add a binding var to your UIViewRepresentable:
@Binding var count: String
Then change updateUIView:
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<UIViewType>) {
uiView.count = count
}
A: Simple wrapper struct - Works like a native:
struct <#NameOfTheWrapperView#>: UIViewRepresentable {
typealias TheUIView = <#AnyUIView#>
var configuration = { (view: TheUIView) in }
func makeUIView(context: UIViewRepresentableContext<Self>) -> TheUIView { TheUIView() }
func updateUIView(_ uiView: TheUIView, context: UIViewRepresentableContext<Self>) {
configuration(uiView)
}
}
Completely customizable
ResponderTextField() {
$0.backgroundColor = .red
$0.tintColor = .blue
}
So $0 points to the exact type and can be edited in anyway that you could in UIKit originally.
Note That I made it like a gist, so you can easily copy and paste it in your code and just need to name it and define the original UIView type you need to use.
| |
doc_2848
|
I have deployment config
---
apiVersion: apps/v1
kind: Deployment
...
spec:
containers:
- configMapRef:
name: **testa**-env
My config map testa-env looks
apiVersion: v1
kind: ConfigMap
data:
AAAA: testA
Also i have another deployment in same namespace with config map BBB: testB
Then i go to my pods and make export and see that configs has been merged?! On podA i see both configs
podA> export
AAAA: testA
BBBB: testB
Also looks output on pod B.
So another developer can steal all config not for his project!
I have been rechecked this on 3 different clusters and have same result
| |
doc_2849
|
*
*Device and APN are set to debug/development
*I can successfully register device token
*I have an active .p8 key with push notification services
*APN says the push message was sent successfully
*didReceiveRemoteNotification doesn't fire
*Tried with app in background and foreground
*using AWS: inbound - port 22, outbound - all ports
This is the response:
{"sent":[{"device":"cc7ec9a821cf232f9510193ca3ffe7d13dd756351794df3f3e44f9112c037c2a"}],"failed":[]}
Here is my code:
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var deviceTokenString: String = ""
for i in 0..<deviceToken.count {
deviceTokenString += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
UserDefaults.standard.set(deviceTokenString, forKey: "push_token")
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
print("\(notification.request.content.userInfo)")
completionHandler([.alert, .badge, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("\(response.notification.request.content.userInfo)")
completionHandler()
}
}
XCode:
Node.js
.p8 key is from Developer Console: Keys > All
var apn = require('apn');
var apnProvider = new apn.Provider({
token: {
key: "/path/to/AuthKey_1234ABCD.p8",
keyId: "1234ABCD",
teamId: "1234ABCD"
},
production: false
});
var note = new apn.Notification();
note.topic = "com.company.app";
note.payload = {
aps: {
"content-available" : 1
},
custom_field: {}
};
apnProvider.send(note, push_token).then(result => {
console.log('result: ', result);
console.log("sent:", result.sent.length);
console.log("failed:", result.failed.length);
});
A: I appreciate everyone's input, I figured out the issue.
'aps' does not belong in the payload field, but instead should be in the Notification constructor.
Node.js:
var note = new apn.Notification({
aps: {
"content-available" : 1
}
});
note.payload = {
custom_field_1: {},
custom_field_2: ''
};
A: I'm not sure if this is the case as your server is using this APN node module and I never used it, but I use Firebase and everytime I tried using content_available : 1, it didn't work. What did work was content_available : true.
Hope this works for you.
A: You wrote this on your AppDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Silent push notification received: \(userInfo)")
}
But then you also wrote:
center.delegate = notificationDelegate
which means you're AppDelegate isn't the notificationCenter's delegate.
either change that to
center.delegate = self
Or just remove that function to the class that adopts it ie your UYLNotificationDelegate
You seem to have it all right. Though I don't know how to read node.js so you may have configured your payload incorrect. Also sometimes if the server isn't managing multiple device tokens correctly you may not get a silent notification at all or another issue we have with our backend was that they were redirecting the notifications server to their local machine while we're testing the notifications, obviously they weren't coming in!
A sample payload from Apple should look like this:
{
"aps" : {
"content-available" : 1
},
"acme1" : "bar",
"acme2" : 42
}
Are you sure your generated payload has a similar format?!
*
*I wrongly suggested to that you should change center.delegate = notificationDelegate to center.delegate = self but if I was that desperate I'd give that a try :D.
*Make sure background App Refresh is enabled (though still without that enabled you should receive in foreground
*If this doesn't work, then try sending it with an alert/badge and see
if that works. Likely it won't work :/
*Delete the app and then
install it again. Sometimes the authorizations don't work correct if
you just reinstall.
*clean derived data, clean build, restart Xcode.
After your EDIT:
You shouldn't have deleted the didReceiveRemoteNotification <-- this is for retrieving any push notification that has content-available : 1.
*
*The willPresent is callback for what to do if app is in FOREGROUND. Only applicable if payload has alert or badge or sound in payload.
*The didReceiveNotificationResponse is NOT what you think it is. It's for handling managing what action the user chose from the notification e.g. your notification has two actions (Snooze, delete) to click like below:
You handle the Response to the notification using this callback.
*
*The application(_:didReceiveRemoteNotification:fetchCompletionHandler:) is used for retrieving the notification upon arrival.
So technically speaking if you just have a silent notification you would only get the third callback and not the first two.
If you had an app in the foreground and the payload had: content-available :1 which also had actions and the user tapped on the action then you would first get the the 3rd callback, then the 1st callback and then the 2nd callback.
| |
doc_2850
|
This is my code.
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->trackConnButton->setEnabled(false);
}
void MainWindow::on_confirmButton_clicked() {
if (ui->usernameText == "name" && ui->passwordText == "password") {
ui->resullabel->setText("Password accepted.");
ui->trackConnButton->setEnabled(true);
} else {
ui->resullabel->setText("Password denied.");
}
}
MainWindow::~MainWindow()
{
delete ui;
}
I get this error:
D:\Qt-Projekte\test3\mainwindow.cpp:12: Fehler: no 'void MainWindow::on_confirmButton_clicked()' member function declared in class 'MainWindow'
void MainWindow::on_confirmButton_clicked() {
^
My question is now: how to fix it?
Thanks in advance.
my mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
A: All member functions of a class must contain a "declaration" and a "definition".
For example:
struct Foo {
// Declarations
void foo() const;
int bar(int x);
};
// Definitions
void Foo::foo() const {
std::cout << "foo" << std::endl;
}
int Foo::bar(int x) {
return x + 1;
}
(Note that if you define a function inline in a class, it counts as both definition and declaration):
struct Foo {
// Declaration AND definition
void foo() const {
std::cout << "foo inline" << std::endl;
}
};
So in your case, you must declare the on_confirmButton_clicked function inside the definition of class MainWindow.
| |
doc_2851
|
WSO2 ESB - writing files out of base64
However, in the answer to that question there was no mention of how to decode the Base64 string in JavaScript and attach it to the payload. That's what I'm interested in.
Thanks in advance,
Strainy
A: Went with a slightly different approach. I created a utility proxy service to re-download the file and then push it into the file system.
utilty_createFile Proxy Service
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="utility_createFile"
transports="https,http"
statistics="disable"
trace="disable"
startOnLoad="true">
<target inSequence="utility_createFile_IN" outSequence="utility_createFile_OUT"/>
<description/>
</proxy>
utility_createFile_IN Sequence
<?xml version="1.0" encoding="UTF-8"?>
<sequence name="utility_createFile_IN" onError="fault" xmlns="http://ws.apache.org/ns/synapse">
<property name="FORCE_SC_ACCEPTED" scope="axis2" value="true"/>
<property expression="//createFile/download_folder"
name="uri.var.download_folder" xmlns:ns="http://org.apache.synapse/xsd"/>
<property expression="//createFile/url" name="uri.var.download_url" xmlns:ns="http://org.apache.synapse/xsd"/>
<script language="js"><![CDATA[var download_url = mc.getProperty('uri.var.download_url');
download_url = decodeURIComponent(download_url);
mc.setProperty('uri.var.download_url', download_url);]]></script>
<send>
<endpoint>
<http method="GET" uri-template="{uri.var.download_url}"/>
</endpoint>
</send>
</sequence>
utility_createFile_OUT Sequence
<?xml version="1.0" encoding="UTF-8"?>
<sequence name="utility_createFile_IN" onError="fault" xmlns="http://ws.apache.org/ns/synapse">
<property name="FORCE_SC_ACCEPTED" scope="axis2" value="true"/>
<property expression="//createFile/download_folder"
name="uri.var.download_folder" xmlns:ns="http://org.apache.synapse/xsd"/>
<property expression="//createFile/url" name="uri.var.download_url" xmlns:ns="http://org.apache.synapse/xsd"/>
<script language="js"><![CDATA[var download_url = mc.getProperty('uri.var.download_url');
download_url = decodeURIComponent(download_url);
mc.setProperty('uri.var.download_url', download_url);]]></script>
<send>
<endpoint>
<http method="GET" uri-template="{uri.var.download_url}"/>
</endpoint>
</send>
</sequence>
| |
doc_2852
|
Circle X Y
A 21 8
A 32 17
A 23 32
B 22 4
B 43 12
C 12 4
How do I plug this data and create a new data frame into this equation:
Vxn = ((X(max value))-(X(min value)))/(Frequency of each unique circle)
A: We can group by 'Circle', loop across the 'X', 'Y', columns get the difference of max, min value of that column divided by the number of elements, create new columns with suffix '_scale' by specifying the .names
library(dplyr)
df2 <- df1 %>%
group_by(Circle) %>%
mutate(across(c(X, Y), ~ (max(.) - min(.))/n(), .names = '{.col}_scale')) %>%
ungroup
-output
df2
# A tibble: 6 x 5
# Circle X Y X_scale Y_scale
# <chr> <int> <int> <dbl> <dbl>
#1 A 21 8 3.67 8
#2 A 32 17 3.67 8
#3 A 23 32 3.67 8
#4 B 22 4 10.5 4
#5 B 43 12 10.5 4
#6 C 12 4 0 0
data
df1 <- structure(list(Circle = c("A", "A", "A", "B", "B", "C"), X = c(21L,
32L, 23L, 22L, 43L, 12L), Y = c(8L, 17L, 32L, 4L, 12L, 4L)),
class = "data.frame", row.names = c(NA,
-6L))
| |
doc_2853
|
I have a function using coroutines:
fun onAuthenticated() {
launch (Dispatchers.IO) {
userRepo.retrieveSelf()!!.let { name ->
userRepo.addAuthenticatedAccount(name)
userRepo.setCurrentAccount(name)
}
activity?.setResult(Activity.RESULT_OK, Intent())
// this block doesn't seem to be run
withContext(Dispatchers.Main) {
Log.d(TAG, "ok looks gucci")
activity?.finish()
}
}
}
When this function is called, the code in the withContext(Dispatchers.Main) { ... } block doesn't run. I'm using it to access the activity in the main thread.
I've been getting kind of frustrated and I'm not sure if I don't understand how the dispatcher/coroutine is supposed to work or there's something I'm missing.
Let me know if you need any additional details or code!
EDIT
So Marko was right. After I moved the activity.?.setResult(Activity.RESULT_OK, Intent()) so that it was being run with the main dispatcher, I found out there was another part of the code in userRepo.setCurrentAccount(name) that was giving an issue. After updating the code as seen below, it works as expected!
override fun onAuthenticated() {
val handler = CoroutineExceptionHandler { _, e ->
Snackbar.make(
web_auth_rootview,
"Authentication unsuccessful",
Snackbar.LENGTH_INDEFINITE
).show()
}
launch(Dispatchers.Main + handler) {
userRepo.retrieveSelf()!!.let { name ->
userRepo.addAuthenticatedAccount(name)
userRepo.setCurrentAccount(name)
}
activity?.apply {
setResult(Activity.RESULT_OK, Intent())
onBackPressed()
}
}
}
Big Thanks to Marko for helping me out!
A: activity?.setResult(Activity.RESULT_OK, Intent())
Here you try to touch a GUI component from the IO thread. This probably throws an exception, but since it's on the IO thread, nothing catches it.
You can wrap everything in a try-catch, but your program would automatically work better if you used the proper idiom, which is to launch in the Main dispatcher and only switch to the IO context for the blocking operations:
launch(Dispatchers.Main) {
withContext(Dispatchers.IO) {
userRepo.retrieveSelf()!!.let { name ->
userRepo.addAuthenticatedAccount(name)
userRepo.setCurrentAccount(name)
}
}
activity?.setResult(Activity.RESULT_OK, Intent())
Log.d(TAG, "ok looks gucci")
activity?.finish()
}
Now, if you get an exception in the IO dispatcher, it will propagate to the top-level coroutine, which will cause an exception on the main thread, and your application will crash with it. This is a solid foundation to add your error handling logic on top of.
Of course, this is still not the way you should work with coroutines because you're missing the structured concurrency aspect.
| |
doc_2854
|
*
*24 inputs with 10 features (one input per hour so 24 hours of input data)
*1 output being a temperature
The model works, I'm all fine with that, however I need to present the way the model works and I'm unsure how some values I see about the model describe it. I'm struggling to visually represent the inner structure (as in the neurons or nodes).
Here is the model (The static input_shape is not set statically in my code, it is purely to help answer the question):
forward_layer = tf.keras.layers.LSTM(units=32, return_sequences=True)
backward_layer = tf.keras.layers.LSTM(units=32, return_sequences=True, go_backwards=True)
bilstm_model = tf.keras.models.Sequential([
tf.keras.layers.Bidirectional(forward_layer, backward_layer=backward_layer, input_shape=(24, 10)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.LSTM(32, return_sequences=True),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.LSTM(32, return_sequences=True),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.LSTM(32, return_sequences=False),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(units=1)
])
Note that the reason I seperated the layers for the Bidirectional is because I am running this with TFLite and had issues if the two weren't pre-defined but the inner workings are the same as far as I understand it.
Now as some experts have probably already figured out just looking at this, the input shape is (32, 24, 10) and the output shape is (32, 1) where the input is under the (batch_size, sequence_length, features) format and the output is under the (batch_size, units) format.
As well as I feel I understand what the numbers represent, I can't quite wrap my head around how the model would "look". I mainly struggle to differentiate the structure during training and during predictions.
Here are the ideas I have (note that I will be describing the model based on neurons):
*
*Input is a 24x10 DataFrame
*The input is therefore 240 values which can be seen as 24 sets of 10 neurons ? (Not sure I'm right here)
*return_sequences means that the 240 values propagate throughout the model ? (Still not sure here)
*The 'neuron' structure would ressemble this:
Input(240 neurons) -> BiLSTM(240 neurons) ->
Dropout(240 neurons, 20% drop rate) -> LSTM(240 neurons) ->
Dropout(240 neurons, 20% drop rate) -> LSTM(240 neurons) ->
Dropout(240 neurons, 20% drop rate) -> LSTM(240 neurons) ->
Dropout(? neurons, 20% drop rate) -> Dense(1 neurons) = Output
If I'm not mistaken, the Dropout layer isn't a layer strictly speaking but it stops (in this case) 20% of the input neurons (or output, I'm not sure) from activating 20% of the output neurons.
I'd really appreciate the help on visualising the structure so thanks in advance to any brave soul ready to help me out
EDIT
Here is an example of what I am trying to get out of the numbers. Note that this image ONLY represents the first BiLSTM layer, not the whole model.
The x ? in the image represent what I'm trying to understand, ie how many layers are there and how many neurons are there in each layer
| |
doc_2855
|
<div class="selector">
<div class="nomination selectors-part">Year</div>
<div class="selection mini">
<select name="seltoYear">
<option selected disabled>Till</option>
<option value="2015">2015</option>
<option>2014</option>
<option>2013</option>
<option>2012</option>
<option>2011</option>
</select>
</div>
<div class="selection mini">
<select name="selfromYear">
<option selected disabled>From</option>
<option>1956</option>
<option>1986</option>
<option>1993</option>
<option>1994</option>
<option>1995</option>
<option>1996</option>
</select>
</div>
<div class="clear"></div>
</div>
I trying to set selected value back after POSt, but nothing hapins
$(function() {
$('div.list input[type=checkbox]').on('change',onValueChange);
$('div.selector select').on('change', onValueChange);
function onValueChange() {
var Checked = {};
var Selected = {};
// Hold all checkboxes
$('div.list input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {
Checked[name] = [];
}
Checked[name].push($el.val());
});
// Hold all dropdowns
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Selected[name]) === 'undefined') {
Selected[name] = [];
}
Selected[name].push($el.val());
});
// Put all together to POST
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(Checked) + "&" + $.param(Selected),
dataType: 'text',
success: function (data) {
$("#ExSearchForm").html(data)
.find('div.list input[type=checkbox],div.selector select').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1) {
$el.prop('checked', true);
}
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
});
}
});
};
});
Checkboxes are selecting as well but dropdowns do not want to be selected.
A: To set the select elements, you have to use val() like
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.val(value);
}
Note, the way you calculate value will not work as your select element does not have an attribute of value
See Set selected option of select box
Update
Change
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Selected[name]) === 'undefined') {
Selected[name] = [];
}
Selected[name].push($el.val());
});
to
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
Selected[name] = $el.val();
});
and
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.prop('selected', true);
}
to
if (Selected[name]) {
$el.val(Selected[name]);
}
A: Try this,
if (Selected[name] && Selected[name].indexOf(value) !== -1) {
$el.attr('selected', 'selected');
}
| |
doc_2856
|
SQFTCost: (([SUPPLY_MASTER]![LAST_COST]+[SUPPLY_MASTER]![FREIGHT_COST])/[SUPPLY_MASTER]![SQFT_PER_CTN])
In this case, LAST_COST is a decimal with a precision of 9 and a scale of 3. FREIGHT_COST is is a decimal with a precision of 8 and a scale of 3, and SQFT_PER_CTN is a decimal with a precision of 7 and a scale of 3.
Whenever I run the make table query, that column and all the others like it are filled with nulls. I know that they are actually null, because I tested that in a routine that I wrote.
However, if I change the query to a SELECT query, all is well. The values are correct.
Does anyone have any idea what can be done to fix this? I am using Access 2003.
A: Just a few suggestions:
*
*Try adding a cLng() or something equivalent in front of your expressions, to force a well defined data type
*I avoid Make Table queries, preferring Append queries. Just make an "template" table properly set up, and use a copy with Append queries. It's the only way to have a clean design.
A: I have come across the correct answer to this issue. It is the result of a sometimes flaky ODBC driver that we are using here. Our data rests in COBOL files that are in the Vision file format. The trouble is coming from using fields that are defined in the xfds as REDEFINES of other fields in the file. Using the original field fixes the issue.
| |
doc_2857
|
The problem is that there are different threads that invoke the event handler and disposes the EventReceiver. The event will be called after the unsubscribe is done. There's a race condidition between event raising and unsubscribing.
How could that be solved?
Here's a sample implementation that demonstrates the problem:
internal class Program
{
private static void Main(string[] args)
{
var eventSource = new EventSource();
Task.Factory.StartNew(
() =>
{
while (true)
{
eventSource.RaiseEvent();
}
});
Task.Factory.StartNew(
() =>
{
while (true)
{
new EventReceiver(eventSource).Dispose();
}
});
Console.ReadKey();
}
}
public class EventSource
{
public event EventHandler<EventArgs> SampleEvent;
public void RaiseEvent()
{
var handler = this.SampleEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
public class EventReceiver : IDisposable
{
private readonly EventSource _source;
public EventReceiver(EventSource source)
{
this._source = source;
this._source.SampleEvent += this.OnSampleEvent;
}
public bool IsDisposed { get; private set; }
private void OnSampleEvent(object sender, EventArgs args)
{
if (this.IsDisposed)
{
throw new InvalidOperationException("This should never happen...");
}
}
public void Dispose()
{
this._source.SampleEvent -= this.OnSampleEvent;
this.IsDisposed = true;
}
}
The exception will be thrown nearly direct after program start on a multi core processor. Yes I know that var handler = this.SampleEvent will create a copy of the event handler and that causes the problem.
I tried to implement the RaiseEvent method like that but it doesn't help:
public void RaiseEvent()
{
try
{
this.SampleEvent(this, EventArgs.Empty);
}
catch (Exception)
{
}
}
The question is: How to implement threadsafe registering to and unregistering from events in a multithreaded manner?
My expectation was that the unregistering will be suspended until the current fired event has been finished (meybe this could only work using the second implementation). But I was disappointed.
A: If you've got two threads - one calling the event handlers, and one unsubscribing - there will always be a race condition, where you end up with the following ordering:
*
*Event-raiser starts to raise the event
*Event-unsubscriber unsubscribes
*Event-raiser executes handler
That's inevitable with the immutability of delegates in .NET. Even with some sort of thread-safe, mutable delegate type there'd always be a finer-grained race condition:
*
*Event-raiser starts to raise the event
*Event-raiser starts to execute handler - but it hasn't yet got to the first line of user code
*Event-unsubscriber unsubscribes
*Handler executes user code
Worse, you could unsubscribe while the handler is executing - what would you expect to happen then? Would you expect the handler code to be arbitrarily terminated?
You can easily implement your own check for "am I really meant to run at this point" within the handler, but you'll need to work out your own semantics. You could use locking to make sure that the handler unsubscription can't occur while the handler is executing, but that feels pretty dangerous to me, unless you know that your event handler will complete in a short time frame.
| |
doc_2858
|
There is SupplierID , SupplierName , SupplierProduceType , SupplierPhone going into the Supplier table
I have no trouble with the ID,name and phone however produce type is difficult as there is 1-5 options which can be selected
i want the textbox to display beef,pork,chicken,lamb,sauce (separated by commas) if there 5 are checked, obviously if only 3 are selected i want only those 3 to show
when i hit the add supplier button, the sql code will be:
sql = "INSERT INTO[Supplier](SupplierID, SupplierName, SupplierProduceType, SupplierPhone) Values('" + Convert.ToInt32(SupplierIDTB.Text) + "', '" + SupplierNameTB.Text + "', '" + SupplierProduceTypeTB.Text + "', '" + Convert.ToInt32(SupplierPhoneTB.Text) + "')";
So when the sql code reads from the SupplierProduceTypeTB.Text it will read "beef,pork,chicken,lamb,sauce" (if all 5 are checked) and input that into the SupplierProduceType column
So far i have:
protected void BeefCB_CheckedChanged(object sender, EventArgs e)
{
String input1 = "beef,";
SupplierProduceTypeTB.Text += input1;
}
but this does nothing!
A: You just only need to change a little bit in your code.
try below code
protected void BeefCB_CheckedChanged(object sender, EventArgs e)
{
SupplierProduceType();
}
protected void PorkCB_CheckedChanged(object sender, EventArgs e)
{
SupplierProduceType();
}
protected void ChickenCB_CheckedChanged(object sender, EventArgs e)
{
SupplierProduceType();
}
protected void LambCB_CheckedChanged(object sender, EventArgs e)
{
SupplierProduceType();
}
protected void SauceCB_CheckedChanged(object sender, EventArgs e)
{
SupplierProduceType();
}
private void SupplierProduceType()
{
string produceType = string.Empty;
if(BeefCB.Checked)
{
produceType = "Beef, ";
}
if(PorkCB_Checked)
{
produceType += "Pork, ";
}
if(ChickenCB_Checked)
{
produceType += "Chicken, ";
}
if(LambCB_Checked)
{
produceType += "Lamb, ";
}
if(SauceCB_Checked)
{
produceType += "Sauce, ";
}
SupplierProduceTypeTB.Text = produceType;
}
As += will not work on textbox.Text property.
Try this one by creating function and call it to you every checkbox checkchange method.
A: SO my way around was to do an if statement in the add supplier button:
if (BeefCB.Checked) {
String input1 = "beef,";
string textboxValue = SupplierProduceTypeTB.Text;
SupplierProduceTypeTB.Text = textboxValue + input1;
}
if (PorkCB.Checked) {
String input1 = "pork,";
string textboxValue = SupplierProduceTypeTB.Text;
SupplierProduceTypeTB.Text = textboxValue + input1;
}
if (ChickenCB.Checked) {
String input1 = "chicken,";
string textboxValue = SupplierProduceTypeTB.Text;
SupplierProduceTypeTB.Text = textboxValue + input1;
}
if (LambCB.Checked) {
String input1 = "lamb,";
string textboxValue = SupplierProduceTypeTB.Text;
SupplierProduceTypeTB.Text = textboxValue + input1;
}
if (SauceCB.Checked) {
String input1 = "sauce";
string textboxValue = SupplierProduceTypeTB.Text;
SupplierProduceTypeTB.Text = textboxValue + input1;
}
| |
doc_2859
|
I tried with record macro but doesnt work for all sheets.
Sub TheWall()
Application.ScreenUpdating = False
Dim lngLstCol As Long, lngLstRow As Long
lngLstRow = ActiveSheet.UsedRange.Rows.Count
lngLstCol = ActiveSheet.UsedRange.Columns.Count
For Each rngCell In Range("A2:A" & lngLstRow)
If rngCell.Value > "" Then
r = rngCell.Row
c = rngCell.Column
Range(Cells(r, c), Cells(r, lngLstCol)).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End If
Next
Application.ScreenUpdating = True
End Sub
Thanks For Your Help!
A: Try this one:
Sub TheWall()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim rngCell As Range
Dim hasValue As Boolean
Dim r As Range
For Each ws In ThisWorkbook.Worksheets
For Each rngCell In ws.UsedRange
hasValue = False
For Each r In rngCell.MergeArea
If r.Value <> "" Then
hasValue = True
Exit For
End If
Next r
If hasValue Then
With rngCell.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End If
Next
Next ws
Application.ScreenUpdating = True
End Sub
| |
doc_2860
|
m = (M - R(i,1)*eye(NumRowsR));
disp(rref(m));
t = null(rref(m));
disp(t);
This part can't give me the nullspace of matrix t after reduced for some reasons (I recently did some research on the Internet and see some people said about the bug of rref and null). The problem is that it keeps showing me elementary matrix
1 0 0
0 1 0
0 0 1
for the eigenvalues. Does anyone know how to fix it? I will be very much appreciated!
Below is my original code, for a better view:
syms x NumRowsM NumColsM NumRowsR NumColsR NumRowst NumColst k numeigen
M = input('Input a square matrix M: ');
k = input('Input the power of matrix M: ');
[NumRowsM, NumColsM]=size(M);
if (NumRowsM ~= NumColsM)
disp('Not valid input. Matrix must be a square matrix!')
else
%Find eigenvalues:
R = solve(det(M - x*eye(NumRowsM)), x);
[NumRowsR, NumColsR] = size(R);
if (or(NumRowsR == 0,NumColsR == 0))
disp('No eigenvalues. The matrix is not diagonalizable')
else
numeigen = 0;
F = zeros(NumRowsR, NumRowsR);
d = zeros(NumRowsR,1);
for i = 1:NumRowsR
m = (M - R(i,1)*eye(NumRowsR));
disp(rref(m));
t = null(rref(m));
disp(t);
[NumRowst, NumColst] = size(t);
if (NumColst == 0)
if (i == NumRowsR && numeigen > NumRowsR)
disp('Matrix not diagonalizable due to invalid eigenvalue');
return
else
continue
end
else
numeigen = numeigen + 1;
if (NumColst == 1)
for j = 1:NumRowsR
[n, d(j)] = numden(sym(t(j,1)));
end
for j = 1:NumRowsR
F(j,i) = sym(t(j,1)) * lcm(sym(d));
end
else
for k = 1:NumColst
for j = 1:NumRowsR
[n, d(j)] = numden(sym(t(j,k)));
end
for j = 1:NumRowsR
F(j,k) = sym(t(j,k)) * lcm(sym(d));
end
end
end
end
end
disp(F);
D = (F\M)*F;
disp('The power k of the matrix M is: ');
T = F*(D^k)/(F);
disp(T)
end
end
| |
doc_2861
|
Data set:
http://bit.ly/1JRfyiz
Output:
http://bit.ly/1Cr9Q4c
There can be any no. of departments and any no. of months(I means max 12 months).
I am not able to figure it out how to merge only headers with same name.
Please tell me what I should do in order to get output I want.
A: "I am not able to figure it out how to merge only headers with same name."
OK, then I assume you have already figured out how to do the first part ("bring the same departments together") and your input has the columns sorted properly.
The idea to merge is then to go from A1, see what department is there, check how far does this department go, merger and start from next cell with another department.
Sub trymerge()
'Variables to know where you are
Dim start As Integer
Dim endc As Integer
start = 1
endc = 1
Application.DisplayAlerts = False
'Loop through all columns where top cell is nonempty
Do While Worksheets(1).Cells(1, start).Value <> ""
'Loop to find columns next to each other with the same dept name
Do While Worksheets(1).Cells(1, start).Value = Worksheets(1).Cells(1, endc).Value
endc = endc + 1
Loop
endc = endc - 1
'Merge what you found
Worksheets(1).Range(Cells(1, start), Cells(1, endc)).Merge
Worksheets(1).Cells(1, start).HorizontalAlignment = xlCenter
'Move to next dept
start = endc + 1
endc = start
Loop
Application.DisplayAlerts = True
End Sub
| |
doc_2862
|
I suddenly started having some issues with data I input (not calculation) and cannot explain the following behavior:
In [600]: df = pd.DataFrame([[0.05], [0.05], [0.05], [0.05]], columns = ['a'])
In [601]: df.dtypes
Out[601]:
a float64
dtype: object
In [602]: df['a'].sum()
Out[602]: 0.20000000000000001
In [603]: df['a'].round(2).sum()
Out[603]: 0.20000000000000001
In [604]: (df['a'] * 1000000).round(0).sum()
Out[604]: 200000.0
In [605]: (df['a'] * 1000000).round(0).sum() / 1000000
Out[605]: 0.20000000000000001
Hopefully somebody can help me either fix this or figure out how to correctly sum 0.2 (or I don't mind if the result is 20 or 2000, but as you can see when I then divide I get to the same point where the sum is incorrect!).
(to run my code remember to do import pandas as pd)
A: Ok so this works:
In [642]: (((df * 1000000).round(0)) / 1000000).sum()
Out[642]:
a 0.2
dtype: float64
But this doesn't:
In [643]: (((df * 1000000).round(0))).sum() * 1000000
Out[643]:
a 2.000000e+11
dtype: float64
So you have to do all calculations inside the Panda array or risk breaking up things.
A: "I get to the same point where the sum is incorrect!" By your definition of incorrect nearly all floating point operations would be incorrect. Only powers of 2 are perfectly represented by floating points, everything else has a rounding error of about 15–17 decimal digits (for double precision floats). Some applications just hide this error better than others when displaying these values.
That precision is far more than sufficient for the data you are using.
If you are bothered by the ugly-looking output, then you can do "{:.1f}".format(value) to round the output string to 1 decimal digit after the point or "{:g}".format(value) to automatically select a reasonable number of digits for display.
| |
doc_2863
|
I have gone through the below link
javax.faces.application.ViewExpiredException: View could not be restored
Have followed most of the stuff,
*
*Setting the context param,
com.sun.faces.enableRestoreView11Compatibility
true
*Instructed the browser to not cache the dynamic JSF pages by adding the below code at top of all JSP pages,
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", -1);
We are not getting the exception when we manually browse through the application. I am not able to figure out the issue.
Kindly advice.
A: The views are stored in the session. The default maximum amount of views which is stored in the session is 15 which is in Mojarra configureable by the com.sun.faces.numberOfViewsInSession context paramerer.
Imagine a situation wherein the enduser opens a random JSF page with a form (which is effectively one view) in at least 16 different browser tabs/windows in the same session. Submitting the form in the first opened tab/window will then throw ViewExpiredException. Perhaps the same is happening during load testing. The load testing should better have created different sessions.
As stated in the answer which you found yourself, the only fix for this is to set the JSF state saving method to client instead of server. Disabling the browser cache just prevents ViewExpiredException which occurs on pages which the enduser has obtained from the browser cache (e.g. by pressing back button and so on).
| |
doc_2864
|
File structure:
*
*/example1/
*/example2/
*/example1.html
*/example2/data.json
*/data.json
Working (redirect to 404.html):
*
*http://example.com/example3/
Working (redirect to 404.json):
*
*http://example.com/not-exists.json
*http://example.com/example3/data.json
*http://example.com/example2/data.json
Working (open the file):
*
*http://example.com/example1.html
*http://example.com/data.json
*http://example.com/example2/ (list files in folder)
Not working (default apache 404):
*
*http://example.com/example1/
*http://example.com/example1/not-exists.json
*http://example.com/example2/not-exists.json
It seems apache is redirecting "example1/" to "example1.html", especially when I try to access a file inside the directory like http://example.com/example2/data.json, shows 404 message:
The requested URL /example2.html/data.json was not found on this server.
It happens even without the .htaccess! All the problem because the example1.html file.
htaccess:
# Rewrite MOD
Options +FollowSymLinks
RewriteEngine On
# If requested resource exists as a file or directory go to it
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) - [L]
# 404 json
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)\.json$ 404.json [L]
# 404 page
RewriteRule . 404.html [L]
Maybe it is some apache file mapping configuration but I can't find anything about it. It happens only for deploy server, for localhost it's fine. =/
A: Have it like this with MultiViews turned off:
Options +FollowSymLinks -MultiViews
RewriteEngine On
# If requested resource exists as a file or directory go to it
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# 404 json
RewriteRule \.json$ 404.json [L,NC]
# 404 page
RewriteRule ^ 404.html [L]
| |
doc_2865
|
So I want when the page loads to display AJAX loader iamge (for example), not to stay white...
Please give more detailed code, I'm new.
Thanks!
A: $(function(){
var ajax_load = "<img src='images/loading.gif' alt='loading...' />";
$('body').html(ajax_load);
var postData = $("#form").serialize();
$.ajax({
type: "POST",
url: "ajaxpage.php",
data: postData,
success: function(body){
$('body').html(body);
}
});
});
I believe that is what you want.
A: Structurally, it would be something like this:
*
*Load the DOM with empty containers, including the "loader image"
*Load javascript files which load your content and fills the containers
*Attach javascript event handlers to all links to override the default behavior of loading a new page
But you will be better off using some sort of framework for it. "Hash bang" (#!) is a popular pattern, make a google search for it.
Good luck!
A: To make it more apparent, imagine we have HTML page with this markup:
<button id="btnLoad">Load Content</button>
<div id="content">
Please click "Load Content" button to load content.
</div>
We want to load content when a user clicks on the "Load Content" button. So we need to bind a click event to that button first and make AJAX request only after it is fired.
$("#btnLoad").click(function(){
// Make AJAX call
$("#content").load("http://example.com");
});
he above code loads contents from http://example.com into the . While the page is being loaded we want to display our animated GIF image in the "content". So we could further improve our code like so:
$("#btnLoad").click(function(){
// Put an animated GIF image insight of content
$("#content").empty().html('<img src="loading.gif" />');
// Make AJAX call
$("#content").load("http://example.com");
});
The .load() function would replace our loading image indicator with the loaded content.
You might be using jQuery’s other AJAX functions like $.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.
Here is also the solution for having the content hidden until the ajax call is completed to reveal it.
CSS:
<style type="text/css">
#content
{
display:none;
}
</style>
jQ:
$(function () {
var loadingImg = $('#loadingImage');
loadingImg.show();
$.ajax({
url: "secondpage.htm",
cache: false,
success: function (html) {
loadingImg.hide();
$("#content").append(html).fadeIn();
}
});
});
HTML:
<body>
<img src="loader.gif" id='loadingImage' alt='Content is loading. Please wait' />
<div id='content'>
</div>
</body>
| |
doc_2866
|
my_list = ['a','b','c','d','e']
my_dict = {'first_item':'', 'middle_items':'','last_item':''}
for key in my_dict.keys():
value = my_list.pop()
my_dict.update({k:''.join(value)})
This approach obviously does not work because pop does not slice the array. And if I want to use slicing, I will have to explicitly access the dictionary variables and assign the corresponding list slices.
I have tried using the list length to slice through the list, but was unable to find a general solution, here is my other approach
for key in my_dict.keys():
value = ''.join(my_list[:-len(my_list)+1])
del my_list[0]
my_dict.update({k:v})
How can I slice a list in a general way such that it splits into a first item, last item, and middle items? below is how the updated dictionary should look like
my_dict = {'first_item':'a', 'middle_items':'b c d','last_item':'e'}
Edit: if I use [0],[1:-1], and [-1] slices then that means that I will have to access each dictionary key individually and update it rather than loop over it (which is the desired approach)
A: If you are using python 3 then you should try this idiom:
my_list = ['a','b','c','d','e']
first_item, *middle_items, last_item = my_list
my_dict = dict(
first_item=first_item,
middle_items=' '.join(middle_items),
last_item=last_item
)
print(my_dict)
# {'last_item': 'e', 'middle_items': 'b c d', 'first_item': 'a'}
A: To get a slice of my_list, use the slice notation.
my_list = ['a', 'b', 'c', 'd', 'e']
my_dict = {
'first_item': my_list[0],
'middle_items': ' '.join(my_list[1:-1]),
'last_item': my_list[-1]
}
Output
{'first_item': 'a',
'middle_items': 'b c d',
'last_item': 'e'}
| |
doc_2867
|
This is how my client prog sends bytes to my server prog:
public void sendBytes()
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
TcpClient cli = tcpServer; //tcpServer is a global TcpClient variable I use to connect to the server.
NetworkStream ns = cli.GetStream();
CopyStreamToStream(fs, ns, null);
ns.Flush();
}
public static void CopyStreamToStream(Stream source, Stream destination, Action<Stream, Stream, Exception> completed)
{
byte[] buffer = new byte[0x1000];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) > 0) // <- client loop
destination.Write(buffer, 0, read);
}
This is how my server prog receives bytes from my client prog:
FileStream ms = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
do
{
int szToRead = s.Available; //s is a socket
byte[] buffer = new byte[szToRead];
int szRead = s.Receive(buffer, szToRead, SocketFlags.None);
if (szRead > 0)
ms.Write(buffer, 0, szRead);
}
while(s.Available != 0); //i also tried ms.length < size_of_file_to_be_received_in_bytes
i stepped into the program and watched the values, and I don't know what causes the lack of bytes received. I don't know if the problem is with the client prog or the server prog.
i don't know if this is relevant, but when i tried stepping into the client loop (to watch the value of fs.length and check if it will be received in the server), all 4 attempts to send a file from the client to the server succeeded. but when i did not watch the client loop, and only watch the server app (to see the value of ms.length), only 1 of 4 attempts to send a file to the server succeeded. on the 3 failed attempts, ms.length is less than the bytes of the source file (i checked it in the file's property).
This is where I based this from
ADDITIONAL INFORMATION:
On the original code (from the website I based my program), the loop has a different condition:
FileStream ms = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
do
{
int szToRead = s.Available; //s is a socket
byte[] buffer = new byte[szToRead];
int szRead = s.Receive(buffer, szToRead, SocketFlags.None);
if (szRead > 0)
ms.Write(buffer, 0, szRead);
}
while(SocketConnected(s)); // <--- i changed this in my program
private static bool SocketConnected(Socket s)
{
return !(s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0));
}
I think the SocketConnected tests if the socket is still connected because the original code for the client program was this:
CopyStreamToStream(fs, ns, null);
ns.Flush();
ns.Close();
i removed the ns.Close() from the program because I want to maintain the connection of the client application to the server. So I want to be able to check if I'm done reading all the bytes coming from the client app without closing the socket connection from the client side.
A: If Available is zero this does not mean that you have finished reading bytes. It means that currently, in this nanosecond, there are no bytes queued. How could the server know how many bytes will be coming in the future?
In good approximation, every singe use of Available is an error!
Delete all usages of Available. Instead, always try to read a full buffer. If you get 0 this means the socket has been closed and you are done.
Edit: Here is some canonical read code:
var buffer = new byte[8192];
while(true) {
var readCount = stream.Read(buffer, 0, buffer.Length);
if (readCount == 0) break;
outputStream.Write(buffer, 0, readCount);
}
| |
doc_2868
|
StationName X Y
po 1 1
wsx 200 200
edc 300 300
rfv 300 100
tgb 200 0
yhn 100 50
I need help with a simple algorithm to find the shortest distance to travel between all stations. I have completed a majority of my code such as finding the euclidean distance but I am stuck on how to compare the list items.
I need a solution that just checks the distance from station A to each other stations and then selects the one with the shortest distance until all have been checked and added.
I have created a Station class and a method for the values I need but I am finding it hard to compare the values that are contained within the list.
Would it be advisable to use a list for each value type e.g.
(StationName, X, Y)
or create it using a station method? e.g.
public Station(string name, double X, double Y)
I have a method for calculating my distance between coordinates.
public static double distance(double x1, double y1, double x2, double y2)
{
return Math.Sqrt((Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)
* 100000.0 / 100000.0) * 1);
}
I am not sure if this enough information to go off. Just let me know and I will provide more.
| |
doc_2869
|
If we have below documents in MongoDB,
Test data
{id:1, filter:{f1:'v1-1', f2:'v2-1', f3:['v3-1', 'v3-3']}}
{id:2, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-2', 'v3-3']}}
{id:3, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-1', 'v3-3']}}
Prepare the collection
db.test.drop()
db.test.insert({id:1, filter:{f1:'v1-1', f2:'v2-1', f3:['v3-1', 'v3-3']}})
db.test.insert({id:2, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-2', 'v3-3']}})
db.test.insert({id:3, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-1', 'v3-3']}})
You can consider the filter field as filter function that used on many shopping sites, for example, they will tell you how many LED TVs and how many LCD TVs on the site.
I want to use MongoDB to calculate how many documents with each filter option (include every item in the array field), the expected result is as below.
Expected result
[
{
_id : { key: 'f1', value: 'v1-1' }, count: 3
},
{
_id : { key: 'f2', value: 'v2-1' }, count: 1
},
{
_id : { key: 'f2', value: 'v2-2' }, count: 2
},
{
_id : { key: 'f3', value: 'v3-1' }, count: 2
},
{
_id : { key: 'f3', value: 'v3-2' }, count: 1
},
{
_id : { key: 'f3', value: 'v3-3' }, count: 3
}
]
It's easy to get the result by using map/reduce,
Map/Reduce solution
map = function () {
for (k in this.filter) {
if (this.filter[k] instanceof Array) {
for (j in this.filter[k]) {
emit( { key: k, value: this.filter[k][j]}, 1 );
}
} else {
emit( { key: k, value: this.filter[k]}, 1 );
}
}
}
reduce = function (k, values) {
result = 0;
values.forEach( function(v) { result += v; } );
return result;
}
db.test.mapReduce(map, reduce, {out:{inline:1}})
But as the performance problem with map/reduce, it can't be used for real time query. and the result set may be changed if I add some query conditions, so I can't save the map/reduce result into another collection for real time query.
And I can use aggregate framework to calculate the count for one filter,
Aggregate solution for only one filter
db.test.aggregate(
{$project: {"filter.f2":1, "_id":0}},
{$group: {"_id": {"key": {$ifNull: [null, "f2"]}, "value":"$filter.f2"}, "count" : {$sum: 1}}}
)
[
{
"_id" : { "key" : "f2", "value" : "v2-2" }, "count" : 2
},
{
"_id" : { "key" : "f2", "value" : "v2-1" }, "count" : 1
}
]
But I don't know how to do it for all filter options. Any idea?
A: If you change your data structure to something like this, note that all the values are arrays, even the ones with single values:
{
_id: 1,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-1']
},{
key: 'f3',
values: ['v3-1', 'v3-3']
}]
}
{
_id: 2,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-2']
},{
key: 'f3',
values: ['v3-2', 'v3-3']
}]
}
{
_id: 3,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-2']
},{
key: 'f3',
values: ['v3-1', 'v3-3']
}]
}
You could do an aggregate function something like this:
db.test.aggregate({
$unwind: "$filters"
},{
$project: {
_id: 1,
key: "$filters.key",
values: "$filters.values"
}
},{
$unwind: "$values"
},{
$group: {
_id: {
$concat: ["$key","|","$values"]
},
count: { $sum: 1 }
}
})
You could probably skip the project step if you want, I just put it in there as a nicety. You'll need two unwinds no matter what though.
| |
doc_2870
|
The Command Pattern encapsulates a request as an object, thereby
letting you parameterize other objects with different requests, queue
or log requests, and support undoable operations.
Later the book said:
The semantics of some applications require that we log all actions and
be able to recover after a crash by reinvoking those actions. The
Command Pattern can support these semantics with the addition of two
methods: store() and load(). In Java we could use object serialization
to implement these methods, but the normal caveats for using
serialization for persistence apply.
How does this work? As we execute commands, we store a history of them
on disk. When a crash occurs, we reload the command objects and invoke
their execute() methods in batch and in order.
I am trying to come up with an example code. The code I wrote till now is:
class Client {
public static void main(String[] args) {
Command enableCommand = new EnableCommand();
enableCommand.execute();
}
}
interface Command {
void execute();
void store();
void load();
}
class EnableCommand implements Command {
public EnableCommand() {
}
@Override
public void execute() {
store();
System.out.println("Execute Command");
}
@Override
public void store() {
System.out.println("Storing on Disk");
}
@Override
public void load() {
// TODO Auto-generated method stub
}
}
How the load() function is supposed to work?
| |
doc_2871
|
public class PayeeContactDetails
{
//[JsonProperty("id")]
//[DefaultValue("")]
//public int ID { get; set; }
[JsonProperty("contact_name")]
[DefaultValue("")]
public string ContactName { get; set; }
[JsonProperty("contact_email")]
[DefaultValue("")]
public string ContactEmail { get; set; }
........
........
}
and here i am having PayeeContactGroup class like this
public class PayeeContactGroup
{
[JsonProperty("payee_contacts")]
public List<PayeeContactDetails> PayeeContact { get; set; }
}
here i am getting data from api response on page by page after completion of all pages i need to send all data at a time to DB
for this purpose i am doing like this
PayeeContactGroup payeeContactDetails = new PayeeContactGroup();
var response = httpClient.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
string data = response.Content.ReadAsStringAsync().Result;
var payeeContactGroupDetails = JsonConvert.DeserializeObject<PayeeContactGroup>(data);
if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage == 1)
{
payeeContactDetails.PayeeContact = payeeContactGroupDetails.PayeeContact.ToList();
}
else if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage > 1)
{
payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact); // error at this line
}
.......
......
}
But i am getting error at
this line
"payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact);"
Error : "Object reference not set to an object"
Could any one please help on this ....
Many thanks in advance
A: You need to create the List first:
public class PayeeContactGroup
{
[JsonProperty("payee_contacts")]
public List<PayeeContactDetails> PayeeContact { get; set; } = new List<PayeeContactDetails>();
}
Or create the List only when necessary:
PayeeContactGroup payeeContactDetails = new PayeeContactGroup();
var response = httpClient.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
string data = response.Content.ReadAsStringAsync().Result;
var payeeContactGroupDetails = JsonConvert.DeserializeObject<PayeeContactGroup>(data);
if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage == 1)
{
payeeContactDetails.PayeeContact = payeeContactGroupDetails.PayeeContact.ToList();
}
else if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage > 1)
{
if(payeeContactDetails.PayeeContact == null)
{
payeeContactDetails.PayeeContact = new List<PayeeContactDetails>();
}
payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact); // error at this line
}
.......
......
}
A: Initialise the empty list first before adding. Or the AddRange method is trying to add to null. This could be done in code:
PayeeContactGroup payeeContactDetails = new PayeeContactGroup();
payeeContactDetails.PayeeContact = new List<PayeeContactDetails>();
| |
doc_2872
|
When communication fails the browser reports an asynch callback error. When I attach with .NET Framework source stepping enabled I get an "Attempted to perform an unauthorized operation" error. I've searched and banged my head on this for hours. What is going on?
My client requires the application to run on Silverlight Runtime 3.0.40624, IE6 and
Windows Server 2003. My client provides no more concerning the machine configuration.
A: This could be caused by a web proxy, which is returning the error message.
Different environments could be configured to bypass the web proxy for different addresses.
| |
doc_2873
|
This first method is setting up the request to the apps homepage basically, just setting up. It's in its own method to reuse of course;
public RequestSpecification downloadRequest(String testRunName){
RequestSpecification request = given()
.baseUri(url)
.config(RestAssured.config().sslConfig(new SSLConfig().allowAllHostnames()))
.cookies(cookiesSpecification())
.header("Authorization", getAuthenticationToken("[email protected]", "Automation0"))
.header("Accept", "application/json, text/plain, */*")
.param("resultsPerPage", 10)
.param("pageNum", 1)
.param("names", testRunName);
return request;
}
Next I have a method which will take in the ID and name of test runs and will find the ID of this specific test run, this is found in the response. This method works fine:
public String getTestDataID(int testRunID, String testRunName) {
log.debug("Downloading Test Data Template");
RequestSpecification request = downloadRequest(testRunName);
ResponseBody response =request
.when()
.get("/restapi/testRuns/" + testRunID + "/testData").getBody();
String testDataID = response.jsonPath().getString("id");
return testDataID;
}
Lastly, the method that keeps failing on me, will take the ID found from the previous and send a get request to the endpoint using this ID in the url. This should then download the zip folder. I return the response and then have another method converting and streaming the zip, that's all ok. The problem is with this method, I am getting Http: 500 internal server error every time I run the tests. However if I put a break point in here and step over from this method onwards it will pass.
public Response getTestDataZip(String testDataID){
return getRequest(url + "/restapi/downloads/" + testDataID + "/content");
}
Any ideas why this would fail when running but pass if I break point it and step over each step. Due to it passing when I step over, it makes me feel like it's a cache issue, but then it is a 500 error, so maybe some authorisation which all seems to be in place ok.
If someone knows something or can see something, that would be much appreciated. Thanks in advance.
| |
doc_2874
|
A: lipo can help to solve the question,
but need to add -create parameter.
lipo -create simulator.a device.a -output universe.a
Then check universe.a
lipo -info universe.a
If built in Xcode 6, expect output is "Architectures in the fat file: universe.a are: i386 x86_64 armv7 arm64 "
| |
doc_2875
|
Can I, and if so, how?
A: Create a TResourceStream. You'll need the module instance handle (usually SysInit.HInstance for the current EXE file, or else whatever you get from LoadLibrary or LoadPackage), the resource type (such as rt_Bitmap or rt_RCData), and either the resource name or numeric ID. Then call the stream's SaveToFile method.
A: try
if not Assigned(Bitmap)
then
Bitmap := TBitmap.Create();
Bitmap.LoadFromResourceName(HInstance,SRC);
except
on E:Exception do
ShowMessage(e.Message);
end;
And then save the Bitmap to disk.
A: Use Delphi's TResourceStream. It's constructor will find and load the resource into memory, and it's SaveToFile method will do the disk write.
Something similar to this should work:
var
ResStream: TResourceStream;
begin
ResStream := TResourceStream.Create(HInstance, 'YOURRESOURCENAME', RT_RCDATA);
try
ResStream.Position := 0;
ResStream.SaveToFile('C:\YourDir\YourFileName.jpg');
finally
ResStream.Free;
end;
end;
If you can use the resource ID instead of name, it's a little less memory. In that case, you'd resplace Create with CreateFromID, and supply the numeric ID rather than the string name.
A: Maybe this might come in handy too if you need to work with the resources itself.
Delphidabbler / ResourceFiles
| |
doc_2876
|
Here is my code:
Mega:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";
void setup() {
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
const char text[] = "Hello World, tw";
radio.write(&text, sizeof(text));
delay(500);
radio.write("what about this?",15);
delay(500);
}
Uno:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("Hello to the world.");
radio.begin();
radio.openReadingPipe(0, address);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
}
void loop() {
//delay(1000);
if (radio.available()) {
char text[32] = "";
radio.read(&text, 15);
Serial.println(text);
}
}
My Scematic
Thanks in advance!
A: The problem is probably the serial monitor is at a different buad rate than the code and/or the transceiver.
Try checking the serial monitor for the baud rate and set it to 9600.
| |
doc_2877
|
Here's what I'm trying to accomplish (I'm struggling)
I need to create a progress chart for each data element in my dataset. They all have different max values. 1 chart may need a max value of 4.5, while another may need a max value of 1.0. The way I'm going to try to go about it is have a function called every time a path is created and that function will get passed the max value which will then return the arc variable needed. Any suggestions?
var arc = d3.svg.arc()
.startAngle(0)
.endAngle(180 * (Math.PI / 180))
.innerRadius(50)
.outerRadius(100);
// Create a variable to append the svg/paths too
var container = d3.select("#aeGroupMarginSlide");
// Create an svg element and append a path for each data element
var svg = container.selectAll(".aeGroupMarginSvg").data(data);
svg.enter()
.append("svg")
.attr({
"class": "col-sm-4 col-md-4 col-lg-4 aeGroupMarginSvg",
"height": 300
})
.append("path")
.attr({
"d": function (d) { return arc; },
"transform": function (d) {
var w = $(this).parent().width();
var h = $(this).parent().height();
return "translate(" + (w / 2) + ", " + (h / 2) + ")"
},
"fill": "white"
})
| |
doc_2878
|
I'm having problems calling a method in a subclass which should override a method in the superclass.
Here is the class structure with removed code:
public interface Movable {
public void move(double delta);
}
public abstract class Unit implements Movable, Viewable{
public void move(double delta){
System.out.println("1");
}
}
public class Alien extends Unit{
public void move(long delta){
System.out.println("2");
}
}
public class Player extends Unit{
public void move(long delta){
System.out.println("3");
}
}
public void main(){
ArrayList<Unit> units = new ArrayList<Unit>();
Unit player = new Player();
Unit alien = new Alien();
units.add(player);
units.add(alien);
for (int i = 0; i < this.units.size(); i++) {
Unit u = (Unit) this.units.get(i);
u.move();
}
}
This would output 1 and 1, but I want it to output 2 and 3.
What am I doing wrong? I thought this was how it worked.
A: You need to add the @Override flag to the move function in your alien and player classes.
that would've helped you notice that you are not quite overriding your move since the type in alien/player are long, not doubles
A: Your child class does not implements the same method signature:
public void move(double delta);
is not the same as:
public void move(long delta);
To catch this kind of error at compile time, you can add @Override in the method signature. The compiler will check if the child class do in fact override a method in the parent class.
A: Your subclasses (Alien and Player) aren't overriding the move() method in their parent class because you have declared 'delta' as a long and not a double.
You can have the compiler spot some of these errors by using the @Override annotation.
A: public class Alien extends Unit{
public void move(long delta){
System.out.println("2");
}
}
public class Player extends Unit{
public void move(long delta){
System.out.println("3");
}
}
Here's your problem, in the interface you have move declared as:
public void move(double delta)
But your child classes declare a:
public void move(long delta)
That creates a new function, separate from move and doesn't override it. To fix it change Alien's and Player's move functions to:
public void move(double delta)
Also, as Outlaw Programmer points out, you can have the compiler catch this sort of error by adding an @Override annotation right above the declaration of any function you intend to override a function in the parent class. Like so:
public class Alien extends Unit {
@Override
public void move(double delta) {
System.out.println("2");
}
}
| |
doc_2879
|
I'm writing a program that is like a blank paper where you can write on (free hand-writing), insert text, add images, add pdfs etc...
For one specific feature I need to convert the Nodes added to the Pane by the user to images. Thankfully, JavaFX-Nodes provide a nice method:
public void snapshot(...)
But there is one issue: When I'm trying to make Snapshots of text-objects they fail. The only Node that I can take snapshots of is javafx.scene.text.Text.
The following classes fail:
javafx.scene.control.TextArea
javafx.scene.web.WebView
Here is an example to illustrate my problem:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
TextArea textArea = new TextArea("Lorem Ipsum is simply dummy text"
+ " of the printing and typesetting industry. Lorem Ipsum has been \n"
+ "the industry's standard dummy text ever since the 1500s, when an \n"
+ "unknown printer took a galley of type and scrambled it to make a type\n"
+ " specimen book. It has survived not only five centuries, but also the\n"
+ " leap into electronic typesetting, remaining essentially unchanged. It\n"
+ " was popularised in the 1960s with the release of Letraset sheets containing\n"
+ " Lorem Ipsum passages, and more recently with desktop publishing software \n"
+ "like Aldus PageMaker including versions of Lorem Ipsum");
SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setFill(Color.TRANSPARENT);
Image img = textArea.snapshot(snapshotParameters, null);
ImageView imgVw = new ImageView( img );
System.out.printf("img.width: %s height: %s%n", img.getWidth(), img.getHeight()); // <= width and height of the image img is 1:1! WHY?
Pane pane = new Pane();
pane.getChildren().addAll(imgVw);
Scene scene = new Scene(pane, 800,800);
pane.setMinWidth(800);
pane.setMinHeight(800);
pane.setMaxWidth(800);
pane.setMaxHeight(800);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
I could think of a work-around by creating a javafx.scene.text.Text-Object and take a snapshot of that. But this will fail for formatted Text displayed by javafx.scene.web.WebView.
Thanks in advance for your help!
A: The TextArea needs to be a Scene before you snapshot it. Add the following line to your code before the snapshot call and the code will work as you expect:
Scene snapshotScene = new Scene(textArea);
This requirement is mentioned in the snapshot javadoc:
NOTE: In order for CSS and layout to function correctly, the node must
be part of a Scene (the Scene may be attached to a Stage, but need not
be).
| |
doc_2880
|
The final child component receives a model (representing just one row in the table) along with field name that defines which filed to display from the model.
All of this works perfectly and UI updates are bound to the model. The problem that I have is that model updates are not being pushed to the UI. Within my child component I bind to the UI element using the following:
tdVal : function(){
return this.get('data').get(this.get('details').get('field'));
}.property()
tdValUpdated : function(){
this.get('data').set(this.get('details').get('field'),this.get('val'));
}.property('tdVal'),
As you can see there is no computed property literal set for tdVal, which is why model updates are not being pushed to the UI. If I were to give this a literal value such as 'data.status' then status updates to the model are pushed to the UI.
What literal value can I use to compute on any attribute change in the model?
I've tried 'data.isUpdated', 'data.isSaving' etc. I can't use 'data.[]' as the single model, not an array of model.
A: OK, after much trial and error I think I've found a workaround for this. It's messy and I'm not very happy with it:
//as previous I render the the appropriate value from the model as defined
//by the passed in config object
tdVal : function(){
return this.get('data').get(this.get('details').get('field'));
}.property(),
//then detect UI changes and push to model if required
tdValUpdated : function(){
this.get('data').set(this.get('details').get('field'),this.get('val'));
}.property('tdVal'),
//Then I observe any changes to model isSaving and directly set tdVal with
//the value of the field for the current td
generalUpdateCatch: function() {
this.set('tdVal',this.get('data').get(this.get('details').get('field')));
}.observes('data.isSaving'),
I did try the following instead:
tdVal : function(){
return this.get('data').get(this.get('details').get('field'));
}.observes('data.isSaving'),
But get the error: 'Uncaught TypeError: unsupported content', no idea why? If anybody has a better solution then please post as I very much dislike these workarounds.
| |
doc_2881
|
I am currently running the following bash script, multithread 15 times:
infile="$1"
start=$2
end=$3
step=$(($4-1))
for((curr=$start, start=$start, end=$end; curr+step <= end; curr+=step+1)); do
cut -f$curr-$((curr+step)) "$infile" > "${infile}.$curr" -d' '
done
However, judging by current progress of the script, it will take 300 days to complete the split?!
Is there a more efficient way to column wise split a space-delimited file into smaller chunks?
A: Try this awk script:
awk -v cols=100 '{
f = 1
for (i = 1; i <= NF; i++) {
printf "%s%s", $i, (i % cols && i < NF ? OFS : ORS) > (FILENAME "." f)
f=int(i/cols)+1
}
}' largefile
I expect it to be faster than the shell script in the question.
| |
doc_2882
|
Thanks to "Installing gem or updating RubyGems fails with permissions error" I installed rbenv. I followed the guide and set my global ruby version, etc. but I continue to get the same error when I try to install gems. When I run gem environment the installation directory for RubyGems is still the system Ruby directory.
Should I update GEM_PATH? Since the rbenv guide doesn't mention anything about that, something makes me think that there is still a problem with my rbenv installation.
Can someone please help me figure this out?
A: You're not showing us the commands you're using but it smells like you're using sudo to install Sinatra. Don't do that with rbenv or RVM managed Rubies.
Just as in the linked question, using rbenv or RVM allows you have one or more Rubies in your user-space where you can modify them all you want. That means you don't need to use sudo, just use gem install ....
An alternate problem you could be having is you set your global Ruby to be system, which is the version installed by Apple for their use, and which you don't want to modify unless you understand why it's there and what they're using it for. IF you have to change it then sudo would be appropriate but, with rbenv or RVM managing Rubies in your user-space there's really no reason to.
Do NOT use chmod to change the ownership of the vendor installed gems; Again, that's for Apple's use so have fun with the local Rubies instead and leave Apple's alone.
A: In this case, I quit Terminal and upon reopening, things were working correctly. Probably a good thing to try if you're stuck and are sure you've followed instructions correctly. It's not explicitly mentioned in the material I read but I believe is a good practice in general.
| |
doc_2883
|
*
*npm start (to start my React app)
*node server.js (to start my node.js server)
How can I host this website?
Another issue I run into:
*
*I run my React app on localhost:3000
*My node.js server listens on localhost:3000
As a result:
When I refresh my application sometimes it says "Cannot GET /" because it is trying to GET the node.js server instead of the React App.
Here is my server.js file for reference
const express = require('express');
const nodemailer = require('nodemailer');
require('dotenv').config()
const app = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: process.env.EMAIL,
pass: process.env.PASS,
},
});
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
app.post('/send', (req, res, next) => {
console.log(req.body)
var name = req.body.contactName
var email = req.body.contactEmail
var subject = req.body.contactSubject
var message = req.body.contactMessage
var mail = {
from: name,
to: email,
subject: subject,
text: message
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
});
Any suggestions on the correct way to do this would be appreciated. Thanks!
UPDATE
Apparently the 'Cannot Get /' is a common issue for node.js react applications and I need to add in something like this into my server.js:
app.route("/").get(function (req, res) {
res.redirect("/public/index.html");
});
Can anyone help with this method to redirect get requests to my node.js server to the home page of my react app?
A: Sorry for my noob question!!
Here is the solution:
https://www.freecodecamp.org/news/how-to-create-a-react-app-with-a-node-backend-the-complete-guide/
Need to add in a proxy to package.json:
..."proxy": "http://localhost:3001",...
and host the node.js server on 3001.
Then you run your React app on 3000 and it can make requests to your node.js server running on port 3001.
Thanks for the help everyone!
| |
doc_2884
|
In build.gradle file i have:
project.env.get("APP_VERSION_CODE").toInteger()
but when i run the app:
* What went wrong:
A problem occurred evaluating project ':app'.
> Cannot invoke method toInteger() on null object
When i copy .env file to root path it work correct.How can i change default .env file path from root to other sub folder??
A: Try moving .env file to root folder and also check whether file have "APP_VERSION_CODE" defined. To use env file in other folder you need to add plugin manually in android and ios to access the env file.
| |
doc_2885
|
-0.06
-1.45
0.02
0.05
...
Using Python/PyQt, I implemented the outlined solution from this accepted answer but it doesn't work.
My subclassed QSqlQueryModel:
class CatalogModel(QSqlQueryModel):
SortRole = Qt.UserRole + 1
def data(self, index, role=Qt.DisplayRole):
col = index.column()
data = super(CatalogModel, self).data(index, role)
print role == self.SortRole # always False
if role == self.SortRole:
if col in (2,3,4):
return data.toFloat()[0]
return data
Setting up the proxy:
proxy = QSortFilterProxyModel(self)
proxy.setSortRole(CatalogModel.SortRole)
My own SortRole does not arrive in my model and the columns with float numbers are still sorted like strings.
Why does this solution not work? Did I miss something?
A: From the latest official documentation:
Behind the scene, the view calls the sort() virtual function on the model to reorder the data in the model. To make your data sortable, you can either implement sort() in your model, or use a QSortFilterProxyModel to wrap your model -- QSortFilterProxyModel provides a generic sort() reimplementation that operates on the sortRole() (Qt::DisplayRole by default) of the items and that understands several data types, including int, QString, and QDateTime. For hierarchical models, sorting is applied recursively to all child items. String comparisons are case sensitive by default; this can be changed by setting the sortCaseSensitivity property.
Implement your own sort() could also be one option, but:
An alternative approach to sorting is to disable sorting on the view and to impose a certain order to the user. This is done by explicitly calling sort() with the desired column and order as arguments on the QSortFilterProxyModel (or on the original model if it implements sort()). For example:
proxyModel->sort(2, Qt::AscendingOrder);
QSortFilterProxyModel can be sorted by column -1, in which case it returns to the sort order of the underlying source model.
You could pass -1 to that method in the following manner:
proxy = QSortFilterProxyModel(self);
proxy.setSortRole(CatalogModel.SortRole);
proxy.sort(-1, Qt.AscendingOrder);
Note that you pasted the two lines there without semi-colon. The code would not even compile like that due to syntax errors. It is better to paste correct code.
If it does not work, just implement your sorting.
A: You need to switch sorting on I think. Something like:
proxy.sort(-1, Qt.AscendingOrder);
According to docs http://doc.qt.io/qt-4.8/qsortfilterproxymodel.html column -1 will switch on the sorting of the underlying model. Which is probably what you need.
| |
doc_2886
|
The code is working fine, but when more than 10 records are found, the website shows a link to a Next() javascript function that loads the next 10 records and so on.
Is there something that I can do with TIDHttp in order to execute the next() function ?
The code I'm using to retrieve the html text is as follows:
procedure TForm1.ObtemStringsCorreio(aParamEntrada:string; var aRetorno:TStringList);
var
_ParamList : TStringList;
begin
_ParamList := TStringList.Create;
_ParamList.Add('cepEntrada=' + aParamEntrada);
_ParamList.Add('tipoCep=ALL');
_ParamList.Add('cepTemp=');
_ParamList.Add('metodo=buscarCep');
try
aRetorno.Text := idhtp1.Post(cEngineCorreios, _ParamList);
mmo1.Lines.Clear;
mmo1.Text := aRetorno.Text;
finally
_ParamList.Free;
end;
end;
A: Indy is a communications library. It does not have any means for client side script execution. You will need to use another library for that.
A headless browser would be the ideal solution. A more heavyweight solution would be to embed a browser in a hidden form, and get it to do the work. You could use TWebBrowser, Chromium, etc. for this purpose.
| |
doc_2887
|
I know I can come up with some really long codes to kind of simulate this but I was wondering if there is a trick to it.
Thanks
A: I think what you want are joints. You can attach a spring joint component to a gameObject with a rigidbody. On the spring joint, set the connected body to a seperate gameObject with a kinematic rigidbody, then play with the spring joint settings until you get a nice jiggle effect. Probably increase the Spring value a bunch.
| |
doc_2888
|
class ViewDeudce{
BigDecimal stateid
BigDecimal motivid
static mapping = {
id column:"id", sqlType:"numeric"
table 'viewDeudce'
version false
}
}
The id of the view is the "client number". If I have a "Client" class, when doing this, I should not be able to relate it?:
class Clients implements Serializable {
String name
BigDecimal document
String brutos
ViewDeudce viewDeudce
static mapping = {
id column:"idclient", sqlType:"numeric", generator: 'assigned'
ViewDeudce column: "id", sqlType:"numeric"
version false
}
From what I understand, am I not telling the Client class to relate to the 'ViewDeudce' class via the id attribute?
Because when restarting the server, it does not start me and it gives me the following error:
Caused by BeanCreationException: Error creating bean with name '$ primaryTransactionManager': Can not resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ' sessionFactory ': Invocation of init method failed; nested exception is org.hibernate.HibernateException: Missing column: id in public.clients
- >> 266 | run in java.util.concurrent.FutureTask
Thanks!
A: maybe try to use id to reated rather than grails.domain class
class Clients implements Serializable {
String name
BigDecimal document
String brutos
//ViewDeudce viewDeudce
//!!change here!!
Long viewDeudceId
static mapping = {
id column:"idclient", sqlType:"numeric", generator: 'assigned'
ViewDeudce column: "id", sqlType:"numeric"
version false
}
| |
doc_2889
|
Vue return the following error:
./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/views/Inbox.vue
Module parse failed: Invalid regular expression flag (170:43) You may
need an appropriate loader to handle this file type.
My regex looks ok: I tested it here:
https://regex101.com/r/noPGfP/1
This is my (simplified) code:
export default {
name: "inbox",
methods: {
load(rs) {
_Api._get('load', {id: rs["uuid"]}).then((response) => {
if(response.status==200 && response.statusText=="OK") {
var html = response.body;
var body = html.match(/\<body[^\>]*\>(.*)\<\/body\>/si);
}
});
}
},
};
| |
doc_2890
|
A: I found answer to my own question. Instead of AsyncPostBackTrigger I added PostBackTrigger and my issue was resolved.
| |
doc_2891
|
Here is what I have so far.
resizeStop: function(newwidth, index) {
alert(index + " : " + newwidth);
}
A: OK, I got it. I store all column widths in a HashMap in a bean I use to save session info. When the resizeStop event is fired I submit the new column size to a controller (I'm using Java and Spring) which updates the values in the HashMap.
Here are the code snippets:
resizeStop: function(newwidth, index) {
var colModel = $("#list").jqGrid('getGridParam','colModel');
$.post("/sessionState/columnWidth/update",
{
column: colModel[index].name,
width: newwidth
}
)
}
and in the colModel:
{name:'Title', index:'title', width: ${uiState.columnWidthMap["Title"]}, jsonmap: 'title', sorttype: "text"}
| |
doc_2892
|
;; key chords
(require 'key-chord)
(key-chord-mode 1)
;(setq key-chord-two-keys-delay 0.2)
;(key-chord-define-global "(home)(home)" 'beginning-of-buffer)
;(key-chord-define-global "[(home)(home)]" 'beginning-of-buffer)
;(key-chord-define-global (home)(home) 'beginning-of-buffer)
;(key-chord-define-global [home][home] 'beginning-of-buffer)
Update: I've switched to the key-combo package, which does work with multiple key-presses including the home key.
A: It is <home>. To find out how emacs calls a particular key — one can press that key, and M-x view-lossage after that.
Edit
Sorry, misunderstood Your question at first. M-x key-chord-define-global doesn't accept home key. So I think currently this can't be done.
A: It sounds like key-chord won't help in this instance, as <home> isn't in its supported character range.
I believe the following should do what you're wanting, and the same pattern can easily be used for other unsupported keys1:
(defvar my-double-key-timeout 0.25
"The number of seconds to wait for a second key press.")
(defun my-home ()
"Move to the beginning of the current line on the first key stroke,
and to the beginning of the buffer if there is a second key stroke
within `my-double-key-timeout' seconds."
(interactive)
(let ((last-called (get this-command 'my-last-call-time)))
(if (and (eq last-command this-command)
last-called
(<= (time-to-seconds (time-since last-called))
my-double-key-timeout))
(beginning-of-buffer)
(move-beginning-of-line nil)))
(put this-command 'my-last-call-time (current-time)))
(global-set-key (kbd "<home>") 'my-home)
Note that this-command will evaluate to my-home when the function runs, so we are setting the my-last-call-time property on the my-home symbol, thus neatly avoiding the need to maintain a separate variable for remembering when this function was last called, which makes the function nicely self-contained and re-usable: to make another similar function, you need only change (beginning-of-buffer) and (move-beginning-of-line nil).
1 The obvious caveat is that both commands execute in succession if you trigger the double-key behaviour, so don't use this approach with commands for which that will be a problem.
(Conversely, the advantage is that we're not messing with timers.)
A: Another solution using smartrep.el which has the advantage of handling this sort of thing in a non-hacky way. The disadvantage is, of course, a dependency on a library.
(require 'smartrep)
(defun beginning-of-line-or-buffer ()
(interactive)
(move-beginning-of-line nil)
(run-at-time 0.2 nil #'keyboard-quit)
(condition-case err
(smartrep-read-event-loop
'(("<home>" . beginning-of-buffer)))
(quit nil)))
(global-set-key (kbd "<home>") #'beginning-of-line-or-buffer)
A: There is no need to use key-chord for this. Remove the calls to key-chord-define-global from your .emacs file and add the following lines instead:
(global-unset-key (kbd "<home>"))
(global-set-key (kbd "<home> <home>") 'beginning-of-buffer)
Explanation:
<home> is bound to move-beginning-of-line by default. If you want to be able to set up a key binding that consists of two presses of <home>, you first have to remove the default binding using global-unset-key. Then you can add the desired binding for beginning-of-buffer to the global keymap.
| |
doc_2893
|
I was using the command:
pip3 install --upgrade pip
After that, every time I call the command pip3 will get the same error:
File "/usr/bin/pip3", line 11, in <module>
sys.exit(main())
File "/home/my_user/.local/lib/python3.5/site-packages/pip/__init__.py", line 11, in main
from pip._internal.utils.entrypoints import _wrapper
File "/home/my_user/.local/lib/python3.5/site-packages/pip/_internal/utils/entrypoints.py", line 4, in <module>
from pip._internal.cli.main import main
File "/home/my_user/.local/lib/python3.5/site-packages/pip/_internal/cli/main.py", line 57
sys.stderr.write(f"ERROR: {exc}")
^
I've tried to search solution by myself and followed this to try to deal with the issue.
This is the command I tried:
curl -fsSL -o- https://bootstrap.pypa.io/pip/3.5/get-pip.py | python3
However, after I tried the command, I got another issue:
Traceback (most recent call last):
File "<stdin>", line 23974, in <module>
File "<stdin>", line 199, in main
File "<stdin>", line 121, in bootstrap
File "/home/my_user/.local/lib/python3.5/site-packages/setuptools/__init__.py", line 18, in <module>
from setuptools.dist import Distribution
File "/home/my_user/.local/lib/python3.5/site-packages/setuptools/dist.py", line 585
license_files: Optional[List[str]] = self.metadata.license_files
^
SyntaxError: invalid syntax
Is there any other way to fix this issue except remove and install python3.5 again? because the python3.5 is used in the Ubuntu 16.04 OS, if I remove it the system will break.
Thank you very much.
| |
doc_2894
|
.marquee {
position: relative;
width: 100%;
overflow: hidden;
animation: marquee 8s linear infinite;
}
.marquee p {
white-space: nowrap;
}
@keyframes marquee {
0% {
top: 10em
}
100% {
top: -2em
}
}
<p class="marquee">text</p>
... overlay: hidden is not working and max-height is not working too.
The text must keep scrolling 'behind' the image and the text must start scroll 'respecting' the height (410px).
Follows the url wheres the marquee is placed festasparapalmoemeio.pt to a better understanding about the issues and to be able to helping me to solve them.
Soon as possible.
Please!
| |
doc_2895
|
Here's the code:
(*Methods*)
member self.DrawSprites() =
_spriteBatch.Begin()
for i = 0 to _list.Length-1 do
let spentity = _list.List.ElementAt(i)
_spriteBatch.Draw(spentity.ImageTexture,new Rectangle(100,100,(int)spentity.Width,(int)spentity.Height),Color.White)
_spriteBatch.End()
(*Overriding*)
override self.Initialize() =
ChangeGraphicsProfile()
_graphicsDevice <- _graphics.GraphicsDevice
_list.AddSprite(0,"NagatoYuki",992.0,990.0)
base.Initialize()
override self.LoadContent() =
_spriteBatch <- new SpriteBatch(_graphicsDevice)
base.LoadContent()
override self.Draw(gameTime : GameTime) =
base.Draw(gameTime)
_graphics.GraphicsDevice.Clear(Color.CornflowerBlue)
self.DrawSprites()
And the AddSprite Method:
member self.AddSprite(ID : int,imageTexture : string , width : float, height : float) =
let texture = content.Load<Texture2D>(imageTexture)
list <- list @ [new SpriteEntity(ID,list.Length, texture,Vector2.Zero,width,height)]
The _list object has a ContentManager, here's the constructor:
type SpriteList(_content : ContentManager byref) =
let mutable content = _content
let mutable list = []
But I can't minimize the window, since when it regains its focus, i get this error:
ObjectDisposedException
Cannot access a disposed object.
Object name: 'GraphicsDevice'.
What is happening?
A: Well after struggling for some time I got it to work. But it doesn't seem "right"
(thinking that way, using XNA and F# doesn't seem right either, but it's fun.)
(*Methods*)
member self.DrawSprites() =
_spriteBatch.Begin()
for i = 0 to _list.Length-1 do
let spentity = _list.List.ElementAt(i)
if spentity.ImageTexture.IsDisposed then
spentity.ImageTexture <- _list.Content.Load<Texture2D>(spentity.Name)
_spriteBatch.Draw(spentity.ImageTexture,new Rectangle(100,100,(int)spentity.Width,(int)spentity.Height),Color.White)
_spriteBatch.End()
(*Overriding*)
override self.Initialize() =
ChangeGraphicsProfile()
_list.AddSprite(0,"NagatoYuki",992.0,990.0)
base.Initialize()
override self.LoadContent() =
ChangeGraphicsProfile()
_graphicsDevice <- _graphics.GraphicsDevice
_spriteBatch <- new SpriteBatch(_graphicsDevice)
base.LoadContent()
I adjust the graphicsDevice whenever my game needs to LoadContent, and in the DrawSprites() method I check if the texture is disposed, if it is, load it up again.
But this thing bugs me. I didn't know I had to Load all Content again everytime the window is minimized.
(And the code makes it look like Initialize() loads Content, and LoadContent() initializes, but oh well)
A: What you are observing is normal behaviour, it's by the way not specific to F#. See http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent.aspx
This method is called by Initialize. Also, it is called any time the game content needs to be reloaded, such as when the DeviceReset event occurs.
Are you loading all of your content in Game.LoadContent? If you do, you should not be getting these errors.
| |
doc_2896
|
So instead of what is below:-
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};
return my;
}());
MODULE could be set to anything you like, I remember seeing it done i a screencast but can't remember where...
Basically i'd like to create a library that could be assigned to any namespace the implementer likes.
A: I'd think you'd just be able to add a method that lets you set it, and nullify MODULE.
http://jsfiddle.net/yrsdR/
my.namespace = function( ns ) {
window[ns] = my;
window.MODULE = null;
}
then:
window.MODULE.namespace( "myNamespace" );
window.MODULE; // null
window.myNamespace // object
or you could have it return the module to whatever variable you want.
http://jsfiddle.net/yrsdR/1/
my.namespace = function() {
window.MODULE = null;
return my;
}
window.myNamespace = MODULE.namespace();
window.MODULE; // null
window.myNamespace // object
A: Funny to come across this now, I just set up a new code base this way. This is how I approached it (it depends on 1 extra global variable however):
// ability to rename namespace easily
var AXS_NS = 'App';
window[AXS_NS] = (function (app, $, Modernizr) {
app.config = {
debug: false
};
app.init = function() {
console.log('init');
};
return app;
})(window[AXS_NS] || {}, jQuery, Modernizr);
Then you could do:
jQuery(function($){
App.init();
});
A: I know this is a long ways after the original question. And I'm not sure of the relevance of having a dynamically named javascript object. But the following pattern does this is a reasonable way by allowing you to set up the object namespace name in the script element of your html page.
Something like
<script src="js/myscript.js" namespaceName="myObject"><script>
Which allows you to then call myObject.hello() in your javascript.
Example javascript that uses this solution.
/**
* Dynamic mechanism for setting a javascript namespace.
*
* This works by adding the namespaceName as an attribute to the script
* element on your page. Something like
*
* **<script src="js/myscript.js" namespaceName="myObject"><script>**
*
* When the script has loaded it will have created a new javascript object
* with the nemespace name "myObject".
*
* You can now use myObject.hello() which returns "ns.hello() called"<br/>
*
* This works on later versions of chrome, firefox and ie.
*/
(function (ns) {
ns.hello = function () {
return "ns.hello() called";
}
} (window[document.getElementsByTagName('script')[document.getElementsByTagName('script').length-1].attributes['namespaceName'].value]=
window[document.getElementsByTagName('script')[document.getElementsByTagName('script').length-1].attributes['namespaceName'].value] || {}));
The
window[document.getElementsByTagName('script')
[document.getElementsByTagName('script').length-1]
.attributes['namespaceName'].value]
Is used to pull the attribute namespaceName value from the script load
| |
doc_2897
|
I am confused as to how to get results from my server to be processed by tokenInput. The following article, What is JSONP?, suggests that I need to add a callback query param to get cross-domain jsonp working:
$(function() {
$("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
preventDuplicates: true,
crossDomain: true,
});
});
This is used to wrap the response in my php code:
header('Content-type: text/javascript');
echo $this->request->query('callback') . '(' . json_encode($token_array) . ')';
exit;
Which then calls the jsonprocess() method in my javascript. However this is out of context of the tokenInput instance so I can't populate the results. Is this the correct functionality? Or is there a way to make the jQuery tokeninput plugin process the jsonp directly?
The success callback in tokeninput:
ajax_params.success = function(results) {
cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hidden_input, results);
}
};
...is never called.
A: As you can see in jQuery Tokeninput documentation, crossDomain must be set as true in options, if you want to it to be a jsonp request.
$(function() {
$("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
preventDuplicates: true,
crossDomain: true
});
});
and The right JSON content type is application/json.
header('Content-type: application/json');
UPDATE:
Ok if it's not working with jsonp you should try it by enabling CORS.
Here what you will do,
$(function() {
$("#token").tokenInput("http://localhost/token/search?callback=jsonprocess", {
preventDuplicates: true,
crossDomain: false, //it's also false as default.
});
});
in PHP you must enable CORS, and you don't need to take result into the callback function. you will dump only JSON.
header("Access-Control-Allow-Origin: *");
header('Content-type: text/javascript');
echo json_encode($token_array);
exit;
A: Easier than I thought; don't need ?callback=jsonprocess in the search url
$(function() {
$("#token").tokenInput("http://localhost/token/search", {
preventDuplicates: true,
crossDomain: true,
});
});
A: Dude you need callback in javascript and php like this:
javascript:
script.php?callback=?&your_parametars_here
and in php
echo $_GET['callback'].$your_data_here
| |
doc_2898
|
Each shared_ptr holds the same memory, but still the count for each one is one.
So, each shared pointer is different, so when they go out of scope they try to free the block and this causes corrupting the heap. My question is how to avoid this?
Just want to add declaration like this
shared_ptr<int> x(p);
is non negotiable I have to declare it.
#include <iostream>
#include <memory>
using namespace std;
int main ()
{
int* p = new int (10);
shared_ptr<int> a (p);
shared_ptr<int> b (p);
shared_ptr<int> c (p);
shared_ptr<int> d (p);
cout<<"Count : "<<a.use_count()<<endl;
cout<<"Count : "<<b.use_count()<<endl;
cout<<"Count : "<<c.use_count()<<endl;
cout<<"Count : "<<d.use_count()<<endl;
return 0;
}
A: You may only crate a smart pointer from a raw one if you have ownership over the pointer. As soon as you create the smart pointer, the ownership will have been passed to the smart pointer. Since you no longer have the ownership, you may not create additional smart pointers from the raw pointer.
To get a shared pointer to memory that is already managed/owned by a shared pointer, you must copy from the existing shared pointer:
shared_ptr<int> b = a;
shared_ptr<int> c = a;
// ....
If you simply create multiple shared pointers from the raw pointer, then none of those shared pointers will know about the existence of each other, and all of them will believe to be the sole owner of that memory and the problems you describe will occur.
| |
doc_2899
|
I need to find the files that have changed between 2 branches of my repository. I use the following command to that:
git diff branch_2..branch_1
I get the follwing error:
fatal: ambiguous argument 'branch_2..branch_1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
git branch gives the following o/p:
git branch -a
* branch_1
master/origin
remotes/origin/HEAD -> origin/master
remotes/origin/branch_2
remotes/origin/branch_1
A: Sometimes you got a shallow git repo, created using
git clone --depth 1 <repo-url>
Trying to git diff fails w/ a fatal: ambiguous argument error:
fatal: ambiguous argument [...]: unknown revision or path not in the working tree.
You then need to make your refs locally available. Convert a shallow git repo to a full (unshallow) repo from a shallow one, see git deep fetch and git unshallow.
Then it should be able to git diff branches:
git diff branch1
Aformentioned example compares branch1 to the active working branch.
HTH
A: If you are simply doing:
git diff branch2..branch1
This will not work, as listed in your git branch list, your 'remotes' are specified as "origin". What this actually means is that you have those branches on your remote, but they aren't actually checked out locally.
So you have two options here. Try these, and let me know how it goes.
Based on the branch list provided:
Diff using origin/
git diff origin/branch2..branch1
If you want to checkout these branches locally to perform your diff and maybe work on them on your workstation. Furthermore, supporting the diff in this format:
git diff branch2..branch1
What you need to do is actually checkout those branches to set them as local branches from your remote. Simply do this:
git checkout branch2
Then you can do
git diff branch2..branch1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.