id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_3100
|
MWE:
require 'nn';
char = nn.LookupTable(100,10,0,1)
charRep = nn.Sequential():add(char):add(nn.Squeeze())
c = {}
c[1] = torch.IntTensor(5):random(1,100)
c[2] = torch.IntTensor(2):random(1,100)
c[3] = torch.IntTensor(3):random(1,100)
--This works fine
print(c)
charFeatures = {}
for i=1,3 do
charFeatures[i] = charRep:forward(c[i])
--table.insert(charFeatures, charRep:forward(c[i]))
-- No difference when table.insert is used
end
--This fails
print(charFeatures)
Maybe i haven't understood how tables work in Lua. But this code copies the last tensor to all previous charFeatures elements.
A: The issue is not related with tables, but is very common in Torch though. When you call the forward method on a neural net, its state value output is changed. Now when you save this value into charFeatures[i] you actually create a reference from charFeatures[i] to charRep.output. Then in the next iteration of the loop charRep.output is modified and consequently all the elements of charFeatures are modified too, since they point to the same value which is charRep.output.
Note that this behavior is the same as when you do
a = torch.Tensor(5):zero()
b = a
a[1] = 0
-- then b is also modified
Finally to solve your problem you should clone the output of the network:
charFeatures[i] = charRep:forward(c[i]):clone()
And all will work as expected!
| |
doc_3101
|
json data
"MenuRole": [
{
"id": 1,
"name": "Manage User",
"icon": "ion-person",
"path_fe": "dashboard/user",
"cmsmenuschild": [
{
"name": "Create User",
"cmsprivilegesroles": {
"is_allowed": 1
}
},
{
"name": "Update User",
"cmsprivilegesroles": {
"is_allowed": 1
}
},
],
},
]
Sidebar.js
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
MenuRole: [],
};
}
getMenus = () => {
return this.state.MenuRole.map((role, index) =>
(<Menu.Item key={role.name}>
<Link to={
{
pathname: `/${role.path_fe}`,
}}
>
<i className={role.icon} />
<span className="nav-text">
<span>{role.name}</span>
<span>{role.cmsmenuschild.name}</span>
<span>{role.cmsmenuschild[0].cmsprivilegesroles.is_allowed}</span>
<span>{role.cmsmenuschild[1].cmsprivilegesroles.is_allowed}</span>
</span>
</Link>
</Menu.Item>));
}
render() {
return(
<div>
{this.getMenus()}
</div>
);
}
}
A: The following line <span>{role.cmsmenuschild.name}</span> is incorrect as csmenuschild is an array and we don't know from which child to get the name. You can get it like this
<span>{role.cmsmenuschild[0].name}</span> or <span>{role.cmsmenuschild[1].name}</span>.
However, this is not a good approach. You are statically accessing the csmenuschild array. There can be more than two children in this array. Hence, you should map over it as you are mapping over MenuRoles
A: I think rewriting of getMenus function is neccessary. As we want to render the array of element from it. We should use array and push the element into it.
getMenus = () => {
var elements = [];
this.state.MenuRole.map((role, index) =>{
elements.push(<Menu.Item key={role.name}>
<Link to={
{
pathname: `/${role.path_fe}`,
}}
>
<i className={role.icon} />
<span className="nav-text">
<span>{role.name}</span>
<span>{role.cmsmenuschild.name}</span>
<span>{role.cmsmenuschild[0].cmsprivilegesroles.is_allowed}</span>
<span>{role.cmsmenuschild[1].cmsprivilegesroles.is_allowed}</span>
</span>
</Link>
</Menu.Item>))
}
return elements;
}
| |
doc_3102
|
It is rather easy to get a boolean vector with True corresponding to all rows that meet the condition. In order to delete them, I thought if I could invert the boolean vector (have False where the the condition is met), I can just index my DataFrame with the inverted vector and be done.
In the process I have, I think made an interesting discovery: List comprehension is faster than numpy invert method for a boolean vector. The length of the vector in question is 221. Here is what I did:
In [1]: def npinvert():
return np.invert((df['col1'] == 'A') & (df['col2'] == 1))
def licomp():
return [not i for i in ((df['col1'] == 'A') & (df['col2'] == 1))]
And then:
In [2]: %timeit npinvert()
Out [2]: 1000 loops, best of 3: 902 µs per loop
In [3]: %timeit licomp()
Out [3]: 1000 loops, best of 3: 880 µs per loop
In any case, I get what I want. But, is there an even faster way to do this? I will have to run this on a much larger DataFrame in the near future. Thanks for your help!
A: To really compare these you need to test them on a range of sizes. Add any test functions you can think of to see if you can improve on the pandas method of ~ (conditions):
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Big (100,000 rows) test dataset
df = pd.DataFrame({'a': np.random.randint(1, 10, 100000),
'b': [np.random.choice(['A', 'B', 'C']) for i in range(100000)]})
def check_pandas(df):
return ~ ((df['a'] == 1) & (df['b'] == 'A'))
def check_list(df):
return [not i for i in ((df['b'] == 'A') & (df['a'] == 1))]
def check_numpy(df):
return np.invert((df['a'] == 1) & (df['b'] == 'A'))
sizes = []
pandas_times = []
list_times = []
np_times = []
for df_size in range(1, 100001, 1000):
sizes.append(df_size)
current_df = df.iloc[:df_size, :]
pandas_before = time.time()
check_pandas(current_df)
pandas_after = time.time()
pandas_times.append(float(pandas_after - pandas_before))
before = time.time()
check_list(current_df)
after = time.time()
list_times.append(float(after - before))
before = time.time()
check_numpy(current_df)
after = time.time()
np_times.append(float(after - before))
# Plot results
fig, ax = plt.subplots()
ax.plot(sizes, pandas_times, 'ro', label='pandas')
ax.plot(sizes, list_times, 'bs', label='list')
ax.plot(sizes, np_times, 'g+', label='numpy')
ax.legend(loc='upper left')
Once the dataframe gets pretty large, using the vectorized
pandas ~ and numpy.invert to invert the boolean seems to be much faster.
| |
doc_3103
|
document.getElementById("myId").children;
outputs an array of DOM elements
But if I do:
$("#myId").get().children;
outputs undefined
Why?
jQuery .get() documentation says:
.get() method grants access to the DOM nodes underlying each jQuery object
so why are the children empty if the DOM node with the id=myId has children?
Plus if I do $("#myId")[0].children I get the same result as with the first method (getElementById). Shouldn't get() do the same?
A: because .get() returns an array.
$("#myId")[0].children
or use .prop() like
$("#myId").prop('children')
.get()
Retrieve the elements matched by the jQuery object.
A: Missing index
.get( index )
$("#myId").get(0).children;
| |
doc_3104
|
private void changeColor( int colorId ) {
ActionBar actionBar = ((ActionBarActivity )getActivity()).getSupportActionBar();
actionBar.setBackgroundDrawable( new ColorDrawable( colorId ) );
this.getView().setBackgroundColor( getResources().getColor( colorId ) );
}
I have the actionbar themed to be blue in my styles.xml not sure if that has any effect. If you have any suggestion please let me know.
Thanks,
Nathan
Solution:
Had to change:
actionBar.setBackgroundDrawable( new ColorDrawable( colorId ) );
To:
actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( colorId ) ) );
A: If i understand your question correctly that you want to change the color base on user intervention, try this instead.
public void setActionBarColor(int parsedColor){
ActionBar mActionBar = getSupportActionBar();
mActionBar.setBackgroundDrawable(new ColorDrawable(parsedColor));
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayShowTitleEnabled(true);
}
using this in a fragment
// check if instance of activity is MyActivity just an example
MyActivity mA = ((MyActivity)getActivity());
mA.setActionBarColor(Color.parseColor("#FFA2C13E"));
hope it helps :)
PS: im using ActionBarActivity
| |
doc_3105
|
byte tmp = (byte)ran.Next(10);
Is there an alternative to this code?
It does not seem to have fully random behavior.
A: There are multiple reasons for why this could occur. One common problem is to create multiple instances of the Random class within a program. When using the Random class you should only create one instance and generate numbers from that. The article Create better random numbers in C# has a good explanation of why and explains why not doing this could lead to a problem.
Another common scenario is accessing the Random class object from multiple threads. System.Random is not thread safe (see the Remarks section of the documentation for Random) and thus can lead to unexpected and unwanted behavior. If using it in a multi-threaded environment then you need to be sure to use some form of locking to prevent multiple threads trying to generate random numbers at the same time.
For higher degrees of security and randomness you can use a cryptographically secure random number generator like
System.Security.Cryptography.RNGCryptoServiceProvider. Note that using a more secure random number generator will incur a performance penalty in comparison with System.Random.
If you don't need something cryptographically secure, but still want something that is more "random" than the Random class you can explore using other PRNG's such as Mersenne Twister. There are lots of options, each with different characteristics and performance profiles. Which you choose is heavily dependent on your goal.
A: It might be simpler than that. If you can this method in a tight loop:
for (int i = 0; i < 1000; i++)
{
Random ran = new Random();
byte tmp;
tmp = (byte)ran.Next(10);
}
You might see the same number over and over. Make sure you create the Random object outside any sort of looping.
Random ran = new Random();
for (int i = 0; i < 1000; i++)
{
byte tmp;
tmp = (byte)ran.Next(10);
}
That said, it is true that the crypto provider is better. But you're only getting randoms between 0 & 9 so how random does it have to be?
A: You could also consider the random.org API
http://www.random.org/clients/http/
| |
doc_3106
|
I tried to get rid of backslash-quote using the following but it ignores it and returns the original string. What am I doing wrong here?
var uNewDate = newDate.replace(/\\\"/gi, '');
here is the entire function:
function pageLoad() {
setStartDate(new Date());
}
// \"3/7/2018\"
function setStartDate(newDate) {debugger
$('#tbStartDate').unbind();
$("#tbStartDate").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
showOn: "button",
defaultDate: new Date(),
buttonImage: "../assets/images/calendar.gif",
buttonImageOnly: true,
buttonText: "Select Start Date",
option: "mm/dd/yy"
});
//var uNewDate = newDate.replace(/\\\"/gi, '');
$("#tbStartDate").datepicker("setDate", newDate);
}
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {debugger
setStartDate(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
A: This isn't using RegEx, but this will work:
var testDateString = '\"3/7/2018\"';
var newDateString = testDateString.split('\"')
.join('');
console.log(newDateString);
A: Remember you are handling JSON data as your response. Special characters are escaped in JSON, like your initial example is showing.
You need to parse it before handling it.
JSON.parse("\"3/7/2018\"")
// Result: "3/7/2018"
| |
doc_3107
|
Following is the code.
#!/usr/bin/perl
use WWW::Scripter;
use URI;
$w = new WWW::Scripter;
$w->use_plugin('JavaScript');
$response=$w->get("sdt1.corp.xyz.com:8080/click/phoenix/339cd9314fe0136d3c30f6e9984b1ddc?clickId=sfshsksk1234go");
$data_ref = $response->content_ref( );
#this response is a html code with a js link enbedded
my $h = $$data_ref;
my $u = new URI 'data:';
$u->media_type('text/html');
$u->data( $h );
$w->get($u);
The html code in $h is as follows (whitespace added for readability)
<html>
<body>
<div id="iat-click-js"></div>
<script>
var _clickurl="http://sdt1.corp.xyz.com:8080/click/phoenix/339cd9314fe0136d3c30f6e9984b1ddc?clickId=sfshsksk1234go&csrdmnb=1343895381009";
var _fpdatakey="afpdata";
(function(){
var e=document.createElement('script');
e.src='https://d3hhytn20582jn.cloudfront.net/iatclickbeacon.js';
e.async=true;
document.getElementById('iat-click-js').appendChild(e);
}());
</script>
</body>
</html>
and the content of the js is as follows.
fortyone=new function(){this.e=(new Date(2005,0,15)).getTimezoneOffset();this.f=(new Date(2005,6,15)).getTimezoneOffset();this.plugins=[];this.d={Flash:["ShockwaveFlash.ShockwaveFlash",function(b){return b.getVariable("$version")}],Director:["SWCtl.SWCtl",function(b){return b.ShockwaveVersion("")}]};this.r=function(b){var c;try{c=document.getElementById(b)}catch(d){}if(c===null||typeof c==="undefined")try{c=document.getElementsByName(b)[0]}catch(e){}if(c===null||typeof c==="undefined")for(var f=0;f<document.forms.length;f++)for(var g=document.forms[f],h=0;h<g.elements.length;h++){var a=g[h];if(a.name===b||a.id===b)return a}return c};this.b=function(b){var c="";try{if(typeof this.c.getComponentVersion!=="undefined")c=this.c.getComponentVersion(b,"ComponentID")}catch(d){b=d.message.length;b=b>40?40:b;c=escape(d.message.substr(0,b))}return c};this.exec=function(b){for(var c=0;c<b.length;c++)try{var d=eval(b[c]);if(d)return d}catch(e){}return""};this.p=function(b){var c="";try{if(navigator.plugins&&navigator.plugins.length){var d=RegExp(b+".* ([0-9._]+)");for(b=0;b<navigator.plugins.length;b++){var e=d.exec(navigator.plugins[b].name);if(e===null)e=d.exec(navigator.plugins[b].description);if(e)c=e[1]}}else if(window.ActiveXObject&&this.d[b])try{var f=new ActiveXObject(this.d[b][0]);c=this.d[b][1](f)}catch(g){c=""}}catch(h){c=h.message}return c};this.q=function(){for(var b=["Acrobat","Flash","QuickTime","Java Plug-in","Director","Office"],c=0;c<b.length;c++){var d=b[c];this.plugins[d]=this.p(d)}};this.g=function(){return Math.abs(this.e-this.f)};this.h=function(){return this.g()!==0};this.i=function(b){var c=Math.min(this.e,this.f);return this.h()&&b.getTimezoneOffset()===c};this.n=function(b){var c=0;c=0;if(this.i(b))c=this.g();return c=-(b.getTimezoneOffset()+c)/60};this.j=function(b,c,d,e){if(typeof e!=="boolean")e=false;for(var f=true,g;(g=b.indexOf(c))>=0&&(e||f);){b=b.substr(0,g)+d+b.substr(g+c.length);f=false}return b};this.m=function(){return(new Date(2005,5,7,21,33,44,888)).toLocaleString()};this.k=function(b){var c=new Date,d=[function(){return"TF1"},function(){return"015"},function(){return ScriptEngineMajorVersion()},function(){return ScriptEngineMinorVersion()},function(){return ScriptEngineBuildVersion()},function(a){return a.b("{7790769C-0471-11D2-AF11-00C04FA35D02}")},function(a){return a.b("{89820200-ECBD-11CF-8B85-00AA005B4340}")},function(a){return a.b("{283807B5-2C60-11D0-A31D-00AA00B92C03}")},function(a){return a.b("{4F216970-C90C-11D1-B5C7-0000F8051515}")},function(a){return a.b("{44BBA848-CC51-11CF-AAFA-00AA00B6015C}")},function(a){return a.b("{9381D8F2-0288-11D0-9501-00AA00B911A5}")},function(a){return a.b("{4F216970-C90C-11D1-B5C7-0000F8051515}")},function(a){return a.b("{5A8D6EE0-3E18-11D0-821E-444553540000}")},function(a){return a.b("{89820200-ECBD-11CF-8B85-00AA005B4383}")},function(a){return a.b("{08B0E5C0-4FCB-11CF-AAA5-00401C608555}")},function(a){return a.b("{45EA75A0-A269-11D1-B5BF-0000F8051515}")},function(a){return a.b("{DE5AED00-A4BF-11D1-9948-00C04F98BBC9}")},function(a){return a.b("{22D6F312-B0F6-11D0-94AB-0080C74C7E95}")},function(a){return a.b("{44BBA842-CC51-11CF-AAFA-00AA00B6015B}")},function(a){return a.b("{3AF36230-A269-11D1-B5BF-0000F8051515}")},function(a){return a.b("{44BBA840-CC51-11CF-AAFA-00AA00B6015C}")},function(a){return a.b("{CC2A9BA0-3BDD-11D0-821E-444553540000}")},function(a){return a.b("{08B0E5C0-4FCB-11CF-AAA5-00401C608500}")},function(){return eval("navigator.appCodeName")},function(){return eval("navigator.appName")},function(){return eval("navigator.appVersion")},function(a){return a.exec(["navigator.productSub","navigator.appMinorVersion"])},function(){return eval("navigator.browserLanguage")},function(){return eval("navigator.cookieEnabled")},function(a){return a.exec(["navigator.oscpu","navigator.cpuClass"])},function(){return eval("navigator.onLine")},function(){return eval("navigator.platform")},function(){return eval("navigator.systemLanguage")},function(){return eval("navigator.userAgent")},function(a){return a.exec(["navigator.language","navigator.userLanguage"])},function(){return eval("document.defaultCharset")},function(){return eval("document.domain")},function(){return eval("screen.deviceXDPI")},function(){return eval("screen.deviceYDPI")},function(){return eval("screen.fontSmoothingEnabled")},function(){return eval("screen.updateInterval")},function(a){return a.h()},function(a){return a.i(c)},function(){return"@UTC@"},function(a){return a.n(c)},function(a){return a.m()},function(){return eval("screen.width")},function(){return eval("screen.height")},function(a){return a.plugins.Acrobat},function(a){return a.plugins.Flash},function(a){return a.plugins.QuickTime},function(a){return a.plugins["Java Plug-in"]},function(a){return a.plugins.Director},function(a){return a.plugins.Office},function(){return(new Date).getTime()-c.getTime()},function(a){return a.e},function(a){return a.f},function(){return c.toLocaleString()},function(){return eval("screen.colorDepth")},function(){return eval("window.screen.availWidth")},function(){return eval("window.screen.availHeight")},function(){return eval("window.screen.availLeft")},function(){return eval("window.screen.availTop")},function(a){return a.a("Acrobat")},function(a){return a.a("Adobe SVG")},function(a){return a.a("Authorware")},function(a){return a.a("Citrix ICA")},function(a){return a.a("Director")},function(a){return a.a("Flash")},function(a){return a.a("MapGuide")},function(a){return a.a("MetaStream")},function(a){return a.a("PDFViewer")},function(a){return a.a("QuickTime")},function(a){return a.a("RealOne")},function(a){return a.a("RealPlayer Enterprise")},function(a){return a.a("RealPlayer Plugin")},function(a){return a.a("Seagate Software Report")},function(a){return a.a("Silverlight")},function(a){return a.a("Windows Media")},function(a){return a.a("iPIX")},function(a){return a.a("nppdf.so")},function(a){return a.o()}];this.q();for(var e="",f=0;f<d.length;f++){if(b){e+=this.j(d[f].toString(),'"',"'",true);e+="="}var g;try{g=d[f](this)}catch(h){g=""}e+=b?g:escape(g);e+=";";if(b)e+="\\n"}return e=this.j(e,escape("@UTC@"),(new Date).getTime())};this.l=function(b){try{if(!b)return this.k();var c;c=this.r(b);if(c!==null)try{c.value=this.k()}catch(d){c.value=escape(d.message)}}catch(e){}};this.a=function(b){try{if(navigator.plugins&&navigator.plugins.length)for(var c=0;c<navigator.plugins.length;c++){var d=navigator.plugins[c];if(d.name.indexOf(b)>=0)return d.name+(d.description?"|"+d.description:"")}}catch(e){}return""};this.o=function(){var b=document.createElement("span");b.innerHTML=" ";b.style.position="absolute";b.style.left="-9999px";document.body.appendChild(b);var c=b.offsetHeight;document.body.removeChild(b);return c}};try{fortyone.c=document.createElement("span");typeof fortyone.c.addBehavior!=="undefined"&&fortyone.c.addBehavior("#default#clientCaps")}catch(i){}window.fortyone=fortyone;window.fortyone.collect=fortyone.l;
function sendclickping(){
var req;
if (window.XMLHttpRequest) {
req=new XMLHttpRequest();
} else {
req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != null) {
req.open("POST",_clickurl,true);
req.onreadystatechange= function() {
if (req.readyState==4 && req.status==200)
{
var _rurl=req.getResponseHeader("location");
if (_rurl && _rurl.length != 0) {
window.location.replace(_rurl);
} else {
console.log("could not get the redirect url");
}
}
}
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var _pbody=_fpdatakey+"="+escape(fortyone.collect());
req.send(_pbody);
} else {
console.log("AJAX (XMLHTTP) not supported.");
}
}
sendclickping();
It was running perfectly fine until this morning and not even a single line of code has been changed. I am getting the following error now when i run the perl script.
gurudutt@MK-QA-28:~$ ./js1.pl
ReferenceError: The variable ActiveXObject has not been declared at https://d3hhytn20582jn.cloudfront.net/iatclickbeacon.js, line 8.</p>
I have no idea what went wrong.
If you look at the js, it should not have gone inside the else condition, all this while when it was working, i think the if condition was satisfied. But for some reason it is not going into the if condition today.
if (window.XMLHttpRequest) { req=new XMLHttpRequest(); } else { req=new ActiveXObject("Microsoft.XMLHTTP"); }
In this script, this part holds the key
my $u = new URI 'data:'; $u->media_type('text/html'); $u->data( $h ); $w->get($u);
Is there something to do with media_style, using something else instead of text/html?
| |
doc_3108
|
- panel data set
- 10 time periods
I need to create a dummy variable, RL that is equal to 1 (TRUE) forever if the dummy variable RS has been 1 once.
in other words:
The new variable RL (spanning 10 periods) has to be 1 in t and all subsequent periods if RS was 1 in period t-1. If no TRUE has happened in RS and RS is 0 (FALSE) then RL should also be 0.
As soon as TRUE happens in RS in period t then RL has to be 1 onwards (in t+1, t+2, t+3, t+4 ..., t+end of panel).
My problem is that FALSE is not properly read as 0 but just as NA.
I used ifelse but it gives me way too many blanks:
df$r_1RL <- rep(0,nrow(df)) # is = 0 cause noone can retire in t-1 since "RS0" doesn't exists
df$r_2RL <- ifelse( df$r_1RS == 1, 1, ifelse(df$r_1RS == 0, 0, NA))
df$r_3RL <- ifelse( (df$r_1RS == 1 | df$r_2RS == 1), 1, ifelse( (df$r_1RS == 0 | df$r_2RS == 0), 0, NA))
df$r_4RL <- ifelse( (df$r_1RS == 1 | df$r_2RS == 1 | df$r_3RS == 1), 1, ifelse( (df$r_1RS == 0 | df$r_2RS == 0 | df$r_3RS == 0), 0, NA))
df$r_5RL <- ifelse( (df$r_1RS == 1 | df$r_2RS == 1 | df$r_3RS == 1 | df$r_4RS == 1 ), 1, ifelse( (df$r_1RS == 0 | df$r_2RS == 0 | df$r_3RS == 0 | df$r_4RS == 0), 0, NA))
and so on... up to 10RL
df <- structure(list(r_1RS = c(FALSE, FALSE, FALSE, FALSE, FALSE, NA
), r_2RS = c(FALSE, NA, FALSE, FALSE, FALSE, NA), r_3RS = c(FALSE,
FALSE, FALSE, FALSE, FALSE, NA), r_4RS = c(FALSE, FALSE, FALSE,
FALSE, NA, FALSE), r_5RS = c(FALSE, TRUE, FALSE, FALSE, NA, FALSE
), r_6RS = c(FALSE, FALSE, FALSE, FALSE, NA, TRUE), r_7RS = c(FALSE,
FALSE, FALSE, FALSE, NA, FALSE), r_8RS = c(TRUE, FALSE, FALSE,
FALSE, FALSE, FALSE), r_9RS = c(FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE), r_10RS = c(FALSE, FALSE, TRUE, FALSE, NA, FALSE), r_1RL = c(0,
0, 0, 0, 0, 0), r_2RL = c(0, 0, 0, 0, 0, NA), r_3RL = c(0, NA,
0, 0, 0, NA), r_4RL = c(0, NA, 0, 0, 0, NA), r_5RL = c(0, NA,
0, 0, NA, NA), r_6RL = c(0, 1, 0, 0, NA, NA), r_7RL = c(0, 1,
0, 0, NA, 1), r_8RL = c(0, 1, 0, 0, NA, 1), r_9RL = c(1, 1, 0,
0, NA, 1), r_10RL = c(1, 1, 0, 0, NA, 1)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
Here you can see how as soon as true happens in RS, RL is 1 after. But there are two problems.. first of all the 1 in r_10RL should be a NA and r_7RL should have 0's and not NA's
The red circled NA should be 0 and the yellow circled 1 should be NA
A: This feels very hackish, and I do not love it, but it works on your sample data. You could probably take the general idea and make it more efficient. Let me know if you run into any issues!
# Using the first 10 columns of your dput dataframe
df <- df[1:10]
> df
# A tibble: 6 x 10
r_1RS r_2RS r_3RS r_4RS r_5RS r_6RS r_7RS r_8RS r_9RS r_10RS
<lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> <lgl>
1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
2 FALSE NA FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
4 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
5 FALSE FALSE FALSE NA NA NA NA FALSE FALSE NA
6 NA NA NA FALSE FALSE TRUE FALSE FALSE FALSE FALSE
# Createing a copy for the new columns
df2 <- df
# There may be other ways to handle NA's but you mentioend you want them
# as zero so this should work for you
df2[is.na(df2)] <- 0
# Changing all values after TRUE to 1
df2 <- data.frame(t(apply(df2, 1, function(x) as.numeric(cumsum(x) > 0))))
# Chaning the names
names(df2) <- sub("RS", "RL", names(df), fixed = T)
# Combining the columns
> cbind(df, df2)
r_1RS r_2RS r_3RS r_4RS r_5RS r_6RS r_7RS r_8RS r_9RS r_10RS r_1RL r_2RL r_3RL r_4RL r_5RL r_6RL r_7RL r_8RL r_9RL r_10RL
1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE 0 0 0 0 0 0 0 1 1 1
2 FALSE NA FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE 0 0 0 0 1 1 1 1 1 1
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE 0 0 0 0 0 0 0 0 0 1
4 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 0 0 0 0 0 0 0 0 0 0
5 FALSE FALSE FALSE NA NA NA NA FALSE FALSE NA 0 0 0 0 0 0 0 0 0 0
6 NA NA NA FALSE FALSE TRUE FALSE FALSE FALSE FALSE 0 0 0 0 0 1 1 1 1 1
EDIT:
Just read the last lines of your post. If you want to retain NA's in the new columns just put df2[is.na(df)] <- NA before cbind. I am a little unclear exactly what you want, so if that is not what you are looking for, can you posted a dataframe with your desired output for the sample data? Comment or post an update if you run into other issues!
EDIT2:
Another way to do the step involving apply (which can be slow). I could not test which way was faster so I wanted to include both:
# Changing all values after TRUE to 1
df2[] <- lapply(df2, as.numeric)
df2_t <- data.frame(t(df2))
> data.frame(t(cumsum(df2_t) > 0)*1)
r_1RS r_2RS r_3RS r_4RS r_5RS r_6RS r_7RS r_8RS r_9RS r_10RS
X1 0 0 0 0 0 0 0 1 1 1
X2 0 0 0 0 1 1 1 1 1 1
X3 0 0 0 0 0 0 0 0 0 1
X4 0 0 0 0 0 0 0 0 0 0
X5 0 0 0 0 0 0 0 0 0 0
X6 0 0 0 0 0 1 1 1 1 1
| |
doc_3109
|
var loader = new THREE.OBJLoader();
loader.load( 'models/refTestblend.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = envMaterial;
}
} );
scene.add( object );
} );
Unfortunately, I have had to sacrifice the .mtl file however, so the next step in my quest will be to attempt to reinstate the exported .mtl textures and somehow mix this will the cubemap material. ( I'm marking this as answered, any further input obviously welcome.. )
EDIT: The solution to this issue of mixing the original texture and envmap comments see below. Hope this is of use!
OP:
I have an environment cubemap exported from blender - I can apply the envmap to generated geometry fine, but how do I apply it to my imported .obj model?
I believe the closest example I can find it this demo - http://mrdoob.github.io/three.js/examples/webgl_materials_cubemap.html
loader = new THREE.BinaryLoader();
loader.load( "obj/walt/WaltHead_bin.js", function( geometry ) { createScene( geometry, cubeMaterial1, cubeMaterial2, cubeMaterial3 ) } );
However it runs off the BinaryLoader, which I don't believe I can use with blender exports - (I may be wrong?)
This is what my loader, envmap/skybox, and working gen'd cube looks like..
var urls = [
'models/cubemap/right.png',
'models/cubemap/left.png',
'models/cubemap/top.png',
'models/cubemap/bottom.png',
'models/cubemap/front.png',
'models/cubemap/back.png'
];
// create the cubemap
var cubemap = THREE.ImageUtils.loadTextureCube(urls);
cubemap.format = THREE.RGBFormat;
// create a custom shader
var shader = THREE.ShaderLib["cube"];
shader.uniforms["tCube"].value = cubemap;
var material = new THREE.ShaderMaterial({
fragmentShader: shader.fragmentShader,
vertexShader: shader.vertexShader,
uniforms: shader.uniforms,
depthWrite: false,
side: THREE.DoubleSide
});
// create the skybox
var skybox = new THREE.Mesh(new THREE.BoxGeometry(10000, 10000, 10000), material);
scene.add(skybox);
var envMaterial = new THREE.MeshBasicMaterial({envMap:cubemap});
var cubeGeometry = new THREE.BoxGeometry(5, 5, 5);
var cube = new THREE.Mesh(cubeGeometry, envMaterial);
cube.name = 'cube';
scene.add(cube);
cube.position.set(-10, 0, 0);
var loader = new THREE.OBJMTLLoader();
loader.load("models/refTestblend.obj",
"models/refTestblend.mtl",
function(obj) {
obj.translateY(-3);
scene.add(obj);
});
Many thanks!
A: You can add an environment map to the existing materials of your OBJ model using a pattern like this one:
var loader = new THREE.OBJLoader();
loader.load( 'myModel.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.envMap = myEnvironmentMap;
// add any other properties you want here. check the docs.
}
} );
scene.add( object );
} );
| |
doc_3110
|
[{
"id": "1",
"title": "test 1",
"venue": "test 1",
"day": "12",
"month": "January",
"year": "2016",
"date": "2016-02-23T14:53:24.118Z",
"tasks": []
}, {
"id": "2",
"title": "test 2",
"venue": "test 2",
"day": "22",
"month": "April",
"year": "2016",
"date": "2016-02-23T14:53:24.118Z",
"tasks": []
}]
I have 2 controllers. One that lists all items in the array in ng-repeat and the other to display a single item:
.controller('ProfileCtrl', function ($scope, Eventers) {
$scope.eventers = Eventers.all();
})
single item display:
.controller('ProfileInnerCtrl', function ($scope, $stateParams, $ionicModal, Eventers) {
$scope.eventer = Eventers.get($stateParams.eventerId);
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
},
{
focusFirstInput: false,
scope: $scope
});
$scope.createTask = function(task, index) {
$scope.eventer.tasks.push({
title: task.title
});
$scope.taskModal.hide();
Eventers.save($scope.eventer);
$scope.taskModal.hide();
};
})
and my factory:
.factory('Eventers', function() {
return {
all: function() {
var eventerString = window.localStorage['eventers'];
if (eventerString) {
return angular.fromJson(eventerString);
}
return [];
},
save: function(eventers) {
window.localStorage['eventers'] = angular.toJson(eventers);
},
newEventer: function(eventerId, eventerTitle,eventerVenue , eventerDay, eventerMonth, eventerYear, eventerDate) {
return {
id: eventerId,
title: eventerTitle,
venue: eventerVenue,
day: eventerDay,
month: eventerMonth,
year: eventerYear,
date: eventerDate,
tasks: []
};
},
get: function(eventerId){
var hell = window.localStorage['eventers'];
var eventers = JSON.parse(hell);
for (var i = 0; i < eventers.length; i++) {
if (parseInt(eventers[i].id) === parseInt(eventerId)){
console.log(eventerId);
return eventers[i];
}
}
return null;
}
}
});
Once in the single item I want a user to be able to open a modal and add items to the nested tasks array and then update local storage but I cannot seem to wrap my head around it. The way I am doing it now seems to add a task but deletes all other posts in the array.
A: Try to read all the items from the local storage not just parts, then you can add, remove or edit anything without problems. After that, you can proceed to save it.
A: Eventers.save($scope.eventer);
is saving only the current event.
While the actual implementation is trying to save all
save: function(eventers) {
window.localStorage['eventers'] = angular.toJson(eventers);
},
Thus, its overwriting all the other events.
| |
doc_3111
|
var params = "type=search" + "&content="+encodeURIComponent(document.getElementsByTagName("body")[0].innerHTML);
xmlhttp.open("POST", "/service/p.aspx", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);
A: The following works fine for me in Firefox and IE8:
<html>
<body>
<script type="text/javascript">
// MAYBE FORGOT THIS PART?
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
document.write(xmlhttp.responseText);
}
}
// THIS PART IS EXACTLY LIKE YOURS
var params = "type=search" + "&content="+encodeURIComponent(document.getElementsByTagName("body")[0].innerHTML);
xmlhttp.open("POST", "/service/p.aspx", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);
</script>
</body>
</html>
Perhaps you just forgot to declare xmlhttp and add a listener for the asynchronous status callback?
Also, see this SO question for more information about getting an XMLHttpRequest object in a cross-browser fashion.
Here is what is being sent in the POST request via FireBug in Firefox:
type=search&content=%0A%20%20%20%20%20%20%20%20%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%2F%2F%20MAYBE%20FORGOT%20THIS%20PART%3F%0Avar%20xmlhttp%20%3D%20new%20XMLHttpRequest()%3B%0Axmlhttp.onreadystatechange%3Dfunction()%0A%7B%0A%20%20%20%20if%20(xmlhttp.readyState%3D%3D4)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20document.write(xmlhttp.responseText)%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%2F%2F%20THIS%20PART%20IS%20EXACTLY%20LIKE%20YOURS%0Avar%20params%20%3D%20%22type%3Dsearch%22%20%2B%20%22%26content%3D%22%2BencodeURIComponent(document.getElementsByTagName(%22body%22)%5B0%5D.innerHTML)%3B%0Axmlhttp.open(%22POST%22%2C%20%22%2Fservice%2Fp.aspx%22%2C%20true)%3B%0Axmlhttp.setRequestHeader(%22Content-type%22%2C%20%22application%2Fx-www-form-urlencoded%22)%3B%0Axmlhttp.setRequestHeader(%22Content-length%22%2C%20params.length)%3B%20%0Axmlhttp.send(params)%3B%0A%20%20%20%20%20%20%20%20%3C%2Fscript%3E
So you have type which equals search, and content, which is the HTTP-encoded body of the HTML above, exactly as programmed. So it seems to be working as intended...
| |
doc_3112
|
@Component
class MySpringClass {
private static PaymentRepo paymentRepo;
@Autowired
MySpringClass(PaymentRepo repo) { MySpringClass.paymentRepo = repo; }
static void usePaymentRepoToDoStuff() { …. using paymentRepo ….. }
}
I've read that assigning static references via autowiring is not recommended. I didn't do it. Not my code.
I can't find a place where even one instance of MySpringClass is explicitly created (but this is a lot of code). This code works reliably.
So, does @Autowired cause Spring to create at least one instance of MySpringClass, and thus the constructor to run, even if never explicitly called for in Java? Otherwise, I'll keep looking and trying to figure this out. thanks.
A: @Component declared on the class, is going to be read by Spring and it's going to be instantiated as a Spring Bean (by default, is going to be a Singleton, so just one instance) and it's going to be added to the Spring Application Context. Also you can then use the MySpringClass all over the application if you @Autowired it.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html
A: It depends on whether your Spring container configured with default lazy initialization of beans (by default is is eager, not lazy).
So by default Spring will create instance of a bean upon creation of Spring context.
And since you are using Spring you do not need to check if code uses constructor directly since Spring will create bean and you should not create objects marked as beans using constructor (this eliminates the whole concept of dependency injection and inversion of control).
In case of lazy loading configured Spring will create bean only when it is needed.
| |
doc_3113
|
Because the data is asynchronous it doesn't appear to work in time - so the console outputs the stations names at the end of the console.
But the correct station name is not injected to the correct station id (e.g. station-4).
Any help much appreciated. Please note, I am ideally looking for a solution that doesn't not rely on jQuery.
window.apiCallback = function(data) {
for (i=0; i < 10; i++) {
document.getElementById("title-"+i+"").innerHTML = data.results[i].name;
}
loadJSON('http://trainstationsdata/near.json?lat='+data.results[i].venue.lat+'&lon='+data.results[i].venue.lon+'&page=1&rpp=1',
function(result) {
// this works and outputs at the end of console
console.log(result.stations[0].name);
// this doesn't work
document.getElementById("station-"+i+"").innerHTML = result.[i].station_name;;
},
function(xhr) { console.error(xhr); }
);
}
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
A: You can try with success, or complete ajax method, that runs when the request is finished (after success and error functions).
Something like this.
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
complete:function(data) {
handleData(data);
}
});
}
and the solution without JQuery would be something like this.
var r = new XMLHttpRequest();
r.open("POST", "webservice", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");
| |
doc_3114
|
printf("Change in dollars: ");
change= GetFloat();
cents= round(change*100);
printf("Cents is %f",cents);
This is a logical error because the program runs fine but there is something wrong with the mathematics for example if i enter 1.50 when prompted, the return i get is 1004 which is clearly wrong. What i want to happen is 150 to be outputted.
A: This is most likely because you have some locale where the decimal separator is , instead of ., and since you are very likely not checking the return value of scanf() "which is what most books do and almost every tutorial", then the variable is not being initialized and what you are printing is a consequence of the layout of your program instead of a value inputed by a user.
To verify what I say, I suggest compiling the same program without modification but with different compilation flags.
What you must do is ensure that the input is correct, try this
float GetFloat(int *ok)
{
float value = 0;
if (scanf("%f", &value) != 1)
*ok = 0;
else
*ok = 1;
return value;
}
which you would call like this
int result = 0;
float change = GetFloat(&result);
if (result == 0)
return -1;
float cents = round(change * 100);
printf("Cents is %f",cents);
If the decimal separator is an issue, the above program will not output anything, because scanf() will return 0, and hence ok will be 0 after you call the function.
One important consequence of ignoring the return value of non-void functions is that if the value was not initialized like in this case with scanf(), and you don't know that because you didn't check the return value, then undefined behavior will happen, meaning that your program will contain bugs that are very difficult to find and hence very hard to fix.
| |
doc_3115
|
However, I get We encountered a problem processing your request issue.
What might be the issue? I don't get any response in my call_back url too.
I used the code from Intuit Sample app.
public static String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static String AUTHORIZE_URL = "https://appcenter.intuit.com/Connect/Begin";
public static String OAUTH_CONSUMER_KEY = "qyprdFHGmJjBj1jDH05Jen95Tu3PyW";
public static String OAUTH_CONSUMER_SECRET = "OMFkKCPRBQKrMoyaLg9mFYTM26kpJg8LPthbNzTB";
public static String OAUTH_CALLBACK_URL = "http://office.technology.com:8081/delegate/intuit/";
public Map<String, String> getRequestTokenSignPost() {
String authURL = null;
OAuthProvider provider = createProvider();
String consumerkey = OAUTH_CONSUMER_KEY;
String consumersecret = OAUTH_CONSUMER_SECRET;
LOG.info("Inside getRequestToken, Consumer Key and Secret: " + consumerkey + " " + consumersecret);
String callback_url = OAUTH_CALLBACK_URL;
LOG.info("callback URL: " + callback_url);
OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey, consumersecret);
try {
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback", URLEncoder.encode(callback_url, "UTF-8"));
ouathconsumer.setAdditionalParameters(additionalParams);
} catch (UnsupportedEncodingException e) {
LOG.error(e.getLocalizedMessage());
}
String requestret = "";
String requestToken = "";
String requestTokenSecret = "";
try {
String signedRequestTokenUrl = ouathconsumer.sign(REQUEST_TOKEN_URL);
LOG.info("signedRequestTokenUrl: " + signedRequestTokenUrl);
URL url;
url = new URL(signedRequestTokenUrl);
HttpURLConnection httpconnection = (HttpURLConnection) url.openConnection();
httpconnection.setRequestMethod("GET");
httpconnection.setRequestProperty("Content-type", "application/xml");
httpconnection.setRequestProperty("Content-Length", "0");
if (httpconnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
requestret = sb.toString();
}
String[] requestTokenSections = requestret.split("&");
for (int i = 0; i < requestTokenSections.length; i++) {
String[] currentElements = requestTokenSections[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
requestToken = currentElements[1];
} else if (currentElements[0].equalsIgnoreCase("oauth_token_secret")) {
requestTokenSecret = currentElements[1];
}
}
Map<String, String> requesttokenmap = new HashMap<String, String>();
try {
authURL = provider.retrieveRequestToken(ouathconsumer, callback_url);
} catch (OAuthNotAuthorizedException e) {
LOG.error(e.getLocalizedMessage());
}
ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(), ouathconsumer.getTokenSecret());
requesttokenmap.put("requestToken", requestToken);
requesttokenmap.put("requestTokenSecret", requestTokenSecret);
requesttokenmap.put("authURL", authURL);
return requesttokenmap;
} catch (OAuthMessageSignerException e) {
LOG.error(e.getLocalizedMessage());
} catch (OAuthExpectationFailedException e) {
LOG.error(e.getLocalizedMessage());
} catch (OAuthCommunicationException e) {
LOG.error(e.getLocalizedMessage());
} catch (MalformedURLException e) {
LOG.error(e.getLocalizedMessage());
} catch (IOException e) {
LOG.error(e.getLocalizedMessage());
}
LOG.info("Error: Failed to get request token.");
return null;
}
public static OAuthProvider createProvider() {
OAuthProvider provider =
new DefaultOAuthProvider(OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL, OauthHelper.AUTHORIZE_URL);
return provider;
}
public String getAuthorizeURL(String requestToken, String requestTokenSecret) {
String authorizeURL = "";
try {
authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
} catch (Exception e) {
LOG.error(e.getLocalizedMessage());
}
LOG.info("Authorize URL: " + authorizeURL);
return authorizeURL;
}
I even get the Request token:
signedRequestTokenUrl: https://oauth.intuit.com/oauth/v1/get_request_token?oauth_signature=EHKmrR%2BV%2ByF4WRcBmpkdBeYEfuE%3D&oauth_callback=http%253Aoffice.technology.com%253A8081%252Fdelegate%252Fintuit&oauth_consumer_key=qyprdFHGaJjBj1jDH05Jen95Tu3PyW&oauth_version=1.0&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1390538706&oauth_nonce=-4612911034475731539
requestret: oauth_token_secret=XkXjGlS6bnFvOWYthCoew54W4ILcdMWQ3jaOMCQQ&oauth_callback_confirmed=true&oauth_token=qyprdRyUiXzU0QLLavn3L3TtdqvYts5CZyomkSk8miZDfB8Y
A: This:
public static String OAUTH_CALLBACK_URL = "http:office.technology.com:8081/delegate/intuit/";
Is not a valid URL, and it needs to be. Fix your URL.
A: I was able to fix the issue using an incognito window without any cookies for my quickbooks developer account.
| |
doc_3116
|
The idea is to rotate each array element right by a given number of places: e.g. [3, 8, 9, 7, 6] rotated 3 times gives [9, 7, 6, 3, 8].
It wasn't so difficult to figure out solution using extra array. The only required think was new position calculated:
(old_position + rotations)%array_size
However, I've started to think how (if) it can be achieved only with one array? My initial idea was to just swap two elements between new and old position (knowing what old position was) and repeat it for all elements. My code looks like that:
int temp_el;
int temp_index = 0;
int new_pos;
for(int i=0;i<A.size();i++)
{
new_pos = (temp_index + rotations)%A.size();
temp_el = A[new_pos];
A[new_pos] = A[0];
A[0] = temp_el;
temp_index = new_pos;
}
but I forgot about case where in the middle or at the beginning of rotations element at 0 is correct. Which element next I need to pick next? I cannot just take ith element, because it might be already moved.
| |
doc_3117
|
I tried something like this but I'm sure that it's not correct:
Picasso.get()
.load(R.drawable.blue_xml_popcorn)
.into((Target) BteyoutubePlay_popcorn);
So if somebody has a solution, it will be really helpful. :)
Thanks!
| |
doc_3118
|
Expected output:
./my_script.sh hello bye 2
hello
bye
2
my output:
./my_script.sh hello bye 2
Word1=1
meu_script.sh: line 2: read: `Word2=': not a valid identifier
hello
bye
2
Program:
#!/bin/bash
read -p "Word1=" $1 "Word2=" $2 "Num=" $3
Word1="${1}"
Word2="${2}"
Num="${3}"
echo ${1}
echo ${2}
echo ${3}
Can someone explain me whats going because i dont understand btw im fairly knew in programming in shell script
A: Maybe I'm oversimplifying your problem, but if you want to prompt the user for inputs and save those inputs to variables (vs. just taking them directly from the command line using $1, $2, etc.), do you just want this?
#!/bin/bash
read -p "Enter word 1: " Word1
read -p "Enter word 2: " Word2
read -p "Enter Num: " Num
echo $Word1
echo $Word2
echo $Num
Alternatively, if taking them directly from the command line is what you want, just use $1, $2, and $3:
#!/bin/bash
echo $1
echo $2
echo $3
That way, ./my_script.sh hello bye 2 prints the results you want.
A: I just discovered the answer
The text file should be saved with UNIX Line Feeds instead of Mac OS CR or Windows CRLF
A: As already mentioned, sometimes there might be an issue with the characters you don't see, but bash does.
I had a very similar issue, even though I worked on debian all the time (but different versions). Moreover, file that used to work, stopped working. However, the problem was solved by
dos2unix yourscriptname.sh
See this post for more details.
| |
doc_3119
|
I also need to check if email address change then it must check this email is unique or not. If not unique then user can't update the data and validation message show "Email Address already exists".
Script
$('#UserEmail').blur(function () {
var url = "/Account/CheckUserEmail";
var Email = $('#UserEmail').val();
$.get(url, { input: email }, function (data) {
if (data == "Available") {
$("#result").html("<span style='color:green;'>User email available</span>");
$("#UserEmail").css('background-color', '');
} else if (data == "Empty") {
$("#result").html("<span> </span>");
} else {
$("#result").html("<span style='color:red'>User email not available</span>");
//$("#UserEmail").css('background-color', '#e97878');
}
});
})
Controller
public string CheckUserEmail(string email)
{
if (input == string.Empty)
{
return "Empty";
}
var finduser = UserManager.FindByEmail(email);
if (finduser == null)
{
return "Available";
}
else
{
return "Not Available";
}
return "";
}
A: Currently you handling the .blur() event which would unnecessarily trigger your ajax call when a user tabs through the controls unchanged. Instead you should be handling the .change() event. This would be triggered only when the text is changed and the control loses focus. A user could still make a change, then go back and undo it so you could prevent the server being called by comparing the value and defaultValue. Finally there seems no point calling the server if the user has not entered an email.
Script (note the isValid variable declared outside the function so this could be checked to prevent a submit)
var isValid = true;
$('#UserEmail').change(function () {
var span = $('<span></span>');
var url = '@Url.Action("CheckUserEmail", "Account")'; // don't hard code your url's
var email = $(this).val();
if(!email) { // assume an email address is required
isValid = false;
span.text('Please enter an email address');
} else if (email == $(this)[0].defaultValue) { // nothing has changed so OK
isValid = true;
} else { // call server to validate
$.get(url, { input: email }, function (data) {
isValid = data;
if (!isValid) {
span.text('User email not available');
}
});
}
if(isValid) {
span.css('color', 'green'); // better to use class names
} else {
span.css('color', 'red');
}
$("#result").html(span);
});
Controller
public JsonResult CheckUserEmail(string email)
{
return Json(UserManager.FindByEmail(email) == null, JsonRequestBehavior.AllowGet);
}
However all this is rather fragile and doesn't prevent the form from being submitted. I would recommend using jquery unobtrusive validation along with the RemoteAttribute for checking if an existing email exists, and the Required and EmailAttribute for ensuring its a valid email address, then using @Html.ValidationMessageFor() in the view.
| |
doc_3120
|
I have googled sadly I have had no luck and I was wondering if anyone knows of a script that can read (icecast ICY metadata?)
A: Please note that web browsers don't support ICY metadata, so you'd have to implement quite a few things manually and consume the whole stream just for the metadata. I do NOT recommend this.
As you indicate Icecast, the recommended way to get metadata is by querying the JSON endpoint: /status-json.xsl. It's documented.
It sounds like you are custom building for a certain server, so this should be a good approach. Note that you must be running a recent Icecast version (at the very least 2.4.1, but for security reasons better latest).
If you are wondering about accessing random Icecast servers where you have no control over, it becomes complicated: https://stackoverflow.com/a/57353140/2648865
If you want to play a stream and then display it's ICY metadata, look at miknik's answer. (It applies to legacy ICY streams, won't work with WebM or Ogg encapsulated Opus, Vorbis, etc)
A: I wrote a script that does exactly this.
It implements a service worker and uses the Fetch API and the Readable Streams API to intercept network requests from your page to your streaming server, add the necessary header to the request to initiate in-stream metadata from your streaming server and then extract the metadata from the response while playing the mp3 via the audio element on your page.
Due to restrictions on service workers and the Fetch API my script will only work if your site is served over SSL and your streaming server and website are on the same domain.
You can find the code on Github and a very basic demo of it in action here (open the console window to view the data being passed from the service worker)
A: I don't know much about stream's but I've found some stuff googling lol
https://www.npmjs.com/package/icy-metadata
https://living-sun.com/es/audio/85978-how-do-i-obtain-shoutcast-ldquonow-playingrdquo-metadata-from-the-stream-audio-stream-metadata-shoutcast-internet-radio.html
also this
Developing the client for the icecast server
its for php but maybe you can translate it to JS.
| |
doc_3121
|
void testMessage() {
verifySomething(this.driver, "iPhone");
}
void verifySomething(WebDriver driver, String userAgent) {
String script = null;
if (driver instanceof HtmlUnitDriver) {
script = "navigator.userAgent=" + "'" + userAgent + "';";
}
else {
// something
}
((JavascriptExecutor) driver).executeScript(script);
}
I am getting the following error:
======= EXCEPTION START ========
EcmaError: lineNumber=[1] column=[0] lineSource=[] name=[TypeError] sourceName=[injected script] message=[TypeError: Cannot set property [Navigator].userAgent that has only a getter to iPhone. (injected script#1)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot set property [Navigator].userAgent that has only a getter to iPhone. (injected script#1)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:663)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:559)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:525)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:594)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:569)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:996)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:466)
...
...
== CALLING JAVASCRIPT ==
function () {
navigator.userAgent = "iPhone";
}
======= EXCEPTION END ========
I know that it is complaining about the setter. It use to work in selenium 2.19.0 but I guess they may have changed the property to read only.
Any help is highly appreciated.
A: You can't set anything into the navigator.userAgent.
navigator.UserAgent is just informations about your current browser.
http://www.w3schools.com/jsref/prop_nav_useragent.asp
A: For FF use this (profile.setPreference("general.useragent.override", "your useragent")
everything needs to be set up from firefox profile.
| |
doc_3122
|
Typical thumbnailLink returned: https://lh4.googleusercontent.com/p4OAiOaP0dBaE4JF…1vTCqNEUVdTH9CoCDAeAZB4D38cIvYpktGekW0IuBpRI=s220
How can I manage to display these images by using the thumbnailLink on localhost please?
import React, { useState, useEffect } from 'react'
export const App = () => {
const [ googleAuth, setGoogleAuth ] = useState({})
const [ thumbnailLink, setThumbnailLink ] = useState([])
const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.file'
const params = {
apiKey: 'XXXXXXXXXXXX',
client_id: 'XXXXXXXXXXXX.apps.googleusercontent.com',
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
scope: SCOPES
}
useEffect(() => {
window.gapi && window.gapi.load('client:auth2', () => {
window.gapi.client.init(params)
.then(onInit)
})
}, [])
const onInit = () => {
setGoogleAuth(window.gapi.auth2.getAuthInstance())
}
const signIn = () => {
googleAuth.signIn()
.then(response => console.log('Success: ', response))
.catch(err => console.log("Error: ", err))
}
const getThumbnail = () => {
gapi.client.drive.files.get({
fileId: '1VFjfZlquVVUkHSmISKjH57UC0OaIQzVo',
fields: 'thumbnailLink'
})
.then((response) => {
setThumbnailLink(response.result.thumbnailLink)
})
.catch((err) => console.log(err))
}
return (
<>
<button onClick={signIn}>Sign In</button>
<button onClick={getThumbnail}>getThumbnail</button>
{thumbnailLink && <img src={thumbnailLink} />} // returns 403 on localhost
</>
)
}
A:
thumbnailLink string A short-lived link to the file's thumbnail. Typically lasts on the order of hours. Only populated when the requesting app can access the file's content. If the file isn't shared publicly, the URL returned in Files.thumbnailLink must be fetched using a credentialed request.
Looks like you are not sending the get request with credentials....
And It could be a problem with the scope....for this I am not sure...
And you can also check this https://developers.google.com/drive/api/guides/handle-errors?hl=en
this have almost all possible resolutions for error 403....
| |
doc_3123
|
{
$user = auth()->user();
$lat = auth()->user()->latitude;
$lon = auth()->user()->longitude;
$radius = 3; // km => converted to meter
$angle_radius = (float)$radius / ( 111 * cos( (float)$lat ) ); // Every lat|lon degree° is ~ 111Km
$min_lat = (float)$lat - (float)$angle_radius;
$max_lat = (float)$lat + (float)$angle_radius;
$min_lon = (float)$lon - (float)$angle_radius;
$max_lon = (float)$lon + (float)$angle_radius;
$persons = User::where('status', STATUS::ACTIVE)
->where('id', '!=', $user->id)
->whereBetween('latitude', [$min_lat, $max_lat])
->whereBetween('longitude', [$min_lon, $max_lon])
->get();
$persons->each(function($person) {
/* auth user coordinate vs user's coordinates */
$point1 = array('lat' => auth()->user()->latitude, 'long' => auth()->user()->longitude);
$point2 = array('lat' => $person->latitude, 'long' => $person->longitude);
$distance = $person->getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
$person['distance'] = $distance;
});
return $persons;
}
I'm searching users within the 3km radius based on user's long/lat.
I'm comparing auth long/lat to nearby user long/lat. It returns collections of user with distance.
Now I am having trouble sorting it by distance.
If I add orderBy('distance', 'desc') of course it will result an error, because I do not have distance column on my DB.
Is their a way to sort it and paginate it.
A: The $persons variable is a collection object, you can use collection methods found in the documentation here: https://laravel.com/docs/5.6/collections#available-methods
You can use the sortBy function of the collection object.
The pagination of laravel is in database query level (https://laravel.com/docs/5.6/pagination), so that you can use the eloquent orderBy method.
If you want to make this work, put a distance column in the users table, but I think you don't want this because you programmatically compute the distance in the getDistanceBetweenPoints.
Another solution that I think of is create a separate table for the distances of each user.
You must think of a solution that will sort distance in the database query level.
Hope this will help you to solve your problem: latitude/longitude find nearest latitude/longitude - complex sql or complex calculation
A: This may help.
$persons->sortBy('distance');
return $persons;
| |
doc_3124
|
TITLE: Connect to Server
Cannot connect to ..
ADDITIONAL INFORMATION:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)
The system cannot find the file specified
| |
doc_3125
|
when i use "var_dump" it shows my function is working correctly and too many $result numbers are created. but when i use ORM INSERT Statement to save them into my database , it always SAVE : 2147483648 in database and it seems it's not depended on my $result !!!!!
here is my code :
public function Timer($Number)
{
$i=0;
while ($i<$Number)
{
$microtime = microtime(true);
$milliseconds = sprintf("%02d", ($microtime - floor($microtime)) * 96 * 62 * 23 * 43);
$result=date('His'. $milliseconds, $microtime)."";
$result=substr($result,1,11);
DB::table('form')->insert([
'Number' => $result,
'IsValid' => false
]);
$i++;
}
}
A: 2147483647 is maximum number for signed INT. So, try to use unsigned BIGINT or VARCHAR to store the value.
Or you could use another way to build random codes, like str_random() or something similar.
| |
doc_3126
|
My user should enter information for an appointment. Once Submit is hit a document window should pop up. The submit button appears to work. The clear button is working also. I programmed a function to handle the window and set the onSubmit to return the function.
< script type = "text/javascript" >
function popUpWindow() { //window should return user's name in a window
newWin = window.open('', 'NewWin', 'toolbar=no,status=no,width=500,height=200');
newWin.document.write("<body bgcolor='yellow'><h3>Appointment Confirmation</h3>);
newWin.document.write("
Your name is: " + document["
form "].name.value);
newWin.document.close();
}
</script>
<html>
<head>
<title>Project</title>
</head>
//this form should accept user's input
<body>
<form name="form" onSubmit="return popUpWindow();">
Please enter your name:
<input type="text" name="name" value="" size="50" />
</p>
<p>
Address:
<input type="text" name="address" size="50" />
</p>
<p>
Phone:
<input type="text" name="area_code" size="10" />
</p>
<p>
Email:
<input type="text" name="email" value="" size="20" />
</p>
<p>
<legend>Stylist</legend>
</p>
<input type="radio" name="stylist" id="stylist1" value="dream" />Dream
<input type="radio" name="stylist" id="stylist2" value="aubrey" />Aubrey
<input type="radio" name="stylist" id="stylist3" value="stag" />Stag
<input type="radio" name="stylist" id="stylist1" value="halo" />Halo
<p>
<legend>Services</legend>
</p>
<input type="checkbox" name="service" id="service1" value="cut" />Cut
<br/>
<input type="checkbox" name="service" id="service2" value="relaxer" />Relaxer
<br/>
<input type="checkbox" name="service" id="service1" value="weave" />Weave
<br/>
<input type="checkbox" name="service" id="service1" value="braids" />Braids
<br/>
<input type="checkbox" name="service" id="service1" value="wash" />Wash and Style
<br/>
<input type="checkbox" name="service" id="service1" value="natural" />Natural
<br/>
<p>Leave Comments</p>
<textarea name="comments" id="comments" align="left" rows "8" cols "75"></textarea>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
| |
doc_3127
|
Exception Type:
System.Web.HttpException
Exception: A potentially dangerous Request.Path value was detected from the client (:).
Stack Trace:
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)
This happens when there's a colon at the end of the URL, and this can be caused by email software that includes the colon in a email written as "my site is at www.someurl.com: you'll find the info".
I want to rewrite and redirect every URL that ends with a colon to the same URL without the colon in last position.
This is what I have: an entry I add in the web.config
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite without last colon">
<match url="[:]\z" /> //not sure this is correct
<action type="Rewrite" url="not sure what to put" />
</rule>
</rules>
</rewrite>
</system.webServer>
A: You can try this rewrite rule.
<rule name="Remove colon" stopProcessing="true">
<match url="(.*):$" />
<action type="Rewrite" url="{R:1}" />
</rule>
(.*) = everything before the :
$ = end of the string to be matched
References
https://learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
https://ruslany.net/2009/04/10-url-rewriting-tips-and-tricks/
| |
doc_3128
|
When I place a dx-toolbar and set locateInMenu="always" for toolbar items, I see a dropdown button with dx-icon-overflow.
Is there any way to customize this button to have a string on it?
A: I used CSS to update that dropdown button.
.customized-toolbar .dx-toolbar-button .dx-dropdownmenu-button .dx-button-content {
& > i {
display: none !important;
}
&:after {
display: block;
content: 'Other Actions';
color: white;
line-height: 18px;
font-size: 14px;
}
}
| |
doc_3129
|
function previewPDF(url,canvasName){
PDFJS.workerSrc = 'js/pdfJS/pdf.worker.js';
PDFJS.getDocument(url).then(function getPdf(pdf) {
pdf.getPage(1).then(function getPage(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById(canvasName);
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
}
However, now I need only a print button with which I can print the pdf file. I have tried numerous times with window.print() but it does not seem to work. Do you have any ideas how I can I do that?
Thank you in advance!!!
| |
doc_3130
|
In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35.
Opening the Network tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35 is present.
in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http.
Is there a way to access in $http the 'raw' response and write our custom parser for the header?
$http.({method: 'GET', url: apiUrl,)
.then( function(response){
console.log('headers: ', response.headers());
console.log('results header: ', response.headers('X-Total-Results'));
// ...
})
console output
headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}
results header: null
A: The reason you can't read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header.
Your server needs to send this header:
Access-Control-Expose-Headers:X-Total-Results
To answer your question in the comments, The Access-Control-Allow-Headers does not allow wildcards according to the W3 Spec
A: Use $httpProvider.interceptors you can intercept both the request as well as the response
for example
$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
return {
'responseError': function (response) {
console.log(response.config);
},
'response': function (response) {
console.log(response.config);
},
'request': function (response) {
console.log(response.config);
},
};
}]);
Update : You can retrive your headers info in call itself
$http.({method: 'GET', url: apiUrl)
.then( (data, status, headers, config){
console.log('headers: ', config.headers);
console.log('results header: ', config.headers('X-Total-Results'));
// ...
})
| |
doc_3131
|
In "desktop" mode, I want the brand logo and other words on the left, and the menu on the right.
In "mobile" mode, I would a block with the logo and other words, and below the menu that should take the whole row.
Any suggestion to obtain this result?
Link to JsFiddle
As you can see I defined some CSS ids, just to have:
display:block
One for the container of the logo+words (on the left) and one for the container of the menu (on the right).
It does not work as I would, because I do not know how to put the menu below the brand's name when I am in mobile mode.
A: I hope this is the result you are looking for:
The CSS to add
@media screen and (max-width: 768px) {
#logo {
display: inline-block;
float: none;
width:100%;
text-align:center;
}
#nav-logo {
display: inline-block;
float: none;
width:100%;
text-align:center;
}
.navbar-header button {
float:none;
margin:15px 0px;
}
}
JSFiddle example
If you want the menu above, invert the html blocks id="nav-logo" and id="logo"... the updatade JSFiddle here.
| |
doc_3132
|
For this i have use model in view.My code is
@using MyProject.Models
@model Role
<h2>AddRole</h2>
@using (Html.BeginForm()){
@Html.LabelFor(m=>m.RoleName)
@Html.TextBoxFor(m=>m.RoleName)<br />
<input type="submit" value="Add Role" />
}
After submitting,it goes to AddRole action in my controller,where I am adding this role to database and return back to same view.
code for AddRole is,
[HttpPost]
public ActionResult AddRole(Role role)
{
//Code for adding role into database
using (UserDbContext db = new UserDbContext())
ViewBag.Message= "Role successfully added.";
return View("AddRole");
}
After adding values to database,it is still showing the already type values in textboxes.
I want it must not show those values after adding into database.
I think it is,sending that role values back to view,that's why it is showing those values in form.So i try to make that value null in action.But not work.
Thanks in advance.
A: You could either do ModelState.Clear() or do a GET request back to your AddRole page i.e. return RedirectToAction("AddRole"). However, the latter would not keep keep your ViewBag.Message;
A: Try using
Role newRole=new Role();
ModelState.Clear(); // the fix
return View("AddRole",newRole);
Update me if it Worked?
| |
doc_3133
|
Field2.Text = Text((5*Value(Self.Text))-10)
Any suggestions please?
| |
doc_3134
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>my-search-frontend</artifactId>
<packaging>pom</packaging>
<version>1.11.0-SNAPSHOT</version>
<name>my search frontend</name>
<description>my search frontend</description>
<parent>
<artifactId>my-search</artifactId>
<groupId>com.regalo.my</groupId>
<version>1.11.0-SNAPSHOT</version>
</parent>
<build>
<finalName>my-search-frontend</finalName>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<filesets>
<fileset>
<directory>node_modules</directory>
<includes>
<include>**/*</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
<fileset>
<directory>build</directory>
<includes>
<include>**/*</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<id>npm-install</id>
<phase>initialize</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
<workingDirectory>${project.basedir}</workingDirectory>
</configuration>
</execution>
<execution>
<id>npm-run-build</id>
<phase>generate-sources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
<workingDirectory>${project.basedir}</workingDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<skipDocker>${skip.docker}</skipDocker>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<dockerDirectory>${project.basedir}/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/build</targetPath>
<directory>${project.basedir}/build</directory>
<include>**/*</include>
</resource>
<resource>
<targetPath>/build</targetPath>
<directory>${project.basedir}</directory>
<includes>
<include>index.html</include>
</includes>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<configuration>
<to>
<image>${docker.repository.host}/${project.artifactId}:${project.version}</image>
</to>
<!-- <skip>${skip.docker}</skip> -->
<extraDirectories>
<paths>
<path>
<from>${project.basedir}</from>
<into>/build</into>
</path>
</paths>
</extraDirectories>
</configuration>
</plugin>
</plugins>
</build>
</project>
Spotify one is the way previously we did it and now we are moving to Jib. But I am getting sollowing issue for this app build,
[ERROR] Failed to execute goal com.google.cloud.tools:jib-maven-plugin:2.7.1:build (default-cli) on project my-search-frontend: Obtaining project build output files failed; make sure you have compiled your project before trying to build the image.
(Did you accidentally run "mvn clean jib:build" instead of "mvn clean compile jib:build"?): /home/cyrex/Documents/Sourcecode/my-search/my-search-frontend/target/classes -> [Help 1]
Project structure of app
Help on this would highly appreciate.
A: The Jib Maven and Gradle plugins are for Java apps, and the error message is complaining that there are no compiled .class files in your NPM module. However, technically, you may be able to make Jib build an NPM image with some tricks (for example, put a dummy DummyClass.java under src/main/java to bypass the error, override <container><entrypoint> to not execute java, use <extraDirectories> to put arbitrary files, set <from><image> to use a non-JRE base image, etc.). You may also need to remove files using the Jib Layer-Filter extension. However, since Jib is really tailored to Java apps, I cannot really recommend it.
Just FYI, Jib is highly customizable and extensible with the Jib Extension Framework, so theoretically you could write an NPM Jib extension to cover this highly specialized workflow (and share it with the Jib community).
Also for non-Java apps and non-Maven workflows, we have other Jib solutions: Jib Core (the Java library) and Jib CLI. Jib CLI may work in this case, although it's a not a Maven plugin. (I don't know if it's a good idea, but FYI, there seems a few ways to run an arbitrary command in Maven.)
Related, this article shows an example that uses the Jib Layer-Filter extension to enable use cases not supported by Jib.
A: To offer an alternative if anyone is still looking going forward (this was first hit for my google search):
you can set the jib plugin to use the packaged .jar file, which is auto generated if you use mvn package and pretty small if no code exists (~2kb)
Also make sure that your project doesn't have a parent or dependencies, otherwise jib will copy the libraries into the image.
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.12.0</version>
<executions>
<execution>
<goals>
<goal>install-node-and-npm</goal>
</goals>
</execution>
<execution>
<goals>
<goal>npm</goal>
</goals>
</execution>
<execution>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
<configuration>
<nodeVersion>v16.9.1</nodeVersion>
</configuration>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>2.7.1</version>
<configuration>
<containerizingMode>packaged</containerizingMode>
<extraDirectories>
<paths>
<path>
<from>build</from>
<into>/var/www/html</into>
</path>
</paths>
</extraDirectories>
<container>
<entrypoint>INHERIT</entrypoint>
</container>
<from>
<image>nginx</image>
</from>
<to>
<image>THE IMAGE NAME:${project.version}</image>
</to>
</configuration>
</plugin>
</plugins>
</build>
to create it: mvn clean package jib:dockerBuild
use dive to check if unnecessary files were added
A: JIB is only for java projects. It handles installing a Java Runtime and dependencies in optimized layers. But it cannot create NPM docker images.
So you can only enable the jib-maven-plugin maven plugin for java modules.
For NPM, you should stick to the spotify docker-maven-plugin or something similar.
Or give fabric8 a try.
| |
doc_3135
|
In my work, i will move in a map, but selenium will work well ,when my screen resolution is 1920*1080, and it doesn't work when my screen resolution is 1366*768.
the code is that:
ChromeDriver driver =(ChromeDriver)webDriver;
WebElement map =driver.findElementsByClassName("ol-unselectable").get(0); // a MAP
Actions actions =new Actions(driver);
System.out.println(map.getSize());
int x =map.getSize().width;
int y =map.getSize().height;
actions.moveToElement(map,0,0).perform();
actions.moveByOffset(5,5).click().perform();
actions.moveByOffset((int)(x*0.5),0).click().perform();
actions.sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).perform();
actions.sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).perform();
actions.sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).perform();
actions.moveToElement(map,(int)(x*0.5),(int)(y*0.8)).click().perform();
actions.doubleClick().perform();
the code
actions.moveToElement(map,(int)(x*0.5),(int)(y*0.8)).click().perform();"
doesn't work when I use a low resolution.
the MAP looks like this:
when my Screen Resolution is: 1920*1080, my Code running result looks like this:
when I change my Screen Resolution to 1366*768, my Code running result looks like this:
So,we can find that,action can't move to the map element{0.5 width, 0.9 high}.
How should I do?
A: Few points required sometimes with Actions class:
*
*Your element should be present on DOM, if it not how mouse hover would work? (To overcome it. Use scroll up or donw according to the position of the element)
*If more than one actions you are performing then use build().perform(); not only .perform().
*Sometimes we can use JavaScript focus method to focus on element before doing any actions using Actions class like below code:
JavascriptExecutor js = (JavascriptExecutor) ts.getDriver();
js.executeScript("arguments[0].focus();", we);
actions.moveToElement(map,(int)(x*0.5),(int)(y*0.8)).click().build().perform();
A: Try this :
actions builder = new Actions(driver);
builder.moveToElement(map,(int)(x*0.5),(int)(y*0.8)).click().build().perform();
Maybe that will solve your problem
Sorry i can not just comment under your question ...
A: Try this,
actions builder = new Actions(driver);
builder.moveToElement(map,(int)(x*0.5),(int)(y*0.8)).click().build().perform();
please try it. if i am not wrong, it will solve the issue.
| |
doc_3136
|
Example:
I have input dataset with 3 columns[EMPID,EMPNAME,EMP_DEPT] and I want to process these data using mapreduce. In the reduce phase is it possible to add new columns say TIMESTAMP(system timestamp when record get processed). Output of the reducer should be EMPID,EMPNAME,EMP_DEPT,TIMESTAMP
Input Data:
EMPID EMPNAME EMP_DEPT
1 David HR
2 Sam IT
Output Data:
EMPID EMPNAME EMP_DEPT Timestamp
1 David HR XX:XX:XX:XX
2 Sam IT XX:XX:XX:XX
A: It seems the purpose of your MapReduce is just to add the timestamp "column" (regarding your input and output example there is no other modification/transformation/processing of the EMPID, EMPNAME and EMP_DEPT fields). If that is the case, the only thing you have to do is to add to the read lines ("rows") the timestamping in the mapper; then let the reducer joins all the new "rows". Workflow:
Each input file is splited into many chunks:
(input file) --> spliter --> split1, split2, ..., splitN
Each split content is:
split1 = {"1 David HR", "2 Sam IT"}
split2 = {...}
Splits are assigned to mappers (one per split), which output (key,value) pairs; in this case, it is enough with a common key for all the pairs:
(offset, "1 David HR") --> mapper1 --> ("key", "1 David HR 2015-06-13 12:23:45.242")
(offset, "2 Sam IT") --> mapper1 --> ("key", "2 Sam IT 2015-06-13 12:23:45.243")
...
"..." --> mapper2 --> ...
...
The reducer receives an array, for each different key, with all the pairs outputted by the mappers that have such a key:
("key", ["1 David HR 2015-06-13 12:23:45.242", "2 Sam IT 2015-06-13 12:23:45.243"]) --> reducer --> (output file)
If your aim is to finally process the original data in some way, do it at the mapper, in addition to the timestamping.
| |
doc_3137
|
But the problem is that it tells me that the source file doesn't exist, what did I do wrong?
Also, is That even a good approach? It will save a copy of the images in folders and retrieve this data in a recycler view; Is there a reason to preferer using a database?
Here is the code for receiving a shared image:
String action = getIntent().getAction(); //Action: receive a shared file.
if (Intent.ACTION_SEND.equals(action)) {
mImageUri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
try {
copyFileForBiggerFiles(new File(mImageUri.getPath()), getFilesDir());
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the code for copying that photo in the internal :
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) { //problem accrues here
return;
}
FileChannel source;
FileChannel destination;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
A: You need to consider that a uri is not necessarily a file uri (file://), so using mImageUri.getPath() does not work when for example a content uri (content://) is passed from the sharing application. When you're dealing with a passed uri it's best to open your input stream using ContentResolver.openInputStream() since it handles both content and file uri scheme types internally:
private void copyFile(Context context, Uri sourceUri, File destFile) throws IOException {
InputStream in = context.getContentResolver().openInputStream(sourceUri);
try {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
OutputStream out = new FileOutputStream(destFile);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
And call it in you activity:
copyFile(this, mImageUri.getPath(), new File(context.getFilesDir(), "fileName"));
| |
doc_3138
|
I am trying to use g_object_set_property as follows:
GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
GValue val = G_VALUE_INIT;
g_value_init (&val, G_TYPE_ENUM);
g_value_set_enum (&val, PANGO_ELLIPSIZE_END);
g_object_set_property (G_OBJECT(renderer), "ellipsize", &val);
However, I get an error message at run time:
(infog:27114): GLib-GObject-WARNING **: 12:24:29.848: ../../../../gobject/gvalue.c:188: cannot initialize GValue with type 'GEnum', this type is abstract with regards to GValue use, use a more specific (derived) type
How do I get the type ID for enum PangoEllipsizeMode that derives from G_TYPE_ENUM?
A: Using g_object_set instead works:
g_object_set (G_OBJECT(renderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL);
A: You need to initialise the GValue container with the type of the enumeration that the property expects. G_TYPE_ENUM is the generic, abstract enumeration type.
The "ellipsize" property of GtkCellRendererText expects a PangoEllipsizeMode enumeration value, which has a GType of PANGO_TYPE_ELLIPSIZE_MODE.
GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
GValue val = G_VALUE_INIT;
g_value_init (&val, PANGO_TYPE_ELLIPSIZE_MODE);
g_value_set_enum (&val, PANGO_ELLIPSIZE_END);
g_object_set_property (G_OBJECT(renderer), "ellipsize", &val);
// Always unset your value to release any memory that may be associated with it
g_value_unset (&val);
| |
doc_3139
|
What I want to do is compare what the backend spits out vs what I have in my hash thats like an index so when I render my view I can have the display look a bit more appealing.
Now I could do something like this with php and an array
array("monkey" => "Monkey", "server" => "server")
and then do a str_replace("monkey", $var, array)
ok thats a poor example but its been a while since I played with php and I am a bit rusty off the top of my head. But thats the notion
the end result is when I find "monkey" in one I want to replace it with "Monkey" for the view's sake.
edit/revision/addition
Ok realized Im not working with a hash, im actually working with an array or a JSON object..
pretty_service = {"namenode" => "Name Nodes","secondarynamenode" => " Secondary Name Nodes", "datanode" => "Data Nodes", "web" => "Web", "tasktracker" => "Task Trackers", "jobtracker" => "Job Trackers", "oozie" => "Oozie", "single-namenode" => "Single NameNode", "single-databse" => "Single Database" }
What I want to is if my strings I am checking contain any one of the keys I want to replace it with the value. Not sure how exactly to do that with rails styling coding. There is some decent concepts below already but I've tried them and they don't seem to work for me. Knowing this now, is there a differnt approach to working this up?
A: String.gsub can do that.
table = {"monkey"=>"Monkey", "teh"=>"the"}
str = "Don't feed teh monkey"
p str.gsub(Regexp.union(table.keys), table)
#=> "Don't feed the Monkey"
A: Here's an example of using the hash functions. You can adapt this to your needs:
if my_hash.keys.include?("monkey")
what_i_will_render.gsub!("monkey",my_hash["monkey"])
end
A: find = {:a => 'a', :b => 'b', :c => 'c'}
replace = {:a => 'A', :b => 'B'}
replace.merge(find) # {:a => 'A', :b => 'B', :c => 'c'}
| |
doc_3140
|
Thank you!
Please keep in mind I'm very new to programming and am not familiar with lambda or other complicated ways to solve this.
A: One way to do so would be to use collections.Counter
from collections import Counter
>>> d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
>>> c = Counter(d.values())
>>> c
[(5, 3), (1, 1), (3, 1)]
>>> c.most_common()[0]
(5, 3) # this is the value, and number of appearances
A: Sorting the dictionary by value should do it:
d = {'a': 5, 'b': 3, 'c': 5, 'd': 1, 'e': 5}
print(d[sorted(d, key=lambda k: d[k])[-1]])
Cyber is right, the above gets the largest value. See below to get the most frequent. My idea is to get the value without using the collections.Counter.
counts = {}
for k in d:
counts[d[k]] = counts.get(d[k], 0) + 1
print(sorted(counts)[-1]) # 5
print(counts) # {1: 1, 3: 1, 5: 3}
| |
doc_3141
|
In the past I've used Rubymine and I remember it automatically loading the folders for all the gems, in the "project view" on the left side, at the bottom, titled "External Libraries." For some reason I am only getting what's in the picture below. I feel as if it may be some sort of RVM issue because it's only showing 2.0.0 when this project has a .ruby-version of 2.3.1.
A: Go to File -> Settings -> Languages & Frameworks -> Ruby SDK and Gems. Then select the correct version of Ruby your code is using (in this case, 2.3.1). This should make the "External Libraries" section on project window to load from the correct version of gem home. Restart Rubymine if necessary.
| |
doc_3142
|
E.g- suppose i want my header with value Address (*"MANDATORY) with below given color.
Address - in Black Color
*"MANDATORY - in Red Color
I came through a method for changing the fontColor provided by apache-poi but that is changing the font color of whole cell value but i want a specific text in different color.
How to resolve above issue ?
A: To fulfill your requirement the cell would must contain rich text string content. This is possible using Cell.setCellValue(RichTextString value). The RichTextString can be created as it is described in Busy Developers' Guide to HSSF and XSSF Features.
Let's have an example which provides a method createRichTextString(Workbook workbook, String[] textParts, Font[] fonts) which creates a RichTextString for an array of text parts using an array of fonts.
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelRichText {
static RichTextString createRichTextString(Workbook workbook, String[] textParts, Font[] fonts) {
CreationHelper creationHelper = workbook.getCreationHelper();
RichTextString richTextString = creationHelper.createRichTextString(String.join("", textParts));
int start = 0;
int end = 0;
for (int tp = 0; tp < textParts.length; tp ++) {
Font font = null;
if (tp < fonts.length) font = fonts[tp];
end += textParts[tp].length();
if (font != null) richTextString.applyFont(start, end, font);
start += textParts[tp].length();
}
return richTextString;
}
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();
String fileName = (workbook instanceof XSSFWorkbook)?"Excel.xlsx":"Excel.xls";
Font font = workbook.createFont(); // default font
Font fontRed = workbook.createFont();
fontRed.setColor(Font.COLOR_RED);
String[] textParts = new String[]{"Address (", "*\"MANDATORY", ")"};
Font[] fonts = new Font[]{font, fontRed, font};
RichTextString richTextString = createRichTextString(workbook, textParts, fonts);
Sheet sheet = workbook.createSheet();
sheet.createRow(0).createCell(0).setCellValue(richTextString);
FileOutputStream out = new FileOutputStream(fileName);
workbook.write(out);
out.close();
workbook.close();
}
}
| |
doc_3143
|
"{\"id\":\"c39fe0f5f9b7c89b005bf3491f2a2ce1\",\"token\":\"c39fe0f5f9b7c89b005bf3491f2a2ce1\",\"line_items\":[{\"id\":32968150843480,\"properties\":{},\"quantity\":2,\"variant_id\":32968150843480,\"key\":\"32968150843480:4a6f6b7d19c7aef119af2cd909f429f1\",\"discounted_price\":\"40.00\",\"discounts\":[],\"gift_card\":false,\"grams\":0,\"line_price\":\"80.00\",\"original_line_price\":\"80.00\",\"original_price\":\"40.00\",\"price\":\"40.00\",\"product_id\":4638774493272,\"sku\":\"36457537-mud-yellow-28\",\"taxable\":false,\"title\":\"Knee Length Summer Shorts - Camel / 28\",\"total_discount\":\"0.00\",\"vendor\":\"Other\",\"discounted_price_set\":{\"shop_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"}},\"line_price_set\":{\"shop_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"}},\"original_line_price_set\":{\"shop_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"}},\"price_set\":{\"shop_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"}},\"total_discount_set\":{\"shop_money\":{\"amount\":\"0.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"0.0\",\"currency_code\":\"USD\"}}}],\"note\":null,\"updated_at\":\"2022-03-15T13:24:02.787Z\",\"created_at\":\"2022-03-15T13:23:31.912Z\",\"controller\":\"custom_webhooks\",\"action\":\"store_data\",\"custom_webhook\":{\"id\":\"c39fe0f5f9b7c89b005bf3491f2a2ce1\",\"token\":\"c39fe0f5f9b7c89b005bf3491f2a2ce1\",\"line_items\":[{\"id\":32968150843480,\"properties\":{},\"quantity\":2,\"variant_id\":32968150843480,\"key\":\"32968150843480:4a6f6b7d19c7aef119af2cd909f429f1\",\"discounted_price\":\"40.00\",\"discounts\":[],\"gift_card\":false,\"grams\":0,\"line_price\":\"80.00\",\"original_line_price\":\"80.00\",\"original_price\":\"40.00\",\"price\":\"40.00\",\"product_id\":4638774493272,\"sku\":\"36457537-mud-yellow-28\",\"taxable\":false,\"title\":\"Knee Length Summer Shorts - Camel / 28\",\"total_discount\":\"0.00\",\"vendor\":\"Other\",\"discounted_price_set\":{\"shop_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"}},\"line_price_set\":{\"shop_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"}},\"original_line_price_set\":{\"shop_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"80.0\",\"currency_code\":\"USD\"}},\"price_set\":{\"shop_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"40.0\",\"currency_code\":\"USD\"}},\"total_discount_set\":{\"shop_money\":{\"amount\":\"0.0\",\"currency_code\":\"USD\"},\"presentment_money\":{\"amount\":\"0.0\",\"currency_code\":\"USD\"}}}],\"note\":null,\"updated_at\":\"2022-03-15T13:24:02.787Z\",\"created_at\":\"2022-03-15T13:23:31.912Z\"}}"
this real JSONB column
I can not find any example of how to deal with this type of JSONB
A: Whatever is inserting your data is screwing it up. It is taking the string representation of a JSON object and stuffing that into a JSON string scalar. You need to fix that or it will just keep happening.
To fix what is already there, you need to extract the real PostgreSQL string out of the JSON string, then cast that to JSONB. Extracting a JSON string can be done unintuitively with #>>'{}', or even less intuitively with ->>0.
select (data#>>'{}')::jsonb from table_name.
Of course you should fix it permanently, not just do it on the fly all the time, which is both slow and confusing.
update table_name set data=(data#>>'{}')::jsonb;
Of course fixing the tool which screws this up in the first place, and fixing the historical data, need to be done in a coordinated fashion or you will have a glorious mess on your hands.
A: I think you have wrong formatted string in jsonb field. You can try fix it in next way:
select trim(both '"' from replace(data::varchar, '\"', '"'))::jsonb data from tbl;
PostgreSQL JSONB online
| |
doc_3144
|
I think I know how to get rid of the blank spaces, but my list has some data that no weighted average for that day. So I need to search my list and delete any value that does not have a space after it, then search back through the list and delete all the spaces.
For example I want this:
[754, 753.554, '', '', '', '', '', 653.455, '', '', 258, 235.6464, '' , '', '']
to return:
[753.554, 653.455, 235.6464]
Any advice?
A: >>> l = [754, 753.554, '', '', '', '', '', 653.455, '',
'', 258, 235.6464, '' , '', '']
>>> filter(None, [i for i, j in zip(l, l[1:] + ['']) if j == ''])
[753.554, 653.455, 235.6464]
A: Actually this is enough:
data = filter(None, [754, 753.554, '', '', '', '', '', 653.455, '', '', 258, 235.6464, '' , '', ''])
Assuming that weighted average will be floating numbers:
filter(lambda x: not isinstance(x, int),filter(None, a))
But you can also replace lambda x: not isinstance(x, int) with a function:
def is_not_weight_avg(x):
# do stuff here
# if it is w. avg.
return x
and then you can write the above line as:
filter(is_weight_avg,filter(None, a)).
This is a little bit of functional programming in Python. Explanation:
b=range(1,11)
def is_odd(x):
if x % 2:
return 0
else:
return x
filter(is_odd, b)
>>> [2, 4, 6, 8, 10]
| |
doc_3145
|
Now what I want to do is the contents that are generated from UserDontrol, the values that are underlined I want to store them in database. I create a public class but in database it is stored as empty value (not NULL).
These are the codes:
.ascx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UserControl_ContactDetails : System.Web.UI.UserControl
{
public String TextProperty
{
get
{
return LabelCmimi.Text;
}
set
{
LabelCmimi.Text = value;
}
}
public void Page_Load(object sender, EventArgs e)
{
//if(Page.IsPostBack)
//{
DropDownListArtikulli.Text = Request.Form[DropDownListArtikulli.UniqueID];
LabelCmimi.Text = Request.Form[LabelCmimi.UniqueID];
TextBoxSasia.Text = Request.Form[TextBoxSasia.UniqueID];
LabelVlera.Text = Request.Form[LabelVlera.UniqueID];
//}
Cmimi();
Vlera();
Session["Artikulli"] = DropDownListArtikulli.SelectedItem.ToString();
Session["Cmimi"] = LabelCmimi.Text;
Session["Sasia"] = TextBoxSasia.Text;
Session["Vlera"] = LabelVlera.Text;
}
public void Cmimi()
{
DataTable listaArtikujt = new DataTable();
using (SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [Artikujt]", lidhje);
adapter.Fill(listaArtikujt);
DropDownListArtikulli.DataSource = listaArtikujt;
DropDownListArtikulli.DataTextField = "Artikulli";
DropDownListArtikulli.DataValueField = "Cmimi";
DropDownListArtikulli.DataBind();
LabelCmimi.Text = DropDownListArtikulli.SelectedValue.ToString();
}
catch (Exception ex)
{
Response.Write("Gabim:" + ex.ToString());
}
}
}
public void Vlera()
{
if(!string.IsNullOrEmpty(TextBoxSasia.Text))
{
LabelVlera.Text = TextBoxSasia.Text.ToString();
int a = Convert.ToInt32(LabelCmimi.Text);
int b = Convert.ToInt32(LabelVlera.Text);
int c = a * b;
LabelVlera.Text = c.ToString();
Session["Totali"] = (Session["Totali"] == null) ? 0 : Convert.ToInt32(Session["Totali"].ToString()) + c;
}
}
}
.aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class DynamicControl : System.Web.UI.Page
{
private const string VIEWSTATEKEY = "ContactCount";
protected void Page_Load(object sender, EventArgs e)
{
//Set the number of default controls
ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 1 : ViewState[VIEWSTATEKEY];
Session["Totali"] = 0;
//Load the contact control based on Vewstate key
LoadContactControls();
}
private void LoadContactControls()
{
for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
{
phContactDetails.Controls.Add(LoadControl("~/UserControl/ContactDetails.ascx"));
}
}
protected void btnAddMore_Click(object sender, EventArgs e)
{
ViewState[VIEWSTATEKEY] = int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
LoadContactControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void OK_Click(object sender, EventArgs e)
{
LabelTotal.Text = Session["Totali"].ToString();
}
}
The question is... how can I store the values in database when I press the button "Dergo" (Button1_Click)?
P.S. A friend told me that the problem is cased by the user control have reload in my Page_Load event, so I get the value is always empty.
And if I want to get the value, he suggested me to add a event in my user control, and then get my input value from the event. And e refer link http://msdn.microsoft.com/en-us/library/fb3w5b53(v=vs.100).aspx
I took his advice but I started learning ASP.NET 2 weeks ago and I didn't succeed. Can anyone help me with more info or write the code please?
Thank You.
A: you need to define property on .ascx.cs to return value of the dropdwon, textbox, and controls you need their value...
and in .aspx.cs and in click handler you can read usercontrol properties simply, like this USERCONTROL_ID.DropDownValue ... DropDownValue is a property on your user control like this:
public string DropDownValue
{
get
{
return DropDownList1.SelectedValue;
}
}
and then you can save everything you want in database
also you can have one property which return a object containing all values like:
public UserControlValue Value
{
get
{
return new UserControlValue(DropDownList1.SelectedValue, TextBox1.Text);
}
}
public class UserControlValue
{
public UserControlValue(string property1, string property2)
{
this.property1 = property1;
this.property2 = property2;
}
public string property1 {get; set;}
public string property2 {get; set;}
}
and read this from aspx.cs like USERCONTROL_ID.Value.property1 or USERCONTROL_ID.Value.property2
A: how about get id of controls after loading and add them to session,
control o = LoadControl("~/UserControl/ContactDetails.ascx");
(Session["controlIDList"] as List<string>).Add(o.ID);
you need to create session before, maybe in page load using this
Session.Add("controlIDList", new List<string>());
and find controls from saved id list in session, and then cast to its type, and get the value you want...
(Session["controlIDList"] as List<string>).ForEach(u =>
{
var c = (TYPE_OF_USERCONTROL)this.Page.FindControl(u);
c.Value; // value is a property on user controls which return value of dropdown, textbox, and ....
});
| |
doc_3146
|
scalaVersion := "2.12.12"
using play-json
"com.typesafe.play" %% "play-json" % "2.9.1"
If I have a Json object that looks like this:
{
"UpperCaseKey": "some value",
"AnotherUpperCaseKey": "some other value"
}
I know I can create a case class like so:
case class Yuck(UpperCaseKey: String, AnotherUpperCaseKey: String)
and follow that up with this chaser:
implicit val jsYuck = Json.format[Yuck]
and that will, of course, give me both reads[Yuck] and writes[Yuck] to and from Json.
I'm asking this because I have a use case where I'm not the one deciding the case of the keys and I've being handed a Json object that is full of keys that start with an uppercase letter.
In this use case I will have to read and convert millions of them so performance is a concern.
I've looked into @JsonAnnotations and Scala's transformers. The former doesn't seem to have much documentation for use in Scala at the field level and the latter seems to be a lot of boilerplate for something that might be very simple another way if I only knew how...
Bear in mind as you answer this that some Keys will be named like this:
XXXYyyyyZzzzzz
So the predefined Snake/Camel case conversions will not work.
Writing a custom conversion seems to be an option yet unsure how to do that with Scala.
Is there a way to arbitrarily request that the Json read will take Key "XXXYyyyZzzz" and match it to a field labeled "xxxYyyyZzzz" in a Scala case class?
Just to be clear I may also need to convert, or at least know how, a Json key named "AbCdEf" into field labeled "fghi".
A: Just use provided PascalCase.
case class Yuck(
upperCaseKey: String,
anotherUpperCaseKey: String)
object Yuck {
import play.api.libs.json._
implicit val jsonFormat: OFormat[Yuck] = {
implicit val cfg = JsonConfiguration(naming = JsonNaming.PascalCase)
Json.format
}
}
play.api.libs.json.Json.parse("""{
"UpperCaseKey": "some value",
"AnotherUpperCaseKey": "some other value"
}""").validate[Yuck]
// => JsSuccess(Yuck(some value,some other value),)
play.api.libs.json.Json.toJson(Yuck(
upperCaseKey = "foo",
anotherUpperCaseKey = "bar"))
// => JsValue = {"UpperCaseKey":"foo","AnotherUpperCaseKey":"bar"}
A: I think that the only way play-json support such a scenario, is defining your own Format.
Let's assume we have:
case class Yuck(xxxYyyyZzzz: String, fghi: String)
So we can define Format on the companion object:
object Yuck {
implicit val format: Format[Yuck] = {
((__ \ "XXXYyyyZzzz").format[String] and (__ \ "AbCdEf").format[String]) (Yuck.apply(_, _), yuck => (yuck.xxxYyyyZzzz, yuck.fghi))
}
}
Then the following:
val jsonString = """{ "XXXYyyyZzzz": "first value", "AbCdEf": "second value" }"""
val yuck = Json.parse(jsonString).validate[Yuck]
println(yuck)
yuck.map(yuckResult => Json.toJson(yuckResult)).foreach(println)
Will output:
JsSuccess(Yuck(first value,second value),)
{"XXXYyyyZzzz":"first value","AbCdEf":"second value"}
As we can see, XXXYyyyZzzz was mapped into xxxYyyyZzzz and AbCdEf into fghi.
Code run at Scastie.
Another option you have, is to usd JsonNaming, as @cchantep suggested in the comment. If you define:
object Yuck {
val keysMap = Map("xxxYyyyZzzz" -> "XXXYyyyZzzz", "fghi" -> "AbCdEf")
implicit val config = JsonConfiguration(JsonNaming(keysMap))
implicit val fotmat = Json.format[Yuck]
}
Running the same code will output the same. Code ru nat Scastie.
| |
doc_3147
|
When myURL is set to 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml' as shown in the following code snippet, the map plus overlay displays as expected. The overlay file is taken from an example shared by Google.
When myURL is set to 'https://www.dropbox.com/s/hq09lfaya2cmu87/test.kml', Google returns an error saying that the document is invalid (status returned is INVALID_DOCUMENT) even though the content of each files is indentical.
// var myURL = 'https://www.dropbox.com/s/hq09lfaya2cmu87/test.kml';
var myURL = 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml';
var myLayer = new google.maps.KmlLayer({
url: myURL
});
google.maps.event.addListener(myLayer,'status_changed',function(){
if (myLayer.getStatus() != 'OK') {
alert('Google Maps could not load the layer: ' + myURL + ' Status returned is: ' + myLayer.getStatus());
};
});
myLayer.setMap(map);
I suspect that the issue is to do with the use of HTTPS. Any advice on this would be appreciated.
A: The issue is caused by the file download dialogue which is activated by default. Suppressing the file download dialogue through the use of the dl parameter solves the problem e.g.
var myURL = 'https://www.dropbox.com/s/hq09lfaya2cmu87/test.kml?dl=1'
working snippet:
function initialize() {
var myLatlng = new google.maps.LatLng(49.496675, -102.65625);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var myURL = 'https://www.dropbox.com/s/hq09lfaya2cmu87/test.kml?dl=1';
var myLayer = new google.maps.KmlLayer({
url: myURL
});
google.maps.event.addListener(myLayer, 'status_changed', function() {
if (myLayer.getStatus() != 'OK') {
alert('Google Maps could not load the layer: ' + myURL + ' Status returned is: ' + myLayer.getStatus());
};
});
myLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>
A: If I try to download your KML on dropbox, I get a login dialog, If I do the same to Google's file, I get the file. Google doesn't have your dropbox credentials, the file must be publicly accessible.
| |
doc_3148
|
I need the Equivalent of
lblPatient.Text = DirectCast(sender, Control).ID
'writen in vb 2010 visual web deveoper
For vb 2008
Code
Imports System.Data.SqlClient
Imports System.Data
Public Class FormRm3A
Dim Labels(40) As Label
Dim X As Integer
Dim Y As Integer
Private Sub FormArrayTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
i = 1
For Me.Y = 1 To 5
For Me.X = 1 To 8
'creates new textbox
Labels(i) = New Label()
'set its properties
Labels(i).Width = 50
Labels(i).Height = 35
Labels(i).Left = X * 49
Labels(i).Top = 30 + (Y * 34)
Labels(i).BorderStyle = BorderStyle.FixedSingle
'add control to current form
Me.Controls.Add(Labels(i))
If Clicky = True Then
AddHandler Labels(i).Click, AddressOf Label1_Click
End If
i = i + 1
Next X
Next Y
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Subject As String
Dim StaffInitials As String
For Session = 1 To 40
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("RoomBookingSystem.My.MySettings.Database1ConnectionString1").ConnectionString
Dim SessionParm As New SqlParameter("Session", Session)
SessionParm.Direction = ParameterDirection.Input
con.Open()
cmd.Connection = con
cmd.Parameters.Add(SessionParm)
cmd.CommandText = "SELECT Subject, StaffInitials FROM PermanantBooking WHERE (Week = 'A') AND(Room = 'Rm3') AND (Session = @Session)"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Subject = Convert.ToString((lrd("Subject").trim))
StaffInitials = Convert.ToString((lrd("StaffInitials").trim))
Labels(Session).Text = Subject & "" & vbNewLine & StaffInitials
End While
'Catch ex As Exception
' MsgBox("" & ex.Message)
'here if there is an error it will go here (can use Msgbox or lable)
Finally
cmd.Parameters.Clear()
con.Close()
End Try
Next
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim objectID As String
objectID = DirectCast(sender, Control).ToString
Day =
Period = X
FormMakeBookingDetails.Show()
Me.Hide()
End Sub
End Class
A: ASP.NET 3.5 already has this property(actually Control.Id exists since 1.1)), so your code should work without a problem.
Can you show the complete code and exception?
Edit:
Since you have mentioned that you're using visual web deveoper i've mistakenly assumed that you are using ASP.NET. Actually you're using Winforms. There is no Id property in Winforms unlike ASP.NET. Maybe you want to use the Name property instead(available since 1.1).
| |
doc_3149
|
#import "C:\Program Files\Microsoft Office 15\root\vfs\ProgramFilesCommonX86\Microsoft Shared\OFFICE15\MSO.DLL" rename("DocumentProperties", "DocumentPropertiesXL") rename("RGB", "RGBXL")
#import "C:\Program Files\Microsoft Office 15\root\vfs\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files\Microsoft Office 15\root\office15\EXCEL.EXE" rename("DialogBox", "DialogBoxXL") rename("RGB", "RGBXL") rename("DocumentProperties", "DocumentPropertiesXL") rename("ReplaceText", "ReplaceTextXL") rename("CopyFile", "CopyFileXL") no_dual_interfaces
The location is correct because I literally copy and paste the location.
However I get the error:
Severity Code Description Project File Line
Error C1083 Cannot open type library file: 'C:\Program Files\Common Files\Microsoft Shared\office12\mso.dll': No such file or directory
But this file or directory definitely exists. My professor said that I need administrative access, but I don't know what that means and how to change this.
How can I fix this error?
A: You did not run it as an administrator, so you cannot access folders requiring administrator access. You need to run it as admin. Read more here.
| |
doc_3150
|
Object reference not set to an instance of an object. in line 48 i.e. con.open();
Please help me solve it. And when i click on edit and insert values in shown txtboxes and then click update it shows another error:
Specified argument was out of the range of valid values. in the line 74 of my code i.e.
EmailID = (TextBox)GridView1.Rows[e.RowIndex].Cells[7].FindControl("EmailID");
The code i have used is-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Admin_viewSalesmanDetails : System.Web.UI.Page
{
SqlConnection con;
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from salesman_details";
cmd.Connection = con;
SqlDataSource1.DataBind();
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label EmpID = new Label();
EmpID = (Label)GridView1.Rows[e.RowIndex].Cells[2].FindControl("EmpID");
cmd = new SqlCommand("delete from salesman_setails where EmpID=" + EmpID.Text + "", con);
con.Open();
int k = cmd.ExecuteNonQuery();
con.Close();
if (k == 1)
{
Response.Write("<script>alert('Employee Deleted Successfully')</script>");
BindGrid();
}
else
{
Response.Write("<script>alert('Error Occured While Deleting')</script>");
BindGrid();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label EmpID = new Label();
TextBox PhnNo = new TextBox();
TextBox EmailID = new TextBox();
EmpID = (Label)GridView1.Rows[e.RowIndex].Cells[2].FindControl("EmpID");
PhnNo = (TextBox)GridView1.Rows[e.RowIndex].Cells[5].FindControl("PhnNo");
EmailID = (TextBox)GridView1.Rows[e.RowIndex].Cells[7].FindControl("EmailID");
cmd = new SqlCommand("update salesman_details set PhnNo='" + PhnNo.Text + "', EmailID='" + EmailID.Text + "' where EmpID=" + EmpID.Text + "", con);
con.Open();
int k = cmd.ExecuteNonQuery();
con.Close();
if (k == 1)
{
Response.Write("<script>alert('Employee Updated Successfully')</script>");
GridView1.EditIndex = -1;
BindGrid();
}
else
{
Response.Write("<script>alert('Error Occured While Updating')</script>");
BindGrid();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
}
A: In your GridView1_RowDeleting and GridView1_RowUpdating you haven't initialized your con and you are trying to open it.
You can either instantiate the connection at declaration or during its usage in the events.
public partial class Admin_viewSalesmanDetails : System.Web.UI.Page
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
Or the better approach would be to instantiate it within the using statement in your events. For example.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label EmpID = new Label();
EmpID = (Label)GridView1.Rows[e.RowIndex].Cells[2].FindControl("EmpID");
cmd = new SqlCommand("delete from salesman_setails where EmpID=" + EmpID.Text + "", con);
using( con = new SqlConnection(strConnection))
{
cmd.Connection = con; //here
con.Open();
int k = cmd.ExecuteNonQuery();
con.Close();
if (k == 1)
{
Response.Write("<script>alert('Employee Deleted Successfully')</script>");
BindGrid();
}
else
{
Response.Write("<script>alert('Error Occured While Deleting')</script>");
BindGrid();
}
}
}
using statement will ensure that Dispose would be called on the connection, (which would close the connection as well), even if some exception occurs.
A: Private fields are lost between PostBacks - in your events (GridView1_RowDeleting) you are using SqlConnection without initializing it first.
Add
con = new SqlConnection(strConnection);
before con.Open();
| |
doc_3151
|
It was running a task with 0 reduce tasks.
The output of each map task was clearly being written on the HDFS as part-000**
But then the system on which the hadoop system was running crashed. Now i want to copyToLocal the output of the Map tasks that completed successfully.
I can see all the "parts" listed when i do hadoop dfs -ls /output_dir, however hadoop dfs -copyFromLocal /output_dir LOCAL_PATH fails with the following error :
copyToLocal: org.apache.hadoop.hdfs.server.namenode.SafeModeException:
Zero blocklocations for ... . Name node is in safe mode.
I am not able to start my data node, most solutions that i found involved formatting the namenode using hadoop namenode -format. I do not want to loose the data.
Can the output be recovered from the dfs.tmp.dir ?
| |
doc_3152
|
When an entry get's deleted / modifyed / added, there happens an api-call to store / modify / delete the data on the database. In case I get a 200 status response, I'd like to refresh the list on the Ui.
public deleteObject {
this.http.delete(...)
.subscribe( () => {
// here the getter method would get called, to get all objects
}, (error: ErrorModel) => {
this.errorHandler.handle(error);
});
}
Which way is most common / performant to refresh the list of objects?
*
*Call this.getAllObject() to make new get-request?
*Return list of objects with the post / put / delete to avoid second server call?
*Modify / delete / add row to existing array, to prevent sending hole list again through the internet?
*Other way?
A: It would be simpler for you to remove the item from the local array.
delete(item).subscribe(response => {
const index = find index of the current item (either by keeping a reference while deleting, or looping through the array to find it)
this.myArray = this.myArray.splice(index, 1);
});
A: it depends ... If you have a lot of data to process in the backend and this slows down the performance, you can use the modified array, otherwise make a new request to the server.
| |
doc_3153
|
TreeMap<Date,String> map = new TreeMap<Date,String>();
map.put(new Date(2011,1,1), "32,1");
map.put(new Date(2011,3,1), "35");
map.put(new Date(2011,4,5), "38,9");
map.put(new Date(2011,8,2), "57!!");
Then I'm lost. I've found this :
NavigableSet<Date> dates = donnees.descendingKeySet();
Then I don't know how to say something like :
for(key in dates and i ; i from 0 to N)
{ do something }
Any help ?
A: It looks like you want to iterate though the descendingMap():
private static final int N = 3;
...
int i = 0;
for (Map.Entry entry : map.descendingMap().entrySet()) {
if (i++ < N) {
System.out.println(entry);
}
}
Console:
Fri Sep 02 11:39:05 EDT 2011=57!!
Thu May 05 11:39:05 EDT 2011=38,9
Fri Apr 01 11:39:05 EDT 2011=35
Addendum: Here's an example using Calendar in the default locale:
private static Date createDate(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar.getTime();
}
...
map.put(createDate(2011, 5, 3), "3-Jun-2011");
A: int i=0;
for(Iterator<Date> it = dates.iterator(); it.hasNext() && i<3;) {
Date date = it.next();
doSomething();
i++
}
Or (equivalent):
int i=0;
Iterator<Date> it = dates.iterator();
while(i<3 && it.hasNext()) {
Date date = it.next();
doSomething();
i++
}
A: Do you care about the state of the tree? If not, then you could do pollLastEntry(). This will remove the last entry off the tree and give it to you. Do 3 times and you're done. Or you could flatten the tree into an arrayList and just return the last 3 elements.
A: Sounds like you just need to loop through the items for the first three:
int i=0;
for(Date date: dates){
//Do something
if(i++ > 2){
break;
}
}
A: *
*TreeMap implements NavigableMap.
*NavigableMap.descendingMap().
*descending Map.entrySet().iterator() // the first 3 entries which are of course
the "last 3" because it is back to front.
You could just implement Comparator and pass it to the TreeMap so the "oldest" dates are at the head of the TreeMap.
A: TreeMap to Array and read the array with a for loop with the condition i < 3
| |
doc_3154
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"></link>
<script type="script" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Delta Fresh Samples:</h1>
<p>save date: 08:23:11 31-May-02015</p>
<div class="jumbotron" id="distance_small">
<h3>distance small</h3><a href="http://104.155.3.206:8080/RoutingManager/routingRequest?returnJSON=true&timeout=60000&to=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.037345+y%3A42.339466+r%3A-1.0+cd%3A-1.0+fn%3A-1+tn%3A-1+bd%3Atrue&returnGeometries=true&nPaths=3&gpsInfo=-1%2C-1.0E-6%2C-1.0E-6%2C-1.0E-6%2C-71.12079%2C42.331749%2C261%2C10%2C338%2C-1&returnClientIds=true&returnInstructions=true&hour=11+59&from=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.12079+y%3A42.331749+r%3A-1.0+cd%3A-1.0+fn%3A59120065+tn%3A18477383+bd%3Afalse+st%3AWhite%7EPl&sameResultType=true&type=HISTORIC_TIME&clientVersion=3.9.4.5&options=AVOID_PRIMARIES%3Afalse%2CIGNORE_REALTIME_INFO%3Afalse%2CAVOID_LONG_TRAILS%3Afalse%2CPREFER_SAME_STREET%3Atrue%2CAVOID_TRAILS%3Atrue%2CAVOID_TOLL_ROADS%3Afalse%2CALLOW_UTURNS%3Atrue%2CAVOID_DANGER_ZONES%3Afalse%2CUSE_EXTENDED_INSTRUCTIONS%3Atrue%2CALLOW_UNKNOWN_DIRECTIONS%3Atrue%2CPREFER_UNKNOWN_DIRECTIONS%3Afalse">0_1</a>
<br>
<a href="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)">
<img alt="missing livemap" src="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)"
height="100" width="200">
</a>
<br><span> </span>editor:<span><a title="0_0" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,77571254,77571249,83969671,83969602,83969601,83969300,83969562,83969306,83969308,83969311,83969444,22950508,22946295,63734947,63734946,22945044,76103782,61849159,22943314,22945842,22949040,76952893,22958740,22955108,22963930,22963937,61487751,78453835,78453836,78190323,78190322,22966401,22963938,22955881,22952772,22942713,22945900,61574081,22948993,22946660,61574071,67889632,67889631,67889637,22942168,22941119,22939556,22945627,61704033,63784515,69051844,61704023,22959771,78100291,78100305,78100306,75676668,22959690,22947454,22940596,22961456,22958490,22948978,22961457,22963582,65496487,22946251,22964699,74195770,75079286,22964701,22965880,62248964,78100492,78100491,22962630,22951570,22948096,22954294,66161229,66147839,22960015,22949762,22945545,22946824,22951606,22951605,22948122,22946840,22960419,22965961,22960420,22962680,22962685,22962684,22962683,22947641,22961812,22964726,22965877,22965967,22965964,22951601,22946847,22949797,75206339,75206338,22962702,22960433,22948128,22960544,22966245">alt 0</a></span><span><a title="0_1" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,77571254,77571249,83969671,83969602,83969601,83969300,83969562,83969306,83969308,83969311,83969776,83970667,83970668,83970679,83970678,83969787,83969884,83969791,83969889,83969965,62003149,22966553,22966554,22946589,22954701,22948771,22960706,22952457,22952456,69823920,67646833,22956976,22942713,22945900,61574081,22948993,22946660,61574071,67889632,67889631,67889637,22942168,22941119,22939556,22945627,61704033,63784515,69051844,61704067,61704043,22957408,61704040,72391451,72391452,61724192,61975137,61975144,57602828,61541078,22965716,22949679,22964912,22943804,22965887,22943805,81603700,81603658,22960396,22960397,22965904,22959154,22965764,22964822,22946555,22954865,22962698,22949797,75206339,75206338,22962702,22960433,22948128,22960544,22966245">alt 1</a></span><span><a title="0_2" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,22551059,22540619,22540617,22521289,22531355,22531357,22523497,77460394,77460392,61690687,67007203,67007202,22959509,22952362,22947304,22946552,73617242,77749675,73617397,22961888,22941066,62110860,83482398,83482876,83482875,22946605,74542235,83482565,83482564,61713972,74882174,74882173,69051742,61975892,65179805,65179806,61713939,77541139,77541140,61975883,22952799,61539504,57601394,22959961,22947692,22959735,22958946,22958947,22958607,22951490,22961077,22964301,22954627,22946241,22963491,76369581,22950499,22966864,22965699,22949657,22962492,22962497,22962496,22946416,22948460,22951483,22948007,22946064,22951140,61459698,22957970,22965738,22954249,22954934,22960321,78858435,22958543,69824727,69824726,22945987,22945859,67102730,77869444,77869443,22966245">alt 2</a></span>
<br>
</div>
<div class="jumbotron" id="distance_large">
<h3>distance large</h3><a href="http://104.155.3.206:8080/RoutingManager/routingRequest?returnJSON=true&timeout=60000&to=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.037345+y%3A42.339466+r%3A-1.0+cd%3A-1.0+fn%3A-1+tn%3A-1+bd%3Atrue&returnGeometries=true&nPaths=3&gpsInfo=-1%2C-1.0E-6%2C-1.0E-6%2C-1.0E-6%2C-71.12079%2C42.331749%2C261%2C10%2C338%2C-1&returnClientIds=true&returnInstructions=true&hour=11+59&from=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.12079+y%3A42.331749+r%3A-1.0+cd%3A-1.0+fn%3A59120065+tn%3A18477383+bd%3Afalse+st%3AWhite%7EPl&sameResultType=true&type=HISTORIC_TIME&clientVersion=3.9.4.5&options=AVOID_PRIMARIES%3Afalse%2CIGNORE_REALTIME_INFO%3Afalse%2CAVOID_LONG_TRAILS%3Afalse%2CPREFER_SAME_STREET%3Atrue%2CAVOID_TRAILS%3Atrue%2CAVOID_TOLL_ROADS%3Afalse%2CALLOW_UTURNS%3Atrue%2CAVOID_DANGER_ZONES%3Afalse%2CUSE_EXTENDED_INSTRUCTIONS%3Atrue%2CALLOW_UNKNOWN_DIRECTIONS%3Atrue%2CPREFER_UNKNOWN_DIRECTIONS%3Afalse">0_0</a>
<br>
<a href="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)">
<img alt="missing livemap" src="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)"
height="100" width="200">
</a>
<br><span> </span>editor:<span><a title="0_0" href="https:/www.waze.com/editor/?
and this is the result:
I wanted to created boxes in the center of the page.
I saw twitter bootstrap example (this example)
but I cannot make class "jumbotron" center my data in medium size gray boxes.
what am i missing?
In Addition, if i would want to style this without twitter bootstrap
how would you advise me to do this?
A: .jumbotron{
position : relative;
margin: 0 auto;
}
and for being in one line use display: inline-block
A: you can achieve that with some styling
like this:
html
<h1>Delta Fresh Samples:</h1>
<p>save date: 08:23:11 31-May-02015</p>
<div class="jumbotron" id="distance_small">
<h3>distance small</h3><a href="http://104.155.3.206:8080/RoutingManager/routingRequest?returnJSON=true&timeout=60000&to=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.037345+y%3A42.339466+r%3A-1.0+cd%3A-1.0+fn%3A-1+tn%3A-1+bd%3Atrue&returnGeometries=true&nPaths=3&gpsInfo=-1%2C-1.0E-6%2C-1.0E-6%2C-1.0E-6%2C-71.12079%2C42.331749%2C261%2C10%2C338%2C-1&returnClientIds=true&returnInstructions=true&hour=11+59&from=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.12079+y%3A42.331749+r%3A-1.0+cd%3A-1.0+fn%3A59120065+tn%3A18477383+bd%3Afalse+st%3AWhite%7EPl&sameResultType=true&type=HISTORIC_TIME&clientVersion=3.9.4.5&options=AVOID_PRIMARIES%3Afalse%2CIGNORE_REALTIME_INFO%3Afalse%2CAVOID_LONG_TRAILS%3Afalse%2CPREFER_SAME_STREET%3Atrue%2CAVOID_TRAILS%3Atrue%2CAVOID_TOLL_ROADS%3Afalse%2CALLOW_UTURNS%3Atrue%2CAVOID_DANGER_ZONES%3Afalse%2CUSE_EXTENDED_INSTRUCTIONS%3Atrue%2CALLOW_UNKNOWN_DIRECTIONS%3Atrue%2CPREFER_UNKNOWN_DIRECTIONS%3Afalse">0_1</a>
<br>
<a href="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)">
<img alt="missing livemap" src="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)"
height="100" width="200">
</a>
<br><span>editor:</span><span><a title="0_0" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,77571254,77571249,83969671,83969602,83969601,83969300,83969562,83969306,83969308,83969311,83969444,22950508,22946295,63734947,63734946,22945044,76103782,61849159,22943314,22945842,22949040,76952893,22958740,22955108,22963930,22963937,61487751,78453835,78453836,78190323,78190322,22966401,22963938,22955881,22952772,22942713,22945900,61574081,22948993,22946660,61574071,67889632,67889631,67889637,22942168,22941119,22939556,22945627,61704033,63784515,69051844,61704023,22959771,78100291,78100305,78100306,75676668,22959690,22947454,22940596,22961456,22958490,22948978,22961457,22963582,65496487,22946251,22964699,74195770,75079286,22964701,22965880,62248964,78100492,78100491,22962630,22951570,22948096,22954294,66161229,66147839,22960015,22949762,22945545,22946824,22951606,22951605,22948122,22946840,22960419,22965961,22960420,22962680,22962685,22962684,22962683,22947641,22961812,22964726,22965877,22965967,22965964,22951601,22946847,22949797,75206339,75206338,22962702,22960433,22948128,22960544,22966245">alt 0</a></span><span><a title="0_1" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,77571254,77571249,83969671,83969602,83969601,83969300,83969562,83969306,83969308,83969311,83969776,83970667,83970668,83970679,83970678,83969787,83969884,83969791,83969889,83969965,62003149,22966553,22966554,22946589,22954701,22948771,22960706,22952457,22952456,69823920,67646833,22956976,22942713,22945900,61574081,22948993,22946660,61574071,67889632,67889631,67889637,22942168,22941119,22939556,22945627,61704033,63784515,69051844,61704067,61704043,22957408,61704040,72391451,72391452,61724192,61975137,61975144,57602828,61541078,22965716,22949679,22964912,22943804,22965887,22943805,81603700,81603658,22960396,22960397,22965904,22959154,22965764,22964822,22946555,22954865,22962698,22949797,75206339,75206338,22962702,22960433,22948128,22960544,22966245">alt 1</a></span><span><a title="0_2" href="https:/www.waze.com/editor/?lon=-71.1181994930557&lat=42.33211431130898&zoom=4&segments=66182276,22523498,22542379,69798169,70183731,70136684,22526478,22551059,22540619,22540617,22521289,22531355,22531357,22523497,77460394,77460392,61690687,67007203,67007202,22959509,22952362,22947304,22946552,73617242,77749675,73617397,22961888,22941066,62110860,83482398,83482876,83482875,22946605,74542235,83482565,83482564,61713972,74882174,74882173,69051742,61975892,65179805,65179806,61713939,77541139,77541140,61975883,22952799,61539504,57601394,22959961,22947692,22959735,22958946,22958947,22958607,22951490,22961077,22964301,22954627,22946241,22963491,76369581,22950499,22966864,22965699,22949657,22962492,22962497,22962496,22946416,22948460,22951483,22948007,22946064,22951140,61459698,22957970,22965738,22954249,22954934,22960321,78858435,22958543,69824727,69824726,22945987,22945859,67102730,77869444,77869443,22966245">alt 2</a></span>
<br>
</div>
<div class="jumbotron" id="distance_large">
<h3>distance large</h3><a href="http://104.155.3.206:8080/RoutingManager/routingRequest?returnJSON=true&timeout=60000&to=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.037345+y%3A42.339466+r%3A-1.0+cd%3A-1.0+fn%3A-1+tn%3A-1+bd%3Atrue&returnGeometries=true&nPaths=3&gpsInfo=-1%2C-1.0E-6%2C-1.0E-6%2C-1.0E-6%2C-71.12079%2C42.331749%2C261%2C10%2C338%2C-1&returnClientIds=true&returnInstructions=true&hour=11+59&from=s%3A-1+d%3Afalse+f%3A-1.0+x%3A-71.12079+y%3A42.331749+r%3A-1.0+cd%3A-1.0+fn%3A59120065+tn%3A18477383+bd%3Afalse+st%3AWhite%7EPl&sameResultType=true&type=HISTORIC_TIME&clientVersion=3.9.4.5&options=AVOID_PRIMARIES%3Afalse%2CIGNORE_REALTIME_INFO%3Afalse%2CAVOID_LONG_TRAILS%3Afalse%2CPREFER_SAME_STREET%3Atrue%2CAVOID_TRAILS%3Atrue%2CAVOID_TOLL_ROADS%3Afalse%2CALLOW_UTURNS%3Atrue%2CAVOID_DANGER_ZONES%3Afalse%2CUSE_EXTENDED_INSTRUCTIONS%3Atrue%2CALLOW_UNKNOWN_DIRECTIONS%3Atrue%2CPREFER_UNKNOWN_DIRECTIONS%3Afalse">0_0</a>
<br>
<a href="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)">
<img alt="missing livemap" src="http://livemap-tiles1.waze.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)"
height="100" width="200">
</a>
<br><span>editor:</span><span><a title="0_0" href="https:/www.waze.com/editor/?"></a>
</div>
css:
.jumbotron{
background:#ddd;
width:220px;
margin:0 auto;
}
.jumbotron img{
display:block;
margin:0 auto;
}
.jumbotron a,.jumbotron span{
display:inline-block;
margin-left:10px;
}
see this fiddle
| |
doc_3155
|
ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)
ERROR: No matching distribution found for numpy
When running the same command with -vvv like pip install numpy -vvv it gives the following output.
Using pip 20.2.1 from c:\program files\python38\lib\site-packages\pip (python 3.8)
Defaulting to user installation because normal site-packages is not writeable
Created temporary directory: C:\Users\d\AppData\Local\Temp\pip-ephem-wheel-cache-bo4luxtk
Created temporary directory: C:\Users\d\AppData\Local\Temp\pip-req-tracker-8z32xx1a
Initialized build tracking at C:\Users\d\AppData\Local\Temp\pip-req-tracker-8z32xx1a
Created build tracker: C:\Users\d\AppData\Local\Temp\pip-req-tracker-8z32xx1a
Entered build tracker: C:\Users\d\AppData\Local\Temp\pip-req-tracker-8z32xx1a
Created temporary directory: C:\Users\d\AppData\Local\Temp\pip-install-2se6s0ld
1 location(s) to search for versions of numpy:
* https://pypi.org/simple/numpy/
Fetching project page and analyzing links: https://pypi.org/simple/numpy/
Getting page https://pypi.org/simple/numpy/
Found index url https://pypi.org/simple
Looking up "https://pypi.org/simple/numpy/" in the cache
Request header has "max_age" as 0, cache bypassed
Starting new HTTPS connection (1): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Incremented Retry for (url='/simple/numpy/'): Retry(total=4, connect=None, read=None, redirect=None, status=None)
Retry: /simple/numpy/
Resetting dropped connection: pypi.org
Starting new HTTPS connection (2): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Incremented Retry for (url='/simple/numpy/'): Retry(total=3, connect=None, read=None, redirect=None, status=None)
Retry: /simple/numpy/
Resetting dropped connection: pypi.org
Starting new HTTPS connection (3): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Incremented Retry for (url='/simple/numpy/'): Retry(total=2, connect=None, read=None, redirect=None, status=None)
Retry: /simple/numpy/
Resetting dropped connection: pypi.org
Starting new HTTPS connection (4): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Incremented Retry for (url='/simple/numpy/'): Retry(total=1, connect=None, read=None, redirect=None, status=None)
Retry: /simple/numpy/
Resetting dropped connection: pypi.org
Starting new HTTPS connection (5): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Incremented Retry for (url='/simple/numpy/'): Retry(total=0, connect=None, read=None, redirect=None, status=None)
Retry: /simple/numpy/
Resetting dropped connection: pypi.org
Starting new HTTPS connection (6): pypi.org:443
https://pypi.org:443 "GET /simple/numpy/ HTTP/1.1" 500 655
Could not fetch URL https://pypi.org/simple/numpy/: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/numpy/ (Caused by ResponseError('too many 500 error responses')) - skipping
Given no hashes to check 0 links for project 'numpy': discarding no candidates
ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)
ERROR: No matching distribution found for numpy
Exception information:
Traceback (most recent call last):
File "c:\program files\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 216, in _main
status = self.run(options, args)
File "c:\program files\python38\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper
return func(self, options, args)
File "c:\program files\python38\lib\site-packages\pip\_internal\commands\install.py", line 324, in run
requirement_set = resolver.resolve(
File "c:\program files\python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 183, in resolve
discovered_reqs.extend(self._resolve_one(requirement_set, req))
File "c:\program files\python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 388, in _resolve_one
abstract_dist = self._get_abstract_dist_for(req_to_install)
File "c:\program files\python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 339, in _get_abstract_dist_for
self._populate_link(req)
File "c:\program files\python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 305, in _populate_link
req.link = self._find_requirement_link(req)
File "c:\program files\python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 270, in _find_requirement_link
best_candidate = self.finder.find_requirement(req, upgrade)
File "c:\program files\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 926, in find_requirement
raise DistributionNotFound(
pip._internal.exceptions.DistributionNotFound: No matching distribution found for numpy
1 location(s) to search for versions of pip:
* https://pypi.org/simple/pip/
Fetching project page and analyzing links: https://pypi.org/simple/pip/
Getting page https://pypi.org/simple/pip/
Found index url https://pypi.org/simple
Looking up "https://pypi.org/simple/pip/" in the cache
Request header has "max_age" as 0, cache bypassed
Starting new HTTPS connection (1): pypi.org:443
https://pypi.org:443 "GET /simple/pip/ HTTP/1.1" 500 655
Could not fetch URL https://pypi.org/simple/pip/: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by ResponseError('too many 500 error responses')) - skipping
Given no hashes to check 0 links for project 'pip': discarding no candidates
Removed build tracker: 'C:\\Users\\d\\AppData\\Local\\Temp\\pip-req-tracker-8z32xx1a'
My pip.ini file looks like
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
How can the 'too many 500 error responses' mentioned in the error be fixed?
Edit:
Reinstalling Python has not fixed the issue and I am using Python 3.8.6. I've also tried restarting my computer.
A: In my case this seems to be a combination of Proxy Server and on one occasion, using a requirements.txt that had been created by pip freeze from another computer and package version numbers were not compatible with my environment. With the latter problem, it was easy, just remove the version numbers and allow Python to grab a compatible version.
the proxy errors for me seem to be intermittent. I can get pip to work most times, but always from my Red Hat Server with the correct proxy settings in http_proxy and https_proxy environment variables. When i try to run pip when building a Docker Container, again with the correct environment variables set in the Dockerfile, I normally can not get a connection and then all of a sudden it works fine.
In summary, this is likely not a problem with pypi.org or files.pythonhosted.org, but probably proxy server settings or trying to install a package that is not compatible with your environment.
A: Over a week later, it started working again just as suddenly as it stopped.
So the answer here seems to be "be patient"?
| |
doc_3156
|
I am trying to send a gift with FBSDKGameRequestContent and I get 2 different errors with 2 different gifts while I am sending from the same code:
FBSDKGameRequestContent *gameRequestContent = [[FBSDKGameRequestContent alloc] init];
gameRequestContent.message = @"Your gift is waiting for you";
gameRequestContent.title = @"Choose Friends";
gameRequestContent.recipients = recipentsToSend;
gameRequestContent.objectID = collection_item;
gameRequestContent.actionType = FBSDKGameRequestActionTypeSend ;
// Assuming self implements <FBSDKGameRequestDialogDelegate>
FBSDKGameRequestDialog* dialog = [[FBSDKGameRequestDialog alloc] init];
dialog.content = gameRequestContent;
dialog.delegate = self;
[dialog show];
gift 1 error 1:
Error Domain=com.facebook.sdk.share Code=2 "(null)" UserInfo={com.facebook.sdk:FBSDKErrorDeveloperMessageKey=The objectID is required when the actionType is either send or askfor., com.facebook.sdk:FBSDKErrorArgumentNameKey=objectID}
gift 2 error 2:
Error Domain=com.facebook.sdk.share Code=100 "(null)" UserInfo={com.facebook.sdk:FBSDKErrorDeveloperMessageKey=Parameter object_id: Invalid id: "ChristmasHomeOrnament"}
Anyone have any idea?
| |
doc_3157
|
When I run my tests, the result is:
System.IO.FileNotFoundException : Could not load file or assembly
'System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'.
The problem is when I create an instance of a class of the references assembly.
How could create a net core or netstandard project that works with that assembly?
It works with a Net 4.8 framework project.
A: Finally I got a solution. I found the assembly in the GAC (C:\Windows\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35), copied to local folder in the project and added the reference to this file and It works.
| |
doc_3158
|
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains <a href='#' class='errorCnt'>" + this.numberOfInvalids() + " errors</a>, see details below.");
this.defaultShowErrors();
}
the code works good, but additionally, the page focus moves to first error input field. I don't want this behavior, instead I want my focus to be on #summary, and when I click on .errorCnt the focus moves to first error field.
A: You want to use the .focus() jquery method
$( "#summary" ).focus();
| |
doc_3159
|
I can run mvn gwt:run and get the form modeler working with jetty.
When I take the WAR file from showcase and try to deploy it in jboss-as-7.1.1 or jboss-eap-6.2.0 it always fails deployment with following error:
11:52:37,365 ERROR [org.jboss.as.server] (HttpManagementService-threads - 10) JBAS015870: Deploy of deployment "jbpm-form-modeler-showcase-6.0.1.Final.war" was rolled back with the following failure message: {"JBAS014771: Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.\"jbpm-form-modeler-showcase-6.0.1.Final\".\"jbpm-form-modeler-showcase-6.0.1.Final\".env.ErraiService is missing [jboss.naming.context.java.jboss.resources.ErraiService]"]}
Any help would be appreciated...
(PS. I got jbpm-console-ng deployed no problem if that make any difference...)
A: I think you need to use fullprofile option when you make build for this module:
mvn clean install -PfullProfile
| |
doc_3160
|
res.setHeader("content-type", 'application/octet-stream');
res.setHeader("Content-Disposition", 'attachment; filename="' + 'original' + '"' + "; filename*=UTF-8''" + 'original' + "");
var readStream;
var exists = fs.existsSync(fullPath);
if (exists) {
callback(true);
readStream = fs.createReadStream(fullPath);
readStream.pipe(res);
} else {
callback(false);
return;
}
res.on('finish', function(){
logger.info('response ending');
readStream.close();
})
res.on('close', function(){
logger.info('response close');
readStream.close();
})
res.on('error', function(error){
logger.info(error);
readStream.close();
})
For some reason, some requests are emitted the close event, while other the finish. As I understand, close is emitted when something get wrong.
The close event can fired between 2 sec and up to 2 min. In rare cases, no close and no finish events are emitted and all, and the request is "stuck", waiting for a response.
What can be the reason that some requests will success, and other not?
EDIT
How can I know why a close event has emitted? Is it a client issue or a bug in my application?
A: if there is a finish then it is all normal, but if there is a close then it could be because of anything. I tried following code following to your event declarations, before the pipe was completed.
1. `res.emit('close');` And
2. `readStream.close();`
Now the first one here explicitly emits the close event, and the second one closes the readStream which was piped. both of these statements cause to trigger the res.on('close'), But I couldn't really find the reason for close.
I can not be sure if it is a server bug or client bug , but there could be following reasons:
*
*res.emit('close'); explicitly emitted the close event.
*something went wrong with source of pipe. (ex. in above case #2 the readStream was closed) in this case it would take a little longer than the rest of the reasons.
*Network went down after the response sending was started
*client can also cause the close event to trigger , if it requested the data and then afterwards client wasn't present to receive the data.
the reason could be anything, which made the response not to complete.
A: i think this comes from the HTTP protocol itself.
there is a option for keep-alive. if this is used then the connection can be reused for different requests.
you shut disable it with res.set("Connection", "close"); ant test it again.
A: i would prefer ending your response when the close and finish event is called rather than closing the readStream.
res.setHeader("content-type", 'application/octet-stream');
res.setHeader("Content-Disposition", 'attachment; filename="' + 'original' + '"' + "; filename*=UTF-8''" + 'original' + "");
var readStream;
var exists = fs.existsSync(fullPath);
if (exists) {
callback(true);
readStream = fs.createReadStream(fullPath);
readStream.pipe(res);
} else {
callback(false);
return;
}
res.on('finish', function(){
logger.info('response ending');
readStream.close(); // This closes the readStream not the response
res.end('FINISHED'); // Ends the response with the message FINISHED
})
res.on('close', function(){
logger.info('response close');
readStream.close(); // This closes the readStream not the response
res.end('CLOSED'); // Ends the response with the message CLOSED
})
res.on('error', function(error){
logger.info(error);
readStream.close(); // This closes the readStream not the response
res.end(error); // Ends the response with ERROR
})
The response is not closed since you close the readStream which closes the readStream alone and not the response. To finish or end the response use res.end().
Reference: http://nodejs.org/api/http.html#http_event_close_1
http://nodejs.org/api/http.html#http_response_end_data_encoding
Hope this helps.
| |
doc_3161
|
require(rjags)
Loading required package: rjags
Loading required package: coda
Error: package or namespace load failed for ‘rjags’: .onLoad failed
in loadNamespace() for 'rjags', details: call: fun(libname, pkgname)
error: Failed to locate any version of JAGS version 4
The rjags package is just an interface to the JAGS library
Make sure you have installed JAGS-4.x.y.exe (for any x >=0, y>=0) from
http://www.sourceforge.net/projects/mcmc-jags/files
The same error message also appeared when I tried JAGS 3.4.0, 4.1.0, and 4.2.0.
I saw on a different post that previously, people solved a similar issue by using an older version of JAGS. That solution didn't work, sadly. Could someone please help me with this?
A: I had the same issue. I found a solution on the JAGS website: I ran
Sys.setenv(JAGS_HOME="C:/Program Files/JAGS/JAGS-4.3.0")
at the RStudio console prompt and this seemed to fix the problem.
| |
doc_3162
|
J_10542741@cs3060:~/assn3$ ./assn3 12
12: 2, 2, 3,
My problem is when I test it on these two other cases:
A) Multiple Arguments:
J_10542741@cs3060:~/assn3$ ./assn3 10 8 6
10: 2, 5,
8: 2, 5,
6: 2, 5,
B) Using a Range of Numbers (i.e. {1..5}):
J_10542741@cs3060:~/assn3$ ./assn3 {1..5}
1:
2:
3:
4:
5:
I've looked around this site for anything regarding the return value of pthread_join() as well as searching through Google. I feel that it's a problem with this part of my code:
// FOR loop to join each thread w/ Main Thread 1x1
for(i = 0; i < argc-1; i++){
retCode = pthread_join(t_id[i], &factors);
results = factors;
if (retCode != 0){
// Print Error Message and return -1
fprintf(stderr, "Failure to join threads.");
return -1;
}
else{
printf("%s: ", argv[i+1]);
while(*results != 0){
printf("%d, ", *results);
results++;
}
}
free(factors);
printf("\n");
}
Here is the code in it's entirety:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
// Return a pointer to the pFactors array
void *primeFactors(void* number){
int *pFactors = malloc(sizeof(int)); // Dynamic Array for prime factors
int capacity = 0;
int size = 1;
int num = atoi((char*)number);
int prime = 2;
// If num < 4, then that number is already prime
if(num < 4)
pFactors[capacity] = num;
else{
while(num > 1){
while(num % prime == 0){
if(capacity == size){
size++;
pFactors = realloc(pFactors, size*sizeof(int));
}
num /= prime;
pFactors[capacity] = prime;
capacity++;
}
prime++;
}
}
if(capacity == size){
size++;
pFactors = realloc(pFactors, size*sizeof(int));
}
pFactors[capacity] = 0;
pthread_exit((void*)pFactors);
}
// MAIN FUNCTION
int main(int argc, char* argv[]){
int i, retCode; // retCode holds the value of successful/fail operation for pthread_create/join
int j = 1;
int* results;
void* factors;
//Thread Identifier value is equal to the number of actual int(s) in argv
pthread_t t_id[argc-1];
// Check argc for too few arguments
if(argc < 2){
fprintf(stderr, "Usage: ./assn3 <integer value>...");
return -1;
}
// Loop through argv and check argv[j] value to ensure it's >= 0
while(j <= argc-1){
if(atoi(argv[j]) < 0){
fprintf(stderr, "%d must be >= 0", atoi(argv[j]));
return -1;
}
j++;
}
// Create the thread
for(i = 0; i < argc-1; i++){
retCode = pthread_create(&t_id[i], NULL, primeFactors, *(argv+1));
if (retCode != 0){
// Print Error Message and return -1
printf("Failure to start thread. Error: %d\n", retCode);
return -1;
}
}
// FOR loop to join each thread w/ Main Thread 1x1
for(i = 0; i < argc-1; i++){
retCode = pthread_join(t_id[i], &factors);
results = factors;
if (retCode != 0){
// Print Error Message and return -1
fprintf(stderr, "Failure to join threads.");
return -1;
}
else{
printf("%s: ", argv[i+1]);
while(*results != 0){
printf("%d, ", *results);
results++;
}
}
free(factors);
printf("\n");
}
return 0;
}
To reiterate, this program works fine if I only enter in 1 argument. However, when there are multiple arguments, the program outputs the prime factors of the first argument correctly but the following arguments are printed with the prime factors of the first argument. Secondly, when you input a bash script range (i.e.{1..5}) it only prints out the arguments and not their respective prime factors. If there's something that needs clarification, feel free to ask. Also if there appears to be a duplicate/similar question(s) somewhere that I haven't been able to find, please let me know. Thanks.
A: pthread_create(&t_id[i], NULL, primeFactors, *(argv+1))
You are passing the same argument, *(argv+1), to every thread. Try with *(argv+1+i) instead.
| |
doc_3163
|
UITextField * myTextField = [[UITextField alloc]init];
NSString * myString = myTextField.text; //Set as reference to string here
NSLog(@"%@", myString); //Should be null
[myTextField setText:@"foobar"];
NSLog(@"%@", myString); //Should be foobar
I'm expecting that when the value of myTextField text to change, that "myString" changes as well.
I know the alternative way is to set a UITextField delegate and check "onChange" and change the string then, but I'm looking to see if there are potentially any other ways.
A: I don't think this is doable in the way you want. the text property of UITextField is an NSString which is immutable. When it changes, a new NSString object is created. Aside from this, there is surely other stuff going on under the hood that makes this impossible.
The two easiest ways to do this would probably be
*
*to set a UITextFieldDelegate as you said, and implement the textField:shouldChangeCharactersInRange:replacementString: method.
*Use NSNotificationCenter and observe the UITextFieldTextDidBeginEditingNotification event. Make sure to remove your object as an observer when it is dealloced
A: NSString is an immutable class. You can't change it. All you can do is point your NSString * pointer variable at a different string. You have to put another
myString = myTextField.text;
In there if you want this behaviour.
| |
doc_3164
|
There is a message producer (Stateless bean), that is sending messages to the Queue (configured on Wildfly 10). And a Message driven bean consuming the messages from the Queue. Also there is a servlet that calls the "SendToQueue(MailEvent mailEvent)" method of my message producer bean.
Now I have an idea to create another method "SendToTopic(MailEvent mailEvent)" in the same bean so that it could be called from another servlet.
*
*Is it the right approach to have one bean with two methods for sending messages to either Topic or Queue?
*And also is it OK for a single MDB to consume these messages?
What is considered the best practice in this situation?
*Is it a good idea to create an interface with "SendToQueue(MailEvent mailEvent)" and "SendToTopic(MailEvent mailEvent)" methods from the OOP perspective?
I'm just learning so may be missing something and will be grateful for any advice or critique.
@Stateless(name = "EmailSessionBean")
public class EmailSessionBean {
public EmailSessionBean() {
}
@Resource(mappedName = "java:/ConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName = "java:/jms/queue/MyQueue")
private Queue queue;
public void SendToQueue(MailEvent mailEvent) {
try {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
ObjectMessage objMsg = session.createObjectMessage();
objMsg.setObject(mailEvent);
messageProducer.send(objMsg);
out.println("Sent ObjectMessage to the Queue");
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
MDB
@MessageDriven(activationConfig = {
@ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(
propertyName = "destination", propertyValue = "java:/jms/queue/MyQueue") })
public class EmailMDB implements javax.jms.MessageListener {
@Resource(mappedName = "java:jboss/mail/Gmail")
private Session mailSession;
public void onMessage(Message message){
try {
if (message instanceof ObjectMessage) {
System.out.println("Queue: I received an ObjectMessage " +
" at " + new Date());
ObjectMessage objectMessage = (ObjectMessage) message;
MailEvent mailEvent = (MailEvent) objectMessage.getObject();
InternetAddress fromAddress = InternetAddress.getLocalAddress(mailSession);
String fromString = fromAddress.getAddress();
javax.mail.Message msg = new MimeMessage(mailSession);
//msg.setFrom(fromAddress);
msg.setFrom(new InternetAddress(fromString,"From me to you"));
InternetAddress[] address = {new InternetAddress(mailEvent.get_To())};
msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
msg.setSubject(mailEvent.getSubject());
msg.setSentDate(new java.util.Date());
msg.setContent(mailEvent.getMessage(), "text/html");
System.out.println("MDB: Sending Message...");
Transport.send(msg);
System.out.println("MDB: Message Sent");
}
else {
System.out.println("Invalid message ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| |
doc_3165
|
Those that are pinnned are important, so if I put the number on 6, open 6, pin 2 then I should be able to open 2 more.
Also, close all but pinned!?
A: Under General-> Editors
"When all editors are dirty or pinned" - choose open new editor
(I'm using Eclipse 3.7.2)
| |
doc_3166
|
Already, I have used the fixedThreadPool to execute these threads.
The problem is that sometimes program control remained in the first running thread and the second one never gets the chance to go to its running state.
Here is a similar sample code to mine:
public class A implements Runnable {
@Override
public void run() {
while(true) {
//do something
}
}
}
public class B implements Runnable {
@Override
public void run() {
while(true) {
//do something
}
}
}
public class Driver {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
A a = new A();
executorService.execute(a);
B b = new B();
executorService.execute(b);
}
}
I'd also done something tricky, make the first thread to sleep once for a second after a short period of running. As a result, it makes the second thread to find the chance for running. But is there any well-formed solution to this problem? where is the problem in your opinion?
A: This is a good example of Producer/Consumer pattern. There are many ways of implementing this. Here's one naive implementation using wait/notify pattern.
public class A implements Runnable {
private Queue<Integer> queue;
private int maxSize;
public A(Queue<Integer> queue, int maxSize) {
super();
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == maxSize) {
try {
System.out.println("Queue is full, " + "Producer thread waiting for "
+ "consumer to take something from queue");
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Random random = new Random();
int i = random.nextInt();
System.out.println("Producing value : " + i);
queue.add(i);
queue.notifyAll();
}
}
}
}
public class B implements Runnable {
private Queue<Integer> queue;
public B(Queue<Integer> queue) {
super();
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println("Queue is empty," + "Consumer thread is waiting"
+ " for producer thread to put something in queue");
try {
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("Consuming value : " + queue.remove());
queue.notifyAll();
}
}
}
}
And here's hot we set things up.
public class ProducerConsumerTest {
public static void main(String[] args) {
Queue<Integer> buffer = new LinkedList<>();
int maxSize = 10;
Thread producer = new Thread(new A(buffer, maxSize));
Thread consumer = new Thread(new B(buffer));
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(producer);
executorService.submit(consumer);
}
}
In this case the Queue acts as the shared memory. You may substitute it with any other data structure that suits your needs. The trick here is that you have to coordinate between threads carefully. That's what your implementation above lacks.
A: I know it may sound radical, but non-framework parts of asynchonous code base should try avoiding while(true) hand-coded loops and instead model it as a (potentially self-rescheduling) callback into an executor
This allows more fair resources utilization and most importantly per-iteration monitoring instrumentation.
When the code is not latency critical (or just while prototyping) the easiest way is to do it with Executors and possibly CompletableFutures.
class Participant implements Runnable {
final Executor context;
@Override
public void run() {
final Item work = workSource.next();
if (workSource.hasNext()) {
context.execute(this::run);
}
}
}
| |
doc_3167
|
[{"scan_status":"ok","visitorData":[{"visitorCompany":"xyl","visitorStreet":"street","visitorBranche":"health","visitorEmail":"[email protected]","lastmodified":"2014-12-15 14:18:55"}]}]
Now in Swift I would like to store this data, and for this I am trying to parse the data into Swift variables, however I got stuck.
do {
//check wat we get back
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves )
let vData = jsonData[0]["visitorData"]
//let vCompany = vData["visitorCompany"]
print("Test vData: \(vData)")
}
This prints
Test vData: Optional(( { visitorStreet = street; visitorPhone = 01606478; visitorCompany = xyl; visitorBranche = Sports; visitorEmail = "[email protected]"; lastmodified = "2014-12-15 14:18:55"; } ))
but when I try to get visitorCompany with
let vCompany = vData["visitorCompany"]
I get a compile error:
Cannot subscript a value of type 'AnyObject?!' with an index of type 'String'
BTW, why do we see the equals sign in swift i.e. visitorStreet = street?
A: This is because the compiler doesn't know the type of your decoded objects.
Help the compiler using casting with if let:
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves )
if let vData = jsonData[0]["visitorData"] as? [[String:AnyObject]] {
if let vCompany = vData[0]["visitorCompany"] {
print(vCompany)
}
}
}
A: let vData = jsonData[0]["visitorData"] populates vData with a generic AnyObject?, because Swift can't know what kind of objects PHP returns in the JSON.
You need to do a an optional cast to another dictionary before you can use vData like you want: jsonData[0]["visitorData"] as? [String:AnyObject].
And because a conditional cast returns an optional, it's best you do an optional binding to unwrap that optional, resulting in a code similar to this:
if let vData = jsonData[0]["visitorData"] as? [String:AnyObject] {
//let vCompany = vData["visitorCompany"]
print("Test vData: \(vData)")
}
Or even better, as jsonData can not be an array, or it could be an empty array (the server malfunctions and sends an invalid json for example), you can go even further with the validation:
if let items = jsonData as? [[String:AnyObject]], vData = items.first?["visitorData"] {
//let vCompany = vData["visitorCompany"]
print("Test vData: \(vData)")
}
items = jsonData as? [[String:AnyObject]] fails if jsonData is not an array, while vData = items.first?["visitorData"] fails if items.first is nil (optional chaining here), or if items.first doesn't have a visitorData key.
A: Try with this:
let vData = jsonData[0]["visitorData"]![0] as! [String:AnyObject]
| |
doc_3168
|
np.random.seed(50)
df = pd.DataFrame(np.random.randint(0,9,size=(30, 3)), columns=list('ABC'))
print df
df
A B C
0 0 0 1
1 4 6 5
2 6 6 5
3 2 7 4
4 3 6 4
5 1 5 0
6 6 3 2
7 3 3 3
8 2 0 3
9 2 0 3
10 0 0 7
11 3 8 7
12 4 4 0
13 0 3 3
14 1 4 5
15 7 0 3
16 5 6 1
17 4 4 4
18 5 4 6
19 3 0 5
20 8 3 6
21 2 8 8
22 5 4 7
23 8 4 4
24 2 1 8
25 7 1 5
26 8 3 3
27 5 3 6
28 8 6 0
29 8 2 1
Here's my code from:
https://pandas.pydata.org/pandas-docs/stable/computation.html
r = df.rolling(window=5)
print 'Agg mean and sdt df'
print r['A', 'B', 'C'].agg([np.mean, np.std])
print
Output
Agg mean and sdt df
A B C
mean std mean std mean std
0 NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN
4 3.0 2.236068 5.0 2.828427 3.8 1.643168
5 3.2 1.923538 6.0 0.707107 3.6 2.073644
6 3.6 2.302173 5.4 1.516575 3.0 2.000000
7 3.0 1.870829 4.8 1.788854 2.6 1.673320
8 3.0 1.870829 3.4 2.302173 2.4 1.516575
9 2.8 1.923538 2.2 2.167948 2.2 1.303840
10 2.6 2.190890 1.2 1.643168 3.6 1.949359
11 2.0 1.224745 2.2 3.492850 4.6 2.190890
12 2.2 1.483240 2.4 3.577709 4.0 3.000000
13 1.8 1.788854 3.0 3.316625 4.0 3.000000
14 1.6 1.816590 3.8 2.863564 4.4 2.966479
15 3.0 2.738613 3.8 2.863564 3.6 2.607681
16 3.4 2.880972 3.4 2.190890 2.4 1.949359
17 3.4 2.880972 3.4 2.190890 3.2 1.483240
18 4.4 2.190890 3.6 2.190890 3.8 1.923538
19 4.8 1.483240 2.8 2.683282 3.8 1.923538
20 5.0 1.870829 3.4 2.190890 4.4 2.073644
21 4.4 2.302173 3.8 2.863564 5.8 1.483240
22 4.6 2.302173 3.8 2.863564 6.4 1.140175
23 5.2 2.774887 3.8 2.863564 6.0 1.581139
24 5.0 3.000000 4.0 2.549510 6.6 1.673320
25 4.8 2.774887 3.6 2.880972 6.4 1.816590
26 6.0 2.549510 2.6 1.516575 5.4 2.073644
27 6.0 2.549510 2.4 1.341641 5.2 1.923538
28 6.0 2.549510 2.8 2.049390 4.4 3.049590
29 7.2 1.303840 3.0 1.870829 3.0 2.549510
And what I am looking for is columns (and data) being:
A A_mean A_std B B_mean B_std C C_mean C_std
I cannot find a solution for 'adding' these columns.
Thanks for the advice.
A: In [18]: res = df.rolling(5).agg(['mean','std'])
In [19]: res.columns = res.columns.map('_'.join)
In [54]: cols = np.concatenate(list(zip(df.columns, res.columns[0::2], res.columns[1::2])))
In [55]: cols
Out[55]:
array(['A', 'A_mean', 'A_std', 'B', 'B_mean', 'B_std', 'C', 'C_mean', 'C_std'],
dtype='<U6')
In [56]: res.join(df).loc[:, cols]
Out[56]:
A A_mean A_std B B_mean B_std C C_mean C_std
0 0 NaN NaN 0 NaN NaN 1 NaN NaN
1 4 NaN NaN 6 NaN NaN 5 NaN NaN
2 6 NaN NaN 6 NaN NaN 5 NaN NaN
3 2 NaN NaN 7 NaN NaN 4 NaN NaN
4 3 3.0 2.236068 6 5.0 2.828427 4 3.8 1.643168
5 1 3.2 1.923538 5 6.0 0.707107 0 3.6 2.073644
6 6 3.6 2.302173 3 5.4 1.516575 2 3.0 2.000000
7 3 3.0 1.870829 3 4.8 1.788854 3 2.6 1.673320
8 2 3.0 1.870829 0 3.4 2.302173 3 2.4 1.516575
9 2 2.8 1.923538 0 2.2 2.167948 3 2.2 1.303840
10 0 2.6 2.190890 0 1.2 1.643168 7 3.6 1.949359
11 3 2.0 1.224745 8 2.2 3.492850 7 4.6 2.190890
12 4 2.2 1.483240 4 2.4 3.577709 0 4.0 3.000000
13 0 1.8 1.788854 3 3.0 3.316625 3 4.0 3.000000
14 1 1.6 1.816590 4 3.8 2.863564 5 4.4 2.966479
15 7 3.0 2.738613 0 3.8 2.863564 3 3.6 2.607681
16 5 3.4 2.880972 6 3.4 2.190890 1 2.4 1.949359
17 4 3.4 2.880972 4 3.4 2.190890 4 3.2 1.483240
18 5 4.4 2.190890 4 3.6 2.190890 6 3.8 1.923538
19 3 4.8 1.483240 0 2.8 2.683282 5 3.8 1.923538
20 8 5.0 1.870829 3 3.4 2.190890 6 4.4 2.073644
21 2 4.4 2.302173 8 3.8 2.863564 8 5.8 1.483240
22 5 4.6 2.302173 4 3.8 2.863564 7 6.4 1.140175
23 8 5.2 2.774887 4 3.8 2.863564 4 6.0 1.581139
24 2 5.0 3.000000 1 4.0 2.549510 8 6.6 1.673320
25 7 4.8 2.774887 1 3.6 2.880972 5 6.4 1.816590
26 8 6.0 2.549510 3 2.6 1.516575 3 5.4 2.073644
27 5 6.0 2.549510 3 2.4 1.341641 6 5.2 1.923538
28 8 6.0 2.549510 6 2.8 2.049390 0 4.4 3.049590
29 8 7.2 1.303840 2 3.0 1.870829 1 3.0 2.549510
| |
doc_3169
|
brew install [email protected]
but I keep receiving
Warning: No available formula with the name "[email protected]".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.
as my error response.
I've tried brew install [email protected], brew install jq=1.3, brew install jq==1.3 to no avail. Any advice?
A: jq 1.3 is available via homebrew, but AFAICT, a version specifically tagged 1.3.1 is not. (See e.g. https://stedolan.github.io/jq/download )
One way to fetch a specific version is as follows:
*First you'll probably want to uninstall jq:
brew uninstall jq
*
*Find a suitable jq.rb
e.g. by browsing
https://github.com/Homebrew/homebrew-core/commits/master/Formula/jq.rb
For jq 1.3 the following would suffice:
URL=https://github.com/Homebrew/homebrew-core/blob/9517da4a73f8eb9af8c8c217a52526f5edf428a2/Formula/jq.rb
*Fetch and execute the script
wget $URL # or use curl
brew install -s jq.rb
| |
doc_3170
|
Any help or a gentle shove in the right direction is greatly appreciated :)
Here's where I am:
namespace TheAirline.GraphicsModel.PageModel.PageFinancesModel
{
/// <summary>
/// Interaction logic for PageFinances.xaml
/// </summary>
public partial class PageFinances : Page
{
private Airline Airline;
public PageFinances(Airline airline)
{
InitializeComponent();
this.Language = XmlLanguage.GetLanguage(new CultureInfo(AppSettings.GetInstance().getLanguage().CultureInfo, true).IetfLanguageTag);
this.Airline = airline;
Page page = null;
//loading the XAML
using (FileStream fs = new FileStream("TheAirline\\GraphicsModel\\PageModel \\PageFinancesModel\\PageFinances.xaml", FileMode.Open, FileAccess.Read))
{
page = (Page)XamlReader.Load(fs);
}
//finding XAML element and trying to set the value to a variable
string airlineCash = GameObject.GetInstance().HumanAirline.Money.ToString();
TextBox cashValue = (TextBox)page.FindName("cashValue");
cashValue.DataContext = airlineCash;
}
}
}
And the first few lines of the XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:AirlineModel="clr-namespace:TheAirline.Model.AirlineModel"
mc:Ignorable="d"
x:Class="TheAirline.GraphicsModel.PageModel.PageFinancesModel.PageFinances"
xmlns:c="clr-namespace:TheAirline.GraphicsModel.Converters"
...>
</Page>
A: Bindings in XAML are resolved against the object that is assigned to the DataContext property of any given XAML element. The value of that property (as well as many other properties) Is Inherited in any given Visual Tree from parent elements to child elements.
for instance, given this class:
public namespace MyNamespace
{
public class ViewModel
{
public string Name {get;set;}
public bool IsActive {get;set;}
}
}
and this XAML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
FontSize="20">
<Window.DataContext>
<local:ViewModel>
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding Path=Name}"/>
<CheckBox IsChecked="{Binding Path=IsActive}"/>
<StackPanel>
</Window>
All four objects defined in XAML, the Window, the StackPanel, the TextBox, and the CheckBox, will have a FontSize of 20, and the instance of the ViewModel class assigned to their DataContext property. Therefore all bindings (Except bindings with a specified ElementName, RelativeSource, or Source) will be resolved against that instance.
It would be exactly the same if the property was assigned in code instead of in XAML:
public MyWindow() //Window Constructor
{
InitializeComponent();
this.DataContext = new ViewModel(); //Note that keyword "this" is redundant, I just explicity put it there for clarity.
}
Because of this, there is no need to set the DataContext property to each element explicitly, as the framework is already taking care of that.
Also, notice that in XAML, most built-in Markup Extensions have a default constructor convention that allows you to abbreviate their usage. In the case of the Binding Markup Extension, the default constructor has the Path property, therefore this:
<TextBox Text="{Binding Path=Name}"/>
is exactly the same as this:
<TextBox Text="{Binding Name}"/>
Now, for property changes in the underlying DataContext to be automatically passed from the binding source (ViewModel) to the binding target (XAML-defined objects), the source object must implement the System.ComponentModel.INotifyPropertyChanged interface and raise the PropertyChanged event every time a property changes.
Therefore, in order to support Two-Way Binding, the example class should look like this:
public namespace MyNamespace
{
public class ViewModel: INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
private bool _isActive;
public bool IsActive
{
get
{
return _isActive;
}
set
{
_isActive = value;
NotifyPropertyChanged("IsActive");
}
}
}
public void NotifyPropertyChanged (string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
Notice that the ViewModel class has no dependency or direct reference to any of the XAML-defined objects, but still it contains the Values of the properties that will appear in the UI. This allows for a complete decoupling between UI and application logic/data known as the MVVM Pattern. I strongly suggest you research on that topic if you expect to be successful in programming in C# + XAML, because it is a radical mindshift when compared to other, traditional UI paradigms.
For example, something like this is not recommended in XAML-based applications:
if (myWindow.CheckBox1.IsChecked)
//Do Something
because that would mean that you're coupling the application logic and making it dependant on the state of UI elements, which is precisely what you need to avoid.
Notice that all the links and all the concepts referenced in this answer pertain to WPF, but are also applicable to Silverlight and WinRT. Since you did not specify which of the three XAML-based frameworks you're using, I posted the WPF ones, which is what I'm most familiar with.
| |
doc_3171
|
I've tried using a LayerDrawable but the checkmark icon gets squished if the image I set using android:src= isn't the same height. Here's what the code for that looks like right now:
AppCompatImageView imageView = (AppCompatImageView) view;
int id = getResources().getIdentifier("drawable/" + view.getTag(), null, getPackageName());
Drawable backgroundLayer = ContextCompat.getDrawable(this, id);
Drawable foregroundLayer = ContextCompat.getDrawable(this, R.drawable.ic_selected);
Drawable[] layers = {backgroundLayer, foregroundLayer};
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setImageDrawable(layerDrawable);
And here's what that ends up looking like:
When I'd like the check to be a square aspect ratio. I'd like to avoid redoing the drawable background to make it a square aspect ratio because I have a large amount of other drawables that I'd have to redo as well.
A: Have you tried setting the image as the background and the checkmark as the src? Once the ImageView is set to a fixed size to match the aspect ratio of the image it should work fine.
imageView.setBackgroundResource(id)
imageView.setImageResource(R.drawable.ic_selected)
Using a scaleType of CENTER if the size of the check mark is ideal or CENTER_INSIDE with padding should get you what you want.
| |
doc_3172
|
Msg 557, Level 16, State 2, Line 2 Only functions and some extended
stored procedures can be executed from within a function.
On the other two it works fine. Is there a setting we are missing on that one specific SQL Server? Or can it be something else? The internet is ambiguous about this error.
Thank you.
A: Thank you for the tips. The problem resolved itself rather unglamorously. It seems that an unhandled error in legacy code, through faulty data, was throwing the scalar function into a fit, causing the that particular error to show up.
Thank you.
| |
doc_3173
|
I want to call a method but the method does not get called and I do not know why.
var rows = GetDataGridRows(dgTickets);
int intTickets = 0;
foreach (System.Windows.Controls.DataGridRow r in rows)
{
//some code
}
private IEnumerable<System.Windows.Controls.DataGridRow>
GetDataGridRows(System.Windows.Controls.DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item)
as System.Windows.Controls.DataGridRow;
if (null != row) yield return row;
}
}
var rows = GetDataGridRows(dgTickets); doesn't call the function and just go to int intTickets = 0
I have no idea what to do
Thanks in advance
A: Your method GetDataGridRows returns an IEnumerable using yield. It's not until your foreach block is executed that you'll step into this method.
The use of the yield keyword allows the C# compiler to use it's state machine generator to create an implementation of IEnumerable which it returns. IEnumerable use lazy invocation, which essentially means it's only interated when it is required. This is where you see it jumping over the declaration to the next step, because at that point, it is only an instance of IEnuemrable which has yet to be cycled through.
A: I believe you should use...
table_id.DataSource = GetDataGridRows(dgTickets);
table_id.DataBind();
| |
doc_3174
|
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="c1" ></ColumnDefinition>
<ColumnDefinition Name="c2" Width="auto" ></ColumnDefinition>
<ColumnDefinition Name="c3" Width="200" ></ColumnDefinition>
<ColumnDefinition Name="c4" Width="auto" ></ColumnDefinition>
<ColumnDefinition Name="c5" Width="200" ></ColumnDefinition>
</Grid.ColumnDefinitions>
<Border Name="t1" Grid.Column="0" Background="Transparent" ></Border>
<Border Name="t2" Grid.Column="2" Background="CadetBlue" ></Border>
<Border Name="t3" Grid.Column="4" Background="Green" ></Border>
<GridSplitter Name="gd1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3" ></GridSplitter>
<GridSplitter Name="gd2" Background="red" Grid.Column="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3"></GridSplitter>
</Grid>
</Window>
A: I think thats what you want :
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Background="Transparent"/>
<Border Grid.Column="2" Background="CadetBlue"/>
<Border Grid.Column="4" Background="Green"/>
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3"/>
<GridSplitter Grid.Column="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3" Background="red"/>
</Grid>
| |
doc_3175
| ERROR: type should be string, got "https://stackoverflow.com/a/356187/1829329\nBut it only works for integers as n in nth root:\nimport gmpy2 as gmpy\n\nresult = gmpy.root((1/0.213), 31.5).real\nprint('result:', result)\n\nresults in:\n---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\n<ipython-input-14-eb4628226deb> in <module>()\n 8 \n----> 9 result = gmpy.root((1/0.213), 31.5).real\n 10 \n 11 print('result:', result)\n\nTypeError: root() requires 'mpfr','int' arguments\n\nWhat is a good and precise way to calculate such a root?\n(This is the python code representation of some formular, which I need to use to calculate in a lecture.)\nEDIT#1\nHere is my solution based on Spektre's answer and information from the people over here at http://math.stackexchange.com.\nimport numpy as np\n\ndef naive_root(nth, a, datatype=np.float128):\n \"\"\"This function can only calculate the nth root, if the operand a is positive.\"\"\"\n logarithm = np.log2(a, dtype=datatype)\n exponent = np.multiply(np.divide(1, nth, dtype=datatype), logarithm, dtype=datatype)\n result = np.exp2(exponent, dtype=datatype)\n return result\n\ndef nth_root(nth, a, datatype=np.float128):\n if a == 0:\n print('operand is zero')\n return 0\n elif a > 0:\n print('a > 0')\n return naive_root(nth, a, datatype=datatype)\n elif a < 0:\n if a % 2 == 1:\n print('a is odd')\n return -naive_root(nth, np.abs(a))\n else:\n print('a is even')\n return naive_root(nth, np.abs(a))\n\n\nA: see Power by squaring for negative exponents \nanyway as I do not code in python or gmpy here some definitions first:\n\n\n*\n\n*pow(x,y) means x powered by y\n\n*root(x,y) means x-th root of y\nAs these are inverse functions we can rewrite:\n\n\n*\n\n*pow(root(x,y),x)=y\n\nYou can use this to check for correctness. As the functions are inverse you can write also this:\n\n\n*\n\n*pow(x,1/y)=root(y,x)\n\n*root(1/x,y)=pow(y,x)\nSo if you got fractional (rational) root or power you can compute it as integer counterpart with inverse function.\nAlso if you got for example something like root(2/3,5) then you need to separate to integer operands first:\nroot(2/3,5)=pow(root(2,5),3)\n ~11.18034 = ~2.236068 ^3\n ~11.18034 = ~11.18034\n\nFor irational roots and powers you can not obtain precise result. Instead you round the root or power to nearest possible representation you can to minimize the error or use pow(x,y) = exp2(y*log2(x)) approach. If you use any floating point or fixed point decimal numbers then you can forget about precise results and go for pow(x,y) = exp2(y*log2(x)) from the start ...\n[Notes]\nI assumed only positive operand ... if you got negative number powered or rooted then you need to handle the sign for integer roots and powers (odd/even). For irational roots and powers have the sign no meaning (or at least we do not understand any yet).\n\nA: If you are willing to use Python 3.x, the native pow() will do exactly what you want by just using root(x,y) = pow(x,1/y). It will automatically return a complex result if that is appropriate.\nPython 3.4.3 (default, Sep 27 2015, 20:37:11)\n[GCC 5.2.1 20150922] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> pow(1/0.213, 1/31.5)\n1.0503191465568489\n>>> pow(1/0.213, -1/31.5)\n0.952091565004975\n>>> pow(-1/0.213, -1/31.5)\n(0.9473604081457588-0.09479770688958634j)\n>>> pow(-1/0.213, 1/31.5)\n(1.045099874779588+0.10457801566102139j)\n>>>\n\nReturning a complex result instead of raising a ValueError is one of changes in Python 3. If you want the same behavior with Python 2, you can use gmpy2 and enable complex results.\n>>> import gmpy2\n>>> gmpy2.version()\n'2.0.5'\n>>> gmpy2.get_context().allow_complex=True\n>>> pow(1/gmpy2.mpfr(\"0.213\"), 1/gmpy2.mpfr(\"31.5\"))\nmpfr('1.0503191465568489')\n>>> pow(-1/gmpy2.mpfr(\"0.213\"), 1/gmpy2.mpfr(\"31.5\"))\nmpc('1.0450998747795881+0.1045780156610214j')\n>>> pow(-1/gmpy2.mpfr(\"0.213\"), -1/gmpy2.mpfr(\"31.5\"))\nmpc('0.94736040814575884-0.094797706889586358j')\n>>> pow(1/gmpy2.mpfr(\"0.213\"), -1/gmpy2.mpfr(\"31.5\"))\nmpfr('0.95209156500497505')\n>>> \n\n\nA: Here is something I use that seems to work with any number just fine:\nroot = number**(1/nthroot)\nprint(root)\n\nIt works with any number data type.\n"
| |
doc_3176
|
I tried using the java.awt RGBoHSB method to get the float array with HSB. The Hue value returned from the method does not seem to be in degrees/radians to me hence I am not able to bifurcate. Moreover I want to avoid using the java.awt so could someone suggest some alternative method for the conversion of Hex colors to HSV in the format which would solve my problem and I can bifurcate the colors into classes according to color wheel.
A: For Conversion of Hex to RGB I used
public Color hex2Rgb(String colorStr) {
return new Color(
Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
And for conversion of RGB to HSV in desired format I followed the article https://www.geeksforgeeks.org/program-change-rgb-color-model-hsv-color-model/
. This helped me to separate Color familes on the basis of Color Wheel theory(http://warrenmars.com/visual_art/theory/colour_wheel/evolution/evolution.htm)
PS: This did not use AWT methods
| |
doc_3177
|
ID DisplayName
1 Surname,User1 [Department]
2 Surname,User2 [Department]
ADSI Query:
DECLARE @sql nvarchar(MAX)
DECLARE @Mail varchar(255)
set @sql = 'SELECT TOP 1 @Mail = mail
FROM openquery(ADSI ,''
SELECT Name, displayName,givenname,distinguishedName, SAMAccountName ,mail
FROM ''''LDAP://DC=Domain,DC=org'''' WHERE displayName = '''''+@DisplayName+'''''
'')'
--print @sql
exec sp_executesql @sql,N'@Mail varchar(255) OUTPUT',@Mail OUTPUT
SELECT @Mail
Desired Output:
ID DisplayName EmailAdrress
1 Surname,User1 [Department] [email protected]
2 Surname,User2 [Department] [email protected]
I created UDF but I got an error, where dynamic query cannot be used in UDF
Only functions and some extended stored procedures can be executed from within a function.
Any help is appreciated.
Thanks!
A: I think you don't avoid looping/cursor:
CREATE TABLE #temp(row_id INT IDENTITY(1,1), Id <type>, DisplayName <type>, EmailAddress <type> NULL);
INSERT INTO #temp(Id, DisplayName)
SELECT Id, DisplayName
FROM Record;
DECLARE @index INT = 1,
@total INT = (SELECT * FROM #temp),
@sql NVARCHAR(MAX),
@Mail VARCHAR(255),
@DisplayName NVARCHAR(100);
WHILE (@index <= @total)
BEGIN
SELECT @DisplayName = DisplayName
FROM #temp
WHERE [row_id] = @index;
SET @sql =
N'SELECT TOP 1 @Mail = mail
FROM openquery(ADSI ,''
SELECT Name, displayName,givenname,distinguishedName, SAMAccountName ,mail
FROM ''''LDAP://DC=Domain,DC=org'''' WHERE displayName = ''@DisplayName'' '')';
EXEC [dbo].[sp_executesql]
@sql
,N'@DisplayName NVARCHAR(100),
@Mail VARCHAR(255) OUTPUT'
,@DisplayName /* Added explicitly parameters */
,@Mail OUTPUT;
UPDATE #temp
SET EmailAddress = @Mail
WHERE row_id = @index;
SET @index += 1;
END
SELECT
Id,
DisplayName,
EmailAddress
FROM #temp;
Do not concatenate @sql string like:
'... WHERE displayName = '''''+@DisplayName+''''' '')'
/* Use explicit parameter for sp_executesql */
'... WHERE displayName = ''@DisplayName'' '')'
| |
doc_3178
|
<span editable-select="item.myDropdown" e-multiple e-ng-options="rol as rol.roleName for rol in myCtrl.roles" onaftersave="showUsers.save($data)" ng-model="myRole.roleSelected"></span>
Because I have a function on my script where it receives the $data as parameter. Here's my sample code:
$scope.save = function (data) { //data = $data
var savedRole = data; //data here is a JSON object
};
A: "The Angular-Xeditable docs don't make it quite clear, but it appears that $data (and $index) are just injected values and that you can pass pretty much anything you want to the save/validate methods." -Michael Oryl
| |
doc_3179
|
A: This is documented by exception--the default applies except for where it is documented not to.
If you don't specify -1 or --single-transaction, then it runs in (the default) autocommit mode. Meaning each SQL statement commits itself upon success. Each COPY therefore is one large transaction of the while table data.
| |
doc_3180
|
type I = () => () => () => "a" | "b" | "c";
Is there a way to create a generic type Unwrap such that Unwrap<I> evaluates to "a" | "b" | "c"?
type I = () => () => () => "a" | "b" | "c";
type Result = Unwrap<I>; // "a" | "b" | "c"
The following (ofc) produces a circularity error:
type Unwrap<
T extends (...args: any[]) => any,
R = ReturnType<T>
> = R extends (...args: any[]) => any
? Unwrap<R>
: R;
Any help would be greatly appreciated. Thank you!
A: Well here's the hack which works in TypeScript 3. It's actually not that awful.
type I = () => (() => (() => "a" | "b" | "c")) | "e" | (() => "f" | "g");
type Unwrap<T> =
T extends (...args: any[]) => infer R
? { 0: Unwrap<R> }[T extends any ? 0 : never] // Hack to recurse.
: T;
type Result = Unwrap<I>;
// type Result = "e" | "a" | "b" | "c" | "f" | "g";
Playground Link
A: As listed in the comment above, the Unwrap type works in TypeScript 4.1 (soon-to-be released).
| |
doc_3181
|
Problem 1 - I cannot loop through the list of variables
Problem 2 - I need to insert each output from the values into Mongo DB
Here is an example of the list:
121715771201463_626656620831011
121715771201463_1149346125105084
Based on this value - I am running a code and i want this output to be inserted into MongoDB. Right now only the first value and its corresponding output is inserted
test_list <-
C("121715771201463_626656620831011","121715771201463_1149346125105084","121715771201463_1149346125105999")
for (i in test_list)
{ //myfunction//
mongo.insert(mongo, DBNS, i)
}
I am able to only pick the values for the first value and not all from the list
Any help is appreciated.
A: Try this example, which prints the final characters
myfunction <- function(x){ print( substr(x, 27, nchar(x)) ) }
test_list <- c("121715771201463_626656620831011",
"121715771201463_1149346125105084",
"121715771201463_1149346125105999")
for (i in test_list){ myfunction(i) }
for (j in 1:length(test_list)){ myfunction(test_list[j]) }
The final two lines should each produce
[1] "31011"
[1] "105084"
[1] "105999"
A: It is not clear whether "variable" is the same as "value" here.
If what you mean by variable is actually an element in the list you construct, then I think Ilyas comment above may solve the issue.
If "variable" is instead an object in the workspace, and elements in the list are the names of the objects you want to process, then you need to make sure that you use get. Like this:
for(i in ls()){
cat(paste(mode(get(i)),"\n") )
}
ls() returns a list of names of objects. The loop above goes through them all, uses get on them to get the proper object. From there, you can do the processing you want to do (in the example above, I just printed the mode of the object).
Hope this helps somehow.
| |
doc_3182
|
such as VMIN*, VCVTT*, VGETEXT*, VREDUCE*, VRANGE* etc.
Intel declares SAE-awareness only with full 512bit vector length, e.g.
VMINPD xmm1 {k1}{z}, xmm2, xmm3
VMINPD ymm1 {k1}{z}, ymm2, ymm3
VMINPD zmm1 {k1}{z}, zmm2, zmm3{sae}
but I don't see a reason why SAE couldn't be applied to instructions where xmm or ymm registers are used.
In chapter 4.6.4 of
Intel Instruction Set Extensions Programming Reference Table 4-7 says that in instructions without rounding semantic bit EVEX.b specifies that SAE is applied, and bits EVEX.L'L specify explicit vector length:
00b: 128bit (XMM)
01b: 256bit (YMM)
10b: 512bit (ZMM)
11b: reserved
so their combination should be legal.
However NASM assembles vminpd zmm1,zmm2,zmm3,{sae} as 62F1ED185DCB, i.e. EVEX.L'L=00b, EVEX.b=1, which is disassembled back by NDISASM 2.12 as vminpd xmm1,xmm2,xmm3
NASM refuses to assemble vminpd ymm1,ymm2,ymm3,{sae}
and NDISASM disassembles 62F1ED385DCB (EVEX.L'L=01b, EVEX.b=1) as vminpd xmm1,xmm2,xmm3
I wonder how does Knights Landing CPU execute VMINPD ymm1, ymm2, ymm3{sae}
(assembled as 62F1ED385DCB, EVEX.L'L=01b, EVEX.b=1):
*
*CPU throws an exception. Intel doc Table 4-7 is misleading.
*SAE is in effect, CPU operates with xmm only, same as in scalar
operations. NASM and NDISASM do it right, Intel documentation is
wrong.
*SAE is ignored, CPU operates with 256 bits according to VMINPD
specification in Intel doc. NASM & NDISASM are wrong.
*SAE is in effect, CPU operates with 256 bits as specified in
instruction code. NASM and NDISASM are wrong, Intel doc needs to
supplementary decorate xmm/ymm instructions with {sae}.
*SAE is in effect, CPU operates with implied full vector size 512
bits, regardless of EVEX.L'L, same as if static roundings {er} were
allowed. NDISASM and Intel doc Table 4-7 are wrong.
A: Your VMINPD ymm1, ymm2, ymm3{sae} instruction is invalid. According to instruction set reference for MINPD in the Intel Architecture Instruction Set Extensions Programming Reference (February 2016) only the following encodings are allowed:
66 0F 5D /r MINPD xmm1, xmm2/m128
VEX.NDS.128.66.0F.WIG 5D /r VMINPD xmm1, xmm2, xmm3/m128
VEX.NDS.256.66.0F.WIG 5D /r VMINPD ymm1, ymm2, ymm3/m256
EVEX.NDS.128.66.0F.W1 5D /r VMINPD xmm1 {k1}{z}, xmm2, xmm3/m128/m64bcst
EVEX.NDS.256.66.0F.W1 5D /r VMINPD ymm1 {k1}{z}, ymm2, ymm3/m256/m64bcst
EVEX.NDS.512.66.0F.W1 5D /r VMINPD zmm1 {k1}{z}, zmm2, zmm3/m512/m64bcst{sae}
Notice that only the last version is shown with a {sae} suffix, meaning it's the only form of the instruction you're allowed to use it with. Just because the bits exists to encode a particular instruction doesn't mean its valid.
Also note that section 4.6.3, SAE Support in EVEX, makes it clear that SAE doesn't apply to 128-bit or 256-bit vectors:
The EVEX encoding system allows arithmetic floating-point instructions without rounding semantic to be encoded
with the SAE attribute. This capability applies to scalar and 512-bit vector lengths, register-to-register only, by
setting EVEX.b. When EVEX.b is set, “suppress all exceptions” is implied. [...]
I'm not sure however whether your hand crafted instruction would generate Invalid Opcode exception, if the EVEX.b bit will simply be ignored, or if the EVEX.L'L bits will be ignored. EVEX encoded VMINPD instructions belong to the Type E2 exception class, and according to Table 4-17, Type E2 Class Exception Conditions, the instruction can generate an #UD exception in any of the following cases:
*
*State requirement, Table 4-8 not met.
*Opcode independent #UD condition in Table 4-9.
*Operand encoding #UD conditions in Table 4-10.
*Opmask encoding #UD condition of Table 4-11.
*If EVEX.L’L != 10b (VL=512).
Only that last reason seems to apply here, but it would mean that your instruction would generate #UD exception with or without the {sae} modifier. Since this seems to directly contradict the allowed encodings in the instruction summary, I'm not sure what would happen.
A: On Twitter, iximeow gives some addenda to Ross Ridge's answer above:
*
*ross ridge is right that the text is invalid, but the important detail is that L'L selects the specific SAE mode, so if you set L'L to indicate ymm, you just get {rd-sae}
*
*this is to say, if you set b for sae at all, the vector width is immediately fixed to 512 bits
*
*vector widths are fixed to 512 bits*
*except for some cvt instructions where one operand is 512 bits and one operand is smaller
(@Pepijn's comment on Ross's answer already linked to those tweets; but I figured it's worth making this a separate answer, if only for visiblity.)
| |
doc_3183
|
Whenever a value of the subscribed key changes, the properties of the subscribed QObject changes to the new value. Works in Qt/C++ fine.
Now I want to make a view in QML. Is it possible to pass from QML to C++ an object with 3 parameters:
*
*QObject pointer of the QML object
*property as string
*DB-key as string
?
The preferable solution were, as if the property connects to another property:
Item{ myQmlProp: MyCppInst("myDBKey") }
EDIT
What currently works is this solution:
Item{
id:myqmlitem
myQmlProp: MyCppInst("myDBKey","myQmlProp",myqmlitem)
}
or like this:
Item{
id:myqmlitem
Component.onCompleted:{
MyCppPublisher.subscribe("myDBKey1","myQmlProp1",myqmlitem)
MyCppPublisher.subscribe("myDBKey2","myQmlProp2",myqmlitem)
}
}
Compared to the preferable solution, I have to pass the connected property name and the QML item instance explicitly. But it is ok, many thanks for the answers!
I've hoped to use QML's this-Keyword but have learned, that it is currently undefined in QML :-(
A: Just give the object an id and pass that id to the function, it will become a QObject * on the C++ side. Then you can use the meta system to access properties by name:
// qml
Item {
id: someitem
...
CppObj.cppFoo(someitem)
}
// c++
void cppFoo(QObject * obj) {
...obj->property("myDBKey")...
}
A reference would do as well, for example children[index].
A: What you could do is a function taking just your dbkey as a parameter, and return a QObject* exposing a Q_PROPERTY with a READ function and NOTIFY signal.
This way, you just have to tell with the notify signal the value has changed, and the QML will call the read function automatically.
It could be implemented like that Item{ myQmlProp: MyCppInst("myDBKey").value }.
If you know the db keys at compile time you could just add a property for each of them in your MyCppInst directly, or if you know them at the creation of your cpp class you could put them in a QQmlPropertyMap.
Usage would be like that : Item { myQmlProp: MyCppInst.myDbKey } (or MyCppInst["myDbKey"] if you need to be dynamic in the QML side).
| |
doc_3184
|
i added the next lines for supported in ios8, but when these lines are added the ipa works on ios8 but not on ios7 on ios7 the application is closed immediately after i open it.
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
#ifdef __IPHONE_8_0
//Right, that is the point
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#else
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
#endif
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
//register to receive notifications
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
//handle the actions
if ([identifier isEqualToString:@"declineAction"]){
}
else if ([identifier isEqualToString:@"answerAction"]){
}
}
#endif
A: The solution:
#ifdef __IPHONE_8_0
if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
#else
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
#endif
A: Since iO8, registerForRemoteNotificationTypes has been deprecated . rgisterUserNotificationSettings: with registerForRemoteNotifications.
Testing wether or not the registerUserNotificationSettings: API is available at runtime, means you're running on iOS8.
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
| |
doc_3185
|
Thor is very popular and has more followers and contributers than Boson, but Boson looks far more powerful than Thor and the architecture is very well thought out.
In Boson you:
*
*can add methods that are used both in the console and ruby environment. So you don't have to both have Thorfiles for console and gems for ruby.
*can have aliases.
*don't have to install your script files, you just put them in ~/.boson/commands. I always have to struggle with uninstalling and installing Thorfiles after each update (which could be every minute when editing the source code, very frustrating).
*have much nicer commands output than thor.
*don't have to write the argument descriptions by hand like in Thor.
*work with modules, which are better than with classes cause you can include modules inside other modules.
*wrap open source snippets (eg. from Gist) inside a module automatically and it works with Boson immediately.
*have different views for your method results.
*don't have to recode anything in your snippets to fit Thor, since it only use native ruby code (modules). That means if you one day don't want to use Boson, you don't have to recode everything, which you have to if you are using Thor.
*The API is documented better - like tutorials inside each class.
*You can just include the "boson" modules inside your ruby script and use them directly, something I cannot with Thor, cause it is only for Thor. You can't share the Thor methods with other Thor classes (not as mixins)
I noticed all these benefits just from reading the documentation and played with Boson for a couple of minutes.
Should I use Thor just because it's more popular (cause I can't find anything else where it shines over boson) or should I take the risk that Boson may be unmaintained after a while, since the author is the only contributor?
Although it's just one guy you see how he has managed to code in a rapid speed and with outstanding quality. Would be great if more contributers like him contributed to that library. I really hope more rubyists are going to use it cause it has a lot of potential for being THE scripting framework for all system automation. Like a Rails for the backend. And the author really helps you out very fast when you file an issue.
Thor only works for the shell (which I guess is its purpose) while boson as I see it has 3 main functionalities. It allows you to have code working in the shell, in ruby (irb and scripts) and you can have nice collections of all your Ruby codes, without modifications.
I have always wanted a framework to be my backend scripting framework, and now I don't have to reinvent the wheel. It seems that boson could be it.
Has someone used both these libraries and could share some thoughts?
A: Disclaimer: I'm the author of boson.
I've used both and thor was what inspired me to write boson. While the two have overlapping functionality, I see them as having different goals.
Thor is a scripting framework which quickly and beautifully gives applications a commandline interface. The 116 gems (including rails) that depend on it are good evidence of that. Initially I tried using thor to manage and use snippets but after awhile, the forced namespacing, the lack of aliasing, writing redundant usage lines, and poor searching, made me realize thor wasn't optimized to manage snippets.
So I wrote boson to manage the endless number of ruby snippets I used to put in ~/bin with this philosophy in mind. At 400+ commands, I'm able to instantly find and use any ruby snippet as a full-blown executable. There are too many features to go over here, though you seem to know some of boson's strengths. As for being the sole contributor, I welcome anyone to contribute their ideas.
If there was one simple comparison to make between the two, I'd say thor is centered around creating executables for projects and apps while boson is centered around creating them for users.
| |
doc_3186
|
The idea is to use all the available HDFS disk space for testing purposes.
I have seen quite a few questions asking how to do this on other vendor’s Hadoop clusters but not on IBM Analytics Engine.
A: Using Ambari you would do something like the following:
*
*Connect to the Ambari web URL.
*Click on the HDFS tab on the left.
*Click on the config tab.
*Click on "Advanced" settings
*Under "General," change the value of "Block Replication"
*Now, restart the HDFS services.
| |
doc_3187
|
Referencing the token smart contract in my crowdsale smart contract allows me to call the token functions.
However... I cannot use the modifier from the token smart contract.
contract Crowdsale is Token {
token private _token;
constructor (ERC20 token) public {
require(address(token) != address(0));
_token = token;
}
// this one works
function test(address account) public view returns (uint256) {
_token.functionFromToken(account);
}
// This does not work because of modifierInToken
function test2(address account) public modifierInToken {
}
}
Is it normal? And if so, is there a workaround?
A: My current workaround is the following:
- In my token smart contract, I added an "intermediate" function. That function is directly called in the modifier from my token.
- In my crowdsale smart contract, I replicated the modifier, calling the intermediate function in it.
This way, whenever I want to update all my modifiers coming from my original smart contract, all I have to do is to edit the "intermediate" function.
The default of that approach is that the "intermediate function" needs to be set to public in order to be called from any other smart contract, so be careful is you're choosing that approach.
| |
doc_3188
|
The issue is when I'm trying to align my TouchableOpacity to something like center or flex-end it does not work inside an Image tag. The TouchableOpacity simply disappears...
Demonstration of the issue:
Here I tried with a View instead of an Image It works...
A: I realised the issue.
Must set:
width: null,
height: null,
to the Image tag.
| |
doc_3189
|
def callback(a,b,c):
print 'i+2'
ButtonsList=[]
VarList=[]
i=0
while i<30:
VarList.append(tk.BooleanVar())
VarList[i].trace('w',callback)
ButtonsList.append(tk.Checkbutton(root, text="This is a CB",variable=VarList[i]))
ButtonsList[i].place(x=x,y=i*20)
i+=1
A: You could wrap your callback in a lambda that adds additional arguments to the function call.
def callback(a,b,c,idx):
print 'i+2'
#later on in the program:
VarList[i].trace('w', lambda a,b,c,i=i: callback(a,b,c,i))
Note the i=i in the lambda. This is necessary for variables whose value changes after you register the callback. Without it, i would always be 30, regardless of which Checkbutton you click.
| |
doc_3190
|
Here's the view code (razor):
@Using Html.BeginForm()
@<fieldset>
<legend></legend>
<br />
<fieldset>
<legend>Datos Generales</legend>
<table>
<tr>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDCertificado)
@Html.TextBox("ID_CERTIFICADO1", "Automático", New With {.readonly = "readonly", .style = "width:90px; text-align:center", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDPoliza)
@Html.DropDownListFor(Function(Model) Model.IDPoliza, Nothing, New With {.style = "width:200px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
<tr>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDCampaña)
@Html.DropDownListFor(Function(Model) Model.IDCampaña, Nothing, New With {.style = "width:250px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDVigencia)
@Html.DropDownListFor(Function(Model) Model.IDVigencia, Nothing, New With {.style = "width:183px; visibility:visible", .class = "letraingreso", .disabled = "disabled"})
</td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<legend>Datos del Certificado</legend>
<table width="99%">
<tr>
<td style="border-width:0px; border-style:solid; width:8%">
@Html.LabelFor(Function(Model) Model.FechaEmision)
</td>
<td style="border-width:0px; border-style:solid; width:11%">
@Html.TextBox("FechaEmision", Nothing, New With {.style = "width:80px; text-align:center", .class = "letraingreso", .readonly = "readonly"})
</td>
<td style="width:1%"></td>
<td style="border-width:0px; border-style:solid; width:8%">
@Html.LabelFor(Function(Model) Model.FechaInicioVigencia)
</td>
<td style="border-width:0px; border-style:solid; width:12%">
@Html.TextBoxFor(Function(Model) Model.FechaInicioVigencia, New With {.maxLength = "10", .onkeyup = "DateFormat(this, this.value, event, false, '3')", .onblur = "DateFormat(this, this.value, event, true, '3')", .style = "width:80px", .class = "letraingreso"})
<a href="#"><img src="@Url.Content("~/Images/spacer.gif")" class="imagenfecha" style="border:0" height="16px" width="20px" id="imgFechaInicioVigencia" alt="" /></a>
<script type="text/javascript">
Calendar.setup(
{
inputField: "FechaInicioVigencia",
ifFormat: "%d/%m/%Y",
button: "imgFechaInicioVigencia",
align: "Tl",
singleClick: true
});
</script>
</td>
<td style="width:1%"></td>
<td style="border-width:0px; border-style:solid; width:25%">
@Html.LabelFor(Function(Model) Model.FechaFinVigencia)
@Html.TextBoxFor(Function(Model) Model.FechaFinVigencia, New With {.maxLength = "10", .onkeyup = "DateFormat(this, this.value, event, false, '3')", .onblur = "DateFormat(this, this.value, event, true, '3')", .style = "width:80px", .class = "letraingreso"})
<a href="#"><img src="@Url.Content("~/Images/spacer.gif")" class="imagenfecha" style="border:0" height="16px" width="20px" id="imgFechaFinVigencia" alt="" /></a>
<script type="text/javascript">
Calendar.setup(
{
inputField: "FechaFinVigencia",
ifFormat: "%d/%m/%Y",
button: "imgFechaFinVigencia",
align: "Tl",
singleClick: true
});
</script>
</td>
</tr>
<tr>
<td style="border-width:0px; border-style:solid; width:8%">
@Html.LabelFor(Function(Model) Model.IDEstado)
</td>
<td style="border-width:0px; border-style:solid; width:11%">
@Html.DropDownListFor(Function(Model) Model.IDEstado, Nothing, New With {.style = "width:100px; visibility:visible", .class = "letraingreso", .disabled = "disabled"})
</td>
<td style="width:1%"></td>
<td colspan="5" style="border-width:0px; border-style:solid; width:13%">
@Html.LabelFor(Function(Model) Model.IDPlanGrupoCobertura)
@Html.DropDownListFor(Function(Model) Model.IDPlanGrupoCobertura, Nothing, New With {.style = "width:350px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
</table>
</fieldset>
<br />
<div id="tabs">
@*Establece los tabs a ser creados*@
<ul>
<li><a href="#fragment-1"><span>Asegurado</span></a></li>
</ul>
@*Asegurados*@
<div id="fragment-1">
<table>
<tr>
<td style="border-width:0px; border-style:solid; width:58px">
@Html.LabelFor(Function(Model) Model.IDAsegurado)
</td>
<td style="border-width:0px; border-style:solid">
@Html.TextBox("IDAsegurado", "Automático", New With {.readonly = "readonly", .style = "width:80px; text-align:center", .class = "letraingreso"})
</td>
<td style="width:10px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDTipoDocumentoAsegurado)
@Html.DropDownListFor(Function(Model) Model.IDTipoDocumentoAsegurado, Nothing, New With {.style = "width:200px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:10px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.NumeroDocumentoAsegurado)
@Html.TextBoxFor(Function(Model) Model.NumeroDocumentoAsegurado, New With {.onkeyup = "if(this.value.match(/\D/))this.value=this.value.replace(/\D/g,'')", .class = "letraingreso", .style = "width:100px"})
</td>
<td style="width:10px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.FechaNacimientoAsegurado)
@Html.TextBoxFor(Function(Model) Model.FechaNacimientoAsegurado, New With {.maxLength = "10", .onkeyup = "DateFormat(this, this.value, event, false, '3')", .onblur = "DateFormat(this, this.value, event, true, '3')", .style = "width:80px", .class = "letraingreso"})
<a href="#"><img src="@Url.Content("~/Images/spacer.gif")" class="imagenfecha" style="border:0" height="16px" width="20px" id="imgFechaNacimientoAsegurado" alt="" /></a>
<script type="text/javascript">
Calendar.setup(
{
inputField: "FechaNacimientoAsegurado",
ifFormat: "%d/%m/%Y",
button: "imgFechaNacimientoAsegurado",
align: "Tl",
singleClick: true
});
</script>
</td>
</tr>
</table>
<table>
<tr>
<td style="border-width:0px; border-style:solid; width:58px">
@Html.LabelFor(Function(Model) Model.NombresAsegurado)
</td>
<td style="border-width:0px; border-style:solid">
@Html.TextBoxFor(Function(Moel) Model.NombresAsegurado, New With {.style = "text-transform:uppercase; width:270px", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.PrimerApellidoAsegurado)
@Html.TextBoxFor(Function(Model) Model.PrimerApellidoAsegurado, New With {.style = "text-transform:uppercase; width:182px", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.SegundoApellidoAsegurado)
@Html.TextBoxFor(Function(Model) Model.SegundoApellidoAsegurado, New With {.style = "text-transform:uppercase; width:182px", .class = "letraingreso"})
</td>
</tr>
</table>
<table>
<tr>
<td style="border-width:0px; border-style:solid; width:58px">
@Html.LabelFor(Function(Model) Model.IDCiudadAsegurado)
</td>
<td style="border-width:0px; border-style:solid">
@Html.DropDownListFor(Function(Model) Model.IDCiudadAsegurado, Nothing, New With {.style = "width:180px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
@Html.LabelFor(Function(Model) Model.IDGeneroAsegurado)
@Html.DropDownListFor(Function(Model) Model.IDGeneroAsegurado, Nothing, New With {.style = "width:98px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
</table>
</div>
</div>
<br />
<fieldset>
<legend>Observaciones</legend>
@Html.LabelFor(Function(Model) Model.Observaciones)
@Html.TextBoxFor(Function(Model) Model.Observaciones, New With {.class = "letraingreso", .style = "width:90%; text-transform:uppercase"})
</fieldset>
</fieldset>
@<div style="display:none; position:absolute; margin:auto; left:0; right:0; text-align:center" id="inprogress">
<br /><br /><br /><br /><br /><br />
<img id="inprogress_img" src="@Url.Content("~/Images/loading.gif")" alt="Procesando..." />
<br />
Por favor espere mientras su solicitud es procesada...
</div>
@<p>
<input type="submit" value="Guardar" id="cmdGuardar" onclick="return doSubmit()" />
</p>
@<div>
@Html.ActionLink(" ", "ListarCertificadosAPG", "CertificadosLayout", New With {.area = ""}, New With {.class = "imgRegresar", .title = "Regresar"})
</div>
End Using
As I said, in MVC3, submit button raise controller:
<HttpPost()> _
Function Create(<Bind(Exclude:="IDCertificado, IDAsegurado")> ByVal parCertificadoAPG As Global.iSAM.Certificados) As ActionResult
todo
End Function
But in MVC4 not firing HttpPost. I put the next code (just like example) after End Using in the view code:
@Using Html.BeginForm()
@<input type="submit" value="SSS" />
End Using
And when I press SSS button it raise the HttpPost.
Can someone help me to solve or understand where is the mistake or error?
Regards.
A: After some tests, I found the reason why submit do not raising. On my MainLayout I've got declared:
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>
I had to comment this line and submit works. However I don't know why this line makes submit doesn't work.
I installed MVC4 RC and now I have commented this 3 lines:
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/themes/base/css")" rel="stylesheet" type="text/css" />
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>
I need to review deeper MVC4 to know what thease lines do.
Regards everybody.
| |
doc_3191
|
I have a print statement in some code (with many contributors). It is printing:
<soapenv:Body><QueryPerf xmlns="urn:vim25"><_this type="PerformanceManager">PerfMgr</_this><querySpec><entity type="VirtualMachine">vm-1442</entity><startTime>2019-05-21T11:32:32.362213-04:00</startTime><endTime>2019-05-22T11:32:32.362213-04:00</endTime><metricId><counterId>2</counterId><instance></instance></metricId><intervalId>300</intervalId></querySpec></QueryPerf></soapenv:Body>
</soapenv:Envelope>
for the life of me, I can't find out where this print statement is.
Its a large python program with many files and its even possible that someone edited a library.
Question
Is there some way to tell a python program to print the location of the print statements that it is executing?
Notes
I've tried grepping around. Judging by the fact that this is a SOAP command my guess is that it is related to pyvmomi
My Solution that worked for me (by some luck)
ctrl C during the execution when the code was printing.
This is a horrible answer in general.
A: if you know what print could have resulted in that (eg print(Alice)) and you're using pycharm you can use ctrl+shift+f to search in all files (same as ctrl+f in web).
| |
doc_3192
|
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("submit");
button.onclick = changeDiv;
}
function changeDiv() {
var counter=1
var name = "ul";
var textInput = document.getElementById("textInput");
var userInput = textInput.value;
alert("adding " + userInput);
var li = document.createElement("li");
li.innerHTML = userInput;
var ul = document.getElementById("ul" + loop());
ul.appendChild(li);
}
function loop() {
return counter;
if (counter==3){
counter==0;
}
counter++;
}
</script>
</head>
<body>
<form id="form">
<input id="textInput" type="text" placeholder="input text here">
<input id="submit" type="button">
</form>
<ul id="ul1">
</ul>
<ul id="ul2">
</ul>
<ul id="ul3">
</ul>
</body>
A: i think you want is one of these:
*
*Give the scope of counter to be global (yuk)
*create a closure around everything and declare counter there
*you could pass counter into loop() when you call it.
*define loop() in changeDiv().
I think you want #2 though so I fiddled it with several corrections in your code:
fiddle
The reason that I went with #2 is:
*
*that a closure allows your logic to gain application to the resources it needs
*but protect the scope at which other applications might be running (now or in the future) from being affected by any changes your application might attempt to that scope. For example, if you declared the counter as a global then all other javascript would potentially have read/write access to it which could negatively affect your demonstrated code, the other code, or both
*keeps your current beginner code as unchanged as possible
*gets you programming with an extremely important aspect of javascript that will help you today and in future as you learn
Answer #4 is similar in that it would create a closure for both changeDiv and loop whereby they both have access to what they need. However, I didn't want to change your existing logical blocks too much to stall incremental learning. But one could definitely make an argument for the loop() (which isn't really a loop but rather a setter) being enclosed in changeDiv() -- albeit you would likely remove the separate function call at that point and integrate the code more.
A: Essentially, you need to:
*
*declare counter in a global scope (loop() cannot access it otherwise)
*in loop(), the return statement must be the LAST thing. Anything after it won't get executed.
I altered the logic a bit and the final code is this:
window.onload = init;
var counter=1;
function init(){
var button = document.getElementById("submit");
button.onclick = changeDiv;
}
function changeDiv(){
var name = "ul";
var textInput = document.getElementById("textInput");
var userInput = textInput.value;
var id = "ul" + loop();
alert("adding " + userInput + " to " + id);
var li = document.createElement("li");
li.innerHTML = userInput;
var ul = document.getElementById(id);
ul.appendChild(li);
}
function loop(){
var tmp = counter++;
if (counter==4){
counter=1;
}
return tmp;
}
Note the changes in the loop() function.
I also altered the changeDiv() function to display the list ID in the alert.
| |
doc_3193
|
I created a view ("center") that returns a single center as a page (machine name page_1"). The page can be accessed from the URL /center/## where ## is the node ID of the center. I used a template to get that to display just the center content without the rest of a normal page.
I created a .js file that, in theory, will attach an AJAX action to call that page view and put the results in the block on the right. This is based on a short tutorial I found here: https://www.thirdandgrove.com/rendering-view-ajax-drupal-8
(function ($) {
Drupal.behaviors.ajaxContentCenter = {
attach: function (context, settings) {
$('#content-center-list-block-2 li').once('attach-links').each(this.attachLink) ;
),
attachLink: function (idx, list) {
// determine the node ID from the link (not ideal but should work for now)
var link = $(list).find('a');
var href = $(link).attr('href');
var matches = /node\/(\d*)/.exec(href);
var nid = matches[1];
var view_info = {
// the view to get one center's record
view_name: 'center',
// the display ID for that view
view_display_id: 'page_1',
// the nid to pass to the view (but doesn't seem to work)
view_args: nid,
// the block to update has a class of js-view-dom-id-ccd-update
view_dom_id: 'ccd-update'
};
// ajax action details
var ajax_settings = {
submit: view_info,
// I'd have thought supplying the nid above would work but
// it doesn't, so I've included it here
url: '/center/'+nid,
element: list,
event: 'click'
};
Drupal.ajax(ajax_settings) ;
}
};
})(jQuery);
When I click on a link, I get the little spinner indicating that ajax is working and in my browser console I can see the ajax result being sent back to the browser. Unfortunately, it never gets put into the div in the block on the right. No error messages that I can see.
I've tried making the view for the block on the right a block instead of a page but then there is no URL that I can call to get to it, as far as I can tell.
Have I misunderstood how Drupal.ajax works? Any help would be most appreciated.
-- Henry
SOLVED:
I figured out what I was missing. The ajax_setting array needs 'wrapper' and 'method' elements (which are listed as optional in the documentation but which are required for what I'm doing, apparently). The document where I found them described is here: https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.2.x#sub_form. I needed to update the div in my target block with an id="ccd-update" to match the wrapper.
var ajax_settings = {
submit: view_info,
url: '/center/'+nid,
element: list,
wrapper: 'ccd-update',
method: 'html',
event: 'click',
} ;
With just the wrapper, the link worked the first time it was clicked but subsequent clicks failed to update the block. With the method set to html, it worked.
I'm not sure what, if any, of the view_info array is needed. That's left as an exercise for the reader.
-- HHH
| |
doc_3194
|
Here is my Code snippet:
@Modifying
@Query("UPDATE TBL_NAME SET DELETE_FLAG = 'YES' WHERE DELETE_FLAG = 'NO'
AND FILE_NM = :FILE_NM")
public void softDelete(@Param("FILE_NM") String fileName)
{
}
I am not getting any error, but data is not being updated in database.
Actual result must be like all the existing rows must be updated with DELETE_FLAG to YES.
A: Make sure you invoke the repository method with an active transaction.
Actually, in my last project I use the following idiom for updating a flag :
Entity is annotated with Hibernetish:
@Entity
@Table(name="myTable")
@Where(clause = "is_deleted = 0")
@Cacheable
public class MyTable {}
Actual update comes with a trivial find method:
@Transactional
public void deleteById(@NonNull final Long themeId) {
themeRepository.findById(themeId).orElseThrow(() -> new EntityNotFoundException(THEME_NOT_FOUND + themeId))
.setDeleted(true);
}
| |
doc_3195
|
"data":{facebook":{"message"}},
but I keep getting square brackets:
"data":{"facebook":["message"]}
Here is my code:
$output["contextOut"] = array(array("name" => "$next-context", "parameters" =>
array("param1" => $param1value, "param2" => $param2value)));
$output["speech"] = $outputtext;
$output["data"] = array("facebook" => array("message"));
$output["displayText"] = $outputtext;
$output["source"] = "index.php";
ob_end_clean();
echo json_encode($output);
and this is my json encoded output:
{"contextOut":[{"name":"buy-context","parameters":{"param1":null,"param2":null}}],"speech":"msg","data":{"facebook":["message"]},"displayText":"msg","source":"index.php"}
How do I obtain the curly brackets instead of the square brackets? Thanks in advance for any help.
A: As Paul Crovella said, your stated goal is invalid JSON.
Your valid options are for the facebook property to directly contain the message string:
{
"data":{"facebook":"message"},
}
(note I've added the outer { and } missing from your question) ...in which case you want:
$output["data"] = array("facebook" => "message");
Or you can make facebook refer to an object with a message property that has a value, like this:
{
"data":{"facebook":{"message":"value"}},
}
by doing this:
$output["data"] = array("facebook" => array("message" => "value"));
| |
doc_3196
|
The droid have a box collider also the door have a box collider.
But when i move the character(FPSController/FirstPersoncharacter) the player the character stop can't move through the door but the droid can.
I tried to turn off/on the Is Trigger property on the droid box collider but it didn't change.
I want the droid to act like the player when colliding with other objects like the droid is part of the player.
The only code i'm using is attached to the FirstPersonCharacter:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroidMove : MonoBehaviour
{
public GameObject droid;
private float distance;
private Camera cam;
private void Start()
{
cam = GetComponent<Camera>();
distance = Vector3.Distance(cam.transform.position, droid.transform.position);
droid.SetActive(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
droid.SetActive(!droid.activeInHierarchy);
}
}
}
I tried to add a Rigidbody component to the droid to the NAVI or to the Droid_Player but it didn't solve it. I don't have any other code that handle collidings.
UPDATE to what i tried and did so far:
From the NAVI (Droid) i removed the box collider component and added two things:
*
*Character Controller component
*Control script (This script is coming with the NAVI(Droid))
This is the Control script:
using UnityEngine;
using System.Collections;
public class Control : MonoBehaviour
{
public float rotationDamping = 20f;
public float speed = 10f;
public int gravity = 0;
public Animator animator;
float verticalVel; // Used for continuing momentum while in air
CharacterController controller;
void Start()
{
controller = (CharacterController)GetComponent(typeof(CharacterController));
}
float UpdateMovement()
{
// Movement
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
inputVec *= speed;
controller.Move((inputVec + Vector3.up * -gravity + new Vector3(0, verticalVel, 0)) * Time.deltaTime);
// Rotation
if (inputVec != Vector3.zero)
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(inputVec),
Time.deltaTime * rotationDamping);
return inputVec.magnitude;
}
void AnimationControl ()
{
if(Input.GetKey("a") || Input.GetKey("s") || Input.GetKey("d") || Input.GetKey("w"))
{
animator.SetBool ("Moving" , true);
}
else
{
animator.SetBool ("Moving" , false);
}
if(Input.GetKey("space"))
{
animator.SetBool ("Angry" , true);
}
else
{
animator.SetBool ("Angry" , false);
}
if(Input.GetKey("mouse 0"))
{
animator.SetBool ("Scared" , true);
}
else
{
animator.SetBool ("Scared" , false);
}
}
void Update()
{
UpdateMovement();
AnimationControl();
if ( controller.isGrounded )
verticalVel = 0f;// Remove any persistent velocity after landing
}
}
Now when i move the character close to a door or wall also the NAVI(Droid) stop and is not moving through the door or wall and this is fine. But now i have another problem. If i will keep moving to the door or wall it looks like the character is moving over/on the NAVI Droid.
The Navi droid is not changing position.
In this screenshot is how it looks like when i moved close to the door the collider on the door and the NAVI Droid are working and the navi droid can't move through the door:
In this screenshot you can see what is happened when i kept moving the character to the door. On the top screen view the NAVI droid is in the same position but on the Game View on the bottom it seems like the character is moving over/on the NAVI droid.
And if i will keep moving to the door the character will not move but the droid looks like pushed back or the character will keep moving over the droid.
This is a short video clip i recorded showing the problem.
The problem start at second 20:
Collider problem
I tried to add box collider to the droid tried rigidbody nothing worked only this script and component but now i have this problem in the video.
A: Looks like your droid probably needs a RigidBody component.
If that doesn't solve it, you should add some relevant code snippets to your question to show how/where you've tried to detect and handle collisions.
| |
doc_3197
|
Instead, I just want to return status code 401 with an empty response body (or at least an empty "_issues" field). Is there any way to do that? Authentication/authorization is not an option, because it's a public registration resource (public method POST allowed).
I already changed the status code to 401 (VALIDATION_ERROR_STATUS), but there is still the specific validation error, so an attacker could "fix" his request according to the validation error.
The aim is to only allow requests with some magic field value in it (which is validated for specific length etc) and to forbid all other requests for this resource.
A: Have you looked into event hooks? Try something like this:
def my_callback(resource, request, response):
data = response.json
del(data['_issues'])
del(data['_error'])
response.set_data(json.dumps(data))
app = Eve()
app.on_post_POST += my_callback
app.run
| |
doc_3198
|
That would be useful to be able to do:
void SortByLength(List<string> t)
{
t = t.OrderBy(
s => s,
Comparer<string>.FromLambda((s1,s2) => s1.Length.CompareTo(s2.Length))
).ToList();
}
It would be much easier than having to define a Comparer class each time.
I know it is not complicated to create such a FromLambda method, but I was wondering if there was an existing way in the framework as I see this as being a pretty common feature.
A: The other answers are from before the release of .NET 4.5. But with the BCL of .NET 4.5 (Visual Studio 2012), you simply say
Comparer<string>.Create((s1,s2) => s1.Length.CompareTo(s2.Length))
See the Comparer<T>.Create documentation.
A: Why would you make it that difficult?
Ordering the list by length is as simple as:
var ordered = list.OrderBy(s => s.Length);
If you really need that complicated stuff, the ComparisonComparer
could help you out. Please have a look here: Converting Comparison to icomparer
This is building an IComparer from a lamda or delegate!
Here is the essential code from that example
public class ComparisonComparer<T> : IComparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
}
A: I ended up creating additional overloads for the common methods (OrderBy, GroupBy, etc.) to take lambdas for IComparer and IEqualityComparer:
public static class EnumerableExtensions
{
public static IEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> comparer)
{
return source.OrderBy(keySelector, new GenericComparer<TKey>(comparer));
}
private class GenericComparer<T> : IComparer<T>
{
private readonly Func<T, T, int> comparer;
public GenericComparer(Func<T, T, int> comparer)
{
this.comparer = comparer;
}
public int Compare(T x, T y)
{
return this.comparer(x, y);
}
}
}
A: I think you are over complicating things.
List<string> SortByLength(List<string> t)
{
return t.OrderBy(
s => s.Length
).ToList();
}
| |
doc_3199
|
<tr>
{{#each columns}}
<th>
{{name}}
</th>
{{/each}}
</tr>
{{#each items}}
<tr>
{{each columns}}
<td>
{{! I want the items statusString field here for example }}
{{../dataField}}
</td>
{{/each}}
</tr>
{{/each}}
and the input to this template looks a bit like this:
columns = [
{name: 'status', dataField: 'statusString'},
{name: 'name', dataField: 'name'}
]
items = [
{status: 1, statusString: 'Active', name: 'item 1'},
{status: 1, statusString: 'Active', name: 'item 2'},
{status: 0, statusString: 'Disabled', name: 'item 3'},
{status: 1, statusString: 'Active', name: 'item 4'}
]
in the template i want to iterate each column and display for each item the data that corresponds to each column. But how do I do it in handlebars? I've tried expressions like {{../{{dataField}}, {{{{dataField}}}} but I can't get anything to work.
I use handlebars in ember.js.
A: This can be completed simply by using a helper
Handlebars.registerHelper('helper', function(fieldname, item) {
return item[fieldname];
});
Another way to do it would be using an object iterator, which has been recently added by handlebars. You can iterate through an object like this
var data = {"a": {"test":"test", "test2":"test2"}};
with a template
{{#each a}}
{{@key}} - {{this}},
{{/each}}
Would print out "test - test, test2 - test2,". If you edited your data you could get the correct output by using this.
Heres a jsfiddle showing both of these.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.