_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d401 | train | Your parameter is only set to 5
$('#form').validate({
rules: {
image: {
....
filesize: 5, ...
That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB. Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.
Try 5242880 if you want to allow files under 5 MB.
filesize: 5242880 // <- 5 MB
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5242880 // <- 5 MB
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
A: Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly.
For example if you want to check if the file size is less than 5MB, you should use
image: {
extension: "jpg,jpeg,png",
filesize: 5*1024*1024,
} | unknown | |
d402 | train | well...i got this answer after loooong research so thank you all who replied to my questions
ok
to externalize the ajax template
1st create a partial view (.ascx)
and cut paste the template[ie- .....]
now on your main page there is only an empty div
now add this script to it calling it onclick[button,link]
<script type="text/javascript">
function calltemp2() {
debugger;
$.get("/Templates/SelectTemp2", function(result) {
alert(result);
$("#Renderthisdiv").html(result);
});
}
</script>
create another empty div having id Renderthisdiv
imp!!
give j query reference
and lastly cut-paste this to external template (.ascx)
<script type="text/javascript">
Sys.Application.add_init(appInit);
function appInit() {
start();
}
</script>
run it
hopefully there is no problem | unknown | |
d403 | train | you can simply iterate over the child array in the template, if you need support for endless nesting, you can use recursive components/templates
<ul>
<li *ngFor="let item of treeComponent">
<input type="radio">{{item.text}}
<div *ngIf="item.children.length">
<ul>
<li *ngFor="let child of item.children">
<input type="radio">{{child.text}}
</li>
</ul>
</div>
</li>
</ul> | unknown | |
d404 | train | You need to make sure that the parent div covers the entire screen. You can do this with the following css:
.wrapper {
position: fixed;
width: 100%;
min-height: 100%;
}
Then you just need to specify the animation on the appropriate div, give it an absolute position and tell it where to go using keyframes.
.wrapper div {
position: absolute;
-webkit-animation: myfirst 5s; /* Chrome, Safari, Opera */
animation: myfirst 5s;
}
.wrapper div.el1{
right: 200px;
}
.wrapper div.el2 {
right: 500px;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
0% {top:0;}
100% {top: 50%; right: 0;}
}
/* Standard syntax */
@keyframes myfirst {
0% {top:0;}
100% {top:50%; right: 0;}
}
Fiddle
A: You missed one property in your element:
position:absolute;
See this: jsFiddle
Note: Only Some Positioning Styles accept top, left, bottom, etc. properties. See documentation for details. | unknown | |
d405 | train | Each browser (on every OS) displays the HTML elements differently. The amount of styling that can override the defaults is also decided by the browser.
You cannot edit beyond what's permitted. If you happen to use selects for Safari, it'll look far more different and you cannot customize much there as well. | unknown | |
d406 | train | Adding a header to revalidate solved my problem.
header('Cache-Control: no-store, no-cache, must-revalidate'); | unknown | |
d407 | train | If your web app is using Bootstrap (Bootstrap is included with asp.net mvc web app templates).
Bootstrap 5 buttons -
https://getbootstrap.com/docs/5.0/components/buttons/
The bootstrap documation states:
class=“btn btn-primary”
You’re adding an extra dash “-“ between btn btn. Try removing the first dash. | unknown | |
d408 | train | You can use dojo/query:
function progClick() {
require(["dojo/query"], function(query) {
query("div[data-viewid=myViewId] > button").forEach(function(node) {
node.click();
});
});
}
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js" data-dojo-config="async: true"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dijit/themes/claro/claro.css">
</head>
<body class="claro">
<div id="everChangingId" data-viewid="myViewId">
<button type="button" onclick="alert('my button got clicked!')">My Button</button>
</div>
<hr/>
<button type="button" onclick="progClick()">Programatically Click My button</button>
</body>
</html> | unknown | |
d409 | train | If you are already using numpy you can set the dtype field to the type that you want (documentation). You'll get a little more flexibility there for typing, but in general you aren't going to get a lot of control over variable precision in Python. You might also have some luck if you want to go through the structural overhead of using the static types from Cython, though if you are new to programming that may not be the best route.
Beyond that, you haven't given us a lot to work with regarding your actual problem and why you feel that the variable precision is the best spot for optimization.
A: Pure CPython (sans numpy, etc.) floats are implemented as C doubles.
http://www.ibm.com/developerworks/opensource/library/os-python1/
Yes, the types are associated with values, not variables. You can check for something being a Python float with isinstance(something, float).
You could perhaps try objgraph to see what's using your memory.
http://mg.pov.lt/objgraph/
There's also a possibility that you are leaking memory, or merely need a garbage collection. And it could be that your machine just doesn't have much memory - sometimes it's cheaper to throw a little extra RAM, or even a little more swap space, at a constrained memory problem.
It's possible that using a low precision, alternative numeric representation would help - perhaps http://pypi.python.org/pypi/Simple%20Python%20Fixed-Point%20Module/0.6 ?. | unknown | |
d410 | train | Several things going on here.
np.random.normal draws samples from the normal distribution. The size parameter specifies the number of samples you want. If you specify 10 you'll get an array with 10 samples. If you specify a tuple, like (4, 5) you'll get a 4x5 array. Also, np.inf is a float and np.random.normal is expecting an integer or a tuple of integers for the size parameter.
What you have in f_manual is a deterministic function (i.e. the PDF) which returns the value of the PDF at the value x.
These are two different things.
scipy has a function to return the PDF of a Gaussian: scipy.stats.norm.pdf
import scipy.stats
scipy.integrate.quad(scipy.stats.norm.pdf, -np.inf, np.inf)
# (0.9999999999999998, 1.0178191320905743e-08)
scipy also has a CDF function that returns the integral from -inf to x:
scipy.stats.norm.cdf(np.inf)
# 1.0
scipy.stats.norm.cdf(0)
# 0.5 | unknown | |
d411 | train | setState is asynchronous.
I think you should handle the renderQuestion in a useEffect
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
useEffect(() => {
renderQuestion()
}, [questionIndex])
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
} | unknown | |
d412 | train | When the edit state is finished, you'll know via the UITableViewDelegate method - (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
You just need to figure out how to differentiate between a delete and a cancel. You'll know it's a delete if the data source "tableView:commitEditingStyle:forRowAtIndexPath:" method is called. If it isn't, then the user cancelled. | unknown | |
d413 | train | Probably the way you are using won't work. Because, you are sending a list but you are probably iterating through a queryset in template. Also, the way you are using distinct won't work. Because you are using 'Rounding','Configuration' togather, hence it will generate something like this:
<QuerySet [('Use Percentage Only', 'Up'), ('Use Percentage Only', 'Down'), ('Use Percentage Only', 'Half'), ...>
So you can try like this(without distinct):
grade = list(gradeScalesSetting.objects.all()) # < DB hit once
rounding = []
configuration = []
for i in grade:
if i.Rounding not in rounding:
rounding.append(i.Rounding)
if i.Configuration not in configuration:
configuration.append(i.Configuration)
return render(request, 'Homepage/gradescale.html',{"rounding":rounding, "configuration":configuration})
// in template
<select>
{% for r in rounding %}
<option value={{r}}>{{r}}</option>
{% endfor %}
</select>
But with distinct you might have to hit the DB twice:
rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct()
configuration = gradeScalesSetting.objects.all().values_list('Configuration', flat=True).distinct() | unknown | |
d414 | train | This is actually a big research problem. You are correct, averaging all the descriptors will not be meaningful. There are several approaches out there for creating a single vector out of a set of local descriptors. One big class of methods is called "bag of features" or "bag of visual words". The general idea is to cluster local descriptors (e. g. sift) from many images (e. g. using k-means). Then you take a particular image, figure out which cluster each descriptor from that image belongs to, and create a histogram. There are different ways of doing the clustering and different ways of creating and normalizing the histogram.
A somewhat different approach is called "Pyramid Match Kernel", which is a way of training an SVM classifier on sets of local descriptors.
So for starters google "bag of features" or "bag of visual words". | unknown | |
d415 | train | Declaration and setting of the Grade in Student is syntactically wrong. Not sure how it's even building like that.
public class Student implements Serializable
{
protected String name ;
protected Grade grade ;
public Student( String name, Grade grade )
{
this.setName(name).setGrade(grade) ;
}
public String getName()
{ return this.name ; }
public Student setName( String name )
{
this.name = name ;
return this ;
}
public Grade getGrade()
{ return this.grade ; }
public Student setGrade( Grade grade )
{
this.grade = grade ;
return this ;
}
}
A: You need to parse the grade class as well. It won't convert the entire complex object in one attempt. Try the below code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
Grade g = gson.fromJson(s2.getGrade().toString(), Grade.class);
System.out.println("Grade Name: " + g.getName());
System.out.println("Grade Score: " + g.getScore());
}
}
Here s2.getGrade().toString() is still a valid JSON string. You are converting that to Grade class and using it. This is the right way to parse complex objects. Hope you understood.
A: I changed everything to XML and using XStream now, which works on my tests. Thanks for everyone's answers. | unknown | |
d416 | train | You can try with OpenCV. And this list may help you. | unknown | |
d417 | train | const dialogflow = require('dialogflow');
const uuid = require('uuid');
const config = require('./config'); // your JSON file
if(!config.private_key) throw new Error('Private key required')
if(!config.client_email)throw new Error('Client email required')
if(!config.project_id) throw new Error('project required')
const credentials = {
client_email: config.client_email,
private_key: config.private_key,
};
const sessionClient = new dialogflow.SessionsClient(
{
projectId: config.project_id,
credentials
}
);
async function runSample(projectId = 'br-poaqqc') {
// A unique identifier for the given session
const sessionId = uuid.v4();
const sessionPath = sessionClient.sessionPath(config.project_id, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hi',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
try {
const responses = await sessionClient.detectIntent(request);
console.log(responses);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
} catch (err) {
console.log('Error getting response', err)
}
}
runSample();
Don't seems any issue but i think issue was with try block.
Make sure you are with internet connection if trying from local and your firewall is not blocking googleapis
A: the issue was not to do with the code, the firewall was blocking the 'googleapis.com' domain. I deployed the app in Heroku server and it worked fine. :)
For anyone who ponders around the same issue and ends up here, make sure its not a firewall issue. Cheers! | unknown | |
d418 | train | Use a parser to extract the information. I used XML::LibXML, but I had to remove the closing br tags that made the parser fail.
#!/usr/bin/perl
use warnings;
use strict;
my $html = '<html>
<head>
<title>Download Files</title>
<meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'>
<link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/main.css\' type=\'text/css\'>
<link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/Menu.css\' type=\'text/css\'>
<link rel=\'stylesheet\' href=\'/statsdoc/freeze.css\' type=\'text/css\'>
</head>
<body>
<table border=1>
<tr class=\'rightTableData\'>
<th>No.</th>
<th>File Name</th>
<th>File Size</th>
</tr><tr class=\'rightTableData\'>
<td>1</td><td>
<a href=\'/dlr_download?file=/mnt/dell6/SRM_DATA/data/API_FILE /20160329/LSUZisbZahtHNeImZJm_1-1.csv.zip\'>1-1.csv.zip</a>
</td><td>487 bytes</td> </tr>
</table>
<!-- </br></br> I had to comment this out! -->
<center><a href=\'/dlr_download?file=/mnt/dell6/SRM_DATA/data/API_FILE/20160329/LSUZisbZahtHNeImZJm-csv.zip\'>Download all</a></center>
</body></html>';
use XML::LibXML;
my $dom = 'XML::LibXML'->load_html( string => $html );
print $dom->findvalue('/html/body/table/tr[2]/td[2]/a/@href');
You could also use the recover flag to parse invalid HTML:
my $dom = 'XML::LibXML'->load_html( string => $html, recover => 1 ); | unknown | |
d419 | train | The rigth way to overload the ostream operator is as follows:
struct Bike {
std::string brand;
std::string model;
bool is_reserved;
friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference
};
std::ostream& operator<<(std::ostream& out, const Bike& b) {
return out
<< "| Brand: " << b.brand << '\n'
<< "| Model: " << b.model << '\n';
}
Also, as noted by @KyleKnoepfel you should change out << bike; to out << *bike; too. | unknown | |
d420 | train | You already know how to use the if/else construct. All you have to do is add one testing nrow(newdata), or maybe combine both as follows:
newdata <- subset(data, Random >= 30 &
Random < 50)
Pvalue <- lapply(dat, function(x){
if (length(x[[4]]) > 1 & nrow(newdata) > 1) {
t.test(newdata$Price, x[[4]])$p.value
} else NA
})
You could also replace lapply(...) with sapply(...) or vapply(..., numeric(1)) to get a numeric vector instead of a list. For that, it is recommended to replace 'not enough observation' with NA like I did, or you could end up with a character vector. | unknown | |
d421 | train | Add the bullets to the ship's parent (or directly to the scene), just not the ship or the turret because that will make the position of the bullet relative to either one.
A: Think of it this way: the ship is facing in a specific direction when it fires the bullet.
Once it fires the bullet, you wouldn't expect it to have any control over the bullet? If it turned around, the bullet should keep moving in the same direction (not stay directly in front of the ship).
This is a hint that the bullet should probably not have the ship as a parent node; it is an entity existing alongside the ship and not as part of it.
Once the bullet is fired, it should be in the same 'system' as the ship, so as @LearnCocos2D suggested it should share a parent with the ship. | unknown | |
d422 | train | You can write (and use) a separate class loader to load classes from anywhere.
That being said I suggest putting the jars into each .war file. Disk space and RAM should not be the problem.
*
*If a central .jar is modified (and a bug is introduced), all web apps will fail.
*You probably test your web app against a specific version of your libraries. If you update a central .jar, you have to re-run the tests for each application.
Generally speaking you will probably run into problems because of dependencies.
A: May you need Create Shared Java EE Library or Optional Package. See more in Install a Java EE library and Understanding WebLogic Server Application Classloading.
A: You can modify the script used to start Weblogic to include the external directory in the server's classpath. See %DOMAIN_HOME%\bin\setDomainEnv.sh (or .cmd if Windows). | unknown | |
d423 | train | Yet one more option is to use the hierarcyid data type
Example
Declare @YourTable Table ([ID] int,[Caption] varchar(50),[Parent] int) Insert Into @YourTable Values
(1,'A',NULL)
,(2,'B',NULL)
,(3,'a',1)
,(4,'b',2)
,(5,'bb',4)
,(6,'C',NULL)
,(7,'aa',3)
,(8,'c',6)
;with cteP as (
Select ID
,Parent
,Caption
,HierID = convert(hierarchyid,concat('/',ID,'/'))
From @YourTable
Where Parent is null
Union All
Select ID = r.ID
,Parent = r.Parent
,Caption = r.Caption
,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.ID,'/'))
From @YourTable r
Join cteP p on r.Parent = p.ID)
Select Lvl = HierID.GetLevel()
,ID
,Parent
,Caption
From cteP A
Order By A.HierID
Returns
Lvl ID Parent Caption
1 1 NULL A
2 3 1 a
3 7 3 aa
1 2 NULL B
2 4 2 b
3 5 4 bb
1 6 NULL C
2 8 6 c
A: Such sort requires somehow traversing the hierarchy to compute the path of each node.
You can do this with a recursive query:
with cte as (
select id, caption, parent, caption addr
from mytable
where parent is null
union all
select t.id, t.caption, t.parent, c.addr + '/' + t.caption
from cte c
inner join mytable t on t.parent = c.id
)
select
id,
row_number() over(order by addr) sort,
caption,
parent
from c
order by addr
A: You can construct the path to each row and then use that for sorting. The construction uses a recursive CTE:
with cte as (
select id, caption, parent, convert(varchar(max), format(id, '0000')) as path, 1 as lev
from t
where parent is null
union all
select t.id, t.caption, t.parent, convert(varchar(max), concat(path, '->', format(t.id, '0000'))), lev + 1
from cte join
t
on cte.id = t.parent
)
select id, caption, parent
from cte
order by path;
Here is a db<>fiddle.
A: No need for recursion, just use some clever sorting!
SELECT
ID,
ROW_NUMBER() over(order by Caption) as Sort,
Caption,
Parent
FROM Address
ORDER BY Caption, Parent
SQL Fiddle: http://sqlfiddle.com/#!18/bbbbe/9 | unknown | |
d424 | train | In build.gradle check if gradle is updated to latest.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
After that clean and rebuild your project. | unknown | |
d425 | train | What are you trying to do with the Title specifically? If you want a custom property on a label control you will need to create a custom control that inherits from the Label control. If you just want to set the text then use the Text property. If you want a tooltip then set the ToolTip property. | unknown | |
d426 | train | Your Hash Join is underneath a Gather node:
Gather (cost=67,575.34..77,959.52 rows=977 width=290) (actual time=51,264.085..52,595.474 rows=381,352 loops=1)
Buffers: shared hit=611279 read=99386
-> Hash Join (cost=66,575.34..76,861.82 rows=407 width=290) (actual time=49,962.789..51,206.643 rows=127,117 loops=3)
Buffers: shared hit=611279 read=99386
That means that The query started two background workers which ran in parallel with the main backend to complete the hash join (see the "Workers Launched": 2 in the execution plan).
Now it is evident that if three processes work on a task, the total execution time will not be the sum of the individual execution times.
In other words, the rule about multiplication of execution time with the number of loops holds for nested loop join, (which is single threaded), but not for parallel execution of a query. | unknown | |
d427 | train | Needle/Haystack in PHP
They are actually not inconsistent like many think. You have partly discovered the consistency:
*
*All string functions are (haystack, needle)
*All array functions are (needle, haystack)
Rasmus Lerdorf (the creator of PHP) states this in a talk in 2019 around 25 minutes in:
25 Years of PHP - phpday 2019
https://youtu.be/iGOAQli7tGc?t=1485
Inconsistencies in PHP
At 16:45, he has a slide titled "What was he thinking?" and he addresses "naming inconsistencies". (needle/haystack issue is just one of them)
https://youtu.be/iGOAQli7tGc?t=1005
In this talk he also explains that his design decisions for PHP are almost all based on the idea that PHP is a "wrapper for underlying C libraries", and has kept the parameters in the same order as the underlying code. | unknown | |
d428 | train | The SharePoint server-side object model you were recommended to use can't be used for your scenario. It only works when run on a server that is a part of the SharePoint farm (which your code won't in this scenario). Since you're on 2007 (no client object model), you're stuck with the webservices (or writing and deploying your own web service code to a server in the SharePoint farm, which your code then calls).
A: Is this code running in the same App Pool as the SharePoint website? If not, your easiest bet would be to use the list service (/_vti_bin/Lists.asmx). SharePoint 2010 added the Client Object Model, but obviously you're excluded from that. Example code can be found here. | unknown | |
d429 | train | The new CreateResponse() method:
/// <summary>
/// Recognizes common repository exceptions and creates a corresponding error response.
/// </summary>
/// <param name="request">The request to which the response should be created.</param>
/// <param name="ex">The exception to handle.</param>
/// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns>
private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex)
{
string message = ex.Message;
HttpStatusCode code = 0;
if (ex is KeyNotFoundException) code = HttpStatusCode.NotFound;
else if (ex is ArgumentException) code = HttpStatusCode.BadRequest;
else if (ex is InvalidOperationException) code = HttpStatusCode.BadRequest;
else if (ex is UnauthorizedAccessException) code = HttpStatusCode.Unauthorized;
else if (ex is HttpException)
{
// HttpExceptions are thrown when request between IdentityServer and the API server have failed.
// IdentityServer has generated an error, the API server received it and now it needs to relay it back to the client.
var httpException = (HttpException) ex;
code = (HttpStatusCode) httpException.GetHttpCode();
message = httpException.Message;
}
else
{
code = HttpStatusCode.InternalServerError;
// For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information
// In development time, the programmer will need the details of the error, so this general message is disabled.
#if DEBUG
message = ex.Message;
#else
message = Errors.InternalServerError;
#endif
}
// For some reason the request.CreateErrorResponse() method ignores the message given to it and parses its own message.
// The error response is constructed manually.
return CreateErrorResponse(request, code, message);
}
private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, HttpStatusCode code, string message)
{
var content = new { Message = message };
return new HttpResponseMessage(code)
{
ReasonPhrase = message,
RequestMessage = request,
Content = new ObjectContent(content.GetType(), content, new JsonMediaTypeFormatter())
};
}
}
Hope this just saved someone's day... ;) | unknown | |
d430 | train | see org.springframework.cloud.bootstrap.config.RefreshEndpoint
code here:
public synchronized String[] refresh() {
Map<String, Object> before = extract(context.getEnvironment()
.getPropertySources());
addConfigFilesToEnvironment();
Set<String> keys = changes(before,
extract(context.getEnvironment().getPropertySources())).keySet();
scope.refreshAll();
if (keys.isEmpty()) {
return new String[0];
}
context.publishEvent(new EnvironmentChangeEvent(keys));
return keys.toArray(new String[keys.size()]);
}
that means /refresh endpoint pull git first and then refresh catch,and public a environmentChangeEvent,so we can customer the code like this. | unknown | |
d431 | train | C# keywords supporting LINQ are still C#. Consider where as a conditional like if; you perform logical operations in the same way. In this case, a logical-OR, you use ||
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(
txtFilter.Text.ToLowerInvariant())
|| creditCard.CardNumber.().Contains(txtFilter.Text)
orderby creditCard.BillToName
select creditCard)
A: You can use the .Where() function to accomplish this.
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
A: You should use the boolean operator that works in your language. Pipe | works in C#
Here's msdn on the single |
Here's msdn on the double pipe ||
The deal with the double pipe is that it short-circuits (does not run the right expression if the left expression is true). Many people just use double pipe only because they never learned single pipe.
Double pipe's short circuiting behavior creates branching code, which could be very bad if a side effect was expected from running the expression on the right.
The reason I prefer single pipes in linq queries is that - if the query is someday used in linq to sql, the underlying translation of both of c#'s OR operators is to sql's OR, which operates like the single pipe. | unknown | |
d432 | train | I made it happen by putting both in autostart. My syntax seemed to be wrong.
@/path/script.sh &
@chromium-browser --kiosk http://website.xyz
works like a charme, where ampersand "&" is for making it a background process. | unknown | |
d433 | train | FWIW...late answer...however, it may help someone: if you have designated (through Info.plist's CFBundleExecutable key's value) the script to be your app's executable, by the time you attempt to sign said script, you should make sure everything else has already been signed.
Note: this is my experience using codesign through a bash script (so, not using XCode). Apple's docs say that you should sign your app bundle "from inside out"; this was my interpretation and it seems to work just fine for us.
A: Something similar to the following shell script in the Build Phases > Run Script section of your project settings should work...
/usr/bin/codesign --force --sign "iPhone Developer" --preserve-metadata=identifier,entitlements --timestamp=none $BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app/Frameworks/$framework | unknown | |
d434 | train | I needed to call fixture.detectChanges() after changing the value in the service. So the tests should have been:
it('should not find job list by css when detailed view is chosen', () => {
component.workHistoryState.ViewTypeChanged("detailed");
fixture.detectChanges();
let jobList = fixture.debugElement.query(By.css('.jobList'));
expect(jobList).toBeNull();
});
it('should not find job list when detailed view is chosen', () => {
component.workHistoryState.ViewTypeChanged("detailed");
fixture.detectChanges();
let jobList = fixture.debugElement.query(By.directive(JobListComponentMock));
expect(jobList).toBeNull();
}); | unknown | |
d435 | train | Change the code to
public class IOSTester {
public static void main(String[] args) throws Exception {
AppiumDriver driver;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "8.1");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("deviceName","iPad Air");
capabilities.setCapability("app", "/Users/AZ-Admin/Documents/test.app");
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIAButton[1]")).click();
}
}
Download Appium Driver.jar and attach it to your code file and Import AppiumDriver | unknown | |
d436 | train | I think you may be confused of what a device context is. A device context is a place in memory that you can draw to, be it the screen buffer or a bitmap or something else. Since I imagine you only want to draw on the screen, you only need one DC. To accomplish what you want, I would recommend passing a rectangle to the function that tells it where to draw. Optionally, and with poorer performance, you could create a new Bitmap for the smaller area, and give the function the Bitmap's DC to draw on. Now that I think about it, that might have been what you meant in the first place :P Good luck!
A: While not foolproof, you can fake a DC as a subsection of a DC by using a combination of SetViewportOrgEx and SelectObject with a region clipped to the sub area in question.
The problem with this approach is if drawing code already uses these APIs it needs to rewritten to be aware that it needs to combine its masking and offsetting with the existing offsets and clipping regions. | unknown | |
d437 | train | Lovespring,
You will need a copy of the kernel source or kernel headers for the kernel you are attempting to compile against. The kernel source is generally not installed with the system by default.
Typically, you can pull down a copy of the kernel source through whatever package/repository manager your have.
A: You may not need an installed kernel, but you will definitely need a copy of the source to be able to compile your module.
A:
Does the kernel module need a linux kernel to finish the compilation ?
Can I compile a kernel module without kernel ?
Yes, you can have single Makefile for your module source code. It still needs to find the kernel headers and some basic build tools.
you do not need to have the kernel sources, and you do not need to recompile the kernel.
Page #94 of this chapter may help:
http://www.linuxfordevices.com/files/misc/newnes_embedded_linux_ch7.pdf | unknown | |
d438 | train | If you are trying to have the tab/drop-down selection change when the user swipes a tab, that will not work in drop-down mode, due to a bug in setSelectedNavigationItem(). I am not aware of a workaround while still using tabs in the action bar. Personally, this is one of the reasons why I prefer PagerTabStrip (or the tab indicator from the ViewPagerIndicator library) over action bar tabs. | unknown | |
d439 | train | Looking at a tight coupling between all classes involved, I don't think that having a reference to the parent (Container) would be a bad idea. There are many models that rely on having parent reference (typical reason could be to ensure a single parent but other reasons such as validations etc can be a cause) - one of the way to model is to have non-public constructor and construct objects via factory methods. Another way of modelling is to have public constructor but have internal setter to set the parent reference. Whenever child is added to the parent's collection object, the reference is set.
I would prefer the later approach. However, one of the thing that I would do is to avoid direct coupling with Container. Rather, I will introduce IContainer interface that will abstract look-ups needed in children and children (Item/ItemStyle) will know only about IContainer interface.
Yet another reasonable design would be to raise events from children when they want to do look-ups. These will be internal events that will be handled by container when the children are added to it.
Yet another approach would be to have a loose model. Essentially, Item can maintain its own ItemStyle references. Whenever needed, Container can build ItemStyle collection by implementing visitor pattern. | unknown | |
d440 | train | Run it like this in a playground, and you will see how it works in more detail:
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted {
print("0: \($0), 1: \($1), returning \($0 > $1)")
return $0 > $1
}
$0 is simply the first argument, and $1 is the second. The output with your numbers array is:
0: 2, 1: 0, returning true
0: 1, 1: 0, returning true
0: 1, 1: 2, returning false
A: It is a syntactic simplification, it is equivalent to:
numbers.sorted {(a, b) -> Bool in
return a > b
}
In fact $0 is the first parameter of the closure, $1 is the second one...
Edit: The fact that it is called 4 times, it's just because of the sort algorithm used. And you should not take care of it.
A: It's shortly but comprehensively described in the documentation:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
...
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Shorthand Argument Names
Swift automatically provides shorthand argument names to inline
closures, which can be used to refer to the values of the closure’s
arguments by the names $0, $1, $2, and so on.
If you use these shorthand argument names within your closure
expression, you can omit the closure’s argument list from its
definition, and the number and type of the shorthand argument names
will be inferred from the expected function type. The in keyword can
also be omitted, because the closure expression is made up entirely of
its body:
reversedNames = names.sorted(by: { $0 > $1 } )
Here, $0 and $1 refer to the closure’s first and second String arguments.
A: The sorted function takes a closure which defines the ordering of any two elements. The sorting algorithm does a series of comparisons between items, and uses the closure to determine the ordering amongst them.
Here's an example which prints out all the comparisons done in the sorting of an example array of numbers:
let numbers = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
let sorted = numbers.sorted { (a: Int, b: Int) -> Bool in
let result = a < b
print("\(a) is \(result ? "" : "not") before \(b)")
return result
}
print(sorted)
$0 and $1 are implicit closure parameters. They're names implicitly given to the parameters of a closure. They're often used in cases where the names given to parameters of a closure are rather arbitrary, such as in this case.
In your example, the closure behaves as if it was like so:
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { leftElement, rightElement in
return leftElement > rightElement
}
As you can see leftElement and rightElement don't add much information to the code, which is why it's preferred to use implicit closure parameters in a case like this.
A: The "(4 times)" means your closure ({ $0 > $1 }) is getting invoked 4 times by the sorted function.
I don't know what the false means, but presumably it's the last return value from your closure, which depends entirely on the internal sorting algorithm used by sorted (which you can visualize e.g. with David Shaw's method). I.e. $0 and $1 are not "changing their positions". | unknown | |
d441 | train | You cannot write file directly from a browser to local computers.
That would be a massive security concern.
*You also cannot use fs on client-side browser
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile() on server-side, which is allowed.
What you could do is:
*
*Create a link and prompt to download.
*Send to server and response with a download.
*Use native environment like Electron to able NodeJs locally to write into local computer.
What I assume you want to do is 1
Is that case you could simply do:
function writeAndDownload(str, filename){
let yourContent = str
//Convert your string into ObjectURL
let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
let blob = new Blob([bom, yourContent], { type: "text/plain" });
let url = (window.URL || window.webkitURL).createObjectURL(blob);
//Create a link and assign the ObjectURL
let link = document.createElement("a");
link.style.display = "none";
link.setAttribute("href", url);
link.setAttribute("download", filename);
//Automatically prompt to download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
writeAndDownload("Text you want to save", "savedData") | unknown | |
d442 | train | I guess that read functions can mess things up, since reading from empty, non existing ect file will return -1.Thus, rest of computations will fall. Try to avoid that by including if firective:
while ((numOfBytes = read(fd_in, buf, 4096))!=0)
{
numOfBytes_key=read(fd_key, buf_key, numOfBytes);
if (numOfBytes>numOfBytes_key && (numOfBytes >= 0) &&(numOfBytes_key >= 0 ))
{
lseek(fd_in, -(numOfBytes - numOfBytes_key), SEEK_CUR);
lseek(fd_key, 0, SEEK_SET);
}
for (i = 0; i < numOfBytes_key; i++){
buf_out[i] = buf[i] ^ buf_key[i];
}
write(fd_out, buf_out, numOfBytes_key);
} | unknown | |
d443 | train | You can't do it with a style or template, since a binding is not a FrameworkElement. But your idea of a class inheriting Binding should work fine, I've done the same before for a similar problem | unknown | |
d444 | train | In addition to your ObjectMapper annotated with @Primary
you can configure more ObjectMappers qualified with bean names of your choice.
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
@Bean("mySpecialObjectMapper")
public ObjectMapper anotherObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
/* do some other configuration */;
return objectMapper;
}
Then you can refer to them in your controllers like this:
*
*Just giving @Autowired will inject the primary ObjectMapper.
*Giving @Autowired together with @Qualifier("anyName") will inject
the ObjectMapper configured with @Bean("anyName")
@Autowired
private ObjectMapper objectMapper;
@Autowired
@Qualifier("mySpecialObjectMapper")
private ObjectMapper otherObjectMapper;
A: Maybe you just need to use @JsonInclude(JsonInclude.Include.NON_NULL). Try to fix it in the response model level. | unknown | |
d445 | train | You have not defined ng-app="myModule" in your html template.
Either define it in html or body tag then it should start working.
A: Just add ng-app="myModule" to your HTML ,
<body ng-app="myModule" ng-controller="myController">
DEMO
var app = angular.module("myModule", [])
app.controller("myController", function($scope){
var technologies = [{name:"C#", likes:0, dislikes:0},
{name:"ASP.NET", likes:0, dislikes:0},
{name:"SQL Server", likes:0,dislikes:0},
{name:"Angular JS", likes:0, dislikes:0},];
$scope.technologies = technologies;
$scope.incrementLikes = function(technology){
technology.likes++;
}
$scope.incrementDislikes = function(technology){
technology.dislikes++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule" ng-controller="myController">
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Likes</th>
<th>DisLikes</th>
<th>Likes/DisLikes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="technology in technologies">
<td>{{ technology.name }}</td>
<td>{{ technology.likes }}</td>
<td>{{ technology.dislikes }}</td>
<td>
<input type="button" value="Like" ng-click="incrementLikes(technology)">
<input type="button" value="Dislike" ng-click="incrementDislikes(technology)">
</td>
</tr>
</tbody>
</table>
</div>
</body> | unknown | |
d446 | train | After a whole afternoon's searching.
Here is what i think:
When I change the controller into this code below,everything still works fine.
So there is nothing wrong with mybatis
@RequestMapping("/login")
Account login(
@RequestParam("username")String username,
@RequestParam("password")String password){
account.setUsername(username);
account.setPassword(password);
return accountMapper.select(account);
//return account;
}
But it i change the code slightly into
@RequestMapping("/login")
Account login(
@RequestParam("username")String username,
@RequestParam("password")String password){
account.setUsername(username);
account.setPassword(password);
//return accountMapper.select(account);
return account;
}
It then report the same error message that i mention in the question.
I think the @SessionScope's bean(which is Account class) is already managed by SpringBoot's ioc container,
and if i return the same session scope bean from that controller method,
these two bean point to the same thing,that causing some kind of self-reference. | unknown | |
d447 | train | A guy in my team found the solution. When referencing the stylesheets I've forgotten the rel="stylesheet" after each of them.
so this
<link type="text/css" href="assets/styles/main.css">
should be this
<link type="text/css" href="assets/styles/main.css" rel="stylesheet"> | unknown | |
d448 | train | Point well taken, so let me try to explain briefly what the code does - you can read more about the ShellWindows object here.
The code below helps you find all running instances of Windows Explorer (not Internet Explorer, note that "explorer" is used in the if statement and not "iexplore").
Add Reference to Shell32.dll, located in the Windows/system32 folder
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
ArrayList windows = new ArrayList();
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("explorer"))
{
//do something with the handle here
MessageBox.Show(ie.HWND.ToString());
}
}
A:
can somebody explain me why the "Windows Explorer" is different from other Programms?
It's the default shell. Explorer.exe handles many (user interface) tasks of Windows, some of which are the taskbar, hosting extensions and harboring the file explorer.
It's a (sort-of) single-instance process, so when you launch a new instance, it'll hand the parameters to the running instance.
If you want to focus or open an Explorer at a certain path, just use:
Process.Start(@"C:\SomeFolder\");
A: Following code iterates through all explorer and internet explorer windows(tabs) (W7/IE11). Location URL will give the folder that is being viewed in the explorer. If the folder is the one you need to bring to foreground, you can use HWND for that window and bring it to foreground.
Note location URL for explorer window for "Computer" will be blank. I am not sure if there are more special cases like that.
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
foreach (SHDocVw.InternetExplorer window in shellWindows){
if (window.LocationURL.Contains("Some Folder I am interested in")){
SetForegroundWindow((IntPtr)window.HWND);
}
} | unknown | |
d449 | train | You cannot do this directly in the manner you are talking about. There are filesystems that sort of do this. For example LessFS can do this. I also believe that the underlying structure of btrfs supports this, so if someone put the hooks in, it would be accessible at user level.
But, there is no way to do this with any of the ext filesystems, and I believe that it happens implicitly in LessFS.
There is a really ugly way of doing it in btrfs. If you make a snapshot, then truncate the snapshot file to 100M, you have effectively achieved your goal.
I believe this would also work with btrfs and a sufficiently recent version of cp you could just copy the file with cp then truncate one copy. The version of cp would have to have the --reflink option, and if you want to be extra sure about this, give the --reflink=always option.
A: Adding to @Omnifarious's answer:
What you're describing is not a hard link. A hard links is essentially a reference to an inode, by a path name. (A soft link is a reference to a path name, by a path name.) There is no mechanism to say, "I want this inode, but slightly different, only the first k blocks". A copy-on-write filesystem could do this for you under the covers. If you were using such a filesystem then you would simply say
cp fileA fileB && truncate -s 200M fileB
Of course, this also works on a non-copy-on-write filesystem, but it takes up an extra 200 MB instead of just the filesystem overhead.
Now, that said, you could still implement something like this easily on Linux with FUSE. You could implement a filesystem that mirrors some target directory but simply artificially sets a maximum length to files (at say 200 MB).
FUSE
FUSE Hello World
A: Maybe you can check ChunkFS. I think this is what you need (I didn't try it). | unknown | |
d450 | train | You can do several things:
*
*Use Label control
*Use Timer and tick 1.5 seconds interval for glide motion
*On the Tick event of the timer change the location of Label.Location gradually to the center top of the application
OR
*
*Subscribe to OnPaint event
*Manually draw the label via Graphics.DrawString()
*Reposition the location of the text via DrawString() location
*Use the Timer to invalidate the painting every 1.5seconds, and Invalidate() the text position
SAMPLE
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
this.InitializeTimer();
}
private void InitializeTimer()
{
this.timer1.Interval = 1500; //1.5 seconds
this.timer1.Enabled = true; //Start
}
private void timer1_Tick(object sender, EventArgs e)
{
int step = 5; //Move 5 pixels every 1.5 seconds
//Limit and stop till center-x of label reaches center-x of the form's
if ((this.label1.Location.X + (this.label1.Width / 2)) < (this.ClientRectangle.Width / 2))
//Move from left to right by incrementing x
this.label1.Location = new Point(this.label1.Location.X + step, this.label1.Location.Y);
else
this.timer1.Enabled = false; //Stop
}
} | unknown | |
d451 | train | You can make use of a dynamic uri in your route block.
See http://camel.apache.org/how-do-i-use-dynamic-uri-in-to.html
Note that this can be done in both from() and to().
Example:
[From (previous application endpoint)]
-> [To (perform rest with dynamic values from the exchange)]
-> [To (process the returned json)]
A: If you're making a rest call you can use the CXFRS component. At the very bottom of the page you'll see an example of a processor that's setting up a message as a rest call. With regards to your question, you can use
inMessage.setHeader(Exchange.HTTP_PATH, "/resources/{var1}/{var2}/details?orderNumber=XXXXX");
to set up any path parameters that you might need.
A: Please Try to use camel servlet.
< from uri="servlet:///orders/resources/{$var1}/{$var2}/details?orderNumber=XXXXX" />
in web.xml,
< url-pattern>/ * < /url-pattern>
Reference:
http://camel.apache.org/servlet.html
A: Below is the example where you can find a Rest call with Apache Camel.
package camelinaction;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.apache.camel.spring.boot.FatJarRouter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class OrderRoute extends FatJarRouter {
@Bean(name = "jsonProvider")
public JacksonJsonProvider jsonProvider() {
return new JacksonJsonProvider();
}
@Override
public void configure() throws Exception {
// use CXF-RS to setup the REST web service using the resource class
// and use the simple binding style which is recommended to use
from("cxfrs:http://localhost:8080?resourceClasses=camelinaction.RestOrderService&bindingStyle=SimpleConsumer&providers=#jsonProvider")
// call the route based on the operation invoked on the REST web service
.toD("direct:${header.operationName}");
// routes that implement the REST services
from("direct:createOrder")
.bean("orderService", "createOrder");
from("direct:getOrder")
.bean("orderService", "getOrder(${header.id})");
from("direct:updateOrder")
.bean("orderService", "updateOrder");
from("direct:cancelOrder")
.bean("orderService", "cancelOrder(${header.id})");
}
}
Source code link :
https://github.com/camelinaction/camelinaction2/tree/master/chapter10/camel-cxf-rest-spring-boot.
I highly encourage to refer camelinaction2 as it covers many advance topics and it is written by @Claus Ibsen. | unknown | |
d452 | train | It really depends. Does the lib expose only 'extern "C"' functions where memory is either managed by straight Win32 methods (CoTaskMemAlloc, etc) or the caller never frees memory allocated by the callee or vice-versa? Do you only rely on basic libraries that haven't changed much since VS 6? If so, you should be fine.
There are 2 basic things to watch for. Changes to global variables used by 3rd-party libraries, and changes to the structure of structs, classes, etc defined by those 3rd-party libraries. For example, the CRT memory allocator has probably changed its hidden allocation management structures between the 2 versions, so having one version of the library allocate a piece of memory and having another free it will probably cause a crash.
As another example, if you expose C++ classes through the interface and they rely on MS runtime libraries like MFC, there's a chance that the class layout has changed between VS 6 and VS 2008. That means that accessing a member/field on the class could go to the wrong thing and cause unpredictable results. You're probably hosed if the .lib uses MFC in any capacity. MFC defines and internally uses tons of globals, and any access to MFC globals by the operations in the .lib could cause failures if the MFC infrastructure has changed in the hosting environment (it has changed a lot since VS 6, BTW).
I haven't explored exactly what changes were made in the MFC headers, but I've seen unpredictable behavior between MFC/ATL-based class binaries compiled in different VS versions.
On top of those issues, there's a risk for functions like strtok() that rely on static global variables defined in the run-time libraries. I'm not sure, but I'm concerned those static variables may not get initialized properly if you use a client expecting the single-threaded CRT on a thread created on the multi-threaded CRT. Look at the documentation for _beginthread() for more info.
A: I shouldn't think why not - as long as you keep the usual CRT memory boundaries (ie if you allocate memory inside a library function, always free it from inside the library - by calling a function in the lib to do the freeing).
this approach works fine for dlls compiled with all kinds of compilers, statically linked libs should be ok too.
A: Yes. There should be no issues with this at all. As gbjbaanb mentioned, you need to mind your memory, but VS2008 will still work with it. As long as you are not trying to mix CLR, (managed) code with it. I'd recommend against that if at all possible. But, if you are talking about raw C or C++ code, sure, it'll work.
What exactly are you planning on using? (What is in this library?) Have you tried it already, but are having issues, or are you just checking before you waste a bunch of time trying to get something to work that just wont?
A: Sure it'll work.
Are you asking where in VS2008 to code the references?
If so, go to proj props -> Linker -> Input on Configuration properties on the property pages. Look for "additional dependencies" and code the .LIB there.
Go to proj props -> Linker -> General and code the libs path in "Additional Library Directories".
That should do it!!
A: There are cases were the answer is no, when we moved from VS6 to VS2k5 we had to rebuild all our libraries, as the memory model had changed, and the CRT functions where different.
A: There were a handful of breaking changes between VC6, VS2003, VS2005 and VS2008. Visual C++ (in VS2005) stopped support for single-threaded, statically linked CRT library. Some breaking changes enumerated here and here. Those changes will impact your use of VC6 built libs in later versions. | unknown | |
d453 | train | Try DataRow's IsNull method to check null values :
Dim isPersonIDNull As Boolean = .Rows(0).IsNull("personId")
Or use IsDBNull method :
Dim isPersonIDNull As Boolean = IsDBNull(.Rows(int).Item("personId"))
Or manually Check if the value equals DBNull :
Dim isPersonIDNull As Boolean = .Rows(int).Item("personId").Equals(DBNull.Value)
A: If DBNull.Value.Equal(.Rows(int).Item("personId")) Then
...
DBNull
A: You can also use the Convert.DbNull constant.
A: You have to check if the value is null before you assign it to PersonID
like:
if .Rows(int).Item("personId") = DBNull.Value Then
' Assign some Dummy Value
PersonID = ""
else
PersonID = .Rows(int).Item("personId")
end if
I would recommend to extract that piece of code into a helper method which gets either the value or a default for a given column.
A: This situation can occur if table with no rows, that time ds.Table(0).Rows(int).Item("personId") will return null reference exception
so you have to use two conditions
Dim PersonID As String =""
if(ds.tables.count>0) Then
if(ds.tables(0).Rows.Count>0) Then
if(NOT DBNull.Value.Equal((ds.tables(0).Rows(int).Item("PersonID"))) Then
PersonID = ds.tables(0).Rows(int).Item("PersonID")
I think It will solve your issue..just minor syntax variation may be present | unknown | |
d454 | train | Index signature is missing on this.props' type.
Indexable Types
Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:
To fix it, you'd need to tell Typescript that this.props' object type has strings as keys:
interface QuestionViewProps {
... your definition,
[key: string]: myType,
}
Second options is to just suppress the warning via "suppressImplicitAnyIndexErrors": true.
Third options is to cast to , which wouldn't be type-safe anymore:
let prop: any = (<any>this.props)[key]; | unknown | |
d455 | train | You've tried onMouseDown?
<button
onMouseDown={() => setdata((previous) => !previous)}
type="button"
style={{ cursor: 'pointer' }}
>
Start
</button>
source: https://stackoverflow.com/a/37273344/19503616
A: It's possible that the issue might be with the type of the button or with the way the event handler is being attached to the button. Try changing the type of the button from "button" to "submit". Also, make sure that the onClick event handler is correctly attached to the button component. Here's how it should look:
<button type="submit" onClick={() => setdata((previous) => !previous)} style={{ cursor: 'pointer' }}>Start</button>
If the above does not work, try debugging the issue by using console.log statements within the event handler to check if it's being called. | unknown | |
d456 | train | I struggled with google tutorial. Here is the code (and explainations) needed to send a file using it's path or to send a file by righ cliking on it (working on windows 7 with python 36)
## windows7 python36: send to gdrive using righ click context menu
import logging
import httplib2
import os #to get files
from os.path import basename #get file name
import sys #to get path
import ctypes # alert box (inbuilt)
import time #date for filename
import oauth2client
from oauth2client import client, tools
# google apli drive
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
#needed for gmail service
from apiclient import discovery
import mimetypes #to guess the mime types of the file to upload
import HtmlClipboard #custom modul which recognized html and copy it in html_clipboard
## About credentials
# There are 2 types of "credentials":
# the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id)
# the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:\Users\user\.credentials)
#Getting the CLIENT_ID
# 1) enable the api you need on https://console.developers.google.com/apis/
# 2) download the .json file (this is the CLIENT_ID)
# 3) save the CLIENT_ID in same folder as your script.py
# 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename
#Optional
# If you don't change the permission ("scope"):
#the CLIENT_ID could be deleted after creating the credential (after the first run)
# If you need to change the scope:
# you will need the CLIENT_ID each time to create a new credential that contains the new scope.
# Set a new credentials_path for the new credential (because it's another file)
## get the credential or create it if doesn't exist
def get_credentials():
# If needed create folder for credential
home_dir = os.path.expanduser('~') #>> C:\Users\Me
credential_dir = os.path.join(home_dir, '.credentials') # >>C:\Users\Me\.credentials (it's a folder)
if not os.path.exists(credential_dir):
os.makedirs(credential_dir) #create folder if doesnt exist
credential_path = os.path.join(credential_dir, 'name_of_your_json_file.json')
#Store the credential
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
CLIENT_SECRET_FILE = 'client_id to send Gmail.json'
APPLICATION_NAME = 'Gmail API Python Send Email'
#The scope URL for read/write access to a user's calendar data
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
# Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials)
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
return credentials
## Send a file by providing it's path (for debug)
def upload_myFile_to_Gdrive(): #needed for testing
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http )
path_file_to_upload=r'C:\Users\Me\Desktop\myFile.docx'
#extract file name from the path
myFile_name=os.path.basename(path_file_to_upload)
#upload in the right folder:
# (to get the id: open the folder on gdrive and look in the browser URL)
folder_id="0B5qsCtRh5yNoTnVbR3hJUHlKZVU"
#send it
file_metadata = { 'name' : myFile_name, 'parents': [folder_id] }
media = MediaFileUpload(path_file_to_upload,
mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)#find the right mime type: http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
#Print result:
print(f"file ID uploaded: {file.get('id')}")
input("close?")
## Send file selected using the "send to" context menu
def upload_right_clicked_files_to_Gdrive():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http)
## launch the script through the context menu "SendTo"
# (in windows7) Type "shell:SendTo" in the URL of an explorer windows. Create a .cmd file containing (remove the first # before each line):
# #@echo off
# cls
# python "The\\path\\of\\your_script.py" "%1"
## the path of the file right-clicked will be stored in "sys.argv[1:]"
#print(sys.argv)
#['C:\\Users\\my_script.py', 'C:\\Desktop\\my', 'photo.jpg'] #(the path will cut if the filename contain space)
##get the right-clicked file path
#join all till the end (because of the space)
path_file_to_upload= ' '.join(sys.argv[1:]) #>> C:\Desktop\my photo.jpg
file_name=os.path.basename(path_file_to_upload)
##guess the content type of the file
#-----About MimeTypes:
# It tells gdrive which application it should use to read the file (it acts like an extension for windows). If you dont provide it, you wont be able to read the file on gdrive (it won't recognized it as text, image...). You'll have to download it to read it (it will be recognized then with it's extension).
file_mime_type, encoding = mimetypes.guess_type(path_file_to_upload)
#file_mime_type: ex image/jpeg or text/plain (or None if extension isn't recognized)
# if your file isn't recognized you can add it here: C:\Users\Me\AppData\Local\Programs\Python\Python36\Lib\mimetypes.py
if file_mime_type is None or encoding is not None:
file_mime_type = 'application/octet-stream' #this mine type will be set for unrecognized extension (so it won't return None).
##upload in the right folder:
# (to get the id: open the folder on gdrive and look in the browser URL)
folder_id="0B5f6Tv7nVYv77BPbVU"
## send file + it's metadata
file_metadata = { 'name' : file_name, 'parents': [folder_id] }
media = MediaFileUpload(path_file_to_upload, mimetype= file_mime_type)
the_file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
##print the uploaded file ID
uploaded_file_id = the_file.get('id')
print(f"file ID: {uploaded_file_id}")
input("close?")
if __name__ == '__main__':
# upload_right_clicked_files_to_Gdrive()
upload_myFile_to_Gdrive() # needed to debug | unknown | |
d457 | train | what's wrong with just running the command with exclude directory.
Pipeline | is parsed before variables are expanded.
Unquoted variable expansion undergo word splitting and filename expansion. This is irrelevant of quotes and backslashes inside the string - you can put as many backslashes as you want, the result of the expansion still will be split on spaces. https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions
y guess is it has to do some with kind of escaping special characters?
No, it does not matter what is the content of the variable. It's important how you use the variable.
Above works, but the snippet below would fail.
Yes, \( is an invalid argument for find, it should be (. The result of expansion is not parsed for escape sequences, they are preserved literally, so \( stays to be \(, two characters. In comparison, when the line is parsed, then quoting is parsed. https://www.gnu.org/software/bash/manual/bash.html#Shell-Operation
In either case, you want to be using Bash arrays and want to do a lot of experimenting with quoting and expansion in shell. The following could be enough to get you started:
findargs=( -not \( -path "./special_directory" -prune \) )
find . "${findargs[@]}"
Check your scripts with shellcheck. Do not store commands in variables - use functions and bash arrays. Quote variable expansions. eval is very unsafe, and if the path comes from the user, shouldn't be used. Use printf "%q" to quote a string for re-eval-ing. See https://mywiki.wooledge.org/BashFAQ/050 , https://mywiki.wooledge.org/BashFAQ/048 , and read many introductions to bash arrays.
A: The reason you typically have to escape the parentheses in a find command is that parentheses have special meaning in bash. Bash sees a command like find . -not ( -path "./special_dir" -prune ) and tries to interpret those parentheses as shell syntax instead of literal characters that you want to pass to your command. It can't do that in this context, so it complains. The simple fix is to escape the parentheses to tell bash to treat them literally.
To reiterate: those backslashes are NOT syntax to the find command, they are there to tell bash not to treat a character specially even if it normally has special meaning. Bash removes those backslashes from the command line before executing the command so the find program never sees any backslashes.
Now in your use case, you're putting the command in a variable. Variable expansion happens after bash has parsed the contents of the command line, so escape characters inside the variable (like '\') won't be treated like escapes. They'll be treated like any normal character. This means your backslashes are being passed as literal characters to your command, and find doesn't actually know what to do with them because they aren't part of that command's syntax.
Further reading on the bash parser
The simplest thing you can do: Just don't include the backslashes. Something like this will work fine:
exclude='-not ( -path ./special_dir -prune )'
command="find . $exclude"
$command
The parentheses don't actually need to be escaped here because the parsing step that would interpret them as special characters happens before variable expansion, so they'll just be treated literally.
But really, you might be better off using a function. Variables are meant to hold data, functions are meant to hold code. This will save you a lot of headaches trying to understand and work around the parsing rules.
A simple example might be:
normal_find() {
find .
}
find_with_exclude() {
find . -not \( -path ./special_dir -prune \)
}
my_command=normal_find
#my_command=find_with_exclude #toggle between these however you like
results=$( $my_command | wc -l )
echo "results=$results" | unknown | |
d458 | train | You can use case when:
select EventType,SendingOrganizationID,
MAX(case when isProcessed = 0 then CreatedOn end) as LastReceived,
MAX(case when isProcessed = 1 then CreatedOn end) as LastProcessed
from mytable
group by SendingOrganizationID,EventType; | unknown | |
d459 | train | PortfolioController is considered a JSF context bean adding @Component to @ManagedBean is totally wrong you can't mark same class as bean in two different contexts (JSF and Spring ).
Two solutions either make PortfolioController a spring bean thus remove the @ManagedBean and @ViewScoped or inject PortfolioController via JSF injection annotation @ManagedProperty
@ManagedProperty("#{portfolioService}")
private PortfolioService portfolioService;
A: if the applicationContext.xml is in your jar dependency, then you need to add asterisk after classpath:
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
With the asterisk spring search files applicationContext.xml anywhere in the classpath not only the current project. | unknown | |
d460 | train | The only tricky one is pizza/pizzeria and it's an issue called stemming.
Both sphinx and solr/sunspot support stemming but I imagine you will need to teach them both that pizza is a stem of pizzeria.
A: One way to remove false positives is to run a user defined function (UDF) to compute the edit distance between a candidate answer and the original string, and ignore those answers whose edit distance is too large.
A: I found a very simple solution that serves my needs.
"%#{"pizza".scan(/./).join("%")}%"
This creates a string that looks like this
"%p%i%z%z%a%"
Then I use it in a LIKE query and I get the expected results. Now all that remains is to solve the non-trivial problem of determining the order of relevance :)
UPDATE:
Found a quick and dirty way of determining order of relevance base on the assumption that a shorter string will most likely be a closer match than a longer one.
ORDER BY length(sequence) ASC | unknown | |
d461 | train | use copy task e.g.
<copy file="myfile.txt" todir="../some/other/dir"/>
A: this should work as I have added copy task under main :
<project name="master" >
<property name="class.dir" location="../Source/buildwork" />
<property name="ecpsproperties.dir" location="D:\ecpsproperties\jars\platform" />
<property name="jbossdeploy.dir" location="D:\jboss-6.1.0.Final\server\default\deploy" />
<target name="clean">
<delete dir="${class.dir}" />
</target>
<target name="makedir">
<mkdir dir="${class.dir}" />
<mkdir dir="${class.dir}/jar" />
<mkdir dir="${class.dir}/ear" />
<mkdir dir="${class.dir}/war" />
</target>
<filelist id="projects" dir=".">
<file name="../Source/ValueObjects/build.xml"/>
<file name="../Source/ECPSValueObjects/build.xml"/>
<file name="../Source/ECPSUtils/build.xml"/>
<file name="../Source/CommonExceptions/build.xml"/>
<file name="../Source/ECPSExceptions/build.xml"/>
<file name="../Source/ECPSCommon/build.xml"/>
<file name="../Source/BaseDAO/build.xml"/>
<file name="../Source/PageManagerValueObjects/build.xml"/>
<file name="../Source/PageManagerDAO/build.xml"/>
<file name="../Source/ECPSDAO/build.xml"/>
<file name="../Source/PageManagerEJBClient/build.xml"/>
<file name="../Source/PartyEJBClient/build.xml"/>
<file name="../Source/ReportsEJBClient/build.xml"/>
<file name="../Source/StagingEJBClient/build.xml"/>
<file name="../Source/MessageBoardEJBClient/build.xml"/>
<file name="../Source/PageManagerFacade/build.xml"/>
<file name="../Source/PartyFacade/build.xml"/>
<file name="../Source/ReportsFacade/build.xml"/>
<file name="../Source/StagingFacade/build.xml"/>
<file name="../Source/MessageBoardFacade/build.xml"/>
<file name="../Source/MessageBoardEJB/build.xml"/>
<file name="../Source/MessageBoardEAR/build.xml"/>
<file name="../Source/PageManagerEJB/build.xml"/>
<file name="../Source/PageManagerEAR/build.xml"/>
<file name="../Source/PartyEJB/build.xml"/>
<file name="../Source/PartyEAR/build.xml"/>
<file name="../Source/ReportsEJB/build.xml"/>
<file name="../Source/ReportsEAR/build.xml"/>
<file name="../Source/StagingEJB/build.xml"/>
<file name="../Source/StagingEAR/build.xml"/>
<file name="../Source/Admin/build.xml"/>
<file name="../Source/eCPSClient/build.xml"/>
<file name="../Source/MessageBoardServices/build.xml"/>
<file name="../Source/OAuth/build.xml"/>
<file name="../Source/PageManagerRest/build.xml"/>
<file name="../Source/PartyServices/build.xml"/>
<file name="../Source/ReportsServices/build.xml"/>
<file name="../Source/StagingServices/build.xml"/>
</filelist>
<target name="main" depends="clean, makedir">
<subant>
<filelist refid="projects" />
</subant>
<copy todir="${jbossdeploy.dir}" overwrite="yes">
<fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/>
</copy>
</target>
</project> | unknown | |
d462 | train | Please ensure the statuts and gardes tables have the id column set as a primary key. I tested the same code and only received the 1005 error when one of the foreign keys was not a primary key in its own table. This is assuming there is a valid statuts and gardes table each with an integer id column.
ALTER TABLE `statuts`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
ALTER TABLE `gardes`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`); | unknown | |
d463 | train | To implement an interface you need:
*
*inherit your class from it
*add it onto interface map
*implement its methods
For example:
class CFoo :
// regular COM object base class, esp. those generated by ATL Simple Object Class Wizard
public IOleCommandTarget
{
BEGIN_COM_MAP(CFoo)
// ...
COM_INTERFACE_ENTRY(IOleCommandTarget)
END_COM_MAP()
// ...
public:
// IOleCommandTarget
STDMETHOD(Exec)(...) // IOleCommandTarget methods go here
{
// ...
}
};
A: To implement you need to do:
*
*In the *h file let your CoClass inherit from interface.
2.In the *h file ,add an interface entry in the COM Map.
In the *h file ,add the prototype of interface methods.
In the *cpp file, implement the method of interface. | unknown | |
d464 | train | Thank you for adding the error logs.
Actual answer:
If you're adding POST data as a string but that's in a valid JSON format, it will be parsed as such. In order to preserve it as a string, you need to add a newline char or whitespace so the beginning of the string:
"\n<post-data-here"
Original answer re the parsing-error which proved not to be the main issue in the end...
You're hitting a parsing error in the ethereum-bridge due to it trying but failing to parse the returned json from your query.
However at the time of writing, your local tunnel is returning a 404 error rather than the data it originally returned.
Then, as the ethereum-bridgeattempts to parse thejsonto pluck the value from thea` key, per your query:
json(https://purple-squid-54.localtunnel.me).a
...it can't because there is not json and so no a field and so you get a parsing error.
To fix it, ensure your local tunnel is working and that the data returned is in correct json format, and that there is an a key present for the parser to work with. | unknown | |
d465 | train | This is because you have reduced the number of significant digits when you changed the datatype. If you have any rows with a value of 100,000 or greater it won't fit inside the new size. If you want to increase the number of decimal places (scale) you will also need to increase the precision by 1.
alter table xxx alter COLUMN xxx decimal (10,5) not null
Please note, this will increase the storage requirements of each row by 4 bytes. The storage requirement will increase from 5 bytes to 9 bytes.
https://msdn.microsoft.com/en-us/library/ms187746.aspx | unknown | |
d466 | train | Pass the mocked context to your method in activity.
@Test
public void isGpsOn() {
final Context context = mock(Context.class);
final LocationManager manager = mock(LocationManager.class);
Mockito.when(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(manager);
Mockito.when(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);
assertTrue(activity.isGpsEnabled(context));
} | unknown | |
d467 | train | Try this:
string[] arrdate = currentLine.Split(' ');
var dateItems = arrdate.Where(item => item.Contains("/")).ToArray()
A: foreach (string s in arrdate)
{
if (s.contains("/"))
{
//do something with s like add it to an array or if you only look for one string assign it and break out of the loop.
}
}
A: if you want to get only one item then try this
// split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}
A: // split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
} | unknown | |
d468 | train | Replace int with Integer since int is a primitive type which won't accept null values. Integer is a wrapper object that accepts null values. | unknown | |
d469 | train | You have a little code that looks like pseudoxode - try this:
if (isNaN(rows)) alert("Error: Not a Number"); | unknown | |
d470 | train | If you get here and are using Powershell 5.0, it's available in the powershell gallery
Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json
$json = '{"test":1}'
[Newtonsoft.Json.Linq.JObject]::Parse($json)
A: maybe this is what you're after :
http://poshcode.org/2930
function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
$mStream = New-Object System.IO.MemoryStream
}
PROCESS {
$json | Write-Stream -Stream $mStream
}
END {
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Write-Stream {
PARAM(
[Parameter(Position=0)]$stream,
[Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
$json = '{
"Name": "Apple",
"Expiry": 1230422400000,
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}'
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
(convert-jsonToXml $json).innerXML
Output :
<root type="object"><Name type="string">Apple</Name><Expiry type="number">1230422
400000</Expiry><Price type="number">3.99</Price><Sizes type="array"><item type="s
tring">Small</item><item type="string">Medium</item><item type="string">Large</it
em></Sizes></root>
If you want the name node :
$j=(convert-jsonToXml $json)
$j.SelectNodes("/root/Name")
or
$j |Select-Xml -XPath "/root/Name" |select -ExpandProperty node
A: Ok, so here is how I did it so it works down to at least PowerShell v2 on Windows 2008.
First, load the Json.NET assembly for the version you would like to use, I took the .NET 3.5 version:
[Reflection.Assembly]::LoadFile("Newtonsoft.Json.dll")
I had the JSON in a file since it was used in a deployment configuration I wrote, so I needed to read the file and then parse the json
$json = (Get-Content $FileName | Out-String) # read file
$config = [Newtonsoft.Json.Linq.JObject]::Parse($json) # parse string
Now to get values from the config you need to to use the Item method which seems defined by PowerShell on hashtables/dictionaries. So to get an item that is a simple string you would write:
Write-Host $config.Item("SomeStringKeyInJson").ToString()
If you had an array of things you would need to do something like
$config.Item("SomeKeyToAnArray") | ForEach-Object { Write-Host $_.Item("SomeKeyInArrayItem").ToString() }
To access nested items you write
$config.Item("SomeItem").Item("NestedItem")
That's how I solved parsing JSON with Json.NET in PowerShell.
A: None of the answers here so far made it straightforward to deserialize, edit, and serialize without Token PropertyName in state ArrayStart would result in an invalid JSON object errors. This is what ended up working for me.
Assuming $json contains a valid json string this deserializes to a hashtable:
$config = [Newtonsoft.Json.JsonConvert]::DeserializeAnonymousType($json, @{})
Or, if you need to maintain key order:
$config = [Newtonsoft.Json.JsonConvert]::DeserializeAnonymousType($json, [ordered]@{})
Then you can work with the data as a normal hashtable, and serialize it again.
$sb = [System.Text.StringBuilder]::new()
$sw = [System.IO.StringWriter]::new($sb)
$jw = [Newtonsoft.Json.JsonTextWriter]::new($sw)
$jw.Formatting = [Newtonsoft.Json.Formatting]::Indented
$s = [Newtonsoft.Json.JsonSerializer]::new()
$s.Serialize($jw, $config)
$json = $sb.ToString() | unknown | |
d471 | train | I think I might have the answer - your argv[ 1 ] is pointing to the 30 'A's - and you have a password buffer of 16. The strcpy() will just fill the buffer and beyond.
I would increase the buffer size to a larger size (say 255 bytes).
In practise, you should review your code, even examples, and make them more robust (example: allowing for larger passwords then 16 )
A: Please less the number of As try A(17) times it will work | unknown | |
d472 | train | You could use awk for this:
awk -F'##' '
{
for(i=1;i<NF;i++){
printf "%d ",length($i)+offset+1
offset+=length($i)+length(FS)
}
printf "\n"
offset=0
}' file
The parameter delimiter -F is set as your pattern.
Loop through all portions of the line ($1,$2...) and print the length of each portion that actually indicates the position of the pattern (adding the offset for line that would contain more than one match).
A: Try this
#!/bin/bash
str1="assert property ( ( req1 == 0 ) ##1 ( req1 == 1 ) ##1 !( req2 == 1 ) || (gnt1 == 0 ) );"
str2="assert property ( ( req1 == 0 ) ##1 !( req1 == 1 ) || ( gnt1 == 1 ) );"
str3="assert property ( ( req1 == 1 && req2 == 0 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );"
char="##"
awk -v a="$str1" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str2" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str3" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
The positions are 32, 32 and 45 for these examples. But there is only the first appearance of the ## char for each one. Not sure if you need to get more appearances.
Solution extracted from Dennis Williamsons comment on this post | unknown | |
d473 | train | //root.setStyle("-fx-background-image: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxsasGQIwQNwjek3F1nSwlfx60g6XpOggnxw5dyQrtCL_0x8IW')");
This worked out. But not all url's it likes.
A: In case you are using FXML, you have to add stylesheets to your GridPane in the Controller class. For example, gridPane is the reference variable of your GridPane and app.css is a name of your stylesheets:
gridPane.getStylesheets().addAll(getClass().getResource("/css/app.css").toExternalForm())
Then write something like this in your stylesheets:
#gridPane { -fx-background-image:url("file:C:/path/to/your/project/folder/src/main/resources/image.jpg"); }
In addition, you can add stylesheets app.css to GridPane in the SceneBuilder.
The aforementioned procedure worked for me. | unknown | |
d474 | train | You forgot to add px to the top and left style property.
Change the code as below
ismile.style.top = topran + 'px';
ismile.style.left = leftran + 'px';
var numberOfFaces = 5;
var leftside = document.getElementById("leftside");
function generatefaces() {
for (i=0;i<=numberOfFaces;i++) {
ismile = document.createElement("img");
ismile.src = "http://orig00.deviantart.net/449c/f/2009/061/5/7/smiley_icon_by_emopunk23.jpg";
ismile.className = "smile";
var topran = Math.random() * 400;
topran = Math.floor(topran);
var leftran = Math.random() *400;
leftran = Math.floor(leftran);
ismile.style.top = topran + 'px';
ismile.style.left = leftran + 'px';
leftside.appendChild(ismile);
}
}
.smile {position:absolute}
div {position:absolute; width:500px;height: 500px}
#rightside {left:500px;border-left: 1px solid black}
<body onload="generatefaces()">
<h1> Matching Game </h1>
<p> click on the extra smiling face on the left </p>
<div id="leftside"></div>
<div id="rightside"></div>
</body> | unknown | |
d475 | train | You were nearly there!:
You just need to supply the package and class of the app you want.
// Try
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(new ComponentName("com.htc.Camera", "com.htc.Camera.Camera"));
startActivity(intent);
// catch not found (only works on HTC phones)
ComponentName
I also just saw you can do it a second way:
PackageManager packageManager = getPackageManager();
startActivity(packageManager.getLaunchIntentForPackage("com.skype.android"));
See: SOQ Ref | unknown | |
d476 | train | I speculate that you want logic something like this:
ON sp.sale_id = so.id and
(sp.origin = so.name and sp.state in ('done') or
sp.origin ilike 'Return%' and sp.state not in ('cancel', 'done')
) | unknown | |
d477 | train | There isn't direct metaspace information in a HPROF file.
Your might have a class loader leak or duplicate classes.
Try reading Permgen vs Metaspace in Java or
The Unknown Generation: Perm | unknown | |
d478 | train | You have not specified the type variable signUpCredentials to the useForm hook, and you should change the onSubmit handler to handleSignup and call the handleSubmit inside that. So, your code should look like this,
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { api } from "../../services/api";
export const Signup = () => {
const schema = yup.object().shape({
name: yup.string(),
email: yup.string(),
password: yup.string(),
address: yup.object().shape({
zipCode: yup.string(),
number: yup.number(),
complement: yup.string(),
})
})
interface signUpCredentials {
name: string
email: string
password: string
address: {
zipCode: string
number: number
complement: string
}
}
const {
register,
formState: { errors },
handleSubmit,
} = useForm<signUpCredentials>({
resolver: yupResolver(schema)
})
const handleSignup = handleSubmit(data: signUpCredentials) => {
console.log(data)
// do api stuff here
}
return (
<form
onSubmit={handleSignup}
>
<input
{...register("name")}
placeholder="name"
/>
<input
{...register("email")}
placeholder="email"
/>
<input
{...register("password")}
placeholder="password"
/>
<input
{...register("address.zipCode")}
placeholder="zipCode"
/>
<input
{...register("address.number")}
placeholder="number"
/>
<input
{...register("address.complement")}
placeholder="complement"
/>
<button type="submit" >
Submit
</button>
</form>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
For a better understanding, I created a Code Sandbox link where I have removed the import statement to services as we don't have that, and you can see the function is called without any warnings/errors by checking the console.
Ref: React Hook form (TS)
A: No need to change the onSubmit as mentioned by @sri-vineeth.
Just use SubmitHandler type.
const handleSignup: SubmitHandler<SignUpCredentials> = ({ address, email, name, password }) => {
...
}
Also please note that interfaces and types should use PascalCase. Therefore change signUpCredentials to SignUpCredentials. | unknown | |
d479 | train | You can use shadow element <if>, e.g.
<if test="@load(vm.yourFlag)">
<grid id="commentGrid">
....
</if>
please see http://books.zkoss.org/zk-mvvm-book/8.0/shadow_elements/flow_control.html
A: Do you mean commentGrid is created but inner window is hidden, so there is space inside commentGrid, right?
Since you specify emptyMessage on commentGrid, it should show no comments. Or there are still comments but all hidden? If so, you can consider hide both commentGrid with inner window. | unknown | |
d480 | train | So I found an overload that I can use which means I need to change the type of one of my parameters. This is the overload:
MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes);
This means I need to pass new { id } into a RouteValueDictionary like so:
helper.BeginForm("Edit", controllerName, new RouteValueDictionary(new { id }), FormMethod.Post, htmlAttributes.Attributes)
I could also pass a dictionary into the RouteValueDictionary, but not sure how marginal the performance difference would be. At any rate, this now works. | unknown | |
d481 | train | NoSuchElementException exception is throwed by in.next(), in list.add(new Task(in.next(),in.next(), in.hasNextBoolean())),.
and for in.next(), if you don't use any Pattern in Scanner to match the next token. it will use default Pattern private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*") to match whole line. it will cause in.next() will read whole line.
so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())) will throw NoSuchElementException, you have read twice but you only check once. | unknown | |
d482 | train | It turns out that you just copied this line:
bOk = tk.Button(frame,text="OK",command=root.destroy)
which binds a call to root.destroy() to the button press.
The fix is to just remove the command parameter:
bOk = tk.Button(frame,text="OK") | unknown | |
d483 | train | Just strip them out, you don't need them to generate the perms.
def create_perm(lst_str):
li = list(lst_str.replace('[','').replace(']',''))
for perm in itertools.permutations(li):
yield '[{}]'.format(''.join(perm))
demo:
list(create_perm('[1]2,'))
Out[102]: ['[12,]', '[1,2]', '[21,]', '[2,1]', '[,12]', '[,21]']
This uses itertools.permutations instead of recursively generating the perms.
A: Why can't you strip out the brackets, generate all permutations of the resulting string, then put the brackets around each result? | unknown | |
d484 | train | Regex
(?<=[a-z,;:] )([A-Z][a-z]+)
Demo
Output:
MATCH 1
1. [65-69] `Lord`
MATCH 2
1. [106-112] `Joseph`
MATCH 3
1. [121-126] `David`
MATCH 4
1. [160-164] `Mary`
MATCH 5
1. [221-225] `Holy`
MATCH 6
1. [226-232] `Spirit`
A: You can try
(?<![.!?;]) ([A-Z]\w+)
demo | unknown | |
d485 | train | Dumb me, i was trying to figure out what is wrong with the code this whole time when its just a simple problem.. i have two models with the same filename (backup project) and i blindly edits model file that is inside the backup project..
Perhaps for future readers seeking an answer, don't forget to check your folder path for your model file, you might make the same mistake as i did. | unknown | |
d486 | train | I had a similar issue where my program would coredump when there was a breakpoint present in a thread. I found out that my instance of gdb (12.0.9) was not working, and installing 12.1 from launchpad fixed my issue.
Found solution here | unknown | |
d487 | train | From this thread:
The IBM.WMQ is IBM's version of Neil Kolban's original work of
converting the Java classes for MQ to classes for the .NET framework.
The IBM.WMQAX is IBM's COM component for accessing MQ (ActiveX)
If you're coding in .NET, use IBM.WMQ since it's managed code. If
you're coding in VB6 or VC++ then use the ActiveX com component.
You could use the COM component from .NET using COM Interop, but that
really would only make sense, IF, the classes for .NET were NOT
available. Seeing that they are, use IBM.WMQ.
A: You need to use IBM.WMQ namespace for developing .NET applications to interact with IBM MQ Queue Manager. The other one, IBM.WMQAX namespace is for ActiveX applications.
A: This thread, linked in the answer by @stuartd contains some valuable information. While the part in his quote seems partially incorrect, additional comments in the thread do a better job clarifying. While I never used VB script or ActiveX, and thus don't quite follow the problem that the IBM.WMQAX namespace was looking to solve, I can ascertain from the discussion that the namespace should be avoided when writing a new .NET application from scratch. | unknown | |
d488 | train | To sum up, what you need is to:
*
*Get all personal sites
*Run Set-SPOSite for each of them using any mechanism like foreach
Here's helpful article for 1: Get a list of all user OneDrive URLs in your organization. So, you need to run something like:
$allSites = Get-SPOSite -IncludePersonalSite $true -Limit all -Filter "Url -like '-my.sharepoint.com/personal/'" | Select -ExpandProperty Url
And for 2. you can use something similar to:
foreach ($site in $allSites) {
Set-SPOSite -Identity $site -LockState NoAccess
}
A: Here's what I came up with to get all sites that are locked. It includes all information fields. Change the export path to a destination that's appropriate for you:
Get-sposite -includepersonalsite $true -Limit ALL -Filter "LockState -like 'NoAccess'" |Export-csv -Path 'C:\PowerShell\OneDriveSitesLocked.csv' -Delimiter ',' -NoTypeInformation | unknown | |
d489 | train | This looks like the JBoss 6.0 EJB3 implementation is dependent upon the version of Hibernate that you have removed.
Why don't you upgrade to JBossAS 7.x for JPA 2.0 support? | unknown | |
d490 | train | I think there can be at least 2 reasons for that:
*
*Your Web API application depends on some DB/storage and for some reasons there bigger latency when you run it on k8s.
*Probably you did not configure deployment limits/requests for CPU. | unknown | |
d491 | train | A LINQish way to do this (rather than just a LINQish way to write the for loop) is to pass the array on to each method and have it take what it needs and return the rest. You won't have the final index in hand, but you will have the remainder:
MyBase[] array = new MyBase[] { new Derived1() , new Derived2(), new Derived1()}
int [] input = new int[] { 1,2,3,4,5,6,7,8,9};
IEnumerable<int> unusedInputs = input;
foreach (MyBase entity in array)
{
unusedInputs = entity.ReadData(unusedInputs);
}
and your ReadData code goes like this:
public override IEnumerable<int> ReadData( IEnumerable<int> data)
{
a = data.Take(1).Single();
return Data.Skip(1);
}
public override IEnumerable<int> ReadData( IEnumerable<int> data)
{
var dataRead = data.Take(2);
a = dataRead.First();
b = dataRead.Skip(1).First();
return data.Skip(2);
} | unknown | |
d492 | train | This would work, if the syntax is supported by MySql, and might be slightly more efficient:
SELECT t1.c1, t2.c1, t.c1
FROM audits AS t1
INNER JOIN t2 ON t2.t1_id=t1.id
INNER JOIN (
select t1_id from t3
union
select t1_id from t4
) as t ON t.t1_id=t1.id
WHERE t2.fk1=123
ORDER BY t1.fk1 ASC
The reason for a pssible performance improvement is the smaller footprint of the relation being UNION'ed; one column instead of 3. UNION eliminates duplicates (unlike UNION ALL) so the entire collection of records must be sorted to eliminate duplicates.
At the meta-level this query informs the optimizer of a specific optimization available, that it may be unable to determine on it's own. | unknown | |
d493 | train | Use a Bounded Wildcard in your interface:
public interface Population<T extends Chromosome>{
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
}
public class TSPPopulation implements Population<TSPChromosome>
{
private List<TSPChromosome> chromosomes;
@Override
public void addChromosomes(List<TSPChromosome> chromosomes) {
...
}
@Override
public List<TSPChromosome> getChromosomes() {
...
}
}
A: The simplest solution is extending a list (then use addAll(...) to add a list of Chromosoms to the list):
class Population<T extends Chromosome> extends ArrayList<T> {
}
But if you want the same structure I would make Population into a generic list class. That way both add... and get... methods can be handled in the generic base class. If you do want to override any other feature you just extend Population (class TSPPopulation extends Population<TSPChromosome>.
Usage:
public static void main(String... args) {
Population<TSPChromosome> tspPopulation = new Population<TSPChromosome>();
...
}
Implementation:
class Population<T extends Chromosome> {
private List<T> chromosomes = new ArrayList<T>();
public void addChromosomes(List<T> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
public List<T> getChromosomes() {
return new ArrayList<T>(this.chromosomes);
}
}
A: It would be much safer if you made the Population generic itself:
public interface Population<T extends Chromosome> {
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
}
public class TspPopulation implements Population<TspChromosome>{
@Override
public void addChromosomes(List<TspChromosome> chromosomes){
//
}
@Override
public List<TspChromosome> getChromosomes(){
//
}
}
That way you would not need any casting in client code.
A: I know GAs, and I would question whether your Population implementation actually needs to know which kind of Chromosome you put in. Do you really have different Population implementations depending on the Chromosome subclass? Or what you really want is to make sure you have the same subclass of Chromosome in a Population? In this last case, you can define the Population interface as others suggested, and the make a generic implementation (or skip the interface altogether):
public class PopulationImpl implements Population<T extends Chromosome> {
private List<T> chromosomes;
@Override
public void addChromosomes(List<T> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
@Override
public List<T> getChromosomes() {
return new ArrayList<T>(chromosomes);
}
}
Be careful not to put too many generics, or you will end up with generics hell, or tons of casts which will make generics more annoying than useful.
A: Yes, for instance:
public interface Population<T extends Chromosome>
{
void addChromosomes(List<T> chromosomes);
List<T> getChromosomes();
// More code here ...
}
public class TSPPopulation implements Population<TSPChromosome>
{
private List<TSPChromosome> chromosomes;
@Override
public void addChromosomes(List<TSPChromosome> chromosomes) {
this.chromosomes.addAll(chromosomes);
}
@Override
public List<TSPChromosome> getChromosomes() {
return new ArrayList<TSPChromosome>(chromosomes);
}
} | unknown | |
d494 | train | Because you add .menu-open to the body, you need to apply the hover effect when the body doesn't have the class with :not.
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
$('.btn-menu').on('click', function() {
$('body').toggleClass('menu-open');
});
.btn-menu {
display: flex;
align-items: center;
justify-content: center;
min-height: 38px;
padding-left: 0;
padding-right: 0;
border: none;
background-color: transparent;
color: inherit;
cursor: pointer;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
position: relative;
width: 40px;
height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
transform: translate(0, -5px);
}
.btn-menu__bars:after {
transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
transform: rotate(-45deg);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-menu" type="button" style="background-color: red;">
<i class="btn-menu__bars" aria-hidden="true"></i>
</button>
Also your script without JQuery :
document.querySelector(".btn-menu").addEventListener("click", () => {
document.querySelector("body").classList.toggle("menu-open")
})
document.querySelector(".btn-menu").addEventListener("click", () => {
document.querySelector("body").classList.toggle("menu-open")
})
.btn-menu {
display: flex;
align-items: center;
justify-content: center;
min-height: 38px;
padding-left: 0;
padding-right: 0;
border: none;
background-color: transparent;
color: inherit;
cursor: pointer;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
position: relative;
width: 40px;
height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
transform: translate(0, -5px);
}
.btn-menu__bars:after {
transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
transform: rotate(-45deg);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
<button class="btn-menu" type="button" style="background-color: red;">
<i class="btn-menu__bars" aria-hidden="true"></i>
</button>
Note that if you only have 1 element with a class, you can use an id (and then use getElementById() instead). | unknown | |
d495 | train | Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs. | unknown | |
d496 | train | Find contour, find bounding rectangle, crop.
Here is example of finding bounding box: example | unknown | |
d497 | train | One simple approach to keep as close to your code as possible is to start off with an empty list called colors before entering your loop, and appending to that all the valid colors as you take inputs. Then, when you are done, you simply use the join method to take that list and make a string with the ':' separators.
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
else:
colors.append(color)
colors = ':'.join(colors)
print ("colors ", colors)
Demo:
please enter Color of your choice(To exit press No): red
please enter Color of your choice(To exit press No): blue
please enter Color of your choice(To exit press No): green
please enter Color of your choice(To exit press No): orange
please enter Color of your choice(To exit press No): No
colors red:blue:green:orange
A: You can concatenate a ':' after every input color
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
color += ':'
print ("colors ", color)
A: you're looking for str.join(), to be used like so: ":".join(colors). Read more at https://docs.python.org/2/library/stdtypes.html#str.join
A: Using a list is neat:
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color in ('No'):
break
colors.append(color)
print("colors ", ':'.join(colors)) | unknown | |
d498 | train | I traced out my problem. IE prevented changing of attribute which let to the jQuery error.
Note: jQuery prohibits changing the type attribute on an or element and
will throw an error in all browsers. This is because the type attribute
cannot be changed in Internet Explorer."
from http://api.jquery.com/attr, just after 1st warning notice.
So I changed my code from earlier
$('input').clone()
to
$('<input />').attr({'type':'hidden'})
and it solved my problem.
Thanks everyone.
A: Just a guess, but do you somewhere use $.error() inside your code? If yes: don't use it.
<edit>
However, this error comes from jQuery.error().
The original error-function looks like this:
error: function( msg ) {
throw msg;
}
You may test it without jquery:
(function( msg ) {
throw msg;
})('errormessage');
You'll get the same error.
If you don't use jQuery.error() maybe you use some plugin that uses it.
You may override this (buggy?) function by executing the following right after the embedded jquery.js:
jQuery.error=function(){}
</edit>
A: jQuery.error() (which throws the message passed as an argument), is totally different to the error handler specified in an AJAX call.
jQuery.error() is used internally by jQuery (search for "error("). You should debug your code and follow the stack trace to find which of your methods is calling the jQuery method which is erroring. | unknown | |
d499 | train | Could you see what happens (not sure here...) when you add a text-field xyz to the form and use a notes-url like notes://localhost/__A92574C800517FC7.nsf/company?OpenForm&xyz=something ? | unknown | |
d500 | train | You can use absolute positioning in the child div's
#foo {
display: table;
height: 400px;
position: relative;
width: 500px;
}
#foo > div {
display: table-cell;
height: 100%;
position: absolute;
}
#left {
background: blue;
left: 0;
right: 200px;
}
#right {
background: green;
right: 0;
width: 200px;
}
click here for demo
there are other methods of achieving the same effect such as changing the margins, I personally prefer the method above | unknown |