_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d15901 | val | Read https://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:45033135081903
Oracle listener is expected to listen to your request for connection.
Here is the copy of Tom's answer
[tkyte@desktop tkyte]$ sh -vx test.sh
sqlplus
'scott/tiger@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost.localdomain)(PORT=152
1)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ora9ir2.kyte.com)))'
Use your host, port and service_name. | unknown | |
d15902 | val | const device = req.body.device;
console.log(device)
return db.none('INSERT INTO '+device+' (adc_v, adc_i, acc_axe_x, acc_axe_y, acc_axe_z, temperature, spo2, pa_diastolique, pa_systolique, indice_confiance, received_on, bpm)' +
'values(${adc_v}, ${adc_i}, ${acc_axe_x}, ${acc_axe_y}, ${acc_axe_z}, ${temperature}, ${spo2}, ${pa_diastolique}, ${pa_systolique}, ${indice_confiance}, ${received_on}, ${bpm})',
req.body)
try this | unknown | |
d15903 | val | Short answer: Yes.
One of the main things that made jQuery popular in the first place was that it allowed older browsers to support the new selectors like :not.
So yes, you will be able to use :not and other selectors in jQuery code.
You can't use :not with querySelectorAll() in IE8 because IE8 simply doesn't support it. IE8 supports CSS2.1 which was the current standard at the time it was released. :not simply wasn't in the picture. And you can't use querySelectorAll() at all in older IE versions than that.
jQuery was created specifically to deal with these issues and allow developers to support older IE versions while still allowing us to use modern browser features.
There may be people today saying that you don't need jQuery any more, but if you need to support old IE versions, the need for jQuery is just as much as it always was. | unknown | |
d15904 | val | The best way to handle this would be to use Task.Run() and Task.WhenAll(), or to use Parallel.Invoke().
However, if you need to use ThreadPool.QueueUserWorkItem you can solve this issue as follows:
*
*For ease of use, encapsulate all the data that you want to pass to the thread in a class. This data should include an instance of CountdownEvent initialised with a count equal to the number of threads you want to wait for. (In the sample code below, this class is called ThreadData.)
*Inside your TaskCallBack() methods, call CountdownEvent.Signal() when the method has completed.
*Inside the main thread, start all the threadpool threads and then call CountdownEvent.Wait() to wait for all the threads to complete.
Putting this all together in a compilable console app:
using System;
using System.Threading;
namespace CoreConsole
{
public sealed class ThreadData
{
public ThreadData(CountdownEvent countdown, int index)
{
Countdown = countdown;
Index = index;
}
public CountdownEvent Countdown { get; }
public int Index { get; }
}
public static class Program
{
static void Main()
{
int n = 20;
var countdown = new CountdownEvent(n);
for (int task = 0; task < n; task++)
{
ThreadPool.QueueUserWorkItem(TaskCallBack, new ThreadData(countdown, task));
}
Console.WriteLine("Waiting for all threads to exit");
countdown.Wait();
Console.WriteLine("Waited for all threads to exit");
}
public static void TaskCallBack(object state)
{
var data = (ThreadData) state;
Console.WriteLine($"Thread {data.Index} is starting.");
Thread.Sleep(_rng.Next(2000, 10000));
data.Countdown.Signal();
Console.WriteLine($"Thread {data.Index} has finished.");
}
static readonly Random _rng = new Random(45698);
}
}
The ThreadData.Index property is just used to identify each thread in the Console.WriteLine() calls.
Note: In real code, it is important to always signal the Countdown event, even if the thread throws an exception - so you should wrap the code in a try/finally like so:
public static void TaskCallBack(object state)
{
var data = (ThreadData)state;
try
{
// Do work here.
Console.WriteLine($"Thread {data.Index} is starting.");
Thread.Sleep(_rng.Next(2000, 10000));
Console.WriteLine($"Thread {data.Index} has finished.");
}
finally
{
data.Countdown.Signal();
}
}
A: Like @Ackdari mentioned in his comment, you could use Task.Run. But you don't need the await keyword. Just create a collection with the tasks and wait for it.
Example:
// Create a list that will hold the tasks
List<Task> tasks = new List<Task>;
// Create the tasks
for (int taskId = 0; taskId < 20; task++)
{
tasks.Add(Task.Run(() => { TaskCallBack(new object[] { filepath1, filepath2, filepath3 }); }));
}
// Wait for ALL tasks to complete
Task.WaitAll(tasks.ToArray());
That way you could also use your own method that will be run by the task.
Example:
public static void ReplaceWithABetterName(string[] filePaths)
{
string filea = filePaths[0);
string fileb = filePaths[1];
string filec = filePaths[2];
//do stuff
} | unknown | |
d15905 | val | I once had a very similar problem.
I published the code on github, check it out multi-tenant-spring-mongodb
You basically have to extend SimpleMongoDbFactory and handle other hosts too. I just did handle multiple databases on the same server. That shouldn't be a problem.
A: You can extend:
1. `SimpleMongoDbFactory`: returning custom DB in DB `getDb(String dbName)`.
2. `MongoTemplate`: Supplying above factory.
Use appropriate MongoTemplate with the help of @Qualifier. | unknown | |
d15906 | val | Yes and no.
According to the server docs on floats, the 'native' C types support up to double precision (BINARY_DOUBLE). However, the NUMBER type can store:
*
*Positive numbers in the range 1 x 10-130 to 9.99...9 x 10125 with up to 38 significant digits
*Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with up to 38 significant digits
which is more precision than long double on x86/amd64.
So, you'd need to use that type instead of BINARY_*. Sadly, the developer docs say:
You should not need to use NUMBER as an external datatype. If you do use it, Oracle returns numeric values in its internal 21-byte binary format and will expect this format on input. The following discussion is included for completeness only.
On the other hand, there are also docs on:
*
*using the OCINumber type;
*OCI NUMBER Functions.
AFAICS OCINumberFromReal() supports long double; and if you want even more precision, then you could use OCINumberFromText() with decimal string. | unknown | |
d15907 | val | I think you've been getting some downvotes because you didn't share any of your previous attempts, on which the solution could be built.
I think what you might want to do is use a CustomClipper to create the desired shape. I wrote you a simple one that makes a wedged shape with just 4 points, but you can use Path.arc to make it more like the image you provided:
class WedgeClipper extends CustomClipper<Path> {
final bool isRight;
WedgeClipper({this.isRight = false});
@override
Path getClip(Size size) {
Path path = Path();
// mirror the clip accordingly when it's left or right aligned
if (isRight) {
path.addPolygon([
Offset(0, size.height / 4),
Offset(size.width, 0),
Offset(size.width, size.height),
Offset(0, 3 * size.height / 4)
], true);
} else {
path.addPolygon([
Offset(0, 0),
Offset(size.width, size.height / 4),
Offset(size.width, 3 * size.height / 4),
Offset(0, size.height)
], true);
}
return path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return true;
}
}
Then to use it in your code, you can do something like:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Wedge List View'),
),
body: ListView.builder(
itemBuilder: (context, index) {
bool isRightAligned = index % 2 == 0;
return Padding(
child: ClipPath(
child: Material(
child: SizedBox(
height: 80,
width: double.maxFinite,
child: Row(
mainAxisAlignment: isRightAligned ? MainAxisAlignment.end : MainAxisAlignment.start,
children: isRightAligned ? [
Text('Tile to the right side'),
SizedBox(width: 10),
Image.network('https://upload.wikimedia.org/wikipedia/commons/b/b1/VAN_CAT.png'),
] : [
Image.network('https://upload.wikimedia.org/wikipedia/commons/b/b1/VAN_CAT.png'),
SizedBox(width: 10),
Text('Tile to the left side'),
],),
),
color: Color(0xffdddddd),
),
clipper: WedgeClipper(
isRight: isRightAligned), // alternating left/right clips
),
padding: EdgeInsets.symmetric(horizontal: 8.0),
);
},
),
);
}
It basically draws a rectangle, clips it with the CustomClipper and renders what's left.
The result looks like this: | unknown | |
d15908 | val | you can do this in two ways:
first you can pass props from the parent to the child and communicate between the two components by this.set your variable in the parent component and pass that via props to the child component.in this case your child component is responsible to show whatever comes from the parent.
the second one is using a global state management like Redux,ContextApi or mobX to catch error in the child and save it to an state and then use that state in the parent component or wherever you want to use.
depend on the size of your project you can use either way.
A: Thanks to the responses and comments I managed to elaborate the following solution:
1- I created a function in ListChat that will receive the error message (msg) by parameter:
setError = (msg) => {
this.setState({error:msg});
}
2- I passed the function as props in rendering the chat:
this.setState({chat: <Chat setError={this.setError}/> });
3- When I need to now pass an error by the Chat for ListChat,
I call in the Chat component:
props.setError("Name is null"); | unknown | |
d15909 | val | Based on documentation PrimeFaces 11 has dependency JSF with ver. 2.0, 2.1, 2.2, 2.3, 3.0, 4.0. Where JSF can be Apache MyFaces or Eclipse (former Oracle) Mojarra. | unknown | |
d15910 | val | I don't have much experience with Rails 3.2; with newer versions, you're able to pass collections to partials:
<%= render @pos, layout: 'today_items_list' %>
#app/views/pos/_today_items_list.html.erb
.tableless_cell.no_padding
%h3.no_margin_vertical= title
%ul.no_margin_vertical
<%= yield %>
#app/views/post/_po.html.erb
<%= link_to "##{po.id}", po %>
<%= po.supplier.name %>
You can read more about collections etc (I presume for Rails 4+) here. | unknown | |
d15911 | val | try this:
webView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
imageView.setImageBitmap(bmap);
A: You can open an InputStream pointing to the image URL (using URLConnection), and create a Drawable from it using Drawable.createFromStream. You can then set the Drawable onto the ImageView.
A: As per your above comment: ok you are right it must be easier getting the image directly... how do i do that ? Do i look in bitmap doc ?, i assume you want to load image from web and want to display the same in imageview, if this is the case then refer this to get exactly: How to display image from URL on Android
A: Bitmap btmp = mwebview.getDrawingCache(true);
this will return the Bitmap image in webview.
And the bitmap can be set to image view by:
imageView.setImageBitmap(bmap); | unknown | |
d15912 | val | Problem:
This problem occurs when you run your code on windows because windows paths use backslash ("\") instead of forward slash ("/").
As you see in the code:
https://github.com/pytorch/vision/blob/7b9d30eb7c4d92490d9ac038a140398e0a690db6/torchvision/datasets/ucf101.py#L94
So, this line of code reads the file path from label file as “action\video_name” and merge it with “root” path using backslash therefore full path becomes like “root\action/video_name”. Such paths doesn’t match with the video lists at line#97 and returns empty list for indices variable.
Solution:
Two of possible solutions can be:
*
*Replace the forwardslashes “/” in the label files with backslashes “\”.
*Override the _select_fold(…) function of class UCF101 and fix the backslashes inside the function | unknown | |
d15913 | val | I wrote a PHP class that I use in all my projects that require different access for different roles. I put a copy of the class out on paste bin: class_role_restrictions.php.
This class also requires another class I wrote, which can be obtained here: better_mysqli.php
The initial setup involves the creation of some database tables (The SQL create statements are found in comments at end of the class_role_restrictions.php file) and adding roles / user memberships via it's admin interface.
Detailed setup/usage can be obtained here: role_restrictions_detailed_example.php
Once it is setup you can use it like this:
<?php
include_once('class_role_restrictions.php');
include_once('better_mysqli.php');
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
$role = new role_restrictions($mysqli, 'http://your_server.com/path/to/this/page/example.php');
// == Restrict an entire page to authorized users only ==
$role->restrict_to('role_name, to_restrict user_to', 'username_currently_logged_in');
// .. now do stuff that only users in any of the roles listed are allowed to do
// -- OR --
// == Only do certain things if the username given is a member of any of the roles given ==
if( $role->has_role('a_list, of_roles, allowed', 'username_currently_logged_in') ){
// .. do stuff that only users in the given role(s) are allowed to do ..
}
?> | unknown | |
d15914 | val | You don't have a bad configuration, it's a bug that Apple introduced in the simulator SDK when they released iOS4. Basically, if code invoked using an NSInvocation object throws an exception, then that exception is uncatchable. I wrote about the issue when it first appeared here:
http://pivotallabs.com/users/adam/blog/articles/1302-objective-c-exceptions-thrown-inside-methods-invoked-via-nsinvocation-are-uncatchable
Unfortunately, this bug affects OCMock and Apple hasn't show much interest in fixing it. Many people have filed bug reports, but to no avail.
I realize this is little comfort, but you will get slightly better error messages when using Cedar for testing (I believe the same is true for GTM).
A: I'd say it's a bug. Verify should report a useable result, even if it fails.
A: I have found that this bug is still around with Xcode 4/SDK 4.3 in April of 2011. For example, Test A passes, Test B crashes the test rig.
Test A:
- (void)testAcceptsAndVerifiesExpectedMethods
{
id mock = [OCMockObject mockForClass:[NSString class]];
[[mock expect] lowercaseString];
[mock lowercaseString];
[mock verify];
}
Test B:
- (void)testAcceptsAndVerifiesExpectedMethods
{
id mock = [OCMockObject mockForClass:[NSString class]];
[[mock expect] lowercaseString];
//[mock lowercaseString];
[mock verify];
}
A: A workaround I've found is to wrap the [mockObject expect] and [mockObject verify] calls with XCTAssertNoThrow, e.g.:
XCTAssertNoThrow([[mockTaskVC expect] showAlertWithTitle:containsString(@"Error") message:OCMOCK_ANY completion:OCMOCK_ANY], @"threw up exception");
This will catch the exception and fail the text rather than crashing.
Credit to author here: http://www.mulle-kybernetik.com/forum/viewtopic.php?f=4&t=315&p=710&hilit=unexpected+method+was+not+invoked+exception#p710 | unknown | |
d15915 | val | Maybe you can use the canDisplay(...) method of the Font class. | unknown | |
d15916 | val | Firstly, don't use inline styles. Anyone that touches your code will hate you and when you want to apply a change to 100 elements that are the same at once you will equally hate yourself.
Also, HTML is the bread, CSS is the butter. On their own they're rubbish but together they're super awesome.
The only reason your "sidebar" isn't full height is because the content of the element next to is has more content. You need to incorporate CSS to stop this from happening.
A: See the fiddle
The reason why the sidebar was a little bit down was because of the inline-block that you had in the style.In the fiddle that i have made i have replaced the display:inline-block; with float:left;. Kindly see the fiddle
The new markup is as follows
<header style='background-color:#013499; height:60px'>
<br> <span style='color:white'>    Whole Number</span>
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</header>
<div>
<div style='float:left; background-color:#7690C5; width:200px;'>Task1
<br>Task2
<br>
</div>
<div style='float:left; background-color:#F2F2F2;'>Top
<br>Content
<br>Bottom</div>
</div>
<footer style='clear:both;background-color:#013499; height:60px'>
<br>
<form name="Actions" action="test.html" method="post">   
<input type="submit" name="send_button" value="Save">   
<input type="submit" name="send_button" value="Cancel">
</form>
</footer>
A: Try using fixed (or absolute) positions perhaps. Try this, for example:
<header style="background-color:#013499; height:60; right: 0;left: 0;top: 0;position: fixed;">
<div style="display:inline-block; background-color:#F2F2F2;float: right;top: 60px;position: fixed;right: 0;">
<footer style="background-color:#013499; height: 62px;position: fixed;width: 100%;left: 0;bottom: 0;"> | unknown | |
d15917 | val | You correctly noted that
in preprocessing stage STRcommaLen is not expanded
- more precisely, not before the strncmp macro gets expanded. This inevitably leads to an error you probably overlooked or forgot to mention:
sample.c:7:30: error: macro "strncmp" requires 3 arguments, but only 2 given
Your conclusion
that -O1 adds some optimizations that are not controlled by flags and
this is one of them
is also right - this is controlled by the macro __OPTIMIZE__ which apparently gets set by -O1.
If I'd do something like that (which I probably wouldn't, in respect of the pitfall you demonstrated by using sizeof a char *), I'd still choose
mapping your own functions to every standard function that may become
a macro
- but rather like
#include <string.h>
#define STRNCMP(s1, s2) strncmp(s1, s2, sizeof(s2)-1)
int main()
{
const char b[] = "string2";
const char c[] = "string3";
STRNCMP(b, c);
} | unknown | |
d15918 | val | Use this code: .resizable( "destroy" )
A: Try .resizable("option", "disabled", true);
http://jqueryui.com/demos/resizable/#option-disabled
Your solution is not working because, as per the documentation you need use the setter that I mentioned, if you want to disable it after initialization (you code will only work if its an initialization call)
A: Oops...
I was disabling "resizable" before I enabled it... | unknown | |
d15919 | val | The best practice linked in your article says Define the MongoDB client connection outside of your handler function. In your case you should change const db = ... to db = ... and declare db outside of your handler function and change it to let db = null like in the example in the article, so you can reuse the connections in different Lambda invocations. For example:
let db = null;
export const handler = async (event, context, callback) => {
if (!db) {
db = connectToDatabase();
}
// do something with your db
callback();
};
Besides that, take @hoangdv 's advice and call the callback function to signal AWS Lambda that you're done with handling the event. That should do the trick.
A: I found that AWS Lambda functions can only run for a maximum of 15 minutes (even if the code is still running after that amount of time). If I wanted to run the script for more than 15 minutes, I guess I would have to use an AWS EC2 instance.
Source: https://aws.amazon.com/lambda/faqs/
A: I have a similar issue with trying so many different approaches, having a larger maximum memory, and having a longer latency time. but they fail to solve it.
Then I found a solution by not using the whole parameter, its' value may be changed, outside of functions. Because cache can store the param in memory. it may lead the program to read the value from cache memory.
So put cachedClient, cachedDb defining in function:connectToDatabase not out of function. | unknown | |
d15920 | val | Long answer short, the limit is 8060 bytes per row, but 8096 bytes per page. The rows in the article you linked have a row size of ~4000 bytes, so they are well under the limit per row. However, that does not answer the question of how many such rows fit on a page.
See "Estimating the size of a heap" in Books Online:
http://msdn.microsoft.com/en-us/library/ms189124.aspx
If you do the calculation for the tables in the article, you'll see that the first table has a physical row size of 4048 bytes, which is exaclty half the 8096 limit for a page.
A: *
*The maximum row size is 8060 bytes
*In this case, there are two rows each of 4039 bytes | unknown | |
d15921 | val | As already said in comments, insert into List<T> preserve ordering, so described behaviour shouldn't happen.
Simple example:
var lst = new List<int> {1,2,3,4};
lst.Insert(0,0);
lst.Dump(); | unknown | |
d15922 | val | Like,
//validate.php
//get the post fields
$email_address = trim( $_POST["emailid"] );
//check if email exists against database, like
if( is_valid_from_db( $email_address ) ) {
return TRUE;
}
else {
return FALSE;
}
A: I am sure you have looked at the docs:
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
validate.php just needs to do what it says validate the fields.
This other question might be of some help:
jQuery Remote validation
A: I was also looking for an answer for this problem of validating multiple fields with remote method.
To determine each field separately, you don't have to define remote method for each field. Whereas you can define remote method for your 'emailid' field and you can send 'userid' alongside the emailid using data option as follows.
emailid: {
required: true,
remote: {
url: "validate.php",
type: "post",
data: {
userid: function() {
return $("#userid").val();
}
}
}
}
So you can have your js like this
<script type="text/javascript">
$(document).ready(function(){
$("form").validate({
rules: {
userid: {
required: true
}
emailid: {
required: true,
remote: {
url: "validate.php",
type: "post",
data: {
userid: function() {
return $("#userid").val();
}
}
}
}
},
messages: {
userid: {
remote: jQuery.validator.format("userid {0} is already taken")
}
emailid: {
remote: jQuery.validator.format("emailid {0} is already taken")
}
}
});
});
</script>
The above will post userid and emailid to your validate.php where you can follow DemoUser's answer. But make sure the returning values (true/false) are string values | unknown | |
d15923 | val | Looks like a bug, it will be fixed in the next release.
Since you are not using the fall-through Switch feature you can just use Select or If/ElseIf instead:
${Select} "${LANGNAME}"
${Case} "${LANGFILE_ALBANIAN_NAME}"
DetailPrint LANG_ALBANIAN
${Case} "${LANGFILE_ARABIC_NAME}"
DetailPrint LANG_ARABIC
${EndSelect} | unknown | |
d15924 | val | SELECT *
FROM posts P
LEFT
JOIN categories C
ON C.cat_id = P.c_id
LEFT JOIN (SELECT p_id FROM votes WHERE u_id = $uid) V
ON V.p_id=P.post_id
WHERE P. active = 1
ORDER
BY P.post_id DESC
LIMIT 0, 10 ;
A: LEFT JOIN votes table (also no need fo left join categories if you don't want null-joins). If user has voted there will be values in joined columns - nulls will be joined otherwise.
SELECT *
FROM posts AS p
INNER JOIN categories AS c ON c.cat_id = p.c_id
LEFT JOIN votes AS v ON p.post_id = v.p_id AND v.u_id = $uid
WHERE p.active = 1
ORDER BY p.post_id DESC
LIMIT 0, 10
Not voted post will have nulls in vote columns, but since you want only know if user has voted you may limit output data (get only what you need) specifying concrete fields and make voted column that returns 1/0 values only:
SELECT p.*, c.title, ..., IF(v.vote_id; 1; 0) AS voted
A: You could use a join targeting the common Fields in both the Votes Table and the Posts Table like so:
<?php
$sql = "SELECT * FROM votes AS V LEFT JOIN posts AS P ON V.p_id=P.post_id
WHERE (V.u_id={$uid} AND V.p_id={$post_id}) GROUP BY V.u_id";
A: You can't select votes as an array in a column but you can actually extract votes and group them. So basically what we'll do is join the two tables partially and maybe sum all the votes
SELECT p.*, c.*, sum(v.Score) FROM posts p LEFT JOIN categories c ON c.cat_id = p.c_id LEFT JOIN votes v ON p.post_id = v.p_id WHERE p.active = 1 AND v.u_id = $uid GROUP BY p.post_id ORDER BY p.post_id DESC LIMIT 0, 10
You can see that I'm summing all the scores in the votes in case there're duplications | unknown | |
d15925 | val | Mapping on a try applies a function to the value held by a success of that try, what you have there is not a Success or a Failure, it's a T, what you want is a match:
def handler[T](t: Try[T], successFunc: T => Unit) = {
t match {
case Success(res) =>
successFunc(res)
case Failure(e: FileNotFoundException) =>
case Failure(e) =>
}
}
The usage in your case of map would be:
t.map(someT => successFunc(someT)) | unknown | |
d15926 | val | func scrollViewDidScroll(_ scrollView: UIScrollView) {
// This will always round down to zero
// since the contentOffset.x will always be smaller than the frame width...
let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width)
// Possible logic to correct this?
let pageIndex = scrollView.contentOffset.x / (width of a slide)
pageControl.currentPage = Int(pageIndex)
}
-- Updated due to chat --
Your scrollview's frame is fine. However, you need to add a stackview to hold all your slides in order to scroll through it. Scrollviews are a bit tricky since you can't just add views and expect it to be scrollable.
Here is test code I used to create a scrollView that contains stackviews.
func createSlideshow() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
let slide1 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide1.backgroundColor = UIColor.red
let slide2 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide2.backgroundColor = UIColor.blue
let slide3 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide3.backgroundColor = UIColor.yellow
let slides: [UIView] = [slide1, slide2, slide3]
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 10
for slide in slides {
stackView.addArrangedSubview(slide)
slide.widthAnchor.constraint(equalToConstant: slide.frame.width).isActive = true
slide.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true
}
scrollView.addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true
stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
} | unknown | |
d15927 | val | Have a look into ASP.NET Web Application Project Deployment Overview
and this one also helps HOW TO: Deploy an ASP.NET Web Application Using the Copy Project Feature in Visual Studio .NET | unknown | |
d15928 | val | You can use the join syntax to join tables according to the matching fields:
SELECT crypted_password, salt
FROM users
JOIN role_users ON users.id = role_uses.user_id
JOIN role ON role_users.role_id = role.id
WHEN role.name = 'teacher'
A: Join Like this
SELECT U.*
FROM USER U
JOIN Role_Users RU ON RU.UserID = U.ID
JOIN Role R ON R.ID = RU.Role_ID
WHERE <Your Conditions here>
A: select crypted_password,salt
from Users U
inner join Role_users RU on RU.user_id = U.ID
inner join Role R on R.id = RU.role_id
where R.name='teacher' | unknown | |
d15929 | val | If it does not have a set number of branches you likely want to loop over a query in your app or write an SP to obtain all nodes. Some good reading here:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ | unknown | |
d15930 | val | why not use random sampling without replacement
import numpy as np
n = 25
a = range(26)
out = np.random.choice(a, size=n, replace=False)
len(np.unique(out))
>>>25 | unknown | |
d15931 | val | controllerProvider is the $controller service used by Angular to create new controllers:
https://docs.angularjs.org/api/ng/provider/$controllerProvider
If you are new to angular I suggest you to use the standard way to create a controller:
var appTmw = angular.module('appTmw', ['ui.router']);
appTmw.controller('controllerName', function($scope){
//your code for the controller here
});
I hope it helps. | unknown | |
d15932 | val | I found that if I wrapped the content of a view in a VStack, perhaps other Stacks would also work, the view will animate in the previewer
Heres a quick example of a view that if wrapped in a VStack in the PreviewProvider previews the button will animate. But if the VStack is removed it will no longer animate. Try it out!
struct AnimatedButton : View {
@State var isAnimating: Bool = false
var body: some View {
Button(action: {
self.isAnimating.toggle()
}) {
Text("asdf")
}.foregroundColor(Color.yellow)
.padding()
.background(Color(.Green))
.cornerRadius(20)
.animation(.spring())
.scaleEffect(isAnimating ? 2.0 : 1.0)
}
}
#if DEBUG
struct FunButton_Previews : PreviewProvider {
static var previews: some View {
VStack {
AnimatedButton()
}
}
}
#endif | unknown | |
d15933 | val | Since the values you posting back are for your nested UnitConfigVals class (not SaveConfigModel, then you controller method should be
public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model)
and the ajax data option needs to be
data: JSON.stringify({ model: saveConfigModel })
Alternatively you could keep the current controller method and use
data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }})
although it seems a little odd that you using a nested class here.
A few other issues with your initial code
*
*$('#ckbx_produceusage').checked will return undefined, and it
needs to be $('#ckbx_produceusage').is(':checked') which will
return true or false
*Since recipients is List<string>, it will need to be
recipients: [ 'someValue', 'anotherValue', etc ]
However all this code to build you json data not really necessary, and if your view is generated correctly using the strongly typed HtmlHelper methods, then your ajax call can be as simple as
$.ajax({
type:"POST",
url:'@Url.Action("PostUnitConfig", "SaveConfig")',
dataType: "json",
data: $('form').serialize(),
success: function(data) {
// do something
}
}); | unknown | |
d15934 | val | This will work
SELECT LENGTH(regexp_replace('220138|251965797?AIRFR?150350161961|||||','[^|]','')) | unknown | |
d15935 | val | You can use of java.nio.ByteBuffer. It has a lot of useful methods for pulling different types out of a byte array and should also handle most of your issues.
byte[] data = new byte[36];
ByteBuffer buffer = ByteBuffer.wrap(data);
float second = buffer.getFloat(); //This helps to
float x = 0;
buffer.putFloat(x);
A: You just need to copy the bits.
Try using BlockCopy.
float[] fArray = new float[] { 1.0f, ..... };
byte[] bArray= new byte[fArray.Length*4];
Buffer.BlockCopy(fArray,0,bArray,0,bArray.Length);
The *4 is since each float is 4 bytes. | unknown | |
d15936 | val | This is the design of the layer caching. When you run the same command with the same inputs as before, Docker finds a layer where you started from the same parent and ran the same command, and is able to reuse that layer. When your input changes (from the COPY command changing its input), the cache becomes invalid and it goes back to building on top of a fresh node:6 image. From that image, none of your previously downloaded files are available. | unknown | |
d15937 | val | dict((z[0], list(z[1:])) for z in zip(list1, list2, list3))
will work. Or, if you prefer the slightly nicer dictionary comprehension syntax:
{z[0]: list(z[1:]) for z in zip(list1, list2, list3)}
This scales up to to an arbitrary number of lists easily:
list_of_lists = [list1, list2, list3, ...]
{z[0]: list(z[1:]) for z in zip(*list_of_lists)}
And if you want to convert the type to make sure that the value lists contain all integers:
def to_int(iterable):
return [int(x) for x in iterable]
{z[0]: to_int(z[1:]) for z in zip(*list_of_lists)}
Of course, you could do that in one line, but I'd rather not.
A: In [12]: list1 = ('a','b','c')
In [13]: list2 = ('1','2','3')
In [14]: list3 = ('4','5','6')
In [15]: zip(list2, list3)
Out[15]: [('1', '4'), ('2', '5'), ('3', '6')]
In [16]: dict(zip(list1, zip(list2, list3)))
Out[16]: {'a': ('1', '4'), 'b': ('2', '5'), 'c': ('3', '6')}
In [17]: dict(zip(list1, zip(map(int, list2), map(int, list3))))
Out[17]: {'a': (1, 4), 'b': (2, 5), 'c': (3, 6)}
In [18]: dict(zip(list1, map(list, zip(map(int, list2), map(int, list3)))))
Out[18]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}
For an arbitrary number of lists, you could do this:
dict(zip(list1, zip(*(map(int, lst) for lst in (list2, list3, list4, ...)))))
Or, to make the values lists rather than tuples,
dict(zip(list1, map(list, zip(*(map(int, lst) for lst in (list2, list3, list4, ...)))))) | unknown | |
d15938 | val | My question is, what is the best way to handle the destruction of a mutex? Should I wait for it to be free?
You should not destroy resources while they are being used because that often leads to undefined behaviour.
The correct course of action is:
*
*Tell the other thread to release the resources and wait till it does, or
*Tell the other thread to terminate politely an wait till it has done so, or
*Pass the ownership of the resource to another thread and let it manage the resource's lifetime as it pleases, or
*Use shared resources, so that they stay alive while its users are still around. | unknown | |
d15939 | val | Try adding your accept header
var req = WebRequest.CreateHttp(uri);
req.Headers.Add(HttpRequestHeader.Accept, "application/ json");
req.Method = "Get";
A: SOLUTION:
My problem was gzip it compressed my json.
using (WebClient wc = new WebClient())
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(testurl);
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
responseinger = req.GetResponse();
reader = new StreamReader(responseinger.GetResponseStream());
httpResponse = reader.ReadToEnd();
//Console.WriteLine(reader);
//Console.WriteLine();
Console.WriteLine(httpResponse);
Console.WriteLine();
} | unknown | |
d15940 | val | I do not know how/where you are using this, but bear in mind that it is completely vulnerable to SQL injection attacks.
String textbox1=request.getParameter("textbox1");
String textbox2=request.getParameter("textbox2");
String textbox3=request.getParameter("textbox3");
String textbox4=request.getParameter("textbox4");
String textbox5=request.getParameter("textbox5");
String textbox6=request.getParameter("textbox6");
String textbox7=request.getParameter("textbox7");
String textbox8=request.getParameter("textbox8");
String textbox9=request.getParameter("textbox9");
String textbox10=request.getParameter("textbox10");
String textbox11=request.getParameter("textbox11");
String textbox12=request.getParameter("textbox12");
for(int i=1;i<13;i++){
String textbox=request.getParameter("textbox"+i+"");
st.executeUpdate("update user_start2 set data='"+textbox+"' where id="+i+";");
}
A: I assume that id is a unique identifier in your table user_start2. If so, then you need to alter the update statement above so that it reads,
"update user_start2 set data= '"+textbox+"' where id = '"+Myuserid);
Based on what you are saying, I assume that there are 13 entries in your database and that you are updating each one. If so, there must be some correspondence between the ids and the index in your for loop. If it is a literal 1 to 1 mapping, then you can simply write your update statement as
"update user_start2 set data= '"+textbox+"' where id = '"+i+"'");
If there is some transformation that needs to be done first, you could create a temporary variable and set the id to that:
For example
int temp = i+4;
"update user_start2 set data= '"+textbox+"' where id = '"+temp+"'");
A: Use PreparedStatement it prevents SQL Injection in Java
for(int i=1;i<13;i++){
String textbox=request.getParameter("textbox"+i+"");
PreparedStatement ps = con.prepareStatement("update user_start2 set data=? where id=?");
//set the values of ?(place holders)
ps.setString(1,textbox);
ps.setInt(2,i); //assuming id is i.
ps.executeUpdate();
}
See also
*
*Oracle docs tutorial PreparedStatement | unknown | |
d15941 | val | I can't comment (don't have enough rep), so I'm posting this as an answer. I think you can create a table that stores ingredient_id and recipe_id, call it RecipeToIngredients or something like that. You can then relate the ingredient_id to the records in the ingredients table, and the recipe_id to the recipe table. You can have multiple recipes linking to exactly the same ingredient row.
You say you want to delete the recipe without deleting the ingredient, so you can do that with this setup. When you delete the recipe, you can delete the records from the RecipeToIngredients table, and not delete them from the Ingredients table.
Then you say "I would like the ingredient to still belong to them". By "them", do you mean still belong to the Recipe? If so, then I wouldn't delete the Recipe, maybe create an "Active" field on the recipe table and set it to inactive. Or you could still delete the Recipe and keep the records on the RecipeToIngredients table, but then you will have a recipe_id value in that table that doesn't mean anything. If by "them" you don't mean the Recipe, then if you would clarify what you do mean, that would be helpful. | unknown | |
d15942 | val | You are missing quotes around [email protected]. You need to change it to "[email protected]", so that it is interpreted as a string. The exception tells you which line and character the error is at, so double check that line when you get errors like these. | unknown | |
d15943 | val | Not sure if you still have this problem, but for me, the scale is exactly the opposite. minimumZoomScale = 1 for me and I have to calculate the maximumZoomScale.
Here's the code:
[self.imageView setImage:image];
// Makes the content size the same size as the imageView size.
// Since the image size and the scroll view size should be the same, the scroll view shouldn't scroll, only bounce.
self.scrollView.contentSize = self.imageView.frame.size;
// despite what tutorials say, the scale actually goes from one (image sized to fit screen) to max (image at actual resolution)
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat minScale = 1;
// max is calculated by finding the max ratio factor of the image size to the scroll view size (which will change based on the device)
CGFloat scaleWidth = image.size.width / scrollViewFrame.size.width;
CGFloat scaleHeight = image.size.height / scrollViewFrame.size.height;
self.scrollView.maximumZoomScale = MAX(scaleWidth, scaleHeight);
self.scrollView.minimumZoomScale = minScale;
// ensure we are zoomed out fully
self.scrollView.zoomScale = minScale;
A: For simple zoom in/out i generally use below code. minimumZoomScale= 1 sets initial zoom to current image size. I have given maximumZoomScale = 10 which can be calculated from actual ratio of image size and container frame size.
[scrollView addSubview: iImageView];
scrollView.contentSize = iImageView.frame.size;
scrollView.minimumZoomScale = 1.0;
scrollView.maximumZoomScale = 10;
[iImageView setFrame:CGRectMake(0, 0, 450, 320)];
[scrollView scrollRectToVisible:iImageView.frame animated:YES]; | unknown | |
d15944 | val | The "decorators" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named "decorator syntax" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to support an application of the Decorator Design Pattern to Lua functions (by holding "extra attributes" -- such as docstrings, typechecking functions, etc -- in separate global tables).
Lua does support HOFs (I'm not sure if you can re-bind a function name to the result of applying a HOF to the function, but you can easily, as the wiki pages show, use an anonymous "original function" and only bind a name to the HOF's result with that anon function as the arg).
Python's "decorator syntax" syntax sugar is nice (and, to my surprise, seems to have increased the use of HOFs by most Pythonistas by an order of magnitude!-), but there's nothing intrinsic or essential about them that you can't do in Lua (and Lua's anonymous functions run circle around Python's goofy, limited lambda anyway -- just like in Javascript, they have essentially the same power, and pretty much the same syntax, as a "normal" named function!-). | unknown | |
d15945 | val | By enclosing A3 in ampersands you are referencing cell A3 in the current sheet. What you want is:
=SUMIF(INDIRECT("'A3'!$B:$B"),D$2,INDIRECT("'A3'!$M:$M"))
On second look, if you are intending to reference a sheet that is named what you have in cell A3 then you don't need the apostrophes around the cell reference:
=SUMIF(INDIRECT(A3&"!$B:$B"),D$2,INDIRECT(A3&"!$M:$M")) | unknown | |
d15946 | val | You seem to initialize the players (and their boards respectively) after trying to add their board to a panel, which is impossible since you did not create the players yet.
public BattleshipUI(){
initComponents(); //Here you try to add the board of a player
initObjects(); //Here you initialize the players (ergo nullpointer)
}
private void initComponents(){
for(int i = 0; i <= 10; i++){
for(int j = 0; j <= 10; j++){
//playerOne is not instantiated yet
playerOnePanel.add(**playerOne**.getBoard());
}
}
}
private void initObjects(){
**playerOne** = new Player("Player One");
playerTwo = new Player("Player Two");
players[1] = playerOne;
players[2] = playerTwo;
}
A: Another thing I see is: You are trying to add a multi-dimensional JButton-Array at once to the JPanel. I think this will not work (please correct me if i am wrong). You have to do this Button by Button:
JButton[][] board = playerOne.getBoard();
for(int i=0;i<rowSize;i++){
for(int j=0;j<columnSize;j++){
playerOnePanel.add(board[i][j]);
}
}
Notice: Obviously you have to get somehow the row size and column size and declare as a variable as here as rowSize and columnSize. | unknown | |
d15947 | val | Here is a recursive function that passes the parent by reference until it finds a leaf and updates totals working backward.
function completionTree(&$elem, &$parent=NULL) {
// Handle arrays that are used only as a container... if we have children but no uuid, simply descend.
if (is_array($elem) && !isset($elem['uuid'])) {
foreach($elem AS &$child) {
completionTree($child, $elem);
}
}
// This array has children. Iterate recursively for each child.
if (!empty($elem['children'])) {
foreach ($elem['children'] AS &$child) {
completionTree($child, $elem);
}
}
// After recursion to handle children, pass completion percentages up to parent object
// If this is the top level, nothing needs to be done (but suppress that error)
if (@$parent['completed'] !== NULL) {
// Completion must be multiplied by the fraction of children it represents so we always add up to 100. Since values are coming in as strings, cast as float to be safe.
$parent['completed'] = floatval($parent['completed']) + (floatval($elem['completed']) * (1/count($parent['children'])));
}
}
// Data set defined statically for demonstration purposes
$tree = array(array (
'uuid' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'title' => 'stackoverflow',
'completed' => '0',
'parent' => NULL,
'children' =>
array (
0 =>
array (
'uuid' => '72ce49a6-76e5-495e-a3f8-0f13d955a3b5',
'title' => 'task2',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
),
1 =>
array (
'uuid' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
'title' => 'task1',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'children' =>
array (
0 =>
array (
'uuid' => 'ac5e9d37-8f14-4169-bcf2-e7b333c5faea',
'title' => 'subtask2',
'completed' => '0',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
1 =>
array (
'uuid' => 'f74b801f-c9f1-40df-b491-b0a274ffd301',
'title' => 'subtask1',
'completed' => '100',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
),
),
),
),
);
// Launch recursive calculations
completionTree($tree);
// Dump resulting tree
var_dump($tree);
A: Though this is answered, I'd like to leave a solution that seems a bit more intuitive (IMHO). Instead of passing down the parent, just handle the children first:
/**
* @param array $nodes
*
* @return array
*/
function calcCompletion(array $nodes): array {
// for each node in nodes
return array_map(function (array $node): array {
// if it has children
if (array_key_exists('children', $node) && is_array($node['children'])) {
// handle the children first
$node['children'] = calcCompletion($node['children']);
// update this node by *averaging* the children values
$node['completed'] = array_reduce($node['children'], function (float $acc, array $node): float {
return $acc + floatval($node['completed']);
}, 0.0) / count($node['children']);
}
return $node;
}, $nodes);
}
A: Well, this might be a little overhead, but you can use RecursiveArrayIterator. First, you must extend it to handle your tree structure:
class MyRecursiveTreeIterator extends RecursiveArrayIterator
{
public function hasChildren()
{
return isset($this->current()['children'])
&& is_array($this->current()['children']);
}
public function getChildren()
{
return new static($this->current()['children']);
}
}
Then using RecursiveIteratorIterator you can create an iterator which will process your tree starting from leaves:
$iterator = new RecursiveIteratorIterator(
new MyRecursiveTreeIterator($tasks),
RecursiveIteratorIterator::CHILD_FIRST
);
Then with this one, you can add your calculation logic:
$results = [];
$temp = [];
$depth = null;
foreach ($iterator as $node) {
if ($iterator->getDepth() === 0) {
// If there were no children use 'completion'
// else use children average
if (
is_null($depth)
|| !isset($temp[$depth])
|| !count($temp[$depth])
) {
$percentage = $node['completed'];
} else {
$percentage = array_sum($temp[$depth]) / count($temp[$depth]);
}
$results[$node['title']] = $percentage;
continue;
}
// Set empty array for current tree depth if needed.
if (!isset($temp[$iterator->getDepth()])) {
$temp[$iterator->getDepth()] = [];
}
// If we went up a tree, collect the average of children
// else push 'completion' for children of current depth.
if ($iterator->getDepth() < $depth) {
$percentage = array_sum($temp[$depth]) / count($temp[$depth]);
$temp[$depth] = [];
$temp[$iterator->getDepth()][] = $percentage;
} else {
$temp[$iterator->getDepth()][] = $node['completed'];
}
$depth = $iterator->getDepth();
}
Here is a demo. | unknown | |
d15948 | val | I don't believe so, but am hoping I am proved wrong.
A: To do what you want you need to extend the Visual Studio development environment by using an add-in. I don't know if the add-in you need already exists, but it is possible to write your own.
There is a list of popular add-ins here on Stack Overflow.
A: Try running cscript //X yourvbscript.vbs - it'll promt you for the debugging application. Select Visual Studio if have it installed.
Can do the same thing from VS but I don't remember at this moment ...
A: You can create a macro that runs your script, either by invoking cscript/wscript or by using the scripting COM-component. You can then add the macro to the context menu.
Another way is to add it as en external tool on the tool menu. | unknown | |
d15949 | val | return Uri.fromFile(getOutputMediaFile(type));
Null Pointer Exception occurring on this line, Because getOutputMediaFile(type) return null.
Because somehow Directory create failed and return null
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
} | unknown | |
d15950 | val | Per Wikipedia's definition of dangling else, you do have a dangling else statement.
C makes your code unambiguous. Your code is interpreted as:
if (n > 0)
{
if (n == 0)
{
printf("n is zero\n");
}
else
{
printf("n is negative\n");
}
}
Had you meant the code to be interpreted as:
if (n > 0)
{
if (n == 0)
{
printf("n is zero\n");
}
}
else
{
printf("n is negative\n");
}
you would be surprised.
FWIW, no matter which interpretation is used, your code is wrong.
What you need to have is:
if (n > 0)
{
printf("n is positive\n");
}
else
{
if (n == 0)
{
printf("n is zero\n");
}
else
{
printf("n is negative\n");
}
}
or
if (n > 0)
{
printf("n is positive\n");
}
else if (n == 0)
{
printf("n is zero\n");
}
else
{
printf("n is negative\n");
}
A: *
*if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); is ONE statement and
*I strongly recommend not even paying any attention into learning the concept of danglings elses (unless it will show up in tests) but instead learning the concept of ALWAYS using curly brackets, because it helps reading the code and it helps preventing bugs especially when inserting debugging statements.
So write:
if (n > 0) {
if (n == 0) {
printf("n is zero\n");
} else {
printf("n is negative\n");
}
}
or
if (n > 0) {
if (n == 0) {
printf("n is zero\n");
}
} else {
printf("n is negative\n");
}
and everything is clear to everyone.
BTW: Proper indentation - that might be broken due to copy&paste I admit - will help in reading code and preventing bugs, too.
A: +1 to @Bodo Thiesen's suggestion to always use curly braces. I suggest you also use clang-format to automatically format your code. It will it will ident everything correctly and generally make coding wonderful.
You can configure clang-format extensively to match your preferred style - this is your code clang-format'd in LLVM's house style.
#include <stdio.h>
void main(void) {
int n = 0;
printf("Enter value of N: ");
scanf("%d", &n);
if (n > 0)
if (n == 0)
printf("n is zero\n");
else
printf("n is negative\n");
getch();
} | unknown | |
d15951 | val | Your stub calls RSA.generate, so it depends on the RSA.generate implementation which involves FFI and loading a dynamically-loaded library on whatever platform you run tests on. Unless you're trying to test package:fastrsa itself, you should avoid calling things such as RSA.generate anyway; that is what you should be replacing with a stub.
The point of a Mock is to test how other code interacts with the mocked object. You cannot use a MockRSAKeysProvider to test the behavior of an RSAKeysProvider itself. If you want to test the behavior of your RSAKeysProvider class, you could change it to accept a stub for RSA.generate:
class RSAKeysProvider {
KeyPair? _keyPair;
KeyPair? get keyPair => _keyPair;
set setKeyPair(KeyPair keyPair) => _keyPair = keyPair;
Future<void> generate(String bits, {Future<KeyPair> Function(int)? generate}) async {
generate ??= RSA.generate;
var keyPair = await generate(int.parse(bits));
_keyPair = keyPair;
notifyListeners();
}
}
and then in your test:
Future<KeyPair> fakeGenerate(int bits) async {
return KeyPair('fakePublicKey', 'fakePrivateKey'); // Or use precomputed values.
}
test('Public and private key should not be null when generated', () async {
final RSAKeysProvider rsaKeys = RSAKeysProvider();
await rsaKeys.generate('2048', generate: fakeGenerate);
expect(rsaKeys.keyPair?.privateKey, isNotNull);
expect(rsaKeys.keyPair?.publicKey, isNotNull);
}); | unknown | |
d15952 | val | You need to add a check for the args itself to be non-null. The ANE is not appropriate for individual components, so you need to use more general AE, like this:
if (args == null)
throw new ArgumentNullException(“args”);
if (args.Property1 == null)
throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
throw new ArgumentException(“Property2 cannot be null.”, “args”);
A: In this case, it may be best to check for a null reference of the FooArgs parameter inside that method, and throw an ArgumentNullException if a null reference has been passed in. Then if other methods or sections of code use the parameters contained within the args class, they should be the ones to check this and throw exceptions as necessary. However, if your method that takes in the args class is the one to use all the arguments, then it would be better to check for valid parameters in that method, as you suggested.
Also, use ArgumentNullException only for arguments that are null references. If it's simply an invalid value (for example an empty string), then you should use the more generic ArgumentException.
A: This kind of depends on your tooling and how you feel about your tooling (resharper, fxcops and the like). Some static code analysis tools accept this:
throw new ArgumentNullException(“args.Property...”,"args");
and reject this
throw new ArgumentNullException(“args.Property...”,"args.Property");
So if you want to use the tooling, then assertions of null-hood against a parameter property must throw an ArgumentException
It's also valid to just make it up as you go along. What ever communicates the right message to the maintenance developer to help him pass the parameters correctly is the correct message.
A: While I agree completely with dasblinkenlight's answer, you may also want to consider moving the validation for FooArgs into the FooArgs class itself. If this class is designed specifically to move arguments around, it is likely not valid for it to have null proeprties, in which case, I would allow its constructor to do its validation. | unknown | |
d15953 | val | Ok well as seems often to be the case I've spent ages looking at this myself. Exhausted all the options, or so I thought. Just after I post this I think I'll just try this thing I've not had to do for any of the other formula just in case. Bingo!
So I had to add
cellFormula.CalculateCell = true;
And this seemed to solve the problem. Why I needed it I don't know as everything else seems to work without explicitly setting this flag but problem seems to be solved. | unknown | |
d15954 | val | No, as functions are not data. But you can define function pointers inside a struct.
struct foo {
int a;
void (*workwithit)(struct foo *);
}
A: No, you cannot have functions inside struct in a C program. I wrote a single code and saved that as a .c and a .cpp. The .cpp file complies and works as expected, but the .c file doesn't even compile.
Here is the code for your reference. Save it once as .cpp and then run it. Then save the same code as .c and compile it. You will get a compilation errors.
#include <stdio.h>
struct C {
void Test(int value) {
static int var = 0;
if (var == value)
printf("var == value\n");
else
printf("var != value\n");
var = value;
}
};
int main() {
C c1;
C c2;
c1.Test(100);
c2.Test(100);
int ii;
scanf("%d",&ii);
}
A: No.
You can have function pointers in structs, but that's as close as you'll get.
A: You can't really declare stuff inside of a struct in C. This is not C++ or any other OO language where an object encapsulates some kind of scope.
C structs are very simple objects, it's just syntactic sugar for managing a piece of memory. When you create new struct "instance", struct A a;, compiler just reserves stack space according to its size, and when you then do a.member, compiler knows that member's offset, so it jumps to &a + offset of that member. Those offsets are usually not just sums of sizes of preceding members, because compiler usually adds some padding bits into the structure to align it nicer into memory.
Hope it helped a bit. You obviously expect slightly too much from C stuctures :-)
A: I came to this post because I was looking for a way to teach a bit of Object Oriented "style" of programming in C for a very simple data structures course. I did not want to teach C++ because I did not want to keep explaining its more advanced features.
But I wanted to explore how one might implement the OO pattern used in Python but in a low-level language / run-time. By explaining what is going on in C, students might better understand the Python OO run-time patterns. So I went a bit beyond the first answer above and adapted some of the patterns from https://stackoverflow.com/a/12642862/1994792 but in a way that would elucidate OO run time patterns a bit.
First I made the "class" with a "constructor" in point.c:
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
int y;
void (*print)(const struct point*);
void (*del)(const struct point*);
};
void point_print(const struct point* self)
{
printf("x=%d\n", self->x);
printf("y=%d\n", self->y);
}
void point_del(const struct point* self) {
free((void *)self);
}
struct point * point_new(int x, int y) {
struct point *p = malloc(sizeof(*p));
p->x = x;
p->y = y;
p->print = point_print;
p->del = point_del;
return p;
}
Then I imported the class, constructed an object from the class, used the object, then destructed the object in main.c
#include "point.c"
int main(void)
{
struct point * p3 = point_new(4,5);
p3->print(p3);
p3->del(p3);
}
It feels very "Pythonic in C".
A: No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.
A: No, You cant define functions inside structures in C programs, However if the extension of your file is .cpp (that is not C), you can have member functions like classes however the default modifier of these functions will be 'public'(unlike class).
Read these links for more information on Structures a good link , another good link, One more good link
As a convention in C++, Classes are used for storing functions and variables both and Structures are used only for storing information (i.e. data).
A: No, but you can in c++ struct!
A: You can in C++ instead:
// Example program
#include <iostream>
#include <string>
struct Node
{
int data; Node *prev,*next;
Node(int x, Node* prev=NULL, Node* next=NULL)
{
this->data=x; this->prev=prev; this->next=next;
}
void print_list()
{
Node* temp=this; //temp is created in function call stack
while(temp!=NULL)
{
std::cout<<temp->data<<" ";
temp=temp->next;
}
}
Node* insert_left(int x)
{
Node* temp=new Node(x,this->prev,this);
this->prev=temp;
return temp; //list gets new head
}
Node* insert_right(int x)
{
Node* temp=new Node(x,this,this->next);
this->next=temp;
return this; //this would still be head
}
};
int main()
{
Node* head=new Node(-1); //-1
head=head->insert_left(0); //0 -1
head=head->insert_right(1); //0 1 -1
head=head->insert_left(2); //2 0 1 -1
head->print_list();
}
A: You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:
#include <stdio.h>
#include <stdlib.h>
struct unit
{
int result;
int (*add) (int x, int y);
};
int sumFunc(int x, int y) { return x + y; }
void *unitInit()
{
struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
ptr->add = &sumFunc;
return ptr;
}
int main(int argc, char **argv)
{
struct unit *U = unitInit();
U->result = U->add(5, 10);
printf("Result is %i\n", U->result);
free(U);
return 0;
}
Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST
Check header and then clist.c file. | unknown | |
d15955 | val | override getItemViewType(int position) and getViewTypeCount() method in your adapter and
inflate you view according to it from getView(). In you case write methods like
@Override
public int getItemViewType(int position) {
if(list.get(position).flag == text)
return 0;
else if(list.get(position).flag == image)
return 1;
else
return 2;
}
@Override
public int getViewTypeCount() {
return 3;
}
A: I am not pretty much sure but it's my concept that firstly create a layout for row that can hold every thing that you want show(image, video, text etc ). And make this layout such a way if one thing is not present then it automatically wrapped(means if video is not present then video space will not be there).
Now make json of every list row and pass it to Adapter of list. Then override getView() method of the
adapter and parse json there and display according to your layout.
A: i implemented similar Custom Adapter for ListView which is used in this link , also used ViewHolders
check this link
http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/ | unknown | |
d15956 | val | The problem is that you are selecting three fields with the same name. These fields are added to an array in the php code, but the array field is being overwritten twice because there can be no duplicate keys in an associative array. If you want to select the three names you will have to give them another name.
$charData = DB::table('characters')
->select('characters.*', 'charclasses.name as charclassname', 'charspecs.name as charspecname')
->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
->orderBy('user_id', 'ASC')
->get();
dd($charData); | unknown | |
d15957 | val | If you have a definition like e.g.
void init() { ... /* some code */ ... }
Then to inhibit name mangling you need to declare it as extern "C":
extern "C" void init() { ... /* some code */ ... }
If you have a declaration in a header file that you want to include in a C source file you need to check if you're including the header file in a C or C++ source file, using the __cplusplus macro:
#ifdef __cplusplus
extern "C"
#endif
void init(void);
Note that the function in the header file has to be declared with void in the argument list, if it doesn't take any arguments. That's because the declaration void init() means something else in C. | unknown | |
d15958 | val | It looks like getEmails actually returns an ES6 Set object, not an array:
Get first email:
// Option 1 (ugly but efficient)
let first = getEmails(text).values().next().value
// Option 2 (pretty but inefficient)
first = [...getEmails(text)][0]
console.log(first)
Iterate over all emails:
for (let email of getEmails(text)) {
console.log(email)
}
A: The README is misleading. The code returns an array of email addresses, so you can just access it by index:
var firstAddress = getEmails(text)[0];
edit — I'm wrong; the comment really is accurate, because it returns a Set instance! I'll leave this here and accept my downvotes in penance.
A: You can loop through all the values in the object via this:
var emails = getEmails();
for (email in emails) {
console.log(emails[email])
} | unknown | |
d15959 | val | Try using a deque. It's part of the Python collections, and it uses a doubly-linked list internally.
from collections import deque
i = 2
feature_vector_set = deque()
while i < 2405 - 2:
j = 2
while j < 1200 - 2:
block = diff_image[i-2:i+3, j-2:j+3]
feature = block.flatten()
feature_vector_set.append(feature)
j = j+1
i = I+1
feature_vector_list = list(feature_vector_set)
You can find the time complexities of common operations on Python data types here.
Deque documentation | unknown | |
d15960 | val | Get with g or G
Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.
That is, instead of swapping the current contents of the hold and pattern space (current line, etc) you can take the pattern space and copy it into the hold space (either replacing or appending to the hold space in the process).
Those two sed commands are among the idiomatic sed one-liners that you can find online and they do the same thing only for certain files (those without blank lines in them).
# double space a file
sed G
# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
sed '/^$/d;G'
A: According to the man sed:
*
*g
Replace the contents of the pattern space with the contents of the hold space.
*G
Append a newline to the contents of the pattern space, and then
append the contents of the hold space to that of the pattern space. | unknown | |
d15961 | val | Depends on how you did it. Pyinstaller is a common one that allows you to do that. | unknown | |
d15962 | val | It can't seem to uninstall the previous version of your app. Just go ahead and uninstall it manually this time. It should work afterwards.
A: If I am understanding correctly, you are attempting to emulate your app on one of the Studio's built in emulators. I believe the problem is your APK is either corrupted, a Gradle Build Error occurred, or the APK and the API of your emulator are two different versions.
I would suggest backing up your project, and then reinstall a newer version of the project. | unknown | |
d15963 | val | Create function which reloads controller and attach that function to view
$scope.reloadController = function ({
$state.go($state.current, {}, { reload: true });
})
And atach it to link:
<a ng-click="reload()">Contacts</button>
A: If the link is to the current page it's actually smart that it doesn't reload. Try using a JavaScript function e.g. reload
http://www.w3schools.com/jsref/met_loc_reload.asp | unknown | |
d15964 | val | Use vertical-align: top; on .div_game_thumb
Inline elements obey to vertical alignment.
Also, if you want cross-browser inline-blocks (IE7+) you need to define it like this:
display: inline-block;
*zoom: 1;
*display: inline;
*Note: The order is important.
A: vertical-align: top saves the day! Put it on .div_game_thumb.
You can restore the little bit of margin that disappears after doing this by adding margin: 2px 0; as well. | unknown | |
d15965 | val | It is quite simple like this.
Iterate then -> following the property name
@foreach($comment as $row)
<li>{{ $row->id }}</li>
<li>{{ $row->post_id}}</li>
//AND SO ON
@endforeach | unknown | |
d15966 | val | The problem is that Swift doesn't have pointers in the C sense. Well, it does, sort of, but it's not worth invoking them just to do what you're trying to do. The simplest approach is to rewrite the core of your method to call a function that takes an inout parameter.
So let's take the reduction you ask about in your last three lines:
CGPoint* startPoint = NULL;
startPoint = &startPoint1;
*startPoint = endPoint;
To do that, we need a general way to set one CGPoint to another by indirection, expressed as a func (because that is the only way to work with an inout parameter). To make it truly general, we may as well make this a generic, so we're not confined to CGPoint alone:
func setByIndirection<T>(_ thing1 : inout T, to thing2: T) {
thing1 = thing2
}
And now we can test it, doing exactly what you asked to do:
var startPoint = CGPoint.zero
let endPoint = CGPoint(x:5, y:5)
setByIndirection(&startPoint, to: endPoint)
print(startPoint) // 5,5
So you see, the use of the inout parameter has allowed us to pass into the function a "pointer" to the CGPoint whose value is to be set, which is what your code is trying to accomplish at its heart.
If you're willing to "damage" your original endPoint, you don't even need to write setByIndirection; you can use the built-in swap:
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:5, y:5)
swap(&startPoint, &endPoint)
A: In swift, I would use enums and an array. I simplified the code a litte, but I guess you'll get it:
var points = [CGPoint(), CGPoint()]
enum indexEnum:Int {
case startPoint = 0
case endPoint = 1
}
func method() {
var inx:indexEnum
if (1==1) {
inx = .startPoint
} else {
inx = .endPoint
}
if (2==2) {
points[inx.rawValue] = CGPoint(x:10,y:10)
} else {
points[inx.rawValue] = CGPoint(x:20,y:20)
}
} | unknown | |
d15967 | val | See creating a bat file for python script to understand how to launch your script with a .bat file, then launch that via windows scheduler rather than launching the python script directly. | unknown | |
d15968 | val | This transformation:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match=
"toctitle
[. is (ancestor::tocline[@toclevel eq '2'][1]//toctitle)[last()]]">
<toctitle last="true">
<xsl:apply-templates select="@*|node()"/>
</toctitle>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<tocline id="d1e11" toclevel="1">
<toctitle>Section 1. Legislative Powers</toctitle>
<tocline id="d1e40" toclevel="2">
<toctitle>Separation of Powers and Checks and Balances</toctitle>
<tocline id="d1e51" toclevel="3">
<toctitle>The Theory Elaborated and Implemented</toctitle>
</tocline>
<tocline id="d1e189" toclevel="3">
<toctitle>Judicial Enforcement</toctitle>
</tocline>
</tocline>
</tocline>
produces the wanted, correct result:
<tocline id="d1e11" toclevel="1">
<toctitle>Section 1. Legislative Powers</toctitle>
<tocline id="d1e40" toclevel="2">
<toctitle>Separation of Powers and Checks and Balances</toctitle>
<tocline id="d1e51" toclevel="3">
<toctitle>The Theory Elaborated and Implemented</toctitle>
</tocline>
<tocline id="d1e189" toclevel="3">
<toctitle last="true">Judicial Enforcement</toctitle>
</tocline>
</tocline>
</tocline>
A: I added a key, and here's what I came up with:
<xsl:key name="l2id" match="tocline[@toclevel eq '2']" use="@id"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="toctitle[. is (ancestor-or-self::tocline/key('l2id',@id)/descendant-or-self::toctitle[last()])]">
<xsl:copy>
<xsl:attribute name="last">
<xsl:value-of select="'true'"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template> | unknown | |
d15969 | val | I'm not sure if this is some sort of bug or memory leak, but the fact is that this is an extremely memory-inefficient way to store data.
As such, I've edited the code to use 3 dimensional arrays with separate dictionaries to associate the indices of arrays with text strings, which is working great.
I was able to store 8 different 3D arrays (150k by 8 by 13) and 7 different 2D arrays (150k 13), both of doubles. Overhead doesn't seem to be too high. Given a size of 8 bytes per double, theoretical memory usage is 1.11GB, which isn't too bad. | unknown | |
d15970 | val | A gdb script might be a solution for your problem.
Create a script that puts break point to each possibly called function.
At break prints the stack with 'bt' and continue the execution.
You should put an other break point to main.cpp:500 to quit from debugging.
b 'main.cpp::500'
commands 1
detach
quit
end
break 'A::f1()'
break 'A::f2()'
while true
continue
bt
end
You can start the script like this:
gdb --command ./gdbscript.gdb fpmanager
If you have too much possibly called function you can grep the code to find all. | unknown | |
d15971 | val | You want to use Promise:
val promise = Promise[Boolean]()
...
override def onNext() = {
...
promise.tryComplete(Success(true))
}
override def onError(e: Throwable) =
promise.tryComplete(Failure(e))
val future = promise.future
You should do something to handle the case when there are no result (as it is now, the future will never be satisfied ... | unknown | |
d15972 | val | try {if (condition) {...}} catch(SomeEx ex) {}
Here you handled the exception if it is arised condition of if also if arised inside if-block.
if (condition) {try {...} catch(SomeEx ex) {}}
Here you handle exception if is arised only inside the if-block. If something goes wrong in if condition then it will not be handled.
So it is depends upon the actual senario.
A: Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation.
In the JVM spec, you see that there is no extra byte code generated on the execution path:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12
A: From the perfomance point of view it should be the same. Throwing of the exception is a costly operation (for starters, the stacktrace must be created and populated). The mere existence of the try block has no (or negligible) performance penalty.
See Should java try blocks be scoped as tightly as possible.
What actually JVM do when I enter try block ?
From JLS 14.20.1. Execution of try-catch:
A try statement without a finally block is executed by first executing the try block. Then there is a choice:
*
*If execution of the try block completes normally, then no further action is taken and the try statement completes normally.
*If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
*
*If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:
*
*If that block completes normally, then the try statement completes normally.
*If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
*If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.
*If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason.
EDIT:
For a complete Exception description see the JVM 2.10 link in The New Idiot's answer.
A: if (condition) {
try {
//something
} catch(SomeEx ex) {}
}
is better to use since it executes the try block if the condition is ok.JVM compiles the try block and validated the catch block or a finally block. I think advantage is not in the compile time but in the run time. Compile time I think no advantage at all
A: Exceptions should be exceptional case , not every time the code runs. So better to check for the condition before trying !
if (condition) {
try {
//something
} catch(SomeEx ex) {}
}
Make sure , if (condition) itself doesn't throws an Exception.
It depends on your usage and functionality . For example this would be better :
if (someObject!=null) {
try {
someObject.getSomething(); // getSomething() potentially throws some Exception
} catch(SomeEx ex) {}
}
What actually JVM do when I enter try block ?
Read JVM spec 2.10.
A: If you see oracle docs
>try {
code
}
catch and finally blocks . . .
The segment in the example labeled code contains one or more legal lines of code that could throw an exception.
So,If you feel doubt on your If condition that it will throw an exception put it inside.Otherwise put outside. | unknown | |
d15973 | val | I don't have an answer on why compiler isn't picking the expected overload in this situation.
I would recommend clarifying the overload you wish to use at call site, like following.
fileprivate extension Dictionary {
subscript(safe key: Key, defaultValue: Value = .empty) -> Value where Key == MyEnum, Value == MyStruct {
get { return self[key, default: defaultValue] }
set { self[key] = newValue }
}
}
With above, you can tell compiler explicitly to use your preferred overload.
func myMethod(type: MyEnum) {
let one: MyStruct = data[safe: type]
let two: MyStruct = data[safe: currentSelectedType]
let three: MyStruct = data[safe: allTypes[index]]
let four: MyStruct = data[safe: .one]
} | unknown | |
d15974 | val | First :
index.android.js or index.ios.js
import React, { Component } from 'react';
import { AppRegistry, Navigator } from 'react-native';
import Index from './app/Index';
import CreateMessage from './app/CreateMessage';
import EnableNotification from './app/EnableNotification';
render() {
return (
<Navigator
initialRoute={{screen: 'Index'}}
renderScene={(route, nav) => {return this.renderScene(route, nav)}}
/>
)
}
renderScene(route,nav) {
switch (route.screen) {
case "Index":
return <Index navigator={nav} />
case "EnableNotification":
return <EnableNotification navigator={nav} />
case "CreateMessage":
return <CreateMessage navigator={nav} />
}
}
After that :
index.js
goEnableNotification() {
this.props.navigator.push({ screen: 'EnableNotification' });
}
Finally :
EnableNotification.js
goCreateMessage() {
this.props.navigator.push({ screen: 'CreateMessage' });
}
If you want to go back, do a function goBack :
goBack() {
this.props.navigator.pop();
}
I hope this will help you !
A: This worked for me - CreateMessage component needs to be part of the navigation stack in order to navigate there through this.props.navigator.navigate(<name>) | unknown | |
d15975 | val | A good function should always be free from side-effects. It should be pure and just do one specific job at a time. As a software programmer/developer, we must write source code that actually produce the output based on input. Such kind of strong pure function actually avoid all kind of side effects and code smell. Let's look at few examples to understand this.
Assume we have a function named as Greeting like below
function Greeting(name) {
return `Hello ${name}`;
}
It is pure because you will always get the output Hello {name} for the name passed via parameter. Let's have a look at another version of same function with many side-effects.
var greeting = "Hey";
function Greeting(name) {
return `${greeting} ${name}`;
}
Now, this function is not pure. Guess why ? Because we are not sure what output we will receive because function is actually dependent on the outer variable named as greeting . So if someone change the value of variable greeting to something else let's say Hello then obviously the output of function will change. So the function is now tightly coupled with the outer variable. That's why it is not pure function anymore.
So to conclude, you must have to write your function in such a way that there is no dependency and no side-effect and it will always do one job.
That is the best practice :)
Happy Coding :)
A: I believe the second Function "FindAveragePricePerDay" calling can be adjusted to act on single day, so that it can be reused on other places
const avgPrices = sortedDays.map(day => FindAveragePricePerDay(day));
/* you can also simplify the FindAveragePricePerDay using the reduce method
following this parameters array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
so all the second line would be */
const avgPrices = day.reduce((t,c,i,arr) => t + c/arr.length, 0);
for more info about array.reduce check this | unknown | |
d15976 | val | (bash) This will find all folders in or beneath current directory with an underscore in the name and rename them as you mention:
for d in $(find . -name '*_*' -type d) ; do
new=$(echo $d | sed -e 's/_/ /g')
mv $d $new
done
A: you could try something like
#> ls -l | grep '^d' | awk '{oldname = $9 ; gsub(/_/, " " ,$9); print "mv " oldname " " $9 }' > temp.script
#> chmod 744 temp.script
#> ./temp.script
Test it first of course :)
A: Does your system have a rename command that does what you need? On some systems, it exists and can use some species of regular expression to make the changes. I use a version which uses Perl regular expressions (a Perl script, in other words):
find . -type f -name '*_*' -print0 | xargs -0 rename 's/_+/ /g'
On the other hand, the standard version on Linux tends to be rather feeble by comparison (and wouldn't do what you need).
Note that if you want to rename directories too, then do them before renaming any files, or after renaming all the files. Doing them mixed up will mean that your renaming runs into problems with accessing file names that were in one directory but the directory has been renamed since the file name was generated. Even using -depth as an option to find is not guaranteed to be safe. | unknown | |
d15977 | val | from matplotlib import pyplot as plt
plt.figure(figsize=(15,20))
try this | unknown | |
d15978 | val | Change the following code in your settings.json:
"workbench.editorAssociations": {
"*.ipynb": "jupyter.notebook.ipynb"
}, | unknown | |
d15979 | val | If you allow the author to not be set then you need to make sure it has been set before you try to use it.
Be a little defensive like this;
class Message(models.Model):
author = models.ForeignKey(User, null=True, related_name='author_messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
if not self.author:
return "Anonymous"
return self.author.username
def last_10_messages():
return Message.objects.order_by('-timestamp').all()[:10]
def message_to_json(self, message):
if message.author:
author = message.author.username
else:
author = "Anonymous"
return {
'id': message.id,
'author': author,
'content': message.content,
'timestamp': str(message.timestamp)
}
A: It seems that you have more the one message even if you said you did not create any. At least you must have created one with the username aysha. The message with the id=1 seems to have no user attached ... so you get the error when trying to access message.author.username.
To add the if not self.author in the __str__ of Message does not change anything as you access or print message.author.username and not message. It would help if you print(message) and message has no author. | unknown | |
d15980 | val | Please follow the APIs available at the https://learn.microsoft.com/en-us/rest/api/azureml/
for Azure ML studio through REST API calls, but other than dataset-related API. | unknown | |
d15981 | val | Change the type of children to a function that returns a React element:
type Props = {
children: (ctx: { hello: string }) => ReactElement;
};
Now when you use the component you get the right types:
{({ hello }) => <div>{hello}</div>} // 'hello' is a string
Try this out here. | unknown | |
d15982 | val | Whenever I add the junction rows (additional courses) by only using the foreign keys, it doesn't fill in the course property as expected after saving. It does fill in the Student property however.
By design, EF Core does not automatically load navigation properties. The only exceptions are when lazy loading is enabled and the navigation property getter is called, navigations to owned entities (or in EF Core 5.0+, navigations configured as AutoInclude) only when querying, or (which is the case with your Student property) the referenced object is already loaded (tracked) in the context. The later is called navigation property fixup, and can happen both during the query materialization or later.
Since you are not using lazy loading, the only guaranteed way to get navigation properties populated is to eager/explicit load them after.
For more info, see Loading Related Data section of the EF Core documentation. | unknown | |
d15983 | val | For mass inserts with very large scripts that are out of order, you can disable referential integrity checks with:
SET DATABASE REFERENTIAL INTEGRITY FALSE
see http://hsqldb.org/doc/2.0/guide/management-chapt.html#mtc_sql_settings on how to check for possible violations after the insert. | unknown | |
d15984 | val | What you actually mean by "a screen"? If you're talking about a pop-up dialog box or page by jQuery Mobile you can probably serialize the form with jQuery and assign it to a JavaSCript variable.
But if you're changing your "screen" by changing UIView to a different url you can use either:
*
*File API to store serialized form in a file and load it on the 2nd "screen"
*Storage API to ... actually do the same
I'd go for number one, as it's easier to implement than using SQL and writing loads of additional code.
Search for:
*
*jQuery.serialize()
*PhoneGap File API | unknown | |
d15985 | val | You just need to restart Apache (httpd) to make the configuration changes take effect. Restarting your computer does that, but you can also run in Terminal:
sudo apachectl restart
A: I solved it. If you face this problem, and you sure about that you did everything right, just restart the computer. | unknown | |
d15986 | val | In your createUser function that is executed on the post request you are doing two things. First you check whether a user with the provided email exists and, second, you create a user. However, those functions are not executed consecutively, instead they are running simultaneously and thus create a race condition.
So going off on your example, if the email check query SELECT email FROM registration WHERE email = ? is faster and the user already exists, it will respond with:
return res.status(400).json({
message: 'User already taken'
})
but the createUser function (below) is still running and once it is finished, it will try to also send a response. Therefore, you are presented with an application crash in the console even though in the postman you can see the response stating that the user already exists.
In order to fix this error you should execute the createUser function only if the results.length is 0 inside the callback provided to the email check query, like so:
createUser: (req, res) => {
const body = req.body;
const salt = genSaltSync(10);
pool.query('SELECT email FROM registration WHERE email = ?', [body.email], (error, results) =>{
if(error){
console.log(error);
}
if(results.length > 0){
return res.status(400).json({
message: 'User already taken'
})
}
createUser(body, (err, results) => {
if(err){
console.log(err);
return res.status(500).json({
success:0,
message:"Error in database connection"
});
}
return res.status(200).json({
success: 1,
message: `User ${results.insertId} signed up successfully`,
data: results
});
});
})
}
Now you execute the createUser function only if a user with the provided email doesn't exist, which effectively removes the race condition between the two functions. | unknown | |
d15987 | val | Nothing you described struck me as anything out of the ordinary. You could easily end up in this situation if, for example, others had made some commits to master since the last time dev had synched with that branch.
The two typical ways to resolve this are merging and rebasing. Let's consider merging, because it is probably the strategy you are already using, and it is more succinct to describe. You could resolve this situation by first merging master into your dev branch. Then, open a pull request back into master from dev, if one does not already remain open. Have your reviewers sign off on it, and then the pull request should go through.
The key step here is merging master into your dev branch. After this operation, Git should not longer be telling you that dev is behind master.
A side note: Technically speaking, master itself was also behind dev. Actually, both branches were mutually behind the other party, because each has new commits since the last time they both synched. | unknown | |
d15988 | val | Outlook Contacts are structured a little differently than Google Contacts. Rather than having a single gd:phoneNumber property with distinct rel values, Outlook uses distinct phone number properties.
It's also important to keep in mind that some phone number properties are collections rather than single values (i.e. homePhones). These collections are ordered so these collections can be maps back to Outlook's UI pretty easily. For example, homePhones[0] holds the "Home Phone" value while homePhones[1] holes "Home Phone 2".
In terms of a 1:1 mapping:
*
*http://schemas.google.com/g/2005#home == homePhones[0]
*http://schemas.google.com/g/2005#work == businessPhones[0]
*http://schemas.google.com/g/2005#mobile == mobilePhone
Finally, Microsoft Graph only returns a limited set of phone numbers by default. In my experience, the set returned by Graph is almost always sufficient but there are certainly some edge cases (the healthcare sector still makes use of pagers for example).
You can access these additional phone numbers using Extended Properties. This is done by requesting specifically requesting a given property using the MAPI tag name.
For example, if you need to retrieve the Pager property, you can request the MAPI identifier 0x3A21 as an extended property:
/v1.0/me/contacts?$expand=singleValueExtendedProperties($filter=id eq 'String 0x3A21')
You can find the complete list of MAPI properties here.
A: "homePhones": [],
"mobilePhone": "124124124124",
"businessPhones": [
"+86 (510) 12114142"
],
"spouseName": null,
"personalNotes": "",
"children": [],
"emailAddresses": [
{
"name": "Charles Test([email protected])",
"address": "[email protected]"
}
],
"homeAddress": {},
"businessAddress": {
"city": "Wuxi"
},
"otherAddress": {}
As you know, the phone reference is not unique, user can share same phone number, so it cannot be used as uniquely identify in all MS Authentication API, unless the phone reference is user's id. So it is not possible for your perfect world.
For the same reason, user can share the same address reference, so it is cannot be used as uniquely identify in all MS Authentication API. So it is not possible for your perfect world too. | unknown | |
d15989 | val | Modern hardware is very likely to implement "Early z-test", i.e. performing depth test before fragment (pixel) shader is run. Alternatively, it is implementable by hand.
So, it is likely more beneficial to sort by state, unless you have transparency issues. In the latter case you may want to look into "Order-independent transparency".
In any case, trust no one. Measure (profile) and compare before optimizing anything. | unknown | |
d15990 | val | In ListCompare::operator() you need to take the parameters as const references.
class ListCompare
{
public:
bool operator()(const Node& pNode1, const Node& pNode2) const
{
return pNode1.getTotalCost() > pNode2.getTotalCost();
}
}; | unknown | |
d15991 | val | To display buttons besides input field, you need to wrap input and button in .input-group class, like this:
<div class="col-md-2 columns">
<div class="input-group">
<label>Time:</label>
<input id="timepicker1" type="text" >
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
</div>
Icons are missing, because glyphicons were removed form Bootstrap 4, so you'll need to load them separately. | unknown | |
d15992 | val | From Apple documentation:
Background sessions are similar to default sessions, except that a separate process handles all data transfers.
Apple simply doesn't provide a way to inject your NSURLProtocol subclass into another process, managed by iOS itself.
Same restriction applies to WKWebView. | unknown | |
d15993 | val | First I will generate random data to test this
# generate random data
test_data <- data.frame(x = 1:100, y = rnorm(100))
# add random NAs
test_data$y[sample(1:100, 50)] <- NA
Now try this:
# locate non NAs in the wanted column
not_na <- which(!is.na(test_data$y))
# define the function replace_NAs_custom
replace_NAs_custom <- function(i, col){
if(is.na(col[i])){
col[i] <- col[max(not_na[not_na < i] )]
}
return(col[i] )
}
test_data$y_2 <- unlist(lapply(1:nrow(test_data), replace_NAs_custom, test_data$y))
A: It looks like your code is doing a lot of calculating and memory allocation every time it loops. To decrease time we want to decrease how much work the loop does each iteration.
I'm not 100% clear on your problem, but I think I've got the gist of it. It sounds like you just want to take the last non-NA value and copy it into the row with the NA value. We can use a pair or indexes to do this.
In the following method all of the memory is already pre-allocated before I enter the loop. The only memory action is to replace a value (NA) with another value. Other then that operation there is a check to see if the value is NA and there is an addition operation on the index. In order to get significantly faster on this problem you would need to use c-optimized vector functions (probably from a package/library).
To use the previous value to fill NA:
# Fill with previous non-NA value
VERINDEX_VEC <- c(NA,"A1","A2",NA,NA,"A3",NA)
VERINDEX_VEC
# [1] NA "A1" "A2" NA NA "A3" NA
non_na_positions <- which(!is.na(VERINDEX_VEC))
# If the first value is NA we need to fill with NA until we hit a known value...
if(is.na(VERINDEX_VEC[1])){
non_na_positions <- c(NA,non_na_positions)
}
index = 1
for(i in 1:length(VERINDEX_VEC)){
if(is.na(VERINDEX_VEC[i])) {
VERINDEX_VEC[i] <- VERINDEX_VEC[non_na_positions[index]]
} else {
index <- index + 1
}
}
VERINDEX_VEC
# [1] NA "A1" "A2" "A2" "A2" "A3" "A3"
To use the next value to fill NA:
# Fill with next non-NA Value
VERINDEX_VEC <- c(NA,"A1","A2",NA,NA,"A3",NA)
VERINDEX_VEC
# [1] NA "A1" "A2" NA NA "A3" NA
non_na_positions <- which(!is.na(VERINDEX_VEC))
# Never need the first position of the vector if we are looking-ahead...
index <- ifelse(non_na_positions[1]==1,2,1)
for(i in 1:length(VERINDEX_VEC)){
if(is.na(VERINDEX_VEC[i])) {
VERINDEX_VEC[i] <- VERINDEX_VEC[non_na_positions[index]]
} else {
index <- index + 1
}
}
VERINDEX_VEC
# [1] "A1" "A1" "A2" "A3" "A3" "A3" NA
A: I believe I may have found a faster way, at least a lot faster than my last answer, however I couldn't compare it with your code, since I couldn't reproduce the output.
(see below for the Benchmarking results)
Can you try this:
set.seed(223)
# generate random data
test_data <- data.frame(x = 1:1000, y = rnorm(1000))
# add random NAs
test_data$y[sample(1:1000, 500)] <- NA
# which records are filled
not_na <- which(!is.na(test_data$y))
# calculate the distance from the previous filled value
# this is to identify how many times should each value be repeated
dist <- unlist(lapply(1:(length(not_na) - 1),
function(i){
not_na[i+1] - not_na[i]
}))
# compine both to create a kind of "look-up table"
not_na <- data.frame(idx = not_na,
rep_num = c(dist, nrow(test_data) - not_na[length(not_na)] + 1))
test_data$y_3 <- unlist(lapply(1:nrow(not_na),
function(x){
rep(test_data[not_na$idx[x], "y"], times = not_na$rep_num[x])
}))
The Benchmarking :
f1() is the last answer
f2() is this answer
*
*For 100.000 rows in test_data
# microbenchmark(f1(), times = 10)
# Unit: seconds
# expr min lq mean median uq max neval
# f1() 39.54495 39.72853 40.38092 40.7027 40.76339 41.29006 10
# microbenchmark(f2(), times = 10)
# Unit: seconds
# expr min lq mean median uq max neval
# f2() 1.578852 1.610565 1.666488 1.645821 1.736301 1.755673 10
*For 1.000.000 rows the new approach needed about 16 seconds
# microbenchmark(f2(), times = 1)
# Unit: seconds
# expr min lq mean median uq max neval
# f2() 16.33777 16.33777 16.33777 16.33777 16.33777 16.33777 1 | unknown | |
d15994 | val | Issue is coz of this line :
[(ngModel)]='basicinfo.website'
Either change this to
[ngModel]='basicinfo?.website'
or
Provide initial value before ngModel initialisation for 2 way binding
basicinfo = { 'website' : '' };
[(ngModel)]='basicinfo.website' | unknown | |
d15995 | val | As you are doing it at MainThread the app will not response to user and it's the worst thing can happen! I suggest you to use RXJava and be aware of blocking UI Thread!
Observable.just(comment)
.delay(3, TimeUnit.SECONDS)
/*for doing at background*/
.subscribeOn(Schedulers.io())
/*for responsing at maint thread*/
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
comment = "";
// and other stuffs you wand after resetting the val
}
});
A: A good approach(based on you having a thread already) would be this:
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>3000) {
//reset your variable
//Allow this to repeat:
startTime = System.nanoTime();
}
In order to initialize, do startTime = System.nanoTime(); where you would initialize the activity.
Now this method has a big drawback: You have to use it with a thread. It cannot be used alone as a listener if you want it to update after 3 seconds and not after 3 seconds on a button press.
Using a thread is a good idea if you want something done repeatedly, but beware of background memory hogging. You may want to create an async thread
A: A better approach would be to use handlers and postDelayed instead of Thread.sleep().
postDelayed puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper.
Thread.sleep() blocks the thread.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do stuff every 3000 ms
handler.postDelayed(this, 3000);
}
}, 1500); | unknown | |
d15996 | val | Latex doesn't use a white space character to separate words. That's the problem. | unknown | |
d15997 | val | You can use index, which returns the first index value if it exists and if not raises a ValueError, and a try-except clause to handle the error:
l = [7,13,6,1]
x = 5
try:
print(l.index(x))
except ValueError:
print(-1)
A: the else clause will happen on each run through the loop, if you unindent it to be on the for loop instead it will only run if the for loop does not break, and if you do find one that matches then you should break out so that it only shows the first occurence:
for i,j in enumerate(list):
if j==x:
print(i)
break
else:
print(-1) | unknown | |
d15998 | val | Something like this I believe you looking for
<a href="#" class="hover:before:scale-x-100 hover:before:origin-left relative before:w-full before:h-1 before:origin-right before:transition-transform before:duration-300 before:scale-x-0 before:bg-red-500 before:absolute before:left-0 before:bottom-0 ">
Hover me
</a>
The trick here is to change CSS transform-origin direction on hover
before:origin-right hover:before:origin-left
A: use this as your base and add your styles to it
this one goes to left
<button class="relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-left after:h-[2px] after:bg-black">Hover Me</button>
and this one to right
<button class="relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-right after:h-[2px] after:bg-black">Hover Me</button>
chnage origin-[direction] to whatever direction you want | unknown | |
d15999 | val | You can use Mockito
@RunWith(MockitoJUnitRunner.class)
class ProductImplTest {
@Mock DataService dService;
@InjectMocks ProductImpl sut;
@Test
public void test() {
ResponseObject ro = new ResponseObject();
String string = "string";
Long longVal = Long.valueOf(123);
sut.parse("string", longVal);
verify(dService).getResponseObject();
assertThat(ro.getId()).isEqualTo("string");
// you should use setters (ie setId()), then you can mock the ResponseObject and use
// verify(ro).setId("string");
}
}
EDIT:
With ResponseObject being an abstract class or preferably an interface, you'd have
interface ResponseObject {
void setId(String id);
String getId();
// same for code
}
and in your test
@Test public void test() {
ResponseObject ro = mock(ResponseObject.class);
// ... same as above, but
verify(dService).getResponseObject();
verify(ro).setId("string"); // no need to test getId for a mock
}
A: Try with constructor injection:
class ProductImpl{
DataServices ds;
@Inject
public ProductImpl(DataServices ds) {
this.ds = ds;
}
} | unknown | |
d16000 | val | please check if this is what you want:
(I have to manually input the genres so I only put 3 lines there)
Genres Drama Sci-Fi Romance Horror
793754 Drama|Sci-Fi True True False False
974374 Drama|Romance True False True False
950027 Horror|Sci-Fi False True False True
the code is :
import pandas as pd
df = pd.DataFrame( {
'Genres' : ['Drama|Sci-Fi', 'Drama|Romance' , 'Horror|Sci-Fi']
},
index = [793754, 974374, 950027] ,
)
genre_movies=list(df.Genres.unique())
genre_movies2 = [words for segments in genre_movies for words in segments.split('|')]
# get a list of unique genres
for genre in genre_movies2:
df[genre] = df.Genres.str.contains(genre, regex=False)
method 2 suggested by @Ins_hunter
use .get_dummies() method
df2 = df.Genres.str.get_dummies(sep='|')
Action Adventure Animation Children's Comedy Crime Documentary Drama Fantasy Film-Noir Horror Musical Mystery Romance Sci-Fi Thriller War Western
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
1 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0
3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
4 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
1000204 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
1000205 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0
1000206 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0
1000207 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
1000208 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0
1000209 rows × 18 columns
and it can be merged back to the original data
df3 = pd.concat([df, df2], axis=1) | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.