id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_5000
|
Thanks
| |
doc_5001
|
It works perfectly in Windows XP, but not on 64-bit Vista, where it fails with "Access denied". Looking into the server's access log, I can see that it gets Error 401 unauthorized, and no username seems to be transferred to the webserver.
In other words, it seems that the SOAP request does not include the username, if it is run on Windows Vista 64-bit, whereas on Windows XP, everything works perfectly.
Does anybody have an idea what this could be?
A: There is much too little information here to be able to tell anything, but I'll venture an educated guess - it's a permission issue. When obtaining the local username you're doing something that requires Administrator access - and under Vista you're by default running as a limited user.
Try running the app by right clicking it and choosing Run as Administrator. If it works then, you've confirmed that suspicion.
How exactly are you querying the credentials which you want to send over the network?
Edit: Never mind, it was a different issue altogether :)
| |
doc_5002
|
$string = "Time: 10:40 Request: page.php Action: whatever this is Refer: Facebook";
Then from something like this I want to achieve an array such that:
$array = ["Time: 10:40", "Request: page.php", "Action: whatever this is", "Refer: Facebook"];
I've tried the following so far:
$split = preg_split('/(:){0}\s/', $visit);
But this is still splitting at every occurence of a white space.
Edit: I think I asked the wrong question, however "whatever this is" should stay as a single string
Edit 2: The bits before the colons are known and stay the same, maybe incorporating those somehow makes the task easier (of not splitting at whitespace characters in strings that should stay together)?
A: You can use a lookahead in your split regex:
/\h+(?=[A-Z][a-z]*: )/
RegEx Demo
Regex \h+(?=[A-Z][a-z]*: ) matches 1+ whitespaces that is followed by a word starting with upper case letter and a colon and space.
A: you can do it
$string = "Time: 10:40 Request: page.php Action: whatever this is Refer: Facebook";
$split = preg_split('/\h+(?=[A-Z][a-z]*:)/', $string);
dd($split);
A: Another option could be to match what is before the colon and then match upon the next part that starts with a space, non whitespace chars and colon:
\S+:\h+.*?(?=\h+\S+:)\K\h+
*
*\S+: Match 1+ times a non whitespace char
*\h+ Match 1+ times a horizontal whitespace char
*.*? Match any char except a newline non greedy
*(?=\h+\S+:) Positive lookahead, assert what is on the right is 1+ horizontal whitespace chars, 1+ non whitespace chars and a colon
*\K\h+ Forget what was matched using \K and match 1+ horizontal whitespace chars
Regex demo | php demo
| |
doc_5003
|
I also have a simple string search query "query_str" (say).
How can i sort the ArrayList of book objects, based on search relevance of either book_title, book_author with "query_str"?
I am an application developer, not very experience with search ranking algorithms, but I found Lucene very interesting. The problem is, it is straightforward to sort a list of strings... but how to do it for a list of objects? (Maybe use the toString() method)
How do i get started with Lucene for this?
A: By default, when you search in Lucene, the results are sorted on relevance.
If you want to use some field in particular to be used in relevance (scoring), lucene provides way to boost score. Just search for "boosting in lucene".
- Query level boosting might be the best fit for your case.
| |
doc_5004
|
var result = [];
User.find(query, function(err, data){
result.push(data);
});
return result;
}
I try to push the data array into result, but keep getting an empty array back.
A: User.find() is async, so you can't just return the value immediately. You have two options to solve this problem:
Option 1:
Accept a callback parameter and call it when results are ready:
module.exports.findUser = function(query, cb) {
var result = [];
User.find(query, function(err, data){
result.push(data);
cb(err, result);
});
}
Common Node.js convention is to have callbacks that have the first parameter err, which would return any errors, and the second parameter the actual data you're giving back.
This would then be used like:
findUser('query', function (err, data) {
if (err) throw new Error(err);
console.log(data);
});
Option 2:
Return a Promise which can then be chained. This isn't super common Node.js convention (Option 1 is), but it's becoming a more prevalent and will likely become the norm in a year or two:
module.exports.findUser = function(query) {
return new Promise(function(resolve, reject) {
var result = [];
User.find(query, function(err, data){
err && reject(err) || result.push(data) && resolve(result);
});
}
}
This would be used like this:
findUser('query').then(result => console.log(result)).catch(err => throw new Error(err));
| |
doc_5005
|
My use case is that I am trying to have Java execute a batch script that needs JAVA_HOME to be set in the local environment. The environment that I am executing this on may not have JAVA_HOME set or even the java executable on the path, but I would assume that the JVM knows where its executable is located.
A: System.getProperty("java.home");
is one option. Which shows the following directory in my machine:
C:\Program Files\Java\jdk1.7.0_02\jre
Most important system properties are listed here.
A: The java.home property will supply the path to the currently running JRE, regardless of what is installed, or what JAVA_HOME is. See the Oracle documentation here.
System.getProperty("java.home");
| |
doc_5006
|
I have three tables: Managers, Employees and C. Managers and Employees have a one-to-many relationship as such:
CREATE TABLE Managers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE Employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
manager_id INT,
FOREIGN KEY (manager_id) references Managers(id)
);
Listing:
Table Managers:
id | name
-----------
1 | Eve
2 | Amber
Table Employees:
id | name | manager_id
-------------------
1 | George | 1
2 | Cecilia | 1
3 | Steve | 2
4 | Martin | 2
Now, I would like to have table C (can't think of a name that would make sense in this specific example) with a reference to Employees such that for every entry in C there's one employee per manager. Could look like this:
Table C:
id | name | employee_id
--------------------------
1 | John | 1
2 | Debora | 3
Adding another entry to C with a reference to an employee who shares the same manager shouldn't be possible. E.g. Adding VALUES (Sheryl, 2) to C shouldn't be allowed since employee with id 2 shares the same managers as employee with id 1 which is already referred in C.
Like a many-to-one from C to Employees with respect to Employees relation to Managers.
Again, I'm sure there's a better way to do this that I can't think of now.
A: -- Manager MNG exists.
--
manager {MNG}
PK {MNG}
-- Employee EMP is managed by manger MNG.
--
employee {EMP, MNG}
PK {EMP}
SK {EMP, MNG}
FK {MNG} REFERENCES manager {MNG}
-- Manager MNG assigned employee EMP as a deputy,
-- in charge when the manager is not available.
--
deputy {MNG, EMP}
PK {MNG}
FK {EMP, MNG} REFERENCES employee {EMP, MNG}
Note:
All attributes (columns) NOT NULL
PK = Primary Key
FK = Foreign Key
SK = Proper Superkey (Unique)
| |
doc_5007
|
A: As mentioned in the comments, so far it doesn't sound like you need a plugin, although we would need more information to be sure.
What I think you want to do is copy existing FileMaker data to another application. You say "The final goal is to export the data into an editor..." Which begs the question, why does the data have to be edited in an editor and not within FileMaker itself, either via the FileMaker Pro client or via a web application using the PHP API?
Assuming you do need this external editor for some reason, FileMaker can almost certainly export the data in some format that the external editor can work with (CSV, XML, HTML, whatever).
If the reason you're thinking of using the external editor is for security purposes, that can be handled with permissions in FileMaker.
| |
doc_5008
|
{
public static void LogDebug(string debuglog)
{
Console.WriteLine($"[Debug] {debuglog}", System.Drawing.Color.Yellow;); //That $ passes the arg(string log) into the string function thus printing it into console
}
public static void InfoLog(string infolog)
{
Console.WriteLine($"[Info] {infolog}", );
}
public static void WarningLog(string warning)
{
Console.WriteLine($"[Warn] {warning}", );
}
}
}
I made this piece of code to help me identify errors and stuff around but if it is all white it doesn't really help. That's why I'm asking you if you know about something easy to type like System.Drawing.Color.Yellow;
Instead of
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
which changes all the text written into that color. All I want its a simple call to change color then go back to white.
A: You can use Console.ResetColor() to reset the console back to the default colors. Then, I usually create a helper class that has Write and WriteLine methods that will let me customize the colors:
class ConsoleHelper
{
public static void Write(string message, ConsoleColor foreColor, ConsoleColor backColor)
{
Console.ForegroundColor = foreColor;
Console.BackgroundColor = backColor;
Console.Write(message);
Console.ResetColor();
}
public static void WriteLine(string message, ConsoleColor foreColor, ConsoleColor backColor)
{
Write(message + Environment.NewLine, foreColor, backColor);
}
}
Then, in the main program, you can do something like:
private static void Main()
{
Console.Write("If the text is ");
ConsoleHelper.Write("green", ConsoleColor.Green, ConsoleColor.Black);
Console.WriteLine(" then it's safe to proceed.");
Console.Write("\nIf the text is ");
ConsoleHelper.Write("yellow", ConsoleColor.Yellow, ConsoleColor.Black);
Console.Write(" or ");
ConsoleHelper.Write("highlighted yellow", ConsoleColor.White, ConsoleColor.DarkYellow);
Console.WriteLine(" then proceed with caution.");
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Which looks like:
Or, as in your example:
ConsoleHelper.WriteLine("White on blue.", ConsoleColor.White, ConsoleColor.Blue);
Console.WriteLine("Another line.");
Produces:
A: Try this function
static void WriteConsoleAndRestore(string text, ConsoleColor background, ConsoleColor foreground)
{
ConsoleColor currentBackground = Console.BackgroundColor;
ConsoleColor currentForeground = Console.ForegroundColor;
Console.BackgroundColor = background;
Console.ForegroundColor = foreground;
Console.WriteLine(text);
Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;
}
| |
doc_5009
|
<script>
$(function () {
//Date range picker with time picker
$('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
//Timepicker
$(".timepicker").timepicker({
showInputs: false
});
});
</script>
<script>
decrementHour: function() {
if (this.showMeridian) {
if (this.hour === 1) {
this.hour = 12;
} else if (this.hour === 12) {
this.hour--;
return this.toggleMeridian();
} else if (this.hour === 0) {
this.hour = 11;
return this.toggleMeridian();
} else {
this.hour--;
}
} else {
if (this.hour === 0) {
this.hour = 23;
} else {
this.hour--;
}
}
this.update();
},
</script>
<div class="bootstrap-timepicker">
<div class="bootstrap-timepicker-widget dropdown-menu">
<table>
<tbody><tr><td><a href="#" data-action="incrementHour"><i class="glyphicon glyphicon-chevron-up"></i></a></td><td class="separator"> </td><td><a href="#" data-action="incrementMinute"><i class="glyphicon glyphicon-chevron-up"></i></a></td><td class="separator"> </td><td class="meridian-column"><a href="#" data-action="toggleMeridian"><i class="glyphicon glyphicon-chevron-up"></i></a></td></tr><tr><td><span class="bootstrap-timepicker-hour">10</span></td> <td class="separator">:</td><td><span class="bootstrap-timepicker-minute">15</span></td> <td class="separator"> </td><td><span class="bootstrap-timepicker-meridian">AM</span></td></tr><tr><td><a href="#" data-action="decrementHour"><i class="glyphicon glyphicon-chevron-down"></i></a></td><td class="separator"></td><td><a href="#" data-action="decrementMinute"><i class="glyphicon glyphicon-chevron-down"></i></a></td><td class="separator"> </td><td><a href="#" data-action="toggleMeridian"><i class="glyphicon glyphicon-chevron-down"></i></a></td></tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="input-group" style="margin-right: 14px;margin-left: 14px">
<input type="text" class="form-control timepicker" id="start_time" name="start_time">
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
</div>
</div>
</div>
</div>
A: You can add disabled word in class where the user selects for picking the date. Also you need to add in css as
.disabled {
pointer-events: none;
}
This would work as Bootstrap don't have default disabled feature. But styling alone present.
| |
doc_5010
|
I found the following example but it does not seem to work:
SELECT TOP 5 obj.name, max_logical_reads, max_elapsed_time
FROM sys.dm_exec_query_stats a
CROSS APPLY sys.dm_exec_sql_text(sql_handle) hnd
INNER JOIN sys.sysobjects obj on hnd.objectid = obj.id
ORDER BY max_logical_reads DESC
Taken from:
http://www.sqlservercurry.com/2010/03/top-5-costly-stored-procedures-in-sql.html
A: This MSDN Magazine article provides excellent info on this topic.
A: If you want to find the worst performing queries by time taken, I'd use this:
SELECT *
FROM sys.dm_exec_query_stats a
CROSS APPLY sys.dm_exec_sql_text(sql_handle) hnd
ORDER BY total_elapsed_time/execution_count DESC
However, finding the "worst" queries often requires a bit more probing into the exec_query_stats DMV. There are lots of things to consider:
*
*Worst individual queries by time taken which the above query will yield.
*Worst CPU hogs (if you are running high on CPU) which would order by total_worker_time/execution_count
*Queries doing the most reads which are often queries that take the longest.
Now these queries will highlight queries that have poor performance but often you might have queries with "fair" performance but get called very frequently which drives down the overall performance of your app. To find these, order the above query by total_elapsed time (or total_[whatever metric you are interested in]) and do not divide by execution_count.
A: Finding slow performing queries with SQL Profiler
*
*Start SQL Profiler (preferrably on the live database).
*File -> New Trace
*Choose SQL server
*Tab filter
*Optionally set a filter on the database name
*Start the profiler (RUN)
*Save the result in a table, for example: _Mytrace, preferrably on a database server that hasn't got much to do already
*Filter the select queries
*order them by duration
*Check exectution plan for this queries
A: top 10 worst queries based on...:
SELECT TOP 10
total_worker_time/execution_count AS Avg_CPU_Time
,execution_count
,total_elapsed_time/execution_count as AVG_Run_Time
,(SELECT
SUBSTRING(text,statement_start_offset/2,(CASE
WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2
ELSE statement_end_offset
END -statement_start_offset)/2
) FROM sys.dm_exec_sql_text(sql_handle)
) AS query_text
FROM sys.dm_exec_query_stats
--pick your criteria
ORDER BY Avg_CPU_Time DESC
--ORDER BY AVG_Run_Time DESC
--ORDER BY execution_count DESC
| |
doc_5011
|
My code is the following:
const app = require('express')();
const bodyParser = require('body-parser');
var request = require('request-promise');
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/jow', (req, res, next) => {
console.log(req.body['g-recaptcha-response']);
var options = {
method: 'POST',
uri: 'https://www.google.com/recaptcha/api/siteverify',
body: {
secret: '6LcAuUoUAAAAAH-uiWl9cz0Wicg7iUsDxHImrgLO',
response: req.body['g-recaptcha-response'],
},
json: true // Automatically stringifies the body to JSON
};
request(options)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log('error');
})
});
I get the following output when I verify the CAPTCHA and send the form:
The errors state that I have a missing input response (while I have the token as we can see logged out) and a missing input secret. This indicates that something went wrong in the http request send using the request-promise package. What am I doing wrong here?
A: I know it's been a long time since the question, but, for future references, here's the solution.
The problem is with the body key:
body: {
secret: RECAPTCHA_SECRET,
response: req.body['g-recaptcha-response']
},
When using request-promise module and recaptcha, you should use the form key instead.
form: {
secret: RECAPTCHA_SECRET,
response: req.body['g-recaptcha-response']
},
Reference: https://github.com/request/request-promise#post-like-html-forms-do
| |
doc_5012
|
da_test = xr.DataArray(rt, dims=['dtime', 'lat', 'lon'], coords={'dtime': tAxis, 'lat': Y,
'lon': X},)
da_test2 = xr.DataArray(rt1, dims=['dtime', 'lat', 'lon'], coords={'dtime': tAxis, 'lat': Y,
'lon': X},)
da_test3 = xr.DataArray(rt2, dims=['dtime', 'lat', 'lon'], coords={'dtime': tAxis, 'lat': Y,
'lon': X},)
ds = xr.Dataset({"test" : da_test, "test2" : da_test2, "test3" : da_test3})
Now I am trying to save the dataset to netcdf file. If the file exists, I open the dataset, concatenate the current dataset along 'dtime' axis and store it back to the netcdf. I have specified 'dtime' as unlimited dimension to make it extendable along that dimension.
dsList = [ds]
if os.path.isfile('./'+outFileName):
diskDS = xr.open_dataset(outFileName, group="/satGrp")
dsList.append(diskDS)
finalDS = xr.concat(dsList, dim="dtime")
diskDS.close()
else:
finalDS = ds
# Setting up compression and writing to nc file
comp = dict(zlib=True, complevel=5)
encoding = {var: comp for var in finalDS.data_vars}
finalDS.to_netcdf(outFileName, group="/satGrp", mode='a', format="NETCDF4", engine='h5netcdf', unlimited_dims=["dtime"], encoding=encoding)
I am trying to simulate a use case where the script will run every half hour and update netcdf with updated datasets. The first pass goes through successfully and the dataset is stored. But when I run it the next time, I get following error:
Traceback (most recent call last):
File "xr.py", line 87, in <module>
finalDS.to_netcdf(outFileName, group="/satGrp", mode='a', format="NETCDF4", engine='h5netcdf', unlimited_dims=["dtime"], encoding=encoding)
File "/usr/local/lib/python3.6/dist-packages/xarray/core/dataset.py", line 1384, in to_netcdf
compute=compute)
File "/usr/local/lib/python3.6/dist-packages/xarray/backends/api.py", line 886, in to_netcdf
unlimited_dims=unlimited_dims)
File "/usr/local/lib/python3.6/dist-packages/xarray/backends/api.py", line 929, in dump_to_store
unlimited_dims=unlimited_dims)
File "/usr/local/lib/python3.6/dist-packages/xarray/backends/common.py", line 271, in store
self.set_dimensions(variables, unlimited_dims=unlimited_dims)
File "/usr/local/lib/python3.6/dist-packages/xarray/backends/common.py", line 343, in set_dimensions
"%r (%d != %d)" % (dim, length, existing_dims[dim]))
TypeError: %d format: a number is required, not NoneType
Dataset stored in first pass:
<xarray.Dataset>
Dimensions: (dtime: 1, lat: 30, lon: 20)
Coordinates:
* dtime (dtime) datetime64[ns] 2019-09-18T12:06:00.298381
* lat (lat) int64 0 1 2 3 4 5 6 7 8 9 ... 20 21 22 23 24 25 26 27 28 29
* lon (lon) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Data variables:
test (dtime, lat, lon) float64 ...
test2 (dtime, lat, lon) float64 ...
test3 (dtime, lat, lon) float64 ...
Current run dataset in memory:
<xarray.Dataset>
Dimensions: (dtime: 1, lat: 30, lon: 20)
Coordinates:
* dtime (dtime) datetime64[ns] 2019-09-18T12:07:10.351870
* lat (lat) int64 0 1 2 3 4 5 6 7 8 9 ... 20 21 22 23 24 25 26 27 28 29
* lon (lon) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Data variables:
test (dtime, lat, lon) float64 47.42 977.8 168.2 ... 685.2 777.5 412.6
test2 (dtime, lat, lon) float64 105.4 2.173e+03 373.8 ... 1.728e+03 916.9
test3 (dtime, lat, lon) float64 26.32 542.7 93.36 ... 380.3 431.5 229.0
Concatenated dataset in memory:
<xarray.Dataset>
Dimensions: (dtime: 2, lat: 30, lon: 20)
Coordinates:
* lat (lat) int64 0 1 2 3 4 5 6 7 8 9 ... 20 21 22 23 24 25 26 27 28 29
* lon (lon) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
* dtime (dtime) datetime64[ns] 2019-09-18T12:07:10.351870 2019-09-18T12:06:00.298381
Data variables:
test (dtime, lat, lon) float64 47.42 977.8 168.2 ... 318.1 977.0 655.4
test2 (dtime, lat, lon) float64 105.4 2.173e+03 ... 2.171e+03 1.456e+03
test3 (dtime, lat, lon) float64 26.32 542.7 93.36 ... 176.6 542.3 363.7
While debugging I found the following in xarray common.py:
odict_items([('dtime', 2), ('lat', 30), ('lon', 20)])
<h5netcdf.Dimensions: lat=30, lon=20, dtime=None>
So the check is failing at existing_dims['dtime'] where its getting None.
Funny thing is, if I change mode to 'w' in to_netcdf call, the updates are smooth. But since I want to have multiple groups in the netcdf, I really need to use 'a' mode.
Look forward to ideas to mitigate this issue.
| |
doc_5013
|
*
*In an Xcode project add a new Cocoa Touch Class
*And select the "Subclass of" UIViewController Select "and also create XIB file"
*Then opening the .xib file there is only a UIView.
Any reason there is no UIViewController which would be the logical choice?
A: There is a connection. The connection is that the ViewController you have created is the owner of the xib. This means that you can add outlets and actions to your view controllers.
Also, xib files are just views. A view controller contains a view too by composition.
| |
doc_5014
|
*
*Using .NET 2013 (C# / VB).
*Mail client is Outlook (2010+).
*Mail server is Exchange.
Questions:
*
*Is there a way from a .NET project to directly send an email using some kind of Outlook object?
*Can it be sent without showing a new window and having to press "send"?
*Will the mail be saved to "Sent Items" folder if the "Send" process finishes successfully?
*Will the process receive back an event / notification if the mail was successfully sent or if it produced an immediate error during "send" (i.e. SMTP server down).
*Is there a built-in process (into the libraries that will be used) to detect if the mail was actually sent or it was returned back for some reason?
A: If you want the message to be in the Sent Items folder, straight SMTP won't work. But you can use the Outlook Object Model or EWS.
| |
doc_5015
|
confirmed, dispatched, recieved.
if passed pending it display pending with tick and if its confirmed on
dropdown it shows confimed with two ticks and dispatched with three ticks
and so on. Tried creating drop down which selects the all four values dont understand how
to implement tickmarks based on the text value and show that widget that I made.
Please help. Thanks.
class OrderListScreen extends StatefulWidget {
const OrderListScreen({Key? key}) : super(key: key);
@override
State<OrderListScreen> createState() => _OrderListScreenState();
}
class _OrderListScreenState extends State<OrderListScreen> {
@override
Widget build(BuildContext context) {
return Material(
child: Container(
child: Column(
children: <Widget>[
Text(
" Please select the order status from the dropdown Below:",
style: TextStyle(backgroundColor: Colors.orange)),
Container(
child: Material(
child: DropdownButton<String>(
items: <String>[
'Pending',
'Confirmed',
'Dispatched',
'Recieved'
].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
),
)),
],
),
),
);
}
}
OrderStatus Widget (that has all dropdown values):
OrderStatusBar(title: widget.order.orderStatus, status: true),
class OrderStatusBar extends StatefulWidget {
const OrderStatusBar({Key? key, required this.title, required this.status})
: super(key: key);
final String title;
final bool status;
@override
State<OrderStatusBar> createState() => _OrderStatusBarState();
}
class _OrderStatusBarState extends State<OrderStatusBar> {
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Row(
children: [
widget.status ? dottedCircleWithCheckMark() : dottedCircle(),
const SizedBox(width: 30),
Text(
widget.title.tr,
style: TextStyle(
fontSize: 20,
fontWeight: widget.status ? FontWeight.bold : null,
),
),
],
),
);
}
}
const size = 25.0;
const strokeWidth = 1.0;
const checkedColor = Color.fromRGBO(232, 113, 65, 1);
Widget dottedLine() {
return Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topRight,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 0, size / 2, 0),
child: const Padding(
padding: EdgeInsets.only(left: 27 / 2),
child: SizedBox(
height: size,
child: DottedLine(
dashColor: Colors.black,
direction: Axis.vertical,
lineLength: size,
lineThickness: strokeWidth,
dashLength: 5,
dashGapLength: 5,
),
),
),
),
),
);
}
dottedCircle() {
return DottedBorder(
borderType: BorderType.Circle,
dashPattern: const [5, 5],
child: Container(
height: size,
width: size,
decoration: const BoxDecoration(shape: BoxShape.circle),
));
}
dottedCircleWithCheckMark() {
return Container(
height: size + strokeWidth * 2,
width: size + strokeWidth * 2,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: checkedColor,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: size / 4 * 3,
),
);
}
A: Create a callback on OrderListScreen to get selected item.
class OrderListScreen extends StatefulWidget {
final Function(String? selectedValue) callback;
const OrderListScreen({Key? key, required this.callback}) : super(key: key);
@override
State<OrderListScreen> createState() => _OrderListScreenState();
}
And get value from from onCHanged
onChanged: (v) {
widget.callback(v);
setState(() {
selectedValue = v;
});
},
Now on parent widget.
class _AppXState extends State<AppX> {
final items = <String>['Pending', 'Confirmed', 'Dispatched', 'Recieved'];
int selectedItemIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
OrderListScreen(
callback: (selectedValue) {
if (selectedValue != null && items.contains(selectedValue)) {
selectedItemIndex = items.indexOf(selectedValue);
setState(() {});
}
},
),
for (int i = 0; i < items.length; i++)
OrderStatusBar(title: items[i], status: i <= selectedItemIndex),
],
),
);
}
}
Test snippet
class AppX extends StatefulWidget {
AppX({Key? key}) : super(key: key);
@override
State<AppX> createState() => _AppXState();
}
class _AppXState extends State<AppX> {
final items = <String>['Pending', 'Confirmed', 'Dispatched', 'Recieved'];
int selectedItemIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
OrderListScreen(
callback: (selectedValue) {
if (selectedValue != null && items.contains(selectedValue)) {
selectedItemIndex = items.indexOf(selectedValue);
setState(() {});
}
},
),
for (int i = 0; i < items.length; i++)
OrderStatusBar(title: items[i], status: i <= selectedItemIndex),
],
),
);
}
}
class OrderListScreen extends StatefulWidget {
final Function(String? selectedValue) callback;
const OrderListScreen({Key? key, required this.callback}) : super(key: key);
@override
State<OrderListScreen> createState() => _OrderListScreenState();
}
class _OrderListScreenState extends State<OrderListScreen> {
String? selectedValue;
@override
Widget build(BuildContext context) {
return Material(
child: Container(
child: Column(
children: <Widget>[
Text(" Please select the order status from the dropdown Below:",
style: TextStyle(backgroundColor: Colors.orange)),
Container(
child: Material(
child: DropdownButton<String>(
value: selectedValue,
items: <String>[
'Pending',
'Confirmed',
'Dispatched',
'Recieved'
].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Row(
children: [
Text(value),
],
),
);
}).toList(),
onChanged: (v) {
widget.callback(v);
setState(() {
selectedValue = v;
});
},
),
)),
],
),
),
);
}
}
| |
doc_5016
|
var request = new XMLHttpRequest();
request.open("GET", 'http://code.jquery.com/jquery-2.1.1.min.js');
request.onerror = function(error) {
alert(error.target.status)
};
request.send()
I will get the following expected error message in the developer console.:
XMLHttpRequest cannot load http://code.jquery.com/jquery-2.1.1.min.js No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
But is this error message from the XmlHttpRequest or from the Browser?
I want to graps that error message from the XmlHttpRequest, but I can't see where.
With the above code I would expect (as seen in https://stackoverflow.com/a/16931075/343475) to see an error message in the alert box, but all I get is 0.
A:
But is this error message from the XmlHttpRequest or from the Browser?
XMLHttpRequest is part of the browser. So "yes".
If you meant "Is the error from the server or from the browser" then it is from the browser. The server can't know if you are making a cross origin request or not.
With the above code I would expect (as seen in https://stackoverflow.com/a/16931075/343475) to see an error message in the alert box, but all I get is 0.
The status code would provide information about the resource on the foreign origin (it would tell you if the resource existed and if the user of the browser had permission to access it) so it is suppressed by the Same Origin Policy.
| |
doc_5017
|
xx:xx:xx:xx/120
via jinja2 filter i would like to take only the IPv6 excluding the subnet. My output after rendering should be
xx:xx:xx:xx
I read all the filters from
https://jinja.palletsprojects.com/en/3.1.x/templates/
but with no success.
Any hint?
Thank you.
| |
doc_5018
|
@interface TESTAppDelegate ()
@property (nonatomic, strong) NSMetadataQuery *query;
@end
@implementation TESTAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchProgressed:) name:NSMetadataQueryGatheringProgressNotification object:nil];
NSMutableArray *predicates = [@[] mutableCopy];
#define add(format, ...) { \
[predicates addObject:[NSPredicate predicateWithFormat:format, ##__VA_ARGS__]]; \
}
//Toggle which of these lines are commented to experiment with breaking the query
//add(@"kMDItemKind like[c] %@", @"*"); //Works
//add(@"(kMDItemContentType != 'com.apple.mail.emlx.part')"); //Works
//add(@"(kMDItemContentType == 'public.data')"); //Works
//add(@"kMDItemFSName like[c] %@", @"*"); //DOES NOT WORK
add(@"kMDItemFSName like[c] %@", @"*Nashville*"); //works...
self.query = [[NSMetadataQuery alloc] init];
[_query setPredicate:predicates.count > 1? [NSCompoundPredicate andPredicateWithSubpredicates:predicates] : predicates.lastObject];
[_query setSearchScopes:@[[@"~/Downloads" stringByExpandingTildeInPath]]];
NSLog(@"Query %@", [_query startQuery]? @"started" : @"could NOT start!");
}
- (void)searchProgressed:(NSNotification *)note
{
NSLog(@"searchProgressed: %li", _query.resultCount);
}
@end
You should be able to confirm this following highly abnormal behavior "recently" introduced (post-Lion) on NSMetadataQuery: it apparently no longer works.
If you run the app as-is, it should log something like "searchProgressed 1204", meaning the query found results. But, if you run it after commenting out the other predicate, it finds nothing.
I have tried many variations of that line, including various formulations of the wildcard, or the %K placeholder, changing the LIKE[c] placeholder to other forms, and, of course, using things like NSMetadataItemFSNameKey, NSMetadataItemURLKey, and kMDItemContentType. Nothing works except the single, simplest case above.
I must be missing something huge about NSMetadataQuery, which I used extensively with great success before, because otherwise everyone would be commenting on how useless it is.
A: I’m just guessing, hopefully this doesn’t violate StackOverflow’s rules:
I wonder if Apple doesn’t want Spotlight used to list the contents of directories completely—it’s probably a pretty inefficient way to do that—so they’re filtering out “overly-broad” queries. If you change the “” to something else, like “F”, does it work?
‘-startQuery' returns a BOOL, have you seen what it’s returning?
| |
doc_5019
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
void* malloc(size_t size)
{
static void* (*real_malloc)(size_t) = NULL;
if (!real_malloc)
real_malloc = dlsym(RTLD_NEXT, "malloc");
void *p = real_malloc(size);
fprintf(stderr, "malloc(%d) = %p\n", size, p);
return p;
}
Valgrind is upset because there are buffers still allocated by dlsym at the end of the program.
==32691== 32 bytes in 1 blocks are still reachable in loss record 1 of 1
==32691== at 0x4C279FC: calloc (vg_replace_malloc.c:467)
==32691== by 0x528559F: _dlerror_run (dlerror.c:142)
==32691== by 0x5285099: dlsym (dlsym.c:71)
==32691== by 0x4060BC: malloc (memory.c:222)
How can I release those resources ?
Thanks
A:
1 blocks are still reachable
These blocks are just fine. You don't need to worry about them, they are not leaks. There is nothing to see here, move along.
It's the "definitely lost" that you should care about.
| |
doc_5020
|
%python
display(flutten_df.printSchema())
display(flutten_df[flutten_df['url'].str.contains("www.ebay.com")])
it gives me this error:
AnalysisException: Can't extract value from url#75009: need struct
type but got string;
the schema is :
root
|-- web: string (nullable = true)
|-- url: string (nullable = true)
How to fix this problem please?
A: You're trying to use pandas syntax on spark DataFrame.
In Pyspark, flutten_df['url'].str means get struct field str from column url. Thus you got that error saying it can't extract value from a column which is not a struct.
Use filter with rlike instead:
display(flutten_df.filter(~flutten_df['url'].rlike("www.ebay.com")))
| |
doc_5021
|
Firstly, once I've pulled the XML file from the API, I'm using DataSet's ReadXML method to create DataTables. There happens to be 19 in total within the DataSet once ingested.
I understand that I can use DataRelation to link all of the tables, but it looks like the ReadXML method has already inferred some schema info and thus generated what appear to be sensible relationships between each DataTable of the DataSet.
However, I'd like to end up with just one table to port into my database, not 19, and I'd prefer to join/merge/relate the tables in C#, instead of within SQL.
Can you advise on a best practice for creating a single table from all related DataTables within my current DataSet?
| |
doc_5022
|
(my code)
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")
request.returnsObjectsAsFaults = false
do {
let result = try? context.fetch(request)
for data in result as! [NSManagedObject] {
FacialViewControllerA = data.value(forKey: "titleA") as! String
}
A: Please refer to Tyler's comment so you learn more about optionals. Also, avoid the usage of ! which is used to force unwrap objects.
In your case, the crash could be happening due to two reasons:
*
*Either the object you are trying to unwrap is not an array [NSManagedObject]
*Or the fetchRequest returned 0 objects or nil value
To avoid the crash you should opt for optional unwrapping which is the safest way of unwrapping an object. You can either a guard-let or If-let statement
Please refer to the code below:
Using guard-let:
guard let unwrappedResult = result as? [NSManagedObject] else {
print("unwrap of result failed")
return
}
for data in unwrappedResult {
//perform your logic
}
Using if-let:
if let unwrappedResult = result as? [NSManagedObject] {
for data in unwrappedResult {
//perform your logic
}
}
A: You've misunderstood what the do-try-catch block does.
When you put the ? after try you are preventing the catch from getting hit. So if try fails, it is setting result to nil. Then you are force casting nil to [NSManagedObject].
You have two options:
*
*Remove the ? after try
*Like Vikram mentioned, don't force cast result, use as? [NSManagedObject]
1)
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
FacialViewControllerA = data.value(forKey: "titleA") as! String
}
} catch {
print("There was an error: \(error)")
}
2)
if let result = try? context.fetch(request) as? [NSManagedObject] {
for data in result {
FacialViewControllerA = data.value(forKey: "titleA") as! String
}
}
| |
doc_5023
|
public class Supplier {
....
....
....
}
I have also Subcontractor class and Subcontractor is a Supplier:
public class Subcontractor:Supplier {
....
....
....
}
In my db I have Suppliers table with data and another table with id field which is act as foreign key to suppliers table and I have in there also the subcintractor data.
In the entity framework edmx file I declared the inheritance relation:
Now I want to gett all the suppliers which are not subcontractors so I am doing:
context.Suppliers.OfType<Supplier>();
But this returns also the subcontractors..
How can I get only the Suppliers that are not subcontractors?
A: Give this a try:
context.Suppliers.Where(s => !(s is Subcontractor));
Edit
If you have more than one class which derives from Supplier the only option with LINQ to Entities seems to be something like:
context.Suppliers.Where(s => !(s is Subcontractor)
&& !(s is DerivedClass2)
&& !(s is DerivedClass3)); // etc.
Entity SQL supports an ONLY keyword which allows to query for a specific type. But a corresponding counterpart is not available as LINQ operator.
Here is an implementation of an OfTypeOnly<TEntity> operator but it makes heavy use of metadata information and manual expression building and might be overkill in simple scenarios.
A: I currently use the following LINQ extension, assuming sub-classes are located in the same assembly.
public static class MyLinqExtensions
{
public static IQueryable<T> OfTypeOnly<T>(this IQueryable<T> query)
{
Type type = typeof (T);
IEnumerable<Type> derivedTypes = Assembly
.GetAssembly(type)
.GetTypes()
.Where(t => t.IsSubclassOf(type));
return query.ExceptTypes(derivedTypes.ToArray());
}
public static IQueryable<T> ExceptTypes<T>(this IQueryable<T> query, params Type[] excludedTypes)
{
if (excludedTypes == null)
return query;
return excludedTypes.Aggregate(query,
(current, excludedType) => current.Where(entity => entity.GetType() != excludedType));
}
}
Usage:
// Get only entities of type Supplier, excluding subclasses.
var suppliers = context.Suppliers.OfTypeOnly<Supplier>();
A: context.Suppliers.Where(s => s.GetType() == typeof(Supplier));
| |
doc_5024
|
Exception in thread "main" java.lang.ExceptionInInitializerError
at model.DBManager.initEntityManagerFactory(DBManager.kt:11)
at controller.restapi.RestapiApplicationKt.main(RestapiApplication.kt:13)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: myPersistenceConfig] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:895)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at org.hibernate.ogm.jpa.HibernateOgmPersistence.createEntityManagerFactory(HibernateOgmPersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at model.util.HibernateOGMUtil.<clinit>(HibernateOGMUtil.kt:15)
... 2 more
Caused by: org.hibernate.MappingException: Could not determine type for: applicationdatamodel.sleep.SleepLevels, at table: Sleep, for columns: [org.hibernate.mapping.Column(levels)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:456)
at org.hibernate.mapping.Property.getType(Property.java:69)
at org.hibernate.jpa.event.spi.JpaIntegrator.integrate(JpaIntegrator.java:150)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:281)
at org.hibernate.ogm.boot.impl.OgmSessionFactoryBuilderImpl.build(OgmSessionFactoryBuilderImpl.java:55)
at org.hibernate.ogm.boot.impl.OgmSessionFactoryBuilderImpl.build(OgmSessionFactoryBuilderImpl.java:23)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
This is the code involved with the Exception:
class HibernateOGMUtil {
companion object {
private lateinit var entityManagerFactory: EntityManagerFactory
init {
try{
entityManagerFactory = Persistence.createEntityManagerFactory("myPersistenceConfig")
}catch (e:Exception){
println(System.err.println("Initial EntityManagerFactory creation failed." + e))
}
}
fun getEntityManagerFactory(): EntityManagerFactory{
return entityManagerFactory
}
}
}
On the other hand, I have tried to remove the attribute 'levels' from next Entity and then, there is no exception and persistence works. So I suppose that something wrong is happening with this attribute. Maybe I should add a special annotation but I´m really stuck on this.
Here is my code:
import applicationdatamodel.sleep.SleepLevels
import org.hibernate.annotations.Type
import java.util.*
import javax.persistence.*
@Entity
data class Sleep (
@Temporal(TemporalType.TIMESTAMP) val dateOfSleep: Date,
val user_cif: String,
val duration: Int,
@Temporal(TemporalType.TIMESTAMP) val startTime: Date,
@Temporal(TemporalType.TIMESTAMP) val endTime: Date,
val minutesAsleep: Int,
val minutesAwake: Int,
val levels: SleepLevels
){
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
private lateinit var id: String
}
I would apreciate any help.
A: The column causing the issue is: val levels: SleepLevels.
Hibernate doesn't know how to map this class on the database (I assume it's not an enum).
This means that you need to map it as:
*
*Embedded, using the @Embeddaded and @Embeddable annotations;
*Association, using the @OneToOne or @ManyToOne annotations.
Not knowing the details of your model I cannot help you more than this but you should be able to find all the details you need in the official hibernate documentation.
| |
doc_5025
|
Imagine I am setting up a new WordPress installation. I will create two new directories for my plugin and theme customization:
*
*wordpress/wp-content/plugins/myplugins/
*wordpress/wp-content/themes/mytheme/
I want to maintain these directories via Git. In Subversion, I would accomplish this by having trunk/myplugins/ and trunk/mytheme/ directories and checking out subdirectories. Does Git have a way to accomplish the same task using a single repository?
I could just be missing the boat on some Git paradigm, as a long time SVN user with little exposure to Git.
Edit: Multiple branches storing different content is an interesting way to handle this.
A: git clone --filter + git sparse-checkout downloads only the required files
E.g., to clone only files in subdirectory small/ in this test repository: https://github.com/cirosantilli/test-git-partial-clone-big-small
git clone --depth 1 --filter=blob:none --sparse \
https://github.com/cirosantilli/test-git-partial-clone-big-small
cd test-git-partial-clone-big-small
git sparse-checkout set small
This option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.
I have covered this in more detail at: How do I clone a subdirectory only of a Git repository?
Tested on git 2.30.0 on January 2021.
A: There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.
If you insist (or really need it), though, you could make a git repository with just mytheme and myplugins directories and symlink those from within the WordPress install.
MDCore wrote:
making a commit to, e.g., mytheme will increment the revision number for myplugin
Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.
The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.
Git really really wants you to use separate repositories for separate entities.
submodules
Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.
A: One thing I don't like about sparse checkouts, is that if you want to checkout a subdirectory that is a few directories deep, your directory structure must contain all directories leading to it.
How I work around this is to clone the repo in a place that is not my workspace and then create a symbolic link in my workspace directory to the subdirectory in the repository. Git works like this quite nicely because things like git status will display the change files relative to your current working directory.
A: Sparse checkouts are now in Git 1.7.
Also see the question “Is it possible to do a sparse checkout without checking out the whole repository first?”.
Note that sparse checkouts still require you to download the whole repository, even though some of the files Git downloads won't end up in your working tree.
A: Actually, "narrow" or "partial" or "sparse" checkouts are under current, heavy development for Git. Note, you'll still have the full repository under .git. So, the other two posts are current for the current state of Git but it looks like we will be able to do sparse checkouts eventually. Checkout the mailing lists if you're interested in more details -- they're changing rapidly.
A: You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.
The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.
The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)
A: As your edit points out, you can use two separate branches to store the two separate directories. This does keep them both in the same repository, but you still can't have commits spanning both directory trees. If you have a change in one that requires a change in the other, you'll have to do those as two separate commits, and you open up the possibility that a pair of checkouts of the two directories can go out of sync.
If you want to treat the pair of directories as one unit, you can use 'wordpress/wp-content' as the root of your repo and use .gitignore file at the top level to ignore everything but the two subdirectories of interest. This is probably the most reasonable solution at this point.
Sparse checkouts have been allegedly coming for two years now, but there's still no sign of them in the git development repo, nor any indication that the necessary changes will ever arrive there. I wouldn't count on them.
A: There is an inspiration here. Just utilize shell regex or git regex.
git checkout commit_id */*.bat # *.bat in 1-depth subdir exclude current dir, shell regex
git checkout commit_id '*.bat' # *.bat in all subdir include current dir, git regex
Use quotation to escape shell regex interpretation and pass wildcards to git.
The first one is not recursive, only files in 1-depth subdir. But the second one is recursive.
As for your situation, the following may be enough.
git checkout master */*/wp-content/*/*
git checkout master '*/wp-content/*'
Just hack the lines as required.
A: You can revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
| |
doc_5026
|
How can I do this?? With lucene possible?? I know lucene can specify store. I don't know about folder.
-->company home
---->mainfolder1
------->doc1
------->doc2
---->mainfolder2
A: Looks like
+PATH:"/app:company_home/cm:mainfolder1//."
is what you want in your search expression.
The full glory details about Alfresco search in general in path queries in particular are at http://wiki.alfresco.com/wiki/Search#Path_Queries
A: Correct is
PATH:"/app:company_home/cm:mainfolder1/*"
as you do not need to search nodes at any depth but only direct children of main folder1.
You can find additional explanations here
http://alfrescoblog.com/2014/07/09/alfresco-lucene-tutorial/
| |
doc_5027
|
Thank you
Tunnuz
A: Generally speaking never make something because some day you might be having to implement or do yadayada (it just makes life complicated and miserable Imho..). If you have a method that should only be used within its class, then make it private. If you ever have to extend it by inheritance than reconsider which functions might have to accessed from bellow. Usually I anyway abstract methods to my superclass so then I anyway have to do the thinking of what will be needed when and where..
A good reason why to ignore what I said about private methods, is if you want to test your internal functions i.e. in a unit test. In C# you can allow another project to see your protected methods from externally so you can write tests against them.
A: You should choose private , because of encapsulation. I do prefer conservative approach on this subject, I prefer private access modifier, if I do expect some extension then I choose protected access modifier. It is not good practice to choose protected modifier instead of private.
A: I don't think there's a drawback.
*
*Private variables, are variables that are visible only to the class to which they belong.
*Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.
So everything should be ok with your code. There's nothing "bad" about that. If you probably extend your class, the protected property will be definately right.
| |
doc_5028
|
So I have both sections, the projects-main-section and project-section-container (the expandable menu on the right) wrapped around a main container projects-main. I figured this would help to get the projects-main-section to grow with it, but no luck so far.
So, as the expandable menu grows in height, I want the projects-main-section to grow with the expanding projects-main parent div, but not exceed the footer.
How can I do this?
Fiddle
Here is what it looks like static.
When the menu expands, it looks like this. You will see the left container, projects-main-section, has a large gap under it from the footer.
<div id="projects-main">
<div id="projects-main-section">
<div id="projects-main-section-title-wrap">
</div>
</div><div id="project-section-container">
</div>
</div>
#projects-main {
height: auto;
}
#projects-main-section, #project-section-container {
display: inline-block;
vertical-align: top;
}
#projects-main-section {
height: 800px;
background: #6f9697;
width: 40%;
}
#project-section-container {
height: auto;
width: 60%;
}
A: May I suggest using flex
html, body{
margin: 0;
}
.flex{
display:flex;
}
.flex.column {
flex-direction: column
}
.over, .under {
background: #0099cc;
height: 75px;
}
.content{
flex: 1;
}
.left_col {
background: orange;
width: 50%;
}
.right_col {
background: lightgreen;
width: 50%;
}
<div class="flex column container">
<div class="over">
</div>
<div class="flex content">
<div class="left_col">
Grows with right column
</div>
<div class="right_col">
long content <br>long content <br>long content <br>long content <br>
long content <br>long content <br>long content <br>long content <br>
long content <br>long content <br>long content <br>long content <br>
long content last
</div>
</div>
<div class="under">
</div>
</div>
| |
doc_5029
|
Ok, for the life of me, I cannot figure this out.
First and foremost, I'm using a DataTable to store the data, which is coming from an SQL server 2008 database, and I'm binding it to a DataRepeater.
I've tried changing the binding like this:
label1.DataBindings.Add("Text", history, "Value", true, DataSourceUpdateMode.Never, "", "N");
which works great on textboxes and labels elsewhere, but not on the DataRepeater. (label1 is part of the ItemTemplate associated with the DataRepeater)
Since binding the data like that isn't working, I want to just take my DataTable and just force the column to have the format listed above.
And manually changing the format of the data: (it's a Float)
for (int i=0;i < history.Rows.Count;i++)
{
history.Rows[i]["Value"] = String.Format("{0:N}", history.Rows[i]["Value"]);
}
Doesn't work either, the datarepeater just changes it back.
I want this:
12,123,123.00
and I get this:
12123123
Any ideas?
A: Sorry for my bad english. This works fine for me.
private void textBox10_TextChanged(object sender, EventArgs e)
{
string f = String.Format("{0:#0.00}", Convert.ToDouble(((TextBox)sender).Text));
((TextBox)sender).Text = f;
}
example:
textBox10.Text= 48
result= 48.00
Change this code for each other data types.
That uses TextChanged event of the textbox in to Datarepeater.
A: I think it is your DataTable "history" that converts the values back to double. When the column's data type is double (which I suspect) then it accepts a string representation of a double and kindly converts it back.
You should add a computed column to your DataTable and fill it with the string representation of the numeric value.
BTW: you forgot a i++ in your for statement.
A: if you want to convert 12123123 to 12,123,123 automatically; put this code in _TextChanged event of your textbox:
int i = ((TextBox)sender).SelectionStart;
if (((TextBox)sender).Text != "")
{
string f = String.Format("{0:N0}", Convert.ToDouble(((TextBox)sender).Text));
((TextBox)sender).Text = f;
int len;
len = ((TextBox)sender).Text.Replace(",", "").Length;
if ((len %= 3) == 1)
{
i += 1;
}
((TextBox)sender).SelectionStart = i;
}
| |
doc_5030
|
I used this formula on onSelect of login button
If(LookUp('Account Name', Title = Username.Text, Password ) = Password, Navigate([@Screen1], ScreenTransition.Fade))
Here Account Name is my DataSource , Title and Password are columns in DataSource.
So how can i achieve this?
A: Let me see if I understand your question properly.
You have a SharePoint List of something like below.
list
And a login page like this
loginpage
on click on Signin button you want to verify Account and password exists in the list and let the user navigate to a welcome page.
Assuming the above scenario is what you want, the onSelect would look like this:
If((LookUp('list-test',AccountName = TextInput1.Text).Password = TextInput3.Text), Set(errorMessage, "");Navigate(Screen2,ScreenTransition.Fade), Set(errorMessage, "Wrong account name or password"))
*
*'list-test' - will be replaced by your datasource name
*AccountName - will be replaced with whatever column name in sharepoint list that contains the account title
*TextInput1 - will be replaced with the name of the TextInput that will contain the account name in login page
*Password - will be replaced with the name of the column in sharepoint list that contains the passwords
*TextInput3 - will be replaced with the name of the TextInput that will contain the user Input password
*errorMessage - this is a global variable I set to display an error message in case of failure
*Screen2 - will be the screen that you will take user to after successful check
In my example I have a label (label3) whose text is bound to that global variable errorMessage in case of error.
| |
doc_5031
|
driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='nav']"))
driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='content']"))
My goal is to get a function that takes an argument just to change nav or content since the rest is basically the same.
What I've already tried is:
def frame_switch(content_or_nav):
x = str(frame[name=str(content_or_nav)] #"frame[name='content_or_nav']"
driver.switch_to.frame(driver.find_element_by_css_selector(x))
But it gives me an error
x = str(frame[name=str(content_or_nav)]
^
SyntaxError: invalid syntax
A: The way this is written, it's trying to parse CSS code as Python code. You don't want that.
This function is suitable:
def frame_switch(css_selector):
driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))
If you are just trying to switch to the frame based on the name attribute, then you can use this:
def frame_switch(name):
driver.switch_to.frame(driver.find_element_by_name(name))
To switch back to the main window, you can use
driver.switch_to.default_content()
| |
doc_5032
|
Example:
Not valid: test@@test test,test test@te,st test@t.e,st
Valid: test@test test@te@st
Next pattern does exactly what I want (it checks whether a line contains @@ or , or . so the result is true/false):
/(@)\1+|[,.]/
but I don't like | sign here.
How can I fix it to use [ ] only? Or is there another way to do this?
A:
I don't like | sign here. How can I fix it to use [ ] only?
You can't. Using | is the only way if you want to have different patterns for @ and the other characters.
You can simplify your expression a bit. For example:
@@+|[,.]
| |
doc_5033
|
---- Show Server details
GO
SELECT
@@servername as ServerName,
@@version as Environment,
SERVERPROPERTY('productversion'),
SERVERPROPERTY ('InstanceName')
-- Show DB details
SELECT
name AS DBName ,
Collation_name as Collation,
User_access_Desc as UserAccess,
Compatibility_level AS CompatiblityLevel ,
state_desc as Status,
Recovery_model_desc as RecoveryModel
FROM sys.databases
ORDER BY Name
-- Sysadmin Roles
SELECT
p.name AS [Name],
r.type_desc,
r.is_disabled,
r.default_database_name
FROM
sys.server_principals r
INNER JOIN
sys.server_role_members m ON r.principal_id = m.role_principal_id
INNER JOIN
sys.server_principals p ON p.principal_id = m.member_principal_id
WHERE
r.type = 'R' and r.name = N'sysadmin'
-- Find all users associated with a database
DECLARE @DB_USers TABLE
(DBName sysname, UserName varchar(max), LoginType sysname, AssociatedRole varchar(max))--,create_date datetime,modify_date datetime)
INSERT @DB_USers
EXEC sp_MSforeachdb
use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%'''
SELECT
DBName,UserName ,LoginType ,
STUFF(
(
SELECT ',' + CONVERT(VARCHAR(500), AssociatedRole)
FROM @DB_USers user2
WHERE
user1.DBName=user2.DBName AND user1.UserName=user2.UserName
FOR XML PATH('')
)
,1,1,'') AS Permissions_user
FROM @DB_USers user1
GROUP BY
DBName,UserName ,LoginType --,create_date ,modify_date
ORDER BY DBName,UserName
--List of all the jobs currently running on server
SELECT
job.job_id,
notify_level_email,
name,
enabled,
description,
step_name,
command,
server,
database_name
FROM
msdb.dbo.sysjobs job
INNER JOIN
msdb.dbo.sysjobsteps steps
ON
job.job_id = steps.job_id
-- Show details of extended stored procedures
SELECT * FROM master.sys.extended_procedures
I don't know where to start
| |
doc_5034
|
FileUtils.copyInputStreamToFile(new FileInputStream(f1), f2);
copyInputStreamToFile is from apache.commons.io and will close the stream. I reason that this should close the InputStream in all usual situations, because if an exception happens when creating the InputStream there is nothing to close, and if one happens inside copyInputStreamToFile then this function will close the stream for me.
However, is it really safe to assume there can be no exception or error between the creation of the InputStream and the start of the try-block in copyInputStreamToFile? I'm thinking of unusual things like OutOfMemoryError or ThreadDeath. So, we could rewrite the code above as:
InputStream is = null;
try {
is = new FileInputStream(f1);
FileUtils.copyInputStreamToFile(is, f2);
} finally {
IOUtils.closeQuietly(is);
}
That should be safe, but do you think it is necessary?
A: I think it depends if your application is concurrent or not. If it is, you can not assume that between the creation of the InputStream and the body of copyInputStreamToFile no other code will run.
Marko Topolnik answers the case when the application is not concurrent.
| |
doc_5035
|
column_01.1
column_01.2
column_01.3
column_02.1
column_02.2
I can split these rownames with the following command:
strsplit(rownames(my_data),split= "\\.")
and get the list:
[[1]]
[1] "column_01" "1"
[[2]]
[1] "column_01" "2"
[[3]]
[1] "column_01" "3"
...
But since I want characters out of the first part and completely discard the second part, like this:
column_01
column_01
column_01
column_02
column_02
I have run out of tricks to extract only this part of the information. I've tried some options with unlist() and as.data.frame(), but no luck. Or is there an easier way to split the strings? I do not want to use as.character(substring(rownames(my_data),1,9)) as the location of the "." can change (while it would work for this example).
A: You can map [ to get the first elements:
sapply(strsplit(rownames(my_data),split= "\\."),'[',1)
...or (better) use regular expressions:
gsub('\\..*$','',rownames(my_data))
(translation: find all matches of (dot-character, something, end-of-string) and replace with empty string)
A: Since I like the stringr package, I thought I'd throw this out there:
str_replace(rownames(my_data), "(^column_.+)\\.\\d+", "\\1")
(I'm not great with regex so the ^ might be better outside the parenthesis)
| |
doc_5036
|
This is my code (I wasn't expecting it to work but I just tried it anyways and it didn't):
class CustomSignUpForm(UserCreationForm):
email = forms.EmailField()
is_teacher = forms.BooleanField(label='I am a teacher')
class Meta:
if is_teacher == True:
model = Teacher
else:
model = Student
fields = ['username', 'email', 'password1', 'password2', 'is_teacher']
A: Yes, you should be able to do this by overriding the save() Method.
Might need some tweaking, but this is generally what I'd do:
class CustomSignUpForm(UserCreationForm):
email = forms.EmailField()
is_teacher = forms.BooleanField(label='I am a teacher')
class Meta:
fields = ['username', 'email', 'password1', 'password2', 'is_teacher']
def save(self, commit=True):
# If you **Don't** want them to also be saved in the User's table, comment these lines out
user = super().save(commit=False)
if commit:
user.save()
# I'm doing get or create only on usernames,
# as I don't want changing the first name to create an entirely
# new object with a duplicate username
if self.cleaned_data.get('is_teacher'):
o, created = Teacher.objects.get_or_create(username=self.cleaned_data.get('username'))
else:
o, created = Student.objects.get_or_create(username=self.cleaned_data.get('username'))
# Manually set the fields
o.email = self.cleaned_data.get('email')
o.set_password(self.cleaned_data["password1"])
# Possibly not needed?- / Implied by table
# o.is_teacher = self.cleaned_data('is_teacher')
o.save()
return o
A: I think you should consider separating the two sign up forms.
It's okay for there to be separate sign up forms, and even separate sign up views in the use case that an application has two very distinct user types.
This is especially prominent when you want to manage permissions with, for example, teacher vs student email addresses, as it is likely a teacher can see more than a student, and therefore that is your intention.
I cant write the answer for you, because there isnt enough contextual information, and doing so would promote questions that are too broad, however, I believe that if you create psuedo:
class TeacherSignupView(...):
# configure the teacher sign ups
# use this view with the Teacher model
And then also in tandem, on another url:
class StudentSignupView(...):
# configure the student sign ups
Then it would be a trivial task to make specific behaviours for each user type.
| |
doc_5037
|
This is the given example that works
curl -X POST \
--header "Content-Type:application/json" \
-d @trace.json \
"https://api.mapbox.com/matching/v4/mapbox.driving.json"
This return me the accurate data.
What I am trying to achieve is the same but using vanilla PHP
function sendRequest() {
// initialise the curl request
$request = curl_init('https://api.mapbox.com/matching/v4/mapbox.driving.json');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'header' => 'Content-Type:application/json',
'file' => '@' . realpath('trace.json')
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
}
sendRequest();
I have tried this, but this returns me a invalid input error, although the input is copied from the example.
I have a feeling that its either down to the CURLOPT_POSTFIELDS that I am sending or the whole structure is wrong.
A: Use CURLOPT_HTTPHEADER, and not pass headers to POST data, like this:
curl_setopt($request, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json'
));
curl_setopt($request, CURLOPT_POSTFIELDS, array(
'file_contents' => '@' . realpath('trace.json')
));
| |
doc_5038
|
A: AJAX. That is all.
If you have any more specific issues, feel free to ask.
A: you could use the jQuery ajax function:
http://api.jquery.com/jQuery.ajax/
A: You can use an AJAX request (if I understood the question)
If your API is written in myapi.php, you can:
var word = "The Word";
$.ajax({
url: "myapi.php?action=searchfor&word="+word,
success: function(data){
alert(data);
}
});
...assuming you're using jQuery, of course :)
| |
doc_5039
|
Normally (i.e. for unstarred commands) I would do it like this:
\let\old@part\part
\renewcommand\part[2][]{
\old@part[#1]{#2}
… rest of definition}
That is, I would save the original definition of \part in \old@part and use that.
However, this doesn’t work for starred commands since they don’t define a single lexeme (unlike the \part command in the example above). This boils down to the following question: How can I save a starred command?
Notice that I already know how to redefine a starred command itself, using the \WithSuffix command from the suffix package. This isn’t the problem.
A: Thanks to @smg’s answer, I’ve cobbled together a solution that works perfectly. Here’s the complete source, along with explanatory comments:
% If this is in *.tex file, uncomment the following line.
%\makeatletter
% Save the original \part declaration
\let\old@part\part
% To that definition, add a new special starred version.
\WithSuffix\def\part*{
% Handle the optional parameter.
\ifx\next[%
\let\next\thesis@part@star%
\else
\def\next{\thesis@part@star[]}%
\fi
\next}
% The actual macro definition.
\def\thesis@part@star[#1]#2{
\ifthenelse{\equal{#1}{}}
{% If the first argument isn’t given, default to the second one.
\def\thesis@part@short{#2}
% Insert the actual (unnumbered) \part header.
\old@part*{#2}}
{% Short name is given.
\def\thesis@part@short{#1}
% Insert the actual (unnumbered) \part header with short name.
\old@part*[#1]{#2}}
% Last, add the part to the table of contents. Use the short name, if provided.
\addcontentsline{toc}{part}{\thesis@part@short}
}
% If this is in *.tex file, uncomment the following line.
%\makeatother
(This needs the packages suffix and ifthen.)
Now, we can use it:
\part*{Example 1}
This will be an unnumbered part that appears in the TOC.
\part{Example 2}
Yes, the unstarred version of \verb/\part/ still works, too.
A: There is no \part* command. What happens is the \part command takes a look at the next character after it (with \@ifstar) and dispatches to one of two other routines that does the actual work based on whether there's an asterisk there or not.
Reference: TeX FAQ entry Commands defined with * options
| |
doc_5040
|
*
*Generate and render the board
*Snake movement (with no eating and dying)
*Generate a fruit randomly inside the board
*Generate a fruit randomly again after being eaten
My issue now is to make the snake update and re-render itself inside the tick() every time it eats a fruit.
/**
* @returns {TickReturn}
*/
tick() {
// very simple movement code which assumes a single length snake
// no eating or dieing implemented yet.
let oldPosition = { ...this._snake[0]
};
switch (this._direction) {
case Direction.Up:
this._snake[0].y -= 1;
break;
case Direction.Down:
this._snake[0].y += 1;
break;
case Direction.Left:
this._snake[0].x -= 1;
break;
case Direction.Right:
this._snake[0].x += 1;
break;
}
if (this.eating(this._fruit)) {
this._fruit = this.nextFruitFn(); // update the position of the fruit
this.update(); // nothing's being done yet
}
return {
gameOver: this._isGameOver,
eating: false, // currently static, not doing anything yet
changes: [{
position: oldPosition,
tileValue: Tiles.Empty
},
{
position: this._snake[0],
tileValue: Tiles.Snake
},
{
position: this._fruit,
tileValue: Tiles.Fruit
}
]
};
}
eating(pos) {
let hasEaten = false;
this._snake.map((s, idx) => {
// if snake and position merged indices,
// then fruit has been eaten
hasEaten = (s.y === pos.y && s.x === pos.x) ? true : false;
if (hasEaten) {
this._board[pos.x][pos.y] = Tiles.Empty;
// make sure to clear the tile after eating
}
});
return hasEaten;
}
I am lost with two things here:
*
*How do you update the snake array? Do you simply get the current x,y index and reduce both of them by 1? { y: y-1, x: x-1 }?
*Once I successfully added the new array inside the snake, how do I properly render it in the TickReturn object? Currently, it is simply updating this._snake[0] at a position.
*How do I update the switch case that will include the succeeding parts of the snake? At the moment, it can only move itself fixed at index 0, like so:
switch (this._direction) {
case Direction.Up:
this._snake[0].y -= 1;
break;
case Direction.Down:
this._snake[0].y += 1;
break;
case Direction.Left:
this._snake[0].x -= 1;
break;
case Direction.Right:
this._snake[0].x += 1;
break;
}
Is this also a similar approach if I start considering the walls? Here's a screenshot of what I have so far:
| |
doc_5041
|
I'm having difficulty in writing sql query according to the input provided by the admin. Firstly i have to check which inputs are provided by the admin and then i have to run query according to that. Values entered by admin are assigned to properties and then queries are build according to values present in properties.
I'm using very inefficient code right now. It's running fine but it can be better.
My insert data code is:
public void InsertData()
{
try
{
var cn = ConfigurationManager.AppSettings["SGSDataBase_CN"];
con = new SqlConnection(cn);
con.Open();
com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
if (ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, DateOfBirth) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @DateOfBirth)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, DateOfBirth, MobileNo) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @DateOfBirth, @MobileNo)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, DateOfBirth, MobileNo, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @DateOfBirth, @MobileNo, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, DateOfBirth, MobileNo, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @DateOfBirth, @MobileNo, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, MobileNo, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @MobileNo, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
//com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, DateOfBirth) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @DateOfBirth)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
//com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
//com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, MobileNo) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @MobileNo)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
//com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin,DateOfBirth, MobileNo) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin,@DateOfBirth, @MobileNo)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
//com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
//com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email == null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, MobileNo) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @MobileNo)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
//com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray == null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, DateOfBirth, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @DateOfBirth, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
//com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
//com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if(ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth != null && ClsCreateUsersProperty.PhoneNumber == null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, DateOfBirth, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @DateOfBirth, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
//com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else if (ClsCreateUsersProperty.ImageArray != null && ClsCreateUsersProperty.DateOfBirth == null && ClsCreateUsersProperty.PhoneNumber != null && ClsCreateUsersProperty.Email != null)
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin, Image, MobileNo, Email) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin, @Image, @MobileNo, @Email)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.Parameters.AddWithValue("@Image", ClsCreateUsersProperty.ImageArray);
//com.Parameters.AddWithValue("@DateOfBirth", ClsCreateUsersProperty.DateOfBirth);
com.Parameters.AddWithValue("@MobileNo", ClsCreateUsersProperty.PhoneNumber);
com.Parameters.AddWithValue("@Email", ClsCreateUsersProperty.Email);
com.ExecuteNonQuery();
}
else
{
com.CommandText = "INSERT INTO dms.Users_Table (UserId, UserName, Password, Department, CreatedOn, ExpiredOn, IsAdmin) VALUES (@UserID, @UserName, @Password, @Department, @CreatedOn, @ExpiredOn, @IsAdmin)";
com.Parameters.AddWithValue("@UserID", ClsCreateUsersProperty.UserId);
com.Parameters.AddWithValue("@UserName", ClsCreateUsersProperty.UserName);
com.Parameters.AddWithValue("@Password", ClsCreateUsersProperty.Password);
com.Parameters.AddWithValue("@Department", ClsCreateUsersProperty.Department);
com.Parameters.AddWithValue("@CreatedOn", ClsCreateUsersProperty.CreatedOn);
com.Parameters.AddWithValue("@ExpiredOn", ClsCreateUsersProperty.ExpiredOn);
com.Parameters.AddWithValue("@IsAdmin", ClsCreateUsersProperty.IsAdmin);
com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (com != null)
com.Dispose();
if (con != null)
con.Dispose();
com = null;
con = null;
}
}
Please suggest efficient way to perform this action.
Thanks in advance
A: Without writing everything out this would be the idea:
Declare empty variables:
int UserId = 0;
string userName = "";
Fill variables with your data (assuming you are using a function?):
private void function(int id, string name, ...further params...) {
int UserId = 0;
string userName = "";
UserId = (id!=null) ? id : 0; /*Shorthand if statement to handle null values*/
userName = name;
/*further params*/
Add to query:
private void function(int id, string name ...further params...) {
int UserId = 0;
string userName = "";
int UserID = id;
string userName = name;
/*further params*/
com.CommandText = "INSERT INTO dms.Users_Table (all of your columns here) VALUES (@UserID, @UserName, ...all params declared above...)";
com.Parameters.AddWithValue("@UserID", UserID);
com.Parameters.AddWithValue("@UserName", userName);
/*further adding*/
}
Having looked around I found that using .add().value is better than .AddWithValue so maybe take a look into change this as well
.add() would be com.Parameters.Add("@UserID", SqlDbType.Int).value = UserID;
| |
doc_5042
|
Array (
[reply] => Array (
[recipient] => Array (
[@msisdn] => 1234123412
[@id] => 5b5f9635-15d7-44d8-b1e3-7015hj95c71c
)
)
)
So I want to get the @mssidn's and the @id's to use like this:
foreach($$$){
$sqldata .= '(' . $last_id . ',' . $msisdn . ',' . $id . '),';
}
$last_id comes from another function, so just need the two others.
I just can't seem to get it working, so any help will be much appreciated.
A: Simply iterate your array get the values by key @msisdn and @id
foreach($array as $value) {
foreach($value as $data) {
$sqldata .= '(' . $last_id . ',' . $data['@msisdn'] . ',' . $data['@id'] . '),';
}
}
A: start the foreach loop at the point in the data structure that you want to process and just loop over the contents of the inner array
foreach ($arr['reply'] as $recip){
$sqldata .= '(' . $last_id . ',' . $recip['@msisdn'] . ',' . $recip['@id'] . '),';
}
| |
doc_5043
|
how can I retrieve the objects from the vector.
How can I make sure to which derived class an object retrieved belongs.
class CricketPlayer:public SlumsMember
{
protected:
int runsScored;
int wicketsTaken;
int catchesTaken;
public:
CricketPlayer(int rNo,string n,double theGpa,char typ,int rScore,int theWicketTaken,int theCatchTaken);
int getRunsScored();
int getWicketsTaken();
int getCatchesTaken();
};
CricketPlayer::CricketPlayer(int rNo,string n,double theGpa,char typ,int rScore,int theWicketTaken,int theCatchTaken):
SlumsMember(rNo,n,theGpa,typ)
{
runsScored=rScore;
wicketsTaken=theWicketTaken;
catchesTaken=theCatchTaken;
}
int CricketPlayer::getRunsScored()
{
return (runsScored);
}
int CricketPlayer::getWicketsTaken()
{
return (wicketsTaken);
}
int CricketPlayer::getCatchesTaken()
{
return(catchesTaken);
}
class FootballPlayer:public SlumsMember
{
protected:
int goalsScored;
int assists;
int interceptions;
public:
FootballPlayer(int rNo,string n,double theGpa,char typ,int theGoalsScored,int theAssists,int theInterceptions);
int getGoalsScored();
int getAssists();
int getInterceptions();
};
FootballPlayer::FootballPlayer(int rNo,string n,double theGpa,char typ,int theGoalsScored,int theAssists,int theInterceptions):
SlumsMember(rNo,n,theGpa,typ)
{
goalsScored=theGoalsScored;
assists=theAssists;
interceptions=theInterceptions;
}
int FootballPlayer::getGoalsScored()
{
return(goalsScored);
}
int FootballPlayer::getAssists()
{
return(assists);
}
int FootballPlayer::getInterceptions()
{
return(interceptions);
}
Here I am using vector to store objects inside a vector.
int main() {
vector<SlumsMember> members;
SlumsMember *slumsMember;
slumsMember=new FootballPlayer(rNo,name,gpa,ch,a,b,c);
slumsMember=new CricketPlayer(rNo,name,gpa,ch,a,b,c);
members.push_back(*slumsMember);
SlumsMember *mbr;
for(int i=0;i<members.size();i++)
{
mbr=members[i];
//How to make sure to which base class an object retrieved belongs to and how to access it.
}
return 0;
}
A: I cleaned up your code a bit...
class SlumsMember
{
try this... make the getWicketsTaken function virtual in the base class
public:
virtual int getWicketsTaken();
int rollNumber;
string name;
double gpa;
char type;
};
class CricketPlayer:public SlumsMember
{
public:
overriding can help with type overload prevention
int getWicketsTaken() override;
int runsScored;
int wicketsTaken;
int catchesTaken;
};
class FootballPlayer: public SlumsMember
{
Then you can override the getWicketsTaken in this class too
int getWicketsTaken() override;
public:
int goalsScored;
int assists;
int interceptions;
};
int main() {
vector<SlumsMember*> members;
Please note that on the next line you should receive a compiler error if the value that you give it is not a type of slumsmember.
members.push_back(new FootballPlayer(rNo,name,gpa,ch,a,b,c));
members.push_back(new CricketPlayer(rNo,name,gpa,ch,a,b,c));
SlumsMember *mbr;
for(int i=0;i<members.size();i++)
{
mbr=members[i];
//How to make sure to which base class an object retrieved belongs to and how to access it.
int rollNumber = mbr->rollNumber;
double gpa = mbr->gpa;
etc... and Don't forget to free your objects at the end at some point so that you don't get memory leaks
}
return 0;
}
| |
doc_5044
|
Here is the cRUL command working in terminal properly.
curl -s --user 'api:key-...' \
https://api.mailgun.net/v3/DomainName/messages \
-F from='Excited User <mailgun@DomainName>' \
-F to=me@outlook.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!'
I can't make sense how I can run this command using Postman.
I tried to import cURL command into Postman but it doesn't import api:key. I really can't understand how I can import this api key into Postman to run the api properly.
Please help me to run this command using Postman.
Thank you!
A: For whoever wants to create the Postman request manually:
The --user (or -u) translates in Postman into Basic Auth Username and Password fields, which you find under the Authorization request nav option:
The -F (for form params) you add under Body request nav option, with x-www-form-urlencoded or form-data selected (if not sure which, check this question):
More on curl options here.
A: Try importing it like this
curl https://api:key@api.mailgun.net/v3/DomainName/messages \
-F from='Excited User <mailgun@DomainName>' \
-F to=me@outlook.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!'
| |
doc_5045
|
A: Well, I believe this should work, if I understand your needs correctly:
const elementToObserve = document.querySelector("#parentElement");
const lookingFor = '#someID';
const observer = new MutationObserver(() => {
if (document.querySelector(lookingFor)) {
console.log(`${lookingFor} is ready`);
observer.disconnect();
}
});
observer.observe(elementToObserve, {subtree: true, childList: true});
You will want to observe the parent of where you expect the element to appear. With the subtree and childList options set to true it will observe for changes there and fire callback once it spots any difference. And you can check in that callback if the element you are looking for is now on the page.
A: Following the documentation to produce a working example was non trivial, and the DOM documentation can provide useful clarification.
It turned out the MutationObserverInit dictionary was not an "object type" but just an Interface Description Language (IDL) term used to describe an options object for observing changes - an Object object is all that is required.
FWIW here's an example of detecting adding a new node with, or changing the id of an existing node to, "certainId".
"use strict";
const target = document.getElementById("target");
const observer = new MutationObserver( checkChanges);
const certainId = "certainId";
function checkChanges(changeList, fromObserver) {
console.log("Callback 2nd argument is the observer object: %s", fromObserver === observer);
for( let change of changeList) {
if( change.type == "attributes") {
if( change.target.id === certainId) {
console.log("id has been changed: ", change.target);
break;
}
}
else if( change.type == "childList") {
for( let node of change.addedNodes) {
if( node.id==certainId) {
console.log("target was added: ", node);
break;
}
}
}
}
}
observer.observe( target, {
subtree: true,
attributeFilter: ["id"],
childList: true
});
// test
function changeId() {
if( document.getElementById("test1")) {
test1.id = "certainId";
}
}
function insertSpan() { // button click
if( document.getElementById("test2")) {
test2.innerHTML = '<span id="certainId">span#certainId<\/span>';
}
}
<div id="target">
<div id="test1">
div#test1 (oriinally)
</div>
<div id="test2">
div#test2
</div>
</div>
<button type="button" onclick='changeId()'>Set id value</button> OR
<button type="button" onclick="insertSpan()">insert new element</button>
It is possible to click both test buttons in the snippet and produce elements with duplicate ids - best avoided in practice.
| |
doc_5046
|
JobA = some base dependencies. When that's compiled, I want to kick off both JobB and JobC.
When both JobB and JobC are complete I had a join trigger for JobD - to prevent JobE or JobF from kicking off when JobB or JobC complete.
The problem I have is that JobE or JobF kick off when either JobB or JobC complete.
Is this something which the join trigger plugin can achieve?
A
B C
D
E F
JobA is triggered by remote github pushes.
JobA has a post-build action to build JobB and JobC, and JobA also has a Join Trigger pointing at JobD
A: I'm an idiot, I forgot I had left something in which dicking around.
JobB and JobC were both configured to trigger JobD after a successful build, thus completely working against the join trigger.
DOH!
| |
doc_5047
|
This is the handler mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<bean id="beanNameResolver"
class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"
p:interceptors-ref="loggerInterceptor" />
<context:component-scan base-package="com.audiClave.controllers" />
<bean id="loggerInterceptor" class="com.audiClave.controllers.LoggerInterceptor" />
</beans>
Here is the interceptor:
package com.audiClave.controllers;
...
public class LoggerInterceptor extends HandlerInterceptorAdapter {
static Logger logger = Logger.getLogger(LoggerInterceptor.class);
static{
BasicConfigurator.configure();
logger.setLevel((Level)Level.INFO);
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
logger.info("Before handling the request");
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info("After handling the request");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info("After rendering the view");
super.afterCompletion(request, response, handler, ex);
}
}
The following message appears in the console:
Mapping [/REST/en/actions] to HandlerExecutionChain with handler [com.audiClave.controllers.RestController@18f110d] and 3 interceptors
The controller is called, but not the interceptor.
Why wouldn't the interceptors be called? I am using Spring 3.0.5
I have tried putting a debug breakpoint in all of the events and none are fired. Have set the logging to INFO but still no output.
The loggerInterceptor is being picked up because of the following log statement:
2011-06-22 21:11:39,828 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@f2ea42: defining beans [beanNameResolver,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#0,baseController,restController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,loggerInterceptor]; root of factory hierarchy
Maybe the class is positioned incorrectly in the list??
A: Not sure these will help but try to use
*
*org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping instead of DefaultAnnotationHandlerMapping and
*replace the schemaLocation to match your Spring version:
... http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
A: The following worked:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="loggerInterceptor" class="com.audiClave.controllers.LoggerInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"
p:interceptors-ref="loggerInterceptor" />
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for @Components to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="com.audiClave.controllers" />
</beans>
| |
doc_5048
|
<?php
$message = "";
$found = $valid = false;
if ($_POST['username'] != "") {
$domain_pos = strpos($_POST['username'], "@");
if ($domain_pos === false) {
$username = $_POST['username'];
$domain = $_POST['domain'];
} else {
$username = substr($_POST['username'], 0, $domain_pos);
$domain = substr($_POST['username'], $domain_pos + 1);
}
$current_password = $_POST['current_password'];
$new_password1 = $_POST['new_password1'];
$new_password2 = $_POST['new_password2'];
$root = $_SERVER['DOCUMENT_ROOT'];
$path_elements = explode('/', $root);
$root = "/{$path_elements[1]}/{$path_elements[2]}"; // for bluehost, extracts homedir ex: /homeN/blueuser may work with other hosts?
$shadow_file = "$root/etc/$domain/shadow";
// check if the shadow file exists. if not, either an invalid
// domain was entered or this may not be a bluehost account...?
if (file_exists($shadow_file)) {
// compare the new passwords entered to ensure they match.
if ($new_password1 == $new_password2) {
if (trim($new_password1) != "") {
// get the contents of the shadow file.
$shadow = file_get_contents($shadow_file);
$lines = explode("\n", $shadow);
// go through each line of shadow file, looking for username entered.
for ($i = 0; $i < count($lines); $i++) {
$elements = explode(":", $lines[$i]);
// found the user...
if ($elements[0] == $username) {
$found = true;
$passwd = explode("$", $elements[1]);
$salt = $passwd[2]; // get the salt currently used
// crypt the "Current Password" entered by user. Can use either builtin
// php crypt function or command line openssl command.
if (CRYPT_MD5 == 1) { // indicates whether or not the crypt command supports MD5.
$current = crypt($current_password, '$1$'.$salt.'$');
} else {
$current = trim(`openssl passwd -1 -salt "$salt" "$current_password"`);
}
// check if the current password entered by the user
// matches the password in the shadow file.
$valid = ($current == $elements[1]);
if ($valid) {
// if they match then crypt the new password using the same salt
// and modify the line in the shadow file with the new hashed password
if (CRYPT_MD5 == 1) {
$new = crypt($new_password1, '$1$'.$salt.'$');
} else {
$new = trim(`openssl passwd -1 -salt "$salt" "$new_password1"`);
}
$elements[1] = $new;
$lines[$i] = implode(":", $elements);
}
break;
}
}
if (!$found) {
$message = "The username you entered is not valid.";
} else if (!$valid) {
$message = "The password you entered is not valid.";
} else {
// write the new contents of the shadow back to the shadow file.
$shadow = implode("\n", $lines);
file_put_contents($shadow_file, $shadow);
$message = 'Your password has been updated.';
}
} else {
$message = "Your password cannot be blank.";
}
} else {
$message = "Both new passwords must match.";
}
} else {
$message = "The domain you entered is not valid.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Change Password</title>
</head>
<body>
<?php
if ($message != "") {
$color = $found && $valid ? "green" : "red";
echo "<span style=\"color:$color;\">$message</span>";
}
?>
<form action="" method="post">
<input type="hidden" name="domain" value="somebluehostdomain.com" />
<table>
<tbody>
<tr>
<td><label for="username">Username</label></td>
<td><input name="username" id="username" type="text" /></td>
</tr>
<tr>
<td><label for="current_password">Current Password</label></td>
<td><input name="current_password" id="current_password" type="password" /></td>
</tr>
<tr>
<td><label for="new_password1">New Password</label></td>
<td><input name="new_password1" id="new_password1" type="password" /></td>
</tr>
<tr>
<td><label for="new_password2">New Password</label></td>
<td><input name="new_password2" id="new_password2" type="password" /></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input type="submit" value="Change Password" />
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
I found it here: http://www.bluehostforum.com/showthread.php?15140-email-password-change&p=88735#post88735
But it doesn't work anymore.
"The password you entered is not valid." message appears, and of course the password is valid, because I can log in using it.
this is the error_log:
PHP Strict Standards: Non-static method PEAR::setErrorHandling() should not be called statically in /home1/account/public_html/site/mail/program/include/iniset.php on line 132
PHP Notice: Undefined index: username in /home1/account/public_html/site/mail/changepassword.php on line 6
I'm using PHP 5.4, on a bluehost server. Can it be incompatible? There are other way to allow users to change their email passwords from PHP (without need an administrator log in to cPanel)?
| |
doc_5049
|
A: You should be able to find this information in the device datasheet found on www.atmel.com
2.2.12 UCAP USB Pads Internal Regulator Output supply voltage. Should be connected to an external capacitor (1µF).
| |
doc_5050
|
The problem is that the second child (<h4> tag) is not being contained within the Flex Box and appears to overflow.
My efforts thus far have resulted in the <h4> tag fitting but the object-fit: cover ceasing to work.
Is this possible to do?
#content {
margin-left: 18%;
margin-right: 18%;
/*border: 1px solid black;*/
}
h1.page-title {
margin-top: 0;
padding: 39px 0px 39px 150px;
}
.image-pane {
display: flex;
background-color: rgba(0, 0, 0, 0.2);
}
.image-tile {
margin: 1%;
width: 48%;
}
span.image-tile>img{
width: 100%;
height: 100%;
object-fit: cover;
box-shadow: 5px 5px 20px 1px rgba(0, 0, 0, 0.2);
}
.image-text {
font-family: aftaSansRegular;
text-align: center;
}
<div id="content">
<h1 class="page-title">
Galleries
</h1>
<div class="image-pane">
<span class="image-tile">
<img src="http://i.turner.ncaa.com/ncaa/big/2016/03/21/379123/1458530071096-mbk-312-wisconsin-xavier-1920.jpg-379123.960x540.jpg" alt="Basketball Image 01"/>
<h4 class="image-text">
Sports
</h4>
</span>
<span class="image-tile">
<img src="https://www.bahn.com/en/view/mdb/pv/agenturservice/2011/mdb_22990_ice_3_schnellfahrstrecke_nuernberg_-_ingolstadt_1000x500_cp_0x144_1000x644.jpg" alt="Train Image 01"/>
<h4 class="image-text">
Models
</h4>
</span>
</div>
</div>
When replying could you please provide an explanation of why it occurs this way so I can understand it rather then just correct it :'P
A: When you tell an element to be height: 100%, it occupies the full height of the container. As a result, there is no space left for siblings. That's why the h4 is being rendered outside the container.
A simple fix is to make the child of the flex container (.image-tile) also a flex container.
Then the children (the image and the heading) become flex items. With flex-direction: column they stack vertically.
Because initial settings on flex items are flex-shrink: 1 and flex-wrap: nowrap, the image with height: 100% is allowed to shrink in order for all items to fit inside the container.
You then need to override the flex minimum height default (min-height: auto) so the image and heading both fit inside the container. More details here:
*
*Why doesn't flex item shrink past content size?
Also, as a side note, if you're going to use percentage margins (or padding) inside a flex container, consider this:
*
*Why doesn't percentage padding / margin work on flex items in Firefox?
#content {
margin-left: 18%;
margin-right: 18%;
}
h1.page-title {
margin-top: 0;
padding: 39px 0px 39px 150px;
}
.image-pane {
display: flex;
background-color: rgba(0, 0, 0, 0.2);
}
.image-tile {
display: flex; /* new */
flex-direction: column; /* new */
margin: 1%;
width: 48%;
}
span.image-tile > img {
min-height: 0; /* new */
width: 100%;
height: 100%;
object-fit: cover;
box-shadow: 5px 5px 20px 1px rgba(0, 0, 0, 0.2);
}
.image-text {
font-family: aftaSansRegular;
text-align: center;
}
<div id="content">
<h1 class="page-title">
Galleries
</h1>
<div class="image-pane">
<span class="image-tile">
<img src="http://i.turner.ncaa.com/ncaa/big/2016/03/21/379123/1458530071096-mbk-312-wisconsin-xavier-1920.jpg-379123.960x540.jpg" alt="Basketball Image 01"/>
<h4 class="image-text">
Sports
</h4>
</span>
<span class="image-tile">
<img src="https://www.bahn.com/en/view/mdb/pv/agenturservice/2011/mdb_22990_ice_3_schnellfahrstrecke_nuernberg_-_ingolstadt_1000x500_cp_0x144_1000x644.jpg" alt="Train Image 01"/>
<h4 class="image-text">
Models
</h4>
</span>
</div>
</div>
A: Image height 100% is creating issue because 100% height occupied by image itself due to parent flex property as flex makes child's height 100%. That's why title goes away from parent div.
So if you want to make it perfect, add some pixels height in image like 300px or anything according to your design.
#content {
margin-left: 18%;
margin-right: 18%;
/*border: 1px solid black;*/
}
h1.page-title {
margin-top: 0;
padding: 39px 0px 39px 150px;
}
.image-pane {
display: flex;
background-color: rgba(0, 0, 0, 0.2);
}
.image-tile {
margin: 1%;
width: 48%;
}
span.image-tile>img{
width: 100%;
height: 200px;
object-fit: cover;
box-shadow: 5px 5px 20px 1px rgba(0, 0, 0, 0.2);
}
.image-text {
font-family: aftaSansRegular;
text-align: center;
}
<div id="content">
<h1 class="page-title">
Galleries
</h1>
<div class="image-pane">
<span class="image-tile">
<img src="http://i.turner.ncaa.com/ncaa/big/2016/03/21/379123/1458530071096-mbk-312-wisconsin-xavier-1920.jpg-379123.960x540.jpg" alt="Basketball Image 01"/>
<h4 class="image-text">
Sports
</h4>
</span>
<span class="image-tile">
<img src="https://www.bahn.com/en/view/mdb/pv/agenturservice/2011/mdb_22990_ice_3_schnellfahrstrecke_nuernberg_-_ingolstadt_1000x500_cp_0x144_1000x644.jpg" alt="Train Image 01"/>
<h4 class="image-text">
Models
</h4>
</span>
</div>
</div>
| |
doc_5051
|
On my webpage I have code to get flashed messages for one set of messages:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
How can I create another instance of this and send an entirely different group of messages to it?
A: The documentation you linked to has a solution:
http://flask.pocoo.org/docs/0.10/patterns/flashing/#filtering-flash-messages
Filtering Flash Messages New in version 0.9.
Optionally you can pass a list of categories which filters the results
of get_flashed_messages(). This is useful if you wish to render each
category in a separate block.
So for example, you could flash messages like this:
flash('category one flash message', 'category1')
flash('category two flash message', 'category2')
Then in your template:
{% with messages = get_flashed_messages(category_filter=["category1"]) %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% with messages = get_flashed_messages(category_filter=["category2"]) %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
| |
doc_5052
|
[
{
"time": "00:00"
"SumofDays": 100,
"schedule": "sch_1"
},
{
"time": "00:00"
"SumofDays": 100,
"schedule": "sch_2"
},
{
"time": "01:00"
"SumofDays": 200,
"schedule": "sch_1"
},
{
"time": "01:00"
"SumofDays": 200,
"schedule": "sch_2"
}....
]
I need to render Above data in a Line graph. With 2 different colored lines for the two different schedules .
<LineChart width={1300} height={300} data={graphData}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="time" />
<YAxis dataKey="SumofDays" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="schedule" stroke="#0095FF" />
</LineChart>
Im unable to rendering the Line because the Line dataKey is not unique. I tried couple of options But still no luck. Any help will be much appreciated.
Thanks.
A: You need to manipulate your current graphData to get both values of two schedules in the same object like this:
const sch1Data = graphData.filter((d) => {
return d.schedule === "sch_1";
});
const sch2Data = graphData.filter((d) => {
return d.schedule === "sch_2";
});
const finalGrapData = sch1Data.map((d, index) => {
const sch2CurrentData = sch2Data.find((d2) => d.time === d2.time);
const finalData = {
...d,
sch_1: d.SumofDays,
sch_2: sch2CurrentData?.SumofDays
};
return finalData;
});
return (
<LineChart
width={500}
height={300}
data={finalGrapData}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="time" />
<YAxis />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey="sch_1"
stroke="#8884d8"
activeDot={{ r: 8 }}
/>
<Line type="monotone" dataKey="sch_2" stroke="#82ca9d" />
</LineChart>
);
You can take a look at this sandbox for a live working example of this solution.
| |
doc_5053
|
Authorization Error
Error 400: redirect_uri_mismatch
The redirect URI in the request, http://localhost:3000/api/auth/callback/google, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/${your_client_id}?project=${your_project_number}
Can you point me in the right direction to fixing this?
A:
Error 400: redirect_uri_mismatch
Is a configuration issue. The redirect uri is used to return the authorization code to your application after the user has consented to your applications access to your data. You have created a web client credentials up on Google developer console.
What you need to do is go back there and add a Redirect uri of
http://localhost:3000/api/auth/callback/google
It must match exactly don't add any spaces at the end or anything.
If you have any issues i have a video which will show you exactly how to add it Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.
A: Seems like there's a mismatch with the Authorized redirect URIs. Are you sure you have entered the correct URIs? Redirect URI should be the URL that you'll be redirecting the user to after the login page or the base URL of your application Eg: https://localhost:8000
Also, make sure that you are using the correct Client ID and Client secret
Similar Questions
*
*Google OAuth 2 authorization - Error: redirect_uri_mismatch
*Correct redirect URI for Google API and OAuth 2.0
| |
doc_5054
|
from turtle import shape
import numpy as np
class stack:
def __init__(self):
self.stack = np.empty(shape=(1,100),like=np.empty_like)
self.n = 100
self.top = -1
def push(self, element):
if (self.top >= self.n - 1):
print("Stack overflow")
else:
self.top = self.top + 1
self.stack[self.top] = element
def pop(self):
if (self.top <= -1):
print("Stack Underflow")
else:
print("Popped element: ", self.stack[self.top])
self.top = self.top - 1
def display(self):
if (self.top >= 0):
print("Stack elements are: ")
i = self.top
while i >= 0:
print(self.stack[i], end=", ")
i = i - 1
else:
print("The stack is empty")
def gettop(self):
if (self.top <= -1):
print("Empty stack")
else:
print("Top: ", self.stack[self.top])
def isEmpty(self):
if (self.top == -1):
print("Stack is Empty")
else:
print("Stack is not empty")
if __name__ == "__main__":
s = stack()
ch = 0
val = 0
print("1) Push in stack")
print("2) Pop from stack")
print("3) Get Top")
print("4) Check if Empty")
print("5) Display Stack")
print("6) Exit")
while (ch != 6):
ch = int(input("Enter Choice: "))
print(ch)
if (ch == 1):
val = input("Enter the value to be pushed: ")
s.push(val)
elif (ch == 2):
s.pop()
elif (ch == 3):
s.gettop()
elif (ch == 4):
s.isEmpty()
elif (ch == 5):
s.display()
elif (ch == 6):
print("Exit")
else:
print("Invalid Choice")
But I am stuck at the creation of stack at the start. It produces a stack with 12 all over when I try to push any element into the array.
And I do know that there are much simpler implementation of the same in python but I was curious if it is possible or not.
A: I messed around with the code for a while and I found a way to do it, and here it is:
"""
Time: 15:08
Date: 16-02-2022
"""
from turtle import shape
import numpy as np
class stack:
def __init__(self):
self.stack = np.array([0,0,0,0,0,0,0,0,0,0])
self.n = 10
self.top = -1
def push(self, element):
if (self.top >= self.n - 1):
print("Stack overflow")
else:
self.top = self.top + 1
self.stack[self.top] = element
def pop(self):
if (self.top <= -1):
print("Stack Underflow")
else:
print("Popped element: ", self.stack[self.top])
self.top = self.top - 1
def display(self):
if (self.top >= 0):
print("Stack elements are: ")
i = self.top
while i >= 0:
print(self.stack[i], end=", ")
i = i - 1
print("")
else:
print("The stack is empty")
def gettop(self):
if (self.top <= -1):
print("Empty stack")
else:
print("Top: ", self.stack[self.top])
def isEmpty(self):
if (self.top == -1):
print("Stack is Empty")
else:
print("Stack is not empty")
if __name__ == "__main__":
s = stack()
ch = 0
val = 0
print("1) Push in stack")
print("2) Pop from stack")
print("3) Get Top")
print("4) Check if Empty")
print("5) Display Stack")
print("6) Exit")
while (ch != 6):
ch = int(input("Enter Choice: "))
print(ch)
if (ch == 1):
val = input("Enter the value to be pushed: ")
s.push(val)
elif (ch == 2):
s.pop()
elif (ch == 3):
s.gettop()
elif (ch == 4):
s.isEmpty()
elif (ch == 5):
s.display()
elif (ch == 6):
print("Exit")
else:
print("Invalid Choice")
| |
doc_5055
|
<div class="form-group">
@Html.LabelFor(model => model.Season, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Season, new SelectList(Enum.GetValues(typeof(Season)), new { @class = "form-control" })
@*@Html.EditorFor(model => model.Season, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.Season, "", new { @class = "text-danger" })
</div>
</div>
//My season class which define field season
public class Season
{
public Season(string value) { Value = value; }
public string Value { get; set; }
public static Season S1 { get { return new Season("2018-2019"); } }
public static Season S2 { get { return new Season("Debug"); } }
public static Season S3 { get { return new Season("Info"); } }
public static Season S4 { get { return new Season("Warning"); } }
public static Season S5 { get { return new Season("Error"); } }
}
A: Focusing just on the drop down list your current code doesn't work for a couple of reasons. Mainly, the Season class you have defined is a class and not an Enumeration so Enum.GetValues(typeof(Season)) won't exactly work.
I would think about restructuring your view model. You may need to update your other form inputs to fit this view model, but it should work for the drop down list your looking to achieve.
@model ViewModel
<div class="form-group">
@Html.LabelFor(model => model.Season, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedSeason, Model.SeasonList, new { @class = "form-control" })
@*@Html.EditorFor(model => model.Season, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.Season, "", new { @class = "text-danger" })
</div>
</div>
public class ViewModel
{
public string SelectedSeason { get; set; }
public IEnumerable<Season> Seasons { get; set; }
public SelectList SeasonList { get; set; }
public ViewModel()
{
Seasons = new List<Season>()
{
{ new Season("2018-2019") },
{ new Season("Debug") },
{ new Season("Info") },
{ new Season("Warning") },
{ new Season("Error") },
};
SeasonList = new SelectList(Seasons, "Value", "Value");
}
}
| |
doc_5056
|
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
Now I want to run a search query against this document and want to return a filtered result set (e.g. author name).
One way to do this is:-
xquery version "1.0-ml";
import module namespace search="http://marklogic.com/appservices/search"
at "/Marklogic/appservices/search/search.xqy";
declare variable $options:=
<options xmlns="http://marklogic.com/appservices/search">
<transform-results apply="raw"/>
</options>;
for $x in search:search("", $options)/search:result
return $x//author/text()
But search:search API is first caching the whole result in its cache and then we are finding our desired node with xpath. I don't want this. I want search:search API to return only the desired element so that whole result set is not cached in marklogic server. Can anybody tell me please how can I achieve this in Marklogic ?
A: The search:search function doesn't really have a cache of its own, as far as I am aware. You might be happier using search:parse and search:resolve-nodes instead, but the XQuery evaluator will still bring the XML into memory in order to extract the author text.
Getting further away from the search API, you could create a range index on author and use cts:element-values to get its values directly from the index.
A: Puneet, if you're using MarkLogic version 5.0, you can configure something called a "metadata snippet" to get just the elements you want instead of the default snippets.
Here's an example configuration:
<options xmlns="http://marklogic.com/appservices/search">
<transform-results apply="metadata-snippet">
<preferred-elements>
<element name='ordinal' ns='http://marklogic.com/ns'/>
</preferred-elements>
</transform-results>
</options>
And another:
<options xmlns="http://marklogic.com/appservices/search">
<transform-results apply="metadata-snippet">
<preferred-elements>
<element name='author' ns=''/>
<element name='title' ns=''/>
</preferred-elements>
</transform-results>
</options>
A: Use Cts:search instead of search:search if you want very slim result.
xquery version "1.0-ml";
import module namespace search="http://marklogic.com/appservices/search"
at "/Marklogic/appservices/search/search.xqy";
declare variable $options:=
<options xmlns="http://marklogic.com/appservices/search">
<grammar xmlns="http://marklogic.com/appservices/search">
<quotation>"</quotation>
<implicit>
<cts:and-query strength="20" xmlns:cts="http://marklogic.com/cts"/>
</implicit>
<starter strength="30" apply="grouping" delimiter=")">(</starter>
<starter strength="40" apply="prefix" element="cts:not-query">- </starter>
<joiner strength="10" apply="infix" element="cts:or-query"
tokenize="word">OR</joiner>
<joiner strength="20" apply="infix" element="cts:and-query"
tokenize="word">AND</joiner>
<joiner strength="30" apply="infix" element="cts:near-query"
tokenize="word">NEAR</joiner>
<joiner strength="30" apply="near2" element="cts:near-query">NEAR/</joiner>
<joiner strength="50" apply="constraint">:</joiner>
<joiner strength="50" apply="constraint" compare="LT"
tokenize="word">LT</joiner>
<joiner strength="50" apply="constraint" compare="LE"
tokenize="word">LE</joiner>
<joiner strength="50" apply="constraint" compare="GT"
tokenize="word">GT</joiner>
<joiner strength="50" apply="constraint" compare="GE"
tokenize="word">GE</joiner>
<joiner strength="50" apply="constraint" compare="NE"
tokenize="word">NE</joiner>
</grammar>
<transform-results apply="raw"/>
</options>;
let $query := cts:query(cts:parse("in-depth look",$options))
let $searchresult := cts:search(fn:doc()//book,$query)
for $each in $searchresult
return $each/author
This will give you a slim result than the Search:search one should avoid using search:search and go through this route. this give much more flexibility and also slim result set.
| |
doc_5057
|
db.places.find({loc : { $near :[ -122.934326171875,37.795268017578] , $maxDistance : 50 } ,$or:[{"uid":"at"},{"myList.$id" :ObjectId("4fdeaeeede2d298262bb80") } ] ,"searchTag" : { $regex : "Union", $options: "i"} } );
A: By using the QueryBuilder you can create the query you wanted. I have created it as follows.
QueryBuilder query = new QueryBuilder();
query.put("loc").near(-122.934326171875, 37.795268017578, 50);
query.or(
QueryBuilder.start("uid").is("at").get(),
QueryBuilder.start("myList.$id").is(new ObjectId("5024f2f577a59dd9736ddc38")).get()
);
query.put("searchTag").regex(Pattern.compile("Union",Pattern.CASE_INSENSITIVE));
When I print the query into the console it looks like :
{ "loc" : { "$near" : [ -122.934326171875 , 37.795268017578 , 50.0]} ,
"$or" : [ { "uid" : "at"} , { "myList.$id" : { "$oid" : "5024f2f577a59dd9736ddc38"}}] ,
"searchTag" : { "$regex" : "Union" , "$options" : "i"}
}
I didn't try it but hope it will work.
| |
doc_5058
|
Receives the data and sorts it to the other functions:
function sortAndStore(data) {
var images = data.data,
pagLink = data.pagination.next_url;
var newImages = [];
for (i = 0; i < images.length; i++) {
var link = images[i].link,
standardRes = images[i].images.standard_resolution.url,
thumb = images[i].images.thumbnail.url;
var tempImages = new Object();
tempImages.link = link;
tempImages.standard_res = standardRes;
tempImages.thumbnail = thumb;
newImages.push(tempImages);
}
createLayout(newImages);
loadMore(pagLink);
}
Creates the desired layout (sloppy right now but working):
function createLayout(data) {
var images = data;
if ($('#authorizeInsta').css('display') === 'inline') {
$('#authorizeInsta').hide();
// Adds additonal structure
$('<div id="instagramFeed" class="row-fluid" data-count="0"></div>').insertAfter('.direct_upload_description_container');
}
if (!$('#feedPrev').length > 0) {
$('<ul id="feedNav" class="pagination"><li><a id="feedPrev" href="#">Prev</a></li><li><a id="feedNext" href="#">Next</a></li></div>').insertAfter('#instagramFeed');
}
var count = $('#instagramFeed').data('count'),
countParse = parseInt(count);
newCount = countParse + 1;
$('<div id="row' + newCount + '" class="span3">').appendTo('#instagramFeed');
$('#instagramFeed').data('count', newCount);
for (i = 0; i < images.length; i++) {
var link = images[i].link,
standardRes = images[i].standard_res,
thumb = images[i].thumbnail,
newImage = '<img data-image="' + standardRes + '" src="' + thumb + '" class="feedImage" id="feedImage' + i + '"/>';
$(newImage).appendTo('#row' + newCount + '');
}
imageSelect();
}
Pagination function:
function loadMore(link) {
var pagLink = link;
console.log(pagLink);
$('#feedPrev').unbind('click').click(function(event) {
$.ajax({
url: link,
type: 'GET',
dataType: 'jsonp',
})
.done(function(data) {
sortAndStore(data);
})
.fail(function(data, response) {
console.log(data);
console.log(response);
});
return false;
});
}
I understand that the issue is probably here in the sortAndStore function
createLayout(newImages);
loadMore(pagLink);
And here is what the pagination link console logs out to. The issue being that I clicked the button three times and I got four responses. The first two times were fine. I got one pagination link, but the third time I received two response.
If you can see a different issue or suggest a different way to structure my functions it would be greatly appreciated. The data parameter in the sortAndStore function is the data from the original Instagram API call.
Thanks,
A: Figured it out! The issue was that every time the pagination button was clicked the browser was storing a new value for pagLink. Therefore, after clicking the button twice, there were two stored variables which made two pagination API calls.
The fix is to redefine the variable every time a new pagination link goes through the function, not to define an additional pagLink variable.
So this:
function sortAndStore(data) {
var images = data.data;
pagLink = data.pagination.next_url;
Instead of this:
function sortAndStore(data) {
var images = data.data,
pagLink = data.pagination.next_url;
So the solution was to redefine the variable, not to add an additional one, like I was doing by accident.
| |
doc_5059
|
server_date=2020-04-18T17:26:33.150;
current_date=2020-05-07;
var days=server_date - current date;
Json Api "CLMM_LAST_ACTIVITY_DT": "2020-04-18T17:26:33.150",
A: you can use difference method of dataTime.
following code help you more.
String server_date = "2020-04-18T17:26:33.150";
DateTime currentTime = DateTime.now();
int days = currentTime.difference(DateTime.parse(server_date)).inDays;
print(days);
| |
doc_5060
|
"repositories": [
{
"type": "vcs",
"url": "ssh2.sftp://example.org",
"options": {
"ssh2": {
"username": "composer",
"pubkey_file": "/home/composer/.ssh/id_rsa.pub",
"privkey_file": "/home/composer/.ssh/id_rsa"
}
}
}
]
The problem is I'm working with other programmers and I don't want specific user content inside the composer.json. Is there a way to exclude the specific user content from the composer.json?
I actually want composer to ask for the programmers personal public and private key during the excecution inside the commandline.
A: Using Composer on the command line with SSH key authenticated repositories works out of the box if the keys are made available to the CLI SSH process via a key agent.
My personal setup is to run Putty on Windows together with Pageant for the key authentication. I configure the SSH session to allow key forwarding, and when logged into a Linux system, I can run Composer commands as well as Git commands without any need to do additional authentication. A different way would be to run a key agent on Linux directly with the key.
The central part is: If Git commands like push or pull do work with the repository, Composer will also work, without the need to authenticate.
Note that there are some more options of giving authentication data to Composer: https://getcomposer.org/doc/articles/handling-private-packages-with-satis.md#authentication
| |
doc_5061
|
I do:
HttpResponse(img.image, content_type=magic.from_file(img.image.path, mime=True))
It is displaying image fine, however, it is not cached in browser. I tried adding:
location /image {
uwsgi_pass django;
include /home/tomas/Desktop/natali_reality/uwsgi_params;
expires 365d;
}
But it doesn't work. Is there a solution for this?
| |
doc_5062
|
I referred to the developer page of Google but i got confused as this is my first project.
I haven't tried the Google APIs.Thanks!!!!
A: Google+ Sign-in for Android
https://developers.google.com/+/mobile/android/sign-in
There are also two other Java libraries that you might consider for this purpose:
https://github.com/fernandezpablo85/scribe-java
| |
doc_5063
|
Is there a way to create a core dump in cygwin for something like this? I have looked around and seen suggestions of using userdump.exe or winDbg, but I haven't used either and they both seem to be for .exe files and I'm running a python script.
UPDATE:
A file named "python2.7.exe.stackdump" is created with the following contents:
Exception: STATUS_ACCESS_VIOLATION at rip=00180169A0D
rax=0000000000000000 rbx=00000003F336662F rcx=0000000000000000
rdx=0000000000000000 rsi=00000001801C805F rdi=00000003F3366615
r8 =0000000000225418 r9 =8080808080808080 r10=FEFEFEFEFEFEFEFF
r11=00000003F3354522 r12=0000000000225420 r13=00000000FFFFFFFF
r14=0000000000225410 r15=0000000000000000
rbp=000000000000002B rsp=0000000000225318
program=C:\cygwin64\bin\python2.7.exe, pid 8872, thread main
cs=0033 ds=002B es=002B fs=0053 gs=002B ss=002B
| |
doc_5064
|
http://localhost/Symfony/web/app_dev.php/clearance/new?projectId=6
I want now to set projectId in the form to 6.
Here is my controller code
public function newclearanceAction(){
$request = $this->getRequest();
$id = $request->query->get('projectId');
echo $id; //this works, but how to send it to the form?????
$clearance = new Clearance();
$form = $this->createForm(new ClearanceType(), $clearance);
if ($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($clearance);
$em->flush();
return $this->redirect($this->generateUrl('MyReportBundle_project_list'));
}
}
return $this->render('MyReportBundle:Clearance:new.html.twig',array('form'=>$form->createView()));
And here is the code for the form view
<form action="{{ path('MyReportBundle_clearance_new') }}" method="post" >
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" />
</form>
Thanks for any help!
A: This depends on whether your clearance entity has a project related to it. If it does you can do something like:
$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();
$project = $em->getRepository("MyReportBundle:Project")->find($id)
$clearance = new Clearance();
$clearance->setProject($project);
$form = $this->createForm(new ClearanceType(), $clearance);
This will set the project on the clearance object and pass it through to the form.
Currently you cannot do a hidden field for an entity in Symfony2 so my current fix is to create a query builder instance and pass it to the form so that the form select for projects does not get ridiculous when you have 100's of projects. To do this in the action I add:
$request = $this->getRequest();
$id = $request->query->get('projectId');
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository("MyReportBundle:Project");
$project = $repo->find($id)
//create the query builder
$query_builder = $repo->createQueryBuilder('p')
->where('p.id = :id')
->setParameter('id', $project->getId());
$clearance = new Clearance();
$clearance->setProject($project);
//pass it through
$form = $this->createForm(new ClearanceType($query_builder), $clearance);
and in the form class:
protected $query_builder;
public function __construct($query_builder)
{
$this->query_builder = $query_builder;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('Your field')
// all other fields
// Then below the query builder to limit to one project
->add('project', 'entity', array(
'class' => 'MyReportBundle:Project',
'query_builder' => $this->query_builder
))
;
}
| |
doc_5065
|
Is there a function in matplotlib that allows to save larger area than the standard area of the figure, so I can save my figure with the legend, like below?
A: bbox_inches='tight' should do the trick:
from matplotlib import pyplot as plt
plt.savefig('figure.png', bbox_inches='tight')
bbox_inches:
Bbox in inches. Only the given portion of the figure is
saved. If 'tight', try to figure out the tight bbox of
the figure.
Example
plt.plot(range(10))
plt.legend(['abc'], loc='upper right', bbox_to_anchor=(1.2, 0.9))
results in this png:
| |
doc_5066
|
The DB starts with a login form that sets a TempVars!CurrentSecurity.Value based on the user logged in (as Admin or common User).
All the other forms have a Form_KeyDown event that will call a module where there is a function/sub that has to change the behavior of F11 (hide/show the navigation pane) depending from the current TempVars!CurrentSecurity.Value (Admin/User).
For instance: if the current logged account is an Admin, the F11 key is enabled, else not..
So i tried in this way:
in the Form_KeyDown event:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
CheckF11 (KeyCode)
end sub
in the module:
Public Function CheckF11(KeyCode As Integer)
If TempVars!CurrentSecurity.Value <> "Admin" Then
If KeyCode = 122 Then KeyCode = 0
End If
End Function
The form's KeyPreview property is already set to True but this doesn't work anyway.. help
A: Function must send result back to calling procedure.
Public function doesn't really reduce code.
This works:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
KeyCode = CheckF11(KeyCode)
End Sub
Public Function CheckF11(intKey As Integer)
If TempVars!CurrentSecurity.Value <> "Admin" Then
If intKey = 122 Then CheckF11 = 0
End If
End Function
| |
doc_5067
|
A: Assuming you are talking about shadowing with names, the Java Language specification says this
Some declarations may be shadowed in part of their scope by another
declaration of the same name, in which case a simple name cannot be
used to refer to the declared entity.
and gives this example
class Test {
static int x = 1;
public static void main(String[] args) {
int x = 0;
System.out.print("x=" + x);
System.out.println(", Test.x=" + Test.x);
}
}
where x is a static class variable and a local variable. The local variable will be used if x is referenced in the method the local variable x is defined in. If you wanted to reference the class variable, you would need to use
Test.x
Analysis tools can find things like this.
| |
doc_5068
|
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[[NSNotificationCenter defaultCenter] postNotificationName:localReceived object:self userInfo:notification.userInfo];
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
else if ([UIApplication instancesRespondToSelector:@selector(registerForRemoteNotificationTypes:)])
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
...
// Local notificaiton example. Icon badge
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSLog(@"locationNotification:%@",locationNotification.alertBody);
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
// call local notification method
[self application:[UIApplication sharedApplication] didReceiveLocalNotification:locationNotification];
}
return YES;
}
When my app is not running, the didFinishLaunchingWithOptions: method is called. In it I call the didReceiveLocalNotification method again where I call postNotificationName. I put the observer in my ViewControllers ViewDidLoad method:
- (void)viewDidLoad
{
...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recieveLocalNotification:) name:localReceived object:nil];
...
}
The problem is that the method recieveLocalNotification: is never called when app is not running. It's called every time when app is in background or running. Can anybody tell me what I'm doing wrong here?
Thanks in advance!
A: -viewDidLoad is called after the view of view controller is instantiated, the view is instantiated after the viewController.view is accessed for the first time.
So you can try call your viewController.view before posting the notification.
| |
doc_5069
|
func checkButton() -> Bool { return !self.appReference.buttons["ButtonA"].isHittable }
How do I continuously ping this function every x seconds until the result is true or a defined timeout expires. I'm new to Swift, but I could achieve the same objective in Java using Awaitility.
Something like
var counter = 0
while (counter < 20) {
if (checkButton()) {break}
sleep(2)
counter++
}
if (counter == 20) throw Error
Does something more official/clean exist or is this how it's done in Swift?
| |
doc_5070
|
<div>
<div>
% if( !$something ) {
<strong><% $title %></strong>
% }
</div>
</div>
Any idea how I can tell Vim to ignore the % at the beginning of the line and indent like it wasn't there?
I'm using https://github.com/aming/vim-mason to support the mixed Perl/HTLM syntax, but I don't think it changes anything.
A: This is Perl code embedded inside HTML, so the indenting comes from $VIMRUNTIME/indent/html.vim. This defines an 'indentexpr', implemented by HtmlIndent().
You need to modify that implementation to ignore % in the first column; whenever it accesses the buffer (getline(), prevnonblank(), shiftwidth()), you need to intercept, find the previous line that does have such % sigil, and return the value for that instead. (If those special lines can also contain HTML tags, you may have to extract those from the Perl code and return only those.) That gets you the indenting you desire.
Unfortunately, it's not trivial, and you have to fork the original implementation. However, if you manage to implement a clean solution, you could suggest adding integration points to the author of indent/html.vim. If there are other languages apart from Mason that use these prefixes on top of HTML, that would be an additional argument for adding such support (and maybe even your wrapper functions).
| |
doc_5071
|
Fullcalendarextern.js (the part for the draggable events):
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#external-events div.external-event').each(function() {
var eventObject = {
title: $.trim($(this).text())
};
$(this).data('eventObject', eventObject);
$(this).draggable({
zIndex: 999,
revert: true,
revertDuration: 0
});
});
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: "../testcalendar/fullcalendar/events.php",
droppable: true,
drop: function(date, allDay) {
var originalEventObject = $(this).data('eventObject');
var copiedEventObject = $.extend({}, originalEventObject);
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
if ($('#drop-remove').is(':checked')) {
$(this).remove();
}
alert(date + ' was moved ' + allDay + ' days\n' +
'(should probably update your database)');
},
});
the html file (draggable part):
<div id='calendar'></div>
<table class="displaylegenda" >
<thead>
<tr>
Kleur
Status
colortag;?>">
soort;?>
Draggable Events
colortag;?>">soort;?>
remove after drop
events.php:
query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
the process.php (currently only using it for the new event dialog):
<?php
//include db configuration file
include 'connection.php';
function user_joined($user_werknemer,$user_project,$user_klant,$user_taak,$user_name,$user_desc, $user_start, $user_end, $user_color){
$q = "INSERT INTO evenement (id,idWerknemer,idProject,idKlant,idTaak,title,description,start,end,color) VALUES
('','".$user_werknemer."','".$user_project."','".$user_klant."','".$user_taak."','".$user_name."','".$user_desc."','".$user_start."','".$user_end."','".$user_color."')";
$qo = "INSERT INTO evenementontvanger (idWerknemer,idProject,idEvent,idKlant,idTaak) VALUES ('".$user_werknemer."','".$user_project."','','".$user_klant."','".$user_taak."')";
mysql_query($q);
mysql_query($qo);}
if(isset($_POST['user_werknemer'],$_POST['user_project'],$_POST['user_klant'],$_POST['user_taak'],$_POST['user_name'],$_POST['user_desc'],$_POST['user_start'],$_POST['user_starttime'],$_POST['user_endtime'],$_POST['user_end'],$_POST['user_color'],$_POST['action'])){
$user_werknemer=$_POST['user_werknemer'];
$user_color=$_POST['user_color'];
$user_name=$_POST['user_name'];
$user_desc=$_POST['user_desc'];
$user_project=$_POST['user_project'];
$user_klant=$_POST['user_klant'];
$user_taak=$_POST['user_taak'];
$user_start=$_POST['user_start']." ".$_POST['user_starttime'];
$user_end=$_POST['user_end']." ".$_POST['user_endtime'];
$action=$_POST['action'];
if ($action=='joined'){
user_joined( $user_werknemer, $user_project, $user_klant, $user_taak, $user_name, $user_desc, $user_start, $user_end, $user_color);
}
}
/*if ( (isset($_POST["id"]) && strlen($_POST["id"]) >= 3 && strlen($_POST["id"]) <= 60) &&
(isset($_POST["name"]) && strlen($_POST["name"]) >= 3 && strlen($_POST["name"]) <= 50) &&
(isset($_POST["age"]) && strlen($_POST["age"]) >= 3 && strlen($_POST["age"]) <= 40) )
{ //check $_POST["name"] and $_POST["address"] and $_POST["city"] are not empty
$id = $_POST["id"];
$name = $_POST["name"];
$age = $_POST["age"];
$q = "INSERT INTO tbltest ( id, name, age) VALUES
('".$id."','".$name."','".$age."')";
mysql_query($q);
}*/
?>
A: I am not familiar with fullcalendar but I think you can make an ajax request in your drop function.
For exemple:
$.post(url: "update.php",{data you need to update});
I think these questions could also help you:
How to send an ajax request to update event in FullCalender UI, when eventDrop is called?
Fullcalendar Event drop and ajax
| |
doc_5072
|
One form that users input details of customer complaints - fields on this form include input of customer reference and defaults to first Customer in Customer list, selection of complaint type list box which also defaults to first in list and selection of financial year list box which defaults to current year. Users want a button to show a list of previous customer complaints of this type in a financial year. I can add the button later if I can just get the query and sub-form working
I have created the Access query which uses the relevant form fields (example of one part of query with form criteria in image below) and added the query as a sub-form
The problems I have are -
*
*When, I run the query itself and input the parameters that are prompted it returns the correct number of expected rows but all fields state "deleted"
*When I double click on the form, instead of showing the parent form, it shows the sub-form in data sheet format with all rows from database and all have the value "deleted"
*If I then right click on the presented data sheet sub-forms header and select "Form View", it shows the parent form, but all fields have the value "deleted" and I cannot change them and the subform has no records
*If I close the form and open again in "Form Design" then right click Form Design and select "Form View", the form view is presented with the first Customer details in database and the sub-form shows the correct number of records for this customer but all fields state "deleted"
can someone tell me how I resolve this please?
| |
doc_5073
|
How can I get a list of all of the urls in a website using Javascript?
A: Using collections
Links: document.links (href)
Images:
document.images (src)
Using DOM
document.getElementsByTagName('img')
Bookmarklet:
Live Demo
(function(){
var imgs = document.getElementsByTagName('img'),t=[];
for (var i=0, n=imgs.length;i<n;i++)
t.push('<a href="'+imgs[i].src+'"><img src="'+
imgs[i].src+'" width="100"></a>');
if (t.length) {
var w=window.open('','_blank');
if (w) {w.document.write(t.join(' '));w.document.close();}
else alert('cannot pop a window');
}
})();
Now you can save the new page to your harddisk and there will be a dir full of images
A: var list=[];
var a=document.getElementsByTagName('img');
for (var i=0,l=a.length;i<l;i++)
{
if (/\.(jpg|gif|png|jpeg)$/im.test(a[i].getAttribute('src')))
{
list.push(a[i].getAttribute('src'));
}
}
This code would generate list of picture URL's which are used in <img>
| |
doc_5074
|
This is my service
public class LocationService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "LocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private GoogleApiClient locationClient;
private String username;
@Override
public void onCreate() {
super.onCreate();
//defaultUploadWebsite = getString(R.string.default_upload_website);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location location) {
// formatted for mysql datetime format
Log.i(TAG, String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()));
}
@Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
// we have our desired accuracy of 500 meters so lets quit this service,
// onDestroy will be called and stop our location uodates
sendLocationDataToWebsite(location);
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(locationClient, this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(Constants.UPDATE_INTERVAL);
locationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
LocationServices.FusedLocationApi.requestLocationUpdates(locationClient,
locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
stopLocationUpdates();
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
public String getCurrentTime()
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String currentTime = sdf.format(new Date());
return currentTime;
}
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
And this is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.fikri.com.navigationsystem" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".SplashScreen"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_splash_screen"
android:theme="@style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" >
</activity>
<service android:name=".Service.LocationService">
</service>
</application>
A: You should probably read runtime permission and Building better apps with Runtime Permissions about how to use runtime permission when targeting Android Marshmallow.
| |
doc_5075
|
The problem is, I can't see what error gcc gave. It looks like stderr is either ignored or stuffed into a logfile somewhere.
I thought I might be able to discover the gcc/stderr output if I copy that command to a terminal window and run it, but it won't compile because some of the files on the command line were temp files that MonoTouch setup, and they were removed after MonoDevelop tried to build.
I've tried:
*
*Setting Log Verbosity to Diagnostic
under
MonoDevelop->Preferences->Build
*Running mdtool on the command line
with -v and that doesn't show me any
gcc output either
*Adding
--stderr=/Users/myname/somefile.txt to the mtouch command line under
Project Options->iPhone Build->Extra
Arguments
.. none of those things work.
So.. how can I get the stderr output from gcc when mtouch runs it?
A: Add "-v -v -v" to the "Extra Arguments" for your build configuration in the iPhone Build settings.
A: In the build results window, mouse over the right end of or click on the step causing the error. A small icon will show up at the end of the line. It looks like an oval with horizontal lines going through it. If you click on that, you will see the commands that were run in that build step, as well as the output of those commands.
| |
doc_5076
|
alter database SSDPrototypeV3 set offline with rollback immediate
restore database SSDPrototypeV3
from disk = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\dustinepogi.bak'
alter database SSDPrototypeV3 set online
when i run this on my application, it successfully restores my db . but when i try to run a sql query (like a select statement), it says that i have an invalid object name, specifically on the table that i performed my select statement . but then, if i reload my application after closing, it is fully restored . how can i get rid of this problem ?
A: Assuming you are using SqlClient (and you are using connection pooling):
*
*switch to master first
*do your restore
*clean your connection pool: using SqlConnection.ClearAllPools (clears all pools for the provider) or ClearPool (clears just the pool associated with the specific connection string)
*run your commands against your original database
And, hopefully, off you go
A: A database connection has a current database that all queries are executed against. The initial database parameter of the connection string determines the current database used when the connection is opened.
I assume that the current database changes back to master when you take your SSDPrototypeV3 database offline. You have two options to fix this:
*
*Change the current database back by executing use SSDPrototypeV3 or
*close and reopen the connection.
| |
doc_5077
|
I want to extend this to match digits in parentheses followed by a space followed by a string which comes from a variable. I know that I can crate a RegExp object to do this but am having trouble understanding which characters to escape to get this to work. Is anybody able to explain this to me?
A: When you do not use RegEx, you can use a literal notation:
/^\(\d+\)/
But when you are using the RegEx constructor, you need to double escape these symbols:
var re = new RegExp("^\\(\\d+\\)");
MDN Reference:
There are 2 ways to create a RegExp object: a literal notation and a
constructor. To indicate strings, the parameters to the literal
notation do not use quotation marks while the parameters to the
constructor function do use quotation marks.
...
Use literal notation when the regular expression will remain constant.
...
Use the constructor function when you know the regular expression pattern will > be changing, or you don't know the pattern and are getting it from
another source, such as user input.
Now, in case you have a variable, it is a good idea to stick to the constructor method.
var re = new RegExp('^\\(\\d+\\) ' + variable);
Escaping the slash is obligatory as it is itself is an escaping symbol.
| |
doc_5078
|
A: <% include file="target.jsp" %> will inline the source of target.jsp into your page, and then the whole thing will then be evaluated as a single JSP. This is done at JSP compile time. This can be highly optimized by the container, and can have side-effects. For example, if you change the content of target.jsp, the container generally will not recompile the JSPs that included it.
<jsp:include page="target.jsp"/> will execute target.jsp as a seperate JSP, and then include the output of that execution into your page. This is done at JSP execution time. Note that this can refer to any path inside the container, not just a JSP (e.g. you can include the output of a servlet).
| |
doc_5079
|
This is really appreciated. Thanks!
A: The only* way to do client-less Lync in the browser is with UCWA. Right now,UCWA is only IM/P but voice/video is coming by the end of the year. Everything else (apart from Lync Web Access obv) requires the client to be on the machine.
*you could write a web proxy to a UCMA service you've written which would achieve the same thing,but this wouldn't be able to do voice/video either.
| |
doc_5080
|
http://www.goproblems.com/test/wilson/wilson-new.php?v1=0&v2=0&v3=0&v4=0&v5=2
PHP Source: http://www.goproblems.com/test/wilson/wilson-new.php.txt
However, I cannot seem to get the same numbers as in the php example.
Where the second 2 is the total ratings
Where the first 2 is the sum rating for a rating of 5 which I get by:
double sum = ((5 - 1) / 4.0) * Total_5_star_Ratings
2 Ratings which are both 5 stars:
Console.WriteLine(5 * ci_lower_bound(2, 2));
public static double ci_lower_bound(double sum, int n)
{
if (n == 0)
return 0.0;
double z = 1.96;
const int k = 4;
double ave = sum/n;
return ((ave + ((z * z) / (2 * n))) - z * Math.Sqrt((k * ave * (1 - ave) + (z * z) / (4 * n)) / n)) / (1 + (k * (z * z)) / n);
}
A: I found the error you may have since you don't post the result you have.
instead of
double sum = ((5 - 1) / 4.0) * Total_5_star_Ratings
you should get in your case
double ave = (5 * n)/n
and then
double xbar = (ave - 1)/4
and in your formula
double result = (( ave + ((z * z) / (2 * n))) - z * Math.Sqrt((((ave * (1 - ave) + (z * z) / (4 * n)) / n)) / (1 + (z * z / n)));
return result 1 + 4 * result;
I did not test it but this should get you on track. check the parenthesis
| |
doc_5081
|
const punctuationCaps = /(^|[.!?]\s+)([a-z])/g;
A: You can match the D.C. part and use an alternation using the 2 capturing groups that you already have.
In the replacement check for one of the groups. If it is present, concatenate them making group 2 toUpperCase(), else return the match keeping D.C. in the string.
const regex = /D\.C\.|(^|[.!?]\s+)([a-z])/g;
let s = "this it D.C. test. and? another test! it is.";
s = s.replace(regex, (m, g1, g2) => g2 ? g1 + g2.toUpperCase() : m);
console.log(s);
A: Use a negative lookahead:
var str = 'is D.C. a capital? i don\'t know about X.Y. stuff.';
var result = str.replace(/(^|[.!?](?<![A-Z]\.[A-Z]\.)\s+)([a-z])/g, (m, c1, c2) => { return c1 + c2.toUpperCase(); });
console.log('in: '+str);
console.log('out: '+result);
Console output:
in: is D.C. a capital? i don't know about X.Y. stuff.
out: Is D.C. a capital? I don't know about X.Y. stuff.
Explanation:
*
*(^|[.!?]) - expect start of string, or a punctuation char
*(?<![A-Z]\.[A-Z]\.) - negative lookahead: but not a sequence of upper char and dot, repeated twice
*\s+ - expect one or more whitespace chars
*all of the above is captured because of the parenthesis
*([a-z]) - expect a lower case char, in parenthesis for second capture group
| |
doc_5082
|
pt is defined in the script with a default, I assume that's the best/only way to define a number.
screen plane_seat():
imagemap:
ground "plane.png"
hotspot(165, 800, 155, 221)
if pt == 1:
jump pbathroom_event
else pass
But the error I get is:
u'jump' is not a keyword argument or valid child for the imagemap statement.
A: This worked perfectly if anyone's curious.
hotspot(165, 800, 155, 221) clicked If(pt == 1, Return("pbathroom_event"))
| |
doc_5083
|
Currently when I refresh it checks all of my checkboxes, not just the one I checked.
Here is how my inputs are set up:
<input type="checkbox" name="filters" ng-click="includeBrand('Brand A')" />Brand A
and here is my function that should keep the same ones checked:
$(function () {
var data = localStorage.getItem("filter-by");
if (data !== null) {
$("input[name='filters']").attr("checked", "checked");
}
});
$("input[name='filters']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("filter-by", $(this).val());
} else {
localStorage.removeItem("filters");
}
});
What could be going wrong as to make it check "all of the above"?
Thanks for the help!
A: Updated response
There's a couple of things going on in your codepen. Here's my recommendations:
First, add a data- attribute, like so:
<input type="checkbox" name="filters" data-filter-by="Brand A" ng-click="includeBrand('Brand A')" />Brand A
Update your click-handler to be more like this:
$("input[name='filters']").click(function () {
var items = localStorage.getItem("filter-by");
items = items ? JSON.parse(items) : [];
var data = $(this).data('filter-by');
var index = items.indexOf(data);
if ($(this).is(":checked")) {
items.push(data);
} else if (index >= 0) {
items.splice(index, 1);
}
localStorage.setItem("filter-by", JSON.stringify(items));
});
And lastly, update the code where you pre-select checkboxes to be something more like this:
$(function () {
var items = localStorage.getItem("filter-by");
items = items ? JSON.parse(items) : [];
$("input[name='filters']").each(function(index, input) {
var data = $(input).data('filter-by');
if (items.indexOf(data) >= 0) {
$(input).attr('checked', 'checked');
}
});
});
Does this make sense?
Original response
This line...
$("input[name='filters']").attr("checked", "checked");
Checks all inputs named "filters" - not just individual ones. I suspect what you mean to do is iterate over your filter checkboxes and only select those where the val() value matches the item stored in localstorage. So something like this...
$("input[name='filters']").each(function(index, input) {
if ($(input).val() === data) {
$(input).attr('checked', 'checked');
}
});
I should also point out that you're writing to filter-by in one place and removing filters in 2 lines below. Those should be the same key.
| |
doc_5084
|
RuntimeError: size mismatch, m1: [5 x 10], m2: [5 x 32] at /pytorch/aten/src/TH/generic/THTensorMath.cpp
I looked at similar questions but they are image related and suggest flattening the input, I tried them with no luck.
I'm using Python 3.6.8 and torch 1.1.0
code sample:
state = [[307, 1588204935.0, 1.0869, 1.08708, 1.08659, 1.08662, 1.08708, 1.08724, 1.08674, 1.08677],
[370, 1588204920.0, 1.08668, 1.08709, 1.08661, 1.08693, 1.08682, 1.08724, 1.08677, 1.08708],
[243, 1588204905.0, 1.08637, 1.08671, 1.08624, 1.08669, 1.08651, 1.08686, 1.08639, 1.08683],
[232, 1588204890.0, 1.08614, 1.08656, 1.08609, 1.08636, 1.08628, 1.0867, 1.08626, 1.0865],
[349, 1588204875.0, 1.086, 1.08623, 1.08585, 1.08614, 1.08614, 1.08638, 1.08597, 1.0863]]
def predict(state, state_dim=5, action_dim=3, hidden_dim=32, lr=0.05):
""" Compute Q values for all actions using the DQL. """
criterion = torch.nn.MSELoss()
model = torch.nn.Sequential(torch.nn.Linear(state_dim, hidden_dim),
torch.nn.LeakyReLU(),
torch.nn.Linear(hidden_dim, hidden_dim*2),
torch.nn.LeakyReLU(),
torch.nn.Linear(hidden_dim*2, action_dim))
optimizer = torch.optim.Adam(model.parameters(), lr)
with torch.no_grad():
return model(torch.Tensor(state)) # Error throw here
predict(state).tolist()
A: Changing my state_dim from 5 to 10 solved my issue.
Reference:
https://discuss.pytorch.org/t/runtimeerror-size-mismatch-m1-5-x-10-m2-5-x-32-at-pytorch-aten-src-th-generic-thtensormath-cpp/79714/2?u=masilive_sifanele
| |
doc_5085
|
My question is: How can we inherit this dashboard to customize it?
For example, I want to add a button which helps clone the dashboard to another user.
It seems that this dashboard is not a usual FormView.
A: You can't inherit dashboards in Odoo 8.because dashboards is work like views container not usual view if you want to customize one .. just copy it's code and paste it in your module over again and customize what you need.
A: Try to make formview for yourself :-)
This is a good example:
<?xml version="1.0" encoding="UTF-8"?>
<openerp>
<data>
<record model="ir.actions.act_window" id="act_centiro_stocks_tree_pendientes">
<field name="name">Centiro stock</field>
<field name="res_model">stock.picking</field>
<field name="view_type">tree</field> <!-- form -->
<field name="view_mode">tree</field>
<field name="domain">[('state', 'not in', ('assigned','done'))]</field>
</record>
<record model="ir.actions.act_window" id="act_centiro_stocks_tree_procesados">
<field name="name">Centiro stock</field>
<field name="res_model">stock.picking</field>
<field name="view_type">tree</field> <!-- form -->
<field name="view_mode">tree</field>
<field name="domain">[('state', 'in', ('assigned','done'))]</field>
</record>
<record model="ir.actions.act_window" id="act_centiro_stocks_graph">
<field name="name">Operaciones Centiro</field>
<field name="res_model">gc.operaciones.centiro</field>
<field name="view_type">form</field>
<field name="auto_refresh" eval="1" />
<field name="view_mode">kanban,form</field>
</record>
<record model="ir.ui.view" id="board_view_stock_centiro_form">
<field name="name">Stock Centiro</field>
<field name="model">board.board</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form string="Centiro Stock Dashboard">
<hpaned>
<child1>
<action string="Estado almacén Centiro" name="%(act_centiro_stocks_graph)d" colspan="2" />
</child1>
<child2>
<action string="Pedidos pendientes" name="%(act_centiro_stocks_tree_pendientes)d" colspan="2" />
<action string="Pedidos sin ubicar" name="%(act_centiro_stocks_tree_procesados)d" colspan="2" />
</child2>
</hpaned>
</form>
</field>
</record>
<record model="ir.actions.act_window" id="open_stock_centiro_board">
<field name="name">Stock Centiro Dashboard</field>
<field name="res_model">board.board</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="usage">menu</field>
<field name="view_id" ref="board_view_stock_centiro_form" />
</record>
<menuitem id="dashboard_menu" name="Dasboard custom module"
parent="cabecera_dashboard_custom_module" action="open_stock_centiro_board" />
</data>
Good luck
| |
doc_5086
|
self.tableView = ({
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
tableView.translatesAutoresizingMaskIntoConstraints = NO;
tableView.scrollEnabled = NO;
tableView.allowsSelection = NO;
tableView.dataSource = self;
tableView.delegate = self;
tableView.backgroundColor = [UIColor clearColor];
tableView;
});
self.waterMarkImageView = ({
UIImageView *imageView = [UIImageView new];
imageView.translatesAutoresizingMaskIntoConstraints = NO;
imageView.contentMode = UIViewContentModeScaleToFill;
imageView.alpha = 1.0;
imageView.image = [UIImage imageNamed:@"waterMark"];
imageView;
});
[self.view addSubview:self.waterMarkImageView];
[self.view addSubview:self.tableView];
[self.waterMarkImageView mas_makeConstraints:^(MASConstraintMaker *make){
make.right.equalTo(self.view.mas_right);
make.bottom.equalTo(self.view.mas_bottom);
make.width.equalTo(self.view.mas_width);
make.height.equalTo(self.view.mas_height);
}];
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.view.mas_top).offset(statusBarHeight + navigationBarHeight + labelHeight);
make.left.equalTo(self.view.mas_left);
make.bottom.equalTo(self.view.mas_bottom);
make.right.equalTo(self.view.mas_right);
}];
However there is no waterMarkImageView shows.
But if I exchange the order that I add waterMarkImageView and tableView to the subviews of self.view, that is:
[self.view addSubview:self.tableView];
[self.view addSubview:self.waterMarkImageView];
Then the waterMarkImageView will show, but above the tableview, that will cover a part of the tableview and that isn't what I expect. Anyone knows how to deal with this problem?
Well sorry actually from the view hierarchy I can see a part of the watermark, not the whole. And when I run the app I can see nothing.
A: You cannot see the imageView because it is behind the tableView. This makes sense as you added the tableView after the imageView. To fix this, simply set the background color of the cells to clearColor(). This will make them transparent so that you can see the imageView that is behind them.
| |
doc_5087
|
For example:
class User extends Model {
public function details()
{
switch($this->account_type) {
case 'staff': return $this->hasOne(Staff::class);
case 'student': return $this->hasOne(Student::class);
case 'parent': return $this->hasOne(ParentUser::class);
}
return null;
}
If I run:
echo $user->details->staff_code;
Then it outputs CRS for example. However, if I run it with object_get():
object_get($user, 'details.staff_code');
Then it outputs null.
I figured because in the object_get() method, it has this line:
if (! is_object($object) || ! isset($object->{$segment}))
I assume because the details property is a magic/dynamic laravel model property, isset() doesn't work on it.
Whats the best way to handle this? Is it safe to edit the object_get() method and replace the isset() segment with something more robust? I don't really want to edit source code in the Vendor directory.
Should I create my own object_get helper function, and if so, where should I place it / autoload it?
Is there another method of achieving the result I want that I'm unaware of?
Any help is appreciated.
A: Well, it seems a bit hacky, but it seems to work, and I only need to do it on the one User model.
I've taken the magic __isset() method from the Illuminate\Database\Eloquent\Model class, and overrode it in the User class.
I've also added a method_exists check in the __isset() method to check to see if the relationship method exists. Because if the relationship method exists, at least we know that the dynamic variable with the same method name exists.
This is the __isset() method in my model if anyone else needs it:
public function __isset($key)
{
return (
isset($this->attributes[$key]) ||
isset($this->relations[$key]) ||
method_exists(static::class, $key)
) ||
($this->hasGetMutator($key) && ! is_null($this->getAttributeValue($key)));
}
Now, if I run:
object_get($user, 'details.staff_code')
It returns the correct value, instead of the default null.
| |
doc_5088
|
Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
Console.WriteLine(Environment.UserName);
Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().User); //GUID
Console.WriteLine(Environment.GetEnvironmentVariable("USERNAME"));
...tries give me back the current user who runs the process, in my case Administrator - but i'd like to have the current user who is logged in.
Any ideas or suggestions?
A: I found this method a long time ago. I am using the WMI query
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
A: The correct way, I believe, would be to execute WTSQuerySessionInformation, something along the lines of:
WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,WTS_CURRENT_SESSION,
WTSUserName,buffer, out byteCount);
PInvoke page for this function.
Tangentially related, but may be of interest - How can I launch an unelevated process from my elevated process and vice versa?
| |
doc_5089
|
The way I call the maintenance function is with a let. This seems like a weird way, to do this it requires creating an unused variable. Should I instead return a sequence with the call to admin:check-collections-exists being the first item in the sequence then the subsequent processing being the second element? Just looking for the standard elegant way to do this. My functions are:
declare function admin:add-collection-to-publication($pub-name, $collection-name)
{
(:does this publication have a COLLECTIONS element?:)
let $unnecessary-variable := admin:check-collections-exists($pub-name)
(:now go and do what this function does:)
return "do some other stuff then return"
};
declare function admin:check-collections-exists($pub-name)
{
if(fn:exists($pubs-node/pub:PUBLICATION[pub:NAME/text()=$pub-name]/pub:COLLECTIONS))
then
"exists"
else
xdmp:node-insert-child($pubs-node/pub:PUBLICATION[pub:NAME/text()=$pub-name],<pub:COLLECTIONS/>)
};
A: Using a sequence is not reliable. MarkLogic will most likely attempt to evaluate the sequence items in parallel, which could cause the creating to happen at 'same' time or even after the other work. The best approach is indeed to use a let. The let's are always evaluated before the return. Note though that let's can be evaluated in parallel as well, but the optimizer is smart enough to detect dependencies.
Personally, I often use unused variables. For example to insert logging statements, in which case I have one unused variable name that I reuse each time:
let $log := xdmp:log($before)
let $result := do:something($before)
let $log := xdmp:log($result)
You could also use a very short variable name like $_. Or you could reconsider actually giving the variable a sensible name, and use it after all, even though you know it never reaches the else
let $exists :=
if (collection-exists()) then
create()
else true()
return
if ($exists) then
"do stuff"
else () (: never reached!! :)
HTH!
| |
doc_5090
|
$ ./console tests/react-test.red
*** Runtime Error 32: segmentation fault
*** at: F6B4E33Eh
ldd console does not report missing libraries. The same binary works OK in 32-bit Debian.
What can be the problem?
When I add system/view/debug?: yes line to tests/react-test.red, there is some debugging info about View events before segfault error:
$ ./console tests/react-test.red
-- on-change event --
face : window
word : type
old : word
new : word
-- on-change event --
face : window
word : size
old : none
new : pair
-- on-change event --
face : window
word : pane
old : none
new : block
-- on-change event --
face : text
word : type
old : word
new : word
-- on-change event --
face : text
word : size
old : none
new : pair
-- on-deep-change event --
owner : text
action : set-path
word : size
target type: pair!
new value : none!
index : -1
part : -1
auto-sync? : true
forced? : false
-- para on-change event --
word : align
old : none
new : word
-- on-change event --
face : text
word : size
old : pair
new : pair
-- on-change event --
face : text
word : para
old : none
new : object
-- para on-change event --
word : parent
old : none
new : block
-- on-change event --
face : text
word : size
old : pair
new : pair
-- para on-change event --
word : parent
old : block
new : none
-- on-change event --
face : text
word : type
old : word
new : word
-- on-change event --
face : text
word : size
old : none
new : pair
-- on-deep-change event --
owner : text
action : set-path
word : size
target type: pair!
new value : none!
index : -1
part : -1
auto-sync? : true
forced? : false
-- para on-change event --
word : align
old : none
new : word
-- font on-change event --
word : style
old : none
new : word
-- font on-change event --
word : name
old : none
new : none
-- font on-change event --
word : size
old : none
new : none
-- on-change event --
face : text
word : size
old : pair
new : pair
-- on-change event --
face : text
word : text
old : none
new : string
-- on-change event --
face : text
word : para
old : none
new : object
-- para on-change event --
word : parent
old : none
new : block
-- on-change event --
face : text
word : font
old : none
new : object
-- font on-change event --
word : parent
old : none
new : block
*** Runtime Error 32: segmentation fault
*** at: F6B5E33Eh
| |
doc_5091
|
So I made a completely new program with only the necessary code and it does the same thing.
Can someone explain me why it does it and if we can resolve this problem?
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('The Test Program')
running = True
update_counter = 1
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
print(str(update_counter) + " updates")
update_counter += 1
pygame.quit()
quit()
# So try to move the window across your screen and you will see that, prints will stop and they will resume when you will release the click
A: So someone tell me that was normal, so I think it's only on Windows but there are no solutions. I put a script that show a pause symbol on screen when the cursor leave the window to make it normal.
| |
doc_5092
|
A: Assuming you have a predicate do/1 which either fails or succeeds, this would be the code:
do(f) :- fail.
do(t) :- true.
writeyesno(X):-
( do(X)
-> write("yes")
; write("no")
).
The block (a -> b ; c) is an if-then-else-block: if a, then b else c.
Queries (tested with SWISH):
?- writeyesno(f).
no
true.
?- writeyesno(t).
yes
true.
?- writeyesno(x).
no
true.
| |
doc_5093
|
mvn package
After this i need to change config.properties in .jar file via command line
How can i do that?
A: https://docs.oracle.com/javase/tutorial/deployment/jar/update.html
Command line:
jar uf yourfile.jar dir{optional}/config.properties
| |
doc_5094
|
The problem is while displaying a text output from ckeditor are shown as html tags in my website because of the effect of htmlentities() i used.This is the output i am getting in my website,
<p><strong><span style="color:#008080">Superhero</span></strong></p>
So the look of website is damaged.I want to show the ckeditor text as it is.But htmlentities()
must have to be used.
I searched stack overflow and found many issues related to this.So i used the following solution in my ckeditor/config.js page as below,
config.entities = false;
config.basicEntities = false;
config.entities_greek = false;
config.entities_latin = false;
But its not working in my code.
Thanks in advance!
A: Well, as far as I am aware there is no in-built way in php to distinguish between malicious injected script tags and normal html tags.
This leads to problem where you want to block malicious script, but not valid html tags.
When I have to accept user input and display again which may contain html tags, instead of using htmlentities I use htmlpurifier. There is another one I am aware of is safeHtml.
However, there might be better solutions then this and I am also interested in knowing as well. Unfortunately haven't came across one.
| |
doc_5095
|
(1) Throughout our projects, we use over 100 "common" JARs (log4j, junit, commons-cli, etc.). Do we have to write the ivy.xml ("module descriptor") files for all of them, or are there generic ones I can find in the ibiblio (or other) repo? To force your users to write their own ivy files for each dependency sounds pretty cruel and unusual to me.
(2) Are ivy files even required for a particular JAR, or does Ivy have defaults for when it looks in a repo for a dependency that doesn't have a corresponding ivy file?
(3) Is it possible to have all my dependencies in one folder (repo) and define 1 ivy.xml file that configures all of them inside it?
Thanks for any help here!
A: (1) Ivy files do not have to list every single jar. Some jars are dependencies of others and automatically pulled by ivy from the repository. No defaults are available. For a new project I normally generate my first ivy file (see the attached ant2ivy script)
(2) An ivy file is only required in an ivy repository when the jar has dependencies. Having said that it's good practice to have one. Personally I cheat and use a Maven repository manager like Nexus to store my jars.
(3) You can create a local repository using the filesystem resolver as follows in your settings file:
<ivysettings>
<settings defaultResolver='maven-repos' />
<resolvers>
<chain name='maven-repos'>
<ibiblio name='central' m2compatible='true' />
<ibiblio name='spring-external' m2compatible='true' root='http://repository.springsource.com/maven/bundles/external' />
</chain>
<filesystem name='local'>
<artifact pattern='/home/mark/tmp/petclinic/build/jars/[artifact]' />
</filesystem>
</resolvers>
<modules>
<module organisation='NA' name='mylibrary1.jar' resolver='local' />
<module organisation='NA' name='mylibrary2.jar' resolver='local' />
..
</modules>
</ivysettings>
When combined with the module declarations this makes the following possible in your ivy.xml file:
<dependency org='NA' name='mylibrary1.jar' rev='NA' />
<dependency org='NA' name='mylibrary2.jar' rev='NA' />
All other dependencies are retrieved from Maven repositories.
If you following the logic of my attached ant2ivy script you'll see I use this strategy with the jars I cannot identify using Sonatype's repository REST API
ant2ivy script
This is a rough and ready groovy script that performs a lookup of Sonatypes repository to identify jars in a specified directory
//
// Dependencies
// ============
import groovy.xml.MarkupBuilder
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Grapes([
@Grab(group='org.slf4j', module='slf4j-simple', version='1.6.2')
])
//
// Classes
// =======
class Ant2Ivy {
Logger log = LoggerFactory.getLogger(this.class.name);
String groupId
String artifactId
String repoUrl
Ant2Ivy(groupId, artifactId) {
this(groupId, artifactId, "http://repository.sonatype.org")
}
Ant2Ivy(groupId, artifactId, repoUrl) {
this.groupId = groupId
this.artifactId = artifactId
this.repoUrl = repoUrl
log.debug "groupId: {}, artifactId: {}", groupId, artifactId
}
//
// Given a directory, find all jar and search Nexus
// based on the file's checksum
//
// Return a data structure containing the GAV coordinates of each jar
//
def search(File inputDir) {
def results = [:]
results["found"] = []
results["missing"] = []
log.info "Searching: {} ...", repoUrl
def ant = new AntBuilder()
ant.fileset(id:"jars", dir:inputDir.absolutePath, includes:"**/*.jar")
ant.project.references.jars.each {
def jar = new File(inputDir, it.name)
// Checksum URL
ant.checksum(file:jar.absolutePath, algorithm:"SHA1", property:jar.name)
def searchUrl = "${repoUrl}/service/local/data_index?sha1=${ant.project.properties[jar.name]}"
log.debug "SearchUrl: {}, File: {}", searchUrl, jar.name
// Search for the first result
def searchResults = new XmlParser().parseText(searchUrl.toURL().text)
def artifact = searchResults.data.artifact[0]
if (artifact) {
log.debug "Found: {}", jar.name
results["found"].add([file:jar.name, groupId:artifact.groupId.text(), artifactId:artifact.artifactId.text(), version:artifact.version.text()])
}
else {
log.warn "Not Found: {}", jar.name
results["missing"].add([file:jar.name, fileObj:jar])
}
}
return results
}
//
// Given an input direcory, search for the GAV coordinates
// and use this information to write two XML files:
//
// ivy.xml Contains the ivy dependency declarations
// ivysettings.xml Resolver configuration
//
def generate(File inputDir, File outputDir) {
outputDir.mkdir()
def antFile = new File(outputDir, "build.xml")
def ivyFile = new File(outputDir, "ivy.xml")
def ivySettingsFile = new File(outputDir, "ivysettings.xml")
def localRepo = new File(outputDir, "jars")
def results = search(inputDir)
//
// Generate the ant build file
//
log.info "Generating ant file: {} ...", antFile.absolutePath
def antContent = new MarkupBuilder(antFile.newPrintWriter())
antContent.project(name: "Sample ivy builde", default:"resolve", "xmlns:ivy":"antlib:org.apache.ivy.ant" ) {
target(name:"resolve") {
"ivy:resolve"()
}
target(name:"clean") {
"ivy:cleancache"()
}
}
//
// Generate the ivy file
//
log.info "Generating ivy file: {} ...", ivyFile.absolutePath
def ivyConfig = new MarkupBuilder(ivyFile.newPrintWriter())
ivyConfig."ivy-module"(version:"2.0") {
info(organisation:this.groupId, module:this.artifactId)
configurations(defaultconfmapping:"default")
dependencies() {
results.found.each {
dependency(org:it.groupId, name:it.artifactId, rev:it.version, conf:"default->master")
}
results.missing.each {
dependency(org:"NA", name:it.file, rev:"NA")
}
}
}
//
// Generate the ivy settings file
//
log.info "Generating ivy settings file: {} ...", ivySettingsFile.absolutePath
def ivySettings = new MarkupBuilder(ivySettingsFile.newPrintWriter())
def ant = new AntBuilder()
ivySettings.ivysettings() {
settings(defaultResolver:"maven-repos")
resolvers() {
chain(name:"maven-repos") {
// TODO: Make this list of Maven repos configurable
ibiblio(name:"central", m2compatible:"true")
ibiblio(name:"spring-external", m2compatible:"true", root:"http://repository.springsource.com/maven/bundles/external")
}
if (results.missing.size() > 0) {
filesystem(name:"local") {
artifact(pattern:"${localRepo.absolutePath}/[artifact]")
}
}
}
if (results.missing.size() > 0) {
modules() {
results.missing.each {
module(organisation:"NA", name:it.file, resolver:"local")
ant.copy(file:it.fileObj.absolutePath, tofile:"${localRepo.absolutePath}/${it.file}")
}
}
}
}
}
}
//
// Main program
// ============
def cli = new CliBuilder(usage: 'ant2ivy')
cli.with {
h longOpt: 'help', 'Show usage information'
g longOpt: 'groupid', args: 1, 'Module groupid', required: true
a longOpt: 'artifactid', args: 1, 'Module artifactid', required: true
s longOpt: 'sourcedir', args: 1, 'Source directory containing jars', required: true
t longOpt: 'targetdir', args: 1, 'Target directory where write ivy build files', required: true
}
def options = cli.parse(args)
if (!options) {
return
}
if (options.help) {
cli.usage()
}
//
// Generate ivy configuration
//
def ant2ivy = new Ant2Ivy(options.groupid, options.artifactid)
ant2ivy.generate(new File(options.sourcedir), new File(options.targetdir))
Script is run as follows:
groovy ant2ivy.groovy -g com.hello -a test -s targetdir/WEB-INF/lib -t build
When run against the petclinic sample it produced the following files
build/build.xml
build/ivy.xml
build/ivysettings.xml
build/jars/..
..
The jars directory contains those libraries which could not be found in a Maven repo.
| |
doc_5096
|
I followed all the steps from the "Devise in an engine" guide on the devise wiki. The problem i'm running in to is that i can't use functions like 'current_user' and 'new_user_session_path' in the controllers of my main applications.
The error i'm getting in the main application is:
Showing .../main_app/app/views/shared/_header.haml where line #19 raised:
undefined local variable or method `new_user_session_path' for #<#<Class:0x007f1578968040>:0x007f157897b348>
= link_to t('user.login'), new_user_session_path
The engine does not have an isolate_namespace. I added Devise as a dependency in the engine.gemspec file and removed Devise from the Gemfile in the main application. The engine is mounted in the main application as:
mount Engine::Engine, at: 'idms'
In the routes of the engine i have devise configuered as:
devise_for :users, {
class_name: "IdmsGem::User",
module: :devise
controllers: { sessions: "devise/sessions" }
}
The initializers/devise.rb file is as followed:
require 'devise/orm/active_record'
Devise.setup do |config|
config.router_name = '/idms_gem'
end
The user model in the engine:
module Engine
class User < ActiveRecord::Base
devise :database_authenticatable
self.table_name = "users"
end
end
Im using Rails 4.2.1 with Devise 3.5.1 on Ruby 2.2.2.
My question is, how can i let my controllers and views in my main applications access functions from devise that is configured in my engine?
Any help is welcome! I have been googling and trying every thing for the last couple of days now.
Thanks every one!
EDIT: Rake routes gives the following output:
Prefix Verb URI Pattern Controller#Action
idms_gem /idms IdmsGem::Engine
{AND THE REST OF MY MAIN APP ROUTES...}
Routes for IdmsGem::Engine:
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
root GET / devise/sessions#new
A: You need to link to the engine's path. This will try and go to the application's path
link_to t('user.login'), new_user_session_path
So change it to (I think this is right)
link_to t('user.login'), IdmsGem.new_user_session_path
| |
doc_5097
| ||
doc_5098
|
Here is the code I used.
In:
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_grouped1
cd2 = data_grouped2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
ifelse(data_frame$dis >= 0, f = c(f,data_frame$dis),y = c(y,data_frame$dis))
This generates the error:
Error in if (x > 0) { : missing value where TRUE/FALSE needed
When I type this function seperate from the if statment it works so I am confused as to the issue.
I tried a workaround with:
for(x in c(dis[1:100])){if(x >= 0){f = c(f,x)}else{y=c(y,x)}}
but got the error:
Error in if (x > 0) { : missing value where TRUE/FALSE needed
Not sure how to fix this.
A: So the problem is that the way you're introducing f and y in the ifelse function, is the way function arguments are introduced. You get the error, because the function is expecting a command for what to do when the statement is TRUE or FALSE, and instead you're giving it an argument that it's not expecting.
One way to work around that is to create a new variable in dis and take it from there. So it would look like:
data_frame$pos<- ifelse(data_frame$dis >= 0, 1, 0)
f<- data_frame$dis[which(data_frame$pos == 1)]
y<- data_frame$dis[which(data_frame$pos == 0)]
A: try this
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_random1
cd2 = data_random2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
for(i in 1:nrow(data_frame)){
if(data_frame$dis[i] >= 0){
f = c(f, data_frame$dis[i])
} else{
y = c(y, data_frame$dis[i])
}
}
| |
doc_5099
|
It is certainly possible with TreeViews:
myTreeView.BeginUpdate();
try
{
//do the updates
}
finally
{
myTreeView.EndUpdate();
}
Is there a generic way to do this with other controls, DataGridView in particular?
UPDATE: Sorry, I am not sure I was clear enough. I see the "flickering", because after single edit the control gets repainted on the screen, so you can see the scroll bar shrinking, etc.
A: The .NET control supports the SuspendLayout and ResumeLayout methods. Pick the appropriate parent control (i.e. the control that hosts the controls you want to populate) and do something like the following:
this.SuspendLayout();
// Do something interesting.
this.ResumeLayout();
A: Double buffering won't help here since that only double buffers paint operations, the flickering the OP is seeing is the result of multiple paint operations:
*
*Clear control contents -> repaint
*Clear columns -> repaint
*Populate new columns -> repaint
*Add rows -> repaint
so that's four repaints to update the control, hence the flicker. Unfortunately, not all the standard controls have the BeginUpdate/EndUpdate which would remove all the repaint calls until the EndUpdate is called. Here's what you can do:
*
*Have a different control for each data set and Show/Hide the controls,
*Remove the control from its parent, update and then add the control again,
*Write your own control.
Options 1 and 2 would still flicker a bit.
On the .Net GUI program I'm working on, I created a set of custom controls that eliminated all flicker.
A: Rather than adding the rows of the data grid one at a time, use the DataGridView.Rows.AddRange method to add all the rows at once. That should only update the display once. There's also a DataGridView.Columns.AddRange to do the same for the columns.
A: This worked for me.
http://www.syncfusion.com/faq/windowsforms/search/558.aspx
Basically it involves deriving from the desired control and setting the following styles.
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
A: People seem to forget a simple fix for this:
Object.Visible = false;
//do update work
Object.Visible = true;
I know it seems weird, but that works. When the object is not visible, it won't redraw itself. You still, however, need to do the begin and end update.
A: Sounds like you want double-buffering:
http://www.codeproject.com/KB/graphics/DoubleBuffering.aspx
Although this is mainly used for individual controls, you can implement this in your Windows Forms control or Form.
A: Unfortunatly, I think that thins might just be a by-product of the .net framework. I am experiencing similar flickering albeit with custom controls. Many of the reference material I have read indicates this, alongside the fact the the double buffering method failed to remove any flickering for me.
A: You may also try this, its work.
public static void DoubleBuffered(Control formControl, bool setting)
{
Type conType = formControl.GetType();
PropertyInfo pi = conType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(formControl, setting, null);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.