id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_2200
|
window.onload = function () {
var canvas=document.getElementById("can");
var img=canvas.toDataURL("image/png");
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
button.onclick = function () {
window.location.href = img.replace("image/png", "image/octet-stream");
window.location.href = prev;
};
};
HTML:
<canvas id="can" width="500" height="200"></canvas><br />
<input type="button" value="Done" id="saveImage">
I am able to display the image on div from canvas but when i try to download it using above javascript function it downloads blank image. I want to know how can i get the picture drawn from the canvas.
A: Try looking here: http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/
The biggest problem you're likely to face is that you can only save the image on the same server as the page which has the canvas element. You'll then have to retrieve that saved image (either server or client side) and prompt the user to save it.
EDIT:
Maybe this would be better, though you need a little bit of server-side code:
http://greenethumb.com/article/1429/user-friendly-image-saving-from-the-canvas/
| |
doc_2201
|
FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
Request->SetURL(apiBaseUrl + "/api/url");
Request->SetVerb("POST");
Request->SetHeader("Authorization", "Bearer " + GetCurrentToken());
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString("JSON_BOBY");
Request->OnProcessRequestComplete().BindUObject(this, &AClass::OnResponse);
Request->ProcessRequest();
But I created a static function to be called from the BP. But when I call another function from this one, the api receives the request but I don't receive the answer for an unknown reason.
void AClass::StaticFunction(AClass* class, FString string01, float amount, FString string02) {
class->Orders(string01, amount, string02);
}
void AClass::Orders(FString string01, float amount, FString string02) {
FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
Request->SetURL(apiBaseUrl + "/api/url");
Request->SetVerb("POST");
Request->SetHeader("Authorization", "Bearer " + GetCurrentToken());
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString("JSON_BOBY");
Request->OnProcessRequestComplete().BindUObject(this, &AClass::OnResponse);
Request->ProcessRequest();
}
void AClass::OnResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!ResponseIsValid(Response, bWasSuccessful)) return;
TSharedPtr<FJsonObject> ResponseObj;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
FJsonSerializer::Deserialize(Reader, ResponseObj);
UE_LOG(LogTemp, Display, TEXT("Response %s"), *Response->GetContentAsString());
}
Thank you in advance if you have a lead or an answer.
| |
doc_2202
|
The problem I am having is that I am trying to reuse this app for a different set of images (the app is basically a template). This includes the splash page. I have done everything I can think of to replace the splash page image including, of course, modifying the view in Interface Builder and loading a different image. However, the previous splash page image still appears briefly when I run the app in simulator.
I have also tried: reviewing the .xib file text; removing the build directory from the app.
Looking for any suggestions on how to make this old image go away.
Edit: I have also deleted the 'old' image from the project. So it seems as if it is still being stored somewhere. Have also deleted the icons from Simulator.
A: isn't it the Default.png ?
| |
doc_2203
|
The numpy.ma module comes with a specific implementation of most ufuncs. Unary and binary functions that have a validity domain (such as log or divide) return the masked constant whenever the input is masked or falls outside the validity domain: e.g.:
ma.log([-1, 0, 1, 2])
masked_array(data = [-- -- 0.0 0.69314718056],
mask = [ True True False False],
fill_value = 1e+20)
I have the problem that for my calculations I need to know where those invalid operations were produced. Concretely I would like this instead:
ma.log([-1, 0, 1, 2])
masked_array(data = [np.nan -- 0.0 0.69314718056],
mask = [ True True False False],
fill_value = 1e+20)
At the risk of this question being conversational my main question is:
What is a good solution to get this masked_array where the computed invalid values (those "fixed" by fix_invalid, like np.nan and np.inf) are not turned into (and conflated with) masked values?
My current solution would be to compute the function on the masked_array.data and then reconstruct the masked array with the original mask. However, I am writing an application which maps arbitrary functions from the user onto many different arrays, some of which are masked and some aren't, and I am looking to avoid a special handler just for masked arrays. Furthermore, these arrays have a distinction between MISSING, NaN, and Inf that is important so I can't just use an array with np.nans instead of masked values.
Additionally, if anyone has any perspective on why this behavior exists I would like to know. It seems strange to have this in the same operation because the validity of results of an operation on unmasked values are really the responsibility of the user, who can choose to then "clean up" by using the fix_invalid function.
Furthermore, if anyone knows anything about the progress of missing values in numpy please share as the oldest posts are from 2011-2012 where there was a debate that never resulted in anything.
EDIT: 2017-10-30
To add to hpaulj's answer; the definition of the log function with a modified domain has side effects on the behavior of the log in the numpy namespace.
In [1]: import numpy as np
In [2]: np.log(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
/home/salotz/anaconda3/bin/ipython:1: RuntimeWarning: divide by zero encountered in log
#!/home/salotz/anaconda3/bin/python
/home/salotz/anaconda3/bin/ipython:1: RuntimeWarning: invalid value encountered in log
#!/home/salotz/anaconda3/bin/python
Out[2]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
In [3]: mylog = np.ma.core._MaskedUnaryOperation(np.core.umath.log)
In [4]: np.log(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
/home/salotz/anaconda3/bin/ipython:1: RuntimeWarning: divide by zero encountered in log
#!/home/salotz/anaconda3/bin/python
/home/salotz/anaconda3/bin/ipython:1: RuntimeWarning: invalid value encountered in log
#!/home/salotz/anaconda3/bin/python
Out[4]:
masked_array(data = [-- -inf 0.0 0.6931471805599453],
mask = [ True False False False],
fill_value = 1e+20)
np.log now has the same behavior as mylog, but np.ma.log is unchanged:
In [5]: np.ma.log(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
Out[5]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
Is there a way to avoid this?
Using Python 3.6.2 :: Anaconda custom (64-bit) and numpy 1.12.1
A: Just clarify what appears to be going on here
np.ma.log runs np.log on the argument, but it traps the Warnings:
In [26]: np.log([-1,0,1,2])
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log
#!/usr/bin/python3
/usr/local/bin/ipython3:1: RuntimeWarning: invalid value encountered in log
#!/usr/bin/python3
Out[26]: array([ nan, -inf, 0. , 0.69314718])
It masks the nan and -inf values. And apparently copies the original values into these data slots:
In [27]: np.ma.log([-1,0,1,2])
Out[27]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
In [28]: _.data
Out[28]: array([-1. , 0. , 0. , 0.69314718])
(running in Py3; numpy version 1.13.1)
This masking behavior is not unique to ma.log. It is determined by its class
In [41]: type(np.ma.log)
Out[41]: numpy.ma.core._MaskedUnaryOperation
In np.ma.core it is defined with fill and domain attributes:
log = _MaskedUnaryOperation(umath.log, 1.0,
_DomainGreater(0.0))
So the valid domain (unmasked) is >0:
In [47]: np.ma.log.domain([-1,0,1,2])
Out[47]: array([ True, True, False, False], dtype=bool)
that domain mask is or-ed with
In [54]: ~np.isfinite(np.log([-1,0,1,2]))
...
Out[54]: array([ True, True, False, False], dtype=bool)
which has the same values.
Looks like I could define a custom log that does not add its own domain masking:
In [58]: mylog = np.ma.core._MaskedUnaryOperation(np.core.umath.log)
In [59]: mylog([-1,0,1,2])
Out[59]:
masked_array(data = [ nan -inf 0. 0.69314718],
mask = False,
fill_value = 1e+20)
In [63]: np.ma.masked_array([-1,0,1,2],[1,0,0,0])
Out[63]:
masked_array(data = [-- 0 1 2],
mask = [ True False False False],
fill_value = 999999)
In [64]: np.ma.log(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
Out[64]:
masked_array(data = [-- -- 0.0 0.6931471805599453],
mask = [ True True False False],
fill_value = 1e+20)
In [65]: mylog(np.ma.masked_array([-1,0,1,2],[1,0,0,0]))
Out[65]:
masked_array(data = [-- -inf 0.0 0.6931471805599453],
mask = [ True False False False],
fill_value = 1e+20)
| |
doc_2204
|
I want to create a component to add it on all my proyects, just for fun.
thanks
UPDATE: I made a simple component, thanks to ZaBlanc
<?xml version="1.0" encoding="utf-8"?>
<mx:UIComponent xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Metadata>
[Event(name="success", type="flash.events.Event")]
</mx:Metadata>
<mx:Script>
<![CDATA[
// up-up-down-down-left-right-left-right-B-A
public static const KONAMI_CODE:String = "UUDDLRLRBA";
// signature
private var signatureKeySequence:String = "";
private function init():void{
systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function onKeyDown(event:KeyboardEvent):void{
var keyCode:int = event.keyCode;
switch (keyCode) {
case Keyboard.UP:
signatureKeySequence += "U";
break;
case Keyboard.DOWN:
signatureKeySequence += "D";
break;
case Keyboard.LEFT:
signatureKeySequence += "L";
break;
case Keyboard.RIGHT:
signatureKeySequence += "R";
break;
case 66: //Keyboard.B only for AIR :/
signatureKeySequence += "B";
break;
case 65: //Keyboard.A only for AIR too :(
signatureKeySequence += "A";
break;
default:
signatureKeySequence = "";
break;
}
// crop sequence
signatureKeySequence = signatureKeySequence.substr(0, KONAMI_CODE.length);
// check for konami code
if (signatureKeySequence == KONAMI_CODE) {
dispatchEvent(new Event("success"));
signatureKeySequence = "";
}
}
]]>
</mx:Script>
</mx:UIComponent>
to test it
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:konamicode="konamicode.*">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
]]>
</mx:Script>
<konamicode:KonamiCodeCatch success="Alert.show('+30 lives!!!')" />
</mx:Application>
A: You may use Casalib. There are classes, Key and KeyCombo. You may listen for KeyComboEvent.SEQUENCE.
Working sample:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import org.casalib.events.KeyComboEvent;
import org.casalib.ui.Key;
import org.casalib.ui.KeyCombo;
import org.casalib.util.StageReference;
private const KONAMI_CODE:KeyCombo = new KeyCombo([Keyboard.UP,Keyboard.UP,Keyboard.DOWN,Keyboard.DOWN,Keyboard.LEFT,Keyboard.RIGHT,Keyboard.LEFT,Keyboard.RIGHT,("B").charCodeAt(),("A").charCodeAt()]);
private function init():void {
StageReference.setStage(this.systemManager.stage);
Key.getInstance().addKeyCombo(KONAMI_CODE);
Key.getInstance().addEventListener(KeyComboEvent.SEQUENCE,onKonami);
}
private function onKonami(evt:KeyComboEvent):void {
if (evt.keyCombo == KONAMI_CODE){
Alert.show("You know Konami code?","WOW");
}
}
]]>
</mx:Script>
</mx:Application>
A: A state machine is fun to write, but in this case I'd go with a signature pattern. Depending on where you want to put the handler (on the stage of the component), here's some code that should work, though you can probably tighten it (and of course customize it to your specific need):
// up-up-down-down-left-right-left-right-B-A
public static const KONAMI_CODE:String = "UUDDLRLRBA";
// signature
private var signatureKeySequence:String = "";
private function onKeyDown(event:KeyboardEvent):void {
var keyCode:int = event.keyCode;
switch (keyCode) {
case Keyboard.UP:
signatureKeySequence += "U";
break;
case Keyboard.DOWN:
signatureKeySequence += "D";
break;
case Keyboard.LEFT:
signatureKeySequence += "L";
break;
case Keyboard.RIGHT:
signatureKeySequence += "R";
break;
case Keyboard.B:
signatureKeySequence += "B";
break;
case Keyboard.A:
signatureKeySequence += "A";
break;
default:
signatureKeySequence = "";
break;
}
// crop sequence
signatureKeySequence = signatureKeySequence.substr(0, KONAMI_CODE.length);
// check for konami code
if (signatureKeySequence == KONAMI_CODE) {
// 30 lives!
}
}
A: var unlockCode:Array = new Array(38,38,40,40,37,39,37,39,66,65,13);
var keyPressArray:Array = new Array();
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkUnlockCode);
function checkUnlockCode(e:KeyboardEvent):void {
if (keyPressArray.length >= unlockCode.length) {
keyPressArray.splice(0,1);
keyPressArray.push(e.keyCode.toString());
} else {
keyPressArray.push(e.keyCode.toString());
}
trace(keyPressArray);
if (keyPressArray.toString() == unlockCode.toString()) {
trace(unlockCode);
}
}
| |
doc_2205
|
Here iam including the code snippet of the data
<td colspan=2>
<input type="submit" value="Login" class="submit3" onclick="return checknull()" tabindex="1">
<input type="button" value="Reset" class="submit3" onclick="call_reset()" tabindex="1">
<input type="button" value="Forgot Password ?" class="submit3" onclick="call_fgpwd()" tabindex="1">
</td>
But when iam selecting with jquery using the class selector $('.submit3') it only returning the first input submit button and it is ignoring the remaining 2.
Here original javascript is here
document.getElementsByClassName("submit3")[0].value = "something";
document.getElementsByClassName("submit3")[1].name = "something";
document.getElementsByClassName("submit3")[2].name = "something";
document.getElementsByClassName("submit3")[2].value = "something";
Now i tried converting it into jquery as
$('.submit3')[0].val("Something New")
Which resulted in error Uncaught TypeError: $(...)[0].val is not a function
Also in the console of chrome browser(Latest Version),when i run $('submit3')
the output is
<input type="submit" value="Login" class="submit3" onclick="return checknull()" tabindex="1">
A: In your code $('.submit3')[0] returns the dom object, you can't use jQuery val() method with it. You can set value property to update the value.
$('.submit3')[0].value = "Something New"
or use eq() method to get jQuery object using index
$('.submit3').eq(0).val("Something New")
// or $('.submit3:eq(0)').val("Something New")
A: When you convert a jQuery collection $('.submit3') to $('.submit3')[0] - raw DOM element [HTMLElement], the jQuery properties don't work. Use plain JS properties.
$( ".foo" )[ 0 ] // is equivalent to document.getElementsByClassName( "foo" )[0]
Use
$('.submit3')[0].value = ...
or alternatively
$('.submit3').get(0).value = ..
| |
doc_2206
|
I'm trying to write some tests, and I want to test that when I press enter in an input, the form does indeed post back. However, I can't get it to simulate this.
No matter which method I choose, the keypress event is being triggered--event listeners see it--but the form isn't being submitted.
jsFiddle link:
Html
<!-- returns an error on submit, but that's fine...
we're only seeing if we can get a submit to happen -->
<form action="POST">
<input id="myinput" type='text' value="foo" />
</form>
<div id="output"></div>
Javascript
$(function () {
var $input = $("#myinput");
$input.on("keypress", function (evt) {
$("#output").append("Typed: " + evt.keyCode + ", but the form didn't submit.<br>");
});
$("form").on("submit", function () { alert("The form submitted!"); } );
// try jQuery event
var e = $.Event("keypress", {
keyCode: 13
});
$input.trigger(e);
// try vanilla javascript
var input = $input[0];
e = new Event("keypress");
e.keyCode = 13;
e.target = input;
input.dispatchEvent(e);
e = document.createEvent("HTMLEvents");
e.initEvent("keypress", true, true);
e.keyCode = 13;
e.target = input;
input.dispatchEvent(e);
});
Is it possible to simulate an actual keypress like this?
If you focus on the text box (in jsFiddle) and physically press enter, the page will post back and will return something like:
This is what I'm trying to achieve, only in code.
Here's why:
$("input").on("keypress", function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
I ran into this in my code base, and I want to test that this sort of thing doesn't happen again.
A: To simulate the keypress event on the input we have to use the KeyboardEvent constructor and pass the event to the input's dispatchEvent method.
const event = new KeyboardEvent("keypress", {
view: window,
keyCode: 13,
bubbles: true,
cancelable: true
});
document.querySelector("input").dispatchEvent(event);
<!-- returns an error on submit, but that's fine...
we're only seeing if we can get a submit to happen -->
<form action="POST">
<input id="myinput" type='text' value="foo" />
</form>
<div id="output"></div>
You can see more information on mdn documentation on triggering and creating events
| |
doc_2207
|
(((?=.*\\d{2,20})(?=.*[a-z]{2,20})(?=.*[A-Z]{3,20})(?=.*[@#$%!@@%&*?_~,-]{2,20})).{9,20}[^<>'\"])
Basically what I want is that it contains all above given characters in password. But it needs those characters in sequence e.g
it validates 23aaAAA@!, but it does not validatea2@!AAAa.
A: Simply add nested capturing groups to keep the chars validation not strictly as a sequence. The regex can be also simplified as follow (without extra groups):
(?=(?:.*[0-9]){2,20})
(?=(?:.*[a-z]){2,20})
(?=(?:.*[A-Z]){3,20})
(?=(?:.*[@#$%!&*?_~,-]){2,20})
.{9,20}
[^<>'\"] # This matches also the newline char, i don't think you really want this...
In java use it as follows to match the :
String regex = "(?=(?:.*[0-9]){2,20})(?=(?:.*[a-z]){2,20})(?=(?:.*[A-Z]){3,20})(?=(?:.*[@#$%!&*?_~,-]){2,20}).{9,20}[^<>'\"]";
String password = "23aaA@AA!@X"; // This have to be 10 chars long at least, no newline
if (password.matches(regex))
System.out.println("Success");
else
System.out.println("Failure");
The regex requires a password with (all not strictly in sequence):
*
*(?=(?:.*[0-9]){2,20}): 2 numbers
*(?=(?:.*[a-z]){2,20}): 3 lowercase lettes
*(?=(?:.*[A-Z]){3,20}): 3 uppercase letters
*(?=(?:.*[@#$%!&*?_~,-]){2,20}): 2 of the symbols in the chars group
*.{9,20}: Min length of 9 and max of 20
*[^<>'\"]: One char that is not in (<,>,',") (NOTE: this matches also the newline)
So the min/max is actually 10/21 but the last statemente matches also the newline, so in the online regex demo, the visible chars will be between 9 and 20.
Regex online demo here
A: I would not try to build a single regexp, because nobody will ever be able to read nor change this expression ever again. It's to hard to understand.
"a2@!AAAa" will never validate because it needs 2 digits.
If you want a password, that contains a minmuum and maximum number of chars from a group. simply count them.
public class Constraint {
private Pattern pattern;
public String regexp = "";
public int mincount=2;
public int maxcount=6;
public Constraint(String regexp, int mincount, int maxcount) {
this.mincount=mincount;
this.maxcount=maxcount;
pattern = Pattern.compile(regexp);
}
public boolean fit(String str)
{
int count = str.length() - pattern.matcher(str).replaceAll("").length();
return count >= mincount && count <= maxcount;
}
@Override
public String toString() {
return pattern.toString();
}
}
public class Test {
static Constraint[] constraints = new Constraint[] {
new Constraint("[a-z]",2,20),
new Constraint("[A-Z]",2,20),
new Constraint("\\d",2,20),
new Constraint("["+Pattern.quote("@#$%!@@%&*?_~,-")+"]",2,20),
new Constraint("[<>'\\\"]",0,0)
};
public static boolean checkit(String pwd)
{
boolean ok=true;
for (Constraint constraint:constraints)
{
if (constraint.fit(pwd)==false)
{
System.out.println("match failed for constraint "+constraint);
ok=false;
}
}
return ok;
}
public static void main(String[] args) {
checkit("23aaAAA@!");
checkit("a2@!AAAa");
}
}
| |
doc_2208
|
*
*Go into External Data -> New Data Source -> From Database -> From SQL Server
*Specify to link the data source
*Select a data source from Machine Data Source
This results in the error
"ODBC -- call failed.
Specified driver could not be loaded due to system error 126: The specified module could not be found (MySQL ODBC 8.0 Unicode Driver, C:\Program FIles\MySQL\Connector ODBC 8.0\myodbc8w.dll). (#160)"
This prevents me from importing data from the MySQL Server into a Microsoft Access database.
A: The version of Office was 64 bit whereas the ODBC driver was 32 bit.
Downloading and installing the 64bit driver from https://dev.mysql.com/downloads/connector/odbc/ fixed the issue
| |
doc_2209
|
In My controller:-
$this->session->set_flashdata('login_error','Your username or password is incorrect.');
redirect(base_url().'admin/login');
In My view
echo '<span>'.$this->session->flashdata('login_error').'</span>';
In Chrome and ie i'm getting blank span whereas in firefox it is displaying flash data.
There are similar questions on the stack but i could not find any answer which are working.
A: I solved my problem.There was some issue with ie and chrome cookie management.
I change the 'sess_cookie_name' in config from 'ci_session' to 'cisession'
and sess_expiration from 7200 to 84200 and it got fixed.
A: I was able to solve the problem by setting:
$config['sess_use_database']= FALSE;
$config['sess_cookie_name']= 'cisession';
$config['sess_expiration'] = 84200;
| |
doc_2210
|
The data in the XML is shown like this:
<is:Person>
<is:PersonId/>
<is:NationalIdentificationNumber/>
<is:Name>
<dg:Title/>
What I need is it to show up like this:
is:Person/is:PersonID
is:Person/is:NationalIdentificationNumber
is:Person/is:Name/
is:Person/is:Name/dg:Title
...
How do I do this?
A: The data in your question is not well-formed XML. It lacks closing tags.
Once the closing tags are added, you can use xmlstarlet on it to get the structure:
$ xmlstarlet el [input file]
The output will be almost what you have shown in your question:
is:Person
is:Person/is:PersonId
is:Person/is:NationalIdentificationNumber
is:Person/is:Name
is:Person/is:Name/dg:Title
It will complain that is and dg are undefined namespaces. XML does not require the use of namespaces, and when namespaces are not used, an XML validator should accept colons in element names. However, I do not know of a flag that will make xmlstarlet not complain about this.
| |
doc_2211
|
Class Title(models.Model):
title = models.CharField(max_length=256)
slug = models.SlugField()
class Issue(models.Model):
title = models.ForeignKey(Title)
number = models.IntegerField(help_text="Do not include the '#'.")
slug = models.SlugField()
admin.py:
class IssueAdmin (admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Issue, IssueAdmin)
What the Issue prepopulates is the ID of the foreign key, but I suppose I would need it to preopulate the slug of the foreign key. How would I go about doing this? I am using Django 1.3. I have checked other threads, but they seem to refer to version of Django a few years older that don't work anymore.
I need the Titles to display the list of issues. So far, it works. And you can click on the link to the issue to see what the issue displays.
I feel as if reworking the Title to abstract classes the way Skidoosh will not allow me to view subsets of objects....
A: If you check the docs (http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields) it does state that you can't reference a foreign key field.
Looking at you design would this not work better:
class BaseModel(models.Model):
title = models.CharField(max_length=256)
slug = models.SlugField()
class Issue(BaseModel):
number = models.IntegerField(help_text="Do not include the '#'.")
class ComicBookSeries(BaseModel):
issues = models.ForeignKey(Issue)
You need to declare the classes in that order!
Hope that helps!
| |
doc_2212
|
I hope it makes sense. I basically want to check the filetype of an uploaded file and then alter the template accordingly.
The code that I am thinking of implementing is something like this but I am kind of confused
models.py
class ScribbleMedia(models.Model):
media = models.FileField(upload_to=get_file_path)
typecheck=find_typecheck
def __unicode__(self):
return self.media
but I don't know where to write this function
def find_typecheck(instance, filename):
label=filename
ext = filename.split('.')[-1]
if ext == 'jpeg':
a=1
else:
a=2
return a
in html template I should be able to do this
{% if ScribbleMedia.typecheck ==1 %}
do something
{% else %}
do something else
{% endif %}
A: You can put that method in your model class and use that in template to get the type of file. You can call this method using the instance of ScribbleMedia.
e.g.
class ScribbleMedia(models.Model):
media = models.FileField(upload_to=get_file_path)
def __unicode__(self):
return self.media
def find_typecheck(self):
filename = self.media.name
try:
ext = filename.split('.')[-1]
if ext == 'jpeg':
a=1
else:
a=2
except Exception:
a=-1 #couldn't determine
return a
In template:
{% if sc_media_obj.find_typecheck ==1 %}
do something
{% else %}
do something else
{% endif %}
On side note: Checking for just file extensions may not be sufficient.
| |
doc_2213
|
date <- c("2012-05-06", "2013-07-09", "2007-01-03")
word_count <- c("17", "2", "390")
df1 <- data.frame(date, word_count)
I also have a separate dataframe with total word counts for every date and then a series of other dates as well. It looks like this:
date <- c("2012-05-06", "2013-07-09", "2007-01-03", "2004-11-03", "1994-12-03")
word_total <- c("17000", "20", "39037", "39558", "58607")
df2 <- data.frame(date, word_count)
I now want to add another column to df1 that incorporates the totals for the dates that are in df2 but excludes data for any dates that are not in df1. I also want to transform the dataframe so that there is another column dividing word_total by word_count.
So the output would look like this:
date <- c("2012-05-06", "2013-07-09", "2007-01-03")
word_count <- c("17", "2", "390")
word_total <- c("17000", "20", "39037")
word_percentage <- c("0.001", "0.1", "0.00999")
df2 <- data.frame(date, word_count, word_total, word_percentage)`
I know how to use transform to get word_percentage once I have word_total loaded in but I have no idea how to add in relevant column data from word_total. I have tried using merge and intersect to no avail. Any ideas?
Thank you in advance for your help!
A: If the columns are numeric, then just do a merge and then create the column by dividing
transform(merge(df1, df2, by = c('date')),
word_percentage = round(word_count/word_total, 3))
Or use match
df1$word_percentage <- df1$word_count/df2$word_total[match(df1$date, df2$date)]
data
df1$word_count <- as.integer(as.character(df1$word_count))
df2$word_total <- as.integer(as.character(df2$word_total))
| |
doc_2214
|
package com.example.soundrecordingexample2;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static final int RECORDER_BPP = 16;
private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
private final int RECORDER_SAMPLERATE = 44100;
private final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord recorder = null;
private int bufferSize = 0;
private Thread recordingThread = null;
private boolean isRecording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setButtonHandlers();
enableButtons(false);
bufferSize = AudioRecord.getMinBufferSize(44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
Log.d( String.valueOf(bufferSize), "nadeeBufferaaaaaaaaaaaaaaaa");
}
private void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}
private void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnStop,isRecording);
}
private String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
}
private String getTempFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
File tempFile = new File(filepath,AUDIO_RECORDER_TEMP_FILE);
if(tempFile.exists())
tempFile.delete();
return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
}
private void startRecording(){
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
int i = recorder.getState();
Log.e(String.valueOf(i), "recorder");
if(i==1)
{
recorder.startRecording();
Log.d("aaa"," equal 1");
}
else
{
Log.d("hhhh","not equal 1");
}
isRecording = true;
recordingThread = new Thread(new Runnable() {
@Override
public void run() {
writeAudioDataToFile();
}
},"AudioRecorder Thread");
recordingThread.start();
}
private void writeAudioDataToFile(){
byte data[] = new byte[bufferSize];
String filename = getTempFilename();
FileOutputStream os = null;
try {
os = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int read = 0;
if(null != os){
while(isRecording){
read = recorder.read(data, 0, bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read){
try {
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording(){
if(null != recorder){
isRecording = false;
int i = recorder.getState();
if(i==1)
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
copyWaveFile(getTempFilename(),getFilename());
deleteTempFile();
}
private void deleteTempFile() {
File file = new File(getTempFilename());
file.delete();
}
private void copyWaveFile(String inFilename,String outFilename){
FileInputStream in = null;
FileOutputStream out = null;
long totalAudioLen = 0;
long totalDataLen = totalAudioLen + 36;
long longSampleRate = RECORDER_SAMPLERATE;
int channels = 2;
long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;
byte[] data = new byte[bufferSize];
try {
in = new FileInputStream(inFilename);
out = new FileOutputStream(outFilename);
totalAudioLen = in.getChannel().size();
totalDataLen = totalAudioLen + 36;
AppLog.logString("File size: " + totalDataLen);
WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate);
while(in.read(data) != -1){
out.write(data);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void WriteWaveFileHeader(
FileOutputStream out, long totalAudioLen,
long totalDataLen, long longSampleRate, int channels,
long byteRate) throws IOException {
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) (2 * 16 / 8); // block align
header[33] = 0;
header[34] = RECORDER_BPP; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalAudioLen & 0xff);
header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
out.write(header, 0, 44);
}
private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop:{
AppLog.logString("Start Recording");
enableButtons(false);
stopRecording();
break;
}
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
A: You can do it by dividing the file size by the length of the audio in seconds, for instance, from a random AAC encoded M4A in my library:
File Size 5MB
Length 183 sec
Which gives: 40000000 (5MB)/183= 218579.234973 bits/sec or ~218kbps
Actual Bitrate: 200kbps
Since most audio files have a known set of valid bitrate levels, you can use that to step the bit rate to the appropriate level for display.
| |
doc_2215
|
I make this code :
interpreter = tf.lite.Interpreter(model_save)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.resize_tensor_input(input_details[0]['index'], ((len(X_test)), 180,180, 3))
interpreter.resize_tensor_input(output_details[0]['index'], (len(X_test), 4))
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.set_tensor(input_details[0]['index'], X_test)
interpreter.invoke()
loss, accuracy = interpreter.evaluate(X_test)
But, show me the error:
'Interpreter' object has no attribute 'evaluate'
After this I tried:
loss, accuracy = interpreter.evaluate_tflite(X_test)
But apparently this just it works for Model Makers model.
So now i just don't know how to preceed.
A: If your tflite model has a signature, then you can leverage the signature, see the guide.
If the model doesn't have signatures, then you can see what are the outputs like this
output_details = interpreter.get_output_details()
# Assuming you have 2 outputs
output_1 = interpreter.get_tensor(output_details[0]['index'])
output_2 = interpreter.get_tensor(output_details[1]['index'])
The signature is the suggested way, and is safer for output reordering issues.
| |
doc_2216
|
Page 1
<script type="text/javascript" src="jscript.js">
<input type="button" value="change" onClick="changeAttr()">
Page 2
<script type="text/javascript" src="jscript.js">
<input type="text" value="Hello" id="dynamictext">
jscript.js
function changeAttr(){
document.getElemenyById('dynamictext').value="World";
}
Now these 2 pages are open on different tabs. What I want to happen is whenever the button on page 1 is clicked, the value of input text on page 2 will change to "World". How can I make this possible with Javascript or Jquery?
A: The 1st tab has the task to change a value in localStorage.
localStorage.setItem('superValue', 'world');
Meanwhile the 2nd tab would be "listen" to changes on that localStorage value:
var dinamictext = document.querySelector('dinamictext');
setInterval(function () {
if (dinamictext.value !== localStorage['superValue']) {
dinamictext.value = localStorage['superValue'];
}
}, 100);
This of course works only with pages on the same domain.
A: You cannot directly access DOM elements from one tab to another. That would be a serious security issue.
*
*You can communicate between your two pages (assuming they are both under your control) using cookies. See this other SO question on the subject.
*You can also use LocalStorage API, assuming you are targeting only modern browsers. See this SO answer.
Both methods will allow you to share data. Then, you will have to define your own protocol, in order to manipulate DOM according to the received command.
A: You can use HTML5 Storage. Here is a simple example
A: The other answers are perfect if both pages belong to the same site. If they're not on the same site however, you'd need a server solution. One page would send a request to the server, and the other page would also have to call the server looking for instructions, and execute those instructions when received. In that scenario, if they're on separate sites, AJAX probably wouldn't work, and you'd have to resort to something like JSONP.
| |
doc_2217
|
From these lines of code:
H, xedges, yedges = np.histogram2d(coord[:, 0], coord[:, 1])
H = H.T
print(H)
I obtain the following histogram:
[[ 7. 20. 16. 14. 10. 8. 16. 7. 10. 7.]
[11. 11. 10. 10. 5. 10. 9. 12. 7. 7.]
[13. 11. 13. 9. 13. 10. 14. 6. 9. 9.]
[ 5. 5. 4. 5. 7. 13. 14. 11. 6. 10.]
[14. 4. 11. 5. 7. 14. 6. 11. 11. 5.]
[12. 9. 5. 7. 9. 14. 15. 15. 13. 12.]
[ 5. 13. 15. 9. 10. 7. 10. 12. 7. 5.]
[ 4. 10. 15. 7. 6. 10. 13. 5. 12. 12.]
[12. 6. 11. 8. 5. 5. 13. 14. 13. 9.]
[10. 11. 9. 8. 18. 13. 16. 8. 8. 13.]]
and I want to find out indices that each element of histogram represents, e.g. (1st row, 1st column -> 7 -> 7 indices should be computed).
I spent many hours trying to follow this post, but I get stuck at one place (I can explain where, if no better approach is known). Another potential duplicate is here but this also does not solve the problem.
So does anybody know, how to resolve this issue?
Thank you!
A: You want scipy.stats.binned_statistic_2d:
H, xedges, yedges, binnumber = scipy.stats.binned_statistic_2d(
coord[:, 0], coord[:, 1], None, 'count', expand_binnumbers=True)
The first three return values are the same as your original code. The fourth (binnumber)` is:
a shape (2,N) ndarray, where each row gives the bin numbers in the corresponding dimension.
| |
doc_2218
|
app.controller('aboutController', function($scope, $route) {
$scope.$on('$routeChangeSuccess', function() {
// Just need this to run once
$('#about').particleground({
dotColor: '#666',
lineColor: '#666',
lineWidth: .3,
particleRadius: 3,
parallaxMultiplier: 3
});
});
A: Check for currentRoute.redirectTo before running the animation inside $routeChangeSuccess`. It will prevent the animation from running multiple times.
$scope.$on("$routeChangeSuccess", function(event, currentRoute, previousRoute){
if(!currentRoute.redirectTo) {
$('#about').particleground({
dotColor: '#666',
lineColor: '#666',
lineWidth: .3,
particleRadius: 3,
parallaxMultiplier: 3
});
}
});
The reason why it's executing twice is:
In your HTML:
<a href="#about">› About Me</a>
In the href, you have just #about but it must be #/about.
<a href="#/about">› About Me</a>
| |
doc_2219
|
the script
#!/bin/bash
LOG_FILE=$homedir/logs/result.log
exec 3>&1
exec > >(tee -a ${LOG_FILE}) 2>&1
echo
end_shell_number=10
for script in `seq -f "%02g_*.sh" 0 $end_shell_number`; do
if ! bash $homedir/$script; then
printf 'Script "%s" failed, terminating...\n' "$script" >&2
exit 1
fi
done
It basically runs through sub-shells number 00 to 10 and logs everything to a LOG_FILE while also displaying on stdout.
I was watching the log getting stacked with tail -F ./logs/result.log,
and it was working nicely until the log file suddenly got removed.
The sub-shells does nothing related to file descriptors nor the log file. They remotely restart tomcats via ssh commands.
Question :
tee was writing on a log file successfully until the file gets erased and logging stops from then on.
Is there a filesize limit or timeout in tee? Is there any known behavior of tee that it deletes a file?
A:
On what occasion does 'tee' deletes the file it was writing on?
tee does not delete nor truncate the file once it has started writing.
Is there a filesize limit or timeout in tee?
No.
Is there any known behavior of tee that it deletes a file?
No.
Note that file can be removed, but the process (tee) still will wrote the open file descriptor, but the file will not be accessible (see man 3 unlink).
| |
doc_2220
|
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANL000}&channelType=any&maxResults=25&order=date&key={XXXXX}
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANL001}&channelType=any&maxResults=25&order=date&key={XXXXX}
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANL002}&channelType=any&maxResults=25&order=date&key={XXXXX}
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANL003}&channelType=any&maxResults=25&order=date&key={XXXXX}
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANL004}&channelType=any&maxResults=25&order=date&key={XXXXX}
Now i want to send a multipart/mixed request to "www.googleapis.com" requesting JSON for all the above api links.
How to do this with axios in reactJS.
Also ref: https://cloud.google.com/storage/docs/json_api/v1/how-tos/batch#example
the following is my axios code:
axios.get('www.googleapis.com/batch')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
where should i include the list of urls in the above axios code
| |
doc_2221
|
A: you should use the google language api, its free to use and supports gujarati. :)
http://code.google.com/apis/language/
Hope this helps,
Eamonn
A: take a look....
http://gu.wikipedia.org/wiki/%E0%AA%AE%E0%AB%81%E0%AA%96%E0%AA%AA%E0%AB%83%E0%AA%B7%E0%AB%8D%E0%AA%A0
take a look again....
http://gu.wikipedia.org/wiki/%E0%AA%97%E0%AB%81%E0%AA%9C%E0%AA%B0%E0%AA%BE%E0%AA%A4%E0%AB%80_%E0%AA%AD%E0%AA%BE%E0%AA%B7%E0%AA%BE
google provide gujarati api... just see that.
http://www.google.com/transliterate/
| |
doc_2222
|
#panel { id = "test" } or #panel { id = test }
the generated html element looks like this:
<div class="wfid_test"></div>.
but what I want is:
<div id="test"></div>
so I can use an anchor link like <a href="#test">Scroll Down to Test</a> to reference the id.
This is basic HTML that has been around forever, so I'm sure Nitrogen must have some way of doing it, right?
A: Use 'html_id' element instead of 'id':
#panel{ html_id=test, body="Test target" }
it will render as:
<div id="test" class="wfid_temp990008">Test target</div>
you can include both 'id' and 'html_id' elements if you need the class for CSS as well:
#panel{ id=test, html_id=test, body="Test target" }
renders as:
<div id="test" class="wfid_temp990008 wfid_test">Test target</div>
A: #panel { id = test } should work fine. Just use atom instead of sting.
| |
doc_2223
|
C:\Users\animesh.vashistha\StudioProjects\MovieListApp\app\src\main\java\com\example\movielistapp\MainViewModel.kt: (21, 43): No type arguments expected for interface Callback
My MainViewModel looks like this:
package com.example.movielistapp
import android.graphics.Movie
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.movielistapp.data.MainRepository
import com.example.movielistapp.model.Model
import retrofit2.Call
import retrofit2.Response
import javax.security.auth.callback.Callback
class MainViewModel constructor(private val repository: MainRepository) : ViewModel() {
val movieList = MutableLiveData<List<Model.Movie>>()
val errorMessage = MutableLiveData<String>()
fun getAllMovies() {
val response = repository.getAllMovies()
response.enqueue(object : Callback<List<Movie>>{
fun onResponse(call: Call<List<Model.Movie>>, response: Response<List<Model.Movie>>) {
movieList.postValue(response.body())
}
fun onFailure(call: Call<List<Model.Movie>>, t: Throwable) {
errorMessage.postValue(t.message)
}
})
}
}
I have imported import retrofit2.call as answered in other solutions to this question. Can someone please check and tell what wrong I'm doing?
| |
doc_2224
|
I'm relatively new to Tkinter and my understanding of it is limited, so I'm sorry if it's an obvious problem.
Whenever I try to install I get the following:
Selecting previously unselected package python3-pil.imagetk:armhf.
dpkg: unrecoverable fatal error, aborting: files list file for package
'qdbus' is missing final newline E: Sub-process /usr/bin/dpkg returned
an error code (2)
A: *
*Install Python Imaging with Tkinter support:
sudo apt-get install python-imaging-tk
*In the code:
from PIL import ImageTk, Image
A: Next advice helped me, after that I was able to import ImageTk from PIL:
# python 2
sudo apt-get install python-imaging python-pil.imagetk
# python 3
sudo apt-get install python3-pil python3-pil.imagetk
reference:
https://www.codegrepper.com/code-examples/whatever/how+to+install+imagetk+in+python
| |
doc_2225
|
This is working correctly but how can I add the else condition ?
<li *ngFor="let product of categories; let num = index">
<div *ngIf="product.id === model.categoriesListDTO[num].id">
{{product.id}}
</div>
</li>
A: try “else” statement of Angular
<li *ngFor="let product of categories; let num = index">
<div *ngIf="product.id === model.categoriesListDTO[num].id; else notEqual">
{{product.id}}
</div>
<ng-template #notEqual>
not equal content
</ng-template>
</li>
A: Good day! You can use else keyword in ngIf directive with ref to the ng-template directive.
<li *ngFor="let product of categories; let num = index">
<div *ngIf="product.id === model.categoriesListDTO[num].id; else tpl">
{{ product.id }}
</div>
<ng-template #tpl>
Any content for else condition goes here..
</ng-template>
</li>
| |
doc_2226
|
create table illustrativeTable
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
label VARCHAR(4),
reportingDate DATE,
attr_1 INT,
attr_2 INT,
attr_3 INT,
PRIMARY KEY(id)
);
I have populated the illustrative table as follows:
INSERT INTO illustrativeTable(label, reportingDate, attr_1, attr_2, attr_3) VALUES('A', '2018-01-01', '1', '3', '100'),
('A', '2018-01-05', '2', '4', '125'), ('A', '2018-01-07', '2', '5', '125'),
('A', '2018-01-08', '3', '6', '150'), ('A', '2018-01-11', '4', '7', NULL),
('B', '2018-01-02', '1', '3', '50'), ('B', '2018-01-05', '2', '5', '75'),
('B', '2018-01-06', '3', '6', '200'), ('B', '2018-01-16', '3', '5', '200'),
('C', '2018-01-05', '6', '9', '175'),('C', '2018-01-08', '7', '9', '225'),
('D', '2018-01-01', '2', '5', '55'), ('D', '2018-01-15', '3', '6', 85),
('D', '2018-01-21', '4', '7', '75'), ('E', '2018-01-25', '2', '4', '65'),
('E', '2018-01-28', '2', '5', NULL);
The query
SELECT * FROM illustrativeTable;
yields the following output:
+----+-------+---------------+--------+--------+--------+
| id | label | reportingDate | attr_1 | attr_2 | attr_3 |
+----+-------+---------------+--------+--------+--------+
| 1 | A | 2018-01-01 | 1 | 3 | 100 |
| 2 | A | 2018-01-05 | 2 | 4 | 125 |
| 3 | A | 2018-01-07 | 2 | 5 | 125 |
| 4 | A | 2018-01-08 | 3 | 6 | 150 |
| 5 | A | 2018-01-11 | 4 | 7 | NULL |
| 6 | B | 2018-01-02 | 1 | 3 | 50 |
| 7 | B | 2018-01-05 | 2 | 5 | 75 |
| 8 | B | 2018-01-06 | 3 | 6 | 200 |
| 9 | B | 2018-01-16 | 3 | 5 | 200 |
| 10 | C | 2018-01-05 | 6 | 9 | 175 |
| 11 | C | 2018-01-08 | 7 | 9 | 225 |
| 12 | D | 2018-01-01 | 2 | 5 | 55 |
| 13 | D | 2018-01-15 | 3 | 6 | 85 |
| 14 | D | 2018-01-21 | 4 | 7 | 75 |
| 15 | E | 2018-01-25 | 2 | 4 | 65 |
| 16 | E | 2018-01-28 | 2 | 5 | NULL |
+----+-------+---------------+--------+--------+--------+
Our issue is that we want to retrieve label, reportingDate and attr_3, from selected tuples, with the following constraints:
1) attr_2 - attr_1 = 3
2) attr_3 IS NOT NULL
3) In case of multiple hits, the value with the highest value for reportingDate is selected
The simplistic query:
SELECT label, reportingDate, attr_3 FROM illustrativeTable
WHERE label IN ('A', 'B', 'C', 'E') AND (attr_2-attr_1=3)
AND attr_3 IS NOT NULL GROUP BY label;
yields the following result:
+-------+---------------+--------+
| label | reportingDate | attr_3 |
+-------+---------------+--------+
| A | 2018-01-07 | 125 |
| B | 2018-01-05 | 75 |
| C | 2018-01-05 | 175 |
+-------+---------------+--------+
The problem with this result is that for label 'A' the highest reportingDate that meets all the constraints is 2018-01-08. Similarly for label 'B' the highest reportingDate that meets all the constraints is 2018-01-06.
We would like to tweak the query so that the output looks as follows:
+-------+---------------+--------+
| label | reportingDate | attr_3 |
+-------+---------------+--------+
| A | 2018-01-08 | 150 |
| B | 2018-01-06 | 200 |
| C | 2018-01-05 | 175 |
+-------+---------------+--------+
I did try some ideas from
https://paulund.co.uk/get-last-record-in-each-mysql-group
but I could not get the results I am looking for.
A: To get the output for the highest reportingDate, you just need to add that as a constraint to the query. Note that unless you have multiple data values for a given reportingDate, you don't need a GROUP BY clause:
SELECT label, reportingDate, attr_3
FROM illustrativeTable it1
WHERE label IN ('A', 'B', 'C', 'E') AND
(attr_2-attr_1=3) AND
attr_3 IS NOT NULL AND
reportingDate = (SELECT MAX(reportingDate)
FROM illustrativeTable
WHERE label = it1.label AND
attr_2-attr_1=3 AND
attr_3 IS NOT NULL)
Output:
label reportingDate attr_3
A 2018-01-08 150
B 2018-01-06 200
C 2018-01-05 175
If you do have multiple values for a given reportingDate, you will need to GROUP BY label, and you will also have to decide whether you want the minimum or maximum value of attr_3, in which case you would change attr_3 in the query to MIN(attr_3) or MAX(attr_3) respectively.
Update
Based on the additional criteria specified by OP in a comment below, this is probably the most efficient query to get the desired result. It joins a sub-select of the initial table (with the non-aggregating conditions applied) to two other tables which give the maximum reportingDate by label and the maximum value of attr2 by reportingDate and label respectively, using the JOIN condition to then filter out all entries which do not match MAX(reportingDate) and MAX(attr_2).
SELECT it1.label, it1.reportingDate, it1.attr_3
FROM (SELECT *
FROM illustrativeTable
WHERE label IN ('A', 'B', 'C', 'E') AND
(attr_2-attr_1=3) AND
attr_3 IS NOT NULL) it1
JOIN (SELECT label, MAX(reportingDate) AS max_reportingDate
FROM illustrativeTable it1
WHERE attr_2-attr_1=3 AND attr_3 IS NOT NULL
GROUP BY label) it2
ON it2.label = it1.label AND it2.max_reportingDate = it1.reportingDate
JOIN (SELECT label, reportingDate, MAX(attr_2) AS max_attr_2
FROM illustrativeTable it1
WHERE attr_2-attr_1=3 AND attr_3 IS NOT NULL
GROUP BY label, reportingDate) it3
ON it3.label = it1.label AND it3.reportingDate = it1.reportingDate AND it3.max_attr_2 = it1.attr_2
ORDER BY it1.label
For the sample data the output remains the same however I have tested it with data which triggers the MAX(attr_2) condition on rextester.
| |
doc_2227
|
A: Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
A: You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
A: You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl
| |
doc_2228
|
The error displayed is:
After some investigation I've found that it only occurs if there's also a textbox on the form. The error does not occur with labels, combo boxes, radio buttons etc. just textboxes.
To replicate this without any extra code, I've created a new Windows Form application, and added a single textbox to the form and the following code (which I copied from some website)
Private Sub Form1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim gradBrush As New LinearGradientBrush(Me.ClientRectangle, Color.Blue, Color.White, LinearGradientMode.BackwardDiagonal)
e.Graphics.FillRectangle(gradBrush, Me.ClientRectangle)
End Sub
There is no other code in the application at all.
If I run that, minimize the form, and then bring it back to focus the error occurs.
This is a link to a screen capture of the process occurring: https://www.screencast.com/t/9EFuez3hk.
I've tried various versions of the LinearGradientBrush code that I've found online, and I get the same each time.
A: If ClientRectangle.IsEmpty Then
Return
End If
That will abort mission if the rectangle has those properties.
| |
doc_2229
|
Since I cannot show the actual classes here, I've tried to make an example identical to my problem, which is as follows.
I have a Company which has several property lists to Person. When I'm using EF to convert this into the database, I'm getting a new foreign key column for each instance of Person.
Company
public GUID CompanyID {get,set}
public List<Person> Employee{get,set}
public List<Person> Janitors {get,set}
public List<Person> Students {get,set}
public List<Person> Professors {get,set}
Person
public GUID CompanyID {get,set}
I would like the database scheme of Person to be
|Column 1 | Column 2 | Column 3 | Company_FK |
----------------------------------------------
But now it is more like this
| Column 1 | Column 2 | Column 3 | Company_ID | Company_ID1 | Company_ID2 ...
--------------------------------------------------------------------------
null reference null
null reference null
reference null null
~~~~~~~~~~~~~~~~~~~~~~etc~~~~~~~~~~~~~~~~~~
All those Company_ID* columns have references to the same Company table, therefor I believe that it is not impossible to just have one column for this reference, and then loose all those null references.
I need a solution with Fluent API, not Data Annotation.
A: Try this with your company configuration:
HasMany(x => x.Employee).WithRequired().HasForeignKey(x => x.CompanyID);
HasMany(x => x.Janitors).WithRequired().HasForeignKey(x => x.CompanyID);
HasMany(x => x.Students).WithRequired().HasForeignKey(x => x.CompanyID);
HasMany(x => x.Professors).WithRequired().HasForeignKey(x => x.CompanyID);
| |
doc_2230
|
I'm trying to find out if I can have a Flutter app with an extra tab that seamlessly embeds a PWA on both Android and iOS, so that when you download the mobile app from an app store you get all the functionality of an existing PWA inside the larger mobile app.
A: Not sure about Google Play, but Apple Mobile store rejects apps that are substantially a wrapper around a single website. I presume this would include bundling a PWA.
| |
doc_2231
|
for(int j=0;j<itemSize;j++){
if(!addItem[j].find(next)){
cout << addItem[j] << endl;//////why doesn't this work for multible words???
}
}
}
if(!next.find("@")){//////////////////////searching for @
for(int j=0;j<itemSize;j++){
if(!addItem[j].find(next)){
cout << addItem[j] << endl;//why doesn't this work for multiple words???
}
}
}
Why is my .find() for @ and + only return true if it finds them in the first word? I'm trying to search the whole string, and cout the whole string if it finds it.
This is a command line argument program;
If my todo.txt contains:
"dog"
"cat"
"bird +animal"
"+animal"
without the "".
If I use .find() to search for +animal, only the last element prints. Im trying for "bird +animal" and "+animal" to print. Whats wrong?
full code::
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[]){
vector<string> addItem;
int numLines =0;
ifstream inDo("todo.txt");
string input;
while(getline(inDo, input)){////////////to get number of lines
numLines++;
addItem.push_back(input);
}
remove("todo.txt");
ofstream todo("todo.txt", std::fstream::app);
for(int i=0; i<argc; i++){
string line = argv[i];
if(!line.find("add")){/////////////////////adds to the list
addItem.push_back(argv[i+1]);
cout << addItem.back() << " - added on line " << numLines+1 << endl;
}
if(!line.find("clear")){////////////////////////////clears the list
while(!addItem.empty()){
addItem.pop_back();
}
cout << "List Has Been Cleared."<< endl;
}
if(!line.find("Do")){////////////////////to remove items from list
if(i+2==argc){
int taskNum = atof(argv[i+1]);
cout << addItem[taskNum-1] << " has been completed << endl;
addItem.erase(addItem.begin()+(taskNum-1));
}
else{
cout << "Incorrect format, please retry with 'do #'" << endl;
}
}
if(!line.find("ls")){/////////////////////////prints the list
if(i+1==argc){
int count=0;
int listSize=addItem.size();
while(count < listSize){
cout << count+1 << " " << addItem[count] << endl;
count++;
}
}
if(i+2==argc){/////////////for searching for a certain word
int itemSize=addItem.size();
string next = argv[i+1];
for(int a=0;a<itemSize;a++){
if(!addItem[a].find(next)){
cout << addItem[a] << endl;
}
}
if(!next.find("+")){/////////////searching for +
for(int j=0;j<itemSize;j++){
if(!addItem[j].find(next)){
cout << addItem[j] << endl;
///doesn't work!!
}
}
}
if(!next.find("@")){//////////////////////searching for @
for(int j=0;j<itemSize;j++){
if(!addItem[j].find(next)){
cout << addItem[j] << endl;
//dosen't work!!
}
}
}
}
}
}
vector<string> temp;////////////////////reverse the vector order
while(!addItem.empty()){
temp.push_back(addItem.back());
addItem.pop_back();
}
while(!temp.empty()){////////////////////send to file
todo << temp.back() << "\n";
temp.pop_back();
}
todo.close();
return 0;
}
A: Because string::find doesn't return a bool but an std::size_t, indicating the position of the found substring. Thus, if your substring is located at the beginning of the string, this function will return 0, which is considered false in a context where a logical expression is needed. If the string is not found, or if it is found at a location different from 0, it will return a non-zero value (string::npos or the location), which is then considered true.
So, if (!list.find("whatever")) is not the right way to check for the string not having been found. if (list.find("whatever") == std::string::npos) is.
| |
doc_2232
|
My models.py:
from django.db import models
from django.contrib.auth.models import User
class Flower(models.Model):
name = models.CharField(max_length=80)
water_time = models.IntegerField()
owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.name
My views.py (view, where i want to use it):
class workspaceView(generic.DetailView):
template_name = 'floris/workspace.html'
def get_object(self):
with connection.cursor() as cursor:
cursor.execute(f'SELECT id,name FROM floris_Flower WHERE owner_id = {self.request.user.id}')
row = cursor.fetchall()
object = row
print(object)
if self.request.user.id == object.id:
return object
else:
print('Error')
My urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index2, name='index2'),
path('login/', views.loginView, name='login'),
path('register/', views.register, name='register'),
path('addflower/', views.AddPlantView, name='addflower'),
path('index.html', views.logout_view, name='logout'),
path('workspace/', views.workspaceView.as_view(), name='workspace'),
path('profile/<str:username>/', views.ProfileView.as_view(), name='profile'),
]
And my error code:
OperationalError at /floris/workspace/
no such column: owner_id
Request Method: GET
Request URL: http://127.0.0.1:8000/floris/workspace/
Django Version: 3.2.4
Exception Type: OperationalError
Exception Value:
no such column: owner_id
Exception Location: /home/stazysta-kamil/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 421, in execute
Python Executable: /usr/bin/python3
Python Version: 3.8.10
Python Path:
['/home/stazysta-kamil/Desktop/floris/mysite',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/stazysta-kamil/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Tue, 06 Jul 2021 10:43:32 +0000
A: Since owner_id is declared as a ForeignKey, it will be available in the actual SQL database as owner_id_id. The additional prefix _id is automatically appended by Django for that relational field. When using Django ORM, you would just access it via owner_id then Django will automatically handle things for you in the background but if you are using raw SQL command, then you have to use the actual table column name which is owner_id_id. If you don't want such behavior, set the db_column of the model field with the exact name you want e.g. owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1, db_column="owner_id").
As stated in Django documentation:
Behind the scenes, Django appends "_id" to the field name to create
its database column name. In the above example, the database table for
the Car model will have a manufacturer_id column.
Related references:
*
*https://docs.djangoproject.com/en/3.2/ref/models/fields/#database-representation
*https://docs.djangoproject.com/en/3.1/topics/db/models/#field-name-hiding-is-not-permitted
*https://docs.djangoproject.com/en/3.1/topics/db/optimization/#use-foreign-key-values-directly
A: The problem is in field "owner_id" of Flower model. When you define a Foreign Key in model, is not necessary to add "_id" at the end since Django add it automatically
in this case, should be enough replace
owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
with
owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
| |
doc_2233
|
A: This is not a database related problem.
You can do this with authorization.
See the following links for more help.
http://www.asp.net/web-forms/tutorials/security/membership/user-based-authorization-cs
http://www.codeproject.com/Articles/98950/ASP-NET-authentication-and-authorization
| |
doc_2234
|
The user_id is a foreign key of the table "BorrowedBooks".
package com.androidcss.jsonexample;
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterNotif mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifmainactivity);
//Make call to AsyncTask
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://192.168.1.7/notif.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataNotif> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
DataNotif fishData = new DataNotif();
fishData.NotifTitle= json_data.getString("notif_Title");
fishData.NotifMessage= json_data.getString("notif_Message");
// fishData.sizeName= json_data.getString("size_name");
fishData.Date= json_data.getString("notif_date");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterNotif(MainActivity.this, data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
and here is my php code
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","jmilibrary") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from notification";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
A: On PHP side write same script as above and replace $sql with the new command like
$sql = "select book_information from table where id = " . $_GET["id"];
On the client side make same request as above just add id to the URL like
url = new URL("http://192.168.1.7/notif.php?id="+UserID);
A: Use Okhttp or volley android.
On Android with Okhtttp:
buildernew.addFormDataPart("user_id","YOUR USER ID");
MultipartBody requestBody = buildernew.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(requestBody)
.build()
;
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("respons is error", "Registration error: " + e.getMessage());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
String jsonData = response.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray jr = Jobject.getJSONArray("notification");
for (int i = 0; i < jr.length(); i++) {
DataNotif fishData = new DataNotif();
JSONObject object = jr.getJSONObject(i);
fishData.NotifTitle(object.getString("notif_Title"));
fishData.NotifMessage(object.getString("notif_Message"));
fishData.Date(object.getString("notif_date"));
data.add(personal);
}
response.body().close();
} catch (IOException e) {
Log.e("respons is not Ok", "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
On PHP:
function connectToDatabase(){
$connection=mysqli_connect("localhost", "root", "", "jmilibrary");
mysqli_set_charset($connection, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $connection;
}
$connection = connectToDatabase();
$user_id = $_REQUEST['user_id'];
$result = mysqli_query($connection, "SELECT * FROM book_information WHERE id=$user_id");
while($row = mysqli_fetch_array($result)) {
$record['id'] = $row['id'];
$record['notif_Title'] = $row['notif_Title'];
$record['notif_Message'] = $row['notif_Message'];
$record['notif_date'] = $row['notif_date'];
$notification['notification'][] = $record;
}
echo json_encode($notification);
mysqli_close($connection);
| |
doc_2235
|
I already managed to talk to the printer via this code:
private void Print(string printer)
{
PrintDocument PrintDoc = new PrintDocument();
PrintDoc.PrinterSettings.PrinterName = printer;
PrintDoc.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDoc.Print();
}
void PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawLine(new Pen(Color.Black), new Point(0, 0), new Point(100, 100));
e.Graphics.DrawString("Hello World", new Font("Times New Roman", 12), new SolidBrush(Color.Black), new Point(45, 45));
}
Which prints me my "hello world" string. Obviously the PrintPage method is code I found on the net.
Sadly I couldn't find a way to
a) set the format the size of the paper I print on (it is 138mm x 99mm landscape format)
b) tell the printer where to print my texts exactly.
The paper is a preprinted form and I have to write my text in the specific fields.
So I'm looking for a way to give my printer a formated document like:
<field1>
<x> 2cm </x>
<y> 1cm </y>
<text> textfield1 </text>
</field1>
<field2>
....
I couldn't find information on how to do that. So if anyone could tell me how to do this or has a link to a good tutorial, I'd be very thankfull
A: To set the size of the paper
printDocument.DefaultPageSettings.PaperSize = new PaperSize("Custom Name", width, height);
printDocument.DefaultPageSettings.Landscape = true;
width and height is in hundredths of an inch
See the tutorial in this SO question for printing text on pre-printed paper.
Also to avoid paper wastage during your experimentation, scan the preprinted paper as image and set it as background in PrintPageHanlder during preview.
void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
if (printDocument.PrintController.IsPreview)
{
Image image = Image.FromFile("ScannedImagePath");
e.Graphics.DrawImage(image,0,0)
}
// print other text here after drawing the background
}
| |
doc_2236
|
int pageNumber = get from user; // for example 2 , 3 ,...
if pageNumber == 2
return records 20 to 29
Thanks!
A: What you want probably is the following:
var itemsToShow = items.OrderBy(p => p.Id)
.Skip((currentPage - 1) * numPerPage)
.Take(numPerPage);
Where you are ordering pages by Id property and you have variables currentPage holding the number of the current page and numPerPage holding the number of items per page.
You probably would like then to make a type containing the paging info to make your life easier. Something like
public class PagingInfo
{
public int ItemsPerPage { get; set; }
public int NumItems { get; set; }
public int CurrentPage { get; set; }
public int TotalPages
{
get
{
return Math.Ceiling((double)NumItems/ItemsPerPage);
}
}
}
Then your currentPage would be pagingInfo.CurrentPage and your numPerPage would be pagingInfo.ItemsPerPage. In addition you have a property to get the total number of pages which can be useful. This is a good approach so that you can transport information about paging on view models.
A: int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);
A: i suggest to use PagedList.MVC its a free library witch is available on Nuget:
here is an example:
this is going to be your action:
public ActionResult Index(int page = 1)
{
//_db is my sample data context but paged list works for any IEnumerable
//since this is an extension method
var model =
_db.Comments
.OrderByDescending(c => c.Date)
.ToPagedList(page, 10);
return View(model);
}
i`v set model for view as an IPagedList, this is the view:
nice thing is that it will automaticlly generate page links.
<div class="pager">
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
its customizable (via css).
this is the nuget page:
PagedList.MVC nuget page
| |
doc_2237
|
mask_grid_navi_via_points = new Ext.LoadMask(grid_navi_via_points.getEl(), {msg: 'Text...<button>Cancel</button>'});
I want insert Ext.Button and if like:
var btn = new Ext.Button({
renderTo: id,
text: 'Cancel',
handler: function(){
mask_grid_navi_via_points.hide();
}
});
mask_grid_navi_via_points = new Ext.LoadMask(grid_navi_via_points.getEl(), {msg: 'Text...'+btn});
return [object Object]?
A: This is not so easy, since LoadMask is not a container, which would have items property. You could try
var loadMask = Ext.create('Ext.LoadMask',{
msg:'Text'
});
loadMask.on('show',function(mask) {
Ext.create('Ext.button.Button',{
text: 'Cancel',
handler: function(){
loadMask.hide();
},
renderTo:loadMask.getEl()
}
});
loadMask.show();
A: In Ext 4, I was able to get the following to work:
targetComponent.setLoading({
msg: msg,
listeners: {
afterrender: function(component) {
var el = component.el.createChild({tag: 'div', style: 'background-image: none; padding: 2px; border: 0; margin: auto; text-align: center;' });
Ext.create('Ext.button.Button', {
renderTo: el,
html: 'Cancel',
handler: function(button) {
// do something
}
});
}
}
});
The extra div was just to get the button to show up nice under the message.
Unfortunately, this didn't work in Ext 5. Everything I tried made the button a child of the targetComponent instead of the LoadMask.
After fiddling, I went with a different approach for Ext 5:
targetComponent.mask(msg);
var maskMsgDiv = targetComponent.getEl().down('.x-mask-msg');
var buttonDiv = maskMsgDiv.appendChild({tag: 'div', style: 'background-image: none; padding: 2px; border: 0; margin: auto; text-align: center;' });
Ext.create('Ext.button.Button', {
renderTo: buttonDiv,
html: 'Cancel',
handler: function(button) {
// do something
}
});
To hide the mask, call targetComponent.unmask().
I really don't like the use of down() here. Seems fragile and might be yet another chance for Sencha to break me...
| |
doc_2238
|
Places: No PlaceSelectionListener is set. No result will be delivered.
Not sure what am doing wrong
Here is how my method looks like
private fun setupPlacesAutoComplete(){
var placeFields = mutableListOf(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS)
Places.initialize(view!!.context, getString(R.string.google_api_key))
placesClient = Places.createClient(view!!.context)
val autoCompleteFragment =
activity?.supportFragmentManager?.findFragmentById(R.id.autoCompleteFragment) as? AutocompleteSupportFragment
autoCompleteFragment?.setPlaceFields(placeFields)
autoCompleteFragment?.setOnPlaceSelectedListener(object : PlaceSelectionListener{
override fun onPlaceSelected(place: Place) {
Toast.makeText(view!!.context, ""+place.address, Toast.LENGTH_SHORT).show()
}
override fun onError(status: Status) {
Toast.makeText(view!!.context, ""+status.statusMessage, Toast.LENGTH_SHORT).show()
}
})
}
my fragment has this included
<fragment
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:id="@+id/autoCompleteFragment"
android:layout_width="match_parent"
android:layout_height="30dp"/>
A: If you have done the set up correctly
*
*Enabled Billing
*Enabled Places API for your Project
And Still, you are not getting the result with above code means most probably this is the problem
If you want to use the AutocompleteSupportFragment inside an Activity, you can get it in this way:
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);
If you want to use the AutocompleteSupportFragment inside a Fragment, you can get it in this way:
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getChildFragmentManager().findFragmentById(R.id.autoCompleteFragment);
I had the same problem :-)
| |
doc_2239
|
Example: {2,4,4,2,4,5,0,0,0,0,...} shift right by 4 -> {0,0,0,0,2,4,4,2,4,5,...}
A: If the shift distance is known at compile time, it’s relatively easy and quite fast. The only caveat, 32-byte byte shift instructions do that independently for 16-byte lanes, for shifts by less than 16 bytes need to propagate these few bytes across lanes. Here’s for the left shift:
// Move 16-byte vector to higher half of the output, and zero out the lower half
inline __m256i setHigh( __m128i v16 )
{
const __m256i v = _mm256_castsi128_si256( v16 );
return _mm256_permute2x128_si256( v, v, 8 );
}
template<int i>
inline __m256i shiftLeftBytes( __m256i src )
{
static_assert( i >= 0 && i < 32 );
if constexpr( i == 0 )
return src;
if constexpr( i == 16 )
return setHigh( _mm256_castsi256_si128( src ) );
if constexpr( 0 == ( i % 8 ) )
{
// Shifting by multiples of 8 bytes is faster with shuffle + blend
constexpr int lanes64 = i / 8;
constexpr int shuffleIndices = ( _MM_SHUFFLE( 3, 2, 1, 0 ) << ( lanes64 * 2 ) ) & 0xFF;
src = _mm256_permute4x64_epi64( src, shuffleIndices );
constexpr int blendMask = ( 0xFF << ( lanes64 * 2 ) ) & 0xFF;
return _mm256_blend_epi32( _mm256_setzero_si256(), src, blendMask );
}
if constexpr( i > 16 )
{
// Shifting by more than half of the register
// Shift low half by ( i - 16 ) bytes to the left, and place into the higher half of the result.
__m128i low = _mm256_castsi256_si128( src );
low = _mm_slli_si128( low, i - 16 );
return setHigh( low );
}
else
{
// Shifting by less than half of the register, using vpalignr to shift.
__m256i low = setHigh( _mm256_castsi256_si128( src ) );
return _mm256_alignr_epi8( src, low, 16 - i );
}
}
However, if the shift distance is not known at compile time, this is rather tricky. Here’s one method. It uses quite a few shuffles, but I hope it’s still somewhat faster than the obvious way with two 32-byte stores (one of them is to write zeroes) followed by 32-byte load.
// 16 bytes of 0xFF (which makes `vpshufb` output zeros), followed by 16 bytes of identity shuffle [ 0 .. 15 ], followed by another 16 bytes of 0xFF
// That data allows to shift 16-byte vectors by runtime-variable count of bytes in [ -16 .. +16 ] range
inline std::array<uint8_t, 48> makeShuffleConstants()
{
std::array<uint8_t, 48> res;
std::fill_n( res.begin(), 16, 0xFF );
for( uint8_t i = 0; i < 16; i++ )
res[ (size_t)16 + i ] = i;
std::fill_n( res.begin() + 32, 16, 0xFF );
return res;
}
// Align by 64 bytes so the complete array stays within cache line
static const alignas( 64 ) std::array<uint8_t, 48> shuffleConstants = makeShuffleConstants();
// Load shuffle constant with offset in bytes. Counterintuitively, positive offset shifts output of to the right.
inline __m128i loadShuffleConstant( int offset )
{
assert( offset >= -16 && offset <= 16 );
return _mm_loadu_si128( ( const __m128i * )( shuffleConstants.data() + 16 + offset ) );
}
// Move 16-byte vector to higher half of the output, and zero out the lower half
inline __m256i setHigh( __m128i v16 )
{
const __m256i v = _mm256_castsi128_si256( v16 );
return _mm256_permute2x128_si256( v, v, 8 );
}
inline __m256i shiftLeftBytes( __m256i src, int i )
{
assert( i >= 0 && i < 32 );
if( i >= 16 )
{
// Shifting by more than half of the register
// Shift low half by ( i - 16 ) bytes to the left, and place into the higher half of the result.
__m128i low = _mm256_castsi256_si128( src );
low = _mm_shuffle_epi8( low, loadShuffleConstant( 16 - i ) );
return setHigh( low );
}
else
{
// Shifting by less than half of the register
// Just like _mm256_slli_si256, _mm_shuffle_epi8 can't move data across 16-byte lanes, need to propagate shifted bytes manually.
__m128i low = _mm256_castsi256_si128( src );
low = _mm_shuffle_epi8( low, loadShuffleConstant( 16 - i ) );
const __m256i cv = _mm256_broadcastsi128_si256( loadShuffleConstant( -i ) );
const __m256i high = setHigh( low );
src = _mm256_shuffle_epi8( src, cv );
return _mm256_or_si256( high, src );
}
}
| |
doc_2240
|
here is my yacc file:sin.y
%{
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define YYSTYPE double
YYSTYPE last_value=0;
extern int yylex(void);
%}
%token NUM
%token LAST
%left '+' '-'
%left '*' '/'
%left '^'
%left NEG
%left COS EXP SIN SQRT TAN
%%
stmt:
|stmt '\n'
|stmt expr '\n' {printf("%.8g\n",last_value=$2);}
;
expr:text {$$=$1;}
|expr '+'expr{$$=$1+$3;}
|expr '-' expr {$$=$1-$3;}
|expr '*' expr {$$=$1*$3;}
|expr '/' expr {$$=$1/$3;}
|expr '^' expr {$$=pow($1,$3);}
|'-'expr %prec NEG {$$=-$2;}
|COS text {$$=cos($2*3.14/180);}
|EXP text{$$=exp($2);}
|SIN text{$$=sin($2*3.14/180);}
|SQRT text{$$=sqrt($2);}
|TAN text{$$=tan($2*3.14/180);}
;
text:NUM {$$=$1;}
|LAST{$$=last_value;}
|'(' expr ')' {$$=$2;}
;
%%
#include "unistd.h"
int ln;
char* fname="-stdin-";
int yyerror(const char *s)
{
fprintf(stderr,"%s(%d):%s\n",fname,ln,s);
exit(0);
}
main()
{
printf("ABILITIES OF CALCULATOR:\n");
printf("Sum MUL DIV SUB POWER COS SIN TAN SQRT \n");
printf("DO WHATEVER YOU WANT TO DO: \n");
yyparse();
}
and lex file sin.l
%{
#include<stdio.h>
#include"y.tab.c"
#include<stdlib.h>
#include<unistd.h>
#include<math.h>
#define YYSTYPE double
extern ln;
extern YYSTYPE yylval;
%}
digit [0-9]
space [ \t]
%%
{space} {;}
{digit}+\.?|{digit}*\.{digit}+ {yylval=strtod(yytext,0);
return NUM; }
\*\* { return '^'; }
last { return LAST; }
cos { return COS; }
exp { return EXP; }
sin { return SIN; }
sqrt { return SQRT; }
tan { return TAN; }
pi { yylval = atan(1.0)*4;
return NUM; }
e { yylval = exp(1.0);
return NUM; }
\n { ln++; return '\n'; }
. { return yytext[0]; }
%%
IT shows various error on compiling like
/tmp/ccd11cX5.o:(.bss+0x0): multiple definition of `last_value'
/tmp/ccO4t7Z8.o:(.bss+0x18): first defined here
/tmp/ccd11cX5.o: In function `yyparse':
y.tab.c:(.text+0x24): multiple definition of `yyparse'
/tmp/ccO4t7Z8.o:lex.yy.c:(.text+0x24): first defined here
/tmp/ccd11cX5.o: In function `yyerror':
y.tab.c:(.text+0xbb9): multiple definition of `yyerror'
/tmp/ccO4t7Z8.o:lex.yy.c:(.text+0xbb9): first defined here
/tmp/ccd11cX5.o:(.data.rel.local+0x0): multiple definition of `fname'
/tmp/ccO4t7Z8.o:(.data.rel.local+0x0): first defined here
/tmp/ccd11cX5.o: In function `main':
y.tab.c:(.text+0xbfe): multiple definition of `main'
/tmp/ccO4t7Z8.o:lex.yy.c:(.text+0xbfe): first defined here
/tmp/ccO4t7Z8.o: In function `yyparse':
lex.yy.c:(.text+0x60a): undefined reference to `pow'
lex.yy.c:(.text+0x667): undefined reference to `cos'
lex.yy.c:(.text+0x696): undefined reference to `exp'
lex.yy.c:(.text+0x6cf): undefined reference to `sin'
lex.yy.c:(.text+0x6fe): undefined reference to `sqrt'
lex.yy.c:(.text+0x734): undefined reference to `tan'
/tmp/ccd11cX5.o: In function `yyparse':
y.tab.c:(.text+0x60a): undefined reference to `pow'
y.tab.c:(.text+0x667): undefined reference to `cos'
y.tab.c:(.text+0x696): undefined reference to `exp'
y.tab.c:(.text+0x6cf): undefined reference to `sin'
y.tab.c:(.text+0x6fe): undefined reference to `sqrt'
y.tab.c:(.text+0x734): undefined reference to `tan'
collect2: error: ld returned 1 exit status
| |
doc_2241
|
Now I want to change the state when I click the mouse button down and change it back when the mouse button goes up. My button has to event "PreviewMouseLeftButtonDown" and "PreviewMouseLeftButtonUp" as you can see in the code below. In the SendStateMessage() method the state is send to a SCADA-Server and the server sends me the new state back and the GUI edits the change.
Normally it doesn't make any problems, but when I click to fast the "PreviewMouseLeftButtonUp" event doesn't get called. So the "MouseUp" is not shown at the consol.
I tried to call a Task.Delay() in the first mouseDown event because i thougt that the method needs some more time but this didn't work well. So i want to ask you if somebody has an idea what the problem could be and a way how this issue can be fixed.
Thanks for your time.
private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//_CurrentItem is an object of the class VM on which the click is executed.
_CurrentItem = sender as FrameworkElement).DataContext as VM
_CurrentItem.SendStateMessage();
}
private void Button_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Console.WriteLine("MouseUp");
}
EDIT:
After a bit of time passing by I had another idea to solve the problem, which is also working. I only wait for the MouseDownEvent and if this gets triggered i have a loop where i wait as long as the mouse is pressed, when the mouse is released i could leave the loop and there i inserte the code which i wanted to do in the MouseUPEvent.
A: You can also wait for the MouseDownEvent and if this gets triggered make a loop where you wait as long as the mouse is pressed, when the mouse is released you could leave the loop and inserte there your code which you wanted to do in the MouseUpEvent.
A: In my case another control consumed the mouseup event. So I catch the mouseup event on level of the top most windows.
| |
doc_2242
|
Lets consider I have a SFC (I am using TypeScript) and export it like:
export const AppShell: React.SFC<Props> = (props: Props) => (
...
)
All fine. But now before I export my component I want to wrap it with a HOC like withStyles from MaterialUI. Now I want to do something like:
const AppShell: React.SFC<Props> = (props: Props) => (
...
)
And export it as:
export const AppShell = withStyles(styles)<Props>(AppShell);
Of course this will result in an error:
[ts] Cannot redeclare block-scoped variable 'AppShell'.
Solutions with trade-off
As far as I know I will now have two options:
1) Use an default export:
export default withStyles(styles)<Props>(AppShell);
Because I am not a fan of default exports because of their many disadvantages I am not ok with that solution.
2) Use a prefix like 'Raw' for my components before they get wrapped:
const RawAppShell: React.SFC<Props> = (props: Props) => (
...
)
Export it like:
export const AppShell = withStyles(styles)<Props>(RawAppShell);
I like this approach much more also with the trade-off of adding this prefix.
Other Solutions
How do you handle this in your projects? Is there already a best-practice solution out there? It is very important for me that I have an named export for my component so I could not accept a solution with an default export at all.
Thank you in advance.
A: Just do it in a single statement:
export const AppShell: React.SFC<Props> = withStyles(styles)<Props>((props: Props) => (
…
));
| |
doc_2243
|
Is there some other configuration parameter that may affect the keyboard behavior I should consider?
Remmina 1.4.5 on Uqbuntu 20.04; connection with Windows 8.1
Possibly related question:
https://unix.stackexchange.com/questions/57725/remmina-doesnt-eat-keys
A: It seems that the 'Use the client keyboard layout' general option (RDP section) also matters; when checked, dead keys don't work properly (as described), even if both keyboard layouts are the same (US International).
Unchecking it resolves the problem.
| |
doc_2244
|
function new_troop() {
var source = SpreadsheetApp.openById("***");
var target = SpreadsheetApp.openById("***");
var source_sheet = source.getSheetByName("***");
var target_sheet = target.getSheetByName("***");
var seller = source_sheet.getRange("B14").getValue();
var category = source_sheet.getRange("B5").getValue();
var probability = source_sheet.getRange("B11").getValue();
var outcome1 = target_sheet.getRange("B1").setValue(seller);
var outcome2 = target_sheet.getRange("B2").setValue(category);
var outcome3 = target_sheet.getRange("B3").setValue(probability);
var source_sheet2 = target.getSheetByName("***");
var target_sheet2 = source.getSheetByName("***");
var range1 = source_sheet2.getRange(1, 5, 100, 1).getValues();
var range2 = source_sheet2.getRange(1, 18, 100, 1).getValues();
var range3 = source_sheet2.getRange(1, 14, 100, 1).getValues();
var range4 = source_sheet2.getRange(1, 17, 100, 1).getValues();
target_sheet2.getRange(1,1, 100,1).setValues(range1);
target_sheet2.getRange(1,2, 100,1).setValues(range2);
target_sheet2.getRange(1,3, 100,1).setValues(range3);
target_sheet2.getRange(1,4, 100,1).setValues(range4);
var distance = SpreadsheetApp.openById("***");
var distance_sheet = distance.getSheetByName("***");
var km = distance_sheet.getRange(1,2,100,5).getValues();
source_sheet.getRange(1,7,100,5).setValues(km);
ScriptApp.newTrigger('new_troop')
.forSpreadsheet(SpreadsheetApp.getActive())
.onEdit()
.create();
}
| |
doc_2245
|
I applied opencv HoughLinesP to it and got the following result
Using the following code:
img = cv2.imread('./image.jpeg', 1)
img_gray = gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cannied = cv2.Canny(img_gray, threshold1=50, threshold2=200, apertureSize=3)
lines = cv2.HoughLinesP(cannied, rho=1, theta=np.pi / 180, threshold=80, minLineLength=30, maxLineGap=10)
for line in get_lines(lines):
leftx, boty, rightx, topy = line
cv2.line(img, (leftx, boty), (rightx,topy), (255, 255, 0), 2)
cv2.imwrite('./lines.png', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
More resources I applied
PyImageSearch
and several others
A: Here's a possible solution. It involves selecting a sample from a couple of rows on the input image, then reducing the sample to a row image using the cv2.reduce function. Loop through the reduced row and look for the pixel intensity jumps from 0 to 255, since that transitions denotes the areas of the page you are using to guide your crop. Finally, store the locations of the jumps in a list to further crop the pages from the image. These are the steps:
*
*Get a sample ROI from the image
*Reduce the sample ROI to a row image of size 1 x width, using the cv2.reduce function in MAX mode to get the maximum intensity values of each column
*Loop through the image and look for the intensity transitions from 0 to 255 - this point is where a vertical line is located
*Store each "transition location" in a list
*Crop the image using the info in "transition locations" list
Let's see the code:
# Imports:
import numpy as np
import cv2
# Set the image path
path = "D://opencvImages//"
fileName = "mx8lW.jpg"
# Read the image in default mode:
inputImage = cv2.imread(path + fileName)
# Convert RGB to grayscale:
grayscaleImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Set the sample ROI and crop it:
(imageHeight, imageWidth) = grayscaleImage.shape[:2]
roiX = 0
roiY = int(0.05 * imageHeight)
roiWidth = imageWidth
roiHeight = int(0.05 * imageHeight)
# Crop the image:
imageRoi = grayscaleImage[roiY:roiY+roiHeight, roiX:roiWidth]
The first bit reads the image, converts it from BGR to grayscale and defines the sample ROI. This ROI is used to locate the vertical lines. Since the vertical lines are constant through the image, selecting and cropping just a sample will do just fine instead of processing the whole image. The ROI I defined selects an area just below the image top, because there are some dark portions that could affect the reduction of the ROI to a row.
This image shows the selected ROI, drawn with a green rectangle:
Note that the two (leftmost and rightmost) vertical lines are shown clearly inside the ROI. If we crop that, we will get this sample image:
All the info we need to crop the pages is right there. Let's threshold the image to get a binary mask:
# Thresholding:
_, binaryImage = cv2.threshold(imageRoi, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
This is the binary mask:
Note the jumps from 0 to 255 and what they imply. Each transition denotes the starting and ending points that we can use to crop the two pages. Ok, let's reduce the binary mask to just one row. We will use the MAX mode, where each pixel value in the row is defined as the maximum intensity value corresponding to that image column:
# Reduce the ROI to a 1 x imageWidth row:
reducedImg = cv2.reduce(binaryImage, 0, cv2.REDUCE_MAX)
This is the image produced, which is just a row:
Let's loop through this image (actually just a plain numpy array) and look for those transitions. Additionally, let's prepare a list and store the jump the locations as we find them:
# Store the transition positions here:
linePositions = []
# Find transitions from 0 to 255:
pastPixel = 255
for x in range(reducedImg.shape[1]):
# Get current pixel:
currentPixel = reducedImg[0,x]
# Check for the "jumps":
if currentPixel == 255 and pastPixel == 0:
# Store the jump locations in list:
print("Got Jump at:"+str(x))
linePositions.append(x)
# Set current pixel to past pixel:
pastPixel = currentPixel
Cool, we have the jump locations ready in linePositions. Let's finally crop the image. I've achieved this looping through the locations list and setting the parameters for cropping:
# Crop pages:
for i in range(len(linePositions)):
# Get top left:
cropX = linePositions[i]
# Get top left:
if i != len(linePositions)-1:
# Get point from the list:
cropWidth = linePositions[i+1]
else:
# Set point from the image's original width:
cropWidth = reducedImg.shape[1]
# Crop page:
cropY = 0
cropHeight = imageHeight
currentCrop = inputImage[cropY:cropHeight,cropX:cropWidth]
# Show current crop:
cv2.imshow("CurrentCrop", currentCrop)
cv2.waitKey(0)
Which produces two crops:
A: Based on this input image, you want to find the longest vertical line that sits at the middle of the image. Therefore you have several options to try:
*
*Crop the image on the left and right, to keep only the middle 1/3 or 1/4, which is roughly where the actual middle line is.
*Adjust the parameter minLineLength in your cv2.HoughLinesP, to eliminate shorter lines.
*If there are still more than one lines left, the longest one is probably what you want. To double check, calculate the lines' slops, the most vertical + longest one should be the final answer.
| |
doc_2246
|
Has someone ever achieved this and can give me a hint?
Thanks,
Matthias
A: You can do that, indeed. Please see an example for this here.
The result looks like
.
| |
doc_2247
|
useEffect(() => {
if (show && inView) {
const timer = () => {
setCount(count + 1);
};
if (count >= number) {
const plus = setPlus('+');
return plus;
}
const interval = setInterval(timer, 800 / number);
return () => clearInterval(interval);
}
setCount(1);
setPlus('');
setShow(false);
}, [count, inView, number, plus, show]);
A: do you use some react extensions for eslint in your project ?
Here's a standard eslint config for react projects:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'plugin:react/recommended',
'airbnb',
],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'react',
'prefer-arrow',
],
}
Try it in your .eslintrc and tell me if you still got this error
EDIT:
Can you join your eslint config file ?
You shouldn't get this error. Maybe I can explain you some stuff about it.
Or your can just disable this rule for your project by editing your .eslintrc file and adding:
rules: {
'consistent-return': 'off',
}
A: This is my .eslintrc
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"react-app",
"plugin:react/recommended",
"airbnb",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react", "prettier"],
"rules": {
"react/jsx-uses-react": ["off"],
"react/react-in-jsx-scope": ["off"],
"react/jsx-props-no-spreading": ["warn"],
"no-shadow": "off"
}
}
| |
doc_2248
|
Im passing the string to the method like this :-
[self buildrawdata2:(const unsigned char *)"0ORANGE\0"];
Here is the method that works when the array uses a string set to "0ORANGE\0", the string I pass over is also missing the "\0" from the end, I believe this is because its a control character / escape sequence, is there anyway to retain this and pass it like the string hardcoded below :-
- (void)buildrawdata2:(const unsigned char *)inputString2;
{
NSLog(@"ViewController::buildrawdata2");
NSLog(@"ViewController::buildrawdata2 - inputstring2: %s", inputString2);
//this works when set like this
const unsigned char magic2[] = "0ORANGE\0";
const uint8_t pattern1 = {0xFC};
const uint8_t pattern2 = {0xE0};
uint8_t rawdata2[56];
uint8_t index = 0;
int byte = 0;
int bit = 0;
while (magic2[byte] != 0x00) {
while (bit < 8) {
if (magic2[byte] & (1<<bit)) {
//add pattern2 to the array
rawdata2[index++] = pattern2;
}else{
//add pattern1 to the array
rawdata2[index++] = pattern1;
}
// next bit please
bit++;
}
//next byte please
byte++;
//reset bit index
bit = 0;
}
NSLog(@"buildrawdata2::RawData %@", [NSData dataWithBytes:rawdata2 length:56]);
}
A: Looks like I have worked out a solution to this, I would be happy to hear others views on this method or suggestions to improve it.
Instead of taking the string passed into the method and trying to directly update the array initializer I used the string to determine which array initializer should be used. For this to work I had to create a pointer before the if block so that I could then assign strings to it from within the if blocks.
const unsigned char *magic = NULL;
if (inputString == @"0APPLES") { magic = (const unsigned char*) "0APPLES\0";}
else if (inputString == @"0ORANGE") { magic = (const unsigned char*) "0ORANGE\0";}
Also recently tried this way and its also working :-
const unsigned char apples[] = "0APPLES\0";
const unsigned char orange[] = "0ORANGE\0";
const unsigned char *magic;
if (inputString2 == @"0APPLES") { magic = apples;}
else if (inputString2 == @"0ORANGE") { magic = orange;}
The method can then be called like this :-
[self buildrawdata1:@"0APPLES"];
[self buildrawdata1:@"0ORANGE"];
| |
doc_2249
|
I have two **div**'s: one for logo and another for menu, they are aligned using **flex**.
When I start decreasing the screen size, menu **div** starts shrinking until some point, when one of the menu item (ABOUT US) looses alignment. Then logo-**div** starts shrinking until the menu disappears.
Please advice, how can I keep the menu item (ABOUT US) inline until the menu completely disappears and how can I make logo-**div** occupy full width and centered when menu is not visible?
Screen Visualisation:
HTML code:
<nav class="item-center flex items-center">
<div class="bg-red-100 pl-5 py-1">
<a href="#"><img src="img/logo.svg" alt="Logo"></a>
</div>
<div class="flex-1">
<ul class="hidden sm:flex bg-blue-200 justify-end gap-12 text-red-500 uppercase text-s pr-5">
<li class="cursor-pointer ">Features </li>
<li class="cursor-pointer ">Products </li>
<li class="cursor-pointer ">Services </li>
<li class="cursor-pointer ">About us </li>
<li class="cursor-pointer ">Contact </li>
</ul>
</div>
</nav>
A: I try to resolve your problem, check here
A: I'd use whitespace-nowrap class for about us section and first thing that comes to my mind for logo is to add a minimum width to it, and flex grow, so that it can't go below certain width and once the menu disappears that it grows to the full width.
A: About wrapping
<li class="cursor-pointer whitespace-nowrap">About us </li>
and about small screen check
https://tailwindcss.com/docs/responsive-design#targeting-a-single-breakpoint
and
<div class="flex bg-red-100 pl-5 py-1 sm:pl-0 sm:w-full sm:justify-center">
<a href="#"><img src="img/logo.svg" alt="Logo"></a>
</div>
| |
doc_2250
|
OAuth2Configuration.java
@Configuration
public class OAuth2Configuration {
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
@Autowired
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.logout()
.logoutUrl("/oauth/logout")
.logoutSuccessHandler(customLogoutSuccessHandler)
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/secure/**", "/person/**", "/product/**").authenticated()
.antMatchers(HttpMethod.GET, "/user/**").authenticated()
.antMatchers(HttpMethod.PUT, "/user/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/user/**").authenticated()
.antMatchers(HttpMethod.POST, "/user").permitAll();
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
private static final String ENV_OAUTH = "authentication.oauth.";
private static final String PROP_CLIENTID = "clientid";
private static final String PROP_SECRET = "secret";
private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
private RelaxedPropertyResolver propertyResolver;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(propertyResolver.getProperty(PROP_CLIENTID))
.scopes("read", "write")
.authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
.authorizedGrantTypes("password", "refresh_token")
.secret(propertyResolver.getProperty(PROP_SECRET))
.redirectUris("http://localhost:8080/login")
.accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
}
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
}
}
}
SecurityConfiguration.java
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
// Define the type of encode
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
//.antMatchers("/h2console/**")
.antMatchers("/register")
.antMatchers("/activate")
.antMatchers("/lostpassword")
.antMatchers("/resetpassword")
//.antMatchers("/hello")
.antMatchers("/person")
.antMatchers("/product");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
}
CustomAuthenticationEntryPoint.java
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ae) throws IOException, ServletException {
log.info("Pre-authenticated entry point called. Rejecting access");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}
what i want to achieve is authenticate users using loging form on browser in order to access protected ressources , but i don't know how in this configuration.
example :
when i access to /product , it shows all products cos it's not secured , but /product/3 for example is protected so it shows a blank webpage with error access denied , i want to show loging form.
when
| |
doc_2251
|
I saw some answers on stack overflow for displaying download progress, but i want to notify my users about upload progress and did not find any solution.
Here is my code:
public static async Task<string> PostFileAsync (Stream filestream, string filename, int filesize) {
var progress = new System.Net.Http.Handlers.ProgressMessageHandler ();
//Progress tracking
progress.HttpSendProgress += (object sender, System.Net.Http.Handlers.HttpProgressEventArgs e) => {
int progressPercentage = (int)(e.BytesTransferred*100/filesize);
//Raise an event that is used to update the UI
UploadProgressMade(sender, new System.Net.Http.Handlers.HttpProgressEventArgs(progressPercentage, null, e.BytesTransferred, null));
};
using (var client = HttpClientFactory.Create(progress)) {
using (var content = new MultipartFormDataContent ("------" + DateTime.Now.Ticks.ToString ("x"))) {
content.Add (new StreamContent (filestream), "Filedata", filename);
using (var message = await client.PostAsync ("http://MyUrl.example", content)) {
var result = await message.Content.ReadAsStringAsync ();
System.Diagnostics.Debug.WriteLine ("Upload done");
return result;
}
}
}
}
Some sort of progress is displayed, but when the progress reaches 100%, the file is not uploaded yet. Message "Upload done" is also printed some time after i have received the last progress message.
Maybe the progress is displaying bytes sent out of the device and not already uploaded bytes, so when it says, that it is 100%, all of the bytes are just sent out but not yet received by the server?
Edit: Tried this solution: https://forums.xamarin.com/discussion/56716/plans-to-add-webclient-to-pcl and it works a bit better.
A: Simplest way to upload file with progress
You can get accurate progress by tracking the Position of the FileStream of the file that you are going to upload.
This demonstrates how to do that.
FileStream fileToUpload = File.OpenRead(@"C:\test.mp3");
HttpContent content = new StreamContent(fileToUpload);
HttpRequestMessage msg = new HttpRequestMessage{
Content=content,
RequestUri = new Uri(--yourUploadURL--)
}
bool keepTracking = true; //to start and stop the tracking thread
new Task(new Action(() => { progressTracker(fileToUpload, ref keepTracking); })).Start();
var result = httpClient.SendAsync(msg).Result;
keepTracking = false; //stops the tracking thread
And progressTracker() function is defined as
void progressTracker(FileStream streamToTrack, ref bool keepTracking)
{
int prevPos = -1;
while (keepTracking)
{
int pos = (int)Math.Round(100 * (streamToTrack.Position / (double)streamToTrack.Length));
if (pos != prevPos)
{
Console.WriteLine(pos + "%");
}
prevPos = pos;
Thread.Sleep(100); //update every 100ms
}
}
A: Try something like this:
I faced same issue. I fixed it by implementing custom HttpContent. I use this object to track percentage of upload progress, you can add an event to and listen it. You should customize SerializeToStreamAsync method.
internal class ProgressableStreamContent : HttpContent
{
private const int defaultBufferSize = 4096;
private Stream content;
private int bufferSize;
private bool contentConsumed;
private Download downloader;
public ProgressableStreamContent(Stream content, Download downloader) : this(content, defaultBufferSize, downloader) {}
public ProgressableStreamContent(Stream content, int bufferSize, Download downloader)
{
if(content == null)
{
throw new ArgumentNullException("content");
}
if(bufferSize <= 0)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
this.content = content;
this.bufferSize = bufferSize;
this.downloader = downloader;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Contract.Assert(stream != null);
PrepareContent();
return Task.Run(() =>
{
var buffer = new Byte[this.bufferSize];
var size = content.Length;
var uploaded = 0;
downloader.ChangeState(DownloadState.PendingUpload);
using(content) while(true)
{
var length = content.Read(buffer, 0, buffer.Length);
if(length <= 0) break;
downloader.Uploaded = uploaded += length;
stream.Write(buffer, 0, length);
downloader.ChangeState(DownloadState.Uploading);
}
downloader.ChangeState(DownloadState.PendingResponse);
});
}
protected override bool TryComputeLength(out long length)
{
length = content.Length;
return true;
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
content.Dispose();
}
base.Dispose(disposing);
}
private void PrepareContent()
{
if(contentConsumed)
{
// If the content needs to be written to a target stream a 2nd time, then the stream must support
// seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target
// stream (e.g. a NetworkStream).
if(content.CanSeek)
{
content.Position = 0;
}
else
{
throw new InvalidOperationException("SR.net_http_content_stream_already_read");
}
}
contentConsumed = true;
}
}
Refer :
*
*https://github.com/paulcbetts/ModernHttpClient/issues/80
*Progress bar for HttpClient uploading
*https://forums.xamarin.com/discussion/18649/best-practice-to-upload-image-selected-to-a-web-api
A: This is because you are doing the math wrong.
Change : int progressPercentage = (int)(e.BytesTransferred*100/filesize);
To : int progressPercentage = (int)(e.BytesTransferred/filesize) *100;
use this code instead:
double bytesOut = double.Parse(e.BytesTransferred.ToString());
double totalBytes = double.Parse(filesize.ToString());
double percentage = bytesOut / totalBytes * 100;
or you can simply use e.ProgressPercentage
| |
doc_2252
|
type Review =
{ MovieName: string;
Rating: double }
type Critic =
{ Name: string;
Ratings: Review[] }
let theReviews = [{ MovieName = "First Movie"; Rating = 5.5 }; { MovieName = "Second Movie"; Rating = 7.5 };]
let theCritic = { Name = "The Critic"; Ratings = [{ MovieName = "First Movie"; Rating = 5.5 }; { MovieName = "Second Movie"; Rating = 7.5 };] }
"the reviews" line is working fine but I can't get the "theCritict" line to work. The error I'm getting is:
Error 1 This expression was expected to have type
Review []
but here has type
'a list
How do I get this to work?
A: Array literals use [| ... |] rather than [ ... ] which are list literals - you need something like
let theCritic = { Name = "The Critic"; Ratings = [|{ MovieName = "First Movie"; Rating = 5.5 }; { MovieName = "Second Movie"; Rating = 7.5 };|] }
This explains the error - you have used a list literal instead of an array literal
A: actually you're using array in your Review definition and list in the implementation..and these are really different beasts, list are inmutables (better for concurrency) and support pattern matching while arrays are mutables..I recommend you keep using list except for long collections (really longs)
if you wish keep using list you can do it:
type Review =
{ MovieName: string;
Rating: double }
type Critic =
{ Name: string;
Ratings: Review list }
here you've a more detailed list about differences between list and arrays:
http://en.wikibooks.org/wiki/F_Sharp_Programming/Arrays#Differences_Between_Arrays_and_Lists ...
| |
doc_2253
|
This does work when clicking the button, but the process I want is:
*
*Add an onClick to the button without downloading the file straight away
*In the onClick event, show a loader
*Then download the file
*Then hide the loader when the file has downloaded
<ExcelFile
filename="Companies"
element={<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>}>
<ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies">
<ExcelColumn label="Company Name" value="name"/>
<ExcelColumn label="Address" value="address"/>
<ExcelColumn label="Town" value="town"/>
<ExcelColumn label="Postcode" value="postcode"/>
<ExcelColumn label="Phone" value="telephone"/>
<ExcelColumn label="Website" value="website"/>
</ExcelSheet>
const downloadCompanies = e => {
setDownloadingLoader(true)
// Download file now
}
// Some event listener when the file has downloaded to hide loader
Does anyone know it's possible to achieve this with this library? Any help would be greatly appreciated.
A: not sure if you are still looking for an answer; I needed to achieve the same thing; what I think I am going to do, is having my own button other than the Download button listed above; onclick event of that button I would trigger the click event for the button attached with ExcelFile. You would obviously change
<ExcelFile
filename="Companies"
element={<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>}>
<ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies">
to
<ExcelFile
filename="Companies"
element={<Button innerRef={this.buttonRef}></Button>}>
<ExcelSheet data={companyExport.length > 0 && companyExport} name="Companies">
Then you can have your own button
<Button variant="dark-green" onClick={downloadCompanies}>Download</Button>
And in your downloadCompanies method you'll do following
if (this.buttonRef.current !== null) {
this.buttonRef.current!.click();
}
This is the best I think we can do with this component, let me know if you ended up with a better way or decided to use another component, thanks!
| |
doc_2254
|
struct X
{
template <typename Iter>
X(Iter a, Iter b) {}
template <typename Iter>
auto f(Iter a, Iter b)
{
return X(a, b);
}
};
In the "C++ Templates, The Complete Guide" 2nd edition, there was the previous example about the subtitles of implicit deduction guides with injected class names. The author mentioned that class argument deduction is disabled for injected class names because the type of the return of f would be X<Iter> due to the implicit deduction guide. But I believe the implicit deduction guide for a template constructor would rather look like the one below.
template <typename T, typename Iter>
X(Iter a, Iter b) -> X<T>;
My question is how would the class template argument types even be deduced in that case T and Iter are two distinct types and the parameters types only rely on Iter. Also even if T could be deduced somehow, T and Iter are independent so deducing Iter from the arguments should not imply that X has type X<Iter> right? Is this some error with the text in the book or should the deduction guide look different from what I thought?
A: You are correct. The implicitly generated deduction guide would indeed look like the one you wrote. And template argument deduction could never deduce T from it. That indeed won't cause a problem. The problem is with user supplied deduction guides. Like this:
template <typename Iter>
X(Iter a, Iter b) -> X<typename Iter::value_type>;
Which are often added to allow class template argument deduction from iterators. That one could wreak havoc if the injected class name did not suppress argument deduction. The authors may have overlooked the need to add that deduction guide to demonstrate the problem.
Here's an illustration of the problem:
auto v = std::vector<int>{1, 2};
auto x1 = X<float>(begin(v), end(v));
auto x2 = x1.f(begin(v), begin(v));
What's the type of x2? If we read the class template definition, we expect it to be X<float> as it would be in C++14, but if class template argument deduction isn't turned off and we add our deduction guide, we'll get X<int>!
Imagine existing code bases where types suddenly shifted after moving to C++17. That would be very bad.
A: I do NOT think the authors have to add any deduction guides to demonstrate the problem here. In my opinion, we can rewrite the definition of X<T>::f as follows:
template <typename Iter>
auto f(Iter b, Iter e){
X ret(b,e);
return ret;
}
If C++ don’t disable class template argument deduction (CTAD) here, this initialization of ret is where CTAD will kick in and gets the type X<Iter>. In Unslander Monica’s example above, x2 will have a more complicated type X<typename std::vector<int>::iterator>. This is why the authors don’t elaborate on it with deduction guides.
| |
doc_2255
|
executing gpml startup script...
warning: addpath: /cov: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /doc: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /inf: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /lik: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /mean: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /prior: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
warning: addpath: /util: No such file or directory
warning: called from
startup at line 8 column 15
/usr/local/Cellar/octave/4.2.2_1/share/octave/4.2.2/m/startup/octaverc at line 31 column 3
I tried to search online for resources that guide you through the installation, but could not find any resource. Any help on this issue is highly appreciated.
| |
doc_2256
|
Place debug information in separate TDS file
Is there any different with the following combination when compile a project:
*
*Checked "Debug Information" and Checked "Place debug information in separate TDS file"
*Unchecked "Debug Information" and Checked "Place debug information in separate TDS file"
I feel that once "Place debug information in separate TDS file" was checked, checked or unchecked "Debug Information" option doesn't play any role in the compilation.
A: I guess that the "Debug Information" option is only to add debugging information inside the EXE, i.e. create debugging information for some external debuggers or profilers, which are able to extract those from the exe. There are several formats arounds, but most rely on the PE chunked format.
This option has nothing to do with "Place debug information in separate TDS file".
You can select either one, either both, either none.
Edited: more accurate answer
A: Anecdotally, it also has an effect on remote debugging. See my findings in the comments to this blog post on XE remote debugging (which still doesnt work very well).
| |
doc_2257
|
<table>
<tr>
<div id ="test1" style ="display:none">
<th>Test1>
<td><div class="test1"></div></td>
</div>
<div id ="test2" style ="display:none">
<th>Test2>
<td><div class="test2"></div></td>
</div>
</tr>
</table>
This is not hiding TH/td tags. If I try to create different ids for th and td (without using div) and then set it's display as none , then when value of divs(test1 and test2) is populated it comes in second line(result2) rather than getting aligned with TH(Result1)
Any idea how can be it done so that my display is like below:
Result1
Test1 test1Value
Test2 test2value
Result2
Test1
test1Value
Test2
Test2Value
A: As mentioned in the comments, the issue is with the code being invalid. To fix this issue:
*
*Restructure the table in a valid way.
*Add similar classes to the cells related to the same test.
*Hide/show the cells based on the class
For example, here is a demo code based on the HTML above and your comments (I used d3.js as the question is tagged with it):
function hideTest1() {
d3.select("body").selectAll(".test1_cell").style("display", "none");
}
function showTest1() {
d3.select("body").selectAll(".test1_cell").style("display", "table-cell");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<table>
<tr>
<th class="test1_cell">Test1></th>
<td class="test1_cell"><div class="test1">Result Test 1</div></td>
<th class="test2_cell">Test2></th>
<td class="test2_cell"><div class="test2">Result Test 2</div></td>
</tr>
</table>
<button onclick="hideTest1()">Hide Test 1</button>
<button onclick="showTest1()">Show Test 1</button>
Just click on the buttons to show/hide the cells related to test 1. You can also see the demo on this JSFiddle: http://jsfiddle.net/ud9bgo8c/
| |
doc_2258
|
<html>
<head>
<script src="JQuery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Team Search</title>
</head>
<body>
<form action="Student Search Results.php" method="Post">
<center>Team Name: <input type="text" name="TeamName" class="search" id="TeamName">
Teacher Sponsor: <input type="text" name="Teacher" class="search" id="Teacher"></center><hr>
</form>
<script>
$(".search").keyup(function(){
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {query: Search_Data},
cache: false,
success: function(){
alert('The values were sent');
}
});
});
</script>
</body>
</html>
Below is the Student Search Results.php page:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
include "Connection.php";
$searchData = explode('?????', $_POST['Search_Data']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
WHERE club_table.Teacher_Email = teacher_user_table.Teacher Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
mysqli_query($con, $query);
echo $query;
?>
</body>
However, $_POST['Search_Data'] is treated as undefined.
Are there any ideas as to why this may be?
Thank you.
A: The name between brackets in a $_POST['XXX'], must be the name with which the value has been posted, in your case query.
So you can either:
change the value name in your POST data from query to Search_Data :
...
data: {Search_Data: Search_Data},
...
or change the index name in the PHP:
$searchData = explode('?????', $_POST['query']);
| |
doc_2259
|
fun=function(x,y) {x^2+y^2}
where x and y are vectors. I would like to to find the "x" such that x^2+y^2=z, numerically in R. How do I so? I tried using the solve command but I am not sure how to specify...keep vector y the same values, solve/minimize the distance/error from the function x^2+y^2 to z to 0.
A: Following may be helpful:
z = sample(1:100, 100, replace=T)
y = sample(1:100, 100, replace=T)
x = mapply(function(z,y) sqrt(z-y^2), z,y)
dd =data.frame(z=z,y=y,x=x)
dd[!is.na(dd$x),]
z y x
51 27 2 4.795832
54 78 5 7.280110
66 74 5 7.000000
70 33 1 5.656854
83 81 9 0.000000
100 29 1 5.291503
A: Here's a solution involving uniroot:
fun <- function(x,y) x^2 + y^2
solfun <- function(z,y) {
if (y^2 > z) return(NaN)
return(uniroot(function(x) z - fun(x,y), c(0,1e10))$root)
}
z <- sample(1:100,5,repl=TRUE)
y <- sample(1:100,5,repl=TRUE)
unlist(Map(solfun,z,y))
As with any root finding algorithm, it can only get approximate answers:
> solfun(20,3)
[1] 3.31661
> solfun(10,3)
[1] 0.9999985
While the above function works on individual pairs of z and y values, by using Map we can apply the function to vectors.
set.seed(4)
z <- sample(1:100,5,repl=TRUE)
y <- sample(1:100,5,repl=TRUE)
> unlist(Map(solfun,z,y))
[1] NaN NaN NaN NaN 4.242638
Note that the overwhelming majority of z,y pairs have complex roots.
| |
doc_2260
|
location /pass/ {
proxy_pass http://localhost:9999/pass/;
proxy_redirect off;
proxy_set_header Host $host;
}
This is working as expected - /pass requests are forwarded to the app running on port 9999.
Now, what I want to do is make the port forwarding part dynamic as follows :
location /pass/<input> {
{a $port variable here that is evaluated via a script (php?)}
proxy_pass http://localhost:$port/pass/;
proxy_redirect off;
proxy_set_header Host $host;
}
Requests to /pass/ABCD1234 should be forwarded to port 9898 and Requests to /pass/ABCD5678 should be forwarded to port 9797.
Note that the flow is dynamic - so, the mapping from ABCD1234 to 9898 should happen through some sort of scripting (PHP maybe?) and based on the output of the script (a port) the proxy_pass should forward the request to that port.
Please Help in this regard.
UPDATE :
Instead of getting the proxy_pass port from URI input, I would like to get this going with a cookie. So, here is the updated code block :
location /pass/ {
add_header X-debug-message $host always;
add_header X-debug-message $cookie_sdmport;
set $proxyurl http://127.0.0.1:$cookie_theport/pass/;
add_header X-debug-message $proxyurl;
proxy_pass $proxyurl;
proxy_redirect off;
proxy_set_header Host $host;
}
With this code, there is looping 301 redirect back to the browser. The moment I switch back to static port, it works again! strange! The $proxyurl in the X-debug-message looks correct on the browser. So, wondering why proxy_pass is doing a 301!
UPDATE 2:
Finally got the forwarding working with following setup:
set $targetIP 127.0.0.1;
set $targetPort $cookie_passport;
proxy_pass http://$targetIP:$targetPort$request_uri;
Not sure why the solution as posted in above keeps spinning with a 301 - I guess nginx does not like mixing dynamic and static parts in the proxy_pass param
Thank You.
A: You can do this using the auth_request module. It's not built by default though, you can find out if you have it by running the following:
nginx -V 2>&1 | grep -qF -- --with-http_auth_request_module && echo ":)" || echo ":("
If you see a smiley face then you are good to go.
location ~* /pass/(.*) { <- regex capture for your variable
auth_request /auth; <- location to process request
auth_request_set $proxyurl http://localhost:$upstream_http_x_port/pass/; <- set $proxyurl using value returned in x-port header of your php script
add_header x-my-variable $1; <- Pass variable from regex capture to auth location
proxy_pass $proxyurl;
}
Then a location to handle the auth subrequests:
location /auth {
internal; <- make location only accessible to internal requests from Nginx
proxy_set_header x-my-variable $http_x_my_variable; <- pass variable to php
proxy_pass_request_body off; <- No point sending body to php
proxy_set_header Content-Length "";
proxy_pass http://your-php-script/file.php;
}
This module is actually meant for access control, so if your php script returns response code 200 then client will be allowed access, if it returns 401 or 403 then access will be denied. Is you dont care about that then just set it to always return 200.
Do whatever evaluation you need and have your php return the port in the header defined earlier:
header('X-Port: 9999');
This now sets the variable for your proxy_pass directive port number and Nginx does the rest.
| |
doc_2261
|
I thought I had found a solution, but c.bind_all won't call my function. I don't get any errors in the shell, and it will call other functions.
from tkinter import *
from random import randint
from time import sleep, time
# Window size
window_height = 500
window_width = 800
ship_speed = 10 # Sets how many pixels to move the ship when a key is pressed
min_bubble_r = 10 # Minimum size of each bubble
max_bubble_r = 30 # Maximum size of each bubble
max_bubble_speed = 4 # Maximum speed of each bubble
gap = 100 # How far across the screen to spawn the bubbles (higher is further right)
bubble_chance = 50 # The chance of a bubble being created
# Changes the direction of the ship depending on which key is pressed
def ship_direction(event):
global ship_direction # Takes the ship direction variable from outside the function
if event.keysym == "Up":
ship_direction = "Up"
elif event.keysym == "Down":
ship_direction = "Down"
elif event.keysym == "Right":
ship_direction = "Right"
elif event.keysym == "Left":
ship_direction = "Left"
# Creates a bubble and adds its info to the lists
def create_bubble():
# Sets the bubble position on the canvas
x = window_width + gap
y = randint(0, window_height)
r = randint(min_bubble_r, max_bubble_r) # Picks a random size for the bubble between the min and max
id1 = c.create_oval(x-r, y-r, x+r, y+r, outline="white") # Creates the bubble shape
# Adds the ID, radius and speed of the bubble to the lists
bubble_id.append(id1)
bubble_r.append(r)
bubble_speed.append(randint(1, max_bubble_speed))
# Moves the ship depending on its direction
ship_direction = str() # Creates an empty string for the ship's movement direction
def move_ship():
if ship_direction == "Up":
c.move(ship_part1, 0, -ship_speed)
c.move(ship_part2, 0, -ship_speed)
elif ship_direction == "Down":
c.move(ship_part1, 0, ship_speed)
c.move(ship_part2, 0, ship_speed)
elif ship_direction == "Right":
c.move(ship_part1, ship_speed, 0)
c.move(ship_part2, ship_speed, 0)
elif ship_direction == "Left":
c.move(ship_part1, -ship_speed, 0)
c.move(ship_part2, -ship_speed, 0)
# Goes through each existing bubble and moves them
def move_bubbles():
# Runs once for each existing bubble
for i in range(len(bubble_id)):
c.move(bubble_id[i], -bubble_speed[i], 0) # Moves the bubble depending on its speed
# Gets the co-ordinates of a bubble
def get_coordinates(id_number):
pos = c.coords(id_number) # Gets the co-ordinates
x = (pos[0] + pos[2])/2 # Works out the x co-ordinate of the middle of the bubble
y = (pos[1] + pos[3])/2 # Works out the y co-ordinate of the middle of the bubble
return x, y
window = Tk() # Creates a new window
window.title("Bubble Blaster") # Title in the top bar
c = Canvas(window, width=window_width, height=window_height, bg="#4269dd") # Creates a canvas that can be drawn on
c.pack()
ship_part1 = c.create_polygon(10, 10, 10, 50, 50, 10, 50, 50, fill="white") # Creates the centre part of the ship
ship_part2 = c.create_oval(3, 3, 57, 57, outline="white") # Creates the circle part of the ship
ship_r = 27 # Sets the ship's radius (for colisions
mid_x = window_width / 2 # Sets the page midway point on the X axis
mid_y = window_height / 2 # Sets the page midway point on the Y axis
c.move(ship_part1, mid_x-ship_r, mid_y-ship_r) # Moves part 1 of the ship to the centre of the page
c.move(ship_part2, mid_x-ship_r, mid_y-ship_r) # Moves part 2 of the ship to the centre of the page
c.bind_all("<Key>", ship_direction) # Runs the ship_direction function whenever a key is pressed
# Creates empty lists to store the ID, radius and speed of each bubble
bubble_id = list()
bubble_r = list()
bubble_speed = list()
# Main loop
while True:
if randint(1, bubble_chance) == 1:
create_bubble()
move_ship()
move_bubbles()
window.update() # Redraws the newly moved objects
sleep(0.01)
A: Your problem is simply that you have two global objects with the same name: a variable named ship_direction and a function named ship_direction. When you create the variable, it overwrites the function, so the function no longer exists.
If you rename your function from ship_direction to change_ship_direction (or any other name), and also change the binding, your code will work.
A:
your problem was that you are trying to call a function that is not yet defined. So i did some replacing of your code but did not need to add a single character to it for it to work. here you go
from tkinter import *
from random import randint
from time import sleep, time
# Window size
window_height = 500
window_width = 800
ship_speed = 10 # Sets how many pixels to move the ship when a key is pressed
min_bubble_r = 10 # Minimum size of each bubble
max_bubble_r = 30 # Maximum size of each bubble
max_bubble_speed = 4 # Maximum speed of each bubble
gap = 100 # How far across the screen to spawn the bubbles (higher is further right)
bubble_chance = 50 # The chance of a bubble being created
window = Tk() # Creates a new window
window.title("Bubble Blaster") # Title in the top bar
c = Canvas(window, width=window_width, height=window_height, bg="#4269dd") # Creates a canvas that can be drawn on
c.pack()
ship_part1 = c.create_polygon(10, 10, 10, 50, 50, 10, 50, 50, fill="white") # Creates the centre part of the ship
ship_part2 = c.create_oval(3, 3, 57, 57, outline="white") # Creates the circle part of the ship
ship_r = 27 # Sets the ship's radius (for colisions
mid_x = window_width / 2 # Sets the page midway point on the X axis
mid_y = window_height / 2 # Sets the page midway point on the Y axis
c.move(ship_part1, mid_x-ship_r, mid_y-ship_r) # Moves part 1 of the ship to the centre of the page
c.move(ship_part2, mid_x-ship_r, mid_y-ship_r) # Moves part 2 of the ship to the centre of the page
# Changes the direction of the ship depending on which key is pressed
def ship_direction(event):
global ship_direction # Takes the ship direction variable from outside the function
if event.keysym == "Up":
ship_direction = "Up"
elif event.keysym == "Down":
ship_direction = "Down"
elif event.keysym == "Right":
ship_direction = "Right"
elif event.keysym == "Left":
ship_direction = "Left"
c.bind_all("<Key>", ship_direction) # Runs the ship_direction function whenever a key is pressed
# Creates a bubble and adds its info to the lists
def create_bubble():
# Sets the bubble position on the canvas
x = window_width + gap
y = randint(0, window_height)
r = randint(min_bubble_r, max_bubble_r) # Picks a random size for the bubble between the min and max
id1 = c.create_oval(x-r, y-r, x+r, y+r, outline="white") # Creates the bubble shape
# Adds the ID, radius and speed of the bubble to the lists
bubble_id.append(id1)
bubble_r.append(r)
bubble_speed.append(randint(1, max_bubble_speed))
# Moves the ship depending on its direction
ship_direction = str() # Creates an empty string for the ship's movement direction
def move_ship():
if ship_direction == "Up":
c.move(ship_part1, 0, -ship_speed)
c.move(ship_part2, 0, -ship_speed)
elif ship_direction == "Down":
c.move(ship_part1, 0, ship_speed)
c.move(ship_part2, 0, ship_speed)
elif ship_direction == "Right":
c.move(ship_part1, ship_speed, 0)
c.move(ship_part2, ship_speed, 0)
elif ship_direction == "Left":
c.move(ship_part1, -ship_speed, 0)
c.move(ship_part2, -ship_speed, 0)
# Goes through each existing bubble and moves them
def move_bubbles():
# Runs once for each existing bubble
for i in range(len(bubble_id)):
c.move(bubble_id[i], -bubble_speed[i], 0) # Moves the bubble depending on its speed
# Gets the co-ordinates of a bubble
def get_coordinates(id_number):
pos = c.coords(id_number) # Gets the co-ordinates
x = (pos[0] + pos[2])/2 # Works out the x co-ordinate of the middle of the bubble
y = (pos[1] + pos[3])/2 # Works out the y co-ordinate of the middle of the bubble
return x, y
# Creates empty lists to store the ID, radius and speed of each bubble
bubble_id = list()
bubble_r = list()
bubble_speed = list()
# Main loop
while True:
if randint(1, bubble_chance) == 1:
create_bubble()
move_ship()
move_bubbles()
window.update() # Redraws the newly moved objects
sleep(0.01)
What i did was moving the code that creates the window to the top so the window will be created before anything else is called, then i moved the canvas.bind_all function bellow your function that it is supposed to call
edit
Why is this answer downvoted as it provides the correct code and localises the fault in the code?
| |
doc_2262
|
client = bigquery.Client()
query = "DELETE FROM Sample_Dataset.Sample_Table WHERE Sample_Table_Id IN {}".format(primary_key_list)
query_job = client.query(query, location="us-west1")
Where primary_key_list is some python list contains a list of Sample_Table unique id like: [123, 124, 125, ...]
Things working good with small data I retrieve but when the primary_key_list grows, it gives me an error:
The query is too large. The maximum standard SQL query length is
1024.00K characters, including comments and white space characters.
I realize the query will be long enough to reach max query length, and after searching on stack overflow I found out there's a solution to use parameterized queries, so I change my code to this:
client = bigquery.Client()
query = "DELETE FROM Sample_Dataset.Sample_Table WHERE Sample_Table_Id IN UNNEST(@List_Sample_Table_Id)"
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ArrayQueryParameter("List_Sample_Table_Id", "INT64", primary_key_list),
]
)
query_job = client.query(query, job_config=job_config)
It stops giving me maximum standard SQL query length, but returns me another error exception, any idea to delete bulk rows from Big Query?
I don't know if this information is useful or not but, I'm running this python code on google cloud Dataproc, and this is just some function I recently added, before I add this function everything is working, and here's the log I've got from running delete using parameterized queries.
Traceback (most recent call last):
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 320, in _send_until_done
return self.connection.send(data)
File "/opt/conda/default/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1737, in send
self._raise_ssl_error(self._ssl, result)
File "/opt/conda/default/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1639, in _raise_ssl_error
raise SysCallError(errno, errorcode.get(errno))
OpenSSL.SSL.SysCallError: (32, 'EPIPE')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1244, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1290, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1239, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1065, in _send_output
self.send(chunk)
File "/opt/conda/default/lib/python3.7/http/client.py", line 987, in send
self.sock.sendall(data)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 331, in sendall
sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 326, in _send_until_done
raise SocketError(str(e))
OSError: (32, 'EPIPE')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/conda/default/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/util/retry.py", line 368, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1244, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1290, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1239, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/opt/conda/default/lib/python3.7/http/client.py", line 1065, in _send_output
self.send(chunk)
File "/opt/conda/default/lib/python3.7/http/client.py", line 987, in send
self.sock.sendall(data)
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 331, in sendall
sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
File "/opt/conda/default/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 326, in _send_until_done
raise SocketError(str(e))
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError("(32, 'EPIPE')"))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/tmp/a05a15822be04a9abdc1ba05e317bb2f/ItemHistory-get.py", line 92, in <module>
delete_duplicate_pk()
File "/tmp/a05a15822be04a9abdc1ba05e317bb2f/ItemHistory-get.py", line 84, in delete_duplicate_pk
query_job = client.query(query, job_config=job_config, location="asia-southeast2")
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/bigquery/client.py", line 2893, in query
query_job._begin(retry=retry, timeout=timeout)
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/bigquery/job/query.py", line 1069, in _begin
super(QueryJob, self)._begin(client=client, retry=retry, timeout=timeout)
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/bigquery/job/base.py", line 438, in _begin
timeout=timeout,
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/bigquery/client.py", line 643, in _call_api
return call()
File "/opt/conda/default/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/opt/conda/default/lib/python3.7/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/_http.py", line 434, in api_request
timeout=timeout,
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/_http.py", line 292, in _make_request
method, url, headers, data, target_object, timeout=timeout
File "/opt/conda/default/lib/python3.7/site-packages/google/cloud/_http.py", line 330, in _do_request
url=url, method=method, headers=headers, data=data, timeout=timeout
File "/opt/conda/default/lib/python3.7/site-packages/google/auth/transport/requests.py", line 470, in request
**kwargs
File "/opt/conda/default/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/opt/conda/default/lib/python3.7/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/opt/conda/default/lib/python3.7/site-packages/requests/adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(32, 'EPIPE')"))
A: As @blackbishop mention, you can try to upgrade requests to the latest version (in my case it solve the problem) but since I tried to update bulk rows (let's say 500.000+ row in Big Query, which every row have a unique id), turns out it gives me a timeout with small machine type Dataproc clusters that I used (if someone has a resource to try with better Dataproc cluster and success please feel free to edit this answer).
So I go with the Merge statement as documented here:
https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement
The script would be like this to update existing rows (assuming I have the new data I retrieve and already load it to Staging_Sample_Dataset.Staging_Sample_Table):
def merge_data():
client = bigquery.Client()
query = """MERGE INTO Sample_Dataset.Sample_Table st
USING Staging_Sample_Dataset.Staging_Sample_Table ss
ON st.Sample_Table_Id = ss.Sample_Table_Id
WHEN MATCHED UPDATE SET st.Your_Column = ss.Your_Column -- and the list goes on...
WHEN NOT MATCHED THEN INSERT ROW
"""
query_job = client.query(query, location="asia-southeast2")
results = query_job.result()
or I could delete bulk rows and call another function to load after this function executed:
def bulk_delete():
client = bigquery.Client()
query = """MERGE INTO Sample_Dataset.Sample_Table st
USING Staging_Sample_Dataset.Staging_Sample_Table sst
ON st.Sample_Table_Id = sst.Sample_Table_Id
WHEN MATCHED THEN DELETE
"""
query_job = client.query(query, location="asia-southeast2")
results = query_job.result()
A: the concept is looping the array of the ids you have and run the delete fro each one of them
it is just the structure, not the actual code. so it might need more than just tweaking
set arrlength = ARRAY_LENGTH(primary_key_list)
client = bigquery.Client()
WHILE i < arrlength DO
query = "delete from Sample_Dataset.Sample_Table WHERE Sample_Table_Id=primary_key_list[OFFSET(i)]"
query_job = client.query(query, location="us-west1")
set i = i+1;
END WHILE;
| |
doc_2263
|
Does anyone knows what this problem could be?
I'm using Win7 x64
this is the traceback information displayed on interactive console:
Traceback (most recent call last):
File "C:\Python27\Scripts\xyhome.pyw", line 21, in <module>
xyhome.main()
File "C:\Python27\lib\site-packages\xy\xyhome.pyw", line 689, in main
form = MainWindow(options)
File "C:\Python27\lib\site-packages\xy\xyhome.pyw", line 134, in __init__
self.scanstartup()
File "C:\Python27\lib\site-packages\xy\xyhome.pyw", line 574, in scanstartup
default_startup()
File "C:\Python27\lib\site-packages\xy\config.py", line 85, in default_startup
filename = osp.join(STARTUP_PATH, CONF.get(None, 'startup'))
File "C:\Python27\lib\ntpath.py", line 109, in join
path += "\\" + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 17: ordinal
not in range(128)
A: This is a known bug in pythonxy: http://code.google.com/p/pythonxy/issues/detail?id=146
The problem is that your home path contains non-ASCII characters; you would probably have to run it from a user without non-ASCII chars in the home path to make it work for now, while there are patches in the bug report comments, they do not seem to work as intended.
A: Do you have any non-ascii characters in your path? If so, maybe you would like to change your installation path. It seems that it has a problem with the character "7".
>>> chr(231)
'\xe7'
>>> chr(55)
'7'
My guess is that your 7 in C:\Python27\ is not really a 7.
| |
doc_2264
|
I thought that when the writer opens the file with FileShare.Read, the reader would be able to access the file, but it produces an error saying that the file is being used by another process.
Writer Application:
FileStream fs = new FileStream("file.log", FileMode.Open, FileAccess.Write, FileShare.Read);
BinaryWriter writer = new BinaryWriter(fs);
Reader Application:
BinaryReader reader = new BinaryReader(File.OpenRead("file.log"));
How do I prevent this error?
A: Can you try specifying FileShare.Read while reading the file also? Instead of directly using File.OpenRead use FileStream with this permission.
Also, for logging, you can use log4Net or any other free logging framework which manages logging so efficiently and we do not have to manage writing to files.
A: o read a locked file you are going to need to provide more flags for the FileStream.
Code such as below.
using (var reader = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Read,FileShare.ReadWrite))
{
using (var binary = new BinaryReader(reader))
{
//todo: add your code
binary.Close();
}
reader.Close();
}
This would open the file for reading only with the share mode of read write. This can be tested with a small app. (Using streamreader\write instead of binary)
static Thread writer,
reader;
static bool abort = false;
static void Main(string[] args)
{
var fs = File.Create("D:\\test.txt");
fs.Dispose();
writer = new Thread(new ThreadStart(testWriteLoop));
reader = new Thread(new ThreadStart(testReadLoop));
writer.Start();
reader.Start();
Console.ReadKey();
abort = true;
}
static void testWriteLoop()
{
using (FileStream fs = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Write, FileShare.Read))
{
using (var writer = new StreamWriter(fs))
{
while (!abort)
{
writer.WriteLine(DateTime.Now.ToString());
writer.Flush();
Thread.Sleep(1000);
}
}
}
}
static void testReadLoop()
{
while (!abort)
{
Thread.Sleep(1000);
using (var reader = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var stream = new StreamReader(reader))
{
Console.WriteLine(stream.ReadToEnd());
stream.Close();
}
reader.Close();
}
}
}
I realize the example above is pretty simple but the fact still remains that the "testWriteLoop" never releases the lock.
Hope this helps
| |
doc_2265
|
Ultimately, I would like to select all factors in a df/tibble and exclude certain variables by name.
Example:
df <- tibble(A = factor(c(0,1,0,1)),
B = factor(c("Yes","No","Yes","No")),
C = c(1,2,3,4))
Various attempts:
Attempt 1
df %>%
select_if(function(col) is.factor(col) & !str_detect(names(col), "A"))
Error in selected[[i]] <- .p(.tbl[[tibble_vars[[i]]]], ...) : replacement has length zero
Attempt 2
df %>%
select_if(function(col) is.factor(col) & negate(str_detect(names(col)), "A"))
Error: Can't convert a logical vector to function Call `rlang::last_error()` to see a backtrace
Attempt 3
df %>%
select_if(function(col) is.factor(col) && !str_detect(names(col), "A"))
Error: Only strings can be converted to symbols Call `rlang::last_error()` to see a backtrace
Attempt 4
df %>%
select_if(is.factor(.) && !str_detect(names(.), "A"))
Error in tbl_if_vars(.tbl, .predicate, caller_env(), .include_group_vars = TRUE) : length(.p) == length(tibble_vars) is not TRUE
In the meanwhile, individual conditions have no problem working:
> df %>%
+ select_if(is.factor)
# A tibble: 4 x 2
A B
<fct> <fct>
1 0 Yes
2 1 No
3 0 Yes
4 1 No
> df %>%
+ select_if(!str_detect(names(.), "A"))
# A tibble: 4 x 2
B c
<fct> <dbl>
1 Yes 1
2 No 2
3 Yes 3
4 No 4
The problem probably lies here:
df %>%
select_if(function(col) !str_detect(names(col), "A"))
Error in selected[[i]] <- .p(.tbl[[tibble_vars[[i]]]], ...) : replacement has length zero
However, I have little clue how to fix this.
A: Perhaps I'm missing something, but is there any reason you couldn't do the following:
df <- tibble(A = factor(c(0,1,0,1)),
B = factor(c("Yes","No","Yes","No")),
C = c(1,2,3,4))
df %>% select_if(function(col) is.factor(col)) %>% select_if(!str_detect(names(.), "A"))
# A tibble: 4 x 1
B
<fct>
1 Yes
2 No
3 Yes
4 No
A: Just for completeness, not sure if it is acceptable for you, but base R may save you some pain here (a first, very quick shot):
df[, sapply(names(df),
function(coln, df) !grepl("A", coln) && is.factor(df[[coln]]), df = df),
drop = FALSE]
| |
doc_2266
|
Example of dates:
String dateOne = "2018-10-10"
String dateTwo = "2019-12-20"
And in excel these become
Row One - 10/10/2018
Row Two - 20/12/2019
I've read some similar sort of questions and tried adding a ' to the strings, so:
String dateOne = "'2018-10-10"
String dateTwo = "'2019-12-20"
But in Excel, these ' appear in the rows, whereas they should be "invisible".
I've tried format cell, and the cells then appear the way I want, but on exiting then re-entering the CSV file, the format is changed back. Even if I were to do this, when I click the actual cell (displaying the format I want) the cell contents itself are the 10/10/2018 format, so clearly it's just all "visual".
Also, I've tried enclosing the strings in double quotations, an example below, but this doesn't work, as well:
String dateOne = "\"2018-10-10\""
Any ideas what I can do to get the format I require?
A: Visit the type box and change it from date to custom or simply edit the date format
A: You can put an equal sign "=" in front of your date, like ="2018-10-10".
If I just type that into an Excel cell, it works fine (even tested the result with the N() function which gives me a zero - so it is clearly considered text).
Maybe, this answer here might help you further.
| |
doc_2267
|
A: If all you want to do is insert some content at the cursor, there's no need to find its position explicitly. The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:
function insertNodeAtCursor(node) {
var range, html;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data : node.outerHTML;
range.pasteHTML(html);
}
}
If you would rather insert an HTML string:
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
}
}
UPDATE
Following the OP's comments, I suggest using my own Rangy library, which adds a wrapper to IE TextRange object that behaves like a DOM Range. A DOM Range consists of a start and end boundary, each of which is expressed in terms of a node and an offset within that node, and a bunch of methods for manipulating the Range. The MDC article should provide some introduction.
| |
doc_2268
|
My understanding of the problem is - I am missing out on the Command to open the file after selecting it.
Here is my Code,
thisYear = Year(Date)
'change the display name of the open file dialog
Application.FileDialog(msoFileDialogOpen).Title = _
"Select Input Report"
'Remove all other filters
Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Excel Files Only", "*.xls*")
'Select the start folder
Application.FileDialog(msoFileDialogOpen _
).InitialFileName = "\\driveA\Reports\" & thisYear & ""
Please kindly share your thoughts. Thanks.
A: I assume that you only let selecting one file (i.e. AllowMultiSelect = False).
Dim file As String
Dim myWbk As Workbook
file = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Set myWbk = Workbooks.Open(file)
First line gets the path of the selected file and then second line opens it. Add this to the end of your code.
| |
doc_2269
|
package main
import (
"fmt"
"math/rand"
"time"
"log"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "username:password@tcp(55b5f18rtr8895.sh.cdb.myqcloud.com:7863)/bsk")
if err != nil {
log.Println(err)
}
db.SetConnMaxLifetime(100 * 100)
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(50)
defer db.Close()
db.Ping()
err = db.Ping()
if err != nil {
log.Println(err)
}
}
And the error is:
driver: bad connection
I am sure the mysql host and port is roght.
But i just can't find any problems here, please help me.
A: I used db.Ping() twice, if one was removed than it works.
| |
doc_2270
|
int ignored = 0;
StreamIgnore si;
si << "This part" << " should be" << ignored << std::endl;
I want that when this code runs si will simply ignore the rest of the stream.
The thing is I want this to be as efficient as possible.
One obvious solution would be to have:
template <typename T>
StreamIgnore& opertaor<<(const T& val) {
//Do nothing
return *this;
}
BUT, if the code was something like:
StreamIgnore si;
si << "Fibonacci(100) = " << fib(100) << std::endl;
Then I'll have to calculate fib(100) before the //Do Nothing part.
So, I want to be able to ignore the rest completely without any unnecessary computations.
To make this request make sense, think that StreamIgnore could be a StreamIgnoreOrNot class, and the c'tor decides whether to ignore the stream or not by either returning *this and use the stream, or a new StreamIgnore() instance and ignoring the rest.
I thought about using Macros some how but could't come up with something that enables me to use this syntax (i.e "si << X << Y...").
I would appreciate it if someone could suggest a way to do that.
Thanks
A: I 'd obviously use IOstreams with disabling/enabling the output amounting to setting/clearing std::ios_base::failbit. Doing this will readily prevent formatting and writing the data. It won't prevent evaluation of arguments, though. For that purpose I'd use the logical and operator:
si && si << not_evaluated() << when_not_used();
A: There is no way to do this (without cheating, as you will see below). Your code is only passed the result of fib(100) and as such cannot short-circuit execution here at all.
However, there is a simple hack you can use:
template<typename T> struct is_ignored { static const bool yes = false; };
template<> struct is_ignored<StreamIgnore> { static const bool yes = true; };
#define S(x) if(!is_ignored<remove_reference<decltype(x)>::type>::yes) x
S(x) << "meep\n";
You may have to add some _Pragmas to disable compiler warnings about the fact that this leads to dead code.
| |
doc_2271
|
public class ReloadableWeapon {
private int numberofbullets;
public ReloadableWeapon(int numberofbullets){
this.numberofbullets = numberofbullets;
}
public void attack(){
numberofbullets--;
}
public void reload(int reloadBullets){
this.numberofbullets += reloadBullets;
}
}
with the following interface:
public interface Command {
void execute();
}
and use it like so:
public class ReloadWeaponCommand implements Command {
private int reloadBullets;
private ReloadableWeapon weapon;
// Is is okay to specify the number of bullets?
public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
this.weapon = weapon;
this.reloadBullets = bullets;
}
@Override
public void execute() {
weapon.reload(reloadBullets);
}
}
Client:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters.
This example, alters the execute method to allow for a parameter.
Another example, more close to what I have here, with parameters in the constructor.
Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?
A: I don't think adding parameters into execute will be bad design or violate command pattern.
It totally depends on how you want to use Command Object: Singleton Or Prototype scope.
If you use Prototype scope, you can pass command parameters in Constructor methods. Each command instance has its own parameters.
If you use Singleton scope (shared/reused instance), you can pass command parameters in execute method. The singleton of the command should be thread safe for this case. This solution is a friend of IoC/DI framework too.
A: The very purpose of this pattern is to allow to define actions, and to execute them later, once or several times.
The code you provide is a good example of this pattern : you define the action "reload", that charges the gun with an amount of bullets=10 ammunition.
Now, if you decide to modify this code to add bullets as a parameter, then you completely lose the purpose of this pattern, because you will have to define the amount of ammunition every time.
IMHO, you can keep your code as it is. You will have to define several ReloadWeaponCommand instances, with different value of bullets. Then you may have to use another pattern (such as Strategy) to switch between the commands.
A: Consider a case you have 95 bullets in hand in starting, and you have made 9 commands with 10 bullets and 1 command with 5 bullets. And you have submitted these commands to Invoker, now invoker doesn't have to worry about how much bullets are left. He will just execute the command. On the other hand if invoker has to provide the no of bullets at run time then it could be the case supplied number of bullets are not available.
My point here is that Invoker must not have to worry about any extra information needs to execute the command. And as mentioned in wiki "an object is used to encapsulate all information needed to perform an action or trigger an event at a later time"
A: Using the Command Pattern with Parameters
Consider the related 'Extension Patterns' in order to hold to a Top-Down Control paradigm 'Inversion of Control'.
This pattern, the Command Pattern, is commonly used in concert with the Composite, Iterator, and Visitor Design Patterns.
Commands are 'First Class Objects'. So it is critical that the integrity of their encapsulation is protected. Also, inverting Control From Top Down to Bottom Up, Violates a Cardinal principle of Object Oriented Design, though I see people suggesting it all of the time...
The Composite pattern will allow you to store Commands, in iterative data structures.
Before going any further, and while your code is still manageable, look at these Patterns.
There are some reasonable points made here in this thread. @Loc has it closest IMO, However, If you consider the patterns mentioned above, then, regardless of the scope of your project (it appears that you intend to make a game, no small task) you will be able to remain in control of lower-level dependency. As @Loc pointed out, with 'Dependency Injection' lower class Objects should be kept 'in the dark' when it comes to any specific implementation, in terms of the data that is consumed by them; this is (should be) reserved for the top level hierarchy. 'Programming to Interfaces, not Implementation'.
It seems that you have a notion of this. Let me just point out where I see a likely mistake at this point. Actually a couple, already, you are focused on grains of sand I.e. "Bullets" you are not at the point where trivialities like that serve any purpose, except to be a cautionary sign, that you are presently about to lose control of higher level dependencies.
Whether you are able to see it yet or not, granular parts can and should be dealt with at higher levels. I will make a couple of suggestions. @Loc already mentioned the best practice 'Constructor Injection' loosely qualified, better to maybe look up this term 'Dependency Injection'.
Take the Bullets for e.g. Since they have already appeared on your scope. The Composite Pattern is designed to deal with many differing yet related First Class Objects e.g. Commands. Between the Iterator and Visitor Patterns you are able to store all of your pre-instantiated Commands, and future instantiations as well, in a dynamic data structure, like a Linked List OR a Binary Search Tree even. At this point forget about the Strategy
Pattern, A few possible scenarios is one thing, but It makes no sense to be writing adaptive interfaces at the outset.
Another thing, I see no indication that you are spawning projectiles from a class, bullets I mean. However, even if it were just a matter of keeping track of weapon configurations, and capacities(int items) (I'm only guessing that is the cause of necessary changes in projectile counts) use a stack structure or depending on what the actual scenario is; a circular queue. If you are actually spawning projectiles from a factory, or if you decide to in the future, you are ready to take advantage of Object Pooling; which, as it turns out, was motivated by this express consideration.
Not that anyone here has done this, but I find it particularly asinine for someone to suggest that it is ok to mishandle or disregard a particular motivation behind any established (especially GoF) Design pattern. If you find yourself having to modify a GoF Design pattern, then you are using the wrong one. Just sayin'
P.S. if you absolutely must, why don't you instead, use a template solution, rather than alter an intentionally specific Interface design;
| |
doc_2272
|
Here is my code:
var map = L.map('map', {
crs: L.CRS.Simple,
attributionControl: false
}).setView([0, 0], 2)
L.tileLayer('/chunks/{x}.{y}.png', {
maxNativeZoom: 1,
minNativeZoom: 1,
}).addTo(map)
function ReloadTile(x,y){
// UPDATE TILE HERE Request for example /chunks/{1}.{1}.png depending on input
}
A: First, listen to the tileload and tileunload events of the L.TileLayer to grab references to tiles as they load (and free those references as they unload), e.g.
let myTileLayer = L.tileLayer(...);
let tileRefs = {};
myTileLayer.on('tileload', function(ev) {
tileRefs[ ev.coords.x + ',' + ev.coords.y ] = ev.tile;
});
myTileLayer.on('tileunload', function(ev) {
delete tileRefs[ ev.coords.x + ',' + ev.coords.y ];
});
...so whenever you want to update a tile, you just have to search for it in the data structure.
Remember that in order to reload a HTMLImageElement, you've got to change its src property, e.g.:
function ReloadTile(x,y){
const tile = tileRefs[x + ',' + y];
if (!tile) {
// Tile is not currently loaded on the screen
return;
}
tile.src = "/chunks/{1}.{1}.png";
}
Beware of requesting a URL that your browser has cached. Do your homework regarding cache busting and relevant HTTP headers.
Note that I'm using a javascript Object as key-value data structure, and string concatenation to build up a unique key per tile. You're free to use other data structures (such a Map) and any other method to index the tiles (such as a double-depth data structure for x-y, or triple-depth for x-y-z, or indexing by tile URL). Also note that the sample code is usign only the X and Y coordinates of the tile since your TileLayer seems to have only one zoom level.
A: lThanks for the help!
My final code:
var map = L.map('map', {
crs: L.CRS.Simple,
attributionControl: false
}).setView([0, 0], 2)
const path = '/chunks/{x}.{y}.png?cash={time}'
const layer = L.tileLayer(path, {
maxNativeZoom: 1,
minNativeZoom: 1,
time: 0
}).addTo(map)
function VectorToString(vector) {
return vector.x + "." + vector.y
}
class TileHandler {
constructor(layer){
this.layer = layer
this.layers = {}
this.layer.on('tileload', (tile) => {
this.layers[VectorToString(tile.coords)] = tile
})
this.layer.on('tileunload', (tile) => {
delete this.layers[VectorToString(tile.coords)]
})
}
update(position){
const tile = this.layers[VectorToString(position)]
const url = L.Util.template(tile.target._url, {
...position,
time: new Date().getTime()
})
if (!tile) return
tile.tile.src = url
}
}
| |
doc_2273
|
+-------------------+
|Percentage Amount|
+-------------------+
|50 3000 |
|20 2000 |
|15 1500 |
|15 1500 |
+-------------------+
I want to update my amount of each row based on the TotalAmount i will pass in my procedure.
Example: If i give 50000 then it will re-calculate the amount based on the percentage in the table (3000 will update to 25000 like that...).
How to get the values of Percentage from each row and calculate the amount and update it?
CREATE PROCEDURE P_SAMPLE
(
TOTAL_AMOUNT NUMBER
)
AS
BEGIN
UPDATE LOGIC...
END;
A: It can be done by the simple UPDATE query:
update sample_table set amount = total_amount * percentage/100;
But if you need PLSQL loops you can use Cursor FOR LOOP :
for x in (select distinct percentage from sample_table) loop
update sample_table set AMOUNT = total_amount * x.percentage/100
where percentage = x.percentage;
dbms_output.put_line(x.percentage || ': ' || total_amount * x.percentage/100);
end loop;
| |
doc_2274
|
I would like to ask you how to export each order on a Worksheet Worksheet within each piece of data is a commodity information
The following are examples
<Workbook>
<Worksheet ss:Name="order1">
<Table>
<Row>
<Cell><Data ss:Type="String">Order #</Data></Cell>
<Cell><Data ss:Type="String">SKU</Data></Cell>
<Cell><Data ss:Type="String">Qty</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">1</Data></Cell>
<Cell><Data ss:Type="String">A1</Data></Cell>
<Cell><Data ss:Type="Number">3</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">1</Data></Cell>
<Cell><Data ss:Type="String">A2</Data></Cell>
<Cell><Data ss:Type="Number">5</Data></Cell>
</Row>
</Table>
</Worksheet>
<Worksheet ss:Name="order2">
<Table>
<Row>
<Cell><Data ss:Type="String">Order #</Data></Cell>
<Cell><Data ss:Type="String">SKU</Data></Cell>
<Cell><Data ss:Type="String">Qty</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">2</Data></Cell>
<Cell><Data ss:Type="String">B1</Data></Cell>
<Cell><Data ss:Type="Number">2</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">2</Data></Cell>
<Cell><Data ss:Type="String">B2</Data></Cell>
<Cell><Data ss:Type="Number">3</Data></Cell>
</Row>
</Table>
</Worksheet>
Through the the understanding lib/Varien/Convert/Parser/Xml/Excel.php, Magento itself does not support multi Worksheet Export
I plan to write another one Parser, do multi-Worksheet Export.
But the bigger issue, export the data needs through
app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php the _prepareColumns () processing
But I can not find how to call database
I hope we can help, thank you
A: You can drop the PHPExcel library in 'lib' and Magento will autoload it without further ado in your module (You'll be needing a custom module).
Since you are writing rather than reading you should be able to work with PHPExcel within your existing memory (importing with PHPExcel can be huge).
There are no limits on what you can do with the fine control of PHPExcel, obviously you'll need to iterate your orders too and your module will need a back end.
You can put together a skeleton module, see if you can create a EXcel file (pop some of the demo code in and see if it picks up the classes etc). Then you should be able to export great reports once you have those bits working.
http://phpexcel.codeplex.com/
https://stackoverflow.com/a/4816738/1617149
| |
doc_2275
|
return the top 5 customer ids and their rankings based on their spend
for each store.
There are only 2 tables - payment and customer. There are 2 stores in total.
For the store_id = 2, the rank() gives repeating 1,2,2,3,4,5 values which is 6. I dont know how to choose the 5 with sql code. Since it is actually 6 - i can't "limit 5"
the sqlfiddle is here. I can't make it do the row_number() in sqlfiddle.
My own query:
with help2 as(
select
store_id,
customer.customer_id,
sum(amount) as revenue
from customer inner join payment on
customer.customer_id = payment.customer_id
where store_id = 2
group by
customer.customer_id
order by revenue desc)
select
store_id, customer_id, revenue,
rank() over(order by revenue desc) as ranking2
from help2
order by ranking2 limit 6 -- i dont think there should be limit 6, this is hard coding
the expected answer is :
store_id customer_id revenue ranking
2 526 221.55 1
2 178 194.61 2
2 137 194.61 2
2 469 177.60 3
2 181 174.66 4
2 259 170.67 5
A: The short answer is to use DENSE_RANK(), not RANK(). This will give you the correct ranking numbers that match the linked exercise's sample output.
From What’s the Difference Between RANK and DENSE_RANK in SQL?:
Unlike DENSE_RANK, RANK skips positions after equal rankings. The number of positions skipped depends on how many rows had an identical ranking. For example, Mary and Lisa sold the same number of products and are both ranked as #2. With RANK, the next position is #4; with DENSE_RANK, the next position is #3.
WITH CustomerSpending AS (
SELECT customer_id
,SUM(amount) as revenue
FROM payment
GROUP BY customer_id
)
,CustomerSpendingRanking AS (
SELECT customer.store_id
,customer.customer_id
,CustomerSpending.revenue
,DENSE_RANK() OVER (PARTITION BY customer.store_id ORDER BY CustomerSpending.revenue DESC) as ranking
FROM customer
JOIN CustomerSpending
ON customer.customer_id = CustomerSpending.customer_id
)
SELECT store_id
,customer_id
,revenue
,ranking
FROM CustomerSpendingRanking
WHERE ranking < 6;
| |
doc_2276
|
File 1 has this format:
f 55 SE 0 0 0
re 13 SE 0 0 0
File 2 has this format:
fe 10 f
fe 02 h
fe 02 re
I need to first compare the files to see if the third column values of file 2 are present in the first column of file 1. If they are, I need the entire row, which contains the value present in both files, in file 1 to be printed to an output file. As shown in the example, some of the values in the third column of file 2 are not present in the first column of file 1. I have tried using awk but I am honestly new to programming and am not entirely sure how to go about this.
My expected output looks like this:
f 55 SE 0 0 0
re 02 SE 0 0 0
It should have the same format as file 1, it simply filters out the rows that do not have a first column value the same as the third column value of file 2.
A: EDIT: Adding this solution as OP added expected output now.
awk 'FNR==NR{a[$3]; next} $1 in a' File2 File1
Since you haven't posted sample output so couldn't test it, could you please try following.
awk 'FNR==NR{a[$3]=$1 OFS $2;next} ($1 in a){print $0,a[$1]}' Input_file2 Input_file1
| |
doc_2277
|
*
*(void) publishFeedWithName:(NSString*)name
captionText:(NSString*)caption
imageurl:(NSString*)url
linkurl:(NSString*)href
userMessagePrompt:(NSString*)prompt
actionLabel:(NSString*)label
actionText:(NSString*)text
actionLink:(NSString*)link
targetId:(NSString*)target{
[self postFeedWithName:name
captionText:caption
imageurl:url
linkurl:href
userMessagePrompt:prompt
actionLabel:label
actionText:text
actionLink:link
targetId:target];
}
A: First you need to get the image as a JPG or other transmittable file image. That can be done with UIImageJPEGRepresentation as described about halfway down here: https://stackoverflow.com/questions/1282830/uiimagepickercontroller-uiimage-memory-and-more
I don't have access right now to the box where I have the Facebook SDK installed and the example app that can upload an image, so I can't tell you the details of how to do that at present. But the Facebook SDK example package shows you how to do it.
| |
doc_2278
|
As you can see in the Ingress file bellow, we have the backend rules to route the traffic to specific services. The problem is that, most of the specific requests like /task/connections/update/advanced/ or /task/connections/update/advanced/ are being sent to the root path / that should only serve the front-end (which works since they use the same container). The problem is that those specific requests are very massive causing the front end API to become unavailable. The specific services run on stronger nodes so they can handle this load, while the front-end api runs on weaker nodes. When I run kubectl get hpa I can see that most of the load (replicas) stays on the API. I even had to increase the max replicas to try to mitigate the issue. I've seen in the logs that some requests are being sent to the specific routes as they should, but the majority is not being sent.
All I wanted to do is to prevent / route to receive those specific requests.
Our ingress looks like this:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/affinity: cookie
nginx.ingress.kubernetes.io/proxy-body-size: 150m
nginx.ingress.kubernetes.io/proxy-connect-timeout: "1200"
nginx.ingress.kubernetes.io/proxy-read-timeout: "1200"
nginx.ingress.kubernetes.io/proxy-send-timeout: "1200"
nginx.ingress.kubernetes.io/upstream-fail-timeout: "1200"
name: ingress-nginx
namespace: default
spec:
tls:
- hosts:
- app.ourdomain.com
- api.ourdomain.com
secretName: ourdomain-certificate
rules:
- host: app.ourdomain.com
http:
paths:
- backend:
serviceName: frontend
servicePort: 80
path: /
- host: api.ourdomain.com
http:
paths:
- backend:
serviceName: api
servicePort: 8000
path: /
- backend:
serviceName: esg
servicePort: 8000
path: /cron/
- backend:
serviceName: esg-bigquery-migration
servicePort: 8000
path: /cron/big-query/
- backend:
serviceName: esg
servicePort: 8000
path: /task/
- backend:
serviceName: esg-trial
servicePort: 8000
path: /task/connections/update/trial/
- backend:
serviceName: esg-advanced
servicePort: 8000
path: /task/connections/update/advanced/
- backend:
serviceName: esg-professional
servicePort: 8000
path: /task/connections/update/professional/
- backend:
serviceName: esg-enterprise
servicePort: 8000
path: /task/connections/update/enterprise/
A: From documentation:
Starting in Version 0.22.0, ingress definitions using the annotation
nginx.ingress.kubernetes.io/rewrite-target are not backwards
compatible with previous versions. In Version 0.22.0 and beyond, any
substrings within the request URI that need to be passed to the
rewritten path must explicitly be defined in a capture group.
In some scenarios the exposed URL in the backend service differs from the specified path in the Ingress rule. Without a rewrite any request will return 404. To circumvent this you can set the annotation ingress.kubernetes.io/rewrite-target to the path expected by the service. Please, refer to documentation to learn more about this. Also, you should add following line to your annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
| |
doc_2279
|
Here is my nginx config file (I have changed the IP and domains for privacy):
server {
listen 80;
server_name my.ip.address example.com www.example.com;
location = /facivon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/tony/vp/vp/config/;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/tony/vp/vp/vp.sock;
}
}
And this is my productions settings.py file:
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '0.0.0.0', 'my.ip.address', 'example.com', '.example.com']
ROOT_URLCONF = "urls.production_urls"
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_SSL_DIRECT = True
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
X_FRAME_OPTIONS = 'DENY'
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'vp',
'USER': 'vp',
'PASSWORD': os.environ["VP_DB_PASS"],
'HOST': 'localhost',
}
}
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL ='media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
And yes my domain is connected to digital ocean.
What could be causing the Bad Request?
Thanks in advance!
EDIT:
For some reason I have more than one error.log for nginx. It has probably something to do with my many attempts on getting this fixed. Below you can find the relevant error.log:
2017/04/23 17:44:56 [alert] 17723#17723: *7 open socket #12 left in connection 4
2017/04/23 17:44:56 [alert] 17723#17723: *10 open socket #13 left in connection 6
2017/04/23 17:44:56 [alert] 17723#17723: *11 open socket #14 left in connection 7
2017/04/23 17:44:56 [alert] 17723#17723: *13 open socket #16 left in connection 9
2017/04/23 17:44:56 [alert] 17723#17723: *14 open socket #17 left in connection 10
2017/04/23 17:44:56 [alert] 17723#17723: *15 open socket #18 left in connection 11
2017/04/23 17:44:56 [alert] 17723#17723: aborting
2017/04/23 23:26:15 [emerg] 20136#20136: unknown directive "cd" in /etc/nginx/sites-enabled/vp:1
2017/04/23 23:27:12 [emerg] 20147#20147: unknown directive "cd" in /etc/nginx/sites-enabled/vp:1
2017/04/23 23:37:43 [alert] 20399#20399: *12 open socket #14 left in connection 7
2017/04/23 23:37:43 [alert] 20399#20399: *7 open socket #18 left in connection 9
2017/04/23 23:37:43 [alert] 20399#20399: aborting
The line: unknown directive "cd" in /etc/nginx/sites-enabled/vp:1 is fixed.
When checking the status of gunicorn I get the following:
sudo systemctl status gunicorn
● gunicorn.service - gunicorn daemon
Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2017-04-23 14:52:07 UTC; 19h ago
Main PID: 16044 (gunicorn)
Tasks: 4
Memory: 86.6M
CPU: 42.667s
CGroup: /system.slice/gunicorn.service
├─16044 /home/tony/vp/vpenv/bin/python3 /home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application
├─16049 /home/tony/vp/vpenv/bin/python3 /home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application
├─16050 /home/tony/vp/vpenv/bin/python3 /home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application
└─16051 /home/tony/vp/vpenv/bin/python3 /home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16044] [INFO] Starting gunicorn 19.7.1
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16044] [INFO] Listening at: unix:/home/tony/vp/vp/vp.sock (16044)
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16044] [INFO] Using worker: sync
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16049] [INFO] Booting worker with pid: 16049
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16050] [INFO] Booting worker with pid: 16050
Apr 23 14:52:07 vp-first gunicorn[16044]: [2017-04-23 14:52:07 +0000] [16051] [INFO] Booting worker with pid: 16051
Apr 23 15:27:51 vp-first systemd[1]: Started gunicorn daemon.
Apr 23 17:12:36 vp-first systemd[1]: Started gunicorn daemon.
Apr 23 17:31:37 vp-first systemd[1]: Started gunicorn daemon.
Apr 23 23:35:18 vp-first systemd[1]: Started gunicorn daemon.
| |
doc_2280
|
<form name="enrollmentform" #enrollmentform="ngForm" novalidate>
<div class='field-container'>
<input type="text" value="" size="25" maxlength="30" placeholder="fullname" [dir]="direction" name="fullname" required #first_name="ngModel" class="floating-input"/>
<div *ngIf="enrollmentform.submitted && full_name.invalid" class="error">
<div class="error-message" *ngIf="first_name.errors.required">{{'First Name is required' | translate}}</div>
</div>
</div>
<div class='field-container'>
<input [dir]="direction" type="text" value="" placeholder="email" name="email" autocomplete="off" [pattern]="emailPattern" required #email="ngModel" />
<div class="error" *ngIf="(email.invalid) && (enrollmentform.submitted || email.dirty || email.touched)">
<div class="error-message" *ngIf="email.errors.required">{{'Email_is_required' | translate}}</div>
<div class="error-message" *ngIf="email.errors.pattern">{{'Please_enter_a_valid_email' | translate}}</div>
</div>
</div>
</form>
How can i show the error message use only english for email when user uses arabic language in email field.
A: Here is a simple example of angular multi-language application using custom translate pipe. Use this type of approach.
You can define your error messages, paragraphs, texts in Language files.
Here assets/languageFiles/en.json
{
"TITLE": "My i18n Application (en)"
}
assets/languageFiles/en.json
{
"TITLE": "My i18n Application (ua)"
}
Translate service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class TranslateService {
data: any = {};
constructor(private http: HttpClient) { }
use(lang: string): Promise<{}> {
return new Promise<{}>((resolve, reject) => {
const langPath = `assets/languageFiles/${lang || 'en'}.json`;
this.http.get<{}>(langPath).subscribe(
translation => {
this.data = Object.assign({}, translation || {});
resolve(this.data);
},
error => {
this.data = {};
resolve(this.data);
}
);
});
}
}
Translate Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from './translate.service';
@Pipe({
name: 'translate',
pure:false
})
export class TranslatePipe implements PipeTransform {
constructor(private translate: TranslateService) {}
transform(key: any): any {
return this.translate.data[key] || key;
}
}
In your html files use in this way using translate file
<h1>
Welcome to {{ 'TITLE' | translate }}!
</h1>
And also you can change the language also.
Please refer the example in the stackblitz.
| |
doc_2281
|
Sample xml file format is as following:
<shows>
<show>
<eventID>10025</eventID>
<name>MARCH Barrel</name>
<ticketURL></ticketURL>
<venue>
<venueID>3648</venueID>
<name>Double Barrel</name>
<address>3770 Las Vegas Blvd. South</address>
<address2></address2>
<city>Las Vegas</city>
<state>NV</state>
<zipcode>89109</zipcode>
<country>US</country>
</venue>
</show>
</shows>
Question:
How, is it possible to store venueID & name in sql server 2008 using C#, as I have a table which contain this type of field ?
A: SQL Server 2005 and up have a datatype called "XML" which you can store XML in - untyped or typed with a XSD schema.
You can basically fill columns of type XML from an XML literal string, so you can easily just use a normal INSERT statement and fill the XML contents into that field.
OR
You can use the function OPENXML and stored procedure sp_xml_preparedocument to easily convert your XML into rowsets.
EDIT: Try This
String xmlFile = @" <shows>
<show>
<eventID>10025</eventID>
<name>MARCH Barrel</name>
<ticketURL></ticketURL>
<venue>
<venueID>3648</venueID>
<name>Double Barrel</name>
<address>3770 Las Vegas Blvd. South</address>
<address2></address2>
<city>Las Vegas</city>
<state>NV</state>
<zipcode>89109</zipcode>
<country>US</country>
</venue>
</show>
</shows>";
DataSet ds = ConvertXMLToDataSet(xmlFile);
foreach (DataTable dt in ds.Tables)
{
//get Your Tables here
}
and Method:
public static DataSet ConvertXMLToDataSet(string xmlData)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xmlData);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch
{
return null;
}
finally
{
if (reader != null) reader.Close();
}
}
A: You can store information in SQL Server XML type field. Following article contains complete information for how to use XML datatype in sql server.
https://www.simple-talk.com/sql/learn-sql-server/working-with-the-xml-data-type-in-sql-server/
| |
doc_2282
|
A: Hi here is a basic example of what you want using :
*
*The HTML content editable property.
*A css class to append a focusout event to the table cell.
*A simple loop to sum all values when one value changes.
$('#tbodyTest >tr').on('focusout', 'td.editable', (e) => {
let target = $(e.target),
parent_row = $(e.target).closest('tr'),
previous_row = parent_row.prev();
setTimeout(() => {
if (!isNaN(target.text())) {
$('#tbodyTest').children('tr').each((i,e)=>{
$(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
})
}else{
target.text("0");
parent_row.find('td').last().text("0");
$('#tbodyTest').children('tr').each((i,e)=>{
$(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
})
}
})
})
.editable {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test" border=1>
<thead>
<th>date</th>
<th>desc</th>
<th>cost</th>
<th>running sum</th>
</thead>
<tbody id="tbodyTest">
<tr>
<td>01-01-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'>1000</td>
<td>1000</td>
</tr>
<tr>
<td>01-02-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
<tr>
<td>01-03-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
<tr>
<td>01-04-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
</tbody>
</table>
Keep in mind that this is a basic example and you will probably add more stuff according to your needs since your ask is simple as well.
Hope it helps
A: Anyone still looking to this.
$('tr').each(function(index, el) {
if (index == 0) {
$(this).find('.running-balance').text($(this).find('.amount').text());
} else {
var prevRow = $(this).prev();
var prevBalance = Number(prevRow.find('.running-balance').text());
var currentAmount = Number($(this).find('.amount').text());
var newBalance = prevBalance + currentAmount;
$(this).find('.running-balance').text(newBalance.toFixed(2));
}
});
td,
th {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Description</th>
<th>Amount</th>
<th>Running Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td class="amount">100</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>b</td>
<td class="amount">150</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>c</td>
<td class="amount">125</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>d</td>
<td class="amount">205</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>e</td>
<td class="amount">50</td>
<td class="running-balance"></td>
</tr>
</tbody>
</table>
| |
doc_2283
|
*
*Controller:
myapp.controller('ClientsCtrl', function ($scope, UserSvc) {
$scope.showForm = UserSvc.frmOpened;
$scope.$watch(function () {
return UserSvc.frmOpened;
}, function () {
$scope.showForm = UserSvc.frmOpened;
console.log('Changed... ' + $scope.showForm);
});
});
*Service
myapp.factory('UserSvc', function ($log, $q, $http) {
return {
frmOpened: false
};
});
*Directive:
myapp.directive('myDirective', ['UserSvc', function (UserSvc) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
angular.element(element).on("click", function () {
var parentElement = $(this).parent();
if (parentElement.hasClass('sample')) UserSvc.frmOpened = true; //This code never update the service
} else {
UserSvc.frmOpened = false; //This code never update the service
}
return false;
});
}
};
}]);
A: .on() is a jQuery method (also included in Angular's jqLite). The code inside the attached event handler lives outside of Angular, so you need to use $apply:
$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life cycle of
exception handling, executing watches.
For example:
element.on("click", function() {
var parentElement = $(this).parent();
scope.$apply(function() {
if (parentElement.hasClass('sample')) {
UserSvc.frmOpened = true;
} else {
UserSvc.frmOpened = false;
}
});
return false;
});
Demo: http://plnkr.co/edit/mCl0jFwzdKW9UgwPYSQ9?p=preview
Also, the element in the link function is already a jqLite/jQuery-wrapped element, no need to perform angular.element() on it again.
A: It looks like you have some brackets where they shouldn't be in your directive. You don't have brackets surrounding the first part of your if statement, but you have a closing bracket before your else. I think this messes up things.
Try using this as your link-function and see if it changes anything:
link: function (scope, element, attrs) {
angular.element(element).on("click", function () {
var parentElement = $(this).parent();
if (parentElement.hasClass('sample')) {
UserSvc.frmOpened = true; //Surrounded this with brackets
} else {
UserSvc.frmOpened = false;
}
return false;
});
}
| |
doc_2284
|
This is what I have at the moment;
function my_form_funnction() {
global $current_user;
$vat_no = get_user_meta( get_current_user_id(), 'vat_number', true );
?>
<form name="setPrices" action="" method="POST">
<label for="lowPrice">Vat Number: </label>
<input type="text" id="vat_number" name="vat_number" value="<?php echo $vat_no ?>" />
<button type="submit">Save</button>
</form>
<?php update_user_meta( get_current_user_id(), 'vat_number', esc_attr($_POST['vat_number']) );
}
But the thing is the php that updates the user meta does so when the page loads, I only want it to do it when the user pressess save.
A: You need to use Ajax to update information on a page without refreshing it. Try jQuery! It is a realy simple way to use Ajax. For example:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<button onclick="javascript:la()">Save or do smth</button>
<div id="a">Here will be included the loadable thing</div>
<script>
function la(){
$("#a").load("/functions.php?func=my_form_function");
}
</script>
And in functions.php you may set:
if(isset($_GET["func"]){
if($_GET["func"] == "my_form_function"){
my_form_funnction();
}
}
| |
doc_2285
|
public class GenericClass<T> {
private final Class<T> type;
public GenericClass(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
}
With that class code is easy to instantiate a new instance of the class with a non-generic type. For example:
GenericClass<String> c = new GenericClass<String>(String.class)
My question is the following. How can I create a new instance of the class with a generic type? Example:
GenericClass<List<String>> c = new GenericClass<List<String>>(...)
If I put List<String>.class the compiler gives me an error. At compile time, which syntax should I use to specify to the constructor the right class of the generic type?
A: A generic doesn't know nor does it care about the generic class being specified, and as such, there's no List<String>.class, only List.class. Did you consider wildcards? What should List<?>.class return? And List<? extends AnotherClass>.class? So no, you can't know what specific class a generic is holding at compile time, basically because it can hold different classes that are only fully specified at runtime.
A: The only way to write generics to class type (and therefore make them available at runtime with reflection) is to create sub class of your GenericClass. Even anonymous inner class does the job:
GenericClass<List<String>> c = new GenericClass<List<String>>(...){};
(pay attention on trailing {}).
A: How about:
public class GenericClass<T> {
Class<T> type;
@SuppressWarnings("unchecked")
public GenericClass() {
Type type = ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof Class<?>)
this.type = (Class<T>)type;
else if (type instanceof ParameterizedType)
this.type = (Class<T>) ((ParameterizedType)type).getRawType();
else
this.type = null;
}
public Class<T> getType() {
return type;
}
}
Usage:
public static void main(String[] args) {
GenericClass<Integer> g = new GenericClass<Integer>() {};
System.out.println(g.getType());
GenericClass<List<String>> g2 = new GenericClass<List<String>>() {};
System.out.println(g2.getType());
}
A: Your issue is that there is only one List class object, which you can get from List.class. But is it Class<List>, Class<List<Object>>, Class<List<String>>, or Class<List<?>>, etc? It can only have one type, and the Java designers chose Class<List> (it's the only safe choice). If you really want a Class<List<String>>, you'll have to do some unchecked casts:
GenericClass<List<String>> c =
new GenericClass<List<String>>((Class<List<String>>)(Class<?>)List.class);
| |
doc_2286
|
library(sf)
library(plotly)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
plot_geo(nc, color = I("red"), fill=I("blue"))
| |
doc_2287
|
A: Easiest way it to add this style to the p enclosing them.
First add a class to the p, like this:
<p class="social-icons-footer">
Then add the style in your css file:
.social-icons-footer {
width: 250px;
display: block;
margin: 0 auto;
}
A: You could utilize
/* style for div parent of links */
div {
display: flex;
justify-content: space-around;
}
To do that wrap all the links in div and apply this to it. See screenshot below.
But in order for it to work properly wrap all images with
<a>
tag.
Notice that flexbox is not yet supported in older browsers in case you require to support them.
screenshot of display: flex
| |
doc_2288
|
import com.cloudbees.plugins.credentials.impl.*;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.*;
Credentials c = (Credentials) new WhateverClassSecretText(
CredentialsScope.GLOBAL,
"my-credential-id",
"Secret Text for something",
"S3cr3t") // TODO find right class here!
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), c)
A: I found a way to do it but I'm still curious if anyone has a better solution.
The class I was looking for is org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl, which actually takes a hudson.util.Secret as the secret string. Here is the code (testable in Jenkins Script Console):
import static com.cloudbees.plugins.credentials.CredentialsScope.GLOBAL
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.SystemCredentialsProvider
import hudson.util.Secret
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl
StringCredentialsImpl credentials = new StringCredentialsImpl(
GLOBAL,
"my-credential-id",
"Secret Text for something",
Secret.fromString("S3cr3t"))
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), credentials)
| |
doc_2289
|
foreach x in File1 ; do grep $x File2.csv >> OUTPUT.csv ; done
bash: foreach: command not found
Here's what I'm working with:
File1
ABCD
EFGH
IJLK
...etc
File2.csv
NODENAME,ABCD,PORTID,LONGNAME,NODEIP,WORKGROUP,etc...
...a whole lot of other entries that might/don't match... etc...
OUTPUT.csv <-- Final file.
I'm looking for (preferably BASH/CSH/KSH/PYTHON[noob]) command line that will one-by-one find/match line individual entries of File1 and output entire line from File2 into File3. File2 is gigantic and I can single grep each of these entries from File1, but need to automate it.
REASON: I have a customer that on one technology (NODENAME) they can match their WORKGROUP, but the File2.csv does not contain WORKGROUP explanations that match, but the ABCD(CircuitID) might exist on more than one Technology platform. The output of each of these NODENAME entries were created as CSV and I was only able to pull matching WORKGROUP from one of the CSVs.
Thanks!!
| |
doc_2290
|
Here is present code -
private ImplClass implObject;
private Future future;
for (Iterator iter = anArrayList.iterator(); iter.hasNext();) {
//Gets a GenericObjectPool Object
implObject = (ImplClass) this.getImplPool().borrowObject();
future = getExecutorServices().submit(implObject);
}
// Wait for Exectuor to complete
while (!future.isDone()) {
try {
Thread.sleep(Global.WaitTime());
} catch (InterruptedException iex) {
}
}
But this is wrong as future waits for only last Thread. Should I create an Array of Futures to monitor each executor ?
A: How about this?:
List<Callable> tasks = new ArrayList<Callable>();
for (Iterator iter = anArrayList.iterator(); iter.hasNext();) {
//Gets a GenericObjectPool Object
implObject = (ImplClass) this.getImplPool().borrowObject();
tasks.add(implObject);
}
List<Future<Object>> futures = getExecutorServices().invokeAll(tasks);
A: ExecutorService has a specific method for that: ExecutorService.invokeAll(tasks)
The ExecutorCompletionService mentioned in Ralf's answer can also be helpful - it allows you to process results by the caller thread as they arrive.
| |
doc_2291
|
I will be calling Javascript from Splunk UI.
What are the splunk configuration changes needs to be done ?
TIA.
| |
doc_2292
|
hi everyone, I'm having trouble using the fullscreen overlay api and would like to ask for help!
follow the steps
*
*Using chrome on Android device, enter full screen overlay mode
*Rotary device.
*Use the back key to exit full screen overlay mode
*Refresh the page
*Wait for the page to load and wait for a few seconds, the screen will become blank
Has anyone encountered the same problem or has a related solution? Thanks!
| |
doc_2293
|
./foo.py train -a 1 -b 2
./foo.py test -a 3 -c 4
./foo.py train -a 1 -b 2 test -a 3 -c 4
I've been trying using two subparsers ('test','train') but it seems like only one can be parsed at the time. Also it would be great to have those subparsers parents of the main parser such that, e.g. command '-a' doesn't have to be added both to the subparsers 'train' and 'test'
Any solution?
A: This has been asked before, though I'm not sure the best way of finding those questions.
The whole subparser mechanism is designed for one such command. There are several things to note:
*
*add_subparsers creates a positional argument; unlike optionals a `positional acts only once.
*'add_subparsers' raises an error if you invoke it several times
*the parsing is built around only one such call
One work around that we've proposed in the past is 'nested' or 'recursive' subparers. In other words train is setup so it too takes a subparser. But there's the complication as to whether subparsers are required or not.
Or you can detect and call multiple parsers, bypassing the subparser mechanism.
From the sidebar
Multiple invocation of the same subcommand in a single command line
and
Parse multiple subcommands in python simultaneously or other way to group parsed arguments
| |
doc_2294
|
The basic logic is that 1. animation should play at a default speed, and when it hits the end, come back at negative half speed. 2. If the animation is triggered again while it is going backwards, it should continue forward as in step 1.
The problem is that the animation gets stuck on the last frame about 20% of the time. The console prints that the frame that it gets stuck on as 0, but it shows the last frame. It also sometimes just jumps to 0 without animating backwards.
Am I missing something stupid?
public GameObject go;
private Animation anim;
private AnimationClip clip;
private float animationLength;
private float limit;
private float originalSpeed = 3;
private string name;
void Start(){
anim = go.GetComponent<Animation>();
anim.wrapMode = WrapMode.Once;
anim.playAutomatically = false;
clip = anim.clip;
clip.legacy = true;
name = anim.clip.name;
animationLength = anim[name].length;
anim[name].speed = 0;
anim.Play(name);
}
void Update(){
if(Input.GetKeyDown("1")){
trigger();
}
animate();
}
void animate(){
limit = animationLength - (animationLength/24f);
if(anim[name].time >= limit){
anim[name].time = limit;
anim[name].speed = -(originalSpeed/2);
}
}
void trigger(){
anim[name].speed = originalSpeed;
anim.Play(name);
}
| |
doc_2295
|
Any ideas why this can't happen?
if the code is like the following
@Path("/cars")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface CarService {
@POST
void create(Car car);
}
it works.
If it is like the below
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface CarService {
@POST
@Path("/cars")
void create(CarDto car);
}
it doesn't.
A: Few things you should aware while writing resource code,
1.You must use the appropriate method like get,post or put based on operation otherwise it throw 405 error.
2.You must specify a unique path to all otherwise it would conflicts. Having a method name as path name is better idea.
3.You should declare the produce and consume type appropriately.
Good luck, code well.
| |
doc_2296
|
let averageReport: any = [1, 2, 3, 4, 5]
let maleData: Array<any> = [];
let femaleData: Array<any> = [];
I loop through average report and push values to maleData and femaleData. I declared the array types as any but still typescript is complaining that "Argument of type 'number' is not assignable to parameter of type 'string'"
There are similar questions with the same question title as this but this is not same as those questions.
here is the code on stackblitz
code,
ngOnInit() {
let averageReport: any = [1, 2, 3, 4, 5]
let maleData: Array<any> = [];
let femaleData: Array<any> = [];
let dateNow = new Date();
let startDate = new Date(dateNow.getTime() - 20000);
averageReport
.map(
x => {
if (x === 1) {
femaleData.push(
{
x: parseInt(startDate.getTime() / 1000), // here is the propblem
y: x.result
})
}
if (x === 2) {
maleData.push(
{
x: parseInt(startDate.getTime() / 1000),
y: x.result
})
}
}
)
}
A: Have a try with this:
I changed "Array" to "any[]", changed .map to for-of, and parseInt to Math.round
ngOnInit() {
let averageReport: any = [1, 2, 3, 4, 5]
let maleData: any[] = [];
let femaleData: any[] = [];
let dateNow = new Date();
let startDate = new Date(dateNow.getTime() - 20000);
for(let report of averageReport) {
if (report === 1) {
femaleData.push(
{
x: Math.round(startDate.getTime() / 1000), // here is the propblem
y: report.result
})
}
if (report === 2) {
maleData.push(
{
x: Math.round(startDate.getTime() / 1000),
y: report.result
})
}
}
}
| |
doc_2297
|
<div id="subscriberApp" class="row">
<div class="col-md-6">
<h2>Subscribers List</h2>
<table class="table">
<thead>
<tr>
<th>Login</th>
<th>Uri</th>
<th>Action</th>
</tr>
</thead>
<tbody class="subscribers-list"></tbody>
</table>
</div>
<div class="col-md-3">
<div>
<h2>Add a Subscriber</h2>
<p><label for="id_login">Login:</label> <input class="form-control" id="id_login" maxlength="100" name="login" style="display:block" type="text" /></p>
<p><label for="id_password">Password:</label> <input class="form-control" id="id_password" maxlength="100" name="password" style="display:block" type="text" /></p>
<p><label for="id_realm">Realm:</label> <input class="form-control" id="id_realm" maxlength="100" name="realm" style="display:block" type="text" /></p>
<p><label for="id_ip_address">Ip address:</label> <input class="form-control" id="id_ip_address" maxlength="100" name="ip_address" style="display:block" type="text" /></p>
<button class="btn btn-success create">Create</button>
</div>
</div>
</div>
<script type="text/template" id="subscribers-tmpl">
<td><span class="login"><%= login %></span></td>
<td><span class="uri"></span></td>
<td><button class="btn btn-warning edit-subscriber">Edit</button> <button class="btn btn-danger remove">Delete</button></td>
</script>
<script src="/static/subscribers/underscore.js"></script>
<script src="/static/subscribers/backbone.js"></script>
<script src="/static/subscribers/script.js"></script>
And here is my backbone script:
var subscribers_model = Backbone.Model.extend({
defaults: {
id: null,
login: null,
password: null,
realm: null,
hotspot_ip: null,
}
});
var subscribers_collection = Backbone.Collection.extend({
url: 'http://example.net/subscribers',
model: subscribers_model,
parse: function(data) {
return data;
}
});
var SubscriberView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#subscribers-tmpl').html()),
initialize: function() {
this.listenTo(this.model, 'destroy', this.remove)
},
render: function() {
var html = this.template(this.model.toJSON());
this.$el.html(html);
return this;
},
events: {
'click .remove': 'onRemove'
},
onRemove: function() {
this.model.destroy();
}
});
var SubscribersView = Backbone.View.extend({
el: '#subscriberApp',
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
},
render: function() {
var $list = this.$('.subscribers-list').empty();
this.collection.each(function(model) {
var item = new SubscriberView({model:model});
var uri = item.model.attributes.uri
item.model.attributes.id = uri.replace('/subscribers/', '');
$list.append(item.render().el);
}, this);
return this;
},
events: {
'click .create': 'onCreate'
},
onCreate: function() {
var self = this;
var $login = this.$('#id_login');
var $password = this.$('#id_password');
var $realm = this.$('#id_realm');
var $ip = this.$('#id_ip_address');
this.collection.create({
login: $login.val(),
password: $password.val(),
realm: $realm.val(),
hotspot_ip: $ip.val()
});
login: $login.val('');
password: $password.val('');
realm: $realm.val('');
hotspot_ip: $ip.val('');
}
});
var subscribers = new subscribers_collection();
var SubsView = new SubscribersView({collection: subscribers});
subscribers.fetch();
So I think that the main issue is that when I fetch my all my resources, I am given a resource id foreach in the response. It is this resource id that I use to delete an individual resource. This works correctly.
However, when I create a new resource all I get back is a server success 200 response, so the resource is created, but I cannot append another row to my listview.
If anyone could suggest a solution or an alternative approach, then that'd be a lifesaver.
Cheers
A: Edit your collection view to display the item when added to collection.
Append to initialize:
this.listenTo(this.collection, 'add', this.on_item_add);
Add function
on_item_add:function(added_item){
var added_item_row = new SubscriberView({model: added_item});
$(".subscribers-list").append(added_item_row.render().el);
},
| |
doc_2298
|
till today it was working fine but now when I open my website on mobile it open popups of onclkds.com, I have searched for the solution and many of the forums have suggested that it is issue related to browser extensions.
But as I totally researched on it, may be its because of some free plugins which is dynamically creating this dynamic popups. but i tried to deactivate this plugins nothing worked for me because it already added the code to my website.
A: I already had this problem, I managed to clean one of my website for this tutorial:
https://www.quora.com/How-do-I-remove-the-http-onclkds-com-ad-from-my-WordPress-website
| |
doc_2299
|
The middleware is attached to a specific spider and the logs show its attached successfully and detached the original one:
Debugging this, I can see that the breakpoint on the process_response function in the original retry middleware is stopped while in my custom one it does not stop.
Any ideas?
EDIT:
to reproduce:
spider:
import time
import scrapy
from scrapy.crawler import CrawlerProcess
class UsptoPatentHistorySpider(scrapy.Spider):
name = 'quotes'
handle_httpstatus_list = [401, 429]
start_urls = [
'https://patentcenter.uspto.gov/retrieval/public/v1/applications/sdwp/external/metadata/7850271',
]
custom_settings = {'RETRY_HTTP_CODES': [429, 401],
'SPIDER_MIDDLEWARES': {
'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,
'chalicelib.scrapy_my.scrapy_my.middlewares.TooManyRequestsRetryMiddleware': 543,
}}
def parse(self, response, **kwargs):
yield {"response": response.body}
def _handle_429(self, response):
time.sleep(60)
return response.follow()
if __name__ == "__main__":
process = CrawlerProcess()
process.crawl(UsptoPatentHistorySpider)
process.start()
middlewares.py:
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
import time
class TooManyRequestsRetryMiddleware(RetryMiddleware):
def __init__(self, crawler):
super(TooManyRequestsRetryMiddleware, self).__init__(crawler.settings)
self.crawler = crawler
@classmethod
def from_crawler(cls, crawler):
return cls(crawler)
def process_response(self, request, response, spider):
if request.meta.get('dont_retry', False):
return response
elif response.status == 429:
self.crawler.engine.pause()
time.sleep(5)
self.crawler.engine.unpause()
reason = response_status_message(response.status)
return self._retry(request, reason, spider) or response
elif response.status in self.retry_http_codes:
reason = response_status_message(response.status)
return self._retry(request, reason, spider) or response
return response
the function "process_response" in the custom middleware is never called
A: scrapy.downloadermiddlewares.retry.RetryMiddleware is downloader middleware (not spider middleware, see scrapy Architecture overview for details)
You didn't disabled original scrapy.downloadermiddlewares.retry.RetryMiddleware and you attached TooManyRequestsRetryMiddleware into spider middleware (you need to modify DOWNLOADER_MIDDLEWARES setting:
custom_settings = {'RETRY_HTTP_CODES': [429, 401],
'DOWNLOADER_MIDDLEWARES': { # not SPIDER_MIDDLEWARES
'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,
'chalicelib.scrapy_my.scrapy_my.middlewares.TooManyRequestsRetryMiddleware': 543,
}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.