id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527400
|
String parm1 = MyXml.toString();
PostMethod post = new Postmethod(url);
post.setRequestEntity(new StringRequestEntity(parm1));
...
I have an object in the program which I want to convert it to xml representation.
My question is that what is the best way to create Myxml in xml format in java which then I can simply print out its String format later.
Thanks.
A: Here is how you can post xml request using Apache HttpClient.
*
*Use apache Velocity to create the request xml format
*Use Castor to convert response stream( respReader ) into java object
final String request = createXmlRequest(); // helper method to create the xml request
final HttpClient client = new HttpClient();
final PostMethod post = new PostMehod(url); // url - www.google.cm/someoperaion
post.setRequestHeader("Content-Language", "en-US");
post.setRequestEntity(new StringRequestEntity(request, "text/xml", "ISO-8859-1"));
final int returnCode = client.executeMethod(post);
final BufferedReader respReader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
A: There are many options for creating XML in Java. This answer How to serialize and de-serialize objects using JAXB? provides a good demo of one common way that seems to fit your use-case.
A: Try to use it this way...
public void postData() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.xyz.com");
List<NameValuePair> list = new ArrayList<NameValuePair>(1);
list.add(new BasicNameValuePair("name","ABC");
httppost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse r = client.execute(httppost);
}
| |
doc_23527401
|
I am trying to convert float test to a character from ASCII table.
float test = 42.5F;
char convertFloatToChar = Convert.ToChar(test);
Console.WriteLine(convertFloatToChar);
A: If you check the overload for Convert.ToChar() then you will see that the exception is logical. You cannot have a float/double in Convert.ToChar() method.
ToChar(Double)
Calling this method always throws InvalidCastException.
You are probably looking for
float test = 42.5F;
String convertFloatToChar = Convert.ToString(test);
Console.WriteLine(convertFloatToChar);
A: All you need is a string:
float test = 42.5F;
String convertFloatToString = Convert.ToString(test);
Console.WriteLine(convertFloatToString);
| |
doc_23527402
|
But what would be the best way to animate between three different states?
Consider as an example a loading indicator for a component. The states could be NotLoading, Loading and HasLoaded. My thinking here would be to have a loading indicator for a component and transition between those states:
*
*Transition for showing the loading indicator: NotLoading -> Loading
*Transition for showing the data: Loading -> HasLoaded
I guess what kind of transition doesn't really matter but I was thinking first fade in loading indicator then fade out loading indicator and fade in content. But this is just an example; in reality I need to specify the transition parameters.
What would be the best way to achieve this with Jetpack Compose? Not sure if my state thinking here is the best approach for this either.
A: You can use the Transition API with more than 2 states - and define the individual properties of each component using animate*AsState APIs.
There is another option if you have completely different Composables, you can use the AnimatedContent APIs.
For example, the below sample uses an enum UiState, and a button to change between the states. The content is then wrapped inside the AnimatedContent() composable. By default, the initial content fades out and then the target content fades in (this behavior is called fade through).
@Composable
fun AnimatedContentStateExample() {
Column {
var state by remember { mutableStateOf(UiState.Loading) }
Button(onClick = {
state = when (state) {
UiState.Loading -> UiState.Loaded
UiState.Loaded -> UiState.Empty
UiState.Empty -> UiState.Loading
}
}) {
Text("Switch States")
}
AnimatedContent(
targetState = state
) { targetState ->
// Make sure to use `targetState`, not `state`.
when (targetState) {
UiState.Loading -> {
CircularProgressIndicator()
}
UiState.Loaded -> {
Box(
Modifier
.background(androidGreen)
.size(100.dp))
Text("Loaded")
}
UiState.Empty -> {
Box(
Modifier
.background(androidBlue)
.size(200.dp))
Text("Empty")
}
}
}
}
}
You can customize this animation behavior by specifying a ContentTransform object to the transitionSpec parameter. You can create ContentTransform by combining an EnterTransition with an ExitTransition using the with infix function. You can apply SizeTransform to the ContentTransform by attaching it with the using infix function.
More information about AnimatedContent can be found here: https://developer.android.com/jetpack/compose/animation#animatedcontent.
And samples of its usage here: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/animation/animation/samples/src/main/java/androidx/compose/animation/samples/AnimatedContentSamples.kt
| |
doc_23527403
|
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate birthDate;
// getters and setters
on jsp page:
<tr>
<td><mvc:label path="birthDate">Birth Date</mvc:label></td>
<td><mvc:input path="birthDate" cssErrorClass="field-error"/></td>
<td><mvc:errors path="birthDate" /></td>
</tr>
So I what I expect from that:
*
*HTML5 rendering of the field, i.e. <input type="date" />
*Validation.
Basically if I had html5 date input, I would already have validation.
All I have now is just <input type="text" /> and if the date is malformed I got a bunch of exceptions on the page. So I am really confused, because there's cute pictures of html5 inputs on the internet while I got nothing.
So the question is how do I achieve all of that?
UPD
Seems like Spring 4 doesn't provide full support of LocalDate yet (according to Mert Caliskan's book). But still, if someone could come up with nice solution that would be greatly appriciated.
| |
doc_23527404
|
When I tried to get the user entered values in textboxes using SQ1.text it didn't work. How can I get the values entered in dynamically generated textboxes?
.aspx file
<div class="form-group inline clearfix"">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<asp:PlaceHolder ID="plhMainItem" runat="server"></asp:PlaceHolder>
</div>
</div>
.aspx.cs file
private void LoadData(bool postback)
{
List<String> qualifications = new List<String>();
qualifications.Add("Professional Qualifications");
qualifications.Add("Special qualifications");
qualifications.Add("Professional Experience");
for (int i = 0; i < qualifications.Count; i++)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "pnldefault" + i;
newControl.Attributes["Class"] = "panel panel-default";
HtmlGenericControl headraw = new HtmlGenericControl("div");
headraw.ID = "headRawDiv" + i;
headraw.Attributes["class"] = "panel-heading";
headraw.Attributes["role"] = "tab";
HtmlGenericControl bodyraw = new HtmlGenericControl("div");
bodyraw.ID = "bodyRawDiv" + i;
bodyraw.Attributes["class"] = "tbl-body row";
HtmlGenericControl nameraw = new HtmlGenericControl("div");
nameraw.ID = "nameRawDiv" + i;
nameraw.Attributes["class"] = "col-md-7 col-sm-4 col-xs-5 tproname";
HyperLink deslink = new HyperLink();
deslink.Attributes["data-toggle"] = "collapse";
deslink.Attributes["Class"] = "collapsed";
deslink.Attributes["data-parent"] = "#accordion";
deslink.Attributes["href"] = "#MainContent_detailsRawDiv" + i;
deslink.Attributes["aria-expanded"] = "true";
deslink.Attributes["aria-controls"] = "MainContent_detailsRawDiv" + i;
deslink.Text = qualifications[i];
nameraw.Controls.Add(deslink);
bodyraw.Controls.Add(nameraw);
headraw.Controls.Add(bodyraw);
newControl.Controls.Add(headraw);
HtmlGenericControl details = new HtmlGenericControl("div");
details.ID = "detailsRawDiv" + i;
details.Attributes["class"] = "panel-collapse collapse";
details.Attributes["role"] = "tabpanel";
details.Attributes["aria-labelledby"] = "MainContent_headRawDiv" + i;
HtmlGenericControl pnlBody = new HtmlGenericControl("div");
pnlBody.ID = "pnlBodyDiv" + i;
pnlBody.Attributes["class"] = "panel-body";
HtmlGenericControl tableBody = new HtmlGenericControl("div");
tableBody.ID = "tableBodyDiv" + i;
tableBody.Attributes["class"] = "tbl-body row";
HtmlGenericControl tableRawBody = new HtmlGenericControl("div");
tableRawBody.ID = "tableRawBodyDiv" + i;
tableRawBody.Attributes["class"] = "tproname";
HtmlGenericControl ul = new HtmlGenericControl("ul");
ul.ID = "lstDetails" + i;
if (qualifications[i] == "Professional Qualifications")
{
for (int j = 1; j <= 3; j++)
{
TextBox tb = new TextBox();
tb.ID = "PQ" + j.ToString();
tb.Attributes.Add("placeholder", "Professional Qualifications " + j.ToString());
tb.Attributes["class"] = "form-control";
tb.Height = 100;
ul.Controls.Add(tb);
}
}
else if (qualifications[i] == "Special qualifications")
{
for (int j = 1; j <= 3; j++)
{
TextBox tb = new TextBox();
tb.ID = "SQ" + j.ToString();
tb.Attributes.Add("placeholder", "Special qualifications " + j.ToString());
tb.Attributes["class"] = "form-control";
tb.Height = 100;
ul.Controls.Add(tb);
}
}
else if (qualifications[i] == "Professional Experience")
{
for (int j = 1; j <= 3; j++)
{
TextBox tb = new TextBox();
tb.ID = "PE" + j.ToString();
tb.Attributes.Add("placeholder", "Name of the work place " + j.ToString());
tb.Attributes["class"] = "form-control";
ul.Controls.Add(tb);
}
}
tableRawBody.Controls.Add(ul);
tableBody.Controls.Add(tableRawBody);
pnlBody.Controls.Add(tableBody);
details.Controls.Add(pnlBody);
newControl.Controls.Add(details);
plhMainItem.Controls.Add(newControl);
}
}
A: You can use FindControl on plhMainItem to get the TextBoxes with ID
int index = 1;
TextBox tb = null;
do
{
tb = plhMainItem.FindControl("SQ"+i++) as TextBox;
if(tb != null)
{
// You can access the value of TextBox using Text property, tb.Text
}
} while(tb != null)
A: One way is to direct use the Request.Form that get's all posted data from the page. To make it work you need also to add the name on the control.
Here is how you can do it.
TextBox tb = new TextBox();
tb.ID = "PQ1" ;
// need to add the name, so later to get the post back using that.
tb.Attributes["name"] = "PQ1";
tb.Attributes.Add("placeholder", "Professional Qualifications 1" );
tb.Attributes["class"] = "form-control";
tb.Height = 100;
if (IsPostBack)
txtDebug.Text = "Value is: " + Request.Form["PQ1"];
| |
doc_23527405
|
setTimeout(function() {
alert("Now I am free");
}, 3000);
Or I could make it fire on document ready...
jQuery(document).ready(function ($) {
setTimeout(function() {
alert("Now I am free");
}, 3000);
});
What is the difference between these two approaches? Which is better?
A: The first approach (just set a delay) has a timing hole in it: the timer could go off before the page has finished loading.
You may consider this unlikely, and it may be unlikely on your system. But consider the visitor whose device has marginal memory capacity, continuous memory faults are occurring because the OS is trying to update itself at the same time as 15 open tabs in the web browser are trying to do background AJAX calls, and the browser is showing "not responding" across the top. And, say, the browser takes another 30 seconds to start responding again. This is not a fictitious, scenario.
Using the document ready mechanism to start the timer guarantees the DOM can be manipulated by call back code when the timer goes off. You could also add an event listener to window "load" event to do the same thing in plain vanilla JavaScript.
Starting the timer in a script block right at the end of the <body> section may also remove the risk of the timer going off too early.
| |
doc_23527406
|
I accidentally copy and delete two different list of emails. The emails did not move to trash folder but deleted permanently. Is there any way that I can recover those emails?
| |
doc_23527407
|
here is the code:
<html>
<head>
<title>LogIN</title>
<script>
function verify()
{
var xml;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xml=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xml=new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange=function()
{
if (xml.readyState==4 && xml.status==200)
{
var res=xml.responseText();
if(res.equals("0"))
{
document.write("zero");
}
else
{
document.write("one");
}
}
else
document.write("Not connected");
}
xml.open("GET", "log_verify.txt", true);
xml.send();
}
function login()
{
//action to login
}
</script>
</head>
<body>
<form>
User name : <input type="text" name="uname" onblur="verify()">
<br>
Pwd : <input type="password" name="passwd" >
<br>
<input type="button" name="Login" value="Login" onclick="login()">
</form>
</body>
</html>
Getting the output as
Not connectedNot connectedNot connected
but when i just display the response text it gets printed correctly as per the code below
<html>
<head>
<title>LogIN</title>
<script>
function verify()
{
var xml;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xml=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xml=new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange=function()
{
if (xml.readyState==4 && xml.status==200)
{
document.getElementById("myDiv").innerHTML+=xml.responseText;
}
}
xml.open("GET", "log_verify.txt", true);
xml.send();
}
function login()
{
//action to login
}
</script>
</head>
<body>
<form>
User name : <input type="text" name="uname" onblur="verify()">
<br>
Pwd : <input type="password" name="passwd" >
<br>
<input type="button" name="Login" value="Login" onclick="login()">
</form>
<div id="myDiv"><h2>Response text:</h2></div>
</body>
</html>
Getting the output as
Response text:
0
is the problem in javascript coding or somewhere in server response??
A: Problem #1
In the first snippet you wrote xml.responseText(), which causes the script to terminate.
In the second snippet you got it right, and wrote xml.responseText. It's a text property, not a function.
Problem #2
Regarding the "Not Connected" messages, there is no problem.
You have assumed that, when onreadystatechange is fired, (xml.readyState==4 && xml.status==200) if connected and the opposite if not connected.
But this is not true.
During an XMLHttpRequest's lifetime, if a connection succeeds, onreadystatechange fires multiple times, tracking the various states of the object as the request proceeds.
These states (which lend their values to .readyState) are listed under section 3.5 of the relevant W3C spec:
*
*UNSENT (numeric value 0)
The object has been constructed.
*OPENED (numeric value 1)
The open() method has been successfully invoked. During this state
request headers can be set using setRequestHeader() and the request
can be made using the send() method.
*HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of
the final response have been received. Several response members of the
object are now available.
*LOADING (numeric value 3)
The response entity body is being received.
*DONE (numeric value 4)
The data transfer has been completed or something went wrong
during the transfer (e.g. infinite redirects).
You use the conditional to perform your code only when the object enters the DONE state, not because any other state indicates failure.
The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.
If you want to look for this failure, check the .state property, which has the following possible values:
*
*If the state is UNSENT or OPENED return 0 and terminate these
steps.
*If the error flag is true return 0 and terminate these steps.
*Return the HTTP status code.
So:
xml.onreadystatechange = function() {
if (xml.readyState != 4) { // handle DONE only
return;
}
if (xml.status == 0) { // error
document.getElementById("myDiv").innerHTML += "Connection error"
}
else if (xml.status == 200) { // HTTP 200 OK
document.getElementById("myDiv").innerHTML += xml.responseText;
}
else { // some other HTTP code
document.getElementById("myDiv").innerHTML += "HTTP response code " + xml.status;
}
}
A: First,
else
document.write("Not connected");
is executed whenever the state changes and it the statusses aren't 4 and 200. It does not necessarily mean Not connected. You could just remove that part. You are currently seeing it three times as the status changes from 0 to 1 to 2 to 3 (and 4 but that doesn't go to the else).
Secondly, you are using .equals but this function is not natively available and you also don't have it defined. Are you looking for:
if(res == "0")
== is the equality operator. And,
res = xml.responseText;
it is not a function so you should not append ().
| |
doc_23527408
|
I can find it in ES5, but no mention of it in ES6.
A: It appears that [[Scope]] has been replaced by [[Environment]] in ES2015. Section 9.2.4 (FunctionInitialize) states:
*Set the [[Environment]] internal slot of F to the value of Scope.
whereas ES5 says this in section 13.2 (Creating Function Objects):
*Set the [[Scope]] internal property of F to the value of Scope.
| |
doc_23527409
|
That my code in Controller:
public function actionDelete($id)
{
$model = $this->loadModel($id);
if (Posts::model()->countByAttributes(['category_id' => $model->id]) == 0) {
$model->deleted = 1;
$model->update();
}
if (!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
Now I just want if Post have any category, it will show popup cannot delete this Post.
Any solutions about this?
A: Ugh... usualy you would add errors in the validator. Honestly that is the best advice... well the Yii way. You could just check if $_POST is set, mass assign $_POST to $model->attributes and then let model worry about validation. What I would do next is write a custom but simple validation function in the model that would check if there are categories for said model and if yes return true, otherwise false. Then you would just do:
if($model->validate())
{
$model->delete = 1;
if($model->update)
{
// do whatever you wanna do redirect/render...
}
else {
Yii::app()->user->setFlash('error', "Unable to delete post");
// render or redirect... flash is more for redirect but it'll do the trick
}
}
This would solve the backend of it. In the view file you need to display this flash. In the view that you render if it's not deleted add this piece of code:
<?php if(Yii::app()->user->hasFlash('error')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('error'); ?>
</div>
<?php endif; ?>
I would do it this way... you can do whatever you want to do
| |
doc_23527410
|
@property(nonatomic,assign)UIViewController* firstController;
in my SecondViewController.h class. Furthermore, I wrote the code bellow in the viewDidLoad part of my SecondViewController.m class (where I want the function to be called).
secondViewController = [[SecondViewController alloc] initWithNibName:@"secondViewController" bundle:nil];
secondViewController.firstController = self;
[self.firstController performSelector:@selector(sendDataToMotor)];
But, Im getting an error with the first word in that code (secondViewController) because of an undeclared identifier issue. Furthermore, I get an error with the second line (secondViewController.firstController = self) because secondViewController has an unknown name type.
In summary, I don't care if you use the above code to answer my question: that was just something I tried to implement that I found online. However, I'm looking for the simplest way to call a function from another View Controller.
A: Notification Center could be solution to you question.
Receiver UIViewController
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveNotification:)
name:@"myNotification"
object:nil];
}
- (void)receiveNotification:(NSNotification *)notification
{
if ([[notification name] isEqualToString:@"myNotification"]) {
//doSomething here.
}
}
Sender UIViewController
- (void)sendNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self];
}
A: You want to use the delegate pattern, and you are almost there.
This line in secondVC:
@property(nonatomic,assign)UIViewController* firstController;
should be generalised so as not refer to a specific type
@property(nonatomic,weak)id <delegateProtocol> delegate;
And you should accompany that with a protocol declaration in the header of your secondVC (above the @interface declaration), something like
@protocol SecondVCDelegate
- (void) sendDataToMotor;
@end
In firstVC interface you can declare your adherence to the delegate protocol in the first line of the @interface declaration in the header file
@interface firstVC < SecondVCDelegate >
Or in the first line of a private interface declaration in the .m file
@interface firstVC() < SecondVCDelegate >
Then you won't need to use performSelector (which anyway should be preceded by a safety check) as the compiler will alert you of errors.
In firstVC after creating secondVC, set it's delegate property to self(i.e. firstVC)
secondVC.delegate = self;
then in secondVC you can just call the method directly on it's delegate:
[self.delegate sendDataToMotor];
I explain this in more (wordy) detail here...
https://stackoverflow.com/a/14910469/1375695
A: There are many problems in your code. I'm going to assume the second chunk of code you included is actually in -viewDidLoad in FirstViewController not the second.
*
*The error you're getting is because you aren't putting the type before secondViewController. It should be SecondViewController *secondViewController = ...
*This probably still won't work for you because when you perform your transition to the second view controller, you won't be using the same object.
| |
doc_23527411
|
I tried the following
<html>
<body>
<script src="http://www.ajax.googleapis.com/ajax/libs/jquery/1.11.1/qjuery.min.js">
</script>
<script>
function makeRed() {
$("tr#oneX").attr("background-color","red");
}
</script>
<table>
<tr id="oneX"><td>test1</td></tr>
<tr id="twoX"><td>test2</td></tr>
<button onclick="makeRed()">Make Red</button>
</table>
</body>
</html>
But can't make it work
A: You have a couple of typos in your code: check your script tag with jquery, background-color and use $().css instead of attr
see the working plunker
http://plnkr.co/edit/uTgnzeU7xmBBGRZxuUZf?p=preview
<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function makeRed() {
$("tr#oneX").css("background-color","red");
}
</script>
<table>
<tr id="oneX"><td>test1</td></tr>
<tr id="twoX"><td>test2</td></tr>
<tr><td><button onclick="makeRed()">Make Red</button></td></tr>
</table>
</body>
</html>
A: Try this.
<html>
<body>
<script src="http://www.ajax.googleapis.com/ajax/libs/jquery/1.11.1/qjuery.min.js">
</script>
<script>
function makeRed() {
$("#oneX").css({"background-color","red"});
}
</script>
<table>
<tr id="oneX"><td>test1</td></tr>
<tr id="twoX"><td>test2</td></tr>
<button onclick="makeRed()">Make Red</button>
</table>
</body>
</html>
| |
doc_23527412
|
<StackPanel Orientation="Horizontal" Margin="3, 10">
<ComboBox x:Name="Agencies" DisplayMemberPath="Name" SelectedValuePath="Value"
SelectedItem="{Binding SelectedAgency}"
Height="50" MinWidth="100" Margin="3,0"/>
<Button x:Name="UploadFile"
MinWidth="70"
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
attachProperties:ButtonIcon.Icon="Resources/Images/add.png"
Content="Upload File" IsEnabled="{Binding EnrollmentFiles.Any}"
Style="{StaticResource ImageButtonStyle}" />
<Button x:Name="EnrollmentDelete"
MinWidth="70"
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
attachProperties:ButtonIcon.Icon="Resources/Images/Remove.png"
Content="Delete Enrollment" IsEnabled="{Binding EnrollmentFiles.Any}"
Style="{StaticResource ImageButtonStyle}" />
<TextBox x:Name="WorkSheetName" />
</StackPanel>
A: You need to set the VerticalAlignment on your ComboBox and TextBox to something like Center. By default it's set to Stretch
<TextBox VerticalAlignment="Center" ... />
| |
doc_23527413
|
<p>Some text, <a data-special="special-link" href="link.com">Needs to stay</a> more text <br /> more tags, <a href="link.com">Needs to go</a>
I tried this, did not match anything
preg_replace('#<a (?![^>]data-special="special-link") .*?>(.*?)</a>#i', '\1', $result["body_value"]);
A: It is best practice to use DOM or other HTML parsers to manipulate HTML code.
Since your input string does not seem to be a valid XHTML, you can use the basic DOM parser to remove the links you do not need:
$html = <<<DATA
<p>Some text, <a data-special="special-link" href="link.com">Needs to stay</a> more text <br /> more tags, <a href="link.com">Needs to go</a>
DATA;
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$links = $xpath->query('//a');
foreach($links as $link) {
if ($link->getAttribute('data-special') == "special-link")
{
$newTxtNode = $dom->createTextNode($link->textContent);
$link->parentNode->replaceChild($newTxtNode, $link);
}
}
echo $dom->saveHTML();
See IDEONE demo
This will replace <br /> with <br>, but I guess that is OK for this scenario.
A: Just for your case: to remove all links from string excepting those which have attribute data-special="special-link" use the following approach:
$str = '<p><a href="link.com">Needs to go first </a> Some text, <a data-special="special-link" href="link.com">Needs to stay</a> more text <br /> more tags, <a href="link.com">Needs to go</a>';
$res = preg_replace('/<a (?![^>]*data-special="special-link").*?>(.*?)<\/a>/i', '', $str);
| |
doc_23527414
|
<tr class="last"><td class="summaryitem"><a href="javascript:OpenRebatesWindow('/shop/Phones/PhonePricingRebates.aspx?action=devicepromo&device=60c0ca0d-b68d-4edd-b667-0d4320b60ede');">Web-only discount</a></td><td class="summaryprice">-$79.99</td></tr>
How to Append "you save" below the table and adding the two costs $200+$79.99) in jQuery.
A: var sum = 0;
$(".summaryprice").each(function(){
sum += getSum(this.html()); // I'm not sure this or $(this) try both
});
function getSum(ammountString){
var t = ammountString.split('-$');
return parseFloat(t[1]);
}
A: var prices = $(".summaryPrice").map(function() {
return parseFloat($(this).text().replace("-$", ""));
}).get();
for(var sum = 0, i = prices.length; i; sum += prices[--i]);
$("#theTable").after("<p>You save " + sum + "</p>");
Demo.
| |
doc_23527415
|
SELECT
1 AS tag,
null AS parent,
row_num AS [enc_obj!1!row_num]
FROM
sa_rowgenerator(1, 2)
ORDER BY
3
FOR JSON EXPLICIT;
I get this as a result, an array of separate arrays for every row:
[
{
"enc_obj": [
{
"row_num": 1
}
]
},
{
"enc_obj": [
{
"row_num": 2
}
]
}
]
How do I modify the query to get single array with all rows in it, like this:
{
"enc_obj": [
{
"row_num": 1
},
{
"row_num": 2
}
]
}
Any ideas?
A: You can simply omit the enc_obj criterium from the json directive:
SELECT
1 AS tag,
null AS parent,
row_num AS [!1!row_num] -- NOTE: "enc_obj" is dropped!
FROM
sa_rowgenerator(1, 2)
ORDER BY
3
FOR JSON EXPLICIT;
As result you'll get an anonymous JSON array without an encapsulating object:
[
{
"row_num": 1
},
{
"row_num": 2
}
]
Can you work with that?
| |
doc_23527416
|
Below is my code and its not working as expected, please help my pointing out my mistake:
SET A REPEATING ALARM
private static void initiateMidnightAlarm(Context context, AlarmManager alarmManager) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent midnightIntent = PendingIntent.getService(context, 0,
new Intent("com.alarms.MidnightProcess"), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, midnightIntent);
}
DECLARE THE RECEIVER IN THE MANIFEST:
<receiver
android:name=".receivers.MidnightProcessReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.alarms.MidnightProcess"/>
</intent-filter>
</receiver>
RECEIVER CODE:
public class MidnightProcessReceiver extends BroadcastReceiver {
public MidnightProcessReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
processMidnightLogic(context);
}
public static void processMidnightLogic(Context context) {
Toast.makeText(context,"MidnightProcessReceiver",Toast.LENGTH_LONG).show();
}
}
UPDATE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appname">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<permission
android:name="com.appname.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.appname.permission.C2D_MESSAGE"/>
<application
android:name=".BaseApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
.
.
..
..
</activity>
<receiver
android:name=".receivers.MidnightProcessReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.alarms.MidnightProcess"/>
</intent-filter>
</receiver>
<receiver
android:name=".receivers.OnBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
Please help!
Thanks in advance.
A: Since you need to fire an implicit broadcast, rather than start a Service, you're retrieving the wrong type of PendingIntent. Change:
PendingIntent midnightIntent = PendingIntent.getService(context, 0,
new Intent("com.alarms.MidnightProcess"), 0);
to:
PendingIntent midnightIntent = PendingIntent.getBroadcast(context, 0,
new Intent("com.alarms.MidnightProcess"), 0);
| |
doc_23527417
|
From what I understand I should be able to just clone it to HTDOCS and it should work if all the dependencies are installed.
I get this error message when I visit the project folder in my browser.
Fatal error: Uncaught Error: Call to a member function init() on null
in C:\xampp\htdocs\sandbox\craft\app\services\CacheService.php:114
Stack trace: #0
C:\xampp\htdocs\sandbox\craft\app\framework\base\CModule.php(394):
Craft\CacheService->init() #1
C:\xampp\htdocs\sandbox\craft\app\etc\web\WebApp.php(595):
CModule->getComponent('cache', true) #2
C:\xampp\htdocs\sandbox\craft\app\framework\base\CModule.php(103):
Craft\WebApp->getComponent('cache') #3
C:\xampp\htdocs\sandbox\craft\app\services\ConfigService.php(392):
CModule->__get('cache') #4
C:\xampp\htdocs\sandbox\craft\app\services\HttpRequestService.php(1181):
Craft\ConfigService->usePathInfo() #5
C:\xampp\htdocs\sandbox\craft\app\services\HttpRequestService.php(131):
Craft\HttpRequestService->getNormalizedPath() #6
C:\xampp\htdocs\sandbox\craft\app\framework\base\CModule.php(394):
Craft\HttpRequestService->init() #7
C:\xampp\htdocs\sandbox\craft\app\etc\web\WebApp.php(595):
CModule->getComponent('request', true) #8
C:\xampp\htdocs\sandbox\craft\app\framework\base\CMo in
C:\xampp\htdocs\sandbox\craft\app\services\CacheService.php on line
114
I know this a vague question but I'd appreciate any help.
Thank you
A: I think once you will clone the craft project from your git repo. You need to add .Env file into it. Then your need "uploads" folder. Also you should run the composer install command to install all the dependencies.
After all this process if you still getting the same error then you should try to remove cache from your runtime cache folder and also you can remove compiled classes and templates once.
I hope this will work.
| |
doc_23527418
|
The class extends a generic "protocol" class, which contains the input processing thread, which calls the function for handling received messages. Originally, I was automatically starting the processing thread in the constructor of the generic class, which turned out to be a terribly stupid idea:
*
*The subclass called the super constructor
*The super constructor started the thread
*The thread immediately called the message handling method with an empty message (to make it send the first message in the protocol). The method set a "sent message counter".
*On the main thread, the super constructor returned, and the subclass initialized the set message counter, resetting it to zero.
I have now changed it by moving the starting of the processing thread to another method and calling it at the end of the constructor of the subclass:
public ProtocolSubclass() {
super();
startProcessingThread();
}
I assume that when I call startProcessingThreads(), the field is guaranteed to be initialized. After startProcessingThread() is called, the field will only be accessed from that thread. Can I do this? Do I need to mark the field volatile, since it gets initialized on the main thread but read on the processing thread?
I think I got it right this time, but after hours of debugging the above-mentioned issue, I'd rather ask...
As requested, here is slightly more detailed (still simplified) code. Note that the code above is much more simplified and thus may not exactly match the code below. The field that was acting up was currentMsg:
public abstract class ProtocolConnection {
public ProtocolConnection(/*stuff*/) {
/*stuff*/
// DO NOT DO THIS HERE: startProcessingThreads();
}
protected void startProcessingThreads() {
inputProcessingThread.start();
}
private final Thread inputProcessingThread = new Thread() {
public void run() {
if (isInitiator) initiateConnection();
while (!closed && !finished) {
ProtocolMessage msg = new ProtocolMessage(inputStream);
log("received", Integer.toString(msg.tag), Integer.toString(msg.length));
ProtocolConnection.this.processMessage(msg);
}
}
};
}
public class SimpleProtocolConnection extends ProtocolConnection {
private int currentMsg = 0;
public SimpleProtocolConnection(/*stuff*/) {
super(/*stuff*/);
startProcessingThreads();
}
@Override
protected void processMessage(ProtocolMessage msg) {
if (msg.tag != LAST_MESSAGE) {
sendNext();
}
}
@Override
protected void initiateConnection() {
sendNext();
}
private void sendNext() {
addToSendingQueue(new ProtocolMessage(currentMsg, getData())); // very simplified
currentMsg++;
}
}
A: The field is initialized in thread 1; then thread 2 is started; then thread 2 exclusively accesses the field. Correct? If so, then...
Volatile/atomic is not needed.
Based on the JLS, an action performed in some thread A before thread B was started is visible to thread B. This is stated in a few different ways:
17.4.2. Actions
An inter-thread action is an action performed by one thread that can
be detected or directly influenced by another thread. There are
several kinds of inter-thread action that a program may perform:
[...]
Actions that start a thread or detect that a thread has terminated
(§17.4.4).
--
17.4.4. Synchronization Order
Every execution has a synchronization order. A synchronization order
is a total order over all of the synchronization actions of an
execution. For each thread t, the synchronization order of the
synchronization actions (§17.4.2) in t is consistent with the program
order (§17.4.3) of t.
Synchronization actions induce the synchronized-with relation on
actions, defined as follows:
[...]
An action that starts a thread synchronizes-with the first action in
the thread it starts.
--
17.4.5. Happens-before Order
Two actions can be ordered by a happens-before relationship. If one
action happens-before another, then the first is visible to and
ordered before the second.
[...]
A call to start() on a thread happens-before any actions in the
started thread.
A: volatile means that a particular field will me modified by different threads. It is not needed if the constructor is marked synchronized, otherwise it is needed.
| |
doc_23527419
|
The difficult part was to instruct AutoHotKey to hold down the mouse button while holding down the key on the keyboard. So you be able to click and drag.
It makes the clicks with the 1, 2 and 3 keys at the keyboard, in inverse order (left click with the 3, as preserving left click with the index finger but of the other hand, trying to mirror the workings inside the brains hemisphere, or something)
This script is activated while ScrollLock is ON (finally some good use for that beautiful and neglected key, activating all sorts of keyboard shortcuts for AutoHotKey)
A: #NoTrayIcon
if (GetKeyState("ScrollLock", "T")) ; check state for icon
{
Menu, Tray, Icon
return
}
else
{
Menu, Tray, NoIcon
return
}
ScrollLock:: ; From state 0 to state 1 (Activated)
Send, {ScrollLock}
Menu, Tray, Icon
SoundBeep, 261.43, 150 ; low tone
SoundBeep, 329.63, 150 ; hight tone
return
#If GetKeyState("ScrollLock", "T") ; State 1 (Activated)
3::
While GetKeyState("3", "P")
{
Click, Left, Down
KeyWait 3
Click, Left, Up
}
Return
2::
While GetKeyState("2", "P")
{
Click, Middle, Down
KeyWait 2
Click, Middle, Up
}
Return
1::
While GetKeyState("1", "P")
{
Click, Right, Down
KeyWait 1
Click, Right, Up
}
Return
ScrollLock:: ; From State 1 to State 0 (Deactivated)
Send, {ScrollLock}
Menu, Tray, NoIcon
SoundBeep, 329.63, 150 ; hight tone
SoundBeep, 261.43, 150 ; low tone
return
^SPACE:: ; Always on Top Functionality
Winset, Alwaysontop, , A
return
#If
Script: Keyboard-Clicks.ahk
It gets activated with the ScrollLock key.
It shows the a tray icon when activated.
It hides the icon when is deactivate it with ScrollLock key again.
Key combination Ctrl+Space for AlwaysOnTop the currently active window.
It makes a distinctive sound beep for activated and de-activated state.
Compiled with an icon from Font Awesome of a hand.
Font-Awesome-left-hand-paper Icon PNG with Transparency
https://i.imgur.com/6tvfVNS.png
| |
doc_23527420
|
-(void) polygons:(MKMapRect)fullRect exclude:(MKMapRect)excludeArea{
NSLog(@"Y is: %f height: %f",excludeArea.origin.y,excludeArea.size.height);
double top = excludeArea.origin.y - fullRect.origin.y;
double lft = excludeArea.origin.x - fullRect.origin.x;
double btm = (fullRect.origin.y + fullRect.size.height) - (excludeArea.origin.y + excludeArea.size.height);
double rgt = (fullRect.origin.x + fullRect.size.width) - (excludeArea.origin.x + excludeArea.size.width);
double ot = fullRect.origin.y, it = (ot + top);
double ol = fullRect.origin.x, il = (ol + lft);
double ob = (fullRect.origin.y + fullRect.size.height), ib = (ob - btm);
double or = (fullRect.origin.x + fullRect.size.width), ir = (or - rgt);
MKMapPoint points[11] = {{ol,it}, {ol,ot}, {or,ot}, {or,ob}, {ol,ob}, {ol,it}, {il,it}, {ir,it}, {ir,ib}, {il,ib}, {il,it}};
MKPolygon *polygon = [MKPolygon polygonWithPoints:points count:11];
}
And my question is now how do I get the minimum number of MKMapRects from this MKPolygon? I have done some googling as well as looking through the forum but havn't found anything.
EDIT:
So the goal is the following:
I have a MKMapRect rect1, then I have a list of rectangles, rectList, which is MKMapRects intersecting with rect1 and what I want to do is create a rectilinear MKPolygon of rect1, remove the surface of all MKMapRects in rectList from rect1 and then create the minimum number of MKMaprects from the created rectilinear MKPolygon.
Right now the problem is the following: I am able to create a polygon when removing one MKMapRect from rect1 but I dont know how to remove the following maprects from rect1 and I dont know how to extract the minimum set of MkMapRects from the polygon created.
Best regards
Peep
A: I'm not sure if this is what you're looking for or if I understand the question fully, but if all you need to know is the minimum number of rectangles in a polygon that's created by subtracting one rectangle from another you should be able to do it by checking the number of corner points in the second rectangle that are contained in the first rectangle. In pseudo code:
int minNumRects(MKRect r1, MKRect r2) {
int numPointsContained = 0;
for (Point p in r2) {
if (MKMapRectContainsPoint(r1, p)) {
numPointsContained++;
}
}
if (numPointsContained == 1) {
return 2;
} else if (numPointsContained == 2) {
return 3;
} else if (numPointsContained == 4) {
return 4;
} else {
return 0;
}
}
P.S. - This assumes that the rectangles are axis-aligned but as far as I know that's the case with MKRects
| |
doc_23527421
|
*
*The first attempt was to switch this project to a maven project and try the 'update maven configuration'. (No go in fact this makes things worse as my stack trace shows several Bean definitions missing.)
*Second attempt was to remove all the tomcat instances and create new instances and making sure the deployment assembly had all my .M2 Repo jars included. No go.
Stack trace as of now.
Sep 15, 2012 10:07:09 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: .:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java
Sep 15, 2012 10:07:09 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Dugsi_Manager' did not find a matching property.
Sep 15, 2012 10:07:10 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 15, 2012 10:07:10 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 15, 2012 10:07:10 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1046 ms
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /Users/warz07/Documents/workspace-sts-2.8.0.RELEASE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Dugsi_Manager does not exist or is not a readable directory
at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:140)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4814)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4994)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.startup.Catalina.start(Catalina.java:620)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:431)
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
Sep 15, 2012 10:07:10 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Dugsi_Manager] startup failed due to previous errors
Sep 15, 2012 10:07:10 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 15, 2012 10:07:10 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 15, 2012 10:07:10 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 374 ms
A: *
*First: You need to make sure that Eclipse compiles the files! -- You can check it: if there is a WAR file, then the compilation process seams to work.
*Second: Make sure that the depoyment process works: Clean the Server and Publish the Project, then start the Server
| |
doc_23527422
|
Just wanted to make a simple login program as I am a beginner but stuck on this error.
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Umer\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From dbo.Table where Username='" + textBox1.Text + "'and password ='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
The problem is in sda.Fill(dt);. It says:
SqlException occurred Incorrect syntax near the keyword 'Table'
It says SqlException occurred Incorrect syntax near the keyword 'Table'
This is the picture of my code. Hope i will will get the answer. Thanks
A: There is missing space between the single cuote and the 'and' keyword
... textBox1.Text + "'and ...
BTW, to avoid SQL injection (and application errors in passwords containing quotes) you should also use parameters as Mike Schmidt suggested.
A: This assumes you have the correct Table in your sql database you are referencing.
The Table name is "Table" and it has two columns "Username" and "Password"
Comments
*
*Your Sql statment is going to return the number of rows that have the username and password that match.
*Passing parameters like that is dangerous and subject to hidden sql utilize the sqlParameter class
*You should break out parameters and such for ease of reading.
String ConnectionString = @"DataSource=LocalDB)\v11.0;AttachDbFilename=C:\Users\Umer\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;";
String QueryString = @"Select Count (*) From dbo.Table where Username= @Username and Password = @Password";
SqlParameter[] Parameters = {new SqlParameter("Username",textBox1.text)
,new SqlParameter("Password",textBox2.text)};
SqlConnection sqlConnection = new SqlConnection(ConnectionString);
SqlCommand sqlCommand = new SqlCommand(QueryString, sqlConnection);
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.AddRange(Parameters);
int nCount;
if (int.TryParse(sqlCommand.ExecuteScalar().ToString(), out nCount))
{
//nCount has valid value
}
else
{
//nCount has invalid value
}
| |
doc_23527423
|
I used the below code to no effect
flow do
###
para link("some text", click: proc {
visit "https://google.com"
})
###
end
And
flow do
###
para link "some text" do visit "https://google.com" end
###
end
Could someone show me how please?
A: Try this
flow do
para(link("some text", :click => "https://google.com"))
end
A: Fixed the link using the method provided on this question
flow do
proc = Proc.new {
system("cmd /c start https://google.com")
}
para link("some text", &proc)
end
Any further suggestions before I close this is welcome.
| |
doc_23527424
|
I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks
$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...
A: Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL.
The alternative is to just split the string by / and get last element.
EDIT: The example on how to retrieve UUID from the URI:
var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';
var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];
url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0], as in the example).
Proof: http://jsfiddle.net/p6zud/2/
EDIT 2: Shortened the pattern used for matching (see revision history for comparison).
A: If the id is always going to be the last section of the URI, you could do something like
var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];
A: using split, convert the url to an array of parameters. Then last array item in your case would be your ID.
there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
A: Try this
alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);
A: The simpliest:
var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];
Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d;
| |
doc_23527425
|
I more expected the app to start up as Landscape Left and be able to rotate to Landscape Right and then won't be able to rotate to any other orientation. I wonder what caused the above behavior?
| |
doc_23527426
|
into which the value was entered/last used sheet
Private Sub Zamknij_Click()
UserForm1.Hide
Worksheets("SheetName").Activate
End Sub
Private Sub Sheet1_Click()
Sheets(1).Cells(1, 1).Value = TextBox1.Value
End Sub
Private Sub Sheet2_Click()
Sheets(2).Cells(1, 1).Value = TextBox1.Value
End Sub
Private Sub Sheet3_Click()
Sheets(3).Cells(1, 1).Value = TextBox1.Value
End Sub
A: Putting my comments into code: Here is one possible way to implement what I think it is you're trying to do.
Private Sub Zamknij_Click()
Unload Me
End Sub
Private Sub Sheet1_Click()
ApplyToSheet Worksheets(1)
End Sub
Private Sub Sheet2_Click()
ApplyToSheet Worksheets(2)
End Sub
Private Sub Sheet3_Click()
ApplyToSheet Worksheets(3)
End Sub
Sub ApplyToSheet(wsSheet As Worksheet)
With wsSheet
.Activate
.Cells(1, 1) = TextBox1.Value
End With
End Sub
The above will show the target and then write TextBox1.
If you need to keep another or the current sheet visible until Zamknij is clicked, here is another approach:
Option Explicit
'At the top of the userform (before any subs): Declare a module-level variable
Private mwsTarget As Worksheet
Private Sub Zamknij_Click()
mwsTarget.Activate
Unload Me
End Sub
Private Sub Sheet1_Click()
ApplyToSheet Worksheets(1)
End Sub
Private Sub Sheet2_Click()
ApplyToSheet Worksheets(2)
End Sub
Private Sub Sheet3_Click()
ApplyToSheet Worksheets(3)
End Sub
Sub ApplyToSheet(wsSheet As Worksheet)
Set mwsTarget = wsSheet
wsSheet.Cells(1, 1) = TextBox1.Value
End Sub
| |
doc_23527427
|
A: I wouldn’t use mod_rewrite for this but a more powerful language. Because Accept-Language is a list of weighted values (see quality value) and the occurrence of one of the identifiers does not mean that it’s preferred over another value (especially q=0 means not acceptable at all).
As already said, use a more powerful language than mod_rewrite, parse the list of value and find the best match of preferred options and available options.
| |
doc_23527428
|
Would anyone have any advice on where I would start debugging this and what could cause this to happen ?
Appreciate the help.
A: NavigationManager class is responsible for providing voice and visual instructions to the user while driving or walking. An instance of NavigationManager can be retrieved using NavigationManager.getInstance(). It should be associated with a map with setMap(Map) method before navigation is started.
Navigation can be started in three different modes:
Simulation Mode - simulate(Route, long) - This mode does not require any GPS data from the device as the position is simulated along the given route.
Navigation Mode - startNavigation(Route) - This mode takes the calculated route and matches the position against the route. Before using this mode, PositioningManager is required to be running with GPS data.
Tracking Mode - startTracking() - This mode does not require a calculated route as it only tracks and shows the current position on the map.
Note: Android permission android.permission.ACCESS_FINE_LOCATION is required to use NavigationManager. Otherwise, the class returns Error.POSITIONING_FAILED. In addition, to ensure that the app receives location updates, the user needs to have the Location permission enabled (toggled to "on") during runtime.
The following is an example of performing navigation on a calculated route:
NavigationManager navigationManager = NavigationManager.getInstance();
//set the map where the navigation will be performed
navigationManager.setMap(getMap());
// if user wants to start real navigation, submit calculated route
// for more information on calculating a route, see the "Directions" section
NavigationManager.Error error = navigationManager.startNavigation(route);
You can check the the map-guidance example for the same.
| |
doc_23527429
|
My clients are querying the table via a PHP script mostly, and the size of the result set is around 10K records (not very large).
select * from T where timestamp > X and timestamp < Y and additionFilters
And I want this operation cheap.
Currently my table is hosting in Postgres 7, on a single 16G memory Box, and I would love to see some good suggestion for me to host this in low cost and also allow me to scale up for performance if needed.
The table serves:
1. Query: 90%
2. Insert: 9.9%
2. Update: 0.1% <-- very rare.
A: PostgreSQL 9.2 supports partitioning and partial indexes. If there are a few hot partitions, and you can put those partitions or their indexes on a solid state disk, you should be able to run rings around your current configuration.
There may or may not be a low cost, scalable option. It depends on what low cost and scalable mean to you.
| |
doc_23527430
|
List of 16
$ dataframe1 :'data.frame': 20 obs. of 60 variables:
..$ Stat : Factor w/ 16 levels "a","b",..: 16 16 16 16 16 16 16 16 16 16 ...
..$ P10 : num [1:31] 1 3 2 2 4 8 0 4 2 5 ...
..$ R : num [1:31] NA NA NA NA NA NA NA NA NA NA ...
..$ S : num [1:31] 0 7 7 1 5 9 3 9 6 2 ...
$ dataframe2 :'data.frame': 20 obs. of 60 variables:
..$ Stat : Factor w/ 16 levels "c","d",..: 16 16 16 16 16 16 16 16 16 16 ...
..$ P10 : num [1:31] 2 1 2 2 5 6 7 2 2 5 ...
..$ R : num [1:31] NA 1 NA NA 2 NA 4 NA NA NA ...
..$ S : num [1:31] 10 2 4 1 5 8 8 8 1 2 ...
...
..
I need the mean from each column and get the results in a data.frame.
dataframe1 dataframe2 ....
Stat NA NA
P10 6 7
R NA 3
S 12 14
... ... ... ...
I have this lapply(myList$variable1, mean) which returns me the results for one data.frame in that list.
ldply(myList, data.frame) does not include the mean function.
How would I do that for the whole list and bring it into one data.frame?
A: We can use a nested sapply. The first one will loop through the list and second will loop through the columns of the data.frame, based on the condition whether the column is numeric, we get the mean or else return NA.
sapply(myList, function(x) sapply(x, function(y)
if(is.numeric(y)) mean(y, na.rm=TRUE) else NA))
| |
doc_23527431
|
//minimum order value
add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );
function required_min_cart_subtotal_amount() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
// HERE Set minimum cart total amount
$min_total = 200;
// Total (before taxes and shipping charges)
$total = WC()->cart->subtotal;
// Add an error notice is cart total is less than the minimum required
if( $total <= $min_total ) {
// Display an error message
wc_add_notice( '<strong>' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($min_total) ) . '<strong>', 'error' );
}
}
}
So I added a custom field to the Dokan settings page
//Extra field on the seller settings and show the value on the store banner -Dokan
// Add an extra field in seller settings
add_filter( 'dokan_settings_form_bottom', 'extra_fields', 10, 2);
function extra_fields( $current_user, $profile_info ){
$minimum_order= isset( $profile_info['minimum_order'] ) ? $profile_info['minimum_order'] : '';
?>
<div class="gregcustom dokan-form-group">
<label class="dokan-w3 dokan-control-label" for="setting_address">
<?php _e( 'Minimum order value', 'dokan' ); ?>
</label>
<div class="dokan-w5">
<input type="number" class="dokan-form-control input-md valid" name="minimum_order" id="reg_minimum_order" value="<?php echo $minimum_order; ?>" />
</div>
</div>
<?php
}
//save the field value
add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
$dokan_settings = dokan_get_store_info($store_id);
if ( isset( $_POST['minimum_order'] ) ) {
$dokan_settings['minimum_order'] = $_POST['minimum_order'];
}
update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}
Now I want some code to use in here,
$min_total = 200;
to get vendor id from items of the cart and use it to get user meta and to show that minimum_order value in above. (200)
Sorry for my bad English.
A: Keep your extra field function and try to add this in your function.php. Just a little tricky but seems to work :)
add_action( 'woocommerce_check_cart_items', 'dokan_minimum_order_amount' );
function dokan_minimum_order_amount()
{
$eachVendorCartTotal = array();
$items = WC()->cart->get_cart();
//build the array: [vendor_id][sub_total]
foreach ($items as $item => $values) {
$product_id = $values['product_id'];
$product_qty = $values['quantity'];
$product_price = get_post_meta($values['product_id'], '_price', true) * $product_qty;
$vendor_id = get_post_field('post_author', $product_id);
if (!array_key_exists($vendor_id, $eachVendorCartTotal)) {
$eachVendorCartTotal[$vendor_id] = $product_price;
} else {
$sub_total = $product_price + $eachVendorCartTotal[$vendor_id];
$eachVendorCartTotal[$vendor_id] = $sub_total;
}
}
if (!empty($eachVendorCartTotal)) {
foreach ($eachVendorCartTotal as $vendor_id => $value) {
$errorMessage = "Your current order total for %s is %s — you must have an order with a minimum of %s to place your order for this vendor";
$store_info = dokan_get_store_info($vendor_id);
$store_name = $store_info['store_name'];
if(!empty($store_info['minimum_order'])) {
$vendor_minimum = !empty($store_info['minimum_order']) ? $store_info['minimum_order'] : 0;
if ($value < $vendor_minimum) {
if (is_cart()) {
wc_print_notice(
sprintf($errorMessage,
$store_name,
wc_price($value),
wc_price($vendor_minimum)
), 'error'
);
} else {
wc_add_notice(
sprintf($errorMessage,
$store_name,
wc_price($value),
wc_price($vendor_minimum)
), 'error'
);
}
}
}
}
}
}
| |
doc_23527432
|
#!/usr/bin/php
<?php
$hash = 'The quick brown fox jumps over the lazy dog';
for ($i = 1; $i <= 4; $i++) {
$hash = hash('sha512', $hash, true);
}
$hash = hash('sha512', $hash, false);
echo $hash;
echo "\n";
The sample code above returns
82a58adbbe7388444507b84f9dc93fd54825c514059d4b698415444ee924e2eb5609941ca4f03e246f9eeae74180298a8a02623698983de14852a8fb88868b9e
I need to move the app from PHP to NodeJS, so I rewrite the above code like this
const crypto = require('crypto');
var hash = 'The quick brown fox jumps over the lazy dog';
for (var i = 1; i <= 4; i++) {
hash = crypto.createHash('sha512').update(hash).digest('binary');
}
hash = crypto.createHash('sha512').update(hash).digest('hex');
console.log(hash);
But I get a different result
684806a7c59ba904dceebf5e286077aa59157b945e5302c7a268f03505b615879bf6f7264e82b2f0969fd317e7ce5d39a1b05978be96819f9a1fa837a329bbd2
The problem seems coming from the binary part. If I just hash text, I get the same result for both.
If you know where the problem is please let me know. Thanks!
EDIT: The PHP code can't be changed, it is the code of a working PHP app and I need to convert the app to Node JS and stuck at this binary issue.
A: Works just fine. Removed the loop cause I'm working in a console.
var hash = 'The quick brown fox jumps over the lazy dog';
hash = crypto.createHash('sha512').update(hash).digest('hex');
hash = crypto.createHash('sha512').update(hash).digest('hex');
hash = crypto.createHash('sha512').update(hash).digest('hex');
hash = crypto.createHash('sha512').update(hash).digest('hex');
hash = crypto.createHash('sha512').update(hash).digest('hex');
console.log(hash)
eb6301ffb2ed389cb952e6d6c22f9c13d015f4de0c6807852acc0b005bd36002d772d8766842909efac9c9feedd2e69b105f2b7394424316f9027c80df8df0b4
$hash = 'The quick brown fox jumps over the lazy dog';
$hash = hash('sha512', $hash, false)
$hash = hash('sha512', $hash, false)
$hash = hash('sha512', $hash, false)
$hash = hash('sha512', $hash, false)
$hash = hash('sha512', $hash, false)
echo $hash;
eb6301ffb2ed389cb952e6d6c22f9c13d015f4de0c6807852acc0b005bd36002d772d8766842909efac9c9feedd2e69b105f2b7394424316f9027c80df8df0b4
A: I found the problem. There is no "binary" encoding. I had created binary the wrong way. Here is the working code:
const crypto = require('crypto');
var hash = 'The quick brown fox jumps over the lazy dog';
for (var i = 1; i <= 4; i++) {
hash = crypto.createHash('sha512').update(hash).digest('hex');
hash = new Buffer(hash, "hex");
}
hash = crypto.createHash('sha512').update(hash).digest('hex');
console.log(hash);
Result:
82a58adbbe7388444507b84f9dc93fd54825c514059d4b698415444ee924e2eb5609941ca4f03e246f9eeae74180298a8a02623698983de14852a8fb88868b9e
| |
doc_23527433
|
This is what i currently use:
if(GamePrefrences.orientation == "landscape")
{
value = UIInterfaceOrientation.LandscapeLeft.rawValue
}
else
{
value = UIInterfaceOrientation.Portrait.rawValue
}
A:
You can override the preferredInterfaceOrientationForPresentation for
a view controller that is intended to be presented full screen in a
specific orientation.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/
| |
doc_23527434
|
in fact i need two arraylist in my recyclerview , one for headers item and one for child item
thank you
My Sample Code(With error about positions):
Please Help!
My Adapter Code
package com.example.recyclerviewpro
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class AdapterRecyclerView(private val listViewType: List<Int>, val HeaderList : List<HeaderModel>, val ContentList : List<ContentModel>) : RecyclerView.Adapter<AdapterRecyclerView.ViewHolder>() {
companion object {
val Header_ITEM = 1
val Child_ITEM = 2
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return when (viewType) {
Header_ITEM -> ViewHolderItemA(LayoutInflater.from(parent.context).inflate(R.layout.layout_header, parent, false))
else -> ViewHolderItemB(LayoutInflater.from(parent.context).inflate(R.layout.layout_item, parent, false))
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val viewType = listViewType[position]
when (viewType) {
Header_ITEM -> {
val viewHolderA = holder as ViewHolderItemA
viewHolderA.bind(ContentList.get(position))
}
else -> {
val viewHolderA = holder as ViewHolderItemB
viewHolderA.bind(HeaderList.get(position - ContentList.size), position)
}
}
}
override fun getItemCount(): Int {
return listViewType.count()
}
override fun getItemViewType(position: Int): Int = listViewType[position]
open inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
inner class ViewHolderItemA(itemView: View) : ViewHolder(itemView) {
val textView1: TextView = itemView.findViewById(R.id.text_view)
fun bind(header : ContentModel){
textView1.text = header.Title
}
}
inner class ViewHolderItemB(itemView: View) : ViewHolder(itemView){
val content : TextView = itemView.findViewById(R.id.textViewC)
val content2 : TextView = itemView.findViewById(R.id.textViewC2)
fun bind(cm : HeaderModel , position: Int){
content.text = cm.title
content2.text = cm.price
if (position % 2 == 1){
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.White))
}else{
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.Gray))
}
}
}
}
Error
2019-10-01 10:08:19.090 3724-3724/com.example.recyclerviewpro E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.recyclerviewpro, PID: 3724
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
at java.util.ArrayList.get(ArrayList.java:439)
at com.example.recyclerviewpro.AdapterRecyclerView.onBindViewHolder(AdapterRecyclerView.kt:34)
at com.example.recyclerviewpro.AdapterRecyclerView.onBindViewHolder(AdapterRecyclerView.kt:11)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:696)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
2019-10-01 10:08:19.090 3724-3724/com.example.recyclerviewpro E/AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-10-01 10:08:19.134 3724-3724/com.example.recyclerviewpro I/Process: Sending signal. PID: 3724 SIG: 9
A: I assume listViewType is used as indicator of HeaderList and ContentList items. Which means for example:
If you have 3 HeaderList items and 3 ContentList items. Your listViewType list should look like this [1,1,1,2,2,2]. Where 1 represents Header type element, and 2 represents Content type element.
I think the problem is that you don't pass correct listViewType. It is necessary for that list to be sorted, and to be correct representation of combination of ContentList and HeaderList.
| |
doc_23527435
|
Couldn't find one in my sourselist.
I guess I need a distribution with a gcc of exact that version.
MATLAB R2011a tells me that 4.3.4 is needed.
Currently I have a higher version of gcc and it does not work for MATLAB.
All gcc versions in my sourselist are too high.
And I don't think it would work if the version is lower.
So I need exactly that version.
A: Go to http://distrowatch.com/. It lists the latest distributions along with the package versions it comes with. Select the one you need
| |
doc_23527436
|
QMAKE_DEFAULT_INCDIRS=\\
INCLUDEPATH += /usr/include
LIBS += -L/usr/lib -lopencv_core -lopencv_imgcodecs -lopencv_highgui -lopencv_videoio -lopencv_imgproc
SOURCES += face.cpp
#include <opencv2/opencv.hpp>
#include "opencv2/objdetect.hpp"
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>
using namespace std;
using namespace cv;
void detectAndDisplay( Mat frame );
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
int main( int argc, const char** argv )
{
CommandLineParser parser(argc, argv,
"{help h||"
"{face_cascade|/home/student/Projects Sem2/Projekt_Facedetection/haarcascade_frontalface_alt.xml|Path to face cascade.}"
"{eyes_cascade|/home/student/Projects Sem2/Projekt_Facedetection/haarcascade_eye_tree_eyeglasses.xml|Path to eyes cascade.}"
"{camera|0|Camera device number.}");
/*parser.about( "\nThis program demonstrates using the cv::CascadeClassifier class to detect objects (Face + eyes) in a video stream.\n"
"You can use Haar or LBP features.\n\n" );*/
parser.printMessage();
String face_cascade_name = ("/home/student/Projects Sem2/Projekt_Facedetection/haarcascade_frontalface_alt.xml");
String eyes_cascade_name = ("/home/student/Projects Sem2/Projekt_Facedetection/haarcascade_eye_tree_eyeglasses.xml");
//-- 1. Load the cascades
if( !face_cascade.load( face_cascade_name ) )
{
cout << "--(!)Error loading face cascade\n";
return -1;
};
if( !eyes_cascade.load( eyes_cascade_name ) )
{
cout << "--(!)Error loading eyes cascade\n";
return -1;
};
I expected the CascadeClassifier to be defined in the opencv lib....
| |
doc_23527437
|
daemon java -jar start.jar
it errors:
daemon: invalid option -- 'j'
Any ideas? thx.
A: Below is a working script for daemonizing Solr. Couple important notes here:
*
*You need to set the chdir for the daemon script or else you'll get errors loading your config file.
*This will allow you to start/stop/status/restart Solr.
*This is a simple version that seems to be working for me.
Here's the script:
#!/bin/sh
# Prerequisites:
# 1. Solr needs to be installed at /usr/local/solr/example
# 2. daemon needs to be installed
# 3. Script needs to be executed by root
# This script will launch Solr in a mode that will automatically respawn if it
# crashes. Output will be sent to /var/log/solr/solr.log. A pid file will be
# created in the standard location.
start () {
echo -n "Starting solr..."
# start daemon
daemon --chdir='/usr/local/solr/example' --command "java -jar start.jar" --respawn --output=/var/log/solr/solr.log --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "done."
else
echo "failed. See error code for more information."
fi
return $RETVAL
}
stop () {
# stop daemon
echo -n "Stopping solr..."
daemon --stop --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "done."
else
echo "failed. See error code for more information."
fi
return $RETVAL
}
restart () {
daemon --restart --name=solr --verbose
}
status () {
# report on the status of the daemon
daemon --running --verbose --name=solr
return $?
}
case "$1" in
start)
start
;;
status)
status
;;
stop)
stop
;;
restart)
restart
;;
*)
echo $"Usage: solr {start|status|stop|restart}"
exit 3
;;
esac
exit $RETVAL
A: See:
*
*How to Daemonize a Java Program?
*How to convert an existing Java application to a SYS V service (daemon)
A: Try this:
daemon `java -jar start.jar`
| |
doc_23527438
|
Example: Given s = "hello", return "olleh".
What's wrong with this code?
class Solution {
public:
string reverseString(string s) {
string s2;
for(int i=0; i<s.length(); i++)
s2[i] = s[s.length()-1-i];
return s2;
}
};
A: Because the very first iteration of the loop attempts to set s2[0] to the last character of the original string.
The problem is that there is no s2[0]. The s2 string is completely empty. The s2 string is, essentially, an empty array.
Attempting to access the contents of the string using the [] operator accesses the existing character of that string. It doesn't create one, if it doesn't exist.
Even if code execution survives this undefined behavior, on the next iteration of the loop an attempt gets made to set s2[1] to some character. s2[1] does not exist, any more than s2[0] did. And so on. Undefined behavior. Crash.
Instead of setting non-existent values of an empty string, just use push_back() to add each character to s2.
This isn't really a particuarly efficient approach to reversing the contents of the string, of course. But it's a fine first attempt at tackling this introductory task.
A: You got out of bound access, you have to resize result string before assign it.
std::string reverseString(const std::string& s) {
std::string s2(s.size(), '\0');
for(int i=0; i<s.length(); i++)
s2[i] = s[s.length()-1-i];
return s2;
}
Or simply use correct constructor:
std::string reverseString(const std::string& s) {
return {s.rbegin(), s.rend()};
}
| |
doc_23527439
|
http://i.imgur.com/lwEox4a.png
And here's what I'm trying to achieve after a user clicks the media object button:
http://i.imgur.com/nbNVDLy.png
I've been trying to do this for a while now and the sidebar always ends up moving the picture down, on top of the arrows, or completely behind the carousel. Can someone help with this or show me a template that achieves this?
Also this is a single plage design so if you also know of a way for the sidebar to basically remain frozen on the left side of the page no matter what part of the site you are on, please tell me!
Thanks
Edit: The site, materializecss, is kind of is what I'm aiming for. I don't even really care about the media object button.
Edit 2: So I'm using this carousel and this one page template
http://startbootstrap.com/template-overviews/full-slider/
http://startbootstrap.com/template-overviews/scrolling-nav/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/full-slider.css" rel="stylesheet">
<link href="css/scrolling-nav.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<!-- Navigation -->
<!-- Full Page Image Background Carousel Header -->
<div class="navmenu navmenu-default navmenu-fixed-left">
<a class="navmenu-brand" href="#">Project name</a>
<ul class="nav navmenu-nav">
<li><a href="../navmenu/">Slide in</a></li>
<li><a href="../navmenu-push/">Push</a></li>
<li class="active"><a href="./">Reveal</a></li>
<li><a href="../navbar-offcanvas/">Off canvas navbar</a></li>
</ul>
<ul class="nav navmenu-nav">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu navmenu-nav">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
<div class="canvas">
<div class="navbar navbar-default navbar-fixed-top">
<button type="button" class="navbar-toggle" data-toggle="offcanvas" data-recalc="false" data-target=".navmenu" data-canvas=".canvas"> <span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="container-fluid">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="http://lorempixel.com/460/345/cats" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/business" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/abstract" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/transportation" />
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
<!-- Intro Section -->
<!-- <section id="intro" class="intro-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Scrolling Nav</h1>
<p><strong>Usage Instructions:</strong> Make sure to include the <code>scrolling-nav.js</code>, <code>jquery.easing.min.js</code>, and <code>scrolling-nav.css</code> files. To make a link smooth scroll to another section on the page, give the link the <code>.page-scroll</code> class and set the link target to a corresponding ID on the page.</p>
<a class="btn btn-default page-scroll" href="#about">Click Me to Scroll Down!</a>
</div>
</div>
</div>
</section> -->
<!-- About Section -->
<section id="photos" class="about-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Photos section</h1>
</div>
</div>
</div>
</section>
<!-- Services Section -->
<section id="projects" class="services-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Projects Section</h1>
</div>
</div>
</div>
</section>
<!-- Contact Section -->
<section id="recognition" class="contact-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Recognition Section</h1>
</div>
</div>
</div>
</section>
<!-- Services Section -->
<section id="teammembers" class="services-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Team Members Section</h1>
</div>
</div>
</div>
</section>
<!-- About Section -->
<section id="contact" class="about-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1>Contact Section</h1>
</div>
</div>
</div>
</section>
<!-- Page Content -->
<div class="container">
<!-- Responsive iFrame -->
<div class="Flexible-container">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3326.973484035864!2d-111.93373599999995!3d33.50206699673241!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x872b749e6453718b%3A0x2efd3ce15e57a886!2sNorris+Architects+LLC!5e0!3m2!1sen!2sus!4v1432435089092" width="1300" height="600" frameborder="0" style="border:0"></iframe></div>
<div class="row">
<div class="col-lg-12">
<h1>Full Slider by Start Bootstrap</h1>
<p>The background images for the slider are set directly in the HTML using inline CSS. The rest of the styles for this template are contained within the <code>full-slider.css</code>file.</p>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Script to Activate the Carousel -->
<script>
$('.carousel').carousel({
interval: 0 //changes the speed
})
</script>
<!-- Scrolling Nav JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>
</body>
</html>
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 70%;
margin: auto;
}
html, body {
height: 100%;
}
.navbar-toggle {
float: left;
margin-left: 15px;
}
.navmenu {
z-index: 1;
}
.canvas {
position: absolute;
left: 0;
right: 0!important;
z-index: 2;
min-height: 100%;
padding: 50px 0 0 0;
background: #fff;
}
.navbar-toggle {
display: block;
}
.navbar {
right: auto;
background: none;
border: none;
}
.container-fluid {
padding: 0px;
}
/*!
* Start Bootstrap - Scrolling Nav HTML Template (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
width: 100%;
height: 100%;
}
html {
width: 100%;
height: 100%;
}
@media(min-width:767px) {
.navbar {
-webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
-moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
transition: background .5s ease-in-out,padding .5s ease-in-out;
}
.top-nav-collapse {
padding: 0;
}
}
/* Demo Sections - You can use these as guides or delete them - the scroller will work with any sort of height, fixed, undefined, or percentage based.
The padding is very important to make sure the scrollspy picks up the right area when scrolled to. Adjust the margin and padding of sections and children
of those sections to manage the look and feel of the site. */
.intro-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #fff;
}
.about-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #eee;
}
.services-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #fff;
}
.contact-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #eee;
}
/* Flexible iFrame */
.Flexible-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0px;
overflow: hidden;
}
.Flexible-container iframe,
.Flexible-container object,
.Flexible-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 50%;
}
A: Jasny Bootstrap has a great offcanvas menu plugin. Using that example with a couple of modifications and this example carousel, I came up with this
(Demo)
CSS
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 70%;
margin: auto;
}
html, body {
height: 100%;
}
.navbar-toggle {
float: left;
margin-left: 15px;
}
.navmenu {
z-index: 1;
}
.canvas {
position: absolute;
left: 0;
right: 0!important;
z-index: 2;
min-height: 100%;
padding: 50px 0 0 0;
background: #fff;
}
.navbar-toggle {
display: block;
}
.navbar {
right: auto;
background: none;
border: none;
}
HTML
<div class="navmenu navmenu-default navmenu-fixed-left">
<a class="navmenu-brand" href="#">Project name</a>
<ul class="nav navmenu-nav">
<li><a href="../navmenu/">Slide in</a></li>
<li><a href="../navmenu-push/">Push</a></li>
<li class="active"><a href="./">Reveal</a></li>
<li><a href="../navbar-offcanvas/">Off canvas navbar</a></li>
</ul>
<ul class="nav navmenu-nav">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu navmenu-nav">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
<div class="canvas">
<div class="navbar navbar-default navbar-fixed-top">
<button type="button" class="navbar-toggle" data-toggle="offcanvas" data-recalc="false" data-target=".navmenu" data-canvas=".canvas"> <span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="container-fluid">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="http://lorempixel.com/460/345/cats" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/business" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/abstract" />
</div>
<div class="item">
<img src="http://lorempixel.com/460/345/transportation" />
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
Then make sure to include these files if you haven't included them already
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
| |
doc_23527440
|
projections {
sum('downloads')
sum('clicks')
groupProperty('site')
groupProperty('link')
groupProperty('device')
}
totalCount returns 939 rows and the result set returns 8. How I can get the no of resultset? I tried resultSet.size but doesn't help because it returns max 50. Right now, I'm running two queries to get the number of records. But is there any way that I can get the resultset with total number in one shot?
| |
doc_23527441
|
I tried to use {!$User.LastLoginDate}, but it says "Field LastLoginDate does not exist. Check spelling".
Please help.
A: It looks like this field is not exposed through the $User global variable. You could expose a date property in your page controller and query for the with SOQL.
public DateTime lastlogin{get;set;}
controller:
User u = [SELECT LastLoginDate FROM User WHERE Id =:UserInfo.getUserId()];
lastlogin = u.LastLoginDate;
VF: {! lastlogin }
| |
doc_23527442
|
SELECT * FROM Message WHERE (sender = user1 AND receiver = user2) OR (sender = user2 AND receiver = user1)
But I don't know how to convert into a Parse query.
Here my Message model:
import java.util.Date;
import com.parse.ParseClassName;
import com.parse.ParseObject;
import com.parse.ParseUser;
@ParseClassName("Message")
public class Message extends ParseObject {
public Message() {
}
public String getId() {
return getObjectId();
}
public Date getDate() {
return getCreatedAt();
}
public ParseUser getSender() {
return getParseUser("sender");
}
public void setSender(ParseUser user) {
put("sender", user);
}
public ParseUser getReceiver() {
return getParseUser("receiver");
}
public void setReceiver(ParseUser user) {
put("receiver", user);
}
public String getContent() {
return getString("content");
}
public void setContent(String content) {
put("content", content);
}
}
A: You can use something similar to this:
String user1;
String user2;
// build first AND condition
ParseQuery<ParseObject> queryPart1 = ParseQuery.getQuery("Message");
queryPart1.whereEqualTo("sender", user1);
queryPart1.whereEqualTo("receiver", user2);
// build second AND condition
ParseQuery<ParseObject> queryPart2 = ParseQuery.getQuery("Message");
queryPart2.whereEqualTo("sender", user2);
queryPart2.whereEqualTo("receiver", user1);
// list all queries condition for next step
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(queryPart1);
queries.add(queryPart2);
// Compose the OR clause
ParseQuery<ParseObject> innerQuery = ParseQuery.or(queries);
innerQuery.addAscendingOrder("createdAt"); // apply sorting for creation date ascending (use addDescendingOrder for Desc sorting)
// *** Parse does not allow selection result greater than 1000 elements for query, so you may need to paging your system
//innerQuery.setSkip(10); // skip the first 10 results
//innerQuery.setLimit(200); // limit selection to first 200 elements ( from your skip offset if set, from the first otherwise )
// Run selection asynchronously
innerQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
// Do your stuff with 'results' list, if no error has been occurred
// ...
// ..
// .
}
});
Hope it helps!
A: You really should focus on how chat messages are stored rather than how to query them. It seems to me that your model is quite SQL-ish, and this results in rather complex and slow queries and calculations when you later want to show a history.
You should design your model in a more NoSQL way to get the benefits from Parse's NoSQL backend (MongoDB).
When you design your model, start with defining what QUERIES you will perform against it. You could solve your chat history by querying and sorting, but a much better approach performancewise is to make sure your chat history is already there on the server. This will make the query for the history superfast, and the load on your user's device minimal.
One solution suggested here: Storing send message history on parse.com for a messaging app?
| |
doc_23527443
|
I have a file as such:
1 C foo C bar
2 C foo C bar
3 C foo C bar
4 H foo H bar
5 H foo H bar
6 O foo O bar
And I need to get it to be:
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
**Unfortunately the spacing between foo and C as well as the spacing between C and bar must be maintained.
I have tried it in a piecewise manner, where I pull out lines containing the different identifiers, C, H, and O, placing them in a temp file. Then I attempt to order them by occurance, and then splice the original file back together.
#!/bin/bash
sed -i -e "/ C /w temp1.txt" -e "//d" File.txt
sed -i -e "/ H /w temp2.txt" -e "//d" File.txt
sed -i -e "/ O /w temp3.txt" -e "//d" File.txt
`awk -i '{print NR $2}' temp1.txt
awk -i '{print NR $2}' temp2.txt
awk -i '{print NR $2}' temp3.txt
cat temp1.txt >> File.txt
cat temp2.txt >> File.txt
cat temp3.txt >> File.txt
However I am pretty sure my syntax is awful, as I am really only familiar with sed rather than awk.
Any help would be greatly appreciated, thank you.
A: EDIT: Here is a solution with GNU awk which preserves actual spaces. If your split supports 4 arguments. After reading man page I got it, even I am happy that I found it, it will be helpful.
awk '
{
n=split($0,array," ",b)
array[2]=sprintf("%s%02d",array[2],++a[array[2]])
line=b[0]
for(i=1;i<=n;i++){
line=(line array[i] b[i])
}
print line
}' Input_file
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
About split in GNU awk man page for 4 arguments:
split(s, a [, r [, seps] ])
Split the string s into the array a and the separators array seps on the regular expression r, and return the
number of fields. If
r is omitted, FS is used instead. The arrays a and seps are cleared first. seps[i] is the field
separator matched by r between
a[i] and a[i+1]. If r is a single space, then leading whitespace in s goes into the extra array element
seps[0] and trailing white-
space goes into the extra array element seps[n], where n is the return value of split(s, a, r, seps).
Splitting behaves identically
to field splitting, described above.
1st solution: Could you please try following,
awk '{$2=sprintf("%s%02d",$2,++a[$2])} 1' Input_file
Output will be as follows.
1 C01 bar C
2 C02 bar C
3 C03 bar C
4 H01 bar H
5 H02 bar H
6 O01 bar O
2nd solution: In case you want to have values in $2 and $4 both places then do following.
awk '{$2=$4=sprintf("%s%02d",$2,++a[$2])} 1' Input_file
1 C01 bar C01
2 C02 bar C02
3 C03 bar C03
4 H01 bar H01
5 H02 bar H02
6 O01 bar O01
3rd solution: In case you want to add/insert a new column at last of line then do following.
awk '{$(NF+1)=sprintf("%s%02d",$2,++a[$2])} 1' Input_file
1 C bar C C01
2 C bar C C02
3 C bar C C03
4 H bar H H01
5 H bar H H02
6 O bar O O01
A: same solution while preserving the initial field positions
$ awk '{r=sprintf("%02d",++a[$2]); sub($2" ",$2r)}1' file
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
Note that this assumes first field values don't overlap with the second field values as shown, otherwise you need to guard to keep changes only to the second field. For second field it can be easily done by prefixing match and replacement values with single space.
A: With GNU awk for the 3rd arg to match() and \S/\s shorthand for [^[:space]:]]/[[:space:]]:
$ awk 'match($0,/(\S+\s+)(\S+)(.*)/,a){ printf "%s%s%02d%s\n", a[1], a[2], ++cnt[a[2]], a[3] }' file
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
The above will work on ALL input, even if a preceding field has the same values as the target field or if the target field contains RE metachars or anything else.
The above is to modify the 2nd field. in general to modify the n-th field for n=4, say, hard-coded would be:
$ awk 'match($0,/((\S+\s+){3})(\S+)(.*)/,a){ printf "%s%s%02d%s\n", a[1], a[3], ++cnt[a[3]], a[4]}' file
1 C foo C01 bar
2 C foo C02 bar
3 C foo C03 bar
4 H foo H01 bar
5 H foo H02 bar
6 O foo O01 bar
and if it's passed as an argument rather than hard-coded:
$ awk -v n=4 'match($0,"((\\S+\\s+){"n-1"})(\\S+)(.*)",a){ printf "%s%s%02d%s\n", a[1], a[3], ++cnt[a[3]], a[4]}' file
1 C foo C01 bar
2 C foo C02 bar
3 C foo C03 bar
4 H foo H01 bar
5 H foo H02 bar
6 O foo O01 bar
A: With a simple awk script:
$ awk '{$2=sprintf("%s%02d",$2,++a[$2]);}1' file
1 C01 foo C
2 C02 foo C
3 C03 foo C
4 H01 foo H
5 H02 foo H
6 O01 foo O
A: Though Perl is not tagged, it seems to be good fit for these cases. Check out this, if you are considering Perl.
> cat wagner.txt
1 C foo C bar
2 C foo C bar
3 C foo C bar
4 H foo H bar
5 H foo H bar
6 O foo O bar
> perl -pe 's/(\s+)(\S+)(\s+)/sprintf("%s%s%02d%s",$1,$2,++$kv{$2},$3)/e ' wagner.txt
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
>
Thanks to Karakfa, the answer can be further shortened by removing $3
> perl -pe 's/(\s+)(\S+)/sprintf("%s%s%02d",$1,$2,++$kv{$2})/e ' wagner.txt
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
>
One more way by further removing one more group
> perl -pe 's/([^^]\S+)/sprintf("%s%02d",$1,++$kv{$1})/e ' wagner.txt
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
5 H02 foo H bar
6 O01 foo O bar
>
or using look-arounds
perl -pe 's/([^?!]\S+)/sprintf("%s%02d",$1,++$kv{$1})/e ' wagner.txt
A: $ awk 'BEGIN{FS=OFS=""}{$6="";$7=((b=++a[$5])>9?"":0) b}1' file file file file
1 C01 foo C bar
2 C02 foo C bar
3 C03 foo C bar
4 H01 foo H bar
...
6 O03 foo O bar
1 C10 foo C bar
2 C11 foo C bar
Explained:
$ awk 'BEGIN {
FS=OFS="" # empty field separators
}
{
$6="" # null $6
$7=((b=++a[$5])>9?"":0) b # $7 carries the count, with leading 0 if below 10
}1' file
| |
doc_23527444
|
Do you have any idea?
sh-3.2# head -n 1 /etc/issue
CentOS release 5.11 (Final)
sh-3.2# wget https://www.cpan.org/src/5.0/perl-5.36.0.tar.gz
--2022-10-21 04:19:21-- https://www.cpan.org/src/5.0/perl-5.36.0.tar.gz
Resolving www.cpan.org... 151.101.53.55, 2a04:4e42:d::311
Connecting to www.cpan.org|151.101.53.55|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
I pushed the image to docker hub.
You can run it by
docker run -it zhongpengqun/centos5.11 /bin/sh
| |
doc_23527445
|
public void SetupFormLogger()
{
NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget();
target.Name = "control";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = richtextLog.Name;
target.FormName = this.Name;
target.TargetForm = this;
target.AutoScroll = true;
target.MaxLines = 10000;
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
new RichTextBoxRowColoringRule(
"level == LogLevel.Trace", // condition
"WhiteSmoke", // font color
"Black", // background color
FontStyle.Regular
)
);
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Black"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "WhiteSmoke", "Black"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "Yellow", "Black"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold));
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Debug);
}
If I call this function it won't log anymore to file and if I don't call this function it logs to file. How can I make NLog to log both to file and RichTextBox at the same time?
And this is my nlog config file
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="myvar" value="myvalue"/>
<targets>
<target name="f" xsi:type="File" layout="${longdate} | ${module} | ${logger} | ${level} | ${message}" fileName="${basedir}/logs/${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>
A: LoggingRule richTextBoxRule = new LoggingRule("*", asyncWrapper);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Debug);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Error);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Fatal);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Info);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Trace);
richTextBoxRule.EnableLoggingForLevel(LogLevel.Warn);
LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper);
LogManager.Configuration.LoggingRules.Add(richTextBoxRule);
LogManager.ReconfigExistingLoggers();
Sadly enough, then it is not easy to dynamically close/remove the target again (Until https://github.com/NLog/NLog/pull/2259 is complete). So you should not close the window again, but just hide it and unhide afterwards (avoid creating multiple target registrations).
A: You can configure a second target for NLog by calling
LogManager.Configuration.AddTarget(asyncWrapper);
More information: https://github.com/nlog/NLog/wiki/Configuration-API
This is assuming that you've already set up your file target somewhere else. You would want to call that code after the file target is set up. It could be helpful to see how you configure file logging also though.
Edit: here's a related question: How to log to multiple targets using NLog?
| |
doc_23527446
|
I found this website as an example. You can select text etc. All the time.
Can somebody give a very easy to understand and little example how this works? I see the source code but I don't really understand it…
Is this CSS3 or HTML5 or both?
How much JavaScript do I need?
Which browsers support this?
A: There are two parts to this.
*
*The first one is about building the 3D shape.
*The second one involves animating it (and this is the simple part).
UPDATE AUGUST 2019
This is a really old answer and I'll leave the meat of the original below, just removing the links that don't work anymore.
But since I wrote this, both my coding abilities and browsers have progressed, so if you want to build a CSS cube in a more efficient fashion, check out this article I wrote on the topic:
Simplifying CSS Cubes with Custom Properties
I'll go through each one of them in detail, but first I'll briefly answer the three questions you've asked at the end.
is this css3 or html5 or both?
It's CSS3. CSS 3D transforms and keyframe animations.
how much javascript do I need?
Well, if you don't want to create 3D shape itself with JavaScript, then you don't need any JavaScript to animate it. Any browser that supports 3D transforms also supports keyframe animations and, if a browser supports keyframe animations, then you probably want to use those instead of jQuery (and maybe even your own custom JS) animations.
which browsers support this?
Things didn't look good two years ago, but they're getting better...
✓ Chrome, Safari, Firefox (though Firefox 3D animations are jiggly and not nice to my CPU... I do have a 6-year-old old laptop, it's true) Opera 15+ (WebKit) support 3D transforms. And of course keyframe animations.
Firefox supports everything unprefixed, Chrome/Safari/Opera need the -webkit- prefix - update: Chrome 36+ and Opera 23+ support them unprefixed as well, so it's only Safari left now. I won't be using any prefixes in the answer or in the demo (-prefix-free takes care of things there). Another update: Safari 9 unprefixes transforms.
✗ 3D transforms were not supported by Opera before switching to WebKit.
✗ IE up to and including 9 don't support 3D transforms. IE10 and IE11 support 3D transforms, but do not support nesting of 3D transformed elements (cannot create realistic looking 3D shapes via applying 3D transforms on both parent and child elements, as 3D transformed children of a 3D transformed parent get flattened into the plane of the parent). Update: Edge now supports nesting of 3D transformed elements.
Alright, I hope that clears a few things. Now...
1 Building a CSS cube.
1.2 What is a cube and starting off with the HTML
First of all, try to picture a cube. Maybe this link helps? Or let's have an image here as well.
It has 6 square faces. 1 top, 1 bottom; 1 in front, 1 in the back; 1 left, 1 right. This means that the HTML is simply:
<ul class='cube'>
<li class='face'></li>
<li class='face'></li>
<li class='face'></li>
<li class='face'></li>
<li class='face'></li>
<li class='face'></li>
</ul>
You first put some regularity into the faces, give them equal width and height, position them absolutely so that they're all stacked one on top of the other, give them different backgrounds, they don't mind that. You can give them some padding, put some dummy text into them, whatever...
Now comes the interesting part: moving them so that they form a cube in space. You do that using 3D transforms.
1.2 The Coordinate System
Consider this 3D coordinate system:
Initially, all the 6 faces are all exactly where you see the blue square, in the xOy plane (where O is the intersection of the 3 axes).
Pay attention to the direction of the y-axis. Coming from a mathematical background, this seemed a bit weird to me at first, but this is how the coordinate system is for the screen.
In 2D, the origin O is at the top left corner, so the + (positive direction) of the x-axis points right and the + of the y-axis points down.
1.2.a Translations along the axes
So a translation of a positive value along the x-axis (for example, translateX(10px)) moves the element to which it is applied to the right (towards the + of the x-axis), while a translation of a negative value along the x-axis (something like translateX(-10px)) moves it to the left.
Similarly, a translation of a positive value along the y-axis (like translateY(10px)) moves the element down (towards the + of the y-axis), while a translation of a negative value along the y-axis (like translateY(-10px)) moves it up.
Now add another dimension. With the z-axis. The + (positive direction) of the z-axis comes out of the screen, towards you. So a translation of a positive value along the z-axis (like translateZ(10px)) moves the element forward (towards the + of the z-axis and towards you), while a translation of a negative value along the z-axis (like translateZ(-10px)) moves it backward (away from you).
1.2.b Rotations around the axes
Rotations of positive angle values (for example, rotate(15deg) - note that if the rotation axis is not specified, then it is assumed to be the z-axis) in CSS are clockwise and rotations of negative angle values (like rotate(-15deg)) are counter-clockwise.
And clockwise means clockwise as seen from the + of the axis around which you rotate the element.
So a positive rotation around the x-axis means a clockwise rotation in the yOz plane as seen from the + of the x-axis, which is at the right.
A positive rotation around the y-axis means a clockwise rotation in the zOx plane (the horizontal plane) as seen from the + of the y-axis, which is at the bottom.
A positive rotation around the z-axis means a clockwise rotation in the xOy plane (the plane of the screen) as seen from the + of the z-axis, which is how you naturally see the screen.
1.3 Put the faces in the right positions in order to form the cube
1.3.1 Put one face at the front
This means translating it forwards (in the positive direction) along the z-axis. What is this? A translateZ of a positive value. What value? Well, it should be half the width (or the height, doesn't matter, it's a square, they're equal).
Suppose I have the width: 16em;
Then in this case, you translate the face forward (along the positive z-axis) by 16em/2 = 8em. In CSS, that's
.face:nth-child(1) { transform: translateZ(8em); }
Note: The translate transform moves the entire coordinate system of the element that is translated (and consequently, the transform-origin for any subsequent transforms).
1.3.2 Put the second face at the back
That's simple, right? Just a translate along the z-axis, by the same value in the opposite direction, right? .face:nth-child(2) { transform: translateZ(-8em); }, right?
Well... actually... only if you don't want to put any content on that face. Or if you don't want to have as a background an image for which it matters which is left and which is right.
Each of these squares that make up the cube has a front and a back. The front is the one towards the positive direction of the z-axis; the one that "looks at you from the computer screen". If you put text there, it flows normally on the front. But it looks vertically mirrored on the back.
That's why the first thing that you should do is to rotate the second square face by 180° around the vertical axis (y-axis). After doing that, you can then translate this second square face along the z-axis in order to move it to the back.
The translate value is again positive in this case. Just like the translate transform moves the coordinate system of the element that is translated, the rotate transform... well... rotates it. This means that after rotateY(180deg) is applied, the + of the z-axis points towards the back (not towards the front anymore).
So the CSS that rotates and then translates the second face into its position on the cube is:
.face:nth-child(2) { transform: rotateY(180deg) translateZ(8em); }
Note: the cube is a really simple 3D shape, but one CSS property that I find really useful to check whether I've rotated faces the right way is backface-visibility. If I set it to hidden and I don't see the rotated element, it means that I'm looking at it from the back.
1.3.3 Put the third face to the right
First of all, its front has to "look" towards the right. This means that it has to be rotated around the y-axis so that the + of the z-axis ends up pointing towards the right and then it has to be translated along the positive z-axis by the same positive value (8em in this case) that is half the length of the side of the square.
Rotated by what angle? Well, 90°, which means the CSS needed is:
.face:nth-child(3) { transform: rotateY(90deg) translateZ(8em); }
1.3.4 Put the fourth face to the left
First rotate it by 90°, but the other way, to make its front "look" towards the left. "The other way" means rotateY(-90deg), then apply the same old translateZ(8em). In one CSS line:
.face:nth-child(4) { transform: rotateY(-90deg) translateZ(8em); }
1.3.5 Put the fifth face at the top
First rotate it by 90° around the x-axis and then translate along the z-axis (which points up after the rotation). CSS:
.face:nth-child(5) { transform: rotateX(90deg) translateZ(8em); }
1.3.6 Put the sixth (and last!) face at the top
Rotate it by 90° the other way around the x-axis, then translate it along the z-axis (which points down after the rotation). CSS:
.face:nth-child(6) { transform: rotateX(-90deg) translateZ(8em); }
1.4 Perspective and realistic looking 3D shapes
All the faces of the cube are now in place. But this won't look like much of a 3D shape unless the faces that are closer seem bigger than those that are further away. The CSS property that takes care of this is called perspective and is applied on the parent of the elements which have 3D transforms applied on them.
It still won't look like much of a 3D shape if you look perpendicular to the center of the front face because you won't see any of the other faces. To fix this, you need to rotate the cube itself in 3D. And this is why it's important that the browser allows nesting of 3D transformed elements.
You enable nesting of 3D transformed elements with transform-style: preserve-3d; on the parent element (.cube in this case). Unfortunately, IE10/11 do not support the preserve-3d value for the transform-style property (only support the flat value), so you cannot have a realistic looking cube in IE yet (unless you take the 3D transforms applied on the cube and chain them before the transforms applied for each face, which means one set of keyframes for each face if you want to animate the cube as a whole).
Update: transform-style: preserve-3d now landing in IE as well.
Note: If you also apply 3D transforms on the .cube, then you should move the perspective property on the parent of the .cube.
2 Animating the CSS cube
That's done using just the regular keyframe animations for the .cube element. Let's say you want to rotate it:
@keyframes ani { to { transform: rotate3d(5, 12, 13, 360deg); } }
You can have multiple keyframes, with rotations around different axes, but this is the basic idea.
A: Its all css3 and javascript. Just inspect the site in your favorite inspector, dig into the dom, and you'll see something like
-webkit-perspective: none;
-webkit-perspective-origin: 200px 200px;
-webkit-transform: matrix3d(-0.9386958080415784, -0.197569680458564, 0.2825179663820851, 0, 0, 0.8194947008605812, 0.5730867606754029, 0, -0.34474654452969944, 0.537954139890128, -0.7692562404101148, 0, 0, 0, 0, 1);
-webkit-transform-style: preserve-3d;
-webkit-transition-delay: 0s;
-webkit-transition-duration: 16s;
-webkit-transition-property: all;
-webkit-transition-timing-function: linear;
how much javascript you need depends on how you want to implement it. It can be 'a lot' or 'a little'.
The more modern a browser, the better the change it will run well. Check here to see which browsers support what.
| |
doc_23527447
|
instead using a lot of IF questions.
I've tried lots of ways to make it work but without success.
I'd love to help me solve this through a smart loop.
This is for software that calculates shelf placement and drawer placement.
I need you to help me solve this problem.
I want somthing like this:
for (int i = 1; i <= NishCount; i++)
{
lblNish + i + .Text = nish + i + .ToString();
}
this is the code:
if (NishCount == 1 && MdfCount == 0)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = "ENTER VALUES";
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 2 && MdfCount == 0)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = "ENTER VALUES";
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 1 && MdfCount == 1)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 2 && MdfCount == 1)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 1 && MdfCount == 2)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = MDF2.ToString();
}
if (NishCount == 2 && MdfCount == 2)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = MDF2.ToString();
}
if (NishCount == 1 && MdfCount == 0 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = shocev.ToString();
lblMDF1.Text = "ENTER VALUES";
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 2 && MdfCount == 0 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = shocev.ToString();
lblMDF1.Text = "ENTER VALUES";
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 1 && MdfCount == 1 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = shocev.ToString();
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 2 && MdfCount == 1 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = shocev.ToString();
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = "ENTER VALUES";
}
if (NishCount == 1 && MdfCount == 2 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = lblSho.ToString();
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = MDF2.ToString();
}
if (NishCount == 2 && MdfCount == 2 && SNCheckBox.Checked == true)
{
lblNish1.Text = nish1.ToString();
lblNish2.Text = nish2.ToString();
lblSho.Text = shocev.ToString();
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = MDF2.ToString();
}
A: You can start by initializing them all:
lblNish1.Text = "הזן מידות";
lblNish2.Text = "הזן מידות";
lblSho.Text = "הזן מידות";
lblMDF1.Text = "הזן מידות";
lblMDF2.Text = "הזן מידות";
Then set them like needed:
if (NishCount >= 1)
lblNish1.Text = nish1.ToString();
if (NishCount >= 2)
lblNish2.Text = nish2.ToString();
if (SNCheckBox.Checked)
lblSho.Text = shocev.ToString();
if (MdfCount >= 1)
lblMDF1.Text = MDF1.ToString();
if (MdfCount >= 2)
lblMDF2.Text = MDF2.ToString();
There's probably a more elegant solution if we would know all your code.
A: Don't use a for loop. You logic simplifies to following
lblNish1.Text = nish1.ToString();
lblNish2.Text = "ENTER VALUES";
lblSho.Text = "ENTER VALUES";
lblMDF1.Text = "ENTER VALUES";
lblMDF2.Text = "ENTER VALUES";
if (NishCount == 2)
{
lblNish2.Text = nish2.ToString();
}
switch(MdfCount)
{
case 1:
lblMDF1.Text = MDF1.ToString();
break;
case 2:
lblMDF1.Text = MDF1.ToString();
lblMDF2.Text = MDF2.ToString();
break;
}
if(SNCheckBox.Checked && !((NishCount == 1) && (MdfCount == 2)))
{
lblSho.Text = shocev.ToString();
}
| |
doc_23527448
|
I'm completely fine without using a CSS pre-processor, and would much rather deal with vanilla CSS than deal with this dependency headache. Is it possible to disable just Sass support when creating a new Rails app? I'm able to use --skip-javascript to disable all javascript support, but since all the other dependencies are able to be installed, it would be a shame to have to disable them just because node-sass can't be installed offline. Is there an option like that for Sass?
I'm aware I could manually copy the .node file from the GitHub release page, however, I'm trying to make this process as minimalistic and automatable as possible.
I'm working with Fedora Linux if that's relevant.
Any help is appreciated.
A: Yes, I think --skip-sprockets option will disable Sass. You can also disable webpacker using --skip-javascript.
You may try below command.
rails new green-forest -S -J
| |
doc_23527449
|
def fnA( x: int, y: int) -> function:
def fnB(z: int) -> int:
return x + y
return fnB
This would allow me to do something like: fnA(3,4)(5) and it would return 12
BUT because of me not typing the function, I dont know what the definition input is and return type of fnB is. I was not sure if: function[int, int] is the way to do it where the last value is the return type or something?
How do I accomplish this? When looking at the Typing module i didnt really see anything.
| |
doc_23527450
|
*
*1 Subreport will generate
*The other subreports are hidden
This works really well when i use a browser to view the rerports or when i export them to Excel. edit: Excel, not XML
When i try to export them to XML, CVS, ... I get errors from the other subreports because they can't execute.
*
*Is there something I'm overlooking?
*Can someone tell me a fix of trick I can use, that would be most helpfull!
*Or is this a bug from SSRS?
Thanks in advance!
Frederic
Extra:
What are the errors you get? Did you debug yet or find any similar issues on the web that may or may not be the same as your case?
I only pass the parameters to 1 subreport, the other reports are hidden and can't be generated. I can pass the parameters but i would get errors from the datasets inside the other subreports + they would retrieve data which is not showed and is not needed.
One or more parameters were not specified for the subreport,
'report2', located at: /Reports/rp_report2. (rrRenderingError) One or
more parameters were not specified for the subreport, 'report2',
located at: /Reports/rp_report2.
I already searched on internet but haven't found anything.
Does it happen only on XML and CSV?
It works fine for HTML, PDF and Excel. It doesn't work for XML, CSV (comma delimited) and TXT (Tab Delimited Text File). Also the TIFF works fine but isn't used.
A: The formats XML and CSV require a special data element (DataElementOutput) in the rdl:
<TablixCell>
<DataElementOutput>NoOutput</DataElementOutput>
<CellContents>
<Subreport Name="report2">
<ReportName>report2</ReportName>
<Parameters>
| |
doc_23527451
|
JarExample.java:
public class JarExample {
public static void main(String[] args) {
}
}
MANIFEST.MF:
Manifest-Version: 1.0
Main-Class: JarExample
I run the follow commands to construct the JAR:
javac JarExample.java
jar cfm JarExample.jar MANIFEST.MF *.class
Yet when I run java -jar JarExample.jar, I get the following error:
no main manifest attribute, in JarExample.jar
Peaking inside the JAR, the correct class file is present, but the following autogenerated manifest, META-INF/MANIFEST.MF, is present:
Manifest-Version: 1.0
Created-By: 1.8.0_162 (Oracle Corporation)
So where is my usage of the jar command incorrect? Why does it not recognize my supplied manifest file?
Thanks!
A: I have followed all steps that you described, and an executable jar file has been successfully created.
I'm using openjdk 11.0.11 2021-04-20
The generated file inside the .jar file looks like this:
Manifest-Version: 1.0
Main-Class: JarExample
Created-By: 11.0.11 (Ubuntu)
So this is may be caused by your Java version or used Operation System.
In the referenced by you answer, there is a useful comment by David:
If you create the MANIFEST.MF file, don't forget to finish the last line
with a line break. On Windows just add an empty line at the end.
Otherwise the last attribute will not make it in the jar file. In this
special case the Main-Class attribute will be missing.
Probably, this is your case. Because when I remove the last line break in the MANIFEST.MF, I'm getting the same error as yours:
no main manifest attribute, in JarExample.jar
Example of MANIFEST.MF with the last line break (3rd line is empty) - works well
Manifest-Version: 1.0
Main-Class: JarExample
Without the last line break (2 lines of code) - crashes with an error
Manifest-Version: 1.0
Main-Class: JarExample
| |
doc_23527452
|
i used on other code i wrote 'encoding ('utf-8)' , but i cant figure out how to use it in this code.
thank you for your time.
import tweepy
from api_keys import *
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret, access_token,access_token_secret)
api = tweepy.API(auth)
user = (api.verify_credentials())
print (user)
"UnicodeEncodeError: 'charmap' codec can't encode character.." # <---the error
| |
doc_23527453
|
In an effort to tidy things up I followed the advice on GitHub and ran
git filter-branch --index-filter 'git rm --cached --ignore-unmatch config/credentials.yml' --prune-empty --tag-name-filter cat -- --all
and then added to gitignore
echo "config/credentials.yml" >> .gitignore
When I try to commit these changes
git add .gitignore
git commit -m "ignored credentials.yml"
I'm getting a message
error: pathspec 'adds credentials.yml to gitignore' did not match any file(s) known to git.
How can I fix this error? Or, how can I undo my changes and safely revert to the git history on my remote?
A: I think you might've forgotten the step
$ git add .gitignore
before trying to commit, or then you mistyped, when you shoud've given
$ git commit -m "Add credentials.yml to .gitignore"
Process advised is highly dangerous [for the repo contents], so one must be really careful to follow all the steps in detail.
A: Just give a file path while adding file to git add command, it works for me
$ git add mainFolder/.../file.extension
Note: mainFolder would be the folder inside your repo
| |
doc_23527454
|
DatabaseHelper helper = DatabaseHelper.getInstance( getActivity() );
int savedID = 0;
WishList wl = new WishList();
wl.setName("abc");
try {
savedID = helper.getWishListDao().create(wl);
WishList wl_saved = helper.getWishListDao().queryForId( savedID );
wl_saved.getId();
} catch (SQLException e) {
e.printStackTrace();
}
Here is my entity. The ID field is auto generated.
@DatabaseTable
public class WishList {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField( canBeNull = false , unique = true )
private String name;
@ForeignCollectionField
private ForeignCollection<WishItem> items;
...
What is wrong is the ID that is generated in the Database is not the same one that that ORMlite returns in the call below. It returns 1.
savedID = helper.getWishListDao().create(wl);
The ID in the database is actually 37. Any ideas what I may be doing wrong?
Using version 4.41
A: ORMLite's Dao.create(...) method does not return the ID of the newly created object but the number of rows in the database that were changed – usually 1. Here are the javadocs for Dao.create(...).
Create a new row in the database from an object. If the object being created uses DatabaseField.generatedId() then the data parameter will be modified and set with the corresponding id from the database. ...
Returns: The number of rows updated in the database. This should be 1.
When ORMLite creates the object, the generated ID is then set to the id field afterwards. To find the ID of your new object you get it from the object itself:
// create returns 1 row changed
helper.getWishListDao().create(wl);
// the id field is set on the w1 object after it was created
savedID = w1.getId();
| |
doc_23527455
|
I am dealing with a legacy code where the object properties access was mostly done this way ( obj['myProp'] instead of obj.myProp so I need to find a way to ad types. Here is the code example and this won't give me any error at compile time sadly :(, is there a way to make a compiler detect that property 'test' does not exists.
interface IPerson{
name: string
}
let x: IPerson
x = { name: 'John' };
let y = x['test'];
A: x['test'] is specifically not checked under default compiler settings to ease migration from Javascript where [] is traditionally used for more dynamic access to objects.
If you turn on noImplicitAny you will get an error on this kind of access if the key is not in the object.
| |
doc_23527456
|
On my system I have my regular installation (currently at v58), a Chrome Canary installation (currently at v61) and Cordova opens a new Chrome with v59.
(This weird reporting was probably due to a pending install on my regular Chrome, both regular Chrome and Cordova's opened Chrome are v59)
Why does Cordova not start in a new tab, or why can't I even drag the newly opened window into a tab of my already open regular Chrome?
A: It's --user-data-dir param that we pass along with chrome.exe, results in the behavior of opening a chrome instance in new window. This feature is incorporated so that user specific data can be kept separately for testing.
This is same reason why you are not able to even drag drop the newly opened window into an already opened instance of chrome. Basically its done to maintain the integrity of individual instances.
The tweak to stop opening new instance of chrome instance(though not recommended unless its really a requirement) is to edit the browser.js file under /Projectroot/platforms/browser/cordova/node_modules/cordova_serve/src folder as you have mentioned in your answer and stop passing the --user-data-dir parameter. Hope it helps. Cheers
A: Based on @Gandhi 's comments I found that switching the var chromeArgs to an empty string in /Projectroot/platforms/browser/cordova/node_modules/cordova_serve/src/browserjs on line 82 achieves the desired result of opening the preview in my default Chrome with logged in user.
This seems a somewhat hacky approach, so I am glad for any more sophisticated solutions on how to reliably switch this from the default behaviour.
| |
doc_23527457
|
And they say there that I need the uploadprogress extension.
Now I search in google how to install and I find some staff, all says about running commands an sets things on php.ini file.
But I dont know where should I run those commands, I buy hosting from company and I have DirectAdmin conrol panel.
Also I dont know which commands should I run, and if I need to download the extension or wo write site address.
I search for the php.ini file in my ftp and I didnt find it, its says that I dont have access to it?
I running php 5 on linux server.
Thanks for helping
A: Ask your hosting provider if you have access to the php.ini file on your server, if you do - ask for the SSH username and password (if you don't have them already). Once you've done that, follow this guide.
If you don't have access to either the php.ini or SSH, then you wont be able to make the modification and you should get yourself a cheap hosting with someone like DigitalOcean (I use them and they're awesome)
| |
doc_23527458
|
The program is checking every number in the list and should output if is prime or not. Probably I just don't get the prime algorithm right.
Currently outputs that no number is prime.
void primList(struct node* stnode)
{
struct node* pr = stnode;
int i;
bool primNum = true;
if (stnode != NULL)
{
while (pr != NULL)
{
if ((pr->num) == 0 || (pr->num) == 1)
primNum = false;
else
{
for (i = 2; i <= ((pr->num) / 2); ++i) //The mistake
if (((pr->num) % i) == 0) //is here?
{
primNum = false;
break;
}
}
if (primNum)
cout << "\n" << pr->num << " is a prime number.";
else
cout << "\n" << pr->num << " is not a prime number.";
pr = pr->nextptr;
bool primNum = true;
}
}
}
A: In general such questions (seeking debugging help) are discouraged, see on-topic.
In this case the minimal change to fix this code would be:
void primList(struct node* stnode)
{
struct node* pr = stnode;
int i;
bool primNum = true;
if (stnode != NULL)
{
while (pr != NULL)
{
if ((pr->num) == 0 || (pr->num) == 1)
primNum = false;
else
{
for (i = 2; i <= ((pr->num) / 2); ++i) //The mistake
if (((pr->num) % i) == 0) //is here?
{
primNum = false;
break;
}
}
if (primNum)
cout << "\n" << pr->num << " is a prime number.";
else
cout << "\n" << pr->num << " is not a prime number.";
pr = pr->nextptr;
primNum = true; // <-- notice I erased bool here
}
}
}
The problem here is that the primNum variable is not really changed in line bool primNum = true, but a new variable with the same name is created (and then immediately destroyed).
There are many other ways on how your code could be improved. See for example The Definitive C++ Book Guide and List as it has a lot of great sources.
| |
doc_23527459
|
import numpy as np
import random as rnd
numberlist = [1,3,5,7,9]
numberlist2 = [0,2,4,6,8]
my_shots = np.array([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
])
def letter_to_column(letter):
"""Takes in lettervalue, and returns what column it corresponds to,
zero-indexed.
Example:
letter_to_column('A') # => 0
"""
return "ABCDEFGHIJ".index(letter.upper())
def find_value(coordinatestring):
"""Takes in a coordinatestring in the form "letternumber" and returns wheter it is a boat
in the coordinate or not
"""
letter = coordinatestring[0]
row = int(coordinatestring[1])
col = letter_to_column(bokstav)
value = my_shots[row][col]
return value
This is the function that repeats the places it shoots, I would appreciate if anyone has any solution to how to make the function not repeat the "lettervalues" it has already given.
def shot(letter = "A", number = "0"):
# Chekcs if I already have shot there
while find_value(letter + number) == 1:
letter = rnd.choice("ABCDEFGHIJ")
# Uses the "chess method" by only shooting on every other route
if letter_to_column(letter) % 2 == 0:
number = str(rnd.choice(numberlist2))
else:
number = str(rnd.choice(numberlist))
A: If the board is "small" like in Battleship, one strategy you could employ is to generate all the shots at once and then just shuffle them. This works like a champ when you have only 100 locations and avoids a clunky "while this_shot != last_shot" type of setup.
import random
letters = list('ABCDEFGHIJ')
nums = range(9)
all_shots = [''.join([str(num), letter]) for num in nums for letter in letters]
random.shuffle(all_shots)
| |
doc_23527460
|
@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
mAdapter.onBindViewHolder(holder, position);
if (!isFirstOnly || position > mLastPosition) {
for (Animator anim : getAnimators(holder.itemView)) {
anim.setDuration(mDuration).start();
anim.setInterpolator(mInterpolator);
}
mLastPosition = position;
} else {
ViewHelper.clear(holder.itemView);
}
}
I've checked that it is because the position is saved for the future use. It is a question to library creator why they need this logic. But issue disappeared when I change the usage of the position to the usage holder.getAdapterPosition():
@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
mAdapter.onBindViewHolder(holder, position);
if (!isFirstOnly || holder.getAdapterPosition() > mLastPosition) {
for (Animator anim : getAnimators(holder.itemView)) {
anim.setDuration(mDuration).start();
anim.setInterpolator(mInterpolator);
}
mLastPosition = holder.getAdapterPosition();
} else {
ViewHelper.clear(holder.itemView);
}
}
I assume that conceptually it didn't change much but lint is satisfied now. Why?
A: The documentation of RecyclerView.Adapter.onBindViewHolder() states:
Note that unlike ListView, RecyclerView will not call this method
again if the position of the item changes in the data set unless the
item itself is invalidated or the new position cannot be determined.
For this reason, you should only use the position parameter while
acquiring the related data item inside this method and should not keep
a copy of it. If you need the position of an item later on (e.g. in a
click listener), use getAdapterPosition() which will have the updated
adapter position
So, technically items may be re-arranged (like sorted, or moved around) and binding will not be necessary because items are not invalidated yet. This means onBindViewHolder() may NOT be called if items show the same data, but just their position/index in a list changes. The position variable received holds true only for the scope of bind function and will not always point to the correct position in the data set. That's why the function getAdapterPosition() must be called every time updated position is needed.
IMHO, mLastPosition = holder.getAdapterPosition(); is still potentially wrong. Because item may be re-arranged and mLastPosition still points to old position.
About why lint is silent, perhaps Lint's rule is not that thorough. It's only checking whether the position parameter is being copied or not.
A: My old code:
@Override
//here int position gave a error
public void onBindViewHolder(@NonNull CartListAdapator.ViewHolder holder, int position) {
holder.titleTxt.setText(foodDomains.get(position).getTitle());
holder.feeEachItem.setText(String.valueOf(foodDomains.get(position).getFee()));
holder.plusItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
managementCart.plusNumberFood(foodDomains, position, new ChangeNumberItemListener() {
@Override
public void changed() {
notifyDataSetChanged();
changeNumberItemListener.changed();
}
});
}
});
So, in plusNumberFood() method I changed the parameter position -> holder.getAdapterPosition();
My new code:
@Override
public void onBindViewHolder(@NonNull CartListAdapator.ViewHolder holder, int position) {
holder.titleTxt.setText(foodDomains.get(position).getTitle());
holder.feeEachItem.setText(String.valueOf(foodDomains.get(position).getFee()));
holder.plusItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
managementCart.plusNumberFood(foodDomains, holder.getAdapterPosition(), new ChangeNumberItemListener() {
@Override
public void changed() {
notifyDataSetChanged();
changeNumberItemListener.changed();
}
});
}
});
| |
doc_23527461
|
The code below is what we are using and it's fine. However, we would like to ideally return some information about the existing user, so that we may display a link to the existing patient's profile.
I've scoured the validator docs and can't seem to find any way to handle return parameters other than true/false. Is this a limitation of the remote method?
jQuery
form.validate({
rules: {
email: {
remote: {
url: "CheckEmailExists.php",
type: "post"
}
}
},
messages: {
email: {
remote: "This email address is already assigned to an existing patient"
}
},
});
PHP
$existingUserQuery = "SELECT tbl_patients.patient_id FROM tbl_patients WHERE tbl_patients.patient_email = :email";
$getUser = $pdo->prepare($existingUserQuery);
$getUser->bindparam(":email", $email);
$getUser->execute();
$numCount = $getUser->rowCount();
if ($numCount > 0) {
echo 'false';
} else {
echo 'true';
}
A: You can create a custom method and within the method do run your own remote call via AJAX. Then in your php, return a JSON object with the values that you want to use.
jQuery.validator.addMethod("validatemmail", function(value, element) {
var _is_valid = false;
var qry = {"email" : value};
$.ajax({
type: "POST",
url: "CheckEmailExists.php",
data: qry,
done: function(data){
if(data.error == "new"){
_is_valid = true;
console.log(data.patient_name);
}
else{
_is_valid = false;
}
return this.optional(element) || _is_valid );
}
});
}, "This email address is already assigned to an existing patient");
$('validatorElement').validate({
rules : {
email : { validatemmail : true }
}
});
Your PHP:
$return = [];
if ($numCount > 0) {
$return["error"] = "exists";
$return["patient_name"] = "John";
} else {
$return["error"] = "new";
}
header('Content-Type: application/json');
echo json_encode($return);
The original idea:
jQuery Validate Plugin - How to create a simple custom rule?
| |
doc_23527462
|
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#import "RootViewController.h"
@interface PromotionViewController : UITableViewController {
NSString *currentCat;
}
@property (nonatomic, retain) NSString *currentCat;
@end
And in the .m i have:
@synthesize currentCat;
However, in the first view controller when I try and set that variable I get a not found error:
PromotionViewController *loadXML = [[PromotionViewController alloc] initWithNibName:@"PromotionViewController" bundle:nil];
[self.navigationController pushViewController:loadXML animated:YES];
[PromotionViewController currentCat: @"Test"];
That third line gives me a: Class method +currentCat not found
What am i doing wrong?
A: Tom,
The issue in your code appears that you are trying to set the string using a static method call to the class. This would work if you implemented a static method named currentCat:
I don't think this is what your want.
See below on how to correct your issue.
[PromotionViewController currentCat:@"Test"];
//This will not work as it is calling the class itself not an instance of it.
[loadXml setCurrentCat:@"Test"];
//This will work. Keep in mind if you are going to call the objective-c
//synthesize setting directly you will need to capitalize the first letter
//of your instance variable name and add "set" to the front as I've done.
//Alternatively in objective-c 2.0 you can also use
//the setter method with the . notation
loadXml.currentCat = @"Test";
//This will work too
A: You need to get the string like this, as it's a property and not a method:
NSString* myString = controller.currentCat; // where controller is an instance of PromotionViewController
A: You need to do:
loadXML.currentCat = @"Test";
A: PromotionViewController *loadXML = [[PromotionViewController alloc] initWithNibName:@"PromotionViewController" bundle:nil];
[loadXML setCurrentCat: @"Test"];
[self.navigationController pushViewController:loadXML animated:YES];
That should do it.
| |
doc_23527463
|
An exception:
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fx.fibi/com.example.fx.fibi.DetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.fx.fibi.News.getTitle()' on a null object reference.
Here is my code:
MainActivity:
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
Query query = FirebaseDatabase.getInstance().getReference().child("Global");
FirebaseRecyclerOptions<News> options = new FirebaseRecyclerOptions.Builder<News>()
.setQuery(query, News.class).build();
final FirebaseRecyclerAdapter<News,NewsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<News,
NewsViewHolder>(options) {
@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_row, parent, false);
return new NewsViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull NewsViewHolder holder, int position, @NonNull News model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(getApplicationContext(), model.getImage());
holder.setOnClickListener(new NewsViewHolder.ClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", position);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
}
});
}
};
@Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
}
DetailActivity (this class gets NullPointerException at "title.setText(news.getTitle());"
public class DetailActivity extends AppCompatActivity {
TextView title, desc;
ImageView imageView;
News news;
String titleString, descString, image;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initCollapsingToolbar();
imageView = findViewById(R.id.thumbnail_image_header);
title = findViewById(R.id.detail_title);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("news")) {
news = getIntent().getParcelableExtra("news");
title.setText(news.getTitle());
desc.setText(news.getDesc());
Picasso.with(mContext).load(image).into(imageView);
}
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbarLayout.setTitle(" ");
isShow = false;
}
}
});
}
}
Model:
public class News implements Parcelable {
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public News (Parcel in) {
String[] data = new String[3];
in.readStringArray(data);
title = data[0];
desc = data[1];
image = data[2];
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {title, desc, image});
}
public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
@Override
public News createFromParcel(Parcel source) {
return new News(source);
}
@Override
public News[] newArray(int size) {
return new News[size];
}
};
}
Sorry if my question seems to be foolish, this is my first full app.
Thanks!
I added an object list List <News> newsList and changed method onItem click to:
if (position != RecyclerView.NO_POSITION) {
News clickedDataItem = newsList.get(position);
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
But now i get "java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference"
A: You can implement java Serializable interface instead of implementing Parcelable in your model class as shown below
public class News implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
//empty contructor neeeded
}
@Overide
public String toString(){
return super.toString();
}
}
Then you can pass the object the intent like this
News news = new News("title", "desc", "image");
Intent intent = new Intent(StartActivity.this, TargetActivity.class);
intent.putExtra("news", news);
startActivity(intent);
In order to get the object from the intent, you need to cast New class into the Intent results as shown below.
News news = (News)getIntent().getSerializableExtra("news");
A: In your onBindViewHolder, you put wrong data.
intent.putExtra("news", position); // position is int
which position is an int, put the News object at the position instead.
A: news = getIntent().getIntExtra("news");
A: You can set the value to the intent ....
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = "value";
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
You can retrive the value in second activity..........
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
| |
doc_23527464
|
<form class="contact-form" method="POST" action="sendemail.php">
<div class="row-fluid">
<div class="span5">
<label>First Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your First Name" name="name">
<label>Last Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your Last Name" name="lname">
<label>Email Address</label>
<input type="text" class="input-block-level" required="required" placeholder="Your email address" name="email">
</div>
<div class="span7">
<label>Message</label>
<textarea name="message" id="message" required="required" class="input-block-level" rows="8" name="message"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary btn-large pull-right" value="Send Message" />
<p> </p>
</form>
and sendemail.php page code is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = @trim(stripslashes($_POST['name']));
$email = @trim(stripslashes($_POST['email']));
$subject = "An enquiry sir";
$message = @trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email@email.com';
echo $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
Why is the output I get blank in my email id, for example:
Name:
Email:
Subject:
Message:
P.N: I am using here a nova template theme.
The form is being submitted via AJAX using the following JavaScript:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
A: the form submission code is not submitting the form data. Here is the code you provided:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
and this is what it should be:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
A: Remove the echo from the line that defines $body
From this...
echo $body = 'Name: ' . $name . "\n\n" . 'Email
To this...
$body = 'Name: ' . $name . "\n\n" . 'Email
| |
doc_23527465
|
I'm able to find the lowest score using the =min function [=min(B2:R2)]
I can find the first instance using the =match function. [=MATCH(S2,B2:R2,0)]
However I would like a formula that returns the latest occurrence of the lowest scoring week.
For example Portia lowest score is 8 the first occurrence is week 4 but I would like it to return the latest occurrence which is week 11
A: You will need to use an Array Formula to achieve this. The following will return the "highest" lowest value if you are using columns B:R as the data columns and column T as the Low Week column. You need to enter this as an array (CSE) formula by copying and pasting it into cell T2 and pressing Ctrl+Shift+Enter.
=IFERROR(INDEX($A$1:$R$1,1,SMALL(IF(B2:R2=MIN(B2:R2),COLUMN(B2:R2),FALSE),COUNTIF(B2:R2,MIN(B2:R2)))),"")
Explanation
First, the COUNTIF(B2:R2,MIN(B2:R2)) will count the number of times the minimum value occurs. This is needed because a simpleMIN(B2:R2) will only grab the first minimum value, not the nth minimum value.
Next, the IF(B2:R2=MIN(B2:R2),COLUMN(B2:R2),FALSE) is the actual array formula part of the equation (the reason why you need to use Ctrl+Shift+Enter). It will only return the references for when you have a minimum and returning FALSE for all other entries greater than the minimum. Now, you have an array of only the column numbers the smallest values in the dataset.
Then, the SMALL(IF(B2:R2=MIN(B2:R2),COLUMN(B2:R2),FALSE),COUNTIF(B2:R2,MIN(B2:R2))) will take the column numbers of the smallest values and find the latest occurrence of this, which comes from the COUNTIF(B2:R2,MIN(B2:R2)) code.
Now that the last smallest occurrences' column number is know, you can use the INDEX function to find the value in the first row INDEX($A$1:$R$1,1.
Finally, the IFERROR will display the Low Week row if the SMALL function finds a match, otherwise it will display a blank cell. This could be used to copy this array formula further down the page for rows that you don't yet have users for.
Result
A: You can also do this using LOOKUP function and avoiding array formulas, e.g. assuming S2 has the minimum value you can get the last week with that value with this formula in T2 copied down
=LOOKUP(2,1/(B2:R2=S2),B$1:R$1)
This works because (B2:R2=S2) returns an array of TRUE/FALSE values, and then dividing 1 by that array gives you an array of 1s or #DIV/0! errors. When you use 2 as the lookup value on that array it won't find any 2s so will therefore match with the last number (the last 1) in the array. That corresponds to the last week with your smallest value so using the top row as the "return vector" means that the formula returns the corresponding week number as required
| |
doc_23527466
|
For instance if I have 4000 results, and I only need 800 results, I want to be able to get every 5th result.
So some like: get, skip, skip, skip, skip, get, skip, skip, skip,..
I was wondering if such a thing is possible in Elasticsearch?
A: You're better off using a scripted filter. Otherwise you're needlessly using the score. Filters are just like queries, but they don't use scoring.
POST /test_index/_search
{
"query": {
"filtered": {
"filter": {
"script": {
"script": "doc['unique_counter'].value % n == 0",
"params" : {
"n" : 5
}
}
}
}
}
}
You're also better off not using dynamic scripting in real world usage.
That said, you probably want to take a look at aggregations for graphing analytical information about your data rather than taking an arbitrary sample.
A: One way you could do it is with random scoring. It won't give you precisely every nth item according to a rigid ordering, but if you can relax that requirement this trick should do nicely.
To test it I set up a simple index (I mapped "doc_id" to "_id" just so the documents would have some contents, so that part isn't required, in case that's not obvious):
PUT /test_index
{
"mappings": {
"doc": {
"_id": {
"path": "doc_id"
}
}
}
}
Then I indexed ten simple documents:
POST /test_index/doc/_bulk
{"index":{}}
{"doc_id":1}
{"index":{}}
{"doc_id":2}
{"index":{}}
{"doc_id":3}
{"index":{}}
{"doc_id":4}
{"index":{}}
{"doc_id":5}
{"index":{}}
{"doc_id":6}
{"index":{}}
{"doc_id":7}
{"index":{}}
{"doc_id":8}
{"index":{}}
{"doc_id":9}
{"index":{}}
{"doc_id":10}
Now I can pull back three random documents like this:
POST /test_index/_search
{
"size": 3,
"query": {
"function_score": {
"functions": [
{
"random_score": {
"seed": "some seed"
}
}
]
}
}
}
...
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 0.93746644,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "1",
"_score": 0.93746644,
"_source": {
"doc_id": 1
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "10",
"_score": 0.926947,
"_source": {
"doc_id": 10
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "5",
"_score": 0.79400194,
"_source": {
"doc_id": 5
}
}
]
}
}
Or a different random three like this:
POST /test_index/_search
{
"size": 3,
"query": {
"function_score": {
"functions": [
{
"random_score": {
"seed": "some other seed"
}
}
]
}
}
}
...
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 0.817295,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "4",
"_score": 0.817295,
"_source": {
"doc_id": 4
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "8",
"_score": 0.469319,
"_source": {
"doc_id": 8
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "3",
"_score": 0.4374538,
"_source": {
"doc_id": 3
}
}
]
}
}
Hopefully it's clear how to generalize this method to what you need. Just take out however many documents you want, in however many chunks make it performant.
Here is all the code I used to test:
http://sense.qbox.io/gist/a02d4da458365915f5e9cf6ea80546d2dfabc75d
EDIT: Actually now that I think about it, you could also use scripted scoring to get precisely every nth item, if you set it up right. Maybe something like,
POST /test_index/_search
{
"size": 3,
"query": {
"function_score": {
"functions": [
{
"script_score": {
"script": "if(doc['doc_id'].value % 3 == 0){ return 1 }; return 0;"
}
}
]
}
}
}
...
{
"took": 13,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 1,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "3",
"_score": 1,
"_source": {
"doc_id": 3
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "6",
"_score": 1,
"_source": {
"doc_id": 6
}
},
{
"_index": "test_index",
"_type": "doc",
"_id": "9",
"_score": 1,
"_source": {
"doc_id": 9
}
}
]
}
}
| |
doc_23527467
|
If the value of alpha is >= the tick rate, the effect is instant, and when the value of alpha is < the tick rate, the speed of the effect seems to lengthen as the difference between tick rate - alpha increases. I currently have no idea why this is the case, so I'm hoping someone more experienced with the library can provide insight into the cause of the effect.
import pygame
def main():
button_rect = pygame.Rect(0, 0, 200, 40)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# When the window is not filled with a color you get a cool
# fade-in effect.
# window.fill((0, 0, 0))
container = pygame.Surface((848, 480), pygame.SRCALPHA)
container.fill((30, 30, 30))
# Place button in center of screen.
button_rect.center = window.get_rect().center
mouse_pos = pygame.mouse.get_pos()
# The value of alpha affects the speed of the effect
alpha = 10
if button_rect.collidepoint(mouse_pos):
button = pygame.draw.rect(container,
(255, 0, 0, alpha),
button_rect)
else:
button = pygame.draw.rect(container,
(255, 255, 255, alpha),
button_rect)
window.blit(container, (0, 0))
window.blit(text, text.get_rect(center=button.center))
pygame.display.update(container.get_rect())
# Clock speed affects fade-in time as well.
clock.tick(60)
if __name__ == "__main__":
initalized, unintialized = pygame.init()
window = pygame.display.set_mode((848, 480), pygame.RESIZABLE)
clock = pygame.time.Clock()
font = pygame.font.Font("../assets/fonts/terminal.ttf", 20)
text = font.render("Hello", 0, (0,0,0))
main()
A: You draw a transparent surface over the window surface in each frame. This creates a fade in effect. The drawing in the window becomes more and more solid the more often you put the transparent surface over it. Increasing the tick rate and doing it more often will make the fade in faster. Increasing the alpha value makes the Surface you're laying over the window less transparent, and the fad-in becomes faster as well.
See also How to fade in a text or an image with PyGame.
| |
doc_23527468
|
Thanks
A: Like this:
$facebook = new Facebook('API', 'SECRET');
echo $facebook->user;
A: The new PHP SDK is available here: http://github.com/facebook/php-sdk. It has an example that shows how to get the user id and profile: http://github.com/facebook/php-sdk/blob/master/examples/example.php.
| |
doc_23527469
|
Say the user enters 11.00, now when i retrieve it as in (priceform.cleaned_data) it returns
Decimal('11.00')
so it looks like
price = Decimal('11.00')
which triggers a validation error when i try to insert it into the database.
I'm coming up blank to any solutions for this
models.py
class Bid(models.Model):
title = models.CharField(max_length=64, blank=True)
date_time = models.DateTimeField(default=timezone.now, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
user = models.CharField(max_length=64)
forms.py:
class BidForm(ModelForm):
class Meta:
model = Bid
fields = ['price']
views.py:
if request.method == "POST":
bidform = BidForm(request.POST)
if bidform.is_valid():
price = bidform.cleaned_data['price']
bid = Bid.objects.create(title=title, price=bidform, user=username)
bid.save()
A: The price should be the price, not bidform:
if request.method == 'POST':
bidform = BidForm(request.POST, request.FILES)
if bidform.is_valid():
bid = Bid.objects.create(
title=title,
price=bidform.cleaned_data['price'],
user=username
)
You can however let the form do the work:
if request.method == 'POST':
bid = Bid(
title=title,
user=username
)
bidform = BidForm(request.POST, request.FILES, instance=bid)
if bidform.is_valid():
bid = bidform.save()
| |
doc_23527470
|
For some of the objects like the last button object, the system tells me "Hardcoded string 'Message', should use'@string' resource". What does this mean?
I've searched online and some say to use <resource> but I don't know what this means. How can I fix this?
For example, in the first ImageView, an error pops up here android:contentDescription="homeImage"
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView6"
android:layout_width="135dp"
android:layout_height="130dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="138dp"
android:contentDescription="homeImage"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@mipmap/ic_launcher_round"
tools:ignore="ImageContrastCheck" />
<TextView
android:id="@+id/textView"
android:layout_width="150dp"
android:layout_height="55dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="136dp"
android:text="TextView"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<Button
android:id="@+id/followButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:layout_marginEnd="88dp"
android:text="Follow"
app:layout_constraintEnd_toStartOf="@+id/messageButton"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:layout_marginEnd="72dp"
android:text="Message"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
A: It's warning not an error.
And only to make it easier to reuse strings and also for translation
A: It is a warning that tells you that you would better use the @string xml file to have your texts at .
In Android studio, a resource is a localized text string, bitmap, layout, or other small piece of noncoded information that your app needs. At build time, all resources get compiled into your application.
for example your layout you are presenting above is a resource file that goes in @layout folder you also can use @drawable folder to save your images vectors ...
and there is plenty of other folders android studio provide to control your and to make it easier for you and for the system .
you might at the beginning find it hard but after some time you will like it .
for more information ,have a look at App resources overview
| |
doc_23527471
|
I've installed both uvicorn and fastapi with a venv and requirements.txt, also I'm running Python 3.5 (maybe that's the issue?)
The issue should be something with uvicorn because I can't run --help or --version
uvicorn --version
Traceback (most recent call last):
File "/home/...../.venv/bin/uvicorn", line 7, in <module>
from uvicorn.main import main
File "/home/...../.venv/lib/python3.5/site-packages/uvicorn/__init__.py", line 1, in <module>
from uvicorn.config import Config
File "/home/...../.venv/lib/python3.5/site-packages/uvicorn/config.py", line 131
message = f"Uvicorn running on {ip_repr} (Press CTRL+C to quit)"
^
SyntaxError: invalid syntax
I really don't have a clue where to start looking as I cannot seem to find anything on internet.
A: Surely with Python 3.5, FastAPI won't work.
FastAPI homepage:
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
uvicorn (from https://github.com/encode/uvicorn):
Requirements: Python 3.6+ (For Python 3.5 support, install version 0.8.6.)
I guess you should update Python to 3.6 at least. pyenv should help.
| |
doc_23527472
|
cuisine
Number.of.order
Customer_id
Fastfood
2
1
cakes
3
1
Western
4
2
Chinese
5
3
What i want is to get rid of the Numbers.of.order column and add the values inside the column as addition rows.
Something like this:
cuisine
Customer_id
Fastfood
1
Fastfood
1
cakes
1
cakes
1
cakes
1
Western
2
Western
2
Western
2
Western
2
Chinese
3
Chinese
3
Chinese
3
Chinese
3
Chinese
3
Im doing this so that I can convert it into a transaction dataframe for association rules.
Any help would be greatly appreciated!!
A: You can use the following solution:
library(dplyr)
df %>%
uncount(Number.of.order)
cuisine Customer_id
1 Fastfood 1
2 Fastfood 1
3 cakes 1
4 cakes 1
5 cakes 1
6 Western 2
7 Western 2
8 Western 2
9 Western 2
10 Chinese 3
11 Chinese 3
12 Chinese 3
13 Chinese 3
14 Chinese 3
A: An option in base R with rep
out <- df1[rep(seq_len(nrow(df1)), df1$Number.of.order), -2]
row.names(out) <- NULL
-output
out
cuisine Customer_id
1 Fastfood 1
2 Fastfood 1
3 cakes 1
4 cakes 1
5 cakes 1
6 Western 2
7 Western 2
8 Western 2
9 Western 2
10 Chinese 3
11 Chinese 3
12 Chinese 3
13 Chinese 3
14 Chinese 3
| |
doc_23527473
|
Object of type 'ContosoUniversity.DAL.SchoolInitializer' cannot be converted to type 'System.Data.Entity.IDatabaseInitializer`1[ContosoUniversity.DAL.SchoolContext]'.
Web.config:
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
</context>
</contexts>
SchoolInitializer.cs: The tutorial has Seed() override declared. When I added "override", it said
Error 1 'ContosoUniversity.DAL.SchoolInitializer.Seed(ContosoUniversity.DAL.SchoolContext)': no suitable method found to override
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
//When accessing DB initially for every run. If there's a difference between database to the model (SchoolContext, Entity Class)
//Drops and recreates Database with data in SchoolInitializer
//In Web.config: add <context> </context> to let Entity Framework use SchoolInitializer
public class SchoolInitializer
{
protected void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
};
//Add entities to DbSet (entity set)
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
var courses = new List<Course>
{
new Course{CourseID=1050,Title="Chemistry",Credits=3,},
new Course{CourseID=4022,Title="Microeconomics",Credits=3,},
new Course{CourseID=4041,Title="Macroeconomics",Credits=3,},
new Course{CourseID=1045,Title="Calculus",Credits=4,},
new Course{CourseID=3141,Title="Trigonometry",Credits=4,},
new Course{CourseID=2021,Title="Composition",Credits=3,},
new Course{CourseID=2042,Title="Literature",Credits=4,}
};
courses.ForEach(s => context.Courses.Add(s));
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
new Enrollment{StudentID=3,CourseID=1050},
new Enrollment{StudentID=4,CourseID=1050,},
new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
new Enrollment{StudentID=6,CourseID=1045},
new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
};
enrollments.ForEach(s => context.Enrollments.Add(s));
context.SaveChanges();
}
}
}
A: Replace following line
public class SchoolInitializer
either with
public class SchoolInitializer: DropCreateDatabaseIfModelChanges<SchoolContext>
or with
public class SchoolInitializer: DropCreateDatabaseAlways<SchoolContext>
| |
doc_23527474
|
The code mostly works, but doesn't quite come together. The last portion, the With .Validation portion, brings up a application defined error. I suspected it has to do with the rng being a range being treated as a string, so I've tried creating a separate string variable set as the address of rng, but that brought up an error too. I also tried (as seen below), just designating the address of rng as the data validation formula itself, which also results in an error.
What am I doing wrong here?
Sub ProcessSelector()
Dim lastrow As Long
Dim c As Range
Dim rng As Range
ActiveWorkbook.Worksheets(2).Select
With ActiveWorkbook.Worksheets(2)
lastrow = .Cells(.Rows.Count, "E").End(xlUp).Row
For Each c In .Range("E1:E" & lastrow)
If c.Text = "Thomas" Then
If rng Is Nothing Then
Set rng = .Range("C" & c.Row)
Else
Set rng = Union(rng, .Range("C" & c.Row))
End If
End If
Next c
End With
ActiveWorkbook.Worksheets(1).Select
With ActiveWorkbook.Sheets(1).Range("D5")
With .Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=" & rng.Address
End With
End With
End Sub
Thanks!
A: I found the answer!
It would work the first time, and give me an error every time after that. The cause was that I needed to add
".Delete" after the with .Validation portion, to clear out the pre-existing data validation settings on that cell.
With ActiveWorkbook.Sheets(1).Range("D5").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=listProcesses"
End With
| |
doc_23527475
|
Are there any means in DOM or other libraries to keep data in sync with my objects? I.e. I wish to write back only what was changed?
| |
doc_23527476
|
At first I installed Flask without creating virtual environment, so I thought that that could be a reason. However, I later created virtual environment for my app using:
python3.4 -m venv venv
source venv/bin/activate
(venv) pip3 install Flask
I checked by running my app using python3 __init.py and it was working on local.
Then I reloaded my apache2 server, and still getting the same error. Please see below output from error log file:
mod_wsgi (pid=25667): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=25667): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'.
Traceback (most recent call last):
File "/var/www/FlaskApp/flaskapp.wsgi", line 11, in <module>
from XYZ import app as application
File "/var/www/FlaskApp/XYZ/__init__.py", line 1, in <module>
from flask import Flask, render_template
ImportError: No module named flask
Any suggestions how to fix it?
FlaskApp.conf file in the etc/apache2/sites-available
<VirtualHost *:80>
ServerName xyz.com
ServerAlias www.xyz.com
ServerAdmin contact@xyz.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/XYZ/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/XYZ/static
<Directory /var/www/FlaskApp/XYZ/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Here's line from apache2 error log file:
AH00489: Apache/2.4.10 (Ubuntu) mod_wsgi/3.5 Python/2.7.8 configured -- resuming normal operations
It looks like mod_wsgi is trying to use 2.7.8 as opposed to 3.4. How do I fix that?
A: I think I finally solved it!
I added the following line of code to FlaskApp.conf file located in etc/apache2/sites-available:
WSGIPythonPath /var/www/FlaskApp/XYZ/venv/:/var/www/FlaskApp/XYZ/venv/lib/python3.4/site-packages
This line should go ahead of VirtualHost!
Then I restarted apache and got my site working, except only with www, non-www does not work.
A: I changed my xx.wsgi from using execfile() to using exec(). Here is what it looks like when it finally worked.
activate_this = '/opt/flask/project_name/py3venv/bin/activate_this.py'
exec(open(activate_this).read(), dict(__file__=activate_this))
import sys
sys.path.insert(0, '/opt/flask/project_name')
from project_app_name import app as application
A: mod_wsgi likely doesn't know about your virtualenv, and simply needs to be told to use that rather than the default system environment.
This info in the Django docs should help.
If it doesn't, please post your flaskapp.wsgi and httpd.conf files.
| |
doc_23527477
|
Error Domain=ADErrorDomain Code=3 "The operation couldn’t be completed. Ad inventory unavailable"
UserInfo=0x118bb420 {ADInternalErrorCode=3, ADInternalErrorDomain=ADErrorDomain, NSLocalizedFailureReason=Ad inventory unavailable}
Can you please tell me its my coding problem or it is the problem form Apple site?
I am allocating iAd object in App Delegate and delegates are also in App Delegate. Here is the code:-
AppDelegate *appDel=(AppDelegate*)[UIApplication sharedApplication].delegate;
CGRect rect1 = CGRectMake( 0.0,300,320,50);
appDel.adBanner = [[ADBannerView alloc] initWithFrame:rect1];
appDel.adBanner.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
appDel.adBanner.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
[appDel.adBanner setHidden:YES];
appDel.adBanner.delegate = self;
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
AppDelegate *app=(AppDelegate*)[UIApplication sharedApplication].delegate;
NSLog(@"iAd load");
app.adBanner.frame=CGRectMake( 0.0,300,320,50);
app.adBanner.hidden=NO;
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
AppDelegate *app=(AppDelegate*)[UIApplication sharedApplication].delegate;
NSLog(@"iAd error: %@", error);
app.adBanner.hidden=YES;
app.adBanner.frame=CGRectMake( 0.0,350,0,0);
}
Then I am adding banner in Abstract UIViewConroller Class
CGFloat y=0;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
y=result.height;
}
AppDelegate *app=(AppDelegate*)[UIApplication sharedApplication].delegate;
CGRect rect2 = CGRectMake( 0.0,y-50,320,50);
app.adBanner.frame =rect2;
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
[topController.view addSubview:app.adBanner];
Thanks in advance for the help.
A: Are you testing on simulator? Probably the issue lies in the domain when you test iAds in iOS simulator. Try testing on device, if the issue persists add some code in question to help us understand where the actual problem is
| |
doc_23527478
|
But I have desktop that
CPU : Core 2Duo
RAM : 4 GB
HDD : 500 GB
It's been week when I just run some basic apps but it's very headache to do it for basics app because my android studio every minute got hang and start lagging I can't open chrome there full of warehouse of my problems related to pc because of android studio
Anyone know any hacks or by tips for me you can feel free for it.
A: The only hacks I can think of are:
*
*Make sure you are not using a remote mounted file system or "share" for either your Android Studio + Java installation or your AS workspace.
*Shutoff (quit) all other applications that are using significant amounts of RAM; e.g. your web browsers, your email tool, Slack, Zoom, etc.
*If you are using Windows, switch to Linux.
Better idea: get a better development machine. I think that the RAM is most important, because it sounds like your machine is thrashing.
A: Putting it bluntly: those specs are simply not enough to do any serious modern development. If you could replacing the HDD with an SSD (even a small, cheap one) would be the highest priority and more memory is second. A better CPU would obviously help, but it's a luxury, the other two items are more important.
Assuming that's not an option, you can do either of those two things:
*
*don't use an IDE (or at least a more light-weight one, such as VS Code) and build your software from the command line. This will be more painful (especially when you're just starting) and even then the resource requirements of the build will be non-trivial.
*Make sure to do as little as possible on your local machine. If you have a decent internet connection, then you might be better off developing on a free remote cloud computer and use something like Projector to show the UI in the browser. I've found this repo with instructions on how to use it with Android Studio, which seems useful, but I've not verified that it works.
A: It may seem unfair but Android Studio is not really suitable to run in a lower end device. It used to lag/hang in my device with Core i7 and 8GB Ram. The best thing you can do is to use an SSD instead of HDD. SSDs with smaller memory are often cheap and this alone can somewhat lessen your problems with Android Studio.
A: i think you should change your HDD to 240 GB SSD and it will works fine
| |
doc_23527479
|
When I built on localhost and then served with everything worked fine so it shouldn't be a problem with the index.html file.
I have been following this guide: https://github.com/Sanjeev-Thiyagarajan/PERN-STACK-DEPLOYMENT
npm install -g serve
serve -s build
ubuntu@ip-hidden:~/apps/bachelor-app/client$ ls
README.md build netlify.toml node_modules package-lock.json package.json public src
ubuntu@ip-hidden:~/apps/bachelor-app/client$ cd build
ubuntu@ip-hidden:~/apps/bachelor-app/client/build$ ls
asset-manifest.json icon.ico index.html logo192.png logo512.png manifest.json robots.txt static
ubuntu@ip-hidden:~/apps/bachelor-app/client/build$ cd /etc/nginx/sites-available
ubuntu@ip-hidden:/etc/nginx/sites-available$ cat dataviz
##
# Default server configuration
server {
listen 80;
listen [::]:80;
root /home/ubuntu/apps/bachelor-app/client/build;
# Add index.php to the liphpinfo.php
server_name [Hidden];
index index.html index.htm index.nginx-debian.html;
}
| |
doc_23527480
|
Using the example in this guide, I was wondering how you could translate an interpolated value being passed in. So say I have something as follows for displaying some validation text to the user.
html
<div ng-message="required" translate="REQUIRED_FIELD" translate-value-field="Description"></div>
locale file
{
"REQUIRED_FIELD": "{{field}} is required",
}
A problem I see with this is that Description is being used literally and therefore not translated.
Could a filter be used for the value being assigned to the translate-value-* directive like so:
html
<div ng-message="required" translate="REQUIRED_FIELD" translate-value-field="{{'GENERAL_TERMS.DESCRIPTION' | translate}}"></div>
locale file
{
"REQUIRED_FIELD": "{{field}} is required",
"GENERAL_TERMS": {
"DESCRIPTION": "Description"
}
}
This does work for me locally, but I wondered whether this approach is correct.
Can anyone offer any advice please?
Thanks
A: This worked for me locally
html tag
<div ng-message="required" translate="REQUIRED_FIELD" translate-value-field="{{'TESTKEY' | translate}}"></div>
with input
{
"REQUIRED_FIELD": "{{field}} is required",
"TESTKEY": "Name"
}
so your approach seems to be correct.
Maybe the problem lies with the translation namespace GENERAL_TERMS.DESCRIPTION key?
| |
doc_23527481
|
hover( handlerIn(eventObject),
handlerOut(eventObject) )
$(".box").each(function() {
var $this = $(this);
$this.data('baseColor', $this.css('background-color'));
$this.hover(function() {
$this.animate( {
backgroundColor : "white"
}, 50);
}, function() {
$this.animate( {
backgroundColor : $this.data('baseColor')
}, 50);
});
});
The problem is when DOM changes the hover effect does not work anymore. I know the live method solved such problems many times for me but how do I solve it in that case?
A: From the manual:
All animated properties should be animated
to a single numeric value, except as
noted below; most properties that are
non-numeric cannot be animated using
basic jQuery functionality. (For
example, width, height, or left can be
animated but background-color cannot
be.) Property values are treated as a
number of pixels unless otherwise
specified. The units em and % can be
specified where applicable.
Specifically For example, width, height, or left can be animated but background-color cannot be.
If you're trying just to update the background color to white, try:
$this.hover(function() {
$this.css('background-color', '#fff');
}, function() {
$this.css('background-color',$this.data('baseColor'));
});
If you're trying to make the effect appear 50ms after the user hovers, try using delay.
Now if you're attempting a transition from the current color to white, you need to learn about color blending. But to save you the trouble here's an excellent script by Michael Leigeber. It supports background color fading.
| |
doc_23527482
|
The generate() function generates a value of '2' in a random empty element
It works just fine and creates one random '2' for me, but the problem starts when I want to call it twice in a handler like this:
const handleNewGame = () => {
generate()
generate()
}
I've read about prevState but have no idea how to implement it in this batch of code to work properly.
Here is my game component:
const width = 4;
const Game = () => {
const [Board, setBoard] = useState([]);
const createBoard = () => {
let initialBoard = [];
for (let i = 0; i < width * width; i++) {
initialBoard.push("");
}
return initialBoard;
};
const generate = () => {
let board = [...Board];
let randomNumber = Math.floor(Math.random() * Board.length);
console.log(randomNumber);
if (board[randomNumber] === "") {
board[randomNumber] = 2;
setBoard(board);
} else generate()
};
const handleNewGame = () => {
generate()
generate()
}
useEffect(() => {
setBoard(createBoard);
console.log(`Board Created!`);
}, []);
return (
<div className="game-container">
<button onClick={handleNewGame}>NewGame</button>
<div className="game">
{Board.map((value, index) => (
<div className="tile" key={index}>
{value}
</div>
))}
</div>
</div>
);
};
export default Game;
I'll be glad for the answer.
A: setState(), named setBoard() in your code is asynchronous, whatch this great video on the Event Loop for you to understand more: https://www.youtube.com/watch?v=8aGhZQkoFbQ.
See if this will suit your needs:
import { useEffect, useState } from 'react';
const width = 4;
const Game = () => {
const [Board, setBoard] = useState([]);
const createBoard = () => {
let initialBoard = [];
for (let i = 0; i < width * width; i++) {
initialBoard.push('');
}
return initialBoard;
};
const randomBoardPosition = () => {
return Math.floor(Math.random() * Board.length);
};
const generate = () => {
let board = createBoard();
let randomNumber = randomBoardPosition();
let positionsFilled = 0;
while (positionsFilled < 2) {
if (board[randomNumber] === '') {
board[randomNumber] = 2;
positionsFilled++;
} else {
randomNumber = randomBoardPosition();
}
}
setBoard(board);
};
const handleNewGame = () => {
generate();
};
useEffect(() => {
setBoard(createBoard);
console.log(`Board Created!`);
}, []);
return (
<div className="game-container">
<button onClick={handleNewGame}>NewGame</button>
<div className="game">
{Board.map((value, index) => (
<div className="tile" key={index}>
{value}
</div>
))}
</div>
</div>
);
};
export default Game;
A: Just us function instead of value
const generate = () => {
setBoard(Board => {
let board = [...Board];
while (true) {
let randomNumber = Math.floor(Math.random() * Board.length);
console.log(randomNumber);
if (board[randomNumber] === "") {
board[randomNumber] = 2;
break
}
}
}
}
| |
doc_23527483
|
constexpr uint64_t double_to_uint64_t(double d) {
??????
}
So that
constexpr uint64_t two_bits = double_to_uint64_t(2.0);
would compile?
The reverse method (uint64 to double) is also of interest.
A: Not until C++20. All of the usual tricks are either outright forbidden (reinterpret_cast) or undefined behavior, and UB becomes ill-formed when executed at compile-time.
C++20 provides std::bit_cast, which does binary conversion between two types, so long as they are both trivially copyable and have the same size. And the function is constexpr, so you can use it at compile-time.
| |
doc_23527484
|
Thanks for sharing your time.
A: You might find this short article useful: http://forums.asp.net/t/1023838.aspx
| |
doc_23527485
|
public class ItemDiscount {
public static void main(String[] args) {
int a = 0;
int b = 5;
final int DISCOUNT1 = 1-12;
final int DISCOUNT2 = 13-49;
final int DISCOUNT3 = 50-99;
final int DISCOUNT4 = 100-199;
final int DISCOUNT5 = 200;
int [] Purchased_Item = {DISCOUNT1, DISCOUNT2, DISCOUNT3, DISCOUNT4, DISCOUNT5};
double [] Discount = {0.00, 0.10, 0.14, 0.18, 0.20};
double ItemDiscount = 0;
int Item1 = 0;
boolean Item = false;
Scanner input = new Scanner (System.in);
System.out.println("Enter the number of item/s you purchased: ");
int num_of_item = input.nextInt();
for (int x = 0; x < b; x++){
if (Item1 == Purchased_Item[x]){
Item = true;
ItemDiscount = Discount[x];
}
}
if (Item)
System.out.println("No Discount");
else
System.out.println("The discount of " + num_of_item +" items is " + ItemDiscount);
}
}
This is the code that I've been working on. You insert the number of items that you will purchase and the system should give an output if you have a discount.
This is a program that allows the user to enter the number of items and checks the discounts.
This is the guide table
This is the output
The output I've been getting keeps giving me 0.0 or 0% discount when I input any number. Thought it should say that when you enter 200 and above you should have a discount of 0.20 or 20%.
Please give me suggestions and teach me what I should be doing. Thank you
A: I'd personally choose a different data structure to hold the discount levels - for example a LinkedHashMap, which in layman's terms is a HashMap that stays in the order that you create it. Storing 2 sets of values separately even though they are obviously linked to one another is not a good idea. Then make a method that returns the correct discount level based on the amount of purchased items. Let's call this class Discount.class:
import java.util.LinkedHashMap;
import java.util.Map;
public class Discount {
private Map<Integer, Double> discountMap;
public Discount() {
discountMap = new LinkedHashMap<Integer, Double>();
discountMap.put(0, 0.00d);
discountMap.put(12, 0.10d);
discountMap.put(49, 0.14d);
discountMap.put(99, 0.18d);
discountMap.put(199, 0.20d);
}
public Double getDiscountAmount(int amountPurchased) {
Double currentDiscount = 0.00d;
for (Map.Entry<Integer, Double> entry : discountMap.entrySet()) {
if (amountPurchased > entry.getKey()) {
currentDiscount = entry.getValue();
} else {
return currentDiscount;
}
}
return currentDiscount;
}
}
Then you can use this class in your program to get the level of discount that you should apply
Scanner input = new Scanner (System.in);
System.out.println("Enter the number of item/s you purchased: ");
int numberOfItems = input.nextInt();
Discount discount = new Discount();
Double discountAmount = discount.getDiscountAmount(numberOfItems);
System.out.printf("The discount of %s items is %s%%",
numberOfItems,
Math.round(discountAmount*100));
There are more "slicker" solutions to this problem, the way this solution is written is just for the sake of clarity.
| |
doc_23527486
|
*
*Create the replicaset to create pod.
*Create Service. (followed the nodeport method on 'Kubernetes in Action').
*Create ingress.
ReplicaSet, Service, Ingress are created successfully, nodeport can be accessed from the public IP address, no UNHEALTHY in ingress.
replicaset:
apiVersion: apps/v1beta2
kind: ReplicaSet
metadata:
name: kubia
spec:
replicas: 3
selector:
matchLabels:
app: kubia
template:
metadata:
labels:
app: kubia
spec:
containers:
- name: kubia
image: sonyfaye/kubia
Service:
apiVersion: v1
kind: Service
metadata:
name: kubia-nodeport
spec:
type: NodePort
ports:
- port: 80
targetPort: 8080
nodePort: 30123
selector:
app: kubia
Ingress:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: kubia
spec:
rules:
- host: kubia.example.com
http:
paths:
- path: /
backend:
serviceName: kubia-nodeport
servicePort: 80
The nodeport itself can be accessed from public IP addresses.
C:\kube>kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.59.240.1 <none> 443/TCP 8d
kubia-nodeport NodePort 10.59.253.10 <none> 80:30123/TCP 20h
C:\kube>kubectl get node
NAME STATUS ROLES AGE VERSION
gke-kubia-default-pool-08dd2133-qbz6 Ready <none> 8d v1.12.8-gke.6
gke-kubia-default-pool-183639fa-18vr Ready <none> 8d v1.12.8-gke.6
gke-kubia-default-pool-42725220-43q8 Ready <none> 8d v1.12.8-gke.6
C:\kube>kubectl get node -o wide
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
gke-kubia-default-pool-08dd2133-qbz6 Ready <none> 8d v1.12.8-gke.6 10.140.0.17 35.201.224.238 Container-Optimized OS from Google 4.14.119+ docker://17.3.2
gke-kubia-default-pool-183639fa-18vr Ready <none> 8d v1.12.8-gke.6 10.140.0.18 35.229.152.12 Container-Optimized OS from Google 4.14.119+ docker://17.3.2
gke-kubia-default-pool-42725220-43q8 Ready <none> 8d v1.12.8-gke.6 10.140.0.16 34.80.225.64 Container-Optimized OS from Google 4.14.119+ docker://17.3.2
C:\kube>curl http://34.80.225.64:30123
You've hit kubia-j2lnr
But the ingress can't be accessed from outside.
hosts file:
34.98.92.110 kubia.example.com
C:\kube>kubectl describe ingress
Name: kubia
Namespace: default
Address: 34.98.92.110
Default backend: default-http-backend:80 (10.56.0.7:8080)
Rules:
Host Path Backends
---- ---- --------
kubia.example.com
/ kubia-nodeport:80 (10.56.0.14:8080,10.56.1.6:8080,10.56.3.4:8080)
Annotations:
ingress.kubernetes.io/backends: {"k8s-be-30123--c4addd497b1e0a6d":"HEALTHY","k8s-be-30594--c4addd497b1e0a6d":"HEALTHY"}
ingress.kubernetes.io/forwarding-rule: k8s-fw-default-kubia--c4addd497b1e0a6d
ingress.kubernetes.io/target-proxy: k8s-tp-default-kubia--c4addd497b1e0a6d
ingress.kubernetes.io/url-map: k8s-um-default-kubia--c4addd497b1e0a6d
Events:
<none>
C:\kube>curl http://kubia.example.com
curl: (7) Failed to connect to kubia.example.com port 80: Timed out
C:\kube>telnet kubia.example.com 80
Connecting To kubia.example.com...
C:\kube>telnet 34.98.92.110 80
Connecting To 34.98.92.110...Could not open connection to the host, on port 80: Connect failed
Tried from intranet.
curl 34.98.92.110 IP can get some resule, and 80 port of 34.98.92.110 is accessible from intranet.
C:\kube>kubectl exec -it kubia-lrt9x bash
root@kubia-lrt9x:/# curl http://kubia.example.com
curl: (6) Could not resolve host: kubia.example.com
root@kubia-lrt9x:/# curl http://34.98.92.110
default backend - 404root@kubia-lrt9x:/# curl http://34.98.92.110
default backend - 404root@kubia-lrt9x:/#
root@kubia-lrt9x:/# curl http://10.56.0.7:8080
default backend - 404root@kubia-lrt9x:/#
Does anybody know how to debug this?
The nodeport is been added to the firewall, or else nodeport is not accessible. The Ingress IP seems don't need to be added to the firewall.
A: Try to expose replicaset to be able to connect from the outside:
$ kubectl expose rs hello-world --type=NodePort --name=my-service
remember to first delete service kubia-nodeport and delete selector and section with service in Ingress configuration file and then apply changes using kubectl apply command.
More information you can find here: exposing-externalip.
Useful doc: kubectl-expose.
| |
doc_23527487
|
What's important is the name, if the name can be the same, it is ideal.
Thanks all.
A: you can unpublish but once your application has been live on the market you cannot delete it.
Yes, you can have multiple apps in the play store with the same display name, but they have to have different package names
If you lost your keystore then there is no way that you can update the app in play sore( it will cause a signature error )!
The only way is that you can create an app with a new package name upload it to store and remove the old app.
| |
doc_23527488
|
The type attribute have the type of HTMLInputTypeAttribute that's an union type that ends up with (string & {}). I don't want the component to receive type values that are not literal described in the union.
Using the Exclude utility type results in never since all literal types extends from string
I've already looked at other questions like How can I remove a wider type from a union type without removing its subtypes in TypeScript? but as their intent was not necessarily related to a previously established union, none of the answers met my need
Is this somehow possible?
A: You need to use Distributive conditional types
type Union = 'a' | 'b' | string & {}
type GetLiteral<Type extends string | number, Value> =
Value extends Type
? (Type extends Value
? never
: Value)
: never
type ObtainLiterals<T> = T extends infer R ? GetLiteral<string, R> : never
// 'a' | 'b'
type Test = ObtainLiterals<Union>
Playground
GetLiteral expects a type of union which corresponds to Type and a value which corresponds to Value generic.
ObtainLiterals - distributes a union. It means that each element in the union is called with GetLiteral which at the end produces 'a'|'b'|never. And never is always getting removed from the union.
| |
doc_23527489
|
A: looks like you can get it from: requestContext.ServiceHost.Name from the handler
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext
| |
doc_23527490
|
Example:
WITH q AS
(...)
SELECT q1.title AS title1, q2.title AS title2
FROM
q AS q1
INNER JOIN
q AS q2 USING(id)
WHERE q1.title != q2.title
EDIT: Assuming multiple titles can be recognised by the same id (kind of a bad choice of name)
So q is a predefined query, which has two columns, being "title" and "id". Combining them this way logically gives me these results:
title1 -- title2
x1 -- y1
y1 -- x1
...
xn -- yn
yn -- xn
etc. But I only need the xi -- yi sets (0 < i <= n).
What would be the best way to do this?
A: Just change != for <
WHERE q1.title < q2.title
| |
doc_23527491
|
{{#each MyApp.listController}}
{{firstName}} {{lastName}}
{{/each}}
This is how the ArrayController is used:
MyApp.listController = Ember.ArrayController.create();
$.get('people.json', function(data) {
MyApp.listController.set('content', data);
});
How would this work differently than using a plain array like this instead?
MyApp.listController = [];
$.get('people.json', function(data) {
MyApp.set('listController', data);
});
A: If you don't need the behavior of a controller, you can use a plain array.
An ArrayController wraps an array, with some other properties added, such as the sortable mixin.
You can see it here:
https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/controllers/array_controller.js
A: in the ember.js documentation says:
(http://docs.emberjs.com/symbols/Ember.ArrayController.html)
The advantage of using an ArrayController is that you only have to set
up your view bindings once; to change what's displayed, simply swap
out the content property on the controller.
it uses an Array in background, only helps with methods to work with the array:
Although you are binding to the controller, the behavior of this
controller is to pass through any methods or properties to the
underlying array
| |
doc_23527492
|
The current application is able to:
*
*open BeamNG
*load a scenario
*control the spawned vehicle.
But I have problems retrieving the current vstate of the vehicle. As I discovered the vstate is properly requested and the put method of beamngs queue collecting the results of these requests is called but the queue stays empty and so I can not get the current vstate.
import time
import beamngpy
BEAMNG_BASEDIR = '<BeamNG_basedir>'
BEAMNG_X64_BINARY = '<BeamNG_64bit_binary>'
with beamngpy.beamng.BeamNGPy('localhost', 64256, userpath='<BeamNGUserpath>',
binary=BEAMNG_X64_BINARY, console=True) as bpy:
bpy.load_scenario('levels/west_coast_usa/scenarios/my_first_scenario.json')
time.sleep(10)
bpy.start_scenario()
bpy.vcontrol({
'throttle': 1.0,
'steering': 0.5,
'gear': 1
})
for _ in range(3):
bpy.req_vstate(800, 600)
time.sleep(1)
for i, vstate in enumerate(bpy.poll_all()):
vstate['img'].save(f'<outputPath>/{i:02}.png')
EDIT:
I realized that the error occurrs in the a lua file of BeamNG.research.
More precisely <beamNG_basedir>/lua/ge/extensions/util/researchAdapter.lua line 180.
The call to Engine.getColorBufferBase64(width, height) fails with the following message.
025.668|E|GameEngineLua:Exception|lua/ge/extensions//util/researchAdapter.lua:180: attempt to call field 'getColorBufferBase64' (a nil value)
=============== Stack Traceback >> START >>
(1) field C function 'getColorBufferBase64'
(2) Lua upvalue 'getVehicleState' at file 'lua/ge/extensions//util/researchAdapter.lua:180'
Local variables:
width = number: 800
height = number: 600
state = table: 0x01e121142160 {clutch:0, rot:-111.05878753658, steering:-0, vel:table: 0x01e1143b6920 (more...)}
vdata = table: 0x01e120efaaf8 {vel:vec3(-0.000107339,9.26956e-05,-8.04267e-05), active:true, dirVecUp:vec3(-0.00877159,0.00343826,0.999956) (more...)}
(*temporary) = nil
(*temporary) = number: 1.02085e-311
(*temporary) = number: 800
(*temporary) = number: 600
(*temporary) = number: -0.933169
(*temporary) = number: -0.359309
(*temporary) = number: 1.02085e-311
(*temporary) = number: -0.359309
(*temporary) = number: 0
(*temporary) = number: -1
(*temporary) = string: "attempt to call field 'getColorBufferBase64' (a nil value)"
(3) Lua local 'handler' at file 'lua/ge/extensions//util/researchAdapter.lua:220'
Local variables:
msg = table: 0x01e121049f10 {type:ReqVState, width:800, height:600}
width = number: 800
height = number: 600
(4) Lua upvalue 'handleSocketInput' at file 'lua/ge/extensions//util/researchAdapter.lua:289'
Local variables:
message = table: 0x01e121049f10 {type:ReqVState, width:800, height:600}
msgType = string: "handleReqVState"
handler = Lua function 'handleReqVState' (defined at line 210 of chunk lua/ge/extensions//util/researchAdapter.lua)
(5) Lua function 'onUpdate' at file 'lua/ge/extensions//util/researchAdapter.lua:310' (best guess)
Local variables:
dt = number: 0.0329248
(6) Lua field 'hook' at file 'lua/common/extensions.lua:454'
Local variables:
func = string: "onUpdate"
funcList = table: 0x01e1211f8780 {1:function: 0x01e11437dc98, 2:function: 0x01e11434a720, 3:function: 0x01e11426daf8 (more...)}
(for index) = number: 5
(for limit) = number: 12
(for step) = number: 1
i = number: 5
(7) Lua function 'update' at file 'lua/ge/main.lua:362' (best guess)
Local variables:
dtReal = number: 0.0329248
dtSim = number: 0.033
dtRaw = number: 0.0329855
--------------- << END <<
| |
doc_23527493
|
I've tried calling on a method in MyAdapter such as
public void updateExerciseNames(String name) {
exerciseNames.add(name);
counter++;
}
(updates an arraylist with strings that should appear on a textview and then the textview is updated.)
Creating a getString method in my Main_Activity that retrieves the string required.
Using an intent.
This is what my custom adapter looks like
public class MyAdapter extends ArrayAdapter<String> {
private ArrayList<String> list;
private Context context;
private TextView list_txt;
public MyAdapter(ArrayList<String> records, Context context) {
super(context, 0, records);
this.list = records;
}
@Override
public View getView (final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
Button list_but=(Button)convertView.findViewById(R.id.list_but);
TextView list_txt = (TextView)convertView.findViewById((R.id.list_txt));
list_but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
list.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
A: You can do that using another constructor like the one you made
MyAdapter(ArrayList<String> records, Context context,YOUR_DATA_TYPE your_data)
| |
doc_23527494
|
when I console log params.title
console: android-paging-advanced-codelab
but
when I try to console log params.id,
console: undefined
I need to access both params inside the getStaticProps so I can use the exact data I need.
I did try context by passing context and using context.params.id but the result is the same.
read the code below and help me, please!
Here you can see the code of my getStaticPaths :
export async function getStaticPaths(){
const { data } = await client.query({
query: gql`
query {
postContents{
data{
attributes{
post_card{
data{
id
attributes{
TitleForLink
}
}
}
}
}
}
}
`
})
const paths = data.postContents.data.map((item)=> {
return {
params: {
id: item.attributes.post_card.data.id.toString(),
title: item.attributes.post_card.data.attributes.TitleForLink.toString(),
}
}
})
return {
paths,
fallback: false,
}
}
And the code of getStaticProps:
export async function getStaticProps({params}){
const { data } = await client.query({
query: gql`
query {
postCards{
data{
id
attributes{
post_content{
data{
id
attributes{
Title
Description
}
}
}
}
}
}
}
`
})
console.log(params.id)
return {
props: {
content: data.postCards.data,
}
}
}
A: The getStaticPaths function should return an object with paths parameters that determines which paths will be pre-rendered only, you can pass additional properties like locale if you have i18 configured.
So you need to make another fetching in the getStaticProps function.
| |
doc_23527495
|
How can I programmatically active ReactDevtools to access this value?
| |
doc_23527496
|
block.h:13:7: note: candidate expects 1 argument, 0 provided
Line 13 is line where is create the class. Here is the Block header file:
#ifndef BLOCK_H
#define BLOCK_H
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Shader.h"
#include "Camera.h"
using namespace glm;
class Block{
public:
void render(Camera cam);
glm::vec3 position;
Block(glm::vec3 position);
private:
void createMesh();
GLuint VAO, VBO;
Shader shader;
};
#endif
The complete error:
world.cpp: In constructor ‘World::World(GLFWwindow*)’:
world.cpp:3:32: error: no matching function for call to ‘Block::Block()’
World::World(GLFWwindow* window)
^
world.cpp:3:32: note: candidates are:
In file included from world.h:9:0,
from world.cpp:1:
block.h:17:2: note: Block::Block(glm::vec3)
Block(glm::vec3 position);
^
block.h:17:2: note: candidate expects 1 argument, 0 provided
block.h:13:7: note: Block::Block(const Block&)
class Block{
^
block.h:13:7: note: candidate expects 1 argument, 0 provided
I am also receiving many other similar compiler errors, here is the output:
http://pastie.org/10691691
---EDIT---
Ok, i have shortend the error down a bit.
Here is the updated error log: http://pastie.org/10691707
A: I saw an error saying that Shader does not have a default constructor, i.e Shader::Shader(). For that error, your constructor for your Block class is going to need to construct it in the member initializer list.
For example
Block::Block(glm::vec3 position)
: m_Shader( "needed shader args" )
{
}
It further looked like you were attempting to construct one of your Blocks somewhere, in a world class?. There too it was complaining about lack of default constructor for Block. If you want default constructor, you must define one in your block class definition. Or you need to initialize your block class in the World class's member initializer list, just like the above example with the shader.
As the compiler suggests, you could also use in class member initializers, but you'd need to turn on C++11 support for that.
A: Your definition of Block requires an argument of glm::vec3 to be passed during its construction (or a Block itself for copy construction). Your constructor of World appears to not supply such an argument.
A: Turns out I had to also put a empty override constructor in every class. The issue was i was calling a constructor when i created the variables as well as when I was instantiating the object. Here is a quick example:
Shader::Shader(){
//Do nothing here is it just a override so we declare the variable before creating it.
}
Shader::Shader(char* vpath, char* fpath){
//Do proper shader stuff here
}
| |
doc_23527497
|
const { useAppDispatch } = useReduxApp();
const dispatch = useAppDispatch();
const [tabs, setTabs] = useState<TabItem[]>(initialTabs);
const newCase = {
key: String(keyNo),
title: (
<div style={{ color: 'red' }}>
New Case {keyNo}
<div className={s.btnCloseTab} onClick={() => delCase(keyNo)}>
<i className="bi bi-x-circle-fill"></i>
</div>
</div>
),
children: <CreateForm keyNo={keyNo} />,
};
const addCase = () => {
setKeyNo((prev) => prev + 1);
const newTabs = [...tabs, newCase];
setTabs(newTabs);
};
const delCase = (id) => {
console.log(id);
console.log(tabs);
};
enter image description here
i just have 6 objects when i click on the X button , missing the object with "key 5" (New Case 5), i dont know what's wrong, please help me
A: Try with updater function,
const addCase = () => {
setKeyNo((prev) => prev + 1);
setTabs(currentTabs => currentTabs.concat(new case)); };
A: As you can see in your console.log. You have 6 object with keys : "myWork","0","1","2","3","4". So there really is no item with key "5", you are missing it or there is something wrong with your logic depending on what you want to do. For example mby you are taking indexes[1,2,3,4,5] instead of [0,1,2,3,4]
| |
doc_23527498
|
from github import Github
def get_helm(filename):
f = open(filename, 'w') # The file I want to copy the binary to
g = Github()
r = g.get_repo("helm/helm")
# Get binary and use f.write() to transfer it to the file
f.close
return filename
I am also well aware of the limits of queries that I can do since there are no credentials.
A: For Helm in particular, you're not going to have a good time since they apparently don't publish their release files via GitHub, only the checksum metadata.
See https://github.com/helm/helm/releases/tag/v3.6.0 ...
Otherwise, this would be as simple as:
*
*get the JSON data from https://api.github.com/repos/{repo}/releases
*get the first release in the list (it's the newest)
*look through the assets of that release to find the file you need (e.g. for your architecture)
*download it using your favorite HTTP client (e.g. the one you used to get the JSON data in the first step)
Nevertheless, here's a script that works for Helm's additional hoops-to-jump-through:
import requests
def download_binary_with_progress(source_url, dest_filename):
binary_resp = requests.get(source_url, stream=True)
binary_resp.raise_for_status()
with open(dest_filename, "wb") as f:
for chunk in binary_resp.iter_content(chunk_size=524288):
f.write(chunk)
print(f.tell(), "bytes written")
return dest_filename
def download_newest_helm(desired_architecture):
releases_resp = requests.get(
f"https://api.github.com/repos/helm/helm/releases"
)
releases_resp.raise_for_status()
releases_data = releases_resp.json()
newest_release = releases_data[0]
for asset in newest_release.get("assets", []):
name = asset["name"]
# For a project using regular releases, this would be simplified to
# checking for the desired architecture and doing
# download_binary_with_progress(asset["browser_download_url"], name)
if desired_architecture in name and name.endswith(".tar.gz.asc"):
tarball_filename = name.replace(".tar.gz.asc", ".tar.gz")
tarball_url = f"https://get.helm.sh/{tarball_filename}"
return download_binary_with_progress(
source_url=tarball_url, dest_filename=tarball_filename
)
raise ValueError("No matching release found")
download_newest_helm("darwin-arm64")
| |
doc_23527499
|
*
*A page content table that contains all the information from the crawled pages as well as some meta data of those pages (like publishing dates that are updated from an external source)
*
*Table name: pages
*Columns: id (PK), url, publishingDate, name, description, category...
*Size: about 500K of rows
*A table of pages in need of crawling. Rows in this table are added by an external system but removed when a crawler has completed crawling of a page in this table.
*
*Table name: needsCrawling
*Column: pageId (FK of pages)
*Size: at most 50K
*A crawler task table that contains a set of pages that a certin crawler should crawl:
*
*Table name: crawlerTaskList
*Columns: id (PK), crawlerId (FK of a table called crawlers), pageId (FK of pages)
*Size: at most 1K rows (10 crawlers and each crawler never has more than 100 pages in it's task list)
The thought behind this is that table 1 (pages) is used to fetch publishingDates and then used for storing the fetched crawl result. Table number 2 is used for "marking" what pages should be crawled and then remove the "mark" after they have been crawled (the publishing date must still be checked since a page might be in need of crawling when, but not before, the publishing date criteria has been met). Table 3 (crawlerTaskList) is used mainly to prevent crawlers from crawling the same pages.
The query I initially used to fetch url's for the crawlers looked like this:
SELECT id, url
FROM pages
WHERE publishingDate < NOW() - INTERVAL 3 minute
AND DATE_SUB(CURDATE(), INTERVAL 60 DAY) < publishingDate
AND id NOT IN (SELECT pageId FROM crawlerTaskList)
AND id IN (SELECT pageId FROM needsCrawling)
ORDER BY publishingDate
It has worked fine until the pages table reached about 300K. Now I have reached a point where the query takes about 40 seconds and it starts to be unsustainable. I have tried to re-write the query (e.g. use JOINs instead of the id IN/ id NOT IN) but without any improvement so I am in desperate need of suggestions. Maybe I must add an index or something else fancy that is out of my knowledge. Thanks anyone that takes his/her time to read all this and sorry for the LONG post!
A: In earlier versions of MySQL in with a subquery was particularly poorly optimized. Simply moving it to a join can improve performance:
SELECT id, url
FROM pages join
(select distinct pageid from needsCrawling) nc
on pages.id = nc.pageid left outer join
(select distinct pageid from crawlerTaskList) ctl
on pages.id = clt.pageid
WHERE publishingDate < NOW() - INTERVAL 3 minute
AND DATE_SUB(CURDATE(), INTERVAL 60 DAY) < publishingDate
AND id ctl.pageid is null
ORDER BY publishingDate;
Note: the distinct is only there in the event that pageid could be duplicated in either table. You should remove it if you know that it is not duplicated. Also, indexes on needsCrawling(pageid) and crawlerTaskList(pageId) would help improve performance.
A: Try to use EXPLAIN (or explain extended) before select, this should give you the informations you need and give some clues,where to add indexes to speed query up.
A: Every modern database will optimize your query to an extremely good degree, so you can write pretty much anything you want and the DB will optimize it.
So you basically have two options:
Add indexes to your tables or improve your db (I would highly recommend the second)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.