id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527200
|
a = [
['A','B','C','D'],
[None,None,2,None],
[None,1,None,None],
[None,None,8,None],
['W','R',5,'Q'],
['H','S','X','V'],
[None,None,None,7]
]
The expected output would be like this:
b = [
['A','B','C','D'],
['A','B',2,'D'],
['A',1,'C','D'],
['A','B',8,'D'],
['W','R',5,'Q'],
['H','S','X','V'],
['H','S','X',7]
]
I was able to make the next code and seems to work but I was wondering if there is a built-in method or more direct
way to do it. I know that there is something like that using pandas but needs to convert to dataframe, and I want
to continue working with list, if possible only update a list, and if not possible to modify a then get output in b list. Thanks
b = []
for z in a:
if None in z:
b.append([temp[i] if value == None else value for i, value in enumerate(z) ])
else:
b.append(z)
temp = z
A: You could use a list comprehension for this, but I'm not sure it adds a lot to your solution already.
b = [a[0]]
for a_row in a[1:]:
b.append([i if i else j for i,j in zip(a_row, b[-1])])
I'm not sure if it's by design, but in your example a number is never carried down to the next row. If you wanted to ensure that only letters are carried down, this could be added by keeping track of the letters last seen in each position. Assuming that the first row of a is always letters then;
last_seen_letters = a[0]
b = []
for a_row in a:
b.append(b_row := [i if i else j for i,j in zip(a_row, last_seen_letters)])
last_seen_letters = [i if isinstance(i, str) else j for i,j in zip(b_row, last_seen_letters)]
A: First, consider the process of "filling down" into a single row. We have two rows as input: the row above and the row below; we want to consider elements from the two lists pairwise. For each pair, our output is determined by simple logic - use the first value if the second value is None, and the second value otherwise:
def fill_down_new_cell(above, current):
return above if current is None else current
which we then apply to each pair in the pairwise iteration:
def fill_down_new_row(above, current):
return [fill_down_new_cell(a, c) for a, c in zip(above, current)]
Next we need to consider overlapping pairs of rows from our original list. Each time, we replace the contents of the "current" row with the fill_down_row result, by slice-assigning them to the entire list. In this way, we can elegantly update the row list in place, which allows changes to propagate to the next iteration. So:
def fill_down_inplace(rows):
for above, current in zip(rows, rows[1:]):
current[:] = fill_down_new_row(above, current)
Let's test it:
>>> a = [
... ['A','B','C','D'],
... [None,None,2,None],
... [None,1,None,None],
... [None,None,8,None],
... ['W','R',5,'Q'],
... ['H','S','X','V'],
... [None,None,None,7]
... ]
>>> fill_down_inplace(a)
>>> import pprint
>>> pprint.pprint(a)
[['A', 'B', 'C', 'D'],
['A', 'B', 2, 'D'],
['A', 1, 2, 'D'],
['A', 1, 8, 'D'],
['W', 'R', 5, 'Q'],
['H', 'S', 'X', 'V'],
['H', 'S', 'X', 7]]
| |
doc_23527201
|
I am running jquery 2.2.2 at the moment with the jquery validation plugin. https://jqueryvalidation.org/
And Trumbowyg WYSIWYG Editor. https://alex-d.github.io/Trumbowyg/
It's great mostly everything works however, every time a use clicks or does anything really. You get the console error Uncaught TypeError: Cannot read property 'nodeName' of undefined. It also creates certain parts of Trumbowyg to not work properly.
So my solution was to use the ignore class on the jquery validation plugin. But it does not work. I have tried ignoring almost every class labeling for different fields and no matter what I do it is never ignored.
So how do I use the jquery validation plugin, with the trumbowyg text editor?
Here is my validation code.
$('form').validate({
errorPlacement: function (error, element) {
if ($(element).parent('.input-group').length) {
error.insertAfter(element.parent().siblings('label'));
error.addClass('alert alert-danger validate');
} else {
error.insertAfter(element.siblings('label'));
error.addClass('alert alert-danger validate');
}
},
errorElement: 'div',
highlight: function (element) {
$(element).parent().addClass("has-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("has-error");
},
ignore: '.advanced',
rules: {
password_confirm: {
equalTo: 'input[name=password]'
},
user_username: {
remote: {
url: 'action/check/',
type: 'POST',
data: {
id: function () {
return $('input[name=id]').val();
}
}
}
},
nav_name: {
remote: {
url: 'action/check/',
type: 'POST',
data: {
id: function () {
return $('input[name=id]').val();
}
}
}
}
},
messages: {
password_confirm: {
equalTo: "Passwords must match"
},
user_username: {
remote: "This Username already exists"
},
nav_name: {
remote: "This Nav Item Name already exists"
}
},
submitHandler: function (form) {
$('button[type="submit"]').addClass('disabled').prop('disabled', true).prepend('<span class="bootstrap-dialog-button-icon glyphicon glyphicon-asterisk icon-spin"></span>');
form.submit();
}
});
I did remove the validation plugin and everything with trumbowyg did work. So maybe it's time to find a new validation plugin, I really would like to avoid that.
Update: I did notice that firefox is giving me a different error, so I figured I would share that as well.
TypeError: owner is undefined
owner[ this.expando ] && owner[ this.expando ][ key ];
An example of the problem should be available to demo here: http://develop.chrischampeau.com/admin/test.php
A: This is a known issue with the jQuery Validation plugin where content editable elements in forms would cause exceptions when an event is triggered.
You can find this issue describing the exact same problems:
*
*Breaks your WYSIWYG.
*Undefined errors.
*All toolbar buttons in your WYSIWYG take two clicks to trigger.
A modification / hack is proposed in this thread to resolve the issue but a pull request fixing this same issue has already been merged into the project in May.
The problem is that the latest release is from February so this merge is not available at the moment. According to this other issue, a maintainer stated 15 hours ago that a release is coming very soon and it includes the fix for your problem.
If you can't wait for the new release, you can always get the latest version from their repository or cherry pick yourself the fix included in this pull request.
Regarding the second issue you described in a comment after applying the fix from the pull request, jQuery Validation check on various events (onfocusout especially in this case) if an element should be ignored or not by checking if it has a class specified in the settings.
You're adding to your textarea class="advanced" to ignore it, unfortunately, when Trumbowyg is initialized, the wrapper created will be the following:
<div class="trumbowyg-editor trumbowyg-reset-css" contenteditable="true" dir="ltr" placeholder="">
It does not propagates the advanced class to the wrapper. A potential fix is to add yourself this class when Trumbowyg is initialized. To do that, you can rely on the tbwinit event by modifying your constructor.
// Setup WYSIWYG
$('textarea.advanced').trumbowyg( {
resetCss: true,
removeformatPasted: true,
autogrow: true,
btnsDef: {
// Customizables dropdowns
image: {
dropdown: ['insertImage', 'upload', 'base64', 'noEmbed'],
ico: 'insertImage'
}
},
btns: [
['viewHTML'],
['undo', 'redo'],
['formatting'],
'btnGrp-design',
['link'],
['image'],
'btnGrp-justify',
'btnGrp-lists',
['foreColor', 'backColor'],
['preformatted'],
['horizontalRule'],
['fullscreen']
],
plugins: {
// Add imagur parameters to upload plugin
upload: {
serverPath: 'https://api.imgur.com/3/image',
fileFieldName: 'image',
headers: {
'Authorization': 'Client-ID 9e57cb1c4791cea'
},
urlPropertyName: 'data.link'
}
}
}).on('tbwinit', function(){
$('.trumbowyg-editor').addClass('advanced');
});
After initialization, your wrapper will have the advanced class so that jQuery Validation can use it.
<div class="trumbowyg-editor trumbowyg-reset-css advanced" contenteditable="true" dir="ltr" placeholder="">
Regarding the second issue, it's triggered because some libraries like Trumbowyg when they open a popup (like the ones your mentioned in your comment: Insert Link, Insert Image, etc.), they are actually appending a <form> in the DOM but inside another <form> which leads to nested forms.
In the case of nested forms, the second error you mentioned is triggered by jQuery Validation. You can check the comment of the jQuery Validation plugin owner regarding this problem on this message:
Nesting forms is invalid HTML. Either the [...] plugin doesn't generate a form if there is already one, or it has to append it outside the current form.
There is already an issue opened on the Trumbowyg Github regarding this problem, but it's a large modification on the core of the plugin and at this moment, it's moved from milestone to milestone since 2015.
A: If you're still getting the following error on line jquery.validate.min.js:formatted:490 whenever the jQuery validation tries to kick in on a Trumbowyg element:
Uncaught TypeError: Cannot read properties of undefined (reading 'replace')
Try adding a random value to an id attribute in the trumbowyg-editor div.
Something like this will work:
$(".trumbowyg").find(".trumbowyg-editor").attr("id", Math.random());
This may not kick start the actual validation, but it will get rid of the error.
| |
doc_23527202
|
Optional<College> college = Optional.ofNullable(student)
.map(stud -> stud.getCollege())
.get()
.stream()
.filter(college -> Objects.nonNull(college.getCollegeName()))
.findFirst();
Now, while writing an unit test, I got a catch that what if student comes as null?
It would be effectively like:
Optional.empty() // the same as the student is null
.map(stud -> stud.getCollege())
.get()
.stream()
.filter(college -> Objects.nonNull(college.getCollegeName()))
.findFirst();
Which I think is not fine because I am getting Exception
expected<com.src.exceptions.CollegeNotFoundException> but
was<java.util.NoSuchElementException>
#Update
Updating the question details for clarifications
*
*Yes stud.getCollege() returns a list<>
A: I agree with @Nikolas approach except that you should not return null, returning null at last is against using Optional
What about this one:
Optional<College> optional = Optional.ofNullable(student)
.map(stud -> stud.getCollegeList())
.orElse(Collections.emptyList())
.stream()
.filter(c -> Objects.nonNull(c.getCollegeName()))
.findFirst();
A: Calling Optional::get with no previous check Optional::isPresent is dangerous because it might produce CollegeNotFoundException. And it is not the way the Optional shall be used. The idea of Optional is mapping/filtering the values and providing a default value if the Optional ends up with no element (empty).
Assuming Student::getCollege returns List<College> having method College::getCollegeName, you can do the following:
College college = Optional.ofNullable(student)
.map(stud -> stud.getCollege())
// if Optional is empty, then use an empty collection
.orElse(Collections.emptyList())
.stream()
.filter(c -> Objects.nonNull(c.getCollegeName()))
.findFirst()
// get the value or else college is null
.orElse(null);
As long as stud.getCollege() returns null, the Optional becomes empty and an empty list will be streamed. And again the same principle is applied: As long as the list is empty, the filter and findFirst are not be called and null is safely returned (or any default value you wish).
Also note that the line .filter(c -> Objects.nonNull(c.getCollegeName())) might also produce NullPointerException as long as there is not guaranteed stud.getCollege() doesn't return a list with a null element (remember the list is not null itself so Optional treats it as a "valuable" item). The safe code actually looks like:
Optional<College> college = Optional.ofNullable(student)
.map(stud -> stud.getCollege())
.orElse(Collections.emptyList())
.stream()
.filter(c -> c != null && c.getCollegeName() != null)
.findFirst();
Actually, I prefer to return either a null-object, null or Optional itself.
| |
doc_23527203
|
et6.setOnKeyListener((v, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK | keyCode == KeyEvent.KEYCODE_DEL) {
et5.setSelected(true);
et5.requestFocus();
}
return false;
});
Now issue is focus jumps to the edittext 4 instead of editext 5. How to resolve this issue? Please provide your suggestions to fix the issue it would be helpful.
A: Well in this case, this might help you. I am using OTP handling like this:
private fun enterOtp() {
val editTexts: Array<EditText> = arrayOf(etOtp1, etOtp2, etOtp3, etOtp4)
etOtp1.addTextChangedListener(
PinTextWatcher(
0,
editTexts,
otpMandatoryTV,
this
)
)
etOtp2.addTextChangedListener(
PinTextWatcher(
1,
editTexts,
otpMandatoryTV,
this
)
)
etOtp3.addTextChangedListener(
PinTextWatcher(
2,
editTexts,
otpMandatoryTV,
this
)
)
etOtp4.addTextChangedListener(
PinTextWatcher(
3,
editTexts,
otpMandatoryTV,
this
)
)
etOtp1.setOnKeyListener(PinOnKeyListener(0, editTexts))
etOtp2.setOnKeyListener(PinOnKeyListener(1, editTexts))
etOtp3.setOnKeyListener(PinOnKeyListener(2, editTexts))
etOtp4.setOnKeyListener(PinOnKeyListener(3, editTexts))
}
And this is the class:
class PinTextWatcher internal constructor(
private val currentIndex: Int,
private val editTexts: Array<EditText>,
private val mandatoryText: TextView,
private val activity: Activity) : TextWatcher {
private var isFirst = false
private var isLast = false
private var newTypedString = ""
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
newTypedString = s.subSequence(start, start + count).toString().trim { it <= ' ' }
}
override fun afterTextChanged(s: Editable) {
var text = newTypedString
/* Detect paste event and set first char */if (text.length > 1) text =
text[0].toString() // TODO: We can fill out other EditTexts
editTexts.get(currentIndex).removeTextChangedListener(this)
editTexts.get(currentIndex).setText(text)
editTexts.get(currentIndex).setSelection(text.length)
editTexts.get(currentIndex).addTextChangedListener(this)
if (text.length == 1) moveToNext() else if (text.length == 0) moveToPrevious()
mandatoryText.visibility = View.INVISIBLE
}
private fun moveToNext() {
if (!isLast) editTexts.get(currentIndex + 1).requestFocus()
if (isAllEditTextsFilled && isLast) { // isLast is optional
editTexts.get(currentIndex).clearFocus()
hideKeyboard()
}
}
private fun moveToPrevious() {
if (!isFirst) editTexts.get(currentIndex - 1).requestFocus()
}
private val isAllEditTextsFilled: Boolean
private get() {
for (editText in editTexts) if (editText.text.toString()
.trim { it <= ' ' }.length == 0
) return false
return true
}
private fun hideKeyboard() {
if (activity.currentFocus != null) {
val inputMethodManager =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val view = activity.currentFocus
inputMethodManager.hideSoftInputFromWindow(view?.getWindowToken(), 0)
}
}
init {
if (currentIndex == 0) isFirst =
true else if (currentIndex == editTexts.size - 1) isLast = true
}
}
class PinOnKeyListener internal constructor(
private val currentIndex: Int,
private val editTexts: Array<EditText>) : View.OnKeyListener {
override fun onKey(
v: View,
keyCode: Int,
event: KeyEvent
): Boolean {
if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
if (editTexts.get(currentIndex).getText().toString()
.isEmpty() && currentIndex != 0
) editTexts.get(currentIndex - 1).requestFocus()
}
return false
}
}
This code is Kotlin and its working. You can convert to Java. If you are not able to let me know I will help along. Also adjust the handling according to your need. I have used 4 fields for OTP. In your case it will be six.
| |
doc_23527204
|
A:
Is it possible to overload new operator for allocating something like 2d array in C++?
Yes.
but can I get some code example?
Example:
std::unique_ptr<int[][10]> arr {new int[n][10]};
with given "height" and "width"?
Only if the inner dimensions are compile time constant. Only the outer dimension may be dynamic.
It is easy to translate between a dynamic single dimensional flat array, and a multi dimensional one.
A: Unfortunately, the global new operator takes one parameter, so you can not provide it with both "height" and "width". And, the global new/delete operator will be used by not only the code you wrote, but also the library you use, for example std::string, std::vector. So, make such a change may cause nasty problems.
| |
doc_23527205
|
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
A: I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.
| |
doc_23527206
|
So, I found HOG descriptor followed by SVM to detect people. This method works very good for pedestrian because of their arms and legs.
My questions are that
Is that method also works good for my situation?
Are there any other methods to count people pass a door?
How can I improve my background subtraction method to handle multiple people counting?
| |
doc_23527207
|
A: You can always add the individual folder to the TFS through Team Explorer if you cannot do it automatically inside visual studio.
A: As you said you checked in the new project but I think that you did not check in the solution file *.sln.
Each project in your solution is defined in the *.sln file.
simply check in the solution file and it will appear.
| |
doc_23527208
|
I am running it on a dual core machine.
The time taken to run using open mp is about 0.05 sec while it takes only 0.03 sec when I run it without openMP.
#include<omp.h>
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
clock_t start=clock();
int i,j,t1,t2, n=1;
float a[1000][1000];
float b[1000][1000];
#pragma omp parallel
{
#pragma omp for private(i)
for(j=0; j<1000; j++)
{
for(i=0; i<1000; i++)
{
a[i][j]=(i*j*i*j)/(i+j+1)/(i*j*i+8*i+1);
b[i][j]=(i*j*i*j)/(i+j+1)/(i*j*i+8*i+1);
}
}
}
clock_t end=clock();
cout<<"Time to run is "<<(double)(end - start)/CLOCKS_PER_SEC<<endl;
}
| |
doc_23527209
|
I know I have to use httpwebrequest or something sounding similar.
Here is the source page snippet of the result.php page
<form action="resultstatus.php" method="post" name="myform" id="myform">
<p align="center">
<font face="Verdana, Arial, Helvetica, sans-serif" size="2">
<span class="style6">Please enter your Application Number or Registration Number </span>
<input type="text" name="regno" size="12" maxlength="10" />
<input type="submit" name="submit" value="Submit" onenter = "submit" onclick="submit" />
How can I pass this roll no to the server, so that I can have an HTML page to work upon?
How can this be done for a username, password, etc?
this is what i hv done till now and it produces no result :
Byte[] Bytes;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://xvc.com/result.php");
Stream RequestStream;
HttpWebResponse Response;
Bytes = Encoding.UTF8.GetBytes("006453");
request.Method = "POST";
request.ContentLength = Bytes.Length;
request.ContentType = "text/Html"; //Set accordingly
RequestStream = request.GetRequestStream();
RequestStream.Write(Bytes, 0, Bytes.Length);
RequestStream.Close();
Response = ( HttpWebResponse) request.GetResponse();
StreamReader ResponseStream = new StreamReader(Response.GetResponseStream(), Encoding.ASCII);
string Result = ResponseStream.ReadToEnd();
ResponseStream.Close();
MessageBox.Show(Result);
A: You basically have to create a HTTP POST to resultstatus.php and provide it with the roll no (regno).
You'll probably want to see this almost identical question and in particular this article.
| |
doc_23527210
|
Here I am trying to develop the gray curved background and it fills the lower part of the screen as well. I'm very new to UIBezierPath and I've tried this:
class CurvedView: UIView {
//MARK:- Data Types
//MARK:- View Setup
override func draw(_ rect: CGRect) {
let fillColor: UIColor = .blue
let path = UIBezierPath()
let y:CGFloat = 0
print(rect.height)
print(rect.width)
path.move(to: CGPoint(x: .zero, y: 100))
path.addLine(to: CGPoint(x: 60, y: 100))
path.addCurve(to: .init(x: 100, y: 0), controlPoint1: .init(x: 125, y: 80), controlPoint2: .init(x: 50, y: 80))
path.close()
fillColor.setFill()
path.fill()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .init(hex: "#dfe1e3")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = .init(hex: "#dfe1e3")
}
}
This code gave me this:
I followed a lot of tutorials but I didn't get the exact understanding. I understood that for this curve I have to move to (0,100) and then add a line and then add a curve and ten extend the line add a curve then straight line lower curve and then straight line and close. But, when I started as you can see the blue line didn't cover the upper part. Can any one please help me?
A: Here some example that I create, you can change the value to make it more similar to what you want
Here a guide how control point in a curve work
Note: I called this code in viewDidload
let path = UIBezierPath()
let fillColor = UIColor.blue
let y: CGFloat = UIScreen.main.bounds.size.height
let x: CGFloat = UIScreen.main.bounds.size.width
let height: CGFloat = 200
path.move(to: CGPoint(x: 0, y: y)) // bottom left
path.addLine(to: CGPoint(x: 0, y: y - 20)) // top left
path.addCurve(to: CGPoint(x: x, y: y - height), controlPoint1: CGPoint(x: x * 2 / 3, y: y), controlPoint2: CGPoint(x: x * 5 / 6, y: y - height * 6 / 5)) // curve to top right
path.addLine(to: CGPoint(x: x, y: y)) // bottom right
path.close() // close the path from bottom right to bottom left
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = fillColor.cgColor
view.layer.addSublayer(shapeLayer)
A: in reference to @aiwiguna
class CurvedView: UIView {
//MARK:- Data Types
//MARK:- View Setup
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
let fillColor = UIColor.blue
let y: CGFloat = UIScreen.main.bounds.size.height
let x: CGFloat = UIScreen.main.bounds.size.width
let height: CGFloat = 200
path.move(to: CGPoint(x: 0, y: y)) // bottom left
path.addLine(to: CGPoint(x: 0, y: y - 20)) // top left
path.addCurve(to: CGPoint(x: x, y: y - height), controlPoint1: CGPoint(x: x * 2 / 3, y: y), controlPoint2: CGPoint(x: x * 5 / 6, y: y - height * 6 / 5)) // curve to top right
path.addLine(to: CGPoint(x: x, y: y)) // bottom right
path.close() // close the path from bottom right to bottom left
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = fillColor.cgColor
path.close()
fillColor.setFill()
path.fill()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = .yellow
}
}
| |
doc_23527211
|
[[size:'l',color:'red'],[size:'xl',color:'blue']]
to
[{size:'l',color:'red'},{size:'xl',color:'blue'}]
in react js
plz help me to fix it. Thank you in advance
A: First of all , your data is an invalid js structure ,
If you use the last invalid data as string then , at first all key and values should be strings , apply replace you could reach that result by using below snippet
(remove brackets by curly braces except first and last )
let arrayString = '[["size":"l","color":"red"],["size":"xl","color":"blue"]]';
let regexLeft = /(?!^)(\[)(?!$)/g;
let regexRight = /(?!^)(\])(?!$)/g;
let newArray = arrayString.replace( regexLeft, '{' );
newArray = newArray.replace( regexRight, '}' );
let object = JSON.parse(newArray);
console.log(object);
A: Please have a look below:
const arrayToObject = (array, key) => {
const defaultValue = {};
return array.reduce((obj, item) => {
return {
...obj,
[item[key]]: item,
};
}, defaultValue);
};
console.log('Data: ', arrayToObject);
I hope it would help you out.
| |
doc_23527212
|
$dirResult = opendir($pathReal);
where path real is string contains path to file, i get error
Warning: opendir(\149.223.22.11\cae\04_Knowledge-base,\149.223.22.11\cae\04_Knowledge-base): Access is denied.
I know, that issue is with user rights in path im trying to acces, thats clear. But what concerns me is why in warning is opendir parameter written twice?
I would expect warning like this
Warning: opendir(\149.223.22.11\cae\04_Knowledge-base): Access is denied.
but nop. Also i double checked input value, and it seems correct to me. Normal string value with only one path parameter.
edit:
Also when i take a look at next warning
Warning: opendir(\149.223.22.11\cae\04_Knowledge-base): failed to open dir:
there is opendir param only one, what seems correct to me :)
| |
doc_23527213
|
A: path_speed = 0 and path_speed = 100 is not good idea. As example, objects can have different speed. I use speed factor, like speed = normal_speed * k where k is 1 for normal speed and 0 for full stop.
Enemy Create event:
spd = irandom_range(5, 10) // different speed, just as example
path_start(path0, spd, 1, true)
path_position = random(1)
k = 1
Enemy Step event:
path_speed = spd * k
Controller Space key pressed event:
with (o_enemy)
k = 0
alarm[0] = 3 * room_speed
Controller Alarm0 event:
with (o_enemy)
k = 1
And finished gm-project
A: You just set alarm. You never decrease it. so your statement is never true and hence the objects do not move.
| |
doc_23527214
|
<div id='b'> Berry </div>
<div id='c'> Cherry </div>
$(document).ready(function () {
$(#a).hide;
$(#b).hide;
$(#c).hide;
var arr = ["a", "b", "c"];
var i;
for (i = 0; i < 10; i++) {
for (j = 0; j < arr.length; i++) {
setInterval(function(){ arr[j].show(); }, 10 * 1000);
arr[j].hide();
}
}
});
Steps:
Hide all divs.
Loop 10 times.
Show each div for 10 seconds, then hide.
In this example, there are 3 divs. There could be more or less divs. So some kind of array is needed, I guess.
A: Get all div's, use setTimeOut inside promise and resolve promise once the specified time is completed.
Inside setTimeout, mantain a index variable i which will loop over div, and set i index to zero once its value is less than the length of div (To start looping from first div).
let prevDiv = null;
const divs = document.querySelectorAll('div');
const length = divs.length;
let i = 0;
const delay = function() {
return new Promise((resolve) => {
setTimeout(() => {
if (prevDiv) {
prevDiv.classList.remove('active');
prevDiv.classList.add('hide');
}
i = i < divs.length ? i : 0;
divs[i].classList.remove('hide');
divs[i].classList.add('active');
prevDiv = divs[i];
i++;
resolve();
}, 1000);
});
}
async function calc() {
for (let i = 0; i < 10; i++) {
await delay();
}
}
calc();
.active {
display: block;
}
.hide {
display: none;
}
<div id='a' class="hide"> Apple </div>
<div id='b' class="hide"> Berry </div>
<div id='c' class="hide"> Cherry </div>
A: Try (I've shorted the time to 2 sec.)
var arrIds = ["a", "b", "c"];
$(document).ready(function () {
setInterval(function(){
showAll();
setTimeout(hideAll, 1*1000);
}, 2*1000);
});
function showAll () {
arrIds.forEach(function (e) {
$('#'+e).removeClass('hidden');
});
}
function hideAll () {
arrIds.forEach(function (e) {
$('#'+e).addClass('hidden');
});
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Started.
<div id="a" class="hidden"> Apple </div>
<div id="b" class="hidden"> Berry </div>
<div id="c" class="hidden"> Cherry </div>
| |
doc_23527215
|
Warning: require_once(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Kolkata' for '5.5/no DST' instead in D:\Inetpub\wwwroot\dotproject\lib\adodb\adodb.inc.php
A: This has nothing to do with require_once() but with the time/date function you're using in the included script.
see http://docs.php.net/datetime.configuration#ini.date.timezone and http://docs.php.net/timezones
Simplest solution: Put
date.timezone = "Asia/Kolkata"
into your php.ini. Use
<?php echo get_cfg_var('cfg_file_path');
to determine which php.ini you have to edit.
| |
doc_23527216
|
3>LINK : fatal error LNK1101: incorrect MSPDB100.DLL version; recheck installation of this product
for every link step.
What could be different in the environment between password and public-key authentication that's causing this? Note that everything else is identical between a working and failing case - only the authentication method has changed, and this is repeatable so it's not running builds in a particular sequence that's at fault.
A: Probably what you need to do is run cyglsa-config in a Cygwin bash shell and then reboot the system. You might need to start the shell by right-clicking the Cygwin shell shortcut and selecting "Run as administrator", otherwise cyglsa-config may fail with a permission error. I had the same issue (with a different version of Visual C++), and cyglsa-config fixed it.
The following page from the Cygwin documentation explains the issues related to Windows security:
http://cygwin.com/cygwin-ug-net/ntsec.html
The relevant stuff starts in the section called "Switching the user context".
It specifically mentions that the default approach has problems with Visual C++.
A: I'm answering the question in case anyone else gets stuck with this issue, although my 'solution' isn't ideal, so I'm not going to accept the answer, in case anyone with a better approach comes across this.
Since the machine we're logging into is only being used for the automated tests, and so we only need to ssh into the one account, I've reconfigured the ssh service to run under that account, ensuring that it has the required permissions and also has ownership of files in /etc and /var previously owned by the cyg_server account. This then allows the build to work when using public-key authentication. It does give the build account rather more privileges than I'd like though!
| |
doc_23527217
|
var stringReference = "obj.inner.method";
var namespace = stringReference.split(".");
// Now I need to Call window[namespace].call();
I'm a little confused as to how to build out the function call. The end result should look like this?
window[obj][inner][method].call();
Context:
<div data-attribute="click:obj.inner.method" > </div>
I am grabbing a data attribute and binding event listeners based on the data attribute.
Also, Thanks in advance.
A: Try something like this:
function getNamespace(base, path) {
path = path.split('.');
for (var i = 0; i < path.length; i++) {
base = base[path[i]]
}
return base;
}
Use it like:
getNamepspace(window, 'obj.inner.method');
A: You could make a recursive function such as
function getProp(obj, keys) {
if (keys.length) return getProp(obj[keys.shift()], keys);
return obj;
}
And then
getProp(window, 'document.body'.split('.')); // <body>
A loop would work too, in which case you could write it as
function getProp(obj, keys) {
var k;
while (keys.length) k = keys.shift(), obj = obj[k];
return obj;
}
Please note in these examples I use shift which has side effects.
A: I imagine you could do something like this:
var namespaces = stringReference.split(".");
var reference = window;
var i = 0;
do {
reference = reference[namespaces[i]];
i++;
} while(reference && i < namespaces.length);
if(reference) {
reference.call();
}
You can even encapsulate inside a function:
function getNamespacedObject(root, path) {
var paths = path.split(".");
var reference = root;
var i = 0;
do {
reference = reference[namespaces[i]];
i++;
} while(reference && i < namespaces.length);
return reference;
}
You can then call this via var obj = getNamespacedObject(window, "my.namespaced.object");.
A: Another suggestion based on "sp0rkyd0rky" and "Paul S." ones :
function fetch(base, path) {
if (!path) { path = base; base = window; }
path = path.split('.');
while (path.length) base = base[path.shift()];
return base;
}
The base parameter is optional and refers to window by default :
fetch(window, 'obj.inner.method') === fetch('obj.inner.method'); // true
You may also take a look at this answer : https://stackoverflow.com/a/18892106/1636522. However, there are many drawbacks that you should consider (security, performances, maintainability, debugability...) : https://stackoverflow.com/a/4599946/1636522.
| |
doc_23527218
|
I have the following element:
<input type="file" name="file" (change)="fileSelected($event)">
When I look at the event that is passed, I can get the File object using:
fileSelected(ev) {
console.log('file: ', ev.target.files[0]);
console.log('file: ', ev.srcElement.files[0]);
}
But I can't seem to get the content of the file (which in this case is just JSON).
Any suggestions?
Thanks...
A: I figured it out:
fileSelected(ev) {
let myFile = ev.target.files[0];
let reader = new FileReader();
reader.readAsText(myFile);
reader.onload = (ev) => {
this.fileJSON = reader.result;
}
}
| |
doc_23527219
|
Error: error waiting for EKS Node Group (mvp-eks:mvp-node-group) to create: unexpected state 'CREATE_FAILED', wanted target 'ACTIVE'. last error: 1 error occurred:
│ * i-012d9a73b270a9af9, i-0e4530288f0bd2023, i-0ecfed4fe95fa3e3c: NodeCreationFailure: Instances failed to
join the kubernetes cluster
I'm assuming it's either a security group or some sort of networking error, but I have no clue what it could be. Here's my networking related resources- I'm trying to deploy the kubernetes nodes to private subnets, while I have a bastion host and nat gateway in the public ones.
resource "aws_vpc" "vpc" {
cidr_block = "10.1.0.0/16"
tags = {
Name = "${var.name}-vpc"
}
}
resource "aws_subnet" "public_subnet" {
count = length(var.azs)
vpc_id = aws_vpc.vpc.id
cidr_block = var.public_cidrs[count.index]
availability_zone = var.azs[count.index]
map_public_ip_on_launch = true
tags = {
Name = "${var.name}-public-subnet-${count.index + 1}"
}
}
resource "aws_subnet" "private_subnet" {
count = length(var.azs)
vpc_id = aws_vpc.vpc.id
cidr_block = var.private_cidrs[count.index]
availability_zone = var.azs[count.index]
map_public_ip_on_launch = false
tags = {
"kubernetes.io/cluster/${var.cluster_name}" = "shared"
"kubernetes.io/role/internal-elb" = "1"
}
}
resource "aws_internet_gateway" "internet_gateway" {
vpc_id = aws_vpc.vpc.id
tags = {
Name = "${var.name}-internet-gateway"
}
}
resource "aws_route_table" "public_rt" {
vpc_id = aws_vpc.vpc.id
tags = {
Name = "${var.name}-public-rt"
}
}
resource "aws_route" "default_route" {
route_table_id = aws_route_table.public_rt.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.internet_gateway.id
}
resource "aws_route_table_association" "public_assoc" {
count = length(var.public_cidrs)
subnet_id = aws_subnet.public_subnet[count.index].id
route_table_id = aws_route_table.public_rt.id
}
resource "aws_eip" "nat_eip" {
count = length(var.public_cidrs)
vpc = true
depends_on = [aws_internet_gateway.internet_gateway]
tags = {
Name = "${var.name}-nat-eip-${count.index + 1}"
}
}
resource "aws_nat_gateway" "nat_gateway" {
count = length(var.public_cidrs)
allocation_id = aws_eip.nat_eip[count.index].id
subnet_id = aws_subnet.public_subnet[count.index].id
depends_on = [aws_internet_gateway.internet_gateway]
tags = {
Name = "${var.name}-NAT-gateway-${count.index + 1}"
}
}
Here's my eks cluster and node-group resources
resource "aws_iam_role" "eks_cluster" {
name = "${var.name}-eks-cluster-role"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "eks.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
POLICY
}
resource "aws_iam_role_policy_attachment" "amazon_eks_cluster_policy" {
policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
role = aws_iam_role.eks_cluster.name
}
resource "aws_eks_cluster" "eks" {
name = var.cluster_name
role_arn = aws_iam_role.eks_cluster.arn
## k8s Version
version = var.k8s_version
vpc_config {
endpoint_private_access = true
endpoint_public_access = false
subnet_ids = [
aws_subnet.private_subnet[0].id,
aws_subnet.private_subnet[1].id,
aws_subnet.private_subnet[2].id,
]
}
depends_on = [
aws_iam_role_policy_attachment.amazon_eks_cluster_policy
]
}
resource "aws_iam_role" "nodes_eks" {
name = "role-node-group-eks"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
POLICY
}
resource "aws_iam_role_policy_attachment" "amazon_eks_worker_node_policy_eks" {
policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
role = aws_iam_role.nodes_eks.name
}
resource "aws_iam_role_policy_attachment" "amazon_eks_cni_policy_eks" {
policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
role = aws_iam_role.nodes_eks.name
}
resource "aws_iam_role_policy_attachment" "amazon_ec2_container_registry_read_only" {
policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
role = aws_iam_role.nodes_eks.name
}
resource "aws_eks_node_group" "nodes_eks" {
cluster_name = aws_eks_cluster.eks.name
node_group_name = "${var.name}-node-group"
node_role_arn = aws_iam_role.nodes_eks.arn
subnet_ids = [
aws_subnet.private_subnet[0].id,
aws_subnet.private_subnet[1].id,
aws_subnet.private_subnet[2].id,
]
remote_access {
ec2_ssh_key = aws_key_pair.bastion_auth.id
}
scaling_config {
desired_size = 3
max_size = 6
min_size = 3
}
ami_type = "AL2_x86_64"
capacity_type = "ON_DEMAND"
disk_size = 20
instance_types = [var.instance_type]
labels = {
role = "nodes-group-1"
}
version = var.k8s_version
depends_on = [
aws_iam_role_policy_attachment.amazon_eks_worker_node_policy_eks,
aws_iam_role_policy_attachment.amazon_eks_cni_policy_eks,
aws_iam_role_policy_attachment.amazon_ec2_container_registry_read_only,
]
}
I followed multiple guides that used all of these iam policies so I think they have the right permissions, but who knows at this point. I can't tell if it's an IAM permission issue or a networking issue
| |
doc_23527220
|
$('#togglebtn').toggle(function() {
$('#panel').show();
}, function() {
$('#panel').hide();
});
I also have another button to close/hide the panel
$('#otherbtn').click(function() {
$('#panel').hide();
});
All I am trying to say is that when I hide the panel with #otherbtn the event is still active on #togglebtn and gives me an extra click to start toggle the panel again. How can I fix that?
A: What you want to do is already available via the other .toggle() function. Just bind it to the click event:
$('#togglebtn').click(function() {
$('#panel').toggle()
});
(instead of $('#togglebtn').toggle(...) )
A: $('#otherbtn').click(function() {
$('#panel').hide();
$('#togglebtn').toggle(function() {
$('#panel').hide();
}, function() {
$('#panel').show();
});
});
Should work. Reversed the toggle behaviour of the 'otherbtn'
A: Trigger click event on toggle button.
$('#otherbtn').click(function() {
$('#panel').hide();
$('#togglebtn').click(); //resets tooglebtn state
});
| |
doc_23527221
|
A: I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:
*
*Unpack
*Pack
A: There is no such thing as a binary array in PHP. All functions requiring byte streams operate on strings. What is it exactly that you want to do?
A: If you're trying to access a specific part of a string you can treat it like an array as-is.
$foo = 'bar';
echo $foo[0];
output: b
A: Let's say that you want to convert $stringA="Hello" to binary.
First take the first character with ord() function. This will give you the ASCII value of the character which is decimal. In this case it is 72.
Now convert it to binary with the dec2bin() function.
Then take the next function.
You can find how these functions work at http://www.php.net.
OR use this piece of code:
<?php
// Call the function like this: asc2bin("text to convert");
function asc2bin($string)
{
$result = '';
$len = strlen($string);
for ($i = 0; $i < $len; $i++)
{
$result .= sprintf("%08b", ord($string{$i}));
}
return $result;
}
// If you want to test it remove the comments
//$test=asc2bin("Hello world");
//echo "Hello world ascii2bin conversion =".$test."<br/>";
//call the function like this: bin2ascii($variableWhoHoldsTheBinary)
function bin2ascii($bin)
{
$result = '';
$len = strlen($bin);
for ($i = 0; $i < $len; $i += 8)
{
$result .= chr(bindec(substr($bin, $i, 8)));
}
return $result;
}
// If you want to test it remove the comments
//$backAgain=bin2ascii($test);
//echo "Back again with bin2ascii() =".$backAgain;
?>
| |
doc_23527222
|
import pdb
import numpy
b=int(raw_input("b?"))
a=int(raw_input("a?"))
c=int(raw_input("c?"))
pdb.set_trace()
sqrt= ( (b*b) - (4* (a*c))) /(2*a)
x= -b(numpy.sqrt(sqrt))
print x
Can anyone please tell me what's the problem?
`
A: This code:
-b(numpy.sqrt(sqrt))
tries to call a function b() and negates the result.
This is what you want:
-b * (numpy.sqrt(sqrt))
| |
doc_23527223
|
I have done this after days of search but it doesn't work.
I created the following controller :
class SoapsController extends AppController {
var $components = array('RequestHandler');
//listes des model utilisé
public $uses =array('Pompe', 'Serie', 'Fluide','Control');
function service() {
$this->layout = false;
$this->autoRender = false;
Configure::write('debug', 0);
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$server = new SoapServer('http://localhost/pps/soaps/wsdl');
$server->setClass("Soap");
$server->handle();
}
function wsdl() {
$this->layout = false;
Configure::write('debug', 0);
$this->RequestHandler->respondAs('xml');
}
}
And put the wsld file in view/soaps/wsdl.ctp.
When I call the webservice with a client it doesn't work.
Can you help me to do this?
After some try I change my code as follow but I have other error when I call webservice with a client
I created a messagescontroller
class MessagesController extends AppController {
public $uses = null; //for demostration purposes we do not need a model
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow();
}
public $components = array(
'Soap' => array(
'wsdl' => 'myWSDLFile', //the file name in the view folder
'action' => 'service', //soap service method / handler
)
);
public function soap_wsdl(){
//will be handled by SoapComponent
}
public function soap_service(){
//will be handled by SoapComponent
}
/**
* A soap call 'soap_foo' is handled here
*
* @param Object $in The input parameter 'foo'
* @return Object
*/
public function soap_foo($in){
$obj = new stdClass();
$obj->out = 'foo response';
return $obj;
}
}
a file WSDL place in view/Elements/myWSDLFile.wsdl
Create a messageModel
class Message extends AppModel {
public $useTable = false; // Ce model n'utilise pas une table de la base de données
}
add the class soapComponent in Controller/Component/SoapComponent.php
App::import('core', 'AppHelper');
/**
* Soap component for handling soap requests in Cake
*
* @author Marcel Raaijmakers (Marcelius)
* @copyright Copyright 2009, Marcel Raaijmakers
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class SoapComponent extends Component{
var $name = 'Soap';
var $components = array('RequestHandler');
var $controller;
var $__settings = array(
'wsdl' => false,
'wsdlAction' => 'wsdl',
'prefix' => 'soap',
'action' => array('service'),
);
public function initialize($controller, $settings = array()){
if (Configure::read('debug') != 0){
ini_set('soap.wsdl_cache_enabled', false);
}
$this->controller = $controller;
if (isset($settings['wsdl']) && !empty($settings['wsdl'])){
$this->__settings['wsdl'] = $settings['wsdl'];
}
if (isset($settings['prefix'])){
$this->__settings['prefix'] = $settings['prefix'];
}
if (isset($settings['action'])){
$this->__settings['action'] = is_array($settings['action']) ? $settings['action'] : array($settings['action']);
}
parent::initialize($controller);
}
public function startup(){
if (isset($this->controller->params['soap'])){
if ($this->__settings['wsdl'] != false){
//render the wsdl file
if ($this->action() == $this->__settings['wsdlAction']){
Configure::write('debug', 0);
$this->RequestHandler->respondAs('xml');
$this->controller->ext = '.wsdl';
$this->controller->render(null, false, DS . 'elements' . DS . $this->__settings['wsdl']); //only works with short open tags set to false!
} elseif(in_array($this->action(), $this->__settings['action'])) {
//handle request
$soapServer = new SoapServer($this->wsdlUrl());
$soapServer->setObject($this->controller);
$soapServer->handle();
//stop script execution
$this->_stop();
return false;
}
}
}
}
/**
* Return the current action
*
* @return string
*/
public function action(){
return (!empty($this->__settings['prefix'])) ? str_replace( $this->__settings['prefix'] . '_', '', $this->controller->action) : $this->controller->action;
}
/**
* Return the url to the wsdl file
*
* @return string
*/
public function wsdlUrl(){
return AppHelper::url(array('controller'=>Inflector::underscore($this->controller->name), 'action'=>$this->__settings['wsdlAction'], $this->__settings['prefix'] => true), true);
}
}
And at the end change the routes file by adding
Router::connect('/soap/:controller/:action/*', array('prefix'=>'soap', 'soap'=>true));
And when I try using my web service with the client as follow
<?php
ini_set('soap.wsdl_cache_enabled', 0); //enable when in production mode, this does save a lot of time
$soapClient = new SoapClient('http://localhost/pps-soap/soap/messages/wsdl');
$param = new StdClass();
$param->in = 'param';
$foo = $soapClient->soap_foo($param);
var_dump($foo); //an object of StdClass with an 'out' field and the value 'foo response'
?>
I have a soap error that PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from
'http://localhost/pps-soap/soap/messages/wsdl'
I'm jsut totally lost!! Need help
A: To use the Soap services in cakePHP. Follow the following steps.
We have 2 options. 1. using WSDL 2. using location and uri parameters. I used uri parameters:
In the Cotroller:
App::uses('Controller', 'Controller');
App::uses('Post', 'Model'); // Dont forgot to add this
class PostsController extends AppController {
var $components = array('RequestHandler');
function myservice() {
$this->layout = false;
$this->autoRender = false;
Configure::write('debug', 2);
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$server = new SoapServer(null, array(
'location' => 'http://localhost:81/webcake/posts/myservice', // Required for non wsdl mode
'uri' => 'http://localhost:81/webcake/posts/myservice', // Required for non wsdl mode
)
);
$server->setClass('Post');
$server->handle();
}
function testClient() {
$client = new SoapClient(null, array('location' => "http://localhost:81/webcake/posts/service",
'uri' => "http://localhost:81/webcake/posts/service"));
echo $client->myTest(5,5);
}
In Model:
class Post extends AppModel {
var $useDbConfig = 'soap';
var $useTable = false;
function myTest($x,$y) {
return $x+$y;
}
In oder to see the results open url: Ex: http://localhost:81/webcake/posts/testClient
A: What worked for me:
Create SoapController:
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Log\Log;
use Cake\View\ViewBuilder;
class SoapController extends AppController {
var $components = array('RequestHandler');
public function initialize () {
parent::initialize();
$this->Auth->allow(["wsdl"]);
$this->Auth->allow(["service"]);
}
public function beforeFilter (Event $event) {
parent::beforeFilter($event);
if (Configure::read('Security')) {
$this->Security->config('unlockedActions', ['service']);
$this->Security->config('unlockedActions', ['wsdl']);
}
}
public function wsdl () {
try {
$builder = new ViewBuilder();
$builder->autoLayout(false);
$builder->template('Soap/wsdl');
$view = $builder->build();
$viewContent = $view->render();
header('Content-Type: text/xml');
echo $viewContent;
} catch (\Exception $e) {
Log::error("SOAP Server error: %s\n", $e->getMessage());
}
exit();
}
public function service () {
$this->viewBuilder()->layout = false;
$this->autoRender = false;
ini_set("soap.wsdl_cache_enabled", "0");
$server = new SoapServer('http://localhost/soap/wsdl');
$server->setClass("App\Controller\{yourClassWithSoapFunctions}");
$server->handle();
}
}
Create a .ctp file: src/Template/Soap/wsdl.ctp and include in there your SOAP XML configuration.
Create a controller: yourClassWithSoapFunctions.php and include the functions you want your SOAP server to include.
You should now be able to make a SOAP request.
| |
doc_23527224
|
I manage to view the list by doing the following
private void LoadFromLocalStorage()
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] fileNames = store.GetFileNames();
foreach (string s in fileNames)
{
listBox1.Items.Add(s);
}
}
}
How do i display it on a Pivot page as an item so when i select , i would be able to load the image.
Thanks in advance!
A: i dont know what is the imageFolder??
imageFolder is a folder where your image is locate in your project. to execute above method just try
LoadFromLocalStorage(YourInageFolderName).Its not necessary that is imageFolder.
| |
doc_23527225
|
I've got following tables:
EMPLEADOS (employees):
+--------+----------+------------+----------+------------+---------+----------+--------+
| EMP_NO | APELLIDO | OFICIO | DIRECTOR | FECHA_ALTA | SALARIO | COMISION | DEP_NO |
+--------+----------+------------+----------+------------+---------+----------+--------+
| 7499 | ALONSO | VENDEDOR | 7698 | 1981-02-23 | 1400.00 | 400.00 | 30 |
| 7521 | LOPEZ | EMPLEADO | 7782 | 1981-05-08 | 1350.50 | NULL | 10 |
| 7654 | MARTIN | VENDEDOR | 7698 | 1981-09-28 | 1500.00 | 1600.00 | 30 |
| 7698 | GARRIDO | DIRECTOR | 7839 | 1981-05-01 | 3850.12 | NULL | 30 |
| 7782 | MARTINEZ | DIRECTOR | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7839 | REY | PRESIDENTE | NULL | 1981-11-17 | 6000.00 | NULL | 10 |
| 7844 | CALVO | VENDEDOR | 7698 | 1981-09-08 | 1800.00 | 0.00 | 30 |
| 7876 | GIL | ANALISTA | 7782 | 1982-05-06 | 3350.00 | NULL | 20 |
| 7900 | JIMENEZ | EMPLEADO | 7782 | 1983-03-24 | 1400.00 | NULL | 20 |
+--------+----------+------------+----------+------------+---------+----------+--------+
CLIENTES (clients):
+------------+-------------------------+-----------+-------------+------+-------+----------------+
| CLIENTE_NO | NOMBRE | LOCALIDAD | VENDEDOR_NO | DEBE | HABER | LIMITE_CREDITO |
+------------+-------------------------+-----------+-------------+------+-------+----------------+
| 101 | DISTRIBUCIONES GOMEZ | MADRID | 7499 | 0.00 | 0.00 | 5000.00 |
| 102 | LOGITRONICA S.L | BARCELONA | 7654 | 0.00 | 0.00 | 5000.00 |
| 103 | INDUSTRIAS LACTEAS S.A. | LAS ROZAS | 7844 | 0.00 | 0.00 | 10000.00 |
| 104 | TALLERES ESTESO S.A. | SEVILLA | 7654 | 0.00 | 0.00 | 5000.00 |
| 105 | EDICIONES SANZ | BARCELONA | 7499 | 0.00 | 0.00 | 5000.00 |
| 106 | SIGNOLOGIC S.A. | MADRID | 7654 | 0.00 | 0.00 | 5000.00 |
| 107 | MARTIN Y ASOCIADOS S.L. | ARAVACA | 7844 | 0.00 | 0.00 | 10000.00 |
| 108 | MANUFACTURAS ALI S.A. | SEVILLA | 7654 | 0.00 | 0.00 | 5000.00 |
+------------+-------------------------+-----------+-------------+------+-------+----------------+
I need to create view using columns EMP_NO, APELLIDO and OFICIO from table EMPLEADOS and CLIENTE_NO, NOMBRE from table CLIENTES. The task is to create view of all employees and corresponding to them (assigned) clients (the reference here is emp_no in the EMPLEADOS table is the same as VENDEDOR_NO in table CLIENTES) BUT the list has to include all employees, eve those that they don´t have any clients assigned to them. And this bit is something I am struggling with.
What I've got is:
create view V_EMPLEADOS (EMP_NO, APELLIDO, OFICIO, CLIENTE_NO, NOMBRE_CL) AS
-> select em.emp_no, em.apellido, em.oficio, cl.cliente_no, cl.nombre
-> from EMPLEADOS em, CLIENTES cl
-> where em.emp_no = cl.vendedor_no;
But that, of course creates view only of employees that have some clients assigned to them. Please help.
A: You want a left join:
create view V_EMPLEADOS (EMP_NO, APELLIDO, OFICIO, CLIENTE_NO, NOMBRE_CL) AS
select em.emp_no, em.apellido, em.oficio, cl.cliente_no, cl.nombre
from EMPLEADOS em left join
CLIENTES cl
on em.emp_no = cl.vendedor_no;
Simple rule: Never use commas in the FROM clause. Always use proper, explicit JOIN syntax with the condition in the ON clause.
| |
doc_23527226
|
I'd like to have a service that processes user notifications in the background: extracts them from the database, sends them, marks as sent. It would process each item in a separate transaction.
I thought I should create a request scope for each batch item in some way.
How is this possible?
| |
doc_23527227
|
<pre>
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="form1" ><input type="text" name="foo.bar" value="test1" /></form>
<form id="form2" >
<input type="text" name="foo.bar" />
<input type="text" name="foo.baz.qux" value="test2" />
<input type="text" name="qux" />
</form>
</body>
</html>
</pre>
///// Expected result/////
// When calling the function with 'form1', expect the following object result
expect(result).toEqual({
foo: {
bar: 'test1',
}
});
// When calling the function with 'form2', expect the following object result
expect(result).toEqual({
foo: {
bar: '',
baz: {
qux: 'test2',
}
},
qux: '',
});
// Solution which i've tried is,
const Forms = document.querySelectorAll("form");
const inputs = [...Forms[0]];
const result = {};
inputs.forEach(input => {
// console.log("Outer", input.name);
const val = input.value;
const arrOfName = input.name.split('.');
let prev = arrOfName[0];
arrOfName.forEach((n, idx) => {
let len = arrOfName.length;
console.log("n", n, "idx", idx,"prev", prev);
// if(idx < len) {
console.log("idx", idx, "prev", prev, "res", result, "current", n, "IS", !result[n]);
if(!result[n]) {
result[n] = {};
prev = n;
} else {
result[prev][n] = {};
prev = result[prev][n];
console.log("result[prev]", result[prev])
}
console.log("Result:", result);
})
});
// Any idea on how to make preserve previously updated key and update new key under it for that same iteration.
// TIA
A: I think this works. As you said it, need to preserve the previously updated key in a variable.
const form = document.querySelector("form");
const inputs = [...form];
var result = {}
inputs.forEach(function(input) {
var name = input.name
var value = input.value
var arr = name.split(".");
var obj = result;
var last = obj;
var last_key = name
arr.forEach(function(name) {
obj[name] = obj[name] || {}
last = obj;
last_key = name;
obj = obj[name]
})
last[last_key] = value;
})
console.log(result)
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="form2">
<input type="text" name="foo.bar" />
<input type="text" name="foo.baz.qux" value="test2" />
<input type="text" name="qux" />
</form>
</body>
</html>
| |
doc_23527228
|
I try to Validate an htl file, validate an cq_dialog.When I try to validate an htl file I have an problem with implementation ( it doesn't work), but in cq_dialog.xml file I can only validate an text label once, and I can't change a logic that my validation was change depending which size of text user chose.
This is My cq_dialog code and the most comfortable for me will be adding all logic here but I don't know this is posible?
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
jcr:primaryType="nt:unstructured"
jcr:title="Text"
sling:resourceType="cq/gui/components/authoring/dialog">
<content jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/container">
<items jcr:primaryType="nt:unstructured">
<column jcr:primaryType="nt:unstructured" sling:resourceType="granite/ui/components/foundation/container">
<items jcr:primaryType="nt:unstructured">
<title
jcr:primaryType="nt:unstructured"
name="./title"
fieldLabel="Text"
sling:resourceType="granite/ui/components/foundation/form/textfield"
fieldDescription="Max 10 elements"
/>
<type
sling:resourceType="granite/ui/components/foundation/form/select"
fieldLabel="Type"
name="./type"
jcr:primaryType="nt:unstructured"
>
<items jcr:primaryType="nt:unstructured">
<h1 jcr:primaryType="nt:unstructured" text="H1" value="h1"/>
<h2 jcr:primaryType="nt:unstructured" text="H2" value="h2"/>
</items>
</type>
</items>
</column>
</items>
</content>
A: You have to create a clientlib and add JS to register a validator for this use case. The clientlib's category must be referenced by the dialog. Using some OOTB category used by the dialog like 'cq.authoring.editor' will make your clientlib work for dialog validation.
Once you have the clientlib set up, register the validator with the granite framework. Refer https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/clientlibs/foundation/js/validation/index.html#validator on how to register the validator.
Here's a sample of how you can do this for your usecase.
var foundationRegistry = $(window).adaptTo("foundation-registry");
foundationRegistry.register("foundation.validation.validator",{
selector: "[name='./title']",
validate: function(el){
var text = el.value;
var type = $("[name='./type']").val();
var limit = type === 'h1' ? 10 : 7;
var numberOfElements = getNumberOfElements(text); //not sure what number of elements means in your context
if(numberOfElements > limit){
return "The input cannot exceed "+limit+ " elements for type "+type;
}
//the field is considered invalid if this method returns a string,
// the string returned is also used as the error message.
}
});
* the code has not been tested
Since the category of the clientlib is generic, this validator will be bound for all dialogs. You can either make the selector of the field more specific or change the clientlib category and explicitly reference it only on this dialog.
| |
doc_23527229
|
USE case : my sql statement car return the string value "ERROR..." for a string field name TEST. The query returns 734 results. My table display all the results.
In the header row i just want to diplay a count of which would be in SQL a count like "ERROR%".
I can't manage to do that whit the aggregation tool !
aggregation builder
Many thanks for your help.
Julien
A: as i can't manage to find the correct way of filtering my aggregation, i provide the results from my SQL request. By i'd be glad to find the dynamic way of filtering it.
Here is an image of a column that contains strings with "ERR". Le top field in red is my aggregation field served by a slq like '%ERR :%' statement.
example
| |
doc_23527230
|
I am trying to replace certain occurrences of a string pattern with something else. The problem I do not want to replace all occurrences, just all apart from one.
For example.
Imagine I have the string: '(M:2,Seq0:2):10,Seq1:20,(Seq2:40,Seq3:40)'
The pattern I want to find is: '\w+\d+:\d' (which refer to Seq[number])
Imagine I want to change all numbers after 'Seq[number]:'
but not the one following for example, 'Seq1:'
Imagine that to all these numbers after Seq[number]: I wanna sum the value of 10
in The end I would like to have the string:
'(M:2,Seq0:12):10,Seq1:20,(Seq2:50,Seq3:50)'
Is there a way of doing this in a loop?
I tried to use re.findall, but it returns all occurences in a text. How could I incorporate this in a loop?
Thanks!
A: You can do this using re.sub with a function as the replacement, for example:
>>> import re
>>> s = '(M:2,Seq0:2):10,Seq1:20,(Seq2:40,Seq3:40)'
>>> def repl(match):
... return match.group(1) + str(int(match.group(2)) + 10)
...
>>> re.sub(r'(\w+(?!1:)\d+:)(\d+)', repl, s)
'(M:2,Seq0:12):10,Seq1:20,(Seq2:50,Seq3:50)'
The restriction to not match Seq1: is handled by the negative lookahead (?!1:), the capturing groups are used just to separate the portion of the string that you want to modify from the rest of it. The replacement function then returns group 1 unchanged plus the value from group 2 plus 10.
As suggested by Cilyan in comments, you could also add the restriction to not replace for Seq1: in the replacement function, which simplifies the regex. Here is how this would look:
def repl(match):
if match.group(1) == 'Seq1:':
return match.group(0)
return match.group(1) + str(int(match.group(2)) + 10)
result = re.sub(r'(\w+\d+:)(\d+)', repl, s)
edit: To address the questions in your comment, here is how you could write this to modify the number that you add and which prefix (like Seq1:) should be ignored:
def make_repl(n, ignore):
def repl(match):
if match.group(1) == ignore:
return match.group(0)
return match.group(1) + str(int(match.group(2)) + n)
return repl
result = re.sub(r'(\w+\d+:)(\d+)', make_repl(10, 'Seq1:'), s)
| |
doc_23527231
|
" OnCommand=event>
Event
GridDataItem item = (GridDataItem)RadGrid1.Items[Convert.ToInt32(e.CommandArgumrnt)];
I am not sure what index the grid returns when the detailtable button is clicked and every time I try to access a column in that row I get an error saying column does not exist. I tried doing so:
GridDataItem item = (GridDataItem)RadGrid1.MasterTable.DetailTables[0].Items[Convert.ToInt32(e.CommandArgumrnt)];
This did not work as well.
Excuse me if I made any mistakes, I am on my mobile phone.
A: I have found a much simpler solution to my problem that doesn't if require me to use oncommand or command argument! Instead I use the simple Onclick.
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridDataItem item = (GridDataItem)btn.NamingContainer;
TableCell cell = (TableCell)item["UniqueName"];
string value = cell.Text;
}
| |
doc_23527232
|
In Java, I can implement a shutdown hook and register it via Runtime.getRuntime().addShutdownHook(). How can I achieve the same in C#?
A: You can attach an event handler to the current application domain's ProcessExit event:
using System;
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
Environment.Exit(0);
}
}
A: Hook AppDomain events:
private static void Main(string[] args)
{
var domain = AppDomain.CurrentDomain;
domain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
domain.ProcessExit += new EventHandler(domain_ProcessExit);
domain.DomainUnload += new EventHandler(domain_DomainUnload);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught: " + e.Message);
}
static void domain_ProcessExit(object sender, EventArgs e)
{
}
static void domain_DomainUnload(object sender, EventArgs e)
{
}
A: I'd recommend wrapping the call to Environment.Exit() in your own method and using that throughout. Something like this:
internal static void MyExit(int exitCode){
// disconnect from network streams
// ensure file connections are disposed
// etc.
Environment.Exit(exitCode);
}
| |
doc_23527233
|
Example:
*
*Start Date = 5/1/2018, End Date = 12/31/2019, Interval = 2
Series I am looking for (dates in rows): 7/31/18, 9/30/18, 11/30/18, ... 11/30/19
*Start Date = 1/1/2018, End Date = 12/31/19, Interval = 3
Series I am looking for (dates in rows): 3/31/18, 6/30/18, 9/30/18, 12/31/18...12/21/19
Details: I have 3 tables that are joined (inner). First table has start date, second table gives me end date of given customer and 3rd table gives me billing frequency. Based are those 3 parameters I need to predict how many invoices and on what dates we will generate invoices to each customer.
A: The problem isn't super clear but you can try something like this. Just plug in your start_date, end_date, and interval. It will give you mostly what you want, then you can customize for your specific case:
with series as (
select generate_series(1, datediff(month, <start_date>, <end_date>), 1) as n, MOD(n, <interval>) as remainder
)
select dateadd(month, n, <start_date>) from series where remainder = 0;
So an example would be:
with series as (
select generate_series(1, datediff(month, '2018-05-01', '2019-12-31'), 1) as n, MOD(n, 3) as remainder
)
select dateadd(month, n, '2018-05-01') from series where remainder = 0;
A: The problem is not clear but assuming the requirement is to create month end dates between start and end dates with the given interval as months
The first example in that case is not correct it should start with 6/1/2018 not 5/1/2018
The SQL I have is
WITH params(start_dt, end_date, interval_) AS
(SELECT '2018-06-01'::date,
'2019-12-31'::date,
'2'::integer)
, dates AS
(SELECT ADD_MONTHS(start_dt, n * interval_) - 1 AS dt
FROM params ,
(SELECT generate_series(1, ((datediff(month, start_dt::date, end_date::date) / interval_) + 1)) n
FROM params) )
SELECT to_char(dt,'MM/DD/YY') dt
FROM dates, params
WHERE dt BETWEEN start_dt AND end_date
The output for this is
dt
07/31/18
09/30/18
11/30/18
01/31/19
03/31/19
05/31/19
07/31/19
09/30/19
11/30/19
For second example
WITH params(start_dt, end_date, interval_) AS
(SELECT '2018-01-01'::date,
'2019-12-31'::date,
'3'::integer)
, dates AS
(SELECT ADD_MONTHS(start_dt, n * interval_) - 1 AS dt
FROM params ,
(SELECT generate_series(1, ((datediff(month, start_dt::date, end_date::date) / interval_) + 1)) n
FROM params) )
SELECT to_char(dt,'MM/DD/YY') dt
FROM dates, params
WHERE dt BETWEEN start_dt AND end_date
The output is
dt
03/31/18
06/30/18
09/30/18
12/31/18
03/31/19
06/30/19
09/30/19
12/31/19
| |
doc_23527234
|
The height of a grid panel header is forcibly set at 28px.
*
*No sass settings
*Header configuration on the panel did not work for me
*Modifying the grid columns height seems to work when configuring < 28px. 28px seems to be the minimum.
This is what I have so far (and it works), but I don't like the solution.
Ext.define('Ext.grid.Panel', {
listeners: {
beforerender: function (cmp, eOpts) {
cmp.headerCt.setHeight(25);
}
}
});
Additionally, column headers seem to be fixed at 28px as well. Setting the height of the header to 25 will not set the column header to 25. You need to override that as well in the scss / css. Otherwise your column header menus will display off the 28px height.
.x-column-header
{
height: 25px;
}
This solution does not work: If you drag column headers, changing the column's index position, it will break -.-
Recommedations?
A: To set the height of the column headers, you must set the height after their compilation. Again, the height value for the column configuration does not work to set the height < 28, but works > 28.
I have found that modifying the height after compilation correctly sets the height and allows columns to be draggable (everything works as it should).
Ext.define('Ext.grid.Panel', {
listeners: {
beforerender: function (cmp, eOpts) {
cmp.columns[0].setHeight(25);
}
}
});
My solution couldn't use this because I create a dynamic grid. In the dynamic part of the grid I use GRID.reconfigure(); - there by destroying anything that was created on a beforerender state.
Ext.define('Ext.grid.Panel', {
listeners: {
reconfigure: function (cmp, eOpts) {
cmp.columns[0].setHeight(25);
}
}
});
The reconfigure function fires after the reconfiguration so this is how I got around the dynamic grid reconfiguration.
A: You can also use sass sub-styles for that gridpanel and set the 'ui' config:
add ui:'custom-height-item' to your config
@include extjs-panel-ui(
'custom-height-item',
$ui-header-line-height: 28px,
$ui-header-padding: 2px;
)
| |
doc_23527235
|
5:24:47 PM [Apache] Apache Service detected with wrong path
5:24:47 PM [Apache] Change XAMPP Apache and Control Panel settings or
5:24:47 PM [Apache] Uninstall/disable the other service manually first
5:24:47 PM [Apache] Found Path: "c:\apache24\bin\httpd.exe" -k
runservice
5:24:47 PM [Apache] Expected Path: "c:\xampp\apache\bin\httpd.exe" -k
runservice
A: 5:24:47 PM [Apache] Apache Service detected with wrong path
5:24:47 PM [Apache] Change XAMPP Apache and Control Panel settings or
5:24:47 PM [Apache] Uninstall/disable the other service manually first
5:24:47 PM [Apache] Found Path: "c:\apache24\bin\httpd.exe" -k runservice
5:24:47 PM [Apache] Expected Path: "c:\xampp\apache\bin\httpd.exe" -k
From what i can see, the problem is you installed XAMPP in the wrong path, so i suggest you uninstall xampp and re-install it again making sure it's PATH is installed like this -->
"c:\xampp\apache\bin\httpd.exe"
The XAMPP folder must be in your C-drive or Local disk, that is where Program files and Program files(x86) are.
Hopefully that helps.
| |
doc_23527236
|
Absolute values are written as a value between 0.0 and 1.0 while percentage value are written as 0 to 100.
How can I distinguish 1 from 1.0?
If I were to use strings, then it's not a problem for sure...
I would like to keep this configuration simple and not have to rely strings.
Is this possible at all?
RECAP:
a = 1
b = 1.0
How to tell that a is not of the same type as b.
EDIT
The configuration file look something like this:
local config = {}
-- A lot of comments describing how to configure
config.paramA = 1
config.paramB = 1.0
return config
In my processing script i read the configs like this:
config = require 'MyConfigFile'
config.paramA
config.paramB
A: With Lua 5.3 came the integer data type which allows to differ between integer & floating point numbers and provides better performance in some cases. math.type is the function to get the subtype of a number.
local x = 1.0
print(math.type(x)) -- float
x = 1
print(math.type(x)) -- integer
If your percent value should be floating point too, William already called it: "a number is a number". You have to add an additional information to your number to differentiate, like packing it in a table with an identifier. Because you have just 2 cases, a boolean would be a cheap solution.
A: From PIL you can see that a number is a number and therefore there's no way to distinguish 1 from 1.0 when working with them because they do have the same type
A way to to solve your problem is using a table that contains both the value and the type:
config.paramA = { 1, 'i' }
config.paramB = { 1.0, 'd' }
Or using a string and parsing it before converting to an integer:
config.paramA = '1'
config.paramB = '1.0'
A: With Lua 5.1 and 5.2 there is no difference, which can be seen from luac output (luac -i) as local a, b = 1, 1.0 generates the following code:
main <1.lua:0,0> (3 instructions, 12 bytes at 007D04E8)
0+ params, 2 slots, 0 upvalues, 2 locals, 1 constant, 0 functions
1 [1] LOADK 0 -1 ; 1
2 [1] LOADK 1 -1 ; 1
3 [1] RETURN 0 1
Lua 5.3 allows to distinguish between the two using math.type as they have different subtypes.
As a solution to your particular problem, if you really want to make it a non-integer, you can probably add a very small delta to the number: 1.0000001 instead of 1.0.
A: some suggestions:
1) allow only one of the two formats
2) use a function to make the format explicit
config.paramA = percent(1.9)
config.paramB = portion(1)
those functions could create tables with type info or just convert the value to a consistent type
| |
doc_23527237
|
I know how i can add on address to the view. But how do i add all the addresses to one map?
Can every help me please?
Many thanks in advance
Marcus
A: Why are you adding a comma?
<?php $this->GoogleMap->addMarker("map_canvas",1, $atla['Atla']['street'].' '.$atla['Atla']['number'].', '.$atla['Atla']['zipcode'].' '.$atla['Atla']['city'],$atla['Atla']['name'])?> <?php endforeach; ?>
should probably be
<?php $this->GoogleMap->addMarker("map_canvas",1, $atla['Atla']['street'].' '.$atla['Atla']['number'].', '.$atla['Atla']['zipcode'].' '.$atla['Atla']['city'].','.$atla['Atla']['name'])?> <?php endforeach; ?>
But: How about http://www.dereuromark.de/2010/12/21/googlemapsv3-cakephp-helper/ ?
It is probably a more complete alternative.
As documented you can use
$this->GoogleMapV3->addMarker($options);
any many times as you want. I tried it with 500 and - although at this point you might want to switch to clusters - it still worked.
| |
doc_23527238
|
10-01 01 100
10-01 02 200
10-01 03 300
10-02 01 1000
10-02 02 2000
10-02 03 3000
My table has a daily entry for every id, with a different value per entry.
I need the query to show:
ID Date1Value Date2Value
01 100 1000
02 200 2000
03 300 3000
Date 1 will be DATE_SUB(curdate(), Interval 1 DAY), while Date2 is DATE_SUB(curdate(), Interval 2 DAY)
A: You can use conditional aggregation for this:
select id,
max(case when date = date_sub(curdate(), Interval 1 DAY)
then value
end) date1value,
max(case when date = date_sub(curdate(), Interval 2 DAY)
then value
end) date2value
from yourtable
group by id
| |
doc_23527239
|
In the notice of the update of android studio, in red letters as above
Plugin incompatible with the new build found: Firebase Services
I get a warning as above,
I don't understand the meaning.
Does this mean that Firebase related packages will not work after updating android studio?
Should I not update android studio?
However,I think that there seems to be no option to never update android studio
I'm currently building an app using Flutter and Firebase,
but depending on the project, the version of the Firebase related package
may be different, what should I do?
A: There is no error with my android studio. i am using on Ubuntu.
A: Late but answering for future help.
Android studio have plugin market place (you can find it at File->setting->plugin). Whenever android studio plans to release an update, it gives beta release first. Meanwhile, most of the plugins, update their plugin accordingly.
In your case, you are facing a warning because Firebase Services plugin had not ready the update for the time being, but in some cases, the plugins release their updates which will be available after you update the android studio. So it is safe to update to the latest android studio.
If you still facing plugin incompatibility warning, disable the plugin until the update will live. It happens only if you are using the low rated plugin. Sometimes, incompatibility warning also appears if your android cache become mess for the system. So cleaning the cache from C:\Users\username\AppData will resolve the issue. Or you can also choose to remove the old android studio files while updating the android studio. But there might be cases that your system do not remove files completely, so remove them manually.
| |
doc_23527240
|
Given a graph, find any path from Node1 to Node2 and return a list of the paths, if the paths are many they have to be shown one by one, as in the example output.
A path from N1 to N2 exists if there is a e(N1,N2).
A path from N1 to N2 is valid if N3 can be reached from N1, and then there is a path from N2 to N3, recursively.
find_any_path(+Graph, +Node1, +Node2, -ListPath)
The output expected should be as the following:
find_any_path([e(1,2),e(1,3),e(2,3)],1,3,L).
– L/[e(1,2),e(2,3)]
– L/[e(1,3)]
Here's my implementation
reaching([], N, []):-!.
reaching(G, N, L):-findall(X, member(e(N,X), G), L).
dropAny(X,[X|T],T).
dropAny(X,[H|Xs],[H|L]):-dropAny(X,Xs,L).
find_any_path([],N1,N2,[]).
find_any_path(G,N1,N2,L):- member(e(N1,N2),G),
reaching(G,N1,R), %R=[2,3]
dropAny(N2,R,M), %M=[2] numbers found between N1 and N3
anypath(G,N1,N2,M,L).
find_any_path(G,N1,N2,[],[e(N1,N2)]).
find_any_path(G,N1,N2,[M|Ms],[e(N1,M),e(M,N2)|L]):- member(e(M,N2),G),
find_any_path(G,N1,N2,Ms,L).
The output shown is the following, different from the expected result :
L / [e(1,2),e(2,3),e(1,3)]
| |
doc_23527241
|
__device__ __forceinline__ uint32_t add_cc(uint32_t a, uint32_t b)
{
uint32_t r;
asm volatile ("add.cc.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b));
return r;
}
I'm porting a CUDA project to HIP-Clang that contains inline PTX assembly. The function is used to implement multi-precision addition in the NVIDIA GPU. I tried:
asm volatile ("add.cc.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); //invalid instruction
asm volatile ("V_ADD_CO_U32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); //invalid operand for instruction
asm volatile ("V_ADD_CO_U32 %0, %1, %2;" : "=v"(r) : "v"(a), "v"(b)); //operands are not valid for this GPU or mode
The target hardware is RX 6800. AMD clang version 14.0.0.
Is RDNA2 the correct instruction set reference?
Is this LLVM user guide to AMDGPU backend an applicable reference?
A: It turns out the answer is hardware dependent. For my hardware for which the compiler defines __gfx1030__ the correct syntax is
asm volatile ("v_add_co_u32 %0, vcc_lo, %1, %2;" : "=v"(r) : "v"(a), "v"(b));
For earlier architechtures such as __gfx900__ replace vcc_lo with vcc
See the discussion on the Rocm Hip Github and this AMD gpu assembly reference.
| |
doc_23527242
|
My JNI works on one, but not on others.
Up until recently, this application and its JNI was working fine. After not needing to make any updates to the application for a year, I reopened it, and now there is a failure.
This JNI code (with a few name changes to obfuscate the project on a public forum):
void * gTheLibrary;
JNIEXPORT int JNICALL Java_com_doamin_ourapp_ourmodule_LoadLib(JNIEnv * env, jobject obj) {
globalObject = env->NewGlobalRef( obj );
env->GetJavaVM( &globalJVM );
if (gTheLibrary != NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, APPNAME," JNI-> The lib is already loaded\n");
return 0;
}
gTheLibrary = dlopen("./libmyprocess.so", RTLD_NOW);
if (gTheLibrary == NULL) {
char buffer[512];
sprintf(buffer," JNI-> **** FAILED to load DSO %s \n", dlerror());
__android_log_print(ANDROID_LOG_VERBOSE, APPNAME,"%s",buffer);
return -1;
}
...
The "dlerror()" log entry reports:
"JNI-> **** FAILED to load DSO dlopen failed: library "./libmyprocess.so" not found"
But the C library is packaged with the APK. So, the C lib module for this JNI is loading. But it's call to "dlopen()" is not finding the DSO.
As I said, this code USED to work on all devices. Until I reopened the project to make some minor changes. And none of them related to the JNI. Just small Java changes.
*
*This code works fine in a Kindle Fire, android version 5.0.1
*This code fails on the "dlopen(...)" On a Samsung Tablet 10.1" Android
6.0.1
*This code fails on the HTC Desire 530, Android 7.0
*This code also works fine on an Odroid SBC running Android 4.4
The devices all were set to allow USB debugging, allow apps from unknown sources, etc... Re-iterating, this used to work all all these devices. Now it fails on some of them.
The JNI library, plus the library it is trying to load, have the Application.mk set with "APP_PLATFORM := android-19" so they are consistent. The Libraries are build outside of Android Studio, so that version shouldn't be a factor, but I am using A.S. 2.3.3. I've recompiled everything in an effort to keep things in sync.
I'm guessing this is related to the OS version. But no leads on what/why it's different for compiled C code. And why, on these same OS versions, it worked a year ago. Is there any advice which can be offered to help identify how to get around this?
Thanks in advance.
-Scotty
---- UPDATE -----
Trying things, and not making progress...
Using "arm-linux-androideabi-readelf" I see there are 6 "NEEDED" libraries:
0x00000001 (NEEDED) Shared library: [liblog.so]
0x00000001 (NEEDED) Shared library: [libandroid.so]
0x00000001 (NEEDED) Shared library: [libstdc++.so]
0x00000001 (NEEDED) Shared library: [libc.so]
0x00000001 (NEEDED) Shared library: [libm.so]
0x00000001 (NEEDED) Shared library: [libdl.so]
I gutted completely the lib, and rebuilt it. Not even any #includes... It literally is this:
void * Initialize() {
return 0;
}
It literally shouldn't need any external libraries. And yet I re-ran "arm-linux-androideabi-readelf" and it still lists those same 6 libraries.
And when I retest the app, it still fails to load.
As another test, I took those 6 needed libraries from ...\platforms\android-19\arch-arm\usr\lib\ and copied them into the same "libs" folder as the JNI and the library in dlopen(...), and verified that they are all in the APK (by opening it as a zip). But the JNI DSO is still giving me the same failure on "dlopen(...)".
And my mind keeps falling back to the old adage "It was working before" - What is it that changed in the devices? Or some autoupdate in the Studio/NDK?
A: This was fixed by eliminating the "local" path...
gTheLibrary = dlopen("libmyprocess.so", RTLD_NOW);
I am not sure why it was in there originally. I assume because 2 years ago it was necessary to specify the local location of the library. Now, however, it is causing the problem. There is no need to include the 6 "Needed" libraries.
| |
doc_23527243
|
const time = "06:15:00"
This is 6:15 am
date.format(time, "h:mm A") // 6:15 AM
I want 6:15 a.m.
date.format(time, "h:mm aa")
doesn't work for some reason
Is there a way?
A: You have to add meridiem plugin
date.plugin('meridiem')
const time = date.parse('06:15:00', 'hh:mm:ss')
console.log(date.format(time, 'hh:mm aa'))
<script src="https://rawcdn.githack.com/knowledgecode/date-and-time/a5f31dcb3fe1bd02fd8ff7770552c73a4401d0a1/date-and-time.min.js" type="text/javascript"></script>
<script src="https://rawcdn.githack.com/knowledgecode/date-and-time/a5f31dcb3fe1bd02fd8ff7770552c73a4401d0a1/plugin/meridiem.js" type="text/javascript"></script>
| |
doc_23527244
|
template<class I, class O>
class Pipeline
{
vector<I> _inputs;
virtual O Execute(void)
{ return foobar( _inputs ) }
};
I would like to implement the operator | (pipe) that combines multiple pipelines together:
EDIT: change code with pointers so that it matches my next code example
// Pipeline* p1, p2, and p3 already exist
Pipeline* p0 = p1 | p2 | p3;
// is equivalent to
p2->_inputs.push_back(p3->execute());
p1->_inputs.push_back(p2->execute());
p0->_inputs.push_back(p1->execute());
I thought rvalue reference was very appropriate for this :
template<class I,class O>
Pipeline<I,O>&& operator | (Pipeline<K,O>* a, Pipeline<I,K>* b)
{
Pipeline* p0 = a;
Pipeline* p1 = b;
p0->_inputs.pushback(p1->execute); //inputs is vector<I*> instead of vector<I>
return std::move(p0);
}
Note, that I would prefer pass by adress rather than value because typename I and O could potentially be big objects and Pipeline could have such big private attributes in it's inner working.
However the above code clearly has a lot of memory management issues:
1/ std::move(p0) means p1 is never freed/deleted
2/ if I work directly on a and b instead of p0 p1, I loose the original pointers?
Can someone help me and tell me how to use an rvalue ref for the pipe operator please?
EDIT: According to @Alexey Guseynov my example is not adapted for rvalue ref. rather than functional code (Minimal Complete Verifiable example) I am looking for an explanation as to why && is not valid here and also when are we are supposed to use them: What is the philosophy behind them and what exactly do they bring to the table.
Thank you in advance
A: Argument type in declaration must match types of arguments you use. So if you use objects themselves:
call.Pipeline p0,p1,p2,p3;
p0 = p1 | p2 | p3;
Then operator | must take objects. In your case it must take const Pipeline&. Note, that semantically operator | does not modify it's operands, so you should not use Pipeline& despite that it allowed.
Rvalue reference is not a good type to return: they are just not designed to be used here. You will return a reference to a temporary object which does not exist any more. You should return a value here.
So in the code you've shown there is no place for pointers, so there are no problems with memory management.
| |
doc_23527245
|
var x = new Checkboxes
{
name = "test",
isChecked = false
};
CheckboxList.Add(x);
I bind this property to my checkbox:
@Html.CheckBoxFor(m => m.CheckboxList[0].isChecked)
But when I check on my returned action
I see that the name field is null (however the data on the isChecked prop is handled correctly)
How can I identify my checkbox then OR how can I pass the object through?
| |
doc_23527246
|
My Gemfile:
gem 'jquery-rails'
gem 'popper_js'
gem 'bootstrap'
My application.js:
//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require popper
//= require bootstrap-sprockets
//= require_tree .
My action_item in:
action_item :query, only: :view_form do
link_to 'New Query', admin_participants_form_queries_path(:id => participant.id, :survey_type => type, :form_name => form_name), {:remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window'}
end
My admin-controller-method:
def admin_queries
respond_to do |format|
format.html
format.js
end
end
my js file:
$("#modal-window").find(".modal-content").html("<%= j (render 'queries_modal') %>");
$("#modal-window").modal('show');
Any help with the above issue will be hugely appretiated. thank you in advance
A: Could be that your jquery is not being recognized:
Try adding this to your config/webpack/environment.js
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)
| |
doc_23527247
|
I tried downloading shape-files from www.census.gov/ but it does not have any documentation on the granularity of shape-files it does contain. So I am not able to correctly pinpoint on the right set of shape-files I can use
import geopandas as gpd
from shapely.geometry import shape
from shapely.geometry import Point, Polygon
import pandas as pd
p1 = Point(32.999231, -96.773696)
data3 = gpd.read_file(fp)
data3['geometry'].intersects(p1)
data3['geometry'].contains(p1)
Final output is Indoor/Outdoor. Need some info on the shape files I can use for this kind of problem.
| |
doc_23527248
|
My problem is that it calculates based only on the last entered resistance.
Is it possible to declare a method inside a function? or should I give up this completely unpractical approach
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
class rez {
float r;
public:
void set(int n);
float val() { return r; }
};
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r;
}
}
float serie(rez r1,int n)
{
float s=0;
int i;
for (i = 1; i <= n; i++)
{
s = s+ r1.val();
}
return s;
}
float para(rez r1, int n)
{
float s = 0;
int i;
for (i = 1; i <= n; i++)
{
s = s + (1/r1.val());
}
return 1/s;
}
int main()
{
char c, k = 'y'; // 'c' selects series or para
rez r1;
int n;
cout << "number of resis:";
cin >> n;
cout << endl;
while (k != 'q')
{
r1.set(n);
float i, u;
cout << "\n Vdc= ";
cin >> u;
cout << endl;
cout << "series or para(s/p)?"<<endl;
cin >> c;
switch (c)
{
case('s'):cout <<"\n equiv resistance = "<< serie(r1,n)<<endl;
i = u / serie(r1, n);
cout << "curr i = " << i << " amp";
break;
case('p'):cout << "\n equiv res = " << para(r1, n)<<endl;
i = u / para(r1, n);
cout << "cur i = " << i << " amp";
break;
}
cout <<endl<< "\n another set?(y/q)?"<<endl;
cin >> k;
}
return 0;
}
A: It is because when you read in the resistances you are setting the value of the total resistance each time not adding to the total resistance.
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r; // <- this sets the value of r, it does not add to it
}
}
To fix this you should create a temporary variable to store the input resistance and then add it to the total resistance
void rez :: set(int n)
{
int i;
for (i = 1; i <= n; i++)
{
float input;
cout << "R" << i << "=";
cin >> input;
r += input;
}
}
| |
doc_23527249
|
Found: 1/22/2016
Milliseconds: 1453449600000
ISO: Fri Jan 22 2016 00:00:00 GMT-0800 (PST)
Found: Jan 22 2016
Milliseconds: 1453449600000
ISO: Fri Jan 22 2016 00:00:00 GMT-0800 (PST)
Found: 2016/1/22 03:00
Milliseconds: 1453460400000
ISO: Fri Jan 22 2016 03:00:00 GMT-0800 (PST)
How do I use moment to parse all of these formats and more?
var foundDue = taskNote.match(/(Deadline|Due):.*(\n|$)/ig);
// if we've found a deadline date...
if (foundDue) {
// Remove deadline/due tag
foundDue = foundDue[0].replace(/(Deadline|Due):? */i, "");
// Remove trailing and leading spaces
foundDue = foundDue.replace(/(^\s*|\s$)*/, "");
console.log("Found: "+ foundDue);
// Use a magic method to parse date
milliseconds = moment.??????(foundDue);
console.log("Milliseconds: "+ milliseconds);
console.log("Parsed2: "+ new Date(foundDue));
var taskDue = new Date(milliseconds);
console.log("ISO: "+ taskDue);
}
Note, this question is adapted from an earlier question.
A: You can use moment parsing with multiple formats to convert your input strings into moment objects, then you can use moment valueOf() to get milliseconds.
Here an example snippet for the inputs given in your question:
var inputs = ['1/22/2016', 'Jan 22 2016', '2016/1/22 03:00'];
for(var i=0; i<inputs.length; i++){
var m = moment(inputs[i], ['M/D/YYYY', 'MMM D YYYY', 'YYYY/M/D HH:mm']);
console.log(m.format(), m.valueOf());
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
Note that, as the docs says, when using multiple formats:
Moment uses some simple heuristics to determine which format to use. In order:
*
*Prefer formats resulting in valid dates over invalid ones.
*Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
*Prefer formats earlier in the array than later.
In the code sample above, ambiguous inputs like 01/02/2016 will always be parsed as January 2nd 2016.
| |
doc_23527250
|
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
model=AutoModelForSeq2SeqLM.from_pretrained('facebook/bart-large-cnn')
tokenizer=AutoTokenizer.from_pretrained('facebook/bart-large-cnn')
sentence_to_summarize = ['This is a text to summarise. I just went for a walk in the park and saw very large crowds gathering to watch an impromptu football match']
encoded_dict = tokenizer.batch_encode_plus(sentence_to_summarize, return_tensors='pt', max_length=1024, padding='max_length')
input_ids = encoded_dict['input_ids']
attention_mask = encoded_dict['attention_mask']
label = tokenizer.encode('I went to the park', return_tensors='pt')
Notice the following two cases.
Case 1:
output = model(input_ids=input_ids, attention_mask=attention_mask)
print(output['logits'].shape)
shape printed is torch.Size([1, 1024, 50264])
Case 2
output = model(input_ids=input_ids, attention_mask=attention_mask, labels=label)
print(output['logits'].shape)
shape printed is torch.Size([1, 7, 50264]) where 7 is the length of the label 'I went to the park' (including start and end tokens).
Ideally the summarization model would learn when to generate the EOS token, but this should not always lead to summaries of identical length of the gold output (i.e. the label). Why is the label length influencing the model output in this way?
I would expect the only difference between cases 1 and 2 being that in the second case the output also contains the loss value, but I wouldn't expect this to influence the logits in any way
A: Original example not use label parameter
https://huggingface.co/docs/transformers/v4.22.1/en/model_doc/bart#transformers.BartForConditionalGeneration.forward.example
label parameter is optional and i think not used for summerizing
https://huggingface.co/docs/transformers/v4.22.1/en/model_doc/bart#transformers.BartForConditionalGeneration.forward.labels
| |
doc_23527251
|
mvn dependency:get \
-Dartifact=org.teavm.flavour:teavm-flavour-application:0.1.0-dev-8 \
-DremoteRepositories=teavm::::https://dl.bintray.com/konsoletyper/teavm
Second, I run archetype generation:
mvn -DarchetypeCatalog=local \
-DarchetypeGroupId=org.teavm.flavour \
-DarchetypeArtifactId=teavm-flavour-application \
-DarchetypeVersion=0.1.0-dev-8 \
archetype:generate
and get the following error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.0:generate
(default-cli) on project standalone-pom: The desired archetype does not exist
(org.teavm.flavour:teavm-flavour-application:0.1.0-dev-8) -> [Help 1]
When I build the project from sources and generate SNAPSHOT archetype, everything works fine.
Is there something I'm doing wrong, or it's a bug in Maven? Is there a workaround?
A: Please go to https://bintray.com/konsoletyper/teavm/teavm-flavour-dev
Then hit Set Me Up!
And choose: Resolving artifacts using Maven
copy this part into your settings xml (usually located in /Users/os-username/.m2/settings.xml see bellow):
<profiles>
<profile>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>bintray-konsoletyper-teavm</id>
<name>bintray</name>
<url>http://dl.bintray.com/konsoletyper/teavm</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>bintray-konsoletyper-teavm</id>
<name>bintray-plugins</name>
<url>http://dl.bintray.com/konsoletyper/teavm</url>
</pluginRepository>
</pluginRepositories>
<id>bintray</id>
</profile>
</profiles>
<activeProfiles>
<activeProfile>bintray</activeProfile>
</activeProfiles>
Then try the second command again.
settings.xml:
There are two locations where a settings.xml file may live:
The Maven install: ${maven.home}/conf/settings.xml
A user’s install: ${user.home}/.m2/settings.xml
https://maven.apache.org/settings.html
A: I had the same issue and fixed it by adding the plugin "Maven Archetype Catalogs" that fetch for external archetype catalog files.
Go to Preferences by taping ⌘, (macOS), or Ctrl+Alt+S (Windows/Linux) then Plugins and look for Maven Archetype Catalogs.
| |
doc_23527252
|
When I put "dist" folder content on a server, there is a console error
"type MIME".
Le chargement du module à l’adresse « http://www.sylvainallain.fr/polyfills-es2015.fd917e7c3ed57f282ee5.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/main-es2015.2fcd6517edb1de962f8a.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/runtime-es2015.24b02acc1f369d9b9f37.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
https://imgur.com/fQKnWAg.jpg
This in French for me ^^.
You can see it in console here http://biblio.sylvainallain.fr
It's a simply application like a library.
Back-end (logs and data) is manage with Firebase.
In local, all is OK.
I make the build with "ng build --prod", it create a "dist" folder.
My index.html after prod:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bibliothèque Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.735ba4029395bfd97371.css"></head>
<body>
<app-root></app-root>
<script src="polyfills-es5.f9fad3ad3c84e6dbdd72.js" nomodule defer></script>
<script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script>
<script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script>
<script src="main-es2015.2fcd6517edb1de962f8a.js" type="module"></script>
<script src="runtime-es5.24b02acc1f369d9b9f37.js" nomodule defer></script>
<script src="main-es5.2fcd6517edb1de962f8a.js" nomodule defer></script></body>
</html>
I find this GitHub post: https://github.com/angular/angular-cli/issues/10325
.This is the same issue, I try some solutions but nothing work.
The issue is only with es2015.*.js files. So I think there is an issue with type="module" which is not recognize like a Javascript file.
I don't understand why Angular don't manage it.
Edit 25 October :
*
*try to replace type="module" with type="application/javascript". Don't work. Source
*try to update Angular/CLI & Angular/core with ng update @angular/cli @angular/core --allow-dirty and ng build --prod again. Don't work
*try to host it with Firebase. Same issue: https://bibliang.firebaseapp.com/
Thanks for help ! :)
A: This is because of dist folder in your project workspace. There are two solutions that worked for me :
Sol 1. In your dist folder there may a folder named as your project name move all the files of that folder to the dist folder and then change the dir location to the dist/index.html in server.js file.
Move all files from dist/you_project_name to dist/
Then change the dir location in server.js file 'dist/you_project_name' to 'dist/'
Sol 2. You can change the src attribute of all error causing tags in index.html file, like ::
<script src="runtime-es2015.js" type="module">
changed to
<script src="folder_name_inside_the_dist_dir/runtime-es2015.js" type="module">
A: <script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script>
<script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script>
<script src="main-es2015.2fcd6517edb1de962f8a.js" type="module"></script>
keep all above file in another folder and give path here like
<script src="../../js/polyfills-es2015.fd917e7c3ed57f282ee5.js" type="text/javascript"></script>
it will work
| |
doc_23527253
|
A: from http://forum.osdev.org/viewtopic.php?t=16990
The ACPI shutdown is technically a really simple thing all that is needed is a outw(PM1a_CNT, SLP_TYPa | SLP_EN ); and the computer is powered off.
The problem lies in the gathering of these values especially since the SLP_TYPa is in the _S5 object which is in the DSDT and therefore AML encoded.
Below is a simple "map" of where to find these fields.
"RSD PTR "
||
RsdtAddress pointer at offset 16
||
\/
"RSDT"
||
pointer at offset 36 + 4 * n (check the target for the sig "FACP" to get the right n)
||
\/
"FACP"
||
||=====\
|| ||
|| PM1a_CNT_BLK; offset: 64 (see section 4.7.3.2)
|| PM1b_CNT_BLK; offset: 68
|| ||
|| \/
|| SLP_TYPx; bit 10-12
|| SLP_EN; bit 13
||
DSDT pointer at offset 40
||
\/
"DSDT" (export the \_S5 object somehow.)
To export the \_S5 object one would normally use an AML interpreter but that's obviously not an option considering we're building a hobby OS. The simple solution is to scan the DSDT manually. The AML language specifies that _... objects are defined only once which makes it very simple to find the \_S5 object since a simple memcmp() is enough.
Once found the SLP_TYPx values are extracted.
bytecode of the \_S5 object
-----------------------------------------
| (optional) | | | |
NameOP | \ | _ | S | 5 | _
08 | 5A | 5F | 53 | 35 | 5F
-----------------------------------------------------------------------------------------------------------
| | | ( SLP_TYPa ) | ( SLP_TYPb ) | ( Reserved ) | (Reserved )
PackageOP | PkgLength | NumElements | byteprefix Num | byteprefix Num | byteprefix Num | byteprefix Num
12 | 0A | 04 | 0A 05 | 0A 05 | 0A 05 | 0A 05
----this-structure-was-also-seen----------------------
PackageOP | PkgLength | NumElements |
12 | 06 | 04 | 00 00 00 00
The gathering of the information is best performed at OS initialization because after that you can reuse the ram and don't need to worry about corrupting it.
Now all that remains is outw(PM1a_CNT, SLP_TYPa | SLP_EN ); and you're gone.
If PM1b_CNT != 0 you need to repeat it with b.
If that was a little too abstract here is some code to look at
//
// here is the slighlty complicated ACPI poweroff code
//
#include <stddef.h>
#include <print.h>
#include <string.h>
#include <io.h>
#include <time.h>
dword *SMI_CMD;
byte ACPI_ENABLE;
byte ACPI_DISABLE;
dword *PM1a_CNT;
dword *PM1b_CNT;
word SLP_TYPa;
word SLP_TYPb;
word SLP_EN;
word SCI_EN;
byte PM1_CNT_LEN;
struct RSDPtr
{
byte Signature[8];
byte CheckSum;
byte OemID[6];
byte Revision;
dword *RsdtAddress;
};
struct FACP
{
byte Signature[4];
dword Length;
byte unneded1[40 - 8];
dword *DSDT;
byte unneded2[48 - 44];
dword *SMI_CMD;
byte ACPI_ENABLE;
byte ACPI_DISABLE;
byte unneded3[64 - 54];
dword *PM1a_CNT_BLK;
dword *PM1b_CNT_BLK;
byte unneded4[89 - 72];
byte PM1_CNT_LEN;
};
// check if the given address has a valid header
unsigned int *acpiCheckRSDPtr(unsigned int *ptr)
{
char *sig = "RSD PTR ";
struct RSDPtr *rsdp = (struct RSDPtr *) ptr;
byte *bptr;
byte check = 0;
int i;
if (memcmp(sig, rsdp, 8) == 0)
{
// check checksum rsdpd
bptr = (byte *) ptr;
for (i=0; i<sizeof(struct RSDPtr); i++)
{
check += *bptr;
bptr++;
}
// found valid rsdpd
if (check == 0) {
/*
if (desc->Revision == 0)
wrstr("acpi 1");
else
wrstr("acpi 2");
*/
return (unsigned int *) rsdp->RsdtAddress;
}
}
return NULL;
}
// finds the acpi header and returns the address of the rsdt
unsigned int *acpiGetRSDPtr(void)
{
unsigned int *addr;
unsigned int *rsdp;
// search below the 1mb mark for RSDP signature
for (addr = (unsigned int *) 0x000E0000; (int) addr<0x00100000; addr += 0x10/sizeof(addr))
{
rsdp = acpiCheckRSDPtr(addr);
if (rsdp != NULL)
return rsdp;
}
// at address 0x40:0x0E is the RM segment of the ebda
int ebda = *((short *) 0x40E); // get pointer
ebda = ebda*0x10 &0x000FFFFF; // transform segment into linear address
// search Extended BIOS Data Area for the Root System Description Pointer signature
for (addr = (unsigned int *) ebda; (int) addr<ebda+1024; addr+= 0x10/sizeof(addr))
{
rsdp = acpiCheckRSDPtr(addr);
if (rsdp != NULL)
return rsdp;
}
return NULL;
}
// checks for a given header and validates checksum
int acpiCheckHeader(unsigned int *ptr, char *sig)
{
if (memcmp(ptr, sig, 4) == 0)
{
char *checkPtr = (char *) ptr;
int len = *(ptr + 1);
char check = 0;
while (0<len--)
{
check += *checkPtr;
checkPtr++;
}
if (check == 0)
return 0;
}
return -1;
}
int acpiEnable(void)
{
// check if acpi is enabled
if ( (inw((unsigned int) PM1a_CNT) &SCI_EN) == 0 )
{
// check if acpi can be enabled
if (SMI_CMD != 0 && ACPI_ENABLE != 0)
{
outb((unsigned int) SMI_CMD, ACPI_ENABLE); // send acpi enable command
// give 3 seconds time to enable acpi
int i;
for (i=0; i<300; i++ )
{
if ( (inw((unsigned int) PM1a_CNT) &SCI_EN) == 1 )
break;
sleep(10);
}
if (PM1b_CNT != 0)
for (; i<300; i++ )
{
if ( (inw((unsigned int) PM1b_CNT) &SCI_EN) == 1 )
break;
sleep(10);
}
if (i<300) {
wrstr("enabled acpi.\n");
return 0;
} else {
wrstr("couldn't enable acpi.\n");
return -1;
}
} else {
wrstr("no known way to enable acpi.\n");
return -1;
}
} else {
//wrstr("acpi was already enabled.\n");
return 0;
}
}
//
// bytecode of the \_S5 object
// -----------------------------------------
// | (optional) | | | |
// NameOP | \ | _ | S | 5 | _
// 08 | 5A | 5F | 53 | 35 | 5F
//
// -----------------------------------------------------------------------------------------------------------
// | | | ( SLP_TYPa ) | ( SLP_TYPb ) | ( Reserved ) | (Reserved )
// PackageOP | PkgLength | NumElements | byteprefix Num | byteprefix Num | byteprefix Num | byteprefix Num
// 12 | 0A | 04 | 0A 05 | 0A 05 | 0A 05 | 0A 05
//
//----this-structure-was-also-seen----------------------
// PackageOP | PkgLength | NumElements |
// 12 | 06 | 04 | 00 00 00 00
//
// (Pkglength bit 6-7 encode additional PkgLength bytes [shouldn't be the case here])
//
int initAcpi(void)
{
unsigned int *ptr = acpiGetRSDPtr();
// check if address is correct ( if acpi is available on this pc )
if (ptr != NULL && acpiCheckHeader(ptr, "RSDT") == 0)
{
// the RSDT contains an unknown number of pointers to acpi tables
int entrys = *(ptr + 1);
entrys = (entrys-36) /4;
ptr += 36/4; // skip header information
while (0<entrys--)
{
// check if the desired table is reached
if (acpiCheckHeader((unsigned int *) *ptr, "FACP") == 0)
{
entrys = -2;
struct FACP *facp = (struct FACP *) *ptr;
if (acpiCheckHeader((unsigned int *) facp->DSDT, "DSDT") == 0)
{
// search the \_S5 package in the DSDT
char *S5Addr = (char *) facp->DSDT +36; // skip header
int dsdtLength = *(facp->DSDT+1) -36;
while (0 < dsdtLength--)
{
if ( memcmp(S5Addr, "_S5_", 4) == 0)
break;
S5Addr++;
}
// check if \_S5 was found
if (dsdtLength > 0)
{
// check for valid AML structure
if ( ( *(S5Addr-1) == 0x08 || ( *(S5Addr-2) == 0x08 && *(S5Addr-1) == '\\') ) && *(S5Addr+4) == 0x12 )
{
S5Addr += 5;
S5Addr += ((*S5Addr &0xC0)>>6) +2; // calculate PkgLength size
if (*S5Addr == 0x0A)
S5Addr++; // skip byteprefix
SLP_TYPa = *(S5Addr)<<10;
S5Addr++;
if (*S5Addr == 0x0A)
S5Addr++; // skip byteprefix
SLP_TYPb = *(S5Addr)<<10;
SMI_CMD = facp->SMI_CMD;
ACPI_ENABLE = facp->ACPI_ENABLE;
ACPI_DISABLE = facp->ACPI_DISABLE;
PM1a_CNT = facp->PM1a_CNT_BLK;
PM1b_CNT = facp->PM1b_CNT_BLK;
PM1_CNT_LEN = facp->PM1_CNT_LEN;
SLP_EN = 1<<13;
SCI_EN = 1;
return 0;
} else {
wrstr("\\_S5 parse error.\n");
}
} else {
wrstr("\\_S5 not present.\n");
}
} else {
wrstr("DSDT invalid.\n");
}
}
ptr++;
}
wrstr("no valid FACP present.\n");
} else {
wrstr("no acpi.\n");
}
return -1;
}
void acpiPowerOff(void)
{
// SCI_EN is set to 1 if acpi shutdown is possible
if (SCI_EN == 0)
return;
acpiEnable();
// send the shutdown command
outw((unsigned int) PM1a_CNT, SLP_TYPa | SLP_EN );
if ( PM1b_CNT != 0 )
outw((unsigned int) PM1b_CNT, SLP_TYPb | SLP_EN );
wrstr("acpi poweroff failed.\n");
}
For further information read the corresponding sections of the ACPI 1.0a specification
9.1.7 Transitioning from the Working to the Soft Off State
7.5.2 \_Sx states
7.4.1 \_S5
4.7.2.3 Sleeping/Wake Control
16.3 AML Byte Streeam Byte Values
16.2.3 Package Length Encoding
This works on all of my machines bochs and qemu.
but I noticed that one needn't enable ACPI for the pc to power down. Though i don't know if this is always the case.
If you just want to play a little.
For bochs and qemu it's outw( 0xB004, 0x0 | 0x2000 );
A: APM
https://en.wikipedia.org/wiki/Advanced_Power_Management
Method tested on qemu-system-i386 2.0.0 Ubuntu 14.04:
mov $0x5301, %ax
xor %bx, %bx
int $0x15
/* Try to set apm version (to 1.2). */
mov $0x530e, %ax
xor %bx, %bx
mov $0x0102, %cx
int $0x15
/* Turn off the system. */
mov $0x5307, %ax
mov $0x0001, %bx
mov $0x0003, %cx
int $0x15
For the exact compilation and running steps on QEMU, see this repo
osdev.org articles: http://wiki.osdev.org/Shutdown , http://wiki.osdev.org/APM
ACPI is the newer, better method.
| |
doc_23527254
|
A: The above needs to be typed everytime you set colorscheme. If you wish to avoid it, you should use autocmd.
See https://vi.stackexchange.com/questions/18295/how-to-set-a-colorscheme-that-still-shows-spelling-errors
A: Spelling errors are highlighted using the SpellBad highlighting group. To get it highlighted as you want, you should put something like
hi clear SpellBad
hi SpellBad cterm=underline
" Set style for gVim
hi SpellBad gui=undercurl
after the last line that is altering the color scheme in your vimrc (it is either set background=(dark|light) or colorscheme {schemename}).
See also :h hl-SpellBad for names and descriptions of other Spell* highlight groups.
A: For a quick and dirty way to change the highlighting color if you have a colorscheme loaded, is to modify your colorscheme.
Running, :verbose highlight SpellBad showed me where the config file is for my theme. More like, it showed where the SpellBad directive was set. Your mileage may vary. Please see below output:
:verbose highlight SpellBad
SpellBad xxx term=reverse ctermbg=9 gui=undercurl guisp=Red
Last set from /usr/share/vim/vim81/colors/desert.vim line 17
I navigated to desert.vim and added, hi SpellBad term=reverse ctermbg=226 gui=undercurl guisp=Yellow1 and saved the file. (you'll need sudo to modify the file). Once I reopened vim and ran, :verbose highlight SpellBad the output was now:
:verbose highlight SpellBad
SpellBad xxx term=reverse ctermbg=226 gui=undercurl guisp=Yellow1
Last set from /usr/share/vim/vim81/colors/desert.vim line 35
My highlight color was changed! Note that if you change your colorscheme, you'll most likely have to change the highlight color in your selected colorscheme file.
| |
doc_23527255
|
function boldText(matches, text)
{
var pattern = new RegExp(matches.join("|"),"g");
text.replace(pattern,"<b>"+__what to write here?__+ "</b>"
}
However, since it's an HTML file, I don't want to bold anything that's between a less-than-sign and a greater-than-sign. Only stuff outside of HTML tags should be bolded. What might that regular expression be?
To reiterate, I'm looking for a regular expression that matches if-and-only-if the match isn't between a 'less-than-sign'+ any number of characters and any number of characters + a "greater-than-sign"
Ugh, nobody is answering me :(
A: You should use the $& pattern as follows:
text.replace(pattern, '<b>$&</b>');
| |
doc_23527256
|
*
*do a put request with the ?resource=file parameters (this creates a file on the ADL)
*append data to the file with the ?action=append&position=<N> parameters
*lastly, you need to flush the data with ?action=flush&position=<FILE_SIZE>
My question is:
Is there a way to tell the server how long the data should live if it is not flushed(written).
Since you need to create a file first to write data into it, there might be scenarios where the flush does not happen, and you are stuck with an empty file in the data lake.
I could not find anything on the Microsoft documentation about this.
Any info would be appreciated.
A: Updated 0219:
If you just call the append api, but not call the flush api, then the uncommitted data will be saved in azure within 7 days.
The uncommitted data will be deleted automatically after 7 days and cannot be deleted from the your end.
Origianl:
The SDK for Azure Datalake Storage Gen2 is ready, and you can use it to operate ADLS Gen2 more easier than using rest api.
If you're using .NET/c#, there is a SDK for Azure Datalake Storage Gen2: Azure.Storage.Files.DataLake.
Here is the official doc for how to use this SDK to operate ADLS Gen2, and the c# code below is used to delete a file / upload a file for ADLS Gen2:
static void Main(string[] args)
{
string accountName = "xxx";
string accountKey = "xxx";
StorageSharedKeyCredential sharedKeyCredential =
new StorageSharedKeyCredential(accountName, accountKey);
string dfsUri = "https://" + accountName + ".dfs.core.windows.net";
DataLakeServiceClient dataLakeServiceClient = new DataLakeServiceClient
(new Uri(dfsUri), sharedKeyCredential);
DataLakeFileSystemClient fileSystemClient = dataLakeServiceClient.GetFileSystemClient("w22");
DataLakeDirectoryClient directoryClient = fileSystemClient.GetDirectoryClient("t2");
// use this line of code to delete a file
//directoryClient.DeleteFile("22.txt");
//use the code below to upload a file
//DataLakeFileClient fileClient = directoryClient.CreateFile("22.txt");
//FileStream fileStream = File.OpenRead("d:\\foo2.txt");
//long fileSize = fileStream.Length;
//fileClient.Append(fileStream, offset: 0);
//fileClient.Flush(position: fileSize);
Console.WriteLine("**completed**");
Console.ReadLine();
}
For Java, refer to this doc.
For Python, refer to this doc.
| |
doc_23527257
|
public function addsession(Request $req)
{
$mod = null;
$latestUserId=Meeting::where('groupID', $req->groupID)
->latest('id')
->first()
?->meetingModerator;
//the first meeting or all the users have already had their turn
$firstUserId=DB::table('group_user')
->where('group_id', $req->groupID)
->orderBy('user_id')
->first()
?->user_id;
//second time meeting is being held
if ($latestUserId) {
$nextUserId=DB::table('group_user')
->where('group_id', $req->groupID)
->where('user_id', ">", $latestUserId)
->orderBy('user_id')
->first()
?->user_id;
$mod = $nextUserId;
} else {
$mod = $firstUserId;
}
$data = new Meeting;
$data->groupID = $req->groupID;
$data->meetingDate = $req->meetingDate;
$data->meetingTime = $req->meetingTime;
$data->meetingModerator = $mod;
$data->save();
}
Model group.php
class Group extends Model
{
use SoftDeletes;
use HasFactory;
public $timestamps=true;
protected $dates = ['deleted_at'];
public function creators()
{
return $this->belongsToMany(User::class);
}
}
Model user.php
class User extends Authenticatable
{
use SoftDeletes;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'name',
'email',
'password',
'role'
];
protected $dates = ['deleted_at'];
public function grp()
{
return $this->belongsToMany(Group::class);
}
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'profile_photo_url',
];
}
Model meeting.php
class Meeting extends Model
{
use HasFactory;
public function gr()
{
return $this->belongsTo('App\Models\Group','groupID');
}
}
| |
doc_23527258
|
If I leave an input box the activeElement is the Window.
If I leave an input box by clicking on a button the activeElement is ... both?
Why does the onfocusout event not register the same activeElement as the button?
Is there anyway I can access the click-on-button event from the function call of the inputbox-leave-event? ie can I ask, "Did you leave me for the lousy button?"
<button type="button" onclick = "myFunction()"> button </button><br>
<input type="text" onfocusout= "myFunction()"> </input>
<script>
function myFunction() {
console.log(document.activeElement);
}
</script>
A: The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.
Often activeElement will return a HTMLInputElement or HTMLTextAreaElement object if it has the text selection at the time. If so, you can get more detail by using the object's selectionStart and selectionEnd properties.
In addition, it is indeed possible to trigger a button click when leaving the input element, you just need to make sure to handle the onfocusout function, and use the code inside the function to trigger the click event, you can refer to here.
function onMouseUp(e) {
const activeTextarea = document.activeElement;
const selection = activeTextarea.value.substring(
activeTextarea.selectionStart, activeTextarea.selectionEnd
);
const outputElement = document.getElementById('output-element');
const outputText = document.getElementById('output-text');
console.log({ id: activeTextarea.id, selection});
}
const textarea1 = document.getElementById('textarea1');
const textarea2 = document.getElementById('textarea2');
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);
<textarea name="textarea1" id="textarea1" rows="7" cols="40">This is Text Area One.</textarea>
<textarea name="textarea2" id="textarea2" rows="7" cols="40">This is Text Area Two</textarea>
A: You can add an event listener for the button inside the myFunction()
function myFunction() {
// console.log(document.activeElement);
var btn = document.getElementById("btn");
btn.addEventListener("click", function (event) {
console.log(event);
});
}
<!DOCTYPE html>
<html>
<body>
<button id="btn" type="button">button</button><br>
<input type="text" onfocusout="myFunction()" />
</body>
</html>
A: The relatedTarget in the event will show you where it's leaving to
of course, you have to use addEventListener to access the event in the first place
But I think this demonstrates what you want to see
it'll definitely tell you
"Did you leave me for the lousy button?"
const button = document.querySelector('button')
const input = document.querySelector('input')
function buttonHandler(e) {
console.log('button clicked');
}
function inputHandler(e) {
console.log('leaving input for', e.relatedTarget?.tagName || 'window');
}
input.addEventListener('focusout', inputHandler);
button.addEventListener('click', buttonHandler);
<button type="button"> button </button><br>
<input type="text"> </input>
| |
doc_23527259
|
How can I test that scope.users gets set so my test passes?
controller
angular.module('web').controller('CardsCtrl',function($scope, $http, Users){
/**
* Get all users on page load
*/
Users.find(function(users) {
$scope.users = users;
});
Users service
(function(window, angular, undefined) {'use strict';
var urlBase = "http://localhost:3333/api";
var module = angular.module("services", ['ngResource']);
module.factory(
"Users",
['LoopBackResource', 'LoopBackAuth', '$injector', function(Resource, LoopBackAuth, $injector) {
var R = Resource(
urlBase + "/users/:id",
{ 'id': '@id' },
{
"find": {
url: urlBase + "/users",
method: "GET",
isArray: true,
},
}
);
return R;
}]);
spec
describe('CardsCtrl', function() {
var scope, ctrl, users;
beforeEach(module('web'));
beforeEach(inject(function($rootScope, $controller, Users) {
scope = $rootScope.$new();
users = Users;
spyOn(users, 'find');
ctrl = $controller('CardsCtrl', {$scope: scope, Users: users});
}));
describe('the cards controller being instantiated', function() {
it('should be defined', function() {
expect(ctrl).toBeDefined();
});
it('tracks that the spy was called', function() {
expect(users.find).toHaveBeenCalled();
});
it('fetches user data and assigns it to scope.users', function(done) {
console.log('users= '+scope.users); // <-- THIS RETURNS UNDEFINED
expect(scope.users).toBeTruthy();
});
});
});
A: You need to call .andCallThrough() on the spy, and use $httpBackend to mock http response:
describe('CardsCtrl', function() {
var scope, ctrl, users, httpBackend;
beforeEach(module('web'));
beforeEach(inject(function($rootScope, $controller, Users, $httpBackend) {
scope = $rootScope.$new();
users = Users;
spyOn(users, 'find').andCallThrough();
httpBackend = $httpBackend;
httpBackend.expectGET(urlBase + '/users').respond(200, ['user1', 'user2']);
ctrl = $controller('CardsCtrl', {$scope: scope, Users: users});
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe('the cards controller being instantiated', function() {
... // other tests
it('fetches user data and assigns it to scope.users', function(done) {
httpBackend.flush();
expect(scope.users).toBeTruthy();
});
});
});
The mock $httpBackend is provided by ngMock service, so you need to include angular-mock.js to run the test.
| |
doc_23527260
|
I started my project using Iron Router, but since changed my mind and I'm currently migrating to FlowRouter.
Everything was going smoothly until I started migrating the comments section of my app. You see, this section is reused several times on the app, it serves as a comment section for news, posts, photos, videos, etc.
Example using IR's data context:
Router.route('/news/:slug', {
name: 'newsItem',
waitOn: function() { Meteor.subscribe('news.single', this.params.slug) },
data: function() {
return News.findOne({slug: this.params.slug});
}
});
<template name="newsItem">
<p>{{title}}</p>
<p>{{body}}</p>
{{> commentSection}}
</template>
The Comment collection schema has a "type" (to know to what type of "thing" this comment belongs to, news, photos, etc). That type was set on the "form .submit" event of commentSection template. Example:
'submit form': function(e, template) {
e.preventDefault();
var $body = $(e.target).find('[name=body]');
console.log(template.data.type);
var comment = {
type: template.data.type,
parentId: template.data._id,
parentSlug: template.data.slug,
body: $body.val()
};
Meteor.call('insertComment', comment, function(error, commentId) {
if (error){
alert(error.reason);
} else {
$body.val('');
}
});
}
This worked because the template data context contained the News item which in turn has a a type property as well.
How could I achieve something similar to this only using Flow Router without setting data on the template as it is recommended by the official guide?
A: You'll want to use a template subscription and a {{#with}} helper probably.
Template.newsItem.onCreated( function() {
Template.instance().subscribe('news.single', FlowRouter.current().params.slug);
});
Template.newsItem.helpers({
item() {
let item = News.findOne();
if( item ) {
return item;
}
}
});
<template name="newsItem">
{{#with item}}
<!-- Your existing stuff -->
{{/with}}
</template>
| |
doc_23527261
|
I used this site (<<<--- link to CSS i am using) to help with some CSS but i can't seem to find the right code block that changes the color of the correct text.
When you compress the webpage so it shows the collapse menu and go to the Dropdown list, you will see that the blue background transfers over to the dropdown menu items, but the font-color is black making it very hard to read. I want this font to be white.
<nav class="navbar navbar-custom" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">ATR Notary</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="~/Order/Index" class="dropdown-toggle"
data-toggle="dropdown">Orders <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="~/Order/Index">View Orders</a></li>
<li><a href="~/Order/Create">Add Order</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="~/Notary/Index" class="dropdown-toggle"
data-toggle="dropdown">Notaries <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="~/Notary/Index">View Notaries</a></li>
<li><a href="~/Notary/Create">Add Notary</a></li>
</ul>
</li>
</ul>
@Html.Partial("_LoginPartial")
</div><!-- /.navbar-collapse -->
</nav>
A: Apply simple css and you are done
See this example:
.navbar{height:70px; padding-top:20px; }
will change height and padding of navbar - that is outter container
.dropdown-menu{background:rgba(0,0,0,0.5); color:white; }
will change background color of dropdown-menu - that is ul under dropdown link.
All we have to understand the structure of navbar.
.dropdown-menu li>a{color:white; }
.dropdown-menu>li{padding:5px; border-bottom:1px solid white;border-left:1px
solid white;border-right:1px solid white }
.dropdown-menu li>a:hover{background:white; }
A: You should be able to use this CSS..
/*-- change navbar dropdown color --*/
.navbar-default .navbar-nav .open .dropdown-menu>li>a,.navbar-default .navbar-nav .open .dropdown-menu {
background-color: #3344ff;
color:#ffffff;
}
Demo: http://www.bootply.com/113750
A: previous answer is saying the same thing pretty much, but their syntax and commenting was a little confusing for me, so possibly it confused others too...
you're first calling out the 'dropdown-menu' class, then the 'li' html element within that class, then, the 'a' html element nested within the 'li' element, so CSS looks like this:
.dropdown-menu li a {
color: white;
}
| |
doc_23527262
|
I have a wordpress blog set up in a subdirectory.
The blog sits under www.domain.co.uk/wordpress/
In order for my permalinks to work I did an htaccess rewrite rule which is this
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?domain.co.uk$
RewriteRule ^(/)?$ http://domain.co.uk/wordpress [L]
Is there a way to take out the /wordpress part on the URL?
I need it to point there but I want the /wordpress to be removed.
Any ideas?
I have now managed to solve this issue following this guide: http://www.optiniche.com/blog/145/wordpress-tutorial-install-wordpress-in-a-different-directory/
A: Remove the wordpress from the redirect in your rule (the http://domain.co.uk/ means there's an implicit redirect) and add a specific rule to internally rewrite instead:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.co.uk$ [NC]
RewriteRule ^ http://domain.co.uk/ [L,R=301]
# now silently rewrite to wordpress
RewriteCond %{REQUEST_URI} !^/wordpress
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /wordpress/$1 [L]
| |
doc_23527263
|
I wanted to know what the [1] does in this code.
Full code:
marksheet=[]
scorelist=[]
if __name__ == '__main_':
for _ in range(int(input())):
name = input()
score = float(input())
marksheet+=[[name,score]]
scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
for a,c in sorted(marksheet):
if c==b:
print(a)
Thanks in advance!
A: it grabs the second item in the sorted scorelist and assigns it to 'b'.
If socrelist is [97,55,78,88] then b will equal 78
This is because 55 will be the "first" item with a place of 0
Since lists run [0, 1, 2, 3, ...]
| |
doc_23527264
|
$ docker build --build-args region=us-east-1 .
// Dockerfile
FROM aws.ecr.huge.url.${region}/repo:php-apache
WORKDIR /var/www
RUN echo "@@@"
${region} never gets replaced and I get an error saying the image doesn't exist.
If I RUN echo ${region} it works, the problem seems to be with FROM instruction.
Is there any way to achieve that?
A: Updated answer:
With the introduction of multi-stage builds, docker added the ability to provide an ARG before the FROM line. This will look like:
# default to us-east-1
ARG region=us-east-1
FROM aws.ecr.huge.url.${region}/repo:php-apache
Note that ARG's are namespaced. When defined before a FROM line, they are available to the FROM lines. And within a stage, they are available until the end of that stage. If you need to use an ARG in multiple namespaces, you can define it multiple times.
Original answer from before the introduction of multi-stage builds:
This is not supported as you've found, and as documented in the variable expansion limitations:
Environment variables are supported by the following list of
instructions in the Dockerfile:
*
*ADD
*COPY
*ENV
*EXPOSE
*LABEL
*USER
*WORKDIR
*VOLUME
*STOPSIGNAL
as well as:
*
*ONBUILD (when combined with one of the supported instructions above)
To workaround this, I suspect you'll need to generate your Dockerfile with an external process first, e.g. with a sed "s/__region__/$region/" <Dockerfile.in >Dockerfile command.
A: ARG is missing in your Dockerfile.
Please try this.
$ docker build --build-args region=us-east-1 .
// Dockerfile
ARG region
FROM aws.ecr.huge.url.${region}/repo:php-apache
WORKDIR /var/www
| |
doc_23527265
|
printf("1")
printf("0")
would need to output:
01
Is there a way to do this? I cannot use arrays. To be clear I'm printing in base two (binary) representation using a divide by two algorithm:
for(int i = 0; i < 16; i++){ // 16 bit int
tmp = num % 2;
if(tmp == 1){
printf("1");
} else {
printf("0");
}
num /= 2;
}
The above code prints the binary representation backwards.
A: Here is my solution to print binary without using array. you can ignore initial zeros by adding another if condition.
#include<stdio.h>
int main(){
int num =50;
int i;
for(i=15;i>=0;i--){
if( (1<<i) & num){
printf("1");
}
else printf("0");
}
return 0;
}
output:
0000000000110010
A: Recursion can perform like a "print before". @rici
The below does not always print 16 digits, just the decimal digits needed.
void print_binary(unsigned n) {
// Break the digits into 2 groups: 1) the one least digit and 2) the rest.
unsigned last_digit = n/10;
unsigned all_the_other_more_significant_digits = n/10;
// Let us print those more significant digits first;
if (all_the_other_more_significant_digits > 0) {
print_binary(all_the_other_more_significant_digits);
}
// Now print the last digit
printf("%u", last_digit);
}
| |
doc_23527266
|
<no location info>: can't find file: test.hs
Failed, modules loaded: none.
My file is named test.hs and this is all the code it contains:
double :: Int -> Int
double x = x + xb
Thanks in advance
/Michael
| |
doc_23527267
|
@router.get('/')
#decorator
@roles_decorator("admin")
async def get_items(user_id: str = Depends(get_current_user)):
return await get_all_items()
get_current_user method will need to receive roles from decorator (in this case admin) and from authorization service receive user_id if role matches provided role. So my question is, can we pass the role from decorator to method in Depends, or is there any chance that we can do this role-based access control with predefined roles for every endpoint?
def get_current_user(role):
#connect to auth_serivce and do other logic
return user_id
A: Instead of trying to mix dependencies and decorators (which won't do anything good), you can instead use a dynamically configured dependency:
async def get_current_user_with_role(role):
async def get_user_and_validate(user=Depends(get_current_user)):
if not user.has_role(role):
raise 403
return user.id
return get_user_and_validate
This will bind the role value you give to the dependency when it gets created:
@router.get('/')
async def get_items(user_id: str = Depends(get_current_user_with_role("admin"))):
pass
A: I'm new to Python and FastAPI but passing params to a dependency wasn't working too well for me, and it started causing the params to appear in Swagger which wasn't what I wanted.
My endpoints require API keys for authentication, so I check who the API key belongs to and if they have the required permissions to access the endpoint.
Coming from other frameworks where I'd use a decorator for this kind of thing, I ended up implementing it this way in my FastAPI project:
Here's the decorator:
def has_permission(permission: str):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
api_key = kwargs.get("api_key_header")
user_service = kwargs.get("user_service")
user = user_service.get_by_api_key(api_key)
if permission not in user.permissions
raise HTTPException(status_code=403, detail="User doesn\'t have required permissions")
return await func(*args, **kwargs)
return wrapper
return decorator
And this is how I use it on my route:
@router.get("/", summary="Retrieve all users.", response_model=List[UserResponse])
@has_permission("users.get")
async def get_all_users(
api_key_header: str = Security(api_key_header), user_service: UserService = Depends(UserService)
):
"""
Retrieve all users.
"""
return user_service.get_all_users()
| |
doc_23527268
|
labels = np.array([1,7,7,1,7])
keras.utils.to_categorical(labels)
I get this response:
array([[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 1.],
[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1.]], dtype=float32)
How can I get only two columns? One for the 1 and one for the 7.
This is a possible way, but not a very good one:
labels = np.delete(labels, np.s_[0:1], axis=1)
np.delete(labels, np.s_[1:6], axis=1)
that gives:
array([[1., 0.],
[0., 1.],
[0., 1.],
[1., 0.],
[0., 1.]], dtype=float32)
Is there a better way to achieve this? Preferably by some "hidden" function in Keras utils or similar?
A: IIUC, you can just index your array by any column that has a value:
cat = keras.utils.to_categorical(labels)
>>> cat
array([[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 0., 0., 1.],
[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1.]])
# Select column if it has at least one value:
>>> cat[:,cat.any(0)]
array([[1., 0.],
[0., 1.],
[0., 1.],
[1., 0.],
[0., 1.]])
You could also use pandas:
import pandas as pd
cat = pd.get_dummies(labels).values
>>> cat
array([[1, 0],
[0, 1],
[0, 1],
[1, 0],
[0, 1]], dtype=uint8)
A: Use np.unique with return_inverse flag -
# Get unique IDs mapped to each group of elements
In [73]: unql, idx = np.unique(labels, return_inverse=True)
# Perform outer comparison for idx against range of unique groups
In [74]: (idx[:,None] == np.arange(len(unql))).astype(float)
Out[74]:
array([[1., 0.],
[0., 1.],
[0., 1.],
[1., 0.],
[0., 1.]])
Alternatively with direct usage of unique labels -
In [96]: (labels[:,None] == np.unique(labels)).astype(float)
Out[96]:
array([[1., 0.],
[0., 1.],
[0., 1.],
[1., 0.],
[0., 1.]])
| |
doc_23527269
|
I have two nearly identical pieces of code, one which works and the other not.
$query = $pdo->prepare("SELECT * FROM active_notifications WHERE direction = '>' AND $usdCurrent > trigger_price AND currency = '$'");
$query->execute();
var_dump($query);
$result = $query->fetchall((PDO::FETCH_ASSOC));
var_dump($result);
The above code works, when I var dump the query it looks like this:
SELECT * FROM active_notifications WHERE direction = '>' AND 182.62000 > trigger_price AND currency = '$'
My problem occurs when I try with a slightly different piece of code where I swap the $ symbol for a £ symbol
Here is the code:
$query = $pdo->prepare("SELECT * FROM active_notifications WHERE direction = '>' AND $gbpCurrent > trigger_price AND currency = '£'");
$query->execute();
var_dump($query);
$result = $query->fetchall((PDO::FETCH_ASSOC));
var_dump($result);
When I var dump the query I get this:
SELECT * FROM active_notifications WHERE direction = '>' AND 114.19942 > trigger_price AND currency = '£'
So all is correct up to this point,
When I run either created query directly in PhpMyAdmin the expected results are returned, However when I var_dump the $result of the £gbp query I get a null array.
At first I though it might be because I was reusing variable names but I tried both in complete isolation, the USD query always works and the GBP never works and always results in a null array being returned.
Like I said both of the generated queries work correctly in PhpMyAdmin (when run directly against the database)
The only difference is that in one query I have a £ symbol and the other I have a $ symbol,
Is the £ symbol some kind of disallowed symbol in PHP or something like that?
Thanks,
John
A: Check php and mysql character encodings. I'm thinking that your php's £ is not the same as your mysql's £.
Ideally, you'd avoid all the mess by using 'gpb', 'usd', etc... for the currency field.
From the OP:
I just slapped this into my pdo init : PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" and all is good.
| |
doc_23527270
|
structure(df)
Recovery.Date SPECIES_ID LAT_FLOAT LON_FLOAT ZIP
9/23/2009 1720 42.91667 -71.41667 3051
10/8/2006 1440 42.75 -72.41667 3451
10/17/2011 1330 39.25 -74.91667 8316
2/4/2012 1690 39.25 -75.91667 21050
12/31/2009 1320 38.25 -75.25 21837
I want to take the lat_float and long_float values into the function and then add county and state (separately or together) as a new column in df. Any help would be greatly appreciated.
A: Step 1 - Create Data.frame pointsDF
pointsDF <- subset(df, select=c("LON_FLOAT", "LAT_FLOAT"))
Step 2 - Make sure you have the right projection/datum
Step 3 - Follow the accepted answer from here.
Step 4 - Merge or Join your two datasets with Lon== & LAT== conditions or you combine lon+lat in one variable on both sides and use it has a key.
| |
doc_23527271
|
WebpackError: ReferenceError: window is not defined (from plugin: gatsby-plugi
n-styled-components)
Seems to be that the external package gatsby-plugin-styled-components is using window somewhere.I've tried replacing by a dummy module as described here https://www.gatsbyjs.com/docs/debugging-html-builds/#fixing-third-party-modules except my styled-components does not work then so it is not a solution.
Perhaps I'm using styled component techniques where are not supported? I've looked at different gatsby/styled components example repo's and cannot find the difference.
You can find the repo here: https://github.com/sanderdebr/sanity-gatsby-portfolio
A: This is because your project or the gatsby-plugin-styled-components is using somewhere styled-components@5.2.2 which is a broken version using window.
The issue has been tracked on SC Github: https://github.com/styled-components/styled-components/issues/3444
I recommend you to update to styled-components@5.2.3
| |
doc_23527272
|
Desire Line Example :
-------------- Or .............
A: You are needing to set the LTYPE property of the line object you have created, Group Code 6. You will need to check to see what styles are available, and perhaps define your own style.
Here is a resource for you.
| |
doc_23527273
|
<Scrollview
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="3dip">
<ImageView
android:id="@+id/peliculaPortada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip" />
<TextView
android:id="@+id/detPeliculaTitulo"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignTop="@id/peliculaPortada"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="9pt" />
<TextView
android:id="@+id/detPeliculaRestriccion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Restricción: "
android:layout_below="@id/detPeliculaTitulo"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaGenero"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Genero: "
android:layout_below="@+id/detPeliculaRestriccion"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaDuracion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Duración: "
android:layout_below="@+id/detPeliculaGenero"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaFechaEstreno"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Fecha Estreno: "
android:layout_below="@+id/detPeliculaDuracion"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<Button
android:id="@+id/sitioOficial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_sitio_oficial"
android:layout_below="@+id/peliculaPortada"
android:text="Sitio Oficial"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<Button
android:id="@+id/imdb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_link"
android:layout_below="@+id/sitioOficial"
android:text="Imdb"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada" />
<Button
android:id="@+id/trailer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_trailer"
android:layout_below="@id/imdb"
android:text="Trailer"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<Button
android:id="@+id/sinopsis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_sinopsis"
android:layout_below="@id/trailer"
android:text="Sinopsis"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<TextView
android:id="@+id/detPeliculaPresentandose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="true"
android:layout_below="@id/sinopsis"
android:layout_toLeftOf="@id/peliculaPortada"
android:singleLine="false"
android:ellipsize="none"
android:scrollHorizontally="false"
android:layout_weight="1"
android:text="Presentandose En"
android:paddingTop="2pt"
android:textSize="7pt" />
<ListView
android:id="@+id/detPeliculaTandas"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/detPeliculaPresentandose"
android:paddingTop="3pt">
</ListView>
</RelativeLayout>
Thanks in advance for any help.
A: i found a solution through the use of an unusual method that was provided by doughw. The solution is to hack the listview to load to a full height.
Here is the link to the answer:
How can I put a ListView into a ScrollView without it collapsing?
Thanks everybody.
A: I had an issue close to what you had and my problem was using layout_width="match_parent" on items that were aligned to the left or right of another item. I changed it to layout_width="wrap_content" and everything worked perfectly after that.
A: Change the wrap_content to fill_parent in the scrollview height attribute.
| |
doc_23527274
|
A: This can be done easily on Linux with an alias.
alias composer="composer -vvv"
You can make this permanent by appending this line to your .bash_profile or equivalent in your home directory.
If you are running on Windows, you can create a batch file wrapper in your PATH, something like:
@echo off
composer -vvv %*
Both of these assume that Composer is in your PATH already - if this is not the case, you'll need to prefix it with the full path.
| |
doc_23527275
|
I created two files under the App_GlobalResources folder:
*
*Unit.en-US.resx
*Unit.pt-BR.resx
And created an entry with the key value of SearchTitle and text "Bla bla bla".
In the web.config file I added:
<globalization uiCulture="auto:en" culture="auto:en-US" />
But now I don't know how to access the resource file. I tried (in Unit.aspx.cs):
string s = Resources.Unit.SearchTitle
But Resources is not recognized or doesn't exists.
Also tried:
<label><%$ Resources:Unit, SearchTitle %></label>
And, finally, also tried to set a custom tool for the resource file, but I wasn't sure what do afterwards:
PublicResXFileCodeGenerator
I've never worked with resources before, and my goal is to use them to translate aspx pages to different languages depending on the user's Culture.
I'm using VS 2012 and .NET 4.0.
Any help appreciated.
A: Try the code below, just to figure out if your project is setup correctly:
GetGlobalResourceObject("Unit", "SearchTitle")
What type of app is it? I normally don't need to set a custom tool or build action.
| |
doc_23527276
|
NameError: "name 'cntk' is not defined"
Could you please tell me what's wrong? Did I miss sths to do?
| |
doc_23527277
|
@Formula("case when preferred_first_name is not null then preferred_first_name else first_name end || ' ' || case when preferred_last_name is not null then preferred_last_name else last_name end")
public String getFullNameFL() {
return WordUtils.capitalizeFully(fullNameFL);
}
This is used in a JPA Projection,
CompoundSelection<ResultBean> selection = cb.construct(
ResultBean.class,
...
nvRoot.get("fullNameFL"),
...
criteriaQuery.select(selection);
TypedQuery<ResultBean> query = entityManager.createQuery(criteriaQuery);
List<ResultBean> results = query.getResultList();
| |
doc_23527278
|
private const string Arg = "C:\\RDP\\myapp.rdp";
private const string FileName = "mstsc";
private Process _myProcess = new Process();
...
myProcess.StartInfo.FileName = sFileName;
myProcess.StartInfo.Arguments = arg;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.Start();
Process mstsc = Process.GetProcessesByName(sFileName)[0];
mstsc.Id not equal myProcess.Id
I see that for first time run first copy mstsc.exe (i think processed/parse file), then for second time run ssecond copy mstsc.exe and first copy was killed
| |
doc_23527279
|
This is my View so far when using my ViewBag list without any js
@model IEnumerable<Site.Models.TicketsOrdered>
<head>
<title>Order</title>
<link rel="stylesheet" href="~/Content/TableSheet.css">
@using GeogSocSite.Models
</head>
<body>
<h1>Choose Your Tickets</h1>
<table align="center" cellspacing="2" border="1" data-bind='visible: gifts().length > 0'>
<thead>
<tr>
<th align="center">Description</th>
<th align="center">Price</th>
<th align="center">Add</th>
</tr>
</thead>
<tbody>
@foreach (Site.Models.Ticket t in ViewBag.listTickets)
{
<tr>
<td align="center">@t.Description</td>
<td align="center">@t.Price</td>
<td align="center">@Html.DropDownList("Quantity", (IList<SelectListItem>)ViewBag.Quantities) </td>
</tr>
}
</tbody>
</table>
<div id="proceed">
@Html.ActionLink("Proceed", "Order", "Order")
</div>
<div>
@Html.ActionLink("Back to List", "Index","Events")
</div>
</body>
I want to be able to save the values selected from the dropdownlist when the proceed button is clicked
I have looked at the documentation on knockout js and looked at the examples but many refer to cascading dropdowns or dropdowns which are just created in the View like the example I found here
@model IEnumerable<Site.Models.TicketsOrdered>
<head>
<title>Order</title>
<link rel="stylesheet" href="~/Content/TableSheet.css">
@using GeogSocSite.Models
</head>
<body>
<h1>Choose Your Tickets</h1>
<tr>
<td class="label">Drop-down list:</td>
<td><select data-bind="options: optionValues, value: selectedOptionValue"></select></td>
</tr>
<tr>
<td class="label">Selected option:</td>
<td data-bind="text: selectedOptionValue"></td>
</tr>
<div id="proceed">
@Html.ActionLink("Proceed", "Order", "Order")
</div>
<div>
@Html.ActionLink("Back to List", "Index","Events")
</div>
</body>
<script type="text/javascript">
var viewModel = {
optionValues : ["Alpha", "Beta", "Gamma"],
selectedOptionValue : ko.observable("Gamma"),
};
ko.applyBindings(viewModel);
</script>
If anyone can help me workout how to use Knockoutjs and my ViewBag.quantities list so that the quantities selected can be saved when proceed is clicked that would be great as I'm totally stuck!
A: You just need to pass the data-bind to the Html Helper it accepts htmlAttributes, so :
@Html.DropDownList("Quantity", (IList<SelectListItem>)ViewBag.Quantities,"", new {data_bind=" value: selectedOptionValue"});
Your code will be like that:
<h1>Choose Your Tickets</h1>
<tr>
<td class="label">Drop-down list:</td>
<td>@Html.DropDownList("Quantity", (IList<SelectListItem>)ViewBag.Quantities,"", new {data_bind=" value: selectedOptionValue"});</td>
</tr>
<tr>
<td class="label">Selected option:</td>
<td data-bind="text: selectedOptionValue"></td>
</tr>
<div id="proceed">
<a data-bind="attr:{href: "@Url.Action("Order","Order")/"+ selectedOptionValue()}">Proceed</a>
<!-- Or with querystring !-->
<!-- <a data-bind="attr:{href: "@Url.Action("Order","Order")?quantity="+ selectedOptionValue()}">Proceed</a>!-->
</div>
<div>
@Html.ActionLink("Back to List", "Index","Events")
</div>
</body>
<script type="text/javascript">
(function(){
var viewModel = {
selectedOptionValue : ko.observable(),
};
ko.applyBindings(viewModel);
})();
</script>
| |
doc_23527280
|
user_id
index_value
some_value
1
0
01
1
1
02
1
2
03
2
0
04
3
0
05
3
1
06
1
3
07
I'm about to delete some records and I need to recalculate the data stored in index_value. For example, delete the line with some_value 03.The expected output should look like this:
user_id
index_value
some_value
1
0
01
1
1
02
2
0
04
3
0
05
3
1
06
1
2
07
What is the best way to go about this?
A: I suggest not even maintaining the index_value column, but instead generating this computed value at the time you query. Assuming you are using MySQL 8+:
SELECT
user_id,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY some_value) - 1 AS index_value,
some_value
FROM yourTable
ORDER BY some_value;
A: Used suggestions from Tim Biegeleisen and Akina.
After recalculating the indexes, a query is called to remove unnecessary rows.
UPDATE table AS t
SET index_value =
(SELECT new_index_value
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY index_value) - 1 AS new_index_value
FROM table WHERE user_id IN (
SELECT user_id FROM table WHERE some_value='some value'
GROUP BY user_id)
AND NOT some_value='some value'
ORDER BY ID)
WHERE ID = t.ID
)
WHERE user_id IN (
SELECT user_id
FROM table
WHERE some_value='some value'
GROUP BY user_id)
AND NOT some_value='some value';
| |
doc_23527281
|
assetPrefix: '/udlejning-sommerhus/',
async rewrites() {
return [
{
source: `/udlejning-sommerhus/_next/:path*`,
destination: '/_next/:path*'
}
]
}
The above code works fine. But when i make changes like mentioned below
basePath: '/udlejning-sommerhus',
assetPrefix: '/asset-path/',
async rewrites() {
return [
{
source: `/asset-path/_next/:path*`,
destination: '/_next/:path*'
}
]
}
It is showing error.
Note: These are in next.config.js
| |
doc_23527282
|
*
*OS: Bigsur 11.3.1
*Sublime text: 3.2.2
*Sublime text extension(package): Anaconda
*Python virtual environment management using Miniconda(Anaconda)
*Use autoenv per each workspace directory
When I open the workspace folder and work on it in Sublime text, I usually go to the directory via Terminal(using cd) and use subl . to open it. (If I moved to the directory, its virtual environment would be activated cuz I used autoenv mentioned above)
And In the package settings(User's custom setting) of Anaconda, I can set python_interpreter, so whenever I use a function like Go to definition of the Class of 3rd party library, it reflects its installed libraries and get me there. The setting looks like this: "python_interpreter": "/Users/chois/miniconda3/envs/MY_VIRTUAL_ENV_NAME/bin/python"
But the problem is, it is set with "python_interpreter": "/Users/chois/miniconda3/bin/python" as a default, which is a (base) interpreter, not a virtual environment of the directory. So whenever I worked on that workspace, I had to manually change it.
What I tried is something like "python_interpreter": "/Users/chois/miniconda3/envs/$VIRTUAL_ENV/bin/python", but the sublime text doesn't recognize the environment variable in the package setting.
How can I flexibly set python_interpreter as each working directory's virtual environment's interpreter path, say, "/Users/chois/miniconda3/envs/$CURRENT_DIRS_VIRTUAL_ENV_NAME/bin/python"?
| |
doc_23527283
|
A: How do you want to combine commit messages? I don't think there is a reasonable way.
If you want to combine just diffs then use git diff instead of git show:
git diff commit1 commit2
See the docs.
A: Ended up doing it like this:
git checkout -b tmp <commit0_sha>~
git cherry-pick <commit0_sha>
git cherry-pick --strategy=recursive -X theirs <commitn_sha>
git rebase -i `git merge-base tmp main`
git show
Would be amazing if there's a more terse way.
| |
doc_23527284
|
My first problem is that not all of my images is exact the same size, and they're not fitting in my bootstrap column. Often the picture is not wide enough, so it leaves alot of free space in the left and right side. Is it possible to crop/zoom in on the image automatically, so it fill out all the space all the time?
Another question I have is.. How do I link each picture to something?
A: To force your images to upsize to their container, you'll have to apply some CSS. Bootstrap's img-responsive class sets max-width to 100%, but that doesn't force upscaling.
<style>
.oversize {
width: 100%;
height: auto;
}
</style>
To link an image, wrap it in an anchor:
<a href="/some-page"><img src="/some-image.jpg" class="oversize" /></a>
| |
doc_23527285
|
I haven't make any changes on the site. Can the reason be in the cPanel?
A: You can run the following commands:
find ./ -type f | xargs chmod 644
find ./ -type d | xargs chmod 755
chmod -Rf 777 var
chmod -Rf 777 media
| |
doc_23527286
|
One of these is a function whose job is to exit printing an error message (the actual subroutine also does some other jobs, but they're not relevant here; no, I am not reinventing die()):
## subroutines.ph
sub errorDie
{
my ($errMsg) = @_;
## various other cleanup tasks here
die($errMsg);
}
1;
And, in pipeline.pl:
#!/usr/bin/perl
require 'subroutines.ph';
errorDie("foo")
Running the script above results in:
foo at subroutines.ph line 5.
Is it possible to have it instead report something like:
foo at pipelines.pl line 4.
So, instead of reporting the line the die() was found on, it should report the line of the original script where the errorDie subroutine was called from. I know I can do this by including the line in the $errMsg variable, but that is fragile and cumbersome. Can this be done automatically? Can a subroutine defined in an external file detect where it was called from?
A: There is caller , to do this:
https://perldoc.perl.org/functions/caller.html
my ($package, $filename, $line) = caller;
gives you the information you need.
However, as you are talking about debugging generally, you can get a complete backtrace from carp, as mentioned already.
A: That's the point of Carp's croak.
Pkg.pm:
package Pkg;
use Carp qw( croak );
sub some_func {
my ($cmd, $param) = @_;
$cmd eq 'encode' || $cmd eq 'decode'
or croak("Invalid command \"$cmd\"");
# ...
}
1;
a.pl:
use Pkg;
Pkg::some_func('foo', 'bar');
Output:
Invalid command "foo" at a.pl line 3.
| |
doc_23527287
|
parameters:
env
prodparam
nonprodparam
resources:
{
"type": "Microsoft.Resources/deployments",
"apiVersion": "2018-05-01",
"url": "[if(equals(parameters('env'),'prod'), parameters('prodparam'), parameters('nonprodparam'))]"
}
I see the url is always set to parameters('nonprodparam') even if parameters('env') = 'prod'. Is this if condition correct? Am I missing something?
A: Your if condition statement is correct, I tested it and got the correct result successfully.
You need to do the following steps to check where your problem is:
1. Check if your parameter definition is correct, especially as Stringfellow mentioned in the comment, to be case sensitive. It should be defined as follows.
2. Pay attention to whether to save after editing arm templates in the azure portal.
You can check the value of the parameter during the deployment process:
| |
doc_23527288
|
country.ts, which declares the values I'll read
export interface Country {
id: number;
name: string;
flag: string;
area: number;
population: number;
}
and contries.ts which is an array from where I'm going to read the data:
import {Country} from './country';
export const COUNTRIES: Country[] = [
{
id: 1,
name: 'Russia',
flag: 'f/f3/Flag_of_Russia.svg',
area: 17075200,
population: 146989754
},
{
id: 2,
name: 'France',
flag: 'c/c3/Flag_of_France.svg',
area: 640679,
population: 64979548
},
]
I need to populate countries.ts with firebase data, something like that:
import {Country} from './country';
import { AngularFirestore } from '@angular/fire/firestore';
export const COUNTRIES: Country[] = firestore.collection('users').valueChanges();
That way I could get the country.service.ts working and read the dynamic data to sort and paginate the datatable like the example of ng-bootstrap.
country.service.ts
import {Injectable, PipeTransform} from '@angular/core';
import {BehaviorSubject, Observable, of, Subject} from 'rxjs';
import {Country} from './country';
import {COUNTRIES} from './countries';
import {DecimalPipe} from '@angular/common';
import {debounceTime, delay, switchMap, tap} from 'rxjs/operators';
import {SortColumn, SortDirection} from './sortable.directive';
interface SearchResult {
countries: Country[];
total: number;
}
interface State {
page: number;
pageSize: number;
searchTerm: string;
sortColumn: SortColumn;
sortDirection: SortDirection;
}
const compare = (v1: string | number, v2: string | number) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
function sort(countries: Country[], column: SortColumn, direction: string): Country[] {
if (direction === '' || column === '') {
return countries;
} else {
return [...countries].sort((a, b) => {
const res = compare(a[column], b[column]);
return direction === 'asc' ? res : -res;
});
}
}
function matches(country: Country, term: string, pipe: PipeTransform) {
return country.name.toLowerCase().includes(term.toLowerCase())
|| pipe.transform(country.area).includes(term)
|| pipe.transform(country.population).includes(term);
}
@Injectable({providedIn: 'root'})
export class CountryService {
private _loading$ = new BehaviorSubject<boolean>(true);
private _search$ = new Subject<void>();
private _countries$ = new BehaviorSubject<Country[]>([]);
private _total$ = new BehaviorSubject<number>(0);
private _state: State = {
page: 1,
pageSize: 4,
searchTerm: '',
sortColumn: '',
sortDirection: ''
};
constructor(private pipe: DecimalPipe) {
this._search$.pipe(
tap(() => this._loading$.next(true)),
debounceTime(200),
switchMap(() => this._search()),
delay(200),
tap(() => this._loading$.next(false))
).subscribe(result => {
this._countries$.next(result.countries);
this._total$.next(result.total);
});
this._search$.next();
}
get countries$() { return this._countries$.asObservable(); }
get total$() { return this._total$.asObservable(); }
get loading$() { return this._loading$.asObservable(); }
get page() { return this._state.page; }
get pageSize() { return this._state.pageSize; }
get searchTerm() { return this._state.searchTerm; }
set page(page: number) { this._set({page}); }
set pageSize(pageSize: number) { this._set({pageSize}); }
set searchTerm(searchTerm: string) { this._set({searchTerm}); }
set sortColumn(sortColumn: SortColumn) { this._set({sortColumn}); }
set sortDirection(sortDirection: SortDirection) { this._set({sortDirection}); }
private _set(patch: Partial<State>) {
Object.assign(this._state, patch);
this._search$.next();
}
private _search(): Observable<SearchResult> {
const {sortColumn, sortDirection, pageSize, page, searchTerm} = this._state;
// 1. sort
let countries = sort(COUNTRIES, sortColumn, sortDirection);
// 2. filter
countries = countries.filter(country => matches(country, searchTerm, this.pipe));
const total = countries.length;
// 3. paginate
countries = countries.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize);
return of({countries, total});
}
}
Has someone already had to do this?
A: .valueChanges() returns an Observable<Country[]>, so you have to pipe your filtering and sorting logic within the _search() method.
And remember to unsubscribe as soon as you can (eg. when the table is destroyed).
private _search(): Observable<SearchResult> {
const {sortColumn, sortDirection, pageSize, page, searchTerm} = this._state;
return COUNTRIES.pipe(
map(countryList => sort(countryList, sortColumn, sortDirection)),
map(countryList => countryList.filter(country => matches(country, searchTerm, this.pipe))),
map(countryList => ({
total: countryList.length,
countries: countries.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize)
}))
);
}
| |
doc_23527289
|
contact = UserContact.find(:all,:select=>"distinct app_id,number",:conditions=>"number ='1234'")
arr=[]
contact.each do|c|
arr << c.app_id
end
name=User.find(:all,:conditions=>"id in(#{arr.join(',')}")
I takes two much time Can i do this using join
Thanks
A: You should do smth like this
User.find(:all, :joins => :user_contacts, :conditions => "user_contacts.number = '1234'")
user should have association. In user.rb should be:
has_many :user_contacts, :foreign_key => :app_id
But it is bad style to name column "app_id" it should be "user_id"(convention over configuration). Renamed it. After rename you can remove ", :foreign_key => :app_id"
A: Unfortunately you can NOT do "includes" and "select" in the same Active record Query. So this will not work...
contacts = UserContact.includes(:users).where("number = ?", '1234').select(:app_id, :number).uniq
BUT.
FIRST: app_id looks like it should be called "user_id"
SECOND: What version of Rails are you using? You might want to use the "pluck" method if you are using rails 3.2. Hence
user_ids = UserContact.where("number = ?", '1234').pluck(:app_id).uniq
users = User.where(:id => user_ids)
THIRD: in ruby instead of doing this:
arr=[]
contact.each do|c|
arr << c.app_id
end
do this:
arr = contact.inject([]) {|arr, c| arr << c.app_id}
FOURTH: As in all my examples your syntax is mostly Rails 2. I assume you are using rails 2? If so you might need to upgrade.
FIFTH: use plural variable names if you return more than one object. Hence
contact = UserContact.....
name=User.....
should be
contacts = UserContact.find.....
users = User.find.....
LAST:
User.joins(:user_contacts).where("user_contacts.number = ?", '1234')
might be good
| |
doc_23527290
|
translation_dict = {'AC': '2', 'AG': '3', 'AT': '4',
'CA': '5', 'CG': '6', 'CT': '7',
'GA': '8', 'GC': '9', 'GT': 'a',
'TA': 'b', 'TC': 'c', 'TG': 'd'}
I need some method for translating a huge numpy.char.array of the 2-byte strings to their corresponding 1-byte string mapping, as shown in the following example:
>>> input_array = numpy.char.array(['CA', 'CA', 'GC', 'TC', 'AT', 'GT', 'AG', 'CT'])
>>> output_array = some_method(input_arr)
>>> output_array
chararray(['5', '5', '9', 'c', '4', 'a', '3', '7'], dtype='S1')
I want to know if there is a fast numpy.char.array method for translating huge arrays of 2-byte strings; I am aware that I can use 'numpy.vectorize' with a function that explicitly looks up the 1-byte dictionary value for each 2-byte key, but this is relatively slow. I can't figure out to use numpy.chararray.translate, although it seems like that only works for 1-byte:1-byte mapping in any event.
A: For such search operations, NumPy has np.searchsorted, so allow me to suggest an approach with it -
def search_dic(dic, search_keys):
# Extract out keys and values
k = dic.keys()
v = dic.values()
# Use searchsorted to locate the indices
sidx = np.argsort(k)
idx = np.searchsorted(k,search_keys, sorter=sidx)
# Finally index and extract out the corresponding values
return np.take(v,sidx[idx])
Sample run -
In [46]: translation_dict = {'AC': '2', 'AG': '3', 'AT': '4',
...: 'CA': '5', 'CG': '6', 'CT': '7',
...: 'GA': '8', 'GC': '9', 'GT': 'a',
...: 'TA': 'b', 'TC': 'c', 'TG': 'd'}
In [47]: s = np.char.array(['CA', 'CA', 'GC', 'TC', 'AT', 'GT', 'AG', 'CT'])
In [48]: search_dic(translation_dict, s)
Out[48]:
array(['5', '5', '9', 'c', '4', 'a', '3', '7'],
dtype='|S1')
A: What about searching for the mininal elements and re-indexing:
uniq, inv_idx = np.unique(input_array, return_inverse=True)
np.array([translation_dict[u] for u in uniq])[inv_idx]
#array(['5', '5', '9', 'c', '4', 'a', '3', '7'],
# dtype='<U1')
Benchmark:
import time
x = np.random.choice(list(translation_dict.keys()),1000000)
t = time.time()
uniq, inv_idx = np.unique(x, return_inverse=True)
res = np.array([translation_dict[u] for u in uniq])[inv_idx]
print("Colonel Beauvel timing is:" + (time.time()-t))
t = time.time()
res = search_dic(translation_dict, x)
print("Divakar timimng is:" + str(time.time()-t))
#Colonel Beauvel timing is:0.32760000228881836
#Divakar timing is:0.10920000076293945
Divakar wins hands down, three times better!
A: Here is a slightly hackish but fast approach using a cheap "hash":
import numpy as np
from timeit import timeit
translation_dict = {'AC': '2', 'AG': '3', 'AT': '4',
'CA': '5', 'CG': '6', 'CT': '7',
'GA': '8', 'GC': '9', 'GT': 'a',
'TA': 'b', 'TC': 'c', 'TG': 'd'}
keys, values = map(np.char.array, zip(*translation_dict.items()))
N = 1000000
mock_data = keys[np.random.randint(0,12,(N,))]
def lookup(hash_fun, td, data):
keys, values = map(np.char.array, zip(*td.items()))
keys_ = hash_fun(keys)
assert len(set(keys_)) == len(keys)
data = hash_fun(data)
lookup = np.empty(max(keys_) + 1, values.dtype)
lookup[keys_] = values
return lookup[data].view(np.chararray)
def hash_12(table):
unit = {8:np.uint32, 4:np.uint16, 2:np.uint8}[table.dtype.itemsize]
lookup = table.view(np.ndarray).view(unit)
return (lookup[1::2]<<1) + lookup[::2]
def search_dic(dic, search_keys):
# Extract out keys and values
k = dic.keys()
v = dic.values()
# Use searchsorted to locate the indices
sidx = np.argsort(k)
idx = np.searchsorted(k, search_keys.view(np.ndarray), sorter=sidx)
# Finally index and extract out the corresponding values
return np.take(v,sidx[idx])
def uniq(translation_dict, input_array):
uniq, inv_idx = np.unique(input_array, return_inverse=True)
return np.char.array([translation_dict[u] for u in uniq])[inv_idx]
# correctness
print(np.all(lookup(hash_12, translation_dict, mock_data)
== search_dic(translation_dict, mock_data)))
print(np.all(lookup(hash_12, translation_dict, mock_data)
== uniq(translation_dict, mock_data)))
# performance
print('C_Beauvel {:9.6f} secs'.format(timeit(lambda: uniq(
translation_dict, mock_data), number=10)/10))
print('Divakar {:9.6f} secs'.format(timeit(lambda: search_dic(
translation_dict, mock_data), number=10)/10))
print('PP {:9.6f} secs'.format(timeit(lambda: lookup(
hash_12, translation_dict, mock_data), number=10)/10))
Prints:
True
True
C_Beauvel 0.622123 secs
Divakar 0.050903 secs
PP 0.011464 secs
| |
doc_23527291
|
*
*I have a class/method that generates SomeData every second.
I need to:
*collect this SomeData into Somewhere<SomeData> for 1 minute,
*after 1 minute take collection and prepare some ReportObject
*and emmit report via EmitterProcessor<ReportObject>.
How can I implement that using Flux?
A: You can use something like:
Flux<SomeData> data = //...
Flux<ReportObject> reports = data
// if you want 60 seconds windows
.window(Duration.ofMinutes(1))
// use a reduce operator to create a report
.flatMap(window -> window.reduce(..));
| |
doc_23527292
|
A: You could create a generic change event handler which sets a flag on change, and then assign all the controls' Change events to it.
This could probably be done pretty easily by looping through all of your controls onload.
A: You could loop through all controls but this would have to be recursive because a control can contain controls, e.g. (no null checks for brevity):
private void IterateOverControls( Control parent )
{
ProcessControl( parent );
foreach( Control control in parent.Controls )
IterateOverControls( control );
}
In ProcessControl you could hook up event handlers to handle OnEnter (to store the state) and OnLeave (to check the current state against the stored state). You'd need to unhook all the event handlers when disposing. Also, the code to store check the state would have to change for different control types, e.g. TextBox would be the Text property, but a radio button would be an index, etc. Obviously this becomes simpler if you can compare form state to your underlying data store state, in which case you can just make the comparison on each OnLeave event.
One thing also to consider is do you need to track real changes? For example, I have 2 radio buttons: A and B. I check B (a change), so the out button or whatever has its Enabled property changes. I then click on A (i.e. back to my original state). Do you need to revert the button at that point?
This is why you should look towards a model view controller approach :)
A: The easiest way to do this would be to simply use a variable on the form named something like "IsChanged." Set it false when the form is initially displayed, and set it true if they make any changes.
Alternately, you could record the values of everything when the form is displayed, and when they finish, check the current values against the old ones to see if anything changed.
A: If this is already nearly finished, and you need something quick it's probably going to be easier to just always assume that something has changed, then in your update logic afterwards (whatever it's doing) don't update stuff that is still the same.
As someone else mentioned, it's very possible for someone to change something, then change it back. What would you want to do in that case? You won't be able to maintain a proper dirty state of the form without a fair bit of additional work.. this is something that you need to plan for before you start, really.
| |
doc_23527293
|
the code from ActionScript is from 2011 so im not sure which version of box2d its using .
im using the latest .
any way this is what i have in action script :
var leftAxle:b2Body=world.CreateBody(leftAxleBodyDef);
leftAxle.CreateFixture(leftAxleFixture);
// this is the part i need to port , there is no SetPosition in the box2d 2.2+ version
leftAxle.SetPosition(new b2Vec2(carPosX/worldScale-axleContainerDistance/worldScale-axleContainerHeight/worldScale*Math.cos((90-axleAngle)*degreesToRadians),carPosY/worldScale+axleContainerDepth/worldScale+axleContainerHeight/worldScale*Math.sin((90-axleAngle)*degreesToRadians)));
basclly its box with Hypotenuse angle
A: Sorry, thought you were converting from C++ to AS3
A quick look at the code: https://github.com/cocos2d/cocos2d-x/blob/ac2c0469c71eaabff38f545ce956859627f2b7fc/external/Box2D/Dynamics/b2Body.cpp
It seems like SetPosition() is now SetTransform(const b2Vec2& position, float32 angle). This is because they're stocking the position and rotation as a b2Transform behind the scenes. Even the GetPosition() is just returning the position property of the b2Transform
| |
doc_23527294
|
Also, do sockets utilize the file.c alloc_fd to allocate the file descriptor or do they utilize some other function?
A: Yes, sys_close() is the entry point for closing all file descriptors, including sockets.
sys_close() calls filp_close(), which calls fput() on the struct file object. When the last reference to the struct file has been put, fput() calls the file object's .release() method, which for sockets, is the sock_close() function in net/socket.c.
The socket code uses get_unused_fd() and put_unused_fd() to acquire and release file descriptors.
| |
doc_23527295
|
I try to achieve this using scale transforms on this views so that while zooming scroll view up I scale this views down using formula 1 / zoomScale and changing their anchor points so that they stay at green border.
The issue is I don't get how to calculate target bounding rect for red views after all these manipulations so I could scroll to it using appropriate zoomScale.
Please see full demo project here
EDIT
Grey view may zoom out of scroll view borders (see last picture), the main thing is to fit green rectangle surrounded by red views (you may think of them as negative insets for green area) inside scroll view bounds, so we should actually calculate taking into account initial and end size of green rectangle, to which red views should be "pinned".
Essential methods
- (void)adjustScrollPositionAndZoomToFrame:(CGRect)frame
{
CGFloat viewWidth = frame.size.width;
CGFloat viewHeight = frame.size.height;
CGFloat scrollViewWidth = self.scrollView.frame.size.width;
CGFloat scrollViewHeight = self.scrollView.frame.size.height;
CGSize newSize = [self scaleSize:frame.size toHeight:scrollViewHeight];
if (newSize.width > scrollViewWidth) {
newSize = [self scaleSize:frame.size toWidth:scrollViewWidth];
}
CGFloat scaleFactor = newSize.height == scrollViewHeight
? scrollViewHeight / viewHeight
: scrollViewWidth / viewWidth;
[self scrollRect:frame toCenterInScrollView:self.scrollView animated:NO];
self.scrollView.zoomScale = scaleFactor;
}
Scaling
- (void)handleZoom:(CGFloat)zoom
{
NSArray *anchorPoints = @[[NSValue valueWithCGPoint:CGPointMake(1.0, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)]
];
for (UILabel *label in _labels) {
[self setViewAnchorPoint:label value:[anchorPoints[[_labels indexOfObject:label]] CGPointValue]];
label.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1 / zoom, 1 / zoom);
}
}
/**
* @see https://stackoverflow.com/a/9649399/3004003
* @param value See view.layer.anchorPoint
*/
- (void)setViewAnchorPoint:(UIView *)view value:(CGPoint)value
{
CGPoint newPoint = CGPointMake(view.bounds.size.width * value.x,
view.bounds.size.height * value.y);
CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x,
view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
CGPoint position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = value;
}
Initial scene before zoom:
What I have after zoom:
What I need after zoom:
A: I downloaded your project and found the following issues:
When you initialize zoomingView, you set the origin of its frame so that zoomingView is in the middle of the scrollView. When you then scale the scrollView, it does also scale the offsets to the origin, which had to be taken into account for the correct placement of the scaled zoomingView.
I think it is clearer if you set the origin to 0:
self.zoomingView = [[ZoomingView alloc] initWithFrame:CGRectMake(0, 0, kZoomingViewWidth, kZoomingViewHeight)];
After scaling the zoomingView you had to center it. This can be done e.g. by
self.scrollView.zoomScale = scaleFactor;
CGRect svb = self.scrollView.bounds;
CGRect zvf = self.zoomingView.frame;
self.scrollView.bounds = CGRectMake((zvf.size.width - svb.size.width)/2.0, (zvf.size.height - svb.size.height)/2.0, svb.size.width, svb.size.height);
Then the following function becomes very simple:
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
[self.zoomingView handleZoom:scrollView.zoomScale];
}
With these modifications, the scaled zoomingView is centered correctly.
However, the scaling factor is still wrong since the inner green rect is scaled to fill the available space. The reason is that one has to consider that 2 boxes of size 30 have to be visible additionally, i.e. the available space for scaling is smaller. This can be done e.g. by
CGFloat scaleFactor = newSize.height == scrollViewHeight
? (scrollViewHeight - 60.0) / viewHeight
: (scrollViewWidth - 60.0) / viewWidth;
Of course, the constants had to be replaced by variables later.
With these modifications, your code runs correctly for me.
One more thing: This excellent post discusses in detail scroll views.
A: What if change anchorPoints to values:
NSArray *anchorPoints = @[[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 1.0)]
];
So you will adjust your views to the edges of zooming view and get what you want:
| |
doc_23527296
|
<ul><strong>PageTitle</strong>
<li>Category A</li>
<li>Category B</li>
<li>Category C</li>
I have my query running successfully in LinQPad, but I can't make it work in MVC. Here is the code I am using in MVC.
public IEnumerable<wl> List()
{
IEnumerable<wl> wlTest;
using (LibEntities _libEntity = new LibEntities()) {
wlTest = (from p in table1
join c in table2 on p.PK equals c.FK
group p by new { c.title } into g
select new wl
{
TitleName = g.Key.title,
Category = from p in g
group p by g.cat_id into d
select new wl{d.Key.cat_id}
}).ToList();
return wlTest;
}
}
Here is wl class info:
public class wl
{
public string TitleName { get; set; }
public string Category { get; set; }
}
I keep getting
Cannot initialize type 'LibraryProject.Model.wl' with a collection initializer because it does not implement 'System.Collections.IEnumerable'.
Okay, here's a very similar query in LinqPad.
from f_a_p in Find_article_progs
join f_a in Find_articles on f_a_p.Prog_num equals f_a.DbProg
where f_a_p.Parent_id == 183
group f_a by new {f_a_p.Prog_title} into d
select new {
d.Key.Prog_title,
Links = from f_a in d
group f_a by new {f_a.DbTitle} into c
select new {
c.Key.DbTitle
}
}
Can anyone help me with this?
A: This is the problem:
select new wl{d.Key.cat_id}
It's not clear what you actually intended to do here (the meaningless type names really don't help) but you might want something like:
select new wl { CategoryId = d.Key.cat_id }
That's now an object initializer rather than a collection initializer.
It seems unlikely that you actually want new wl at all, mind you - given that you're already creating a wl. Likewise unless your Category property is actually a collection, you probably want to get a single entry from the group rather than all of a query's results.
If you could improve your naming and give more details about what you're trying to do (and your data hierarchy) we may be able to help you more.
(The query you've given won't with LINQPad either, by the way...)
A: in here don't type g.Key.title_name because g.Key is already your title name
TitleName = g.Key.title_name // wrong
TitleName = g.Key // correct
And when selecting your categories I think you want to do something like this:
Categories = (from c in g
where c.TitleName == g.Key
select c).ToList();
I don't know much about your entity, and your class names are killing me. So I can't give your more advice unless you provide me more information about your entities.
| |
doc_23527297
|
library(tidyverse)
library(lubridate)
date <- data.frame(date=seq(ymd('2018-01-01'),ymd('2018-02-28'), by = '1 day'))
group <- data.frame(group=c("A","B"))
subgroup <- data.frame(subgroup=c("C","D"))
DF <- merge(merge(date,group,by=NULL),subgroup,by=NULL)
DF$group_value <- apply(DF, 1, function(x) sample(8:12,1))
DF$subgroup_value <- apply(DF, 1, function(x) sample(1:5,1))
DF <- DF %>%
arrange(date,group,subgroup)
I now want to calculate the following:
for every given day t, group and subgroup combination calculate the
number of days until the (backward) cumsum of subgroup_value is equal
or greater than the group value of day t.
I know how to do that by using some for loops and some dplyr functionality, but this is just terrible slow:
for(i in seq(1,nrow(date),1)) {
for(j in seq(1,nrow(group),1)) {
for(k in seq(1,nrow(subgroup),1)) {
tmp <- DF %>%
filter(date<=date[i] & group == group[j] & subgroup == subgroup[k]) %>%
arrange(desc(date))
tmp$helper <- 1
tmp <- tmp %>%
mutate(
cs_helper = cumsum(helper),
cs_subgroup_value = cumsum(subgroup_value),
nr_days = case_when (
cs_subgroup_value >= group_value ~ cs_helper,
TRUE ~ NA_real_)
)
#this is the final result for date[i], group[j], subgroup[k]
value <- min(tmp[,"nr_days"], na.rm=T)
}
}
}
Example
head(DF,10)
date group subgroup group_value subgroup_value result
1 2018-01-01 A C 12 2 NA
2 2018-01-02 A C 11 4 NA
3 2018-01-03 A C 11 4 NA
4 2018-01-04 A C 9 5 2
5 2018-01-05 A C 12 5 3
6 2018-01-06 A C 10 3 3
7 2018-01-07 A C 12 5 3
8 2018-01-08 A C 8 1 3
9 2018-01-09 A C 12 4 4
10 2018-01-10 A C 9 1 4
So for row 10, I need to sum the last 4 values of subgroup to be greater or equal to 9.
I am sure that this code can be highly optimized by using some vectorized version but I am struggle to find a good starting point for that (As you can see from the code above, I am a newbie in R)
My question is: How would you approach this problem in order to vectorize it for speed optimisation?
Thanks!
Stephan
A: Here's an attempt, take a copy of each group/subgroups data frame, and cross join to the data. This is then filtered to only find the days before. This allows us for each day to calculate all of the cumulative sums
DF %>%
group_by(group, subgroup) %>%
mutate(day = row_number(), J = TRUE) %>%
nest() %>%
arrange(group, subgroup) %>%
mutate(data = map(data, function(d) {
inner_join(d, transmute(d, x = day, v = subgroup_value, J), by = "J") %>%
filter(day >= x) %>%
mutate(x = day - x + 1) %>%
arrange(day, x) %>%
group_by(date, group_value, date, subgroup_value) %>%
mutate(vv = cumsum(v),
vv = ifelse(vv >= group_value, vv, NA),
xx = ifelse(!is.na(vv), x, NA)) %>%
group_by(date, group_value, day, subgroup_value) %>%
summarise(x = min(xx, na.rm = TRUE), v = min(vv, na.rm = TRUE))
})) %>%
unnest()
| |
doc_23527298
|
*
*Having a CI server like Jenkins or Hudson
*Build jobs with Maven 3 and Java projects/artifacts
*Each time a build is performed at the end a SonarQube analysis will be performed
A situation that occur, but I have no control over is, that the SonarQube server is not available. The underlying cause isn't relevant for the question. If the build tries to perform the SonarQube analysis via Maven sonar:sonar or the Jenkins SonarQube plugin as post-step the SonarQube analysis causes the build to crash or have the status failed. In my eyes the build is OK and SonarQube isn't the decisive factor.
Is there any (maven/jenkins)-plugin or possibility to avoid the analysis, if the SonarQube server isn't available? The SonarQube analysis of the build shall only perform if the SonarQube server is online and can perform an analysis.
A: There is no such feature for the moment, but maybe Jenkins has some built-in feature to run a post-job only if a specific condition is met? And in this case, you could just run a "curl" like command to check the availability of the SonarQube server to serve as a condition for the post-job to be executed?
| |
doc_23527299
|
I have been using the following, but these also changes some other CDN URLs such as FontAwesome and others that I don't want. So just need something a bit more specific
(https?://)(.*?)(/.*)
URLS TO CAPTURE
https://lirp-cdn.multiscreensite.com/624dfs85te/dms3rep/multi/opt/logo-400w.jpg
https://lirp-cdn.multiscreensite.com/624dfs85te/dms3rep/multi/opt/home04-96006935-1920w.jpg
https://irp-cdn.multiscreensite.com/624dfs85te/dms3rep/multi/home02.jpg
DESIRED RESULT
https://mywebsite.com/logo-400w.jpg
https://mywebsite.com/home04-96006935-1920w.jpg
https://mywebsite.com/home02.jpg
A: Incorporate the domain of the CDN
You must remove the ? from the *? because you want all the directories in group 2, only the last / in group 3.
(https?://)(l?irp-cdn.multiscreensite.com.*)(/.*)
A: Use
(https?://)l?irp-cdn\.multiscreensite\.com(?:/.*)?(/.*)
Replace with:
$1mywebsite.com$2
See proof
EXPLANATION:
NODE EXPLANATION
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
http 'http'
--------------------------------------------------------------------------------
s? 's' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
:// '://'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
l? 'l' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
irp-cdn 'irp-cdn'
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
multiscreensite 'multiscreensite'
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
com 'com'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of \2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.