input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Reset select border radius on Chrome (Mac) <p>I am trying to reset the <code>border radius</code> of <code>select</code> tag in chrome (Mac) but its still showing after applying my <code>CSS</code>, how do I reset the <code>border-radius</code> in chrome (mac), it works fine in windows and fireFox in Mac.</p>
<p>Here is <a href="https://jsfiddle.net/sanjeevks121/1uwbgtm9/" rel="nofollow">JSFiddle</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>select {
padding: 10px;
height: 50px;
line-height: 50px;
border-radius: 0;
-webkit-border-radius:0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
<option>Option Title Goes here</option>
<option>Option Title Goes here</option>
<option>Option Title Goes here</option>
<option>Option Title Goes here</option>
<option>Option Title Goes here</option>
<option>Option Title Goes here</option>
</select></code></pre>
</div>
</div>
</p>
| <p>Try adding this to your css, and style select then according to your needs.</p>
<pre><code>-webkit-appearance: none;
</code></pre>
|
Where to find auth.token data, inside firebase objects <p>I am using <code>signInWithCustomToken</code>, after authentication I can not find where is stored my custom claims data which I have set in the server side(createCustomToken).</p>
<p>I can see them in firebase rules via auth.token, but how can I access them through firebase objects from within my javascript code.</p>
| <p>The information in the token is not automatically available to your application code. But it is embedded in the token, so you can decode it yourself:</p>
<pre><code>function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
};
var user = firebase.auth().currentUser
user.getToken().then(data => {
console.log(parseJwt(data));
});
</code></pre>
<p>The function to parse the JWT comes from this question: <a href="http://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript">How to decode jwt token in javascript</a></p>
<p>You'll note that it doesn't verify that the ID token is valid. That seems fine to me in client-side code, since the information will be used by the user themselves anyway. But if you do want to verify the token, you'll have to use a more involved method.</p>
|
Creat treeview array or sub array <p>These are the data as they are in mysql table</p>
<p>Table A (Tasks)</p>
<pre><code>task_id | name | description
-----------------------------
1 | soccer| fora
-----------------------------
2 | sussam| forb
-----------------------------
3 | sosssi| forc
-----------------------------
4 | sillly| ford
</code></pre>
<p>Tabble B Milestones</p>
<pre><code>mile_id | name | task_id
------------------
1 | task1mi | 1
------------------
2 | task2mi | 1
-------------------
3 | task3mi | 3
</code></pre>
<p>I am looking to making a treeview array, something like for each task as a parent milestone as a child array of task id.</p>
<p>What the print_r() function should return (desired output with php after mysql query)</p>
<pre><code> array(
name=>'soccer',
description =>'fora'
task_id=>array(
mile_id=>'1',
name=>'task1mi'
)
)
</code></pre>
<p>Any Suggestions</p>
| <p>You can do it following way but it is not good for performance. I don`t know exact requirement and fretwork are you using. So i am giving basic idea.</p>
<pre><code>$sqlparent = "select * from tasks";// get your task details from database.
$parentData = $sqlparent;// result from sql function.
foreach($parentData as $key=>$value)
{
$sql = "select * from Milestones where task_id='".$value['task_id']."'";// find the Milestones of the task
$milestonesResult = mysql_featch_array($sql); // run sql and get data from database it is giving you single record you need to create loop here. as i don`t know what are you using for PHP.
$value['milestoneslist'] = $milestonesResult; //task_id=>array( here you can not use task_id => array as it is already there. if you do it it will over-right the task_id
}
</code></pre>
<p>I hope you will get idea from this.</p>
|
Calling SQL Server stored procedure from vb.net 2008 error <p>I am trying to execute a SQL Server stored procedure from vb.net 2008. But I get the error </p>
<blockquote>
<p>Procedure or function 'Sp_Messages_Display' expects parameter '@MsgSno', which was not supplied.</p>
</blockquote>
<p>Here is my code</p>
<pre><code>Public Function Load(ByVal CnnStr As String, ByVal MsgSno As Long, ByVal Msg_Status As eMsgStatus) As ADODB.Recordset
Dim Cnn As ADODB.Connection
Dim Com As ADODB.Command
Cnn = New ADODB.Connection
Cnn.CursorLocation = ADODB.CursorLocationEnum.adUseClient
Cnn.ConnectionString = CnnStr
Cnn.Open()
Com = New ADODB.Command
Com.ActiveConnection = Cnn
With Com
.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
.CommandText = "Sp_Messages_Display"
.CreateParameter("@MsgSno", ADODB.DataTypeEnum.adBigInt, ADODB.ParameterDirectionEnum.adParamInput, 4, MsgSno)
.CreateParameter("@Msg_Status", ADODB.DataTypeEnum.adSmallInt, ADODB.ParameterDirectionEnum.adParamInput, 4, Msg_Status)
Load = .Execute(RecordsAffected)
SqlError = Err.Description
End With
If Not Load.EOF Then
With Me
.MsgSno = Load.Fields("MsgSno").Value
End With
End If
Com.ActiveConnection = Nothing
Cnn = Nothing
End Function
</code></pre>
<p>Please help me where I am wrong. Thanks in advance</p>
| <p>You need to add parameters to the <code>Command</code>, the <code>CreateParameter</code> only creates a new instance without adding it to the collection of the <code>Command</code>:</p>
<pre><code>With Com
CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
.CommandText = "Sp_Messages_Display"
.Parameters.Add("@MsgSno", ADODB.DataTypeEnum.adBigInt, ADODB.ParameterDirectionEnum.adParamInput, 4, MsgSno)
.Parameters.Add("@Msg_Status", ADODB.DataTypeEnum.adSmallInt, ADODB.ParameterDirectionEnum.adParamInput, 4, Msg_Status)
Load = .Execute(RecordsAffected)
SqlError = Err.Description
End With
</code></pre>
<p>I now believe you are not using <strong>VB.NET</strong>, but <strong>VB</strong>, in that case this is the way to go from MSDN:</p>
<pre><code>ccmd.parameters.Append ccmd.CreateParameter(, adInteger, adParamReturnValue, , NULL) ' return value
ccmd.parameters.Append ccmd.CreateParameter("InParam", adVarChar, adParamInput, 20, "hello world") ' input parameter
ccmd.parameters.Append ccmd.CreateParameter("OutParam", adVarChar, adParamOuput, 20, NULL) ' output parameter
</code></pre>
|
Create database in mongoDB using php <p>I am on mongoDB 3 and php version 5.6. I want to create a database for adding data in it. I am trying in this way. </p>
<pre><code><?php
require 'vendor/autoload.php';
// connect to mongodb
$db = new MongoDB\Client("mongodb://localhost:27017");
echo "Connected";
// select a database
$data = $db->selectDatabase("admin");
echo "Done ";
?>
</code></pre>
<p>This code is running well but not making any database in the <code>MongoDB</code>. Can someone help?</p>
| <p>I hope you have installed Mongodb driver for PHP and you are not receiving any exception while executing your code.<br><br></p>
<p><strong>After the db connection is established you need to save something in collection so that the db comes to existence. This is missing in your code.</strong><br><br></p>
<p>Try below code<br><br></p>
<pre><code><?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->admin;
echo "Database admin selected";
$collection = $db->createCollection("mycol");
echo "Collection created succsessfully";
?>
</code></pre>
|
YII2 UrlManager wrong route <p>On my site I have this urlManager rule:
<code>'city/<id:\d+>-<alias:\S*>' => 'city/view'</code>,
On page of module "user", for example this <a href="https://example.com/user/profile" rel="nofollow">https://example.com/user/profile</a>, there is a link for rule </p>
<pre><code>Url::to(['city/view', 'id' => $this->id, 'alias' => $this->alias], $absolute)
</code></pre>
<p>But link becomes this <a href="https://example.com/user/city/view?id=1&alias=city_alias" rel="nofollow">https://example.com/user/city/view?id=1&alias=city_alias</a>
What I am doing wrong?</p>
| <p>You need to add module ID in the route as well. In the simplest case it's</p>
<pre><code>'user/city/<id:\d+>-<alias:\S*>' => 'user/city/view'
</code></pre>
<p>If there are more than one module using similar route you can use wildcard</p>
<pre><code>'<module>/city/<id:\d+>-<alias:\S*>' => '<module>/city/view'
</code></pre>
|
Why is code first migrations changing table name? <p>I am trying to make a forein key relation (one ---to----many)</p>
<p>And have the applicationUser have a foreinKey to an existing person table.</p>
<p>my code.</p>
<pre><code>public class ApplicationUser : IdentityUser
{
[Required]
public long PersonId { get; set; }
//[Required]
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
</code></pre>
<p><strong>Person Table(existing in db)</strong></p>
<pre><code>public class Person
{
[System.ComponentModel.DataAnnotations.KeyAttribute()]
[System.ComponentModel.DataAnnotations.Schema.DatabaseGeâânerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGenââeratedOption.None)]
public long PersonId { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
}
</code></pre>
<p><strong>Problem</strong>:</p>
<p>When using the migrations I get the following.</p>
<p><strong>up method:</strong></p>
<pre><code> CreateTable(
"dbo.People",
c => new
{
PersonId = c.Long(nullable: false),
})
.PrimaryKey(t => t.PersonId);
</code></pre>
<p><strong>down method:</strong></p>
<pre><code> public override void Down()
{
DropForeignKey("dbo.AspNetUsers", "PersonId", "dbo.People");
DropIndex("dbo.AspNetUsers", new[] { "PersonId" });
DropTable("dbo.People");
}
</code></pre>
<p>Where did the dbo.People come from??? it is suppose to go to db.Person which is an already created table(via sql).</p>
<p>How can I solve this?</p>
| <p>By default Entity Framework pluralizes the entity name to name the DB table. You can switch off this behavior in the <code>OnModelCreating</code> method by adding the following code:</p>
<pre><code>modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
</code></pre>
|
Javascript smooth window scrolling via scrollbar <p>I would like my webpage to have smooth browser scrolling via the window scrollbar. That is, if you drag the window scroll bar down and stop, I want the webpage to start scrolling immediately and then decelerate to the stop point.</p>
<p>I've seen implementations of this for mousewheel event, but I want it for scrollbar event as well. For example on this stack overflow question <a href="http://stackoverflow.com/questions/19349245/enable-smooth-scrolling-for-my-website-in-all-browsers">Enable smooth scrolling for my website in all browsers</a> , Jan TuroÅ gave a good implementation for mousewheel. I want that same behaviour, but also for scrollbar drag and stop.</p>
<p>Anyone know how to do it?</p>
| <p>I achieved the results I want with mcustomscrollbar. But it took me a while to figure out how to use it within a react project, which I explained here:</p>
<p><a href="http://stackoverflow.com/questions/38490303/reactjs-jquery-custom-content-scroller-with-reactjs/39938434#39938434">Reactjs: jQuery custom content scroller with reactjs</a></p>
|
Mouse & Touch horizontal div sliding <p>I'm trying to make a feature for my website which allows user to horizontally scroll div content using mousemove and touchmove events (it's similar to Apple AppStore <a href="https://itunes.apple.com/us/app/itunes-movie-trailers/id471966214?mt=8" rel="nofollow">any app Screenshots section</a>). I'm doing this by setting a negative margin-left property for first child. Everything is working except that when user on mobile device touches screen or on desktop moves cursor into parent div, it's content not scrolling from where currently is but it's "jumping". I tried to do this by adding current margin-left value to new pageX value, but it's not working. What I'm doing wrong? Or maybe it's not possible to do this feature this way?</p>
<p>JS/Babel code:</p>
<pre><code>class Collage {
constructor(selector) {
this.selector = $(selector);
this.children = this.selector.children(':first-child');
this.selector.on('mousemove touchmove', this.onMove.bind(this));
}
onMove(event) {
const marginLeft = parseFloat(this.children.css('margin-left'));
let mouseX = event.pageX || -event.touches[0].pageX || -event.changedTouches[0].pageX;
const margin = calculateMargin(mouseX, 1);
this.children.css('margin-left', margin);
function calculateMargin(value, speed) {
let val = -value*speed;
return val <= 0 ? val : 0;
}
}
}
</code></pre>
<p>SCSS code:</p>
<pre><code>.collage {
overflow: hidden;
max-height: 300px;
white-space: nowrap;
font-size: 0;
img {
display: inline-block;
&:first-of-type {
margin-left: -20%;
}
}
}
</code></pre>
<p>My <a href="https://jsfiddle.net/ojs0L3xd/3/" rel="nofollow">fiddle</a></p>
<p>Thanks in advance for your answers.</p>
| <p>Can you just get what you want without Javascript by creating a second wrapper element around the images?</p>
<pre><code><div class="collage">
<div class="wrapper">
<img /> ....
</div>
</div>
</code></pre>
<p>Then CSS</p>
<pre><code>.collage {
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
width: 100%;
display: block;
position: relative;
}
.wrapper {
width: 10000px;
/* set width to something large
or set with Javascript to the calculated width of your images */
}
</code></pre>
|
404 error while searching for twilio available phone number <p>I'm using Twilio trial account to know the compatibility of twilio with our project, I've tried to search for Twilio phone number using NodeJS API but, it is throwing 404 error for all the locations every time. Is it the problem with trial account or code.</p>
<p>Here is my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var accountSid = '[My AccountSid]';
var authToken = '[My authToken]';
//require the Twilio module and create a REST client
var client = require('../lib')('ACCOUNT_SID', 'AUTH_TOKEN');
client.availablePhoneNumbers('US').mobile.get({
}, function(err, data) {
if(data){
data.incomingPhoneNumbers.forEach(function(number) {
console.log(number.PhoneNumber);
});
}else{
console.log(err);
}
}); </code></pre>
</div>
</div>
</p>
| <p>Twilio developer evangelist here.</p>
<p>We don't actually have a distinction between mobile and local numbers in the US, since the number format is the same and all numbers are voice and SMS capable.</p>
<p>So, I'd just use <code>.local</code> instead of <code>.mobile</code>.</p>
<p>Let me know if that helps.</p>
<p><strong>[EDIT]</strong></p>
<p>I used the following code and it returned and printed a list of US local numbers:</p>
<pre><code>var twilio = require("twilio");
var client = new twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
client.availablePhoneNumbers('US').local.get({},
function(err, data) {
console.log(data);
}
)
</code></pre>
|
How to read editor text before cursor position to match specific words? <p>I am trying to detect when the cursor has moved somewhere immediately after a specific strings ... I can do it only for I have one string , But when I have more than one I cant't matched ... If I have one string like : "color:" then the code to match the word is :</p>
<pre><code><!-- Create a simple CodeMirror instance -->
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<textarea id="myTextarea"></textarea>
<script>
var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});
//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
stringToMatch = "color:",
n = stringToMatch.length,
stringToTest = e.doc.getLine(line).substr(Math.max(ch - n,0),n);
if (stringToTest == stringToMatch) console.log("SUCCESS!!!");
});
</script>
</code></pre>
<p>But when I have array of strings like (var array=["one","three","five"]) and I want to match any word in this array I can't do it ... so any body can help I try a lot and failed </p>
<p>NOTE : the code above I take it from : <a href="http://stackoverflow.com/questions/32622128/codemirror-how-to-read-editor-text-before-or-after-cursor-position">here</a></p>
| <p>You could use a regular expression for matching one of several words:</p>
<pre><code>var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
// Select all characters before cursor
stringToTest = e.doc.getLine(line).substr(0, ch),
// Array with search words: escape characters for use in regular expression:
array=["one","three","five"].map( s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') );
// Join words with OR (|) and require they match just before the cursor
// (i.e. at end of string: $)
if (stringToTest.match(new RegExp('('+array.join('|')+')$'))) console.log("SUCCESS!!!");
</code></pre>
<p>Here is a working snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});
//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
// Select all characters before cursor
stringToTest = e.doc.getLine(line).substr(0, ch),
// Array with search words: escape characters for use in regular expression:
array=["one","three","five"]
.map( s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') );
// Join words and require they match just before the cursor
// (i.e. at end of string: $)
if (stringToTest.match(new RegExp('(' + array.join('|') + ')$')))
console.log("SUCCESS!!!");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.19.0/codemirror.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.19.0/codemirror.js"></script>
<textarea id="myTextarea"></textarea></code></pre>
</div>
</div>
</p>
|
PHP session.save_path ignored <p>I was having problems with my PHP website (SuiteCRM) not being able to log users in and I found it was due to not being able to write on the sessions directory.</p>
<p>I am able to fix it by creating the directory <code>/tmp/php_sessions</code> and giving it write permissions for the Apache user <code>www-data</code>. I see the directory get populated with files as users log in.</p>
<p>However, Ubuntu Xenial is deleting my entire <code>tmp</code> directory on reboots, so I have to redo this all over again every time. I decided to move my <code>save_path</code> elsewhere.</p>
<p>After changing things in my php.ini file, and restarting Apache, I can check that they are effective by running this simple script:</p>
<pre><code><?php
echo ini_get("session.save_path");
phpinfo();
?>
</code></pre>
<p>This shows me a double confirmation of the new path, first echoing <code>/var/tmp/php_sessions</code> and then, in the middle of all the phpinfo information, showing the same value as both <code>Local Value</code> and <code>Master value</code> for directive <code>session.save_path</code>.</p>
<p><strong>BUT</strong> the directory that php is using is still the first one, <code>/tmp/php_sessions</code>! It seems that my setting is being ignored.</p>
<p>Am I overlooking something? Where could that old setting be buried? Or how can I make the new one effective?</p>
<p>(P.S. - I am not using a <code>redis</code> handler as in another similar SO question)</p>
| <p>Ok, I solved my own problem and the <strong>general answer</strong> is as follows:</p>
<p>There are two more things that can be changing the path and need to be checked, </p>
<ol>
<li><p>the PHP code of the application might be changing the <code>ini</code> directive, search the code for <code>ini_set(session.save_path</code></p></li>
<li><p>the PHP code might be using the <code>session_save_path</code> PHP command to override the <code>ini</code>. Search the code for that also (and notice the two underscores <code>_</code>!)</p></li>
</ol>
<p>And the <strong>specific answer</strong> for my case was that SuiteCRM uses <code>session_save_path</code> command to set its path with a value coming from the file <code>config.php</code> found at the web root. That's where I found the old setting, and changing it solved my problem (for good, I hope).</p>
|
Transition effect not working when added display attribute <ul>
<li><p>Requirement is to put <code>transition</code> effect on redeem now button. Initially redeem now button is hidden, on hover it will display the redeem now button with transition</p></li>
<li><p>Problem is I have added <code>display: none</code> for redeem now button and on hover its showing <code>display: block</code>. </p></li>
</ul>
<p>Below is my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wpf-demo-3 {
background-color: #FFF;
display: block;
width: 265px;
height: 300px;
overflow: hidden;
position: relative;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
-ms-transition: all 0.5s;
-o-transition: all 0.5s;
transition: all 0.5s;
}
.wpf-demo-3:hover .view-caption {
-moz-transform: translateY(-100%);
-o-transform: translateY(-100%);
-ms-transform: translateY(-100%);
-webkit-transform: translateY(-100%);
transform: translateY(-100%);
position: absolute;
left: 0px;
right: 0px;
bottom: -287px;
display: block;
height: 270px;
text-align: center;
border-top: 2px none #0066b3;
border-right-width: 0px;
background-color: hsla(0, 0%, 100%, .3);
box-shadow: 0 -1px 8px 0 rgba(0, 0, 0, .16);
transition: all 0.5s;
transition-duration : 0.3s;
display: block !important;
}
.wpf-demo-3 .view-caption {
background-color: #FFF;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
-ms-transition: all 0.5s;
-o-transition: all 0.5s;
transition: all 0.5s;
padding: 10px;
height: 15%;
display: none !important;
}
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div class="col-xs-12 col-sm-3 col-md-3 text-center item-spacing" style=" margin: 0px; padding: 0px;" >
<div class="item hot-deals-wrapper clearfix item-spacingies " style="height: 300px;">
<div class="wpf-demo-3">
<h5> <strong><a style="color:#000;text-decoration:none" data-bind="text:name,attr:{href:redirectLink}"></a></strong> </h5>
<div data-bind="ifnot: mediumImage">
<div class="img-wrapper"> <a data-bind="attr:{href:redirectLink}"><img src="https://d2kbtrec8muwrn.cloudfront.net/assets/web/fnp/fnp/basket/B28.jpg"/></a> </div>
</div>
<div> <a href="javascript:void(0)" class="news socialwrapper" class="btn text-right"><i class="fa fa-share-alt share-icon socialicons"></i></a>
<div style="display:none" class="alert_list"> </div>
</div>
<a href = "https://www.google.co.in/" class = "view-caption">
<button class="btn btn-default pb-bg-red bottommarginmore redeemNowBtn " style=" width: 128px; margin-top: 25px;">Redeem Now</button>
</a> </div>
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>You can try this instead of dispaly property </p>
<p><strong>CSS CODE:</strong></p>
<pre><code>.wpf-demo-3:hover .view-caption {
-moz-transform: translateY(-100%);
-o-transform: translateY(-100%);
-ms-transform: translateY(-100%);
-webkit-transform: translateY(-100%);
transform: translateY(-100%);
position: absolute;
left: 0px;
right: 0px;
bottom: -287px;
display: block;
height: 270px;
text-align:center;
border-top: 2px none #0066b3;
border-right-width: 0px;
background-color: hsla(0, 0%, 100%, .3);
box-shadow: 0 -1px 8px 0 rgba(0, 0, 0, .16);
transition: all 0.5s;
transition-duration : 0.3s;
opacity: 1;
visibility: visible;
}
.wpf-demo-3 .view-caption {
background-color: #FFF;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
-ms-transition: all 0.5s;
-o-transition: all 0.5s;
transition: all 0.5s;
padding: 10px;
height: 15%;
opacity: 0;
visibility: hidden;
}
</code></pre>
<p><strong>DEMO:</strong>
<a href="https://jsfiddle.net/JentiDabhi/k5c6net2/" rel="nofollow">https://jsfiddle.net/JentiDabhi/k5c6net2/</a></p>
|
Parsing this JSON in HIVE <p>I'm completely new to JSON. I have below JSON in one of the HIVE columns. I am not sure, how to arrange {} and [] ,but tried my best.</p>
<pre><code>{
"main_key":
[
{
"type":"RESPONSIBLE",
"lastName":"John"
},
{
"ids":
[
{
"id":"001815015",
"qual":"PIN"
},
{
"id":"592852900",
"qual":"TIN"
}
],
"type":"BILLING",
"lastName":"Joe"
},
{
"ids":
[
{
"id":"002329056",
"qual":"PIN"
}
],
"type":"SVC",
"lastName":"Jame"
}
]
}
</code></pre>
<p>Above JSON should be parsed to as below. Need Hive query which can do like this. </p>
<p><a href="http://i.stack.imgur.com/UrZMq.png" rel="nofollow"><img src="http://i.stack.imgur.com/UrZMq.png" alt="enter image description here"></a>
Thanks,</p>
| <p>You can use <code>get_json_object</code> or <code>json_tuple</code></p>
<p>Example: src_json table is a single column (json), single row table:</p>
<pre><code>+----+
                               json
+----+
{"store":
  {"fruit":\[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],
   "bicycle":{"price":19.95,"color":"red"}
  },
 "email":"amy@only_for_json_udf_test.net",
 "owner":"amy"
}
+----+
hive> SELECT get_json_object(src_json.json, '$.owner') as owner FROM src_json;
amy
Â
hive> SELECT get_json_object(src_json.json, '$.store.fruit\[0]') as fruitdata FROM src_json;
{"weight":8,"type":"apple"}
Â
hive> SELECT get_json_object(src_json.json, '$.non_exist_key') FROM src_json;
NULL
</code></pre>
<p><a href="http://thornydev.blogspot.com/2013/07/querying-json-records-via-hive.html" rel="nofollow">more info</a></p>
|
Why isn't TaskCanceledException stored in Task.Exception property when I execute multiple tasks? <p>I have an application that executes several consequent HTTP requests to RESTful API for each of the different items.</p>
<p>The code I have to handle exceptions from executing these requests is similar to the one described in <a href="http://shop.oreilly.com/product/0636920030171.do?cmp=af-code-books-video-product_cj_0636920030171_7489747" rel="nofollow">Concurrency in C# Cookbook</a> by <a href="http://stackoverflow.com/users/263693/stephen-cleary">Stephen Cleary</a>, recipe 2.4:</p>
<pre><code>var tasks = new List<Task>();
foreach(var item in items)
{
tasks.Add(ProcessItemAsync(item));
}
var parentTask = Task.WhenAll(tasks);
try {
await parentTask;
} catch {
var exceptions = parentTask.Exception;
if (exceptions != null) {
// log individual exceptions
}
}
</code></pre>
<p>While analyzing the logs, I noticed that some of the processing did not result in sending all of the needed requests. However, there were no exceptions recorded in the logs. </p>
<p>When debugging the application, I found that calling one of the endpoints resulted in TaskCanceledException being thrown due to a timeout from Web API. However, <code>parentTask.Exception</code> property was <code>null</code>, hence, I did not correctly record this exception in the log.</p>
<p>My questions are the following:</p>
<ul>
<li>Why isn't TaskCanceledException stored in Task.Exception property?</li>
<li>Are there any other exceptions that would not be stored in Task.Exception property similar to TaskCanceledException?</li>
</ul>
| <p>You can get some more info about this by reading <a href="https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx" rel="nofollow">this documentation</a> about task cancellation, especially this part:</p>
<blockquote>
<p>If you are waiting on a Task that transitions to the Canceled state, a
System.Threading.Tasks.TaskCanceledException exception (wrapped in an
AggregateException exception) is thrown. Note that this exception
indicates successful cancellation instead of a faulty situation.
Therefore, <strong>the task's Exception property returns null</strong>.</p>
</blockquote>
<p>So main point is - task cancellation is an expected thing, it's not a fault. So no reason to set <code>Exception</code> property - information about cancellation is already recorded in <code>Task</code> state. </p>
<p>Another story is timeout <em>is</em> a fault and should not result in task cancellation. On the other hand, pending web request <em>is</em> cancelled after some time (after timeout), so that's arguable.</p>
<p>As a workaround, you might inspect all tasks in your <code>tasks</code> array to see if they are in cancelled state (<code>IsCancelled</code> returns true) and log accordingly.</p>
|
Word VBA: ConvertToShape method makes image disappear <p>I wrote some code for a client which isn't working correctly on his machine (Win 10, Office 365) but is on mine (Win 10, Office 2016). The code inserts an image to the header then positions it and resizes it. I use the ConvertToShape method so I can access properties like width, height and position of the Shape class.</p>
<pre><code>Dim pic As Shape
Dim shp As Word.InlineShape
Set shp = thisDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range.InlineShapes.AddPicture(fpImage) ' insert the image to the header
Set pic = shp.ConvertToShape ' THIS LINE CAUSES THE PROBLEM
</code></pre>
<p>The method causes the image to disappear. 'Pic' is still available and setting it's properties causes no error, but it is not visible. It's .visible property returns true.</p>
<p>Any ideas? Thanks.</p>
| <p>Answer provided to cross-post at <a href="https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom/word-vba-converttoshape-method-makes-image/900c4e6d-23e3-4c84-a5ad-4b47e8c9d848" rel="nofollow">Microsoft Community</a></p>
<p>There is a way to do this with only an inline shape, by setting up a table to position the text on the left and the picture on the right. An additional advantage of this method is that, if you set the table's AutoFitBehavior property to wdAutoFitFixed and set the column width to the width you want for the shape, Word will automatically resize the picture to that width and keep the aspect ratio.</p>
<p>Here's a little sample macro:</p>
<pre><code>Sub x()
Dim fpImage As String
Dim strExistingHeaderText
Dim tbl As Table
Dim shp As InlineShape
fpImage = "D:\Pictures\bunnycakes.jpg"
With ActiveDocument
strExistingHeaderText = _
.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text
Set tbl = .Tables.Add( _
Range:=.Sections(1).Headers(wdHeaderFooterPrimary).Range, _
numrows:=1, numcolumns:=2, _
AutoFitBehavior:=wdAutoFitFixed)
tbl.Columns(2).Width = InchesToPoints(1.5)
tbl.Columns(1).Width = InchesToPoints(5#)
tbl.Cell(1, 1).Range.Text = strExistingHeaderText
'tbl.Borders.Enable = False
Set shp = tbl.Cell(1, 2).Range.InlineShapes.AddPicture(fpImage)
End With
End Sub
</code></pre>
|
"incompatible types" in foreach with jdk 1.7 - no error with 1.6 <p>I have code similar to the following which compiles with jdk 1.6.0_22 but not with jdk 1.7.0_79:</p>
<pre><code>for(Entry<A, B> entry: aBean.getData().entrySet()) { }
</code></pre>
<p><code>getData()</code> returns a <code>Map<A, B></code>. With 1.7 the following compile error occurs, suggesting that the generics of the returned Set are erased:</p>
<pre><code>[compile] /path/to/file.java:170: error: incompatible types
[compile] for (Entry<A, B> entry: aBean.getData().entrySet()) {
[compile] ^
[compile] required: Entry<A, B>
[compile] found: Object
</code></pre>
<p>The error disappears when I use a local variable to hold the Set:</p>
<pre><code>Set<Entry<A, B>> mySet = aBean.getData().entrySet();
for(Entry<A, B> entry: mySet) { } //works
</code></pre>
<p>Given that this compiles under 1.6, am I correct in assuming this is a compile Bug? If not, what am I doing wrong?</p>
| <p>Have you already tested this with Java 8? If the issue still exists with the latest â and only supported â Java version, I suggest you create a <a href="http://bugs.java.com" rel="nofollow">bug report</a>.</p>
<p>Otherwise use the solution you already provided in your question.</p>
|
Passing data from controller function to controller function before redirect <p>I am using <strong>codeigniter</strong> I have an edit page which shows me all information of a vacancy.
The (Vacancy) controller method to load this view looks like this, it makes sure all data is preloaded.</p>
<pre><code>public function editVacancy($vacancyid)
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
// Passing Variables
$data['title'] = 'Titletest';
$data['class'] = 'vacancy';
$orgadminuserid = $this->vacancies_model->getOrgAdminUserId($vacancyid);
if ((!is_null($orgadminuserid)) && ($this->auth_user_id == $orgadminuserid[0]->user_id)) {
$data['vacancyid'] = $vacancyid;
$data['vacancy'] = $this->vacancies_model->get($vacancyid);
$data['test'] = $this->session->flashdata('feedbackdata');
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/edit_vacancy', 'footer' => '_master/footer/footer');
$this->template->load('_master/master', $partials, $data);
}
}
</code></pre>
<p>In this view i have different forms for updating different sections.
Every form submit goes to a different method in my <strong>'Vacancy' controller</strong>. </p>
<pre><code> public function saveGeneralInfo()
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
$vacancyid = $this->input->post('vacancyid');
$vacancyUpdateData = $this->vacancies_model->get($vacancyid);
$result = $this->vacancies_model->update($vacancyid, $vacancyUpdateData);
if ($result) {
$feedbackdata = array(
'type' => 'alert-success',
'icon' => 'fa-check-circle',
'title' => 'Success!',
'text' => 'De algemene vacature gegevens zijn geupdate.'
);
$this->session->set_flashdata('feedbackdata', $feedbackdata);
redirect("dashboard/vacancy/editVacancy/" . $vacancyid);
}
}
}
</code></pre>
<p>Where I indicated in my code "//HERE ..." is where I would want the feedback message parameter to pass on to my 'main controller method' which loads the view with the prefilled data. (editVacancy). </p>
<p>Is there a clean way to do this? </p>
<p>EDIT:</p>
<p>I tried using flashdata, i updated the code to have the flashdata inserted.</p>
<p>However when i do a var_dump($test); in my view, it remains null.</p>
<p>EDIT 2:
I noticed when i put my $_SESSION in a variable in my editVacancy controller method (which is being redirected to) and var_dump it in my view that this does not contain the ci_vars with the flashdata in.</p>
| <p>Instead of using <code>set_header</code> you can use simple <code>redirect</code> function for it.</p>
<pre><code>redirect("dashboard/vacancy/editVacancy/".$vacancyid);
</code></pre>
|
PHP: replace words from list in .txt-file with * <p>I've searched around the web for days now, and I can't get an answer for my problem...<br><br><b>So this is what I need to do:</b><br>
I have an .txt-file which contains one word per line. Let's say it's called <code>list.txt</code>.<br>And I have another .txt-file called <code>text.txt</code> with random stuff in it.<br>Now I want to have a PHP-file which checks if it finds words from <code>list.txt</code> in the <code>text.txt</code>-file and replace them with ******.<br><br><br><b>THANK YOU VERY MUCH FOR ANY HELP!</b></p>
| <p>Consider this as a kind of pseudocode, although it's PHP. It should guide you for your desired solution:</p>
<pre><code>$content = file_get_contents('text.txt');
$censored = explode("\n", file_get_contents('list.txt'));
$content = str_replace($censored, '*****', $content);
file_put_contents('text.txt', $content);
</code></pre>
|
How to make a form in excel <p>I don't know much about Excel. But, I want to make a form in Excel. Some items are fillable, and then others will have a drop-down menu for choices that is linked to another page that I can update from time to time. And, then I want the form to output all the items selected and items filled. How should I go about doing this? I hope you could help me. Thanks!</p>
| <p>This is as good a starting point as any for forms in Excel:
<a href="https://www.youtube.com/watch?v=lV9X2K8uEYE" rel="nofollow">https://www.youtube.com/watch?v=lV9X2K8uEYE</a></p>
<p>(It's worth continuing down the google forms route though as they provide an excellent interface and Google has already done most of the heavy lifting for you.)</p>
<p>Good luck!</p>
|
R: how to resample intraday data at the group level? <p>Consider the following dataframe</p>
<pre><code>time <-c('2016-04-13 23:07:45','2016-04-13 23:07:50','2016-04-13 23:08:45','2016-04-13 23:08:45'
,'2016-04-13 23:08:45','2016-04-13 23:07:50','2016-04-13 23:07:51')
group <-c('A','A','A','B','B','B','B')
value<- c(5,10,2,2,NA,1,4)
df<-data.frame(time,group,value)
> df
time group value
1 2016-04-13 23:07:45 A 5
2 2016-04-13 23:07:50 A 10
3 2016-04-13 23:08:45 A 2
4 2016-04-13 23:08:45 B 2
5 2016-04-13 23:08:45 B NA
6 2016-04-13 23:07:50 B 1
7 2016-04-13 23:07:51 B 4
</code></pre>
<p>I would like to <strong>resample</strong> this dataframe at the <code>5 seconds level</code> - <code>group level</code>, and compute the <strong>sum</strong> of <code>value</code> for each <code>time-interval</code> - <code>group value</code>.</p>
<p><strong>The interval should be closed on the left and open on the right</strong>. For instance, the first line of output should be</p>
<p><code>2016-04-13 23:07:45 A 5</code> because the first 5-sec interval is <code>[2016-04-13 23:07:45, 2016-04-13 23:07:50[</code></p>
<p>How can I do that in either <code>dplyr</code> or <code>data.table</code>? Do I need to import <code>lubridate</code> for the timestamps?</p>
| <p>With latest <a href="https://github.com/Rdatatable/data.table/wiki/Installation">devel version</a> (1.9.7+) of <code>data.table</code>:</p>
<pre><code>library(data.table)
# convert to data.table, fix time, add future time
setDT(df)
df[, time := as.POSIXct(time)][, time.5s := time + 5]
# use non-equi join to filter on the required intervals and sum
df[, newval := df[df, on = .(group, time < time.5s, time >= time),
sum(value, na.rm = T), by = .EACHI]$V1]
df
# time group value time.5s newval
#1: 2016-04-13 23:07:45 A 5 2016-04-13 23:07:50 5
#2: 2016-04-13 23:07:50 A 10 2016-04-13 23:07:55 10
#3: 2016-04-13 23:08:45 A 2 2016-04-13 23:08:50 2
#4: 2016-04-13 23:08:45 B 2 2016-04-13 23:08:50 2
#5: 2016-04-13 23:08:45 B NA 2016-04-13 23:08:50 2
#6: 2016-04-13 23:07:50 B 1 2016-04-13 23:07:55 5
#7: 2016-04-13 23:07:51 B 4 2016-04-13 23:07:56 4
</code></pre>
|
Creating Topics on AzureServiceBus using MassTransit <p>I have a namespace created in AzureSerivceBus. Directly, using Azure APIs, am able to create Topics and send-receive messages to it.</p>
<p>Now, I want to be able to create Topics using MassTransit as an abstraction layer. This is because for local installations, we use RabbitMq and MassTransit provides good abstraction. We now want the same code to move seamlessly over to Cloud (AzureServiceBus) and be able to perform the similar things. Is it possible to do it via MassTransit, i.e, create Topics and subscriptions to it?</p>
<p>The Azure document for MassTransit is very limited, so am not sure if it even supports Topics.</p>
<p>Any hints?</p>
| <p>As you noted correctly, MassTransit is an abstraction on top of the messaging service you choose to use. RabbitMQ or Azure Service Bus, doesn't matter. The whole point is that it will provide you the features you need w/o burdening with details. Topic are commonly used for pub/sub (publishing events). While documentation for ASB is not as detailed as for RabbitMQ, there a section that states support for publishing messages using topics (<a href="http://masstransit.readthedocs.io/en/master/overview/publishing.html#routing-on-azure-service-bus" rel="nofollow">http://masstransit.readthedocs.io/en/master/overview/publishing.html#routing-on-azure-service-bus</a>).</p>
|
How can I use the package.json to pull private git-repository from a certain branch when using Jenkins? <p>We have a main project, that loads sub-projects and then bundles them into one file with npm. Here is the package.json:</p>
<pre><code>{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"angular": "^1.5.7"
},
"devDependencies": {
"project-a": "git+ssh://git@bitbucket.org/project-a.git",
"project-b": "git+ssh://git@bitbucket.org/project-b.git"
},
"author": "",
"license": "ISC"
}
</code></pre>
<p>We want to build the project on multiple servers, e.g. master and develop and those are the names of the branches. Now if we build the develop-branch npm should pull from <code>git+ssh://git@bitbucket.org/project-a.git#develop</code> and <code>git+ssh://git@bitbucket.org/project-b.git#develop</code>. But I cant find a way to tell npm to pull those branches and not the master.</p>
<p>Any help is appreciated.</p>
| <p>First off, npm will pull what ever branch you tell it to pull. Format is like this:</p>
<pre><code>"devDependencies": {
"project-a": "git+ssh://git@bitbucket.org/project-a.git#branchName"
}
</code></pre>
<p>And if there's no branch defined, it will default to master. </p>
<p>So, this gives a starting point that you need to modify your dependency at runtime by appending the name of the branch to the url. On possibility to archive this that before you run npm install, you process the package.json by a tool that changes keyword (for example #branchName) into what you want it to be. Very easy to archive w/ tool like sed</p>
<p>However, that will leave your git repo "dirty" (as in, unmodified changes). Another alternative is to write a cli tool which will read your package.json, extracts the dependencies and installs them manually by calling npm install $reporul and postfixing the url repo with the branch you want .. Maybe this repo provides a tool that you can use if you are not up to writing one yourself: <a href="https://github.com/CrowdArchitects/node-rebranch-dependencies" rel="nofollow">https://github.com/CrowdArchitects/node-rebranch-dependencies</a></p>
|
Bootstrap DateRangePicker language on Range setting <p>I know I can use the <code>locale</code> setting to define Bootstrap DateRangePicker plugin language, although I can't figure out how do I define the language for the <code>range</code> setting.</p>
<pre><code>$('#my-calendar').daterangepicker(
{
ranges:
{
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 days': [moment().subtract(6, 'days'), moment()],
'Last 30 days': [moment().subtract(29, 'days'), moment()],
'This month': [moment().startOf('month'), moment().endOf('month')]
}
}
</code></pre>
<p>I would like to change <code>today</code>, <code>yesterday</code>, etc to the defined language. So I tried without success:</p>
<pre><code>var lang = JSON.parse($('#lang').val());
/*
* lang[0] = 'Today'
* lang[1] = 'Yesterday'
* lang[2] = 'Last 7 days'
* lang[3] = 'Last 30 days'
* lang[4] = 'This month'
*/
$('#my-calendar').daterangepicker(
{
ranges:
{
lang[0]: [moment(), moment()],
lang[1]: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
lang[2]: [moment().subtract(6, 'days'), moment()],
lang[3]: [moment().subtract(29, 'days'), moment()],
lang[4]: [moment().startOf('month'), moment().endOf('month')]
}
}
</code></pre>
<p>But this retrieves error <code>Uncaught SyntaxError: Unexpected token [</code> in every <code>lang[number]</code> line.</p>
<p>How do I set the right label language in the range setting?</p>
| <p><strong>Solved</strong> in a non-fashion way.</p>
<p>Basically, the DateRangePicker plugin creates a div which contains an list with <code>Today</code>, <code>Yesterday</code>, etc. </p>
<pre><code><div class="ranges">
<ul>
<li>Today</li>
<li>Yesterday</li>
</ul>
</div>
</code></pre>
<p>So after the plugin has done being initialized I change the <code>text</code>of the <code>li</code> manually.</p>
<pre><code>$('.ranges ul li').eq(0).text(lang[0]);
$('.ranges ul li').eq(1).text(lang[1]);
</code></pre>
|
Excel Graph from text Input <p>I have table in Excel with 2 Columns. </p>
<p>My Column Headers are: "Company Name" and "Company Status."</p>
<p>I want to make a graph of these two columns showing the following data:</p>
<ol>
<li><p>How many % of companies or how many companies have value "Success"</p></li>
<li><p>How many % of companies or how many companies have value "Fail"</p></li>
</ol>
<p><a href="http://i.stack.imgur.com/QnTa6.png" rel="nofollow"><img src="http://i.stack.imgur.com/QnTa6.png" alt="Graph"></a></p>
<p>Any help?</p>
<p>Thank you</p>
| <p>Refer to <a href="http://www.techrepublic.com/blog/microsoft-office/displaying-percentages-as-a-series-in-an-excel-chart/" rel="nofollow">http://www.techrepublic.com/blog/microsoft-office/displaying-percentages-as-a-series-in-an-excel-chart/</a>
and consider pass as a value of 100, and a fail as a value of 0. You can get your averages from this.</p>
|
Android - Connecting Android Phone and Gain Span Module <p>I am connectiong a Gain Span wifi module to an android phone and I need the android phone connected as the Group Owner. Currently I am starting the group negotiations from the device that has the Gain Span module connected.</p>
<p>This works with devices such as the Nexus 5, Samsung Galaxy s2 and Samsung Galaxy s4. But when trying this with a Nexus 6p it fail all of the time. I currently thing that the issue I am having is the group owner intent on the Nexus 6p is set by default wierdly low and I need to change it before the GainSpan module initiates the group formation.</p>
<p>Problem is I can't seem to find a way of doing this so I still don't know for sure this is my issue.</p>
<p>Edit (13/10/2016):</p>
<p>Now thinking that the issue isn't with the GO intent. I am currently initiating the group negotiations from the gain span module using the commands:
at+p2ppd=mac,0
at+p2pgrpform=mac,listenChan,0,,1,0,0</p>
<p>I would prever to initiate this from the phone side as currently I have to hard code the name of the device to ensure the correct phone is connected to. This means I need to respond to a 'p2p-prov-disc-req' response from the GainSpan side, but I am unsure of how to do this. The programmers user guide says that the correct reponse is the command 'at+p2pprovok' but still im unsure of what else needs to be done.</p>
<p>Also I realise that the question has changed now but still open solution to the original problem. Also I have realiszed the s2 connects every time and it takes allot of attempts to get the s4 to connect and the nexus 6p doesn' connect.</p>
<p>Edit (14/10/2016):</p>
<p>Ok solved the 6p issue, it was because the 6p was connected to a via wifi to my office network. Problem is the other phones where connected to the same network and worked. Any Ideas why only the 6p would behave this way.</p>
| <p>Per the <a href="https://developer.android.com/reference/android/net/wifi/p2p/WifiP2pConfig.html" rel="nofollow">documentation</a>, the higher the number, the higher the odds that you will be the group owner, however this might not be 100% sure. Has the group information been persisted on the phone? Check the WiFi Direct settings on the phone and see if the group has been saved. If so, delete it and try to connect again, specifying the highest number possible.</p>
<p>You can edit the values of your Wifip2pConfig object. Including the groupOwnerIntent</p>
|
#1449 - phpMyAdmin (The user specified as a definer ('***'@'localhost') does not exist) <p>I am currently transferring all of my 'Views' from a VPS hosted with 123-reg to another VPS provided by Heart Internet.</p>
<p>Here is the View:</p>
<pre><code>CREATE ALGORITHM=UNDEFINED DEFINER=`etd`@`localhost` SQL SECURITY DEFINER VIEW `vShoppingCart` AS SELECT `VCoursesUOC`.`Distributor` AS `Distributor`,`VCoursesUOC`.`Company` AS `Company`,`VCoursesUOC`.`Title` AS `Title`,`VCoursesUOC`.`Price` AS `Price`,(`VCoursesUOC`.`Price` / 5) AS `VAT`,(`VCoursesUOC`.`Price` * 1.2) AS `WithVAT`,(sum(`VCoursesUOC`.`Price`) * 1.2) AS `Total`,count(`VCoursesUOC`.`CourseId`) AS `NoOfCourses` FROM `VCoursesUOC` WHERE (`VCoursesUOC`.`Payment` = 'Unpaid') GROUP BY `VCoursesUOC`.`Title`,`VCoursesUOC`.`Distributor`,`VCoursesUOC`.`Company`,`VCoursesUOC`.`Price`
</code></pre>
<p>Everytime I try to run this I get the following error:</p>
<pre><code>#1449 - The user specified as a definer ('etd'@'localhost') does not exist
</code></pre>
<p>I have tried to change <code>etd</code> to root and a Database username on the MySQL Database but it does not fix the error.</p>
<p>What can I try?</p>
<p>I am logged in to phpMyAdmin as the root user.</p>
| <p>The user does not exist, so you either need to create it or to use another user, which exists and has the necessary privileges.</p>
<p>etd is a user used at the original source as a definer.</p>
|
Codeigniter Foreach within an Email Message <p>When using the <code>foreach</code> within the message:</p>
<pre><code>$this->email->message('The following orders have backorders:<br><br>'.foreach ($backOrdersArray as $row2)
{
echo $OrderNumber.
'<br>Kind Regaards,<br>Merchant Lite');
};
</code></pre>
<p>Error:</p>
<pre><code>PHP Parse error: syntax error, unexpected 'foreach' (T_FOREACH)
</code></pre>
<p>The code provided originally sends the email but only with one order number (and not multiple)</p>
<p>_</p>
<p>Update with print of backorders array as requested:</p>
<pre><code>array(1) { [0]=> object(stdClass)#27 (1) { ["ORDER"]=> string(9) "SPA1" } }
array(6) { [0]=> object(stdClass)#64 (1) { ["ORDER"]=> string(11) "BHS2" } [1]=> object(stdClass)#65 (1) { ["ORDER"]=> string(11) "BHS3" } [2]=> object(stdClass)#66 (1) { ["ORDER"]=> string(11) "BHS4" } [3]=> object(stdClass)#67 (1) { ["ORDER"]=> string(11) "BHS5" } [4]=> object(stdClass)#68 (1) { ["ORDER"]=> string(11) "BHS6" } [5]=> object(stdClass)#69 (1) { ["ORDER"]=> string(11) "BHS7" } }
array(2) { [0]=> object(stdClass)#71 (1) { ["ORDER"]=> string(9) "10G1" } [1]=> object(stdClass)#72 (1) { ["ORDER"]=> string(9) "10G2" } }
</code></pre>
<p>These are generated within a <code>foreach</code> (To get the back orders for each customer)</p>
<p>-</p>
<p>I'm getting some problems trying to get this working. Is there anyway to get a <code>foreach</code> to loop through a list of numbers and print them in the message?</p>
<p>For example, I have a list of order numbers from a database <code>query</code>. I want to show these in the <code>message</code> of the email. I have tried to put the <code>foreach</code> within the message, but that results in an error message.</p>
<p>This is my current code. I have also tried the <code>foreach</code> within the message with no success:</p>
<pre><code>$this->load->library('email');
$this->email->from($CustomersEmail);
$this->email->to($NoReply);
$this->email->subject('Back Orders');
foreach ($backOrdersArray as $row2)
{
$OrderNumber = $row2->ORDER;
echo $OrderNumber;
echo '<br>';
$this->email->message('The following orders have backorders:<br><br>'.$OrderNumber.'.);
};
$this->email->send();
</code></pre>
<p>Any help would be great.</p>
| <p>Try this</p>
<pre><code>$this->load->library('email');
$this->email->from($CustomersEmail);
$this->email->to($NoReply);
$this->email->subject('Back Orders');
$msg = "The following orders have backorders:<br><br>";
foreach ($backOrdersArray as $row2)
{
$OrderNumber = $row2->ORDER;
$msg .='<br>';
$msg .= $OrderNumber;
};
$this->email->message($msg);
$this->email->send();
</code></pre>
|
Sprite Kit Modifying Attribute of a Child SKShapeNode Does Not Work <p>I have a class named <strong>Node</strong>,</p>
<p><strong>Node</strong> is a subclass of <strong>SKNode</strong>,</p>
<p>I have created and added a <strong>SKShapeNode</strong> object as a child in the <em>init</em> method of the <strong>Node</strong> object,</p>
<p>But when i try to modify this child object after adding it as a child, nothing happens.</p>
<pre><code>@interface Node ()
@property (nonatomic, strong) SKShapeNode *circle;
@end
@implementation Node
- (id)initWithRadius:(float)radius{
if (self = [super init]) {
_circle = [SKShapeNode shapeNodeWithCircleOfRadius:radius];
_circle.fillColor = [UIColor whiteColor];
_circle.name = @"c";
[self addChild:_circle];
}
return self;
}
//1st type of handling child object
- (void)setHighlighted{
NSLog(@"Called");
SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"/c"];
circ.fillColor = [SKColor redColor];
}
</code></pre>
<p>I also tried changing attribute of the property directly</p>
<pre><code>- (void)setHighlighted{
_circle.fillColor = [SKColor redColor];
}
</code></pre>
<p>The <em>setHighlighted</em> method is being called for sure.</p>
<p>I even tried [_circle removeFromParent] and set position, alpha, isHidden attributes but nothing happens!!</p>
<p>What is the problem here?</p>
<p>Thanks</p>
<p><strong>EDIT:</strong></p>
<p><strong>There is no problem with the code above!</strong></p>
<p>Sorry the problem was:
I have <strong>NSArray *nodes</strong>
I was populating nodes and as they are being created I stored them in a dummy <strong>NSMutableArray *mutableNodesArray</strong> at the same time I was adding them as a child to the scene;
and after the loop finished, I <strong>"copied"</strong> objects from the <strong>mutableNodesArray</strong> to the <strong>nodesArray</strong>,</p>
<p>so when i was trying to do operations on a Node object stored inside the nodesArray, methods were being called but these methods did not belong to the Node objects added as a child...</p>
<p>My mistake...</p>
| <p>I suppose your problem is in the line:</p>
<pre><code>SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"/c"];
</code></pre>
<p>that could be:</p>
<pre><code>SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"//c"];
</code></pre>
<p>Differences according to <a href="https://developer.apple.com/reference/spritekit/sknode#//apple_ref/doc/uid/TP40013023-CH1-SW74" rel="nofollow">API</a> reference:</p>
<p><strong>/</strong> :</p>
<blockquote>
<p>When placed at the start of the search string, this indicates that
the search should be performed on the treeâs root node. When placed
anywhere but the start of the search string, this indicates that the
search should move to the nodeâs children. </p>
</blockquote>
<p><strong>//</strong> :</p>
<blockquote>
<p>When placed at the start
of the search string, this specifies that the search should begin at
the root node and be performed recursively across the entire node
tree. Otherwise, it performs a recursive search from its current
position.</p>
</blockquote>
<p>You could try to put also a breakpoint to the line below and check to the debug console the circ properties with <code>po circ.debugDescription</code> :</p>
<p>(breakpoint to the line:)
-> <code>circ.fillColor = [SKColor redColor];</code></p>
<p>You could try also to use a <code>customActionWithDuration</code>:</p>
<pre><code>SKAction* circleColor = [SKAction customActionWithDuration:0.5f actionBlock:^(SKNode *node, CGFloat elapsedTime)
{
circ.fillColor = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f];
NSLog(@"changed to red");
}];
[circ runAction:circleColor];
</code></pre>
|
Lotus Notes Attachments export <p>Did anyone find a solution how to export attachments from the .NSF file?
And how to export Lotus Notes Forms into PDF files?</p>
<p>Able to export Body in a Rich Text format into separate MS Word files.
But cannot get Attachments from the database body. </p>
<p>Tried Kernel for Lotus Notes to PDF but it works for mail-in databases only. </p>
| <p>Below, there's an agent code taken from official domino designer documentation. It iterates over all documents in a mail database and processes every document. In every document it gets a rich text item object from the field <code>Body</code>:</p>
<pre><code>RichTextItem body = (RichTextItem)doc.getFirstItem("Body");
</code></pre>
<p>Then it gets a list of embedded objects from this rich text item object via:</p>
<pre><code>Vector v = body.getEmbeddedObjects();
</code></pre>
<p>And then it iterates over this list to determine file attachments via:</p>
<pre><code>if (eo.getType() == EmbeddedObject.EMBED_ATTACHMENT) { ... }
</code></pre>
<p>As an attachment has been found, it is being extracted to the <code>c:\\extracts\\</code> folder, preserving the attachment file name.</p>
<p>If you store attachments in a rich text field with different name (not <code>Body</code>), just modify the following code to reflect your requirements.</p>
<p>The agent code:</p>
<pre><code>import lotus.domino.*;
import java.util.Vector;
import java.util.Enumeration;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
DocumentCollection dc = db.getAllDocuments();
Document doc = dc.getFirstDocument();
boolean saveFlag = false;
while (doc != null) {
RichTextItem body =
(RichTextItem)doc.getFirstItem("Body");
System.out.println(doc.getItemValueString("Subject"));
Vector v = body.getEmbeddedObjects();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
EmbeddedObject eo = (EmbeddedObject)e.nextElement();
if (eo.getType() == EmbeddedObject.EMBED_ATTACHMENT) {
eo.extractFile("c:\\extracts\\" + eo.getSource());
saveFlag = true;
}
}
if (saveFlag) {
doc.save(true, true);
saveFlag = false;
}
doc = dc.getNextDocument();
}
} catch(NotesException e) {
System.out.println(e.id + " " + e.text);
e.printStackTrace();
}
}
}
</code></pre>
<p>Also check <a href="http://stackoverflow.com/questions/25543025/java-lotus-notes-get-attachment-name-from-item-instance/25543294#25543294">my answer to a similar question here</a></p>
|
How can I make child waiting parents to return (not exit) and then suicide? <p>I want to write such a function, which is called from other place. Which use fork to make a child and wait main process to return to its main function. I tried this method and also tried to set one flag to tell child parents return. But they are all not correct, and I have know the reason. I just want to know how can I make this point? Thanks!</p>
<pre><code>void otherplacecall(){
fpid=fork();
if (fpid == 0) {
printf("i am the child process, my process id is %d\n",getpid());
while(getppid()!=1){printf("waiting\n");sleep(1);}
if(getppid()==1){
printf("father die!\n");
printf("I am dying\n");
exit(0);
}
}
else {
printf("in the parents!, my process id is%d\n",getpid());
printf("my son take care of yourself\n");
return 1;
}
}
</code></pre>
| <p>You say you want the child to</p>
<blockquote>
<p>wait main process to return to its main function</p>
</blockquote>
<p>. That's a bit hard to follow, but I think you mean that you want the child to wait until its <em>parent</em> process returns to the <em>caller</em> of the function in which the <code>fork()</code> was performed. It's unclear whether the caller is expected to be that process's <code>main()</code> function, but that doesn't actually make any difference.</p>
<p>However, no function can exert direct control over what happens when it returns. The best it can do is perform some action immediately before it returns.</p>
<p>Moreover, since the function you present is not <code>main()</code>, there is no reason to suppose that the parent process terminates when it returns from that function. Until it does terminate, the child process will remain its child, and therefore will not observe itself being inherited by process 1.</p>
<p>Since the program in fact is not working as you expect, I suppose that the parent process indeed is not terminating, so you need a different approach. Specifically, you need some form or other of inter-process communication (IPC). There are several flavors to choose from, and as a bonus, many of them do not require the child to busy-wait. Among the more likely options are</p>
<ul>
<li>a process-shared mutex or semaphore</li>
<li>a signal</li>
<li>a pipe</li>
</ul>
<p>Of those, I'd recommend the last. It could look like this:</p>
<pre><code>void otherplacecall(){
int pfd[2];
pid_t pid;
char c;
if (pipe(pfd)) {
// ... handle error in pipe() ...
return;
}
switch(pid = fork()) {
case -1:
// (parent) ... handle error in fork() ...
break;
case 0:
// child
printf("child: my process id is %d\n", (int) pid);
if (close(pfd[1])) {
// ... handle error in close() ...
_Exit(1);
}
if (read(pfd[0], &c, 1) < 0) {
// ... handle error in read() ...
}
puts("child: received the signal to proceed");
puts("child: I terminating");
_Exit(0);
default:
// parent
close(pfd[0]);
puts("parent: my son, take care of yourself");
close(pfd[1]); // this will cause the child's read() to return
}
}
</code></pre>
<p>Among the characteristics of this approach is that if the parent <em>does</em> terminate then its copies of the pipe ends will be closed, even if it does not close them explicitly, so the child will then proceed. That won't happen under some other circumstances, such as if the child is awaiting a signal, and the parent dies before sending it.</p>
|
Datatables columns don't get fit width when it first loads? <p>I wonder why my datatables don't get fit width columns when it first load, but when I do any change like ordered, sreach, or select, it gets fit columns width. here's my datatables when it first load (<a href="https://postimg.org/image/vw4lvp3db/" rel="nofollow">https://postimg.org/image/vw4lvp3db/</a>)
here my datatables when I select any data from any column (<a href="https://postimg.org/image/k0sagi7vl/" rel="nofollow">https://postimg.org/image/k0sagi7vl/</a>)
Here's my HTML table file </p>
<pre><code><table id="laporan_temuan" class="table table-hover table-bordered">
<thead>
<td style="">No</td>
<td style="">No BA</td>
<td style="">Tanggal ditemukan</td>
<td style="">Penyelia</td>
<td style="">Manager</td>
<td style="">Operator</td>
<td style="">Saksi</td>
<td style="">Cabang</td>
<td style="">Teler</td>
<td style="">Jam</td>
<td style="">Tanggal Ban-banan</td>
<td style="">Temuan</td>
<td style="">Denom</td>
<td style="">Jumlah</td>
<td style="">No Seri</td>
<td style="">Total</td>
<td style="">AKSI</td>
</thead>
<tfoot>
<td style="">No</td>
<td style="">No BA</td>
<td style="">Tanggal ditemukan</td>
<td style="">Penyelia</td>
<td style="">Manager</td>
<td style="">Operator</td>
<td style="">Saksi</td>
<td style="">Cabang</td>
<td style="">Teler</td>
<td style="">Jam</td>
<td style="">Tanggal Ban-banan</td>
<td style="">Temuan</td>
<td style="">Denom</td>
<td style="">Jumlah</td>
<td style="">No Seri</td>
<td style="">Total</td>
<td >AKSI</td>
</tfoot>
<tbody>
</tbody>
</table>
</code></pre>
<p>and here is my js file </p>
<pre><code>$("#laporan_temuan").DataTable({
//"aLengthMenu":[[5,15,30,-1],[5,15,30,"All"]],
"pageLength":5,
"columnDefs": [
{ "width": "4%", "targets": 0 },
{ "width": "10%", "targets": 1 },
{ "width": "10.5%", "targets": 2 },
{ "width": "11.8%", "targets": 3 },
{ "width": "12%", "targets": 4 },
{ "width": "13.8%", "targets": 5 },
{ "width": "13.8%", "targets": 6 },
{ "width": "15%", "targets": 8 },
{ "width": "20%", "targets": 10 },
{ "width": "25%", "targets": 14 },
{ "width": "15%", "targets": 16 },
],
"lengthChange": false,
//button-button untuk export ke cetak, excel, dan pdf
dom :'Bfrtip',
buttons:[
{
extend: 'print',
className: 'btn btn-default'
},
{
extend:'excelHtml5',
className: 'btn btn-success',
text: 'EXCEL'
}
],
"ordering":true,
scrollX:true,
ajax:{
url: "{{url('laporantemuanajax')}}",
dataSrc:''
},columns:[
{data:'no'},
{data:'no_ba'},
{data:'tanggal_ditemukan'},
{data:'penyelia'},
{data:'manajer'},
{data:'operator'},
{data:'saksi'},
{data:'cabang'},
{data:'teler'},
{data:'jam'},
{data:'tanggal_banbanan'},
{data:'temuan'},
{data:'denom'},
{data:'jumlah'},
{data:'no_seri'},
{data:'total'},
{data:'aksi'},
],
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select class="form-control"><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
language:{
"search":"Goleti Data",
"zeroRecords":"Ora ana data sing pada karo sing koen maksud",
"lengthMenu":"Munculna _MENU_ data",
"info":"Munculna sing _START_ kosi _END_ sing _TOTAL_ data",
"infoFiltered":"(disaring sing _TOTAL_ kabehe data)",
"infoEmpty":"Munculna sing 0 kosi 0 sing 0 data"
}
});
</code></pre>
<p>What's worng with my datatables?</p>
| <p>Is your table visible when you first initialize the DataTable? If not, you may need to call the following as soon as it becomes visible:</p>
<pre><code>$("#laporan_temuan").DataTable().columns.adjust().draw()
</code></pre>
<p>Also, I notice that you are defining your column widths on initialization. If you want the columns to use best fit, you probably should remove the following:</p>
<pre><code>"columnDefs": [
{ "width": "4%", "targets": 0 },
{ "width": "10%", "targets": 1 },
{ "width": "10.5%", "targets": 2 },
{ "width": "11.8%", "targets": 3 },
{ "width": "12%", "targets": 4 },
{ "width": "13.8%", "targets": 5 },
{ "width": "13.8%", "targets": 6 },
{ "width": "15%", "targets": 8 },
{ "width": "20%", "targets": 10 },
{ "width": "25%", "targets": 14 },
{ "width": "15%", "targets": 16 },
],
</code></pre>
|
Need to read registry value from both 32 bit and 64 bit machine Windows machine <p>I need to read some registry values using a .cmd file. I am using the following command for that purpose.</p>
<pre><code>FOR /f "tokens=2*" %%a in ('reg query "HKLM\SOFTWARE\Looptest" /v "tscFile"') do set "TSCFile=%%b"
</code></pre>
<p>The problem is that, when I install the software on 32 bit,the path for registry is : <code>"HKLM\SOFTWARE\Looptest"</code> and when I install the software on 64 bit machine, the path becomes : <code>"HKLM\SOFTWARE\Wow6432Node\Looptest"</code></p>
<p>Is there a way to read keys without knowing the version of OS?</p>
<p>Of course I know that initially I can check for the OS version and then can write the code accordingly. But, other than that, is there any other way to do it ?</p>
<p>Thanks !</p>
| <p>Do REQ QUERY /? and notice the /reg:32 and /reg:64 switches. Then add something like this to the beginning of your bat file (before you do any reg operations) so that it works on 32 or 64 bit machines.</p>
<pre><code>set "Reg32="
set "Reg64="
if defined Programfiles(x86) set "Reg64=/reg:64" & set "Reg32=/reg:32"
</code></pre>
<p>This has the added advantage that you can specify either 32 bit or 64 bit registry area on 64 bit machines by using the appropriate Regnn variable for your registry operations. Assuming you want the 64 bit registry area when you are on a 64 bit machine your example would then become:</p>
<pre><code>FOR /f "tokens=2*" %%a in ('reg query "HKLM\SOFTWARE\Looptest" /v "tscFile" %Reg64%') do set "TSCFile=%%b"
</code></pre>
<p>And since %Reg64% is not defined on a 32 bit machine, you code will work correctly there too.</p>
|
AFNetworking 3.0 The data couldnât be read because it isnât in the correct format <p>There are other questions with similar titles but none of them helped me. I've to send a <code>PUT</code> request to server in order to change the status of appointment so I've made this method <code>-(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID</code> In which I'm setting the URL and Parameters as</p>
<pre><code>NSString *string = [NSString stringWithFormat:@"%@/API/Appointments/3",BaseURLString];
NSDictionary *para = @{
@"AppointmentStatusId":statusID,
@"ID":appointmentID
};
</code></pre>
<p>Then I've made URL request as</p>
<pre><code>AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:string parameters:para error:nil];
</code></pre>
<p>After that I'm setting the header for an authorization token as</p>
<pre><code> NSString *token = [NSString stringWithFormat:@"Bearer %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"]];
[req setValue:token forHTTPHeaderField:@"Authorization"];
</code></pre>
<p>So finally I'm calling it as</p>
<pre><code>[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(@"Respose Object: %@",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(@"Error: %@, %@, %@", error, response, responseObject);
NSLog(@"Error: %@", error.localizedDescription);
}
}] resume];
</code></pre>
<p>Now it is successfully sending the data to the server but as a response I'm getting</p>
<blockquote>
<p>Error: The data couldnât be read because it isnât in the correct
format.</p>
</blockquote>
<p>I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.</p>
| <p>try to use below code:</p>
<pre><code>AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
</code></pre>
|
How do I use Broadcast Receiver that toasts when an SMS is received? <p>This is the <code>MainActivity.java</code>:</p>
<pre><code>package tagit.aj.com.broadcastreceiverforsms;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
</code></pre>
<p>This the <code>MyReceiver</code> class which includes the broadcast receiver's <code>onReceive</code> method. One of the methods used here is "deprecated" but I assume it does not create any problems in testing. </p>
<pre><code>package tagit.aj.com.broadcastreceiverforsms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"IncomingSms",Toast.LENGTH_SHORT).show();
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[i]);
String phoneNumber = messages.getDisplayOriginatingAddress();
String phone = phoneNumber;
String stringMessage = messages.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG;
Log.i("Broadcasting", "Number" + phone + "Message" + stringMessage);
Toast toast = Toast.makeText(context, "senderNum: " + phone + ", message: " + stringMessage, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
</code></pre>
<p>The XML layout is:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="tagit.aj.com.broadcastreceiverforsms.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
</code></pre>
<p>And the AndroidManifest file is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tagit.aj.com.broadcastreceiverforsms">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
</code></pre>
<p>Please provide me with why this problem is occurring, and a solution (if any). And I'm running this app on Android KitKat.</p>
| <p>I think his problem is that his code is not working, due to changes made in SMS Provider in Android 4.4</p>
<p><a href="https://developer.android.com/about/versions/android-4.4.html#SMS" rel="nofollow">SMS Provider in Android 4.4</a></p>
|
How to read from text file in Map specific data? <p>I need the read from the data file of the form:</p>
<p>1,14.23,1.71,2.43,15.6,127,2.8,3.06,.28,2.29,5.64,1.04,3.92,1065
2,12.72,1.81,2.2,18.8,86,2.2,2.53,.26,1.77,3.9,1.16,3.14,714
2,12.08,1.13,2.51,24,78,2,1.58,.4,1.4,2.2,1.31,2.72,630
....................................
3,13.11,1.9,2.75,25.5,116,2.2,1.28,.26,1.56,7.1,.61,1.33,425
3,13.23,3.3,2.28,18.5,98,1.8,.83,.61,1.87,10.52,.56,1.51,675
................and so on</p>
<p>Where first symbol - the key, the rest are values.</p>
<p>I try to do it this way</p>
<pre><code> Map<String, String> map = new HashMap<String, String>();
BufferedReader in = new BufferedReader(new FileReader("wine.data.txt"));
String line = "";
while ((line = in.readLine()) != null) {
String parts[] = line.split(",");
for(int i = 1; i < parts.length; i++)
map.put(parts[0], parts[i]);
System.out.println(map.toString());
}
in.close();
</code></pre>
<p>But I see only last number of each line.
How to fix it?</p>
| <p>Everytime <code>put</code> is called, the value for the speficied key is being replaced.</p>
<p>You want to store the result in a <code>Map<String, List<String>></code>:</p>
<pre><code>String parts[] = line.split(",");
List<String> values = map.get(parts[0]);
if(values == null) { // first time this key is found -> create new list
values = new ArrayList<>();
map.put(parts[0], values);
}
for(int i = 1; i < parts.length; i++) {
values.add(parts[i]);
}
</code></pre>
|
Line break or Carriage return in a Delimited Field in Sql <p>I have an email column that stores a minimum of more than 10 emails in a row. Now, I want to write a query that puts each email on a separate line, e.g:</p>
<pre><code> hay@line.com
u@y.com
live.gmail.com
</code></pre>
<p>How do write this?</p>
| <p>If you mean rows of data... Any Parse/Split function will do if you don't have 2016. Otherwise the REPLACE() as JohnHC mentioned</p>
<pre><code>Declare @YourTable table (ID int,Emails varchar(max))
Insert Into @YourTable values
(1,'hay@line.com,u@y.com,live.gmail.com')
Select A.ID
,EMail=B.RetVal
From @YourTable A
Cross Apply [dbo].[udf-Str-Parse](A.EMails,',') B
</code></pre>
<p>Returns</p>
<pre><code>ID EMail
1 hay@line.com
1 u@y.com
1 live.gmail.com
</code></pre>
<p>Or Simply</p>
<pre><code>Select * from [dbo].[udf-Str-Parse]('hay@line.com,u@y.com,live.gmail.com',',')
</code></pre>
<p>Returns</p>
<pre><code>RetSeq RetVal
1 hay@line.com
2 u@y.com
3 live.gmail.com
</code></pre>
<p>The Function if Needed</p>
<pre><code>CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
</code></pre>
|
Converting a string into array in phpGrid for inserting into postgresql <p>I am trying to insert a string into an integer array using phpGrid with a PostgreSQL database. I had to convert the array to a string to remove the brackets when displaying data inside the grid for viewing, but when I try to convert the string back into an array upon adding a field, it is not converting to the format {1,2,3,4}. I'm using the string_to_array function that PostgreSQL offers to do so. Here is the code I am using:</p>
<pre><code>$dg = new C_DataGrid("SELECT array_to_string(field, ', ') as field_to_string FROM tblname");
</code></pre>
<p>This works as expected (removes the { } from the data being displayed) but when I try to insert, this query looks like this:</p>
<pre><code>INSERT INTO tblname (field_to_string) VALUES ('1,2,3,4');
</code></pre>
<p>and this is what I am trying to insert (convert to array)</p>
<pre><code>$arrFields['field_to_string'] = "string_to_array('" . $arrFields['field_to_string'] . "', ',')";
$sqlCrud = $db->db->GetInsertSQL($rs, $arrFields, get_magic_quotes_gpc(), true);
</code></pre>
<p>Any help would be appreciated. </p>
<p>Thanks.</p>
| <p>Can you echo sqlCrud and find out the SQL Insert statement by setting its <a href="http://phpgrid.com/documentation/debug/" rel="nofollow">DEBUG</a> set to true? It's likely the Insert statement has an error during conversion. </p>
<p>Your PostgreSql should be something similar to the following:</p>
<pre><code>INSERT INTO tblname(field_to_string) VALUES ('{1,2,3,4}'::varchar[])
</code></pre>
<p>You can check out PostGreSql with array to string conversion examples here: <a href="http://www.postgresonline.com/journal/archives/228-PostgreSQL-Array-The-ANY-and-Contains-trick.html" rel="nofollow">http://www.postgresonline.com/journal/archives/228-PostgreSQL-Array-The-ANY-and-Contains-trick.html</a></p>
|
Post sign & to another php file <p>How do i post a string with sign '&' to a php file.</p>
<p>I have a jscript:</p>
<pre><code>function saveRow(oTable, nRow) {
var jqInputs = $('input', nRow);
oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 4, false);
oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 5, false);
oTable.fnDraw();
var val1 = jqInputs[0].value;
var val2 = jqInputs[1].value;
var val3 = jqInputs[2].value;
var val4 = jqInputs[3].value;
var dataString = 'pairchannels=1' + '&eventname=' + val1 + '&datetime=' + val2 + '&pairedchannel=' + val3 + '&realchannel=' + val4;
if (val1 == '' || val2 == '' || val3 == '' || val4 == '') {
alert(jqInputs[1].value);
} else {
alert(val1);
$.ajax({
type: "POST",
url: "process.php?",
data: dataString,
cache: false,
success: function(result) {
alert(dataString);
}
});
}
return false;
}
</code></pre>
<p>Which sends a POST to process.php:</p>
<pre><code> ...
else if(isset($_POST['pairchannels'])){
$this->procPairChannels();
}
...
function procPairChannels(){
global $session, $form;
/* Account edit attempt */
$retval = $session->procPairChannels($_POST['eventname'], $_POST['datetime'], $_POST['pairedchannel'], $_POST['realchannel']);
}
</code></pre>
<p>But instead of whole string in $_POST['eventname'] which is "Bosnia & Herzegovina" php splits the string at "&". This is the first time error like this occurred because i have never had a "&" in any of my strings until now.</p>
<p>What should i do to handle this kind of strings?</p>
| <p>You need to encode the values you are sending in your datastring correctly so that they won't be interpreted as special characters in a url (a <code>&</code> separates key-value pairs...):</p>
<p>The easiest way to do that, is to let jQuery handle that by sending an object instead of a string:</p>
<pre><code>// Maybe a name change to dataObject...
var dataString = {
pairchannels: 1,
eventname: val1,
// etc.
};
</code></pre>
<p>If you want to build the query-string yourself you need to use <a href="https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow"><code>encodeURIComponent()</code></a> on each individual value.</p>
|
UWP and InkToolbar: how to draw basic shapes <p>I work on a UWP app where the user must be able to take a photo from the camera, and add details by drawing some shapes. I think the simplest way to do this is using the <strong>InkToolbar</strong>. So I've donwloaded the official sample: <a href="https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/SimpleInk" rel="nofollow">SimpleInk</a></p>
<p>But I don't see how to solve some of my needs:</p>
<ul>
<li>add a background image to the InkCanvas: I would like get a <strong>BitmapImage</strong> containing the original photo and the items drawed by the user</li>
</ul>
<p><strong><em>=> is it possible to do this properly? or do I need to superpose the Image and the InkCanvas in the Grid and take a screenshot?</em></strong></p>
<ul>
<li>draw basic shapes like circles or rectangles: all the samples are based on hand drawing with different kinds of pencils</li>
</ul>
<p><strong><em>=> is there a way to draw shapes like circles or rectangles through this control? or what is the better way for allowing user to "draw" shapes easily?</em></strong> </p>
<p>I also looked at the Win2D samples <a href="https://github.com/Microsoft/Win2D-samples" rel="nofollow">Win2D-samples</a>, but I didn't found a similar case.</p>
<p>Thanks in advance for your feedbacks!</p>
| <blockquote>
<p>add a background image to the InkCanvas: I would like get a BitmapImage containing the original photo and the items drawed by the user</p>
</blockquote>
<p>The <code>InkCanvas</code> doesn't contain a <code>background</code> property directly. You can create an <code>InkCanvas</code> overlays a background image by using an <code>Image</code> control like the <a href="https://msdn.microsoft.com/windows/uwp/input-and-devices/pen-and-stylus-interactions#basic-inking-with-inkcanvas" rel="nofollow">Basic inking with InkCanvas</a> sample shows.</p>
<p>But if you need to get a new BitmapImage from original image with <code>InkCanvas</code> drawing you need to use the <a href="https://www.nuget.org/packages/Win2D.uwp" rel="nofollow">Win2D</a> library. For more details and a completed demo please reference <a href="http://stackoverflow.com/questions/37179815/displaying-a-background-image-on-a-uwp-ink-canvas">this thread</a>.</p>
<blockquote>
<p>draw basic shapes like circles or rectangles: all the samples are based on hand drawing with different kinds of pencils</p>
</blockquote>
<p>For this, the <a href="https://github.com/Microsoft/Win2D-Samples/tree/master/SimpleSample/UAP" rel="nofollow">UAP</a> sample of <a href="https://github.com/Microsoft/Win2D-Samples/tree/master/SimpleSample/UAP" rel="nofollow"><code>Win2D-samples</code></a> you mentioned above provided a demo for drawing a circle you can reference(same with <code>rectangles</code> like follows). </p>
<pre><code>args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3);
args.DrawingSession.DrawRectangle(155, 115, 80, 30, Colors.Black);
</code></pre>
<p>The official <a href="https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/ComplexInk" rel="nofollow">Complex inking sample</a> also provide the <code>Insert a shape</code> feature you can test and reference.</p>
|
C# unit test boolean <p>I need help on writing a unit test for this</p>
<pre><code>Public static Boolean InList(byte value, Type t)
{
if (!Enum.IsDefined(t, value))
{
return false;
}
return true;
</code></pre>
<p>This is what i written so far but it keep given me error "out of bound"</p>
<pre><code> [TestMethod()]
Public void InListTest()
{
Assert.IsTrue(ValidationUI.InList(1, Type.EmptyTypes[0]));
}
</code></pre>
<p>I don't expect what I wrote on unit test is what the test is asking for, i need some guidance. Thanks in advance </p>
| <p>This will test your method:</p>
<pre><code>public enum TestEnum : byte {
One = 1,
Two = 2
}
[TestMethod()]
Public void InListTest()
{
Assert.IsTrue(ValidationUI.InList(1, typeof(TestEnum));
Assert.IsFalse(ValidationUI.InList(100, typeof(TestEnum));
}
</code></pre>
|
ASP.NET MVC - prevent submit of invalid form using jQuery unobtrusive validation <p>I have an ASP.NET project that automatically wires up client side validation using <a href="https://jqueryvalidation.org/" rel="nofollow">jQuery.Validate</a> and the <a href="https://github.com/aspnet/jquery-validation-unobtrusive" rel="nofollow">unobtrusive wrapper</a> built by ASP.NET.</p>
<p>a) I definitely have the appropriate libraries: <a href="https://cdnjs.com/libraries/jquery/1.12.4" rel="nofollow">jquery.js</a>, <a href="https://cdnjs.com/libraries/jquery-validate/1.9.0" rel="nofollow">jquery.validate.js</a>, & <a href="https://cdnjs.com/libraries/jquery-validation-unobtrusive" rel="nofollow">jquery.validate.unobtrusive.js</a></p>
<p>b) And the MVC rendering engine is definitely turned on (<code>ClientValidationEnabled</code> & <code>UnobtrusiveJavaScriptEnabled</code> in the <code>appSettings</code> section of the web.config)</p>
<p>Here's a trivial example where things are broken:</p>
<p><strong>Model</strong>:</p>
<pre class="lang-cs prettyprint-override"><code>public class Person
{
[Required]
public string Name { get; set; }
}
</code></pre>
<p><strong>Controller</strong>:</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult Edit()
{
Person p = new Person();
return View(p);
}
</code></pre>
<p><strong>View</strong>:</p>
<pre class="lang-cs prettyprint-override"><code>@model validation.Models.Person
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
}
</code></pre>
<p>This generates the following client side markup:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<input type="submit" value="Save" />
</form></code></pre>
</div>
</div>
</p>
<p>When run it will perform the client side validation, noting that some form elements are invalid, but then <em>also</em> post back to the server. </p>
<p>Why is it not preventing postback on a form with an invalid state?</p>
| <h2>The Problem</h2>
<p>It turns out this happens when you don't include a <code>@Html.ValidationMessageFor</code> placeholder for a given form element.</p>
<p>Here's a deeper dive into where the problem occurs:</p>
<p>When a form submits, <code>jquery.validate.js</code> will call the following methods:</p>
<pre class="lang-js prettyprint-override"><code>validate: function( options ) {
form: function() {
showErrors: function(errors) {
defaultShowErrors: function() {
showLabel: function(element, message) {
this.settings.errorPlacement(label, $(element) )
</code></pre>
<p>Where <code>errorPlacement</code> will call this method in <code>jquery.validate.unobtrusive.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>function onError(error, inputElement) {
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
</code></pre>
<p>When we don't add a placeholder for the validation message, <code>$(this).find(...)</code> won't find anything.</p>
<p>Meaning <code>container.attr("data-valmsg-replace")</code> will return <code>undefined</code></p>
<p>This poses a problem is when we try to call <code>$.parseJSON</code> on an undefined value. If an error is thrown (and not caught), JavaScript will stop dead in its tracks and never reach the final line of code in the original method (<code>return false</code>) which prevents the form from submitting.</p>
<h2>The Solution</h2>
<h3>Upgrade jQuery Validate Unobtrusive</h3>
<p><a href="https://www.asp.net/ajax/cdn" rel="nofollow">Newer versions of jQuery Validate</a> handle this better and check for nulls before passing them to <code>$.parseJSON</code></p>
<pre class="lang-js prettyprint-override"><code>function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
</code></pre>
<h3>Add ValidationMessageFor</h3>
<p>To address the core problem, for every input on your form, make sure to include:</p>
<pre class="lang-cs prettyprint-override"><code>@Html.ValidationMessageFor(model => model.Name)
</code></pre>
<p>Which will render the following client side markup</p>
<pre class="lang-html prettyprint-override"><code><span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<input type="submit" value="Save" />
</form></code></pre>
</div>
</div>
</p>
|
Laravel blade template showing html even when the condition is false <p>I have setup if conditions in my blade template with an if condition that consists of an or operator, but it is showing html even when the condition is false. Not sure how to fix that? </p>
<pre><code>@if(count($images) || count($videos) > 1)
<div class="orbit" role="region" data-orbit id="slider">
<ul class="orbit-container">
<button class="orbit-previous"><span class="show-for-sr">Previous Slide</span>&#9664;&#xFE0E;</button>
<button class="orbit-next"><span class="show-for-sr">Next Slide</span>&#9654;&#xFE0E;</button>
@if(count($images) > 1)
@foreach($images as $image)
<li class="orbit-slide">
<img src="http://coop.app/imagecache/cover/{{ $image }}" class="header-img">
</li>
@endforeach
@endif
@if(count($videos) > 1)
@foreach($videos as $video)
<li class="orbit-slide">
<div class="flex-video">
<iframe src="{{ $video }}"></iframe>
</div>
</li>
@endforeach
@endif
</ul>
</div>
@endif
</code></pre>
| <p>You write or (||) condition in if statement that means if one condition (count($images)) or count($videos) is true then if statement will work.
If two condition is false then your if statement will not work</p>
|
Averaging two time points <p>I have a time series spanning two years. I need to average the two values for each month to create a new value to assign to each month. Is there a way to do so in R? </p>
<p>Thanks</p>
| <p>Without a data set it is hard, but here is the general framework:</p>
<pre><code>library(dplyr)
library(lubridate)
data %>% group_by(year(date), month(date)) %>% summarize(value = mean(value))
</code></pre>
|
Column appended in a pandas dataframe malfunctions <p>I have a dataframe named df1</p>
<pre><code> df1.columns
Out[55]: Index(['TowerLon', 'TowerLat'], dtype='object')
df1.shape
Out[56]: (1141, 2)
df1.head(3)
Out[57]:
TowerLon TowerLat
0 -96.709417 32.731611
1 -96.709500 32.731722
2 -96.910389 32.899944
</code></pre>
<p>I also have an np.ndarray named labels:</p>
<pre><code> type(labels)
Out[62]: numpy.ndarray
labels
Out[63]: array([1, 1, 0, ..., 0, 0, 1])
</code></pre>
<p>I appended the np.ndarray labels to the dataframe df1 using the following command:</p>
<pre><code> df1["labels"] = labels.tolist()
</code></pre>
<p>The operation was seemingly successful:</p>
<pre><code> df1.shape
Out[68]: (1141, 3)
df1.dtypes
Out[69]:
TowerLon float64
TowerLat float64
labels int64
dtype: object
df1.head(3)
Out[70]:
TowerLon TowerLat labels
0 -96.709417 32.731611 1
1 -96.709500 32.731722 1
2 -96.910389 32.899944 0
</code></pre>
<p>However when I try to list the values of the new column I get an error message:</p>
<pre><code> df1.labels
Traceback (most recent call last):
File "<ipython-input-71-6afd8264be10>", line 1, in <module>
df1.labels
File "C:\Users\Alexandros_7\Anaconda3\lib\site- packages\pandas\core\generic.py", line 2668, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'labels'
</code></pre>
<p>I get a similar error message when I try to use labels to form a scatter plot:</p>
<pre><code> plt.scatter(df1.TowerLat, df1.TowerLon, c=df1.labels)
Traceback (most recent call last):
File "<ipython-input-73-b71c79011e38>", line 1, in <module>
plt.scatter(df1.TowerLat, df1.TowerLon, c=df1.labels)
File "C:\Users\Alexandros_7\Anaconda3\lib\site - packages\pandas\core\generic.py", line 2668, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'labels'
</code></pre>
<p>Could you help me? Thank you!</p>
| <p>The <code>AttributeError</code> occurs due to the fact that <code>labels</code> is not part of the original <code>DataFrame</code>. You can however access the data by using the following method:</p>
<pre><code>df1['labels']
</code></pre>
<p>This will give you the following output:</p>
<pre><code>0 1
1 1
2 0
Name: labels, dtype: int64
</code></pre>
<p>for your plotting error also replace <code>df1.labels</code> with the method suggested above as follows:</p>
<pre><code>plt.scatter(df1.TowerLat, df1.TowerLon, c=df1['labels'])
</code></pre>
<p>As for the error with the <code>groupby</code> method change it to:</p>
<pre><code>bylevel=df1.groupby(df1["labels"])
</code></pre>
<p>as <code>levels</code> is not part of the <code>DataFrame</code></p>
|
Calculate moving average in numpy array with NaNs <p>I am trying to calculate the moving average in a large numpy array that contains NaNs. Currently I am using:</p>
<pre><code>import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
</code></pre>
<p>When calculating with a masked array:</p>
<pre><code>x = np.array([1.,3,np.nan,7,8,1,2,4,np.nan,np.nan,4,4,np.nan,1,3,6,3])
mx = np.ma.masked_array(x,np.isnan(x))
y = moving_average(mx).filled(np.nan)
print y
>>> array([3.8,3.8,3.6,nan,nan,nan,2,2.4,nan,nan,nan,2.8,2.6])
</code></pre>
<p>The result I am looking for (below) should ideally have NaNs only in the place where the original array, x, had NaNs and the averaging should be done over the number of non-NaN elements in the grouping (I need some way to change the size of n in the function.)</p>
<pre><code>y = array([4.75,4.75,nan,4.4,3.75,2.33,3.33,4,nan,nan,3,3.5,nan,3.25,4,4.5,3])
</code></pre>
<p>I could loop over the entire array and check index by index but the array I am using is very large and that would take a long time. Is there a numpythonic way to do this? </p>
| <p>I'll just add to the great answers before that you could still use cumsum to achieve this:</p>
<pre><code>import numpy as np
def moving_average(a, n=5):
ret = np.cumsum(a.filled(0))
ret[n:] = ret[n:] - ret[:-n]
counts = np.cumsum(~a.mask)
counts[n:] = counts[n:] - counts[:-n]
ret[~a.mask] /= counts[~a.mask]
ret[a.mask] = np.nan
return ret
x = np.array([1.,3,np.nan,7,8,1,2,4,np.nan,np.nan,4,4,np.nan,1,3,6,3])
mx = np.ma.masked_array(x,np.isnan(x))
y = moving_average(mx)
</code></pre>
|
Android game Multi Screen Resolution <p>If I design a game for 3:2 screen ratio, and another device has 4:3 or 16:9, how can I make the game look the same? I can scale the resolution for same aspect ratio, but when it's different what can I do?</p>
| <p>The best approach is to design your game with biggest screen possible (3:2 i think), and then check it with the smallest screen(16:9 i think). if your game is portrait then scale when height changed and if your game is landscape then scale your game when width changes.</p>
|
Node.js - read and download all files in directory from server and save locally <p>I have a Node Webkit Desktop App and need to download files from the server and save locally for when users are offline. I can download and save a file when I know what the file name is, but how do I read the contents of a directory on the server so I can download each file?</p>
<pre><code>function cacheFiles(filelink, filepath, cb) {
var path_array = filelink.split("/");
var foldername = path_array[path_array.length - 2]
//create new folder for locally html files
var newdir = filepath + '/' + foldername;
if (fs.existsSync(newdir)){
alert('file already exists, cannot cache this file.');
} else {
fs.mkdirSync(newdir);
}
//download and save index.html - THIS WORKS
var indexfile = fs.createWriteStream(newdir+'/index.html');
var request = http.get(filelink, function(response) {
response.pipe(indexfile);
indexfile.on('finish', function() {
indexfile.close(cb);
});
});
//read contents of data folder - THIS DOESN'T WORK
var datafolder = filelink.replace('index.html','');
fs.readdir( datafolder, function (err, datafiles) {
if (!err) {
console.log(datafiles);
}else{
console.log(err) ;
}
});
</code></pre>
<p>}</p>
<p>The error I get in my console is: </p>
<blockquote>
<p>"ENOENT: no such file or directory, scandir
'C:\Users\my.name\desktopApp\app\http:\www.mysite.co.uk\wp-content\uploads\wifi_corp2\data'"</p>
</blockquote>
<p>The above is looking for the files locally and not at the online link I supplied in <strong><em>filelink</em></strong> eg.
<a href="http://www.mysite.co.uk/wp-content/uploads/wifi_corp2/data">http://www.mysite.co.uk/wp-content/uploads/wifi_corp2/data</a></p>
| <p>The following code doesn't read a remote file system, it's used for reading files on your local hard drive.</p>
<pre><code>import fs from 'fs'
import path from 'path'
fs.readdir(path.resolve(__dirname, '..', 'public'), 'utf8', (err, files) => {
files.forEach((file) => console.info(file))
})
</code></pre>
<p>Will print out all the file names from one directory up and in a 'public' directory from the script location. You can use <code>fs.readFile</code> to read the contents of each file. If they are JSON, you may read them as utf8 strings and parse them with <code>JSON.parse</code>.</p>
<p>To read files from a remote server, they must be served via express or some other static file server:</p>
<pre><code>import express from 'express'
const app = express()
app.use(express.static('public'))
app.listen(8000)
</code></pre>
<p>Then on the client end you could use fetch or request http library to call the express endpoint hosted at port 8000 (in this simple example.</p>
|
matplotlib scatter plot: How to use the data= argument <p>The matplotlib documentation for <code>scatter()</code> states:</p>
<blockquote>
<p>In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[]:</p>
<p>All arguments with the following names: âsâ, âcolorâ, âyâ, âcâ, âlinewidthsâ, âfacecolorâ, âfacecolorsâ, âxâ, âedgecolorsâ.</p>
</blockquote>
<p>However, I cannot figure out how to get this to work.
The minimal example</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(size=(3, 2))
props = {'c': ['r', 'g', 'b'],
's': [50, 100, 20],
'edgecolor': ['b', 'g', 'r']}
plt.scatter(data[:, 0], data[:, 1], data=props)
plt.show()
</code></pre>
<p>produces a plot with the default color and sizes, instead of the supplied one.</p>
<p>Anyone has used that functionality?</p>
| <p>In reference to your example, I think the following does what you want:</p>
<pre><code>plt.scatter(data[:, 0], data[:, 1], **props)
</code></pre>
<p>That bit in the docs is confusing to me, and looking at the sources, <code>scatter</code> in <code>axes/_axes.py</code> seems to do nothing with this <code>data</code> argument. Remaining <code>kwargs</code> end up as arguments to a <code>PathCollection</code>, maybe there is a bug there.</p>
<p>You could also set these parameters after <code>scatter</code> with the the various <code>set</code> methods in PathCollection, e.g.:</p>
<pre><code>pc = plt.scatter(data[:, 0], data[:, 1])
pc.set_sizes([500,100,200])
</code></pre>
|
Compile typescript without transpiling async functions <p>Is there a way to use the TypeScript compiler only to remove type annotations, but not transpiling async functions? Something like a <code>{ target: 'esInfinite' }</code> option? The reason is: There are browsers that already support async functions, so I wish to have a build target where those functions are not affected.</p>
<p>example input:</p>
<pre><code>async function foo(a : number) : Promise<void> {}
</code></pre>
<p>example output:</p>
<pre><code>async function foo(a) {}
</code></pre>
| <p>This feature was already requested <a href="https://github.com/Microsoft/TypeScript/issues/5361" rel="nofollow">here</a>. Targeting es2016 and es2017 should be available in the <a href="https://github.com/Microsoft/TypeScript/milestone/2" rel="nofollow">Community</a> milestone and in <a href="https://github.com/Microsoft/TypeScript/milestone/20" rel="nofollow">TypeScript 2.1</a>.</p>
|
ASP.NET Core & EntityFramework Core: Left (Outer) Join in Linq <p>I am trying to get a left join working in Linq using ASP.NET Core and EntityFramework Core.</p>
<p>Simple situation with two tables:</p>
<ul>Person (id, firstname, lastname)</ul>
<ul>PersonDetails (id, PersonId, DetailText)</ul>
<p>The data I try to query is Person.id, Person.firstname, Person.lastname and PersonDetails.DetailText.
Some persons do not have a DetailText so the wanted result is NULL.</p>
<p>In SQL it works fine</p>
<pre><code>
SELECT p.id, p.Firstname, p.Lastname, d.DetailText FROM Person p
LEFT JOIN PersonDetails d on d.id = p.Id
ORDER BY p.id ASC
</code></pre>
<p>results as expected:</p>
<pre><code>
# | id | firstname | lastname | detailtext
1 | 1 | First1 | Last1 | details1
2 | 2 | First2 | Last2 | details2
3 | 3 | First3 | Last3 | NULL
</code></pre>
<p>inside my Web API controller i query:</p>
<pre><code>
[HttpGet]
public IActionResult Get()
{
var result = from person in _dbContext.Person
join detail in _dbContext.PersonDetails on person.Id equals detail.PersonId
select new
{
id = person.Id,
firstname = person.Firstname,
lastname = person.Lastname,
detailText = detail.DetailText
};
return Ok(result);
}
</code></pre>
<p>The results in swagger are missing Person 3 (those without detail text)</p>
<pre><code>
[
{
"id": 1,
"firstname": "First1",
"lastname": "Last1",
"detailText": "details1"
},
{
"id": 2,
"firstname": "First2",
"lastname": "Last2",
"detailText": "details2"
}
]
</code></pre>
<p>What am I doing wrong in Linq?</p>
<hr>
<h2>Update 1:</h2>
<p>Thank you for the answers and the links so far.</p>
<p>I copied and pasted the code(s) below using <code>into</code> and <code>.DefaultIfEmpty()</code> and after some further readings I understand that this should work.</p>
<p>Unfortunatly it doesn't.</p>
<p>First there the code starts throwing exceptions but still returns with the first two results (with the NULLs missing). Copy Paste from the output window:</p>
<pre><code>
System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method(Closure , TransparentIdentifier`2 )
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteObject(TextWriter writer, Object value)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.ExceptionTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.RequestTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()
Microsoft.AspNetCore.Server.Kestrel:Error: Connection id "0HKVGPV90QGE0": An unhandled exception was thrown by the application.
System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method(Closure , TransparentIdentifier`2 )
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteObject(TextWriter writer, Object value)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.ExceptionTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ApplicationInsights.AspNetCore.RequestTrackingMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()
</code></pre>
<p>Google gave me that one: <a href="https://github.com/aspnet/EntityFramework/issues/4002" rel="nofollow">"LEFT OUTER JOIN PROBLEMS #4002"</a>
as well as <a href="http://stackoverflow.com/questions/34095062/left-outer-join-with-entity-framework-core">"Left outer join @ Stackoverflow"</a></p>
<p>Now I am not sure if that is some bug that either still exists or should have been fixed already. I am using EntityFramework Core RC2.</p>
<hr>
<h2>Solution 1: Navigation Properties</h2>
<p>As Gert Arnold pointed out in the comments: use the navigation properties</p>
<p>This means the (working) query simply looks like</p>
<pre><code>
var result = from person in _dbContext.Person
select new
{
id = person.Id,
firstname = person.Firstname,
lastname = person.Lastname,
detailText = person.PersonDetails.Select(d => d.DetailText).SingleOrDefault()
};
return Ok(result);
</code></pre>
<p>In my PersonExampleDB I hadn't correctly set the foreign key so the property <code>PersonDetails</code> wasn't in the scaffolded model class. But using this is the simplest solution (and works and even works fast) instead of the join for now (see the bug reports).</p>
<hr>
<p>Still happy about updates when the join way works one time.</p>
| <p>If you need to do the <strong>Left joins</strong> then you have to use <code>into</code> and <code>DefaultIfEmpty()</code> as shown below.</p>
<pre><code>var result = from person in _dbContext.Person
join detail in _dbContext.PersonDetails on person.Id equals detail.PersonId into Details
from m in Details.DefaultIfEmpty()
select new
{
id = person.Id,
firstname = person.Firstname,
lastname = person.Lastname,
detailText = m.DetailText
};
</code></pre>
<p>You can learn more about it : <a href="http://www.progware.org/Blog/post/Left-Outer-Join-in-LINQ-to-Entities-(for-Entity-Framework-4).aspx" rel="nofollow"><strong>Left Outer Join in LINQ to Entities</strong></a></p>
|
Unity3D 5.4.1 - Can I get object transformations at different times from animation? <p>I'm trying to export levels created in Unity for a school project, and I would like to export a path that the player will fly along. My plan was to create an animation and store positions along the path and then export the transformation values at those points (or possibly at intermediate points on the curve as well), however I can't figure out how to extract the object transformations at a certain point in the animation. Is this at all possible? Could I for example animate the gameobject in code and pick out the transformations at some interval or something? I have been done a lot of googling, but I've not really found a clear answer.</p>
<p>Thank you in advance!</p>
| <p>Yes it's possible using <a href="https://docs.unity3d.com/Manual/animeditor-AnimationEvents.html" rel="nofollow">Animation events</a>. Write a method to record the data you want at various points in the animation timeline. Be advised though there is <a href="https://www.google.co.uk/search?q=unity%20animation%20events%20not%20firing&ie=utf-8&oe=utf-8&client=firefox-b&gfe_rd=cr&ei=KtD3V_msK-nR8gfn64HoDQ" rel="nofollow">some arguement</a> as to whether this is reliable. An alternative would be to use coroutines to report the data you're after after some time period according to when you want the animations to yield data. Edit: hey look at me I used 'after after' legitimately in a sentence :)</p>
|
Deprecation warning: moment construction falls back to js Date This is discouraged and will be removed in upcoming major release <p>I am using <code>Moments</code> but get a <strong>depreciation</strong> warning. Can anyone advise where my code is causing this, and what it should change to please?</p>
<p><a href="http://momentjs.com/guides/#/warnings/js-date/" rel="nofollow">http://momentjs.com/guides/#/warnings/js-date/</a></p>
<pre><code>Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: [object Object]
Error
at Function.<anonymous> (file:///android_asset/www/build/js/app.bundle.js:101533:106)
at configFromString (file:///android_asset/www/build/js/app.bundle.js:103263:33)
at configFromInput (file:///android_asset/www/build/js/app.bundle.js:103623:14)
at prepareConfig (file:///android_asset/www/build/js/app.bundle.js:103606:14)
at createFromConfig (file:///android_asset/www/build/js/app.bundle.js:103573:45)
at createLocalOrUTC (file:///android_asset/www/build/js/app.bundle.js:103660:17)
at local__createLocal (file:///android_asset/www/build/js/app.bundle.js:103664:17)
at utils_hooks__hooks (file:///android_asset/www/build/js/app.bundle.js:101264:30)
at DateFormatPipe.transform (file:///android_asset/www/build/js/app.bundle.js:115304:17)
at DebugAppView._View_MessagesPage3.detectChangesInternal (MessagesPage.template.js:795:88)
at DebugAppView.AppView.detectChanges (file:///android_asset/www/build/js/app.bundle.js:16171:15)
</code></pre>
<p><strong>messages.html</strong></p>
<pre><code><center><span class="message-datetime">{{message.createdAt | amDateFormat: 'DD MMM YYYY'}}</span></center>
<span class="message-timestamp">{{message.createdAt | amDateFormat: 'h:mm a'}}</span>
</code></pre>
<p><strong>messages.ts</strong></p>
<pre><code>import {DateFormatPipe} from 'angular2-moment';
@Component({
templateUrl: 'build/pages/messages/messages.html',
pipes: [DateFormatPipe]
})
</code></pre>
<p><strong>models.d.ts</strong></p>
<pre><code> interface Message {
_id?: string;
chatId?: string;
senderId?: string;
ownership?: string;
content?: string;
createdAt?: Date;
changeDate?: boolean;
readByReceiver?: boolean;
lastMessageComp?: Tracker.Computation;
}
</code></pre>
| <p>It seems that "createdAt" property contains a string and not a date. Is the object retrieved from server? if it is, most probably you have a date formatted to text (something like "2012-04-21T18:25:43" or "\"\/Date(1335205592410)\/\"").</p>
<p>Please remember that with typescript you can specify the types of the variables, type-checking is performed at "compile time", but it is not guarantee that the content is a date when the transpiled ts is executed by the browser (and also, you can apply a pipe to a string property without any "compile time" errors).</p>
<p>If the object is a json deserialized from http, what you can do is manually parse the date:</p>
<pre><code>return this.http.get('api/Some/Url/Messages', { search: params })
.map((res: Response) => {
let messages = res.json();
return _.map(messages, (t: Message) => {
return {
chatId: t.chatId,
senderId: t.senderId,
...: ...,
createdAt: moment(t.createdAt, 'YYYYMMDD').toDate(),
...: ...
};
});
})
.catch(this.handleError);
</code></pre>
|
Jar file contains no class files after bintrayUpload <p>I am trying to publish my lib to bintray. But the jar file that is created only contains a META-INF folder and no class files.</p>
<p>I have followed the guide at <a href="https://github.com/bintray/gradle-bintray-plugin#readme" rel="nofollow">https://github.com/bintray/gradle-bintray-plugin#readme</a> but can not get it to work.</p>
<p>This is how my gradle file looks like.</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
plugins {
id "com.jfrog.bintray" version "1.7"
}
apply plugin: 'maven-publish'
apply plugin: 'java'
allprojects {
repositories {
jcenter()
}
}
publishing {
publications {
MyPublication(MavenPublication) {
from components.java
groupId ''
artifactId ''
version '1.0'
}
}
}
bintray {
user = ''
key = ''
publications = ['MyPublication']
pkg {
repo = 'maven'
name = ''
desc = ''
licenses = ['Apache-2.0']
websiteUrl = ''
vcsUrl = ''
version {
name = '1.0'
vcsTag = '1.0'
released = new Date()
attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
}
}
}
</code></pre>
<p>Then I run gradlew bintrayUpload and it is uploaded to bintray, but the jar files just contains the META-INF folder, no class files. </p>
| <p>I managed to fix it.
Biggest difference was I used configurations instead of publications when pushing to bintray. Below is the gradle files I setup for it to work.
Then just run gradlew bintrayUpload. I got some error messages that I did not manage to fix, but they were not necessary to fix as it worked to upload anyway.</p>
<p>in the root build.gradle</p>
<pre><code>plugins {
id "com.jfrog.bintray" version "1.7"
id "com.github.dcendents.android-maven" version "1.5"
}
</code></pre>
<p>in the end of mylib.gradle file</p>
<pre><code>// bintrayUpload config
apply from: 'bintray-publish.gradle'
</code></pre>
<p>bintray-publish.gradle</p>
<pre><code>apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
// Maven group id and version for the artifact
group = LIB_GROUP_ID
version = LIB_VERSION
install {
repositories.mavenInstaller {
// This generates POM.xml with proper parameters
pom {
project {
packaging POM_PACKAGING
groupId LIB_GROUP_ID
artifactId LIB_ARTIFACT_ID
name LIB_NAME
description LIB_DESCRIPTION
url LIB_URL
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
}
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
// TODO: Java doc generates errors for some reason, disable for now
//archives javadocJar
archives sourcesJar
}
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
bintray {
user = POM_DEVELOPER_ID
key = properties.getProperty("bintray.apikey")
configurations = ['archives']
pkg {
repo = 'maven'
name = BIN_TRAY_NAME
desc = LIB_DESCRIPTION
licenses = ['Apache-2.0']
websiteUrl = LIB_URL
vcsUrl = LIB_VCS_URL
publish = true
dryRun = false
version {
name = LIB_VERSION
desc = LIB_DESCRIPTION
released = new Date()
}
}
}
</code></pre>
<p>gradle.properties</p>
<pre><code>BIN_TRAY_NAME = MyLib
LIB_VERSION = 1.0.0
LIB_GROUP_ID = com.xxx.mylib
# The artifact name should be the same as the library module name
LIB_ARTIFACT_ID = mylib
LIB_NAME = MyLib
LIB_DESCRIPTION = My desc
LIB_URL = https://github.com/xxx/mylib
LIB_VCS_URL = https://github.com/xxx/mylib.git
POM_DEVELOPER_ID = My bintray id
POM_DEVELOPER_NAME = My bintray name
POM_SCM_URL = scm:git@github.com/xxx/mylib.git
POM_SCM_CONNECTION = scm:git@github.com/xxx/mylib.git
POM_SCM_DEV_CONNECTION = scm:git@github.com/xxx/mylib.git
POM_LICENCE_NAME = The Apache Software License, Version 2.0
POM_LICENCE_URL = http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
POM_PACKAGING = aar
</code></pre>
|
delete text without element inside div after some button <p>here the code</p>
<pre><code><div
id="user-alert"
class="alert alert-danger col-md-offset-1 col-md-10 alert-dismissible"
role="alert"
>
<button type="button" class="close" data-hide="alert" aria-hidden="true">
<span aria-hidden="true">&times;</span>
</button>
myquestion is,, how to remove/delete this text using jquery, just this text only,,
</div>
</code></pre>
<p>i've tried <code>$('#user-alert :not(:first-child)').remove();</code> but it won't work</p>
<p>i also tried <code>$('#user-alert button.close).text('')</code> still not work</p>
| <p>Selector for the last node of element is <code>$('#user-alert').contents().last()[0]</code> and using that selector you can remove the text of it.</p>
<pre><code>$('#user-alert').contents().last()[0].textContent='';
</code></pre>
<p><strong>Working snippet:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('#user-alert').contents().last()[0].textContent='';</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div
id="user-alert"
class="alert alert-danger col-md-offset-1 col-md-10 alert-dismissible"
role="alert"
>
<button type="button" class="close" data-hide="alert" aria-hidden="true">
<span aria-hidden="true">&times;</span>
</button>
myquestion is,, how to remove/delete this text using jquery, just this text only,,
</div></code></pre>
</div>
</div>
</p>
|
Need help debugging SSLHandshakeException in Android Nougat <p>I have an app that downloads documents from 3rd party sites (to browse offline).</p>
<p>I am using a standard HttpUrlConnection.</p>
<p>It used to work like a charm, but since upgrading to Nougat, one of the site produces a very consistent SSLHandshakeException the others are working fine.</p>
<p>I have tries using the new app certificates, no luck.
I have even tried the old trick of the "trust all certs" TrustManager. No luck. The TrustManager id not even queries.</p>
<p>I noticed though that this server is using a fairly old cipher.</p>
<pre><code>...
New, TLSv1/SSLv3, Cipher is RC4-MD5
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1
Cipher : RC4-MD5
...
</code></pre>
<p>Can it be the reason for my woes, and if it is how can I add this cipher to my connection ?</p>
<p>Thx</p>
<p>Edit 1: The app is targetting SDK 22 and compiling against API 22 as well</p>
<p>Edit 2:
The code has been hacked a bit to test with a "forced" CA (build with the site's certificate) and to test with the "trust all" trust manager as well.
It is to note that, when in use, the "trust all" manager is never used.</p>
<pre><code>SSLContext sslContext = null;
if (testWitCa) {
Certificate ca = null;
try {
ca = cf.generateCertificate(caInput);
Log.v(this, "ca = " + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
} else {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
Log.v(FileDownloader.this, "Checking client with %s", authType);
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
Log.v(FileDownloader.this, "Checking server with %s", authType);
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, null);
}
URL url = new URL(fromUrl);
HttpURLConnection httpConn;
httpConn = (HttpsURLConnection) url.openConnection();
if (sslContext != null) {
((HttpsURLConnection) httpConn).setSSLSocketFactory(sslContext.getSocketFactory());
}
responseCode = httpConn.getResponseCode();
</code></pre>
<p>I have tried using the following security config file as well (the root CA for the site the Thawte G3):</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="@raw/site_ca"/>
<certificates src="@raw/thawte_g3_ca"/>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
</code></pre>
| <p>Same thing on Nexus 6 updated to Nougat.
My application worked and now doesn't work anymore.</p>
<p>I tried using an alternative libary (OkHttp) but it ends up in the same result.
javax.net.ssl.SSLHandshakeException: Connection closed by peer</p>
<p>The app work against other servers but not this particular one (same cipher parameters as your).</p>
<p>Same app on older Android (6 and below) works great.
It doesn't matter if you build for an older version. It crashs on 7.</p>
<p>Something has changed on the SSL stack.</p>
<p>Regards</p>
|
Java: Closing Streams: Streams non-NULL even after close() <p>In my finally clause I clean up any streams, e.g.,</p>
<pre><code> finally // Clean up
{
if (os != null) {
try {
os.close();
}
catch (IOException ioe) {
logger.warn("Failed to close outputStream", ioe);
}
}
if (is != null) {
try {
is.close();
}
catch (IOException ioe) {
logger.warn("Failed to close inputStream", ioe);
}
}
</code></pre>
<p>But I see that the Streams remain non-NULL even after closing. So is it wrong to check for NULL? Or do I not see the result of <code>close</code> ?</p>
| <p>The stream "object" is a reference to a instance of a stream. Whether the stream is open or not is part of its state. The close function is a function that runs in the objects state and thus will not affect references to it.</p>
<p>The reference will stay non-NULL until you set it null, but the stream's state is closed meaning that you cant use it anymore.</p>
|
Create akka message listener without extending Actor class <p>As I have seen from samples that one should be an actor in order to catch a message. But I need a custom listener in order to listen messages without creating a new actor class etc. I want something like this:</p>
<pre><code>throw message
listen Response{
...
}
</code></pre>
<p>Any usage like that?</p>
<p>Thx</p>
<p>EDIT: My purpose is to write a CEP and this CEP will need some business scenarios in order to produce outputs. So a scenario like this will occur:</p>
<p>Check if customer.internetusage>1000
check if quota exceeded
fraud check
...</p>
<p>This needs to be injected at runtime so I need a kind of structure in order to write a scenario like above.</p>
| <p>You can subscribe to the event-bus. You just need to implement the traits defined here: <a href="http://doc.akka.io/docs/akka/current/scala/event-bus.html" rel="nofollow">http://doc.akka.io/docs/akka/current/scala/event-bus.html</a></p>
|
rxjs and angular 2 and the use of the "take" operator <p>I am trying to use the "take" operator in my code (learning rxjs) but it is not sending the top 5 like I want. my simple code is below, anyone have any idea how to help?</p>
<pre><code>countries: Observable<Country[]>;
private searchTerms = new Subject<string>();
this.countries = this.searchTerms.debounceTime(300).distinctUntilChanged().switchMap(
searchTerm => searchTerm ? this.countrySearchService.search(searchTerm) : observable.of<Country[]>([]))
.take(5);
</code></pre>
| <p>After reading your comment, I understand you need the first 5 countries. Now note that your observable emits arrays of countries and not countries. The reason you use Observable.of instead of Observable.from. So, the right syntax should be:</p>
<pre><code>this.countries = this.searchTerms.debounceTime(300).distinctUntilChanged().switchMap(
searchTerm => searchTerm ? this.countrySearchService.search(searchTerm) : observable.from<Country[]>([]))
.take(5);
</code></pre>
<p>If you want a sample that demonstrate various use cases, have a look at <a href="http://jsbin.com/jusuzep/edit?js,console" rel="nofollow">this jsbin</a>.</p>
|
How to Check if Arrays in a Object Are All Empty? <p>So I need to pass in a object where each of its properties are arrays. The function will use the information held in each array, but I want to check if the whole object is empty empty (not just having no properties) by checking if each of its arrays are empty/null as well. What I have so far:</p>
<pre><code>function isUnPopulatedObject(obj) { // checks if any of the object's values are falsy
if (!obj) {
return true;
}
for (var i = 0; i < obj.length; i++) {
console.log(obj[i]);
if (obj[i].length != 0) {
return false;
}
}
return true;
}
</code></pre>
<p>So for example, this would result in the above being <code>false</code>:</p>
<pre><code>obj {
0: Array[0]
1: Array[1]
2: Array[0]
}
</code></pre>
<p>While this is the empty I'm checking for (so is true):</p>
<pre><code>obj {
0: Array[0]
1: Array[0]
2: Array[0]
}
</code></pre>
<p>The above code doesn't work. Thanks in advance.</p>
| <p>So if we want to go through the object and find if every key of that object passes a check, we can use <code>Object.keys</code> and the Array#extra <code>every</code> like so:</p>
<pre><code>var allEmpty = Object.keys(obj).every(function(key){
return obj[key].length === 0
})
</code></pre>
<p>This will set <code>allEmpty</code> to a boolean value (true/false), depending on if every time we run the given check <code>obj[key].length === 0</code> returns true or not.</p>
<p>This object sets <code>allEmpty</code> to true:</p>
<pre><code>var obj = {
0: [],
1: [],
2: []
}
</code></pre>
<p>while this sets it to false:</p>
<pre><code>var obj = {
0: [],
1: [],
2: [],
3: [1]
}
</code></pre>
|
Pandas: calculating the mean values of duplicate entries in a dataframe <p>I have been working with a dataframe in python and pandas that contains duplicate entries in the first column. The dataframe looks something like this:</p>
<pre><code> sample_id qual percent
0 sample_1 10 20
1 sample_2 20 30
2 sample_1 50 60
3 sample_2 10 90
4 sample_3 100 20
</code></pre>
<p>I want to write something that identifies duplicate entries within the first column and calculates the mean values of the subsequent columns. An ideal output would be something similar to the following:</p>
<pre><code> sample_id qual percent
0 sample_1 30 40
1 sample_2 15 60
2 sample_3 100 20
</code></pre>
<p>I have been struggling with this problem all afternoon and would appreciate any help.</p>
| <p><code>groupby</code> the <code>sample_id</code> column and use <code>mean</code></p>
<p><code>df.groupby('sample_id').mean().reset_index()</code><br>
<strong><em>or</em></strong><br>
<code>df.groupby('sample_id', as_index=False).mean()</code></p>
<p>get you </p>
<p><a href="http://i.stack.imgur.com/nw7e9.png" rel="nofollow"><img src="http://i.stack.imgur.com/nw7e9.png" alt="enter image description here"></a></p>
|
Using a dynamic variable in an ajax query <p>I'm struggling to pass a GET variable into a jquery file.</p>
<p>My code is</p>
<pre><code>function upload(files){ // upload function
var fd = new FormData(); // Create a FormData object
for (var i = 0; i < files.length; i++) { // Loop all files
fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
}
fd.append('nbr_files', i); // The last append is the number of files
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
data: fd, // We send the data string
processData: false,
contentType: false,
success: function(data) {
$('#result').html(data); // Display images thumbnail as result
$('#dock').attr('class', 'dock'); // #dock div with the "dock" class
$('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
},
xhrFields: { //
onprogress: function (e) {
if (e.lengthComputable) {
var pourc = e.loaded / e.total * 100;
$('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
}
}
},
});
</code></pre>
<p>I need the 5 in <code>url: 'ajax/tuto-dd-upload-image.php?order=5'</code> to be the vatriable <code>order</code> passed through a url like <code>domain.com/?order=XX</code></p>
| <p>You can use PHP and export the variable:</p>
<pre><code>var orderId = <?php echo json_encode($_GET['order']); ?>;
function upload(files) {
...
url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,
</code></pre>
<p>Or you could parse it directly in javascript:</p>
<pre><code>var orderId = self.location.search.match(/order=(\d+)/)[1];
// Then continue like the previous example
</code></pre>
<p>Of course you'll probably need some error checking around this, if there's a chance the GET param might ever be missing.</p>
|
Javascript replace not working in Angular JS <p>I'm trying to iterate through a list of titles and replace an escaped '&' character with the single character '&'. </p>
<p>For some reason I'm getting a console error saying that 'replace' is not a function and I don't know why.</p>
<p>Here is the code:</p>
<pre><code>//fetch discover menu
footerService.getDiscoverMenu()
.then(function(result) {
var hold = [];
angular.forEach(result.data, function(value, key){
// replacing escaped charater (&) from endpoint
this.push(key + ':' + value.replace(/&#038;/g,'&'));
}, hold);
self.discoverMenu = hold;
}, function(error) {
console.log('discover menu fetch error: ', error);
});
</code></pre>
<p>What am I doing wrong?</p>
| <pre><code>angular.forEach(result.data, function(value, key){
// replacing escaped charater (&) from endpoint
this.push(key + ':' + value.replace(/&#038;/g,'&'));
</code></pre>
<p>You are trying to iterate over <code>key</code>, rather than <code>value</code>. Look at the argument order, first goes <code>key</code> and then comes <code>value</code>. </p>
<p>It should be: </p>
<pre><code>//fetch discover menu
footerService.getDiscoverMenu()
.then(function(result) {
var hold = [];
angular.forEach(result.data, function(key, value){
// replacing escaped charater (&) from endpoint
this.push(key + ':' + value.replace(/&#038;/g,'&'));
}, hold);
self.discoverMenu = hold;
}, function(error) {
console.log('discover menu fetch error: ', error);
});
</code></pre>
|
Constructing an object of class type 'ClassName' with a metatype value must use a 'required' initializer XCode8 Swift 3 changes <p>I'm struggling with this particular error as a result of XCode 8 swift 3 changes, and can't find anywhere a detailed explanation as to why this is happening. </p>
<p>Error:</p>
<p><strong>Constructing an object of class type 'PermissionScope' with a metatype value must use a 'required' initializer</strong> </p>
<p>In Method:</p>
<pre><code>public convenience init() {
type(of: self).init(backgroundTapCancels: true)
}
</code></pre>
<p>Any help would be appreciated.</p>
| <p>This compiled:</p>
<pre><code>public convenience init() {
self.init(backgroundTapCancels: true)
}
</code></pre>
<p>Still would like to know why.</p>
|
Access nested structures without moving <p>I've got these structs:</p>
<pre><code>#[derive(Debug, RustcDecodable)]
struct Config {
ssl: Option<SslConfig>,
}
#[derive(Debug, RustcDecodable)]
struct SslConfig {
key: Option<String>,
cert: Option<String>,
}
</code></pre>
<p>They get filled from a <code>toml</code> file. This works perfectly fine. Since I got an <code>Option<T></code> in it I either have to call <code>unwrap()</code> or do a <code>match</code>.</p>
<p>But if I want to do the following:</p>
<pre><code>let cfg: Config = read_config(); // Reads a File, parses it and returns the Config-Struct
let keypath = cfg.ssl.unwrap().key.unwrap();
let certpath = cfg.ssl.unwrap().cert.unwrap();
</code></pre>
<p>It won't work because <code>cfg.ssl</code> gets moved to <code>keypath</code>. But why does it get moved? I call <code>unwrap()</code> on <code>ssl</code> to get the key (and <code>unwrap()</code> it to). So the result of <code>key.unwrap()</code> should get moved?</p>
<p>Or am I missing a point? Whats the best way to make these structs accessible like this (or in a other neat way)? I tried to implement <code>#[derive(Debug, RustcDecodable, Copy, Clone)]</code> but this won't work because I have to implement <code>Copy</code> to <code>String</code> as well. Then I have to implement <code>Copy</code> to <code>Vec<u8></code> and so on. There must be a more convenient solution?</p>
| <p>What is the definition of <code>Option::unwrap</code>? <a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap" rel="nofollow">From the documentation</a>:</p>
<pre><code>fn unwrap(self) -> T
</code></pre>
<p>it consumes its input (<code>cfg.ssl</code> here).</p>
<p>This is not what you want, you instead want to go from <code>Option<T></code> to <code>&T</code>, which will start by consuming <code>&self</code> (by reference, not value)... or you want to <code>clone</code> the <code>Option</code> before calling <code>unwrap</code>.</p>
<p>Cloning is rarely the solution... the alternative here is <a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.as_ref" rel="nofollow"><code>as_ref</code></a>:</p>
<pre><code>fn as_ref(&self) -> Option<&T>
</code></pre>
<p>And therefore you can write:</p>
<pre><code>let keypath /*: &String*/ = cfg.ssl.as_ref().unwrap().key.as_ref().unwrap();
^~~~~~~ ^~~~~~~~
</code></pre>
|
Set sort order of MySQL query using dropdown options <p>I want to allow site users to change the sort order of results that are returned by an existing query.
The query is currently</p>
<pre><code>$searchList = 'select distinct pa.products_id, pd.products_name,
p.products_model
FROM ' . TABLE_PRODUCTS_ATTRIBUTES . ' pa
left join ' . TABLE_PRODUCTS_DESCRIPTION . ' pd on (pa.products_id = pd.products_id)
left join ' . TABLE_PRODUCTS . ' p on (pa.products_id = p.products_id)
WHERE pd.language_id = ' . $language_id . '
order by products_model';
</code></pre>
<p>I've added the following code to generate the dropdown</p>
<pre><code><select id = "SortBy">
<option value ="">Please Choose<br>
<option value ="products_model;">Model (asc)<br>
<option value ="products_model DESC;">Model (desc)<br>
<option value ="products_name;">Name (asc)<br>
<option value ="products_name DESC;">Name (desc)<br>
<option value ="products_id;">Product ID (asc)<br>
<option value ="products_id DESC;">Product ID (desc)
</select>
</code></pre>
<p>and updated the query to</p>
<pre><code>$searchList = 'select distinct pa.products_id, pd.products_name,
p.products_model
FROM ' . TABLE_PRODUCTS_ATTRIBUTES . ' pa
left join ' . TABLE_PRODUCTS_DESCRIPTION . ' pd on (pa.products_id = pd.products_id)
left join ' . TABLE_PRODUCTS . ' p on (pa.products_id = p.products_id)
WHERE pd.language_id = ' . $language_id . '
order by ".mysql_real_escape_string($sort)."';
</code></pre>
<p>After the select options and before the sql query I've added</p>
<pre><code>$sort=$_POST["SortBy"]
</code></pre>
<p>which i believe should contain the selection made once it's submitted.</p>
<p>This is where I'm a little stuck. I want the user to be able to select their option from the dropdown and have it auto submit and store the choice so that the query which follows uses their selection but I don't know how to do this. I'm assuming some type of jQuery, but to be honest I'm lost when it comes to coding in this.</p>
<p>Following comments from Jeff I have changed the select list to this</p>
<pre><code><select id = "SortBy" name="SortBy>
<option value ="">Please Choose<br>
<option value ="model+">Model (asc)<br>
<option value ="model-">Model (desc)<br>
<option value ="name+">Name (asc)<br>
<option value ="name-">Name (desc)<br>
<option value ="prodid+">Product ID (asc)<br>
<option value ="prodid-">Product ID (desc)
</select>
</code></pre>
<p>and added the following code</p>
<pre><code> switch ($_SESSION ['sba_sort_order']) {
case 'model+' :
$order_by = ' products_model; ';
break;
case 'model-' :
$order_by = ' products_model DESC; ';
break;
case 'name+' :
$order_by = ' products_name; ';
break;
case 'name-' :
$order_by = ' products_name DESC; ';
break;
case 'prodid+' :
$order_by = ' products_id; ';
break;
case 'prodid-' :
$order_by = ' products_id DESC; ';
break;
</code></pre>
<p>Still lost on how to get this to trigger automatically and store the result for the sql query on selection of a dropdown though.</p>
| <p>First of all if you want some kind of "auto submit" you need to handle the onChange event, so your select could look like the following:</p>
<pre><code><select id = "SortBy" name="SortBy" onchange="submitForm()">
</code></pre>
<p>jQuery style</p>
<pre><code>$("#SortBy" ).change(function() {
//submit the form
});
</code></pre>
<p>Of course all kinds of toolkits like Dojo, jQuery and other (you mentioned jQuery - IMO it's always good to use any of them, at least for the cross-browser support) will help you with this. </p>
<p>Also, think about how do you want to post the data to your server: asynchronously or not.</p>
<p>Have a look at <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">MVC</a> and try to implement it this way. Create a controller which will handle the request (it may also validate it, some prefer validate on the model level), create a model which will save the chosen option if you want it persistent and prepare a view to interact with the user. It may be just "Your choice was successfuly saved", but it really depends on how you actually want it.</p>
|
npm: using 'npm uninstall' vs. just removing the folder <p>I wanted to try grunt-babel, so I opened up a terminal in my Home folder and did npm install --save-dev grunt-babel babel-preset-es2015 according to the plugin's instructions.</p>
<p>I was doing this too hastily, and realized I should probably have done this in my <em>new</em> project folder where I am dabbling with ES6 code. I had not even done npm init in that folder nor in the Home folder from where I executed the install command. </p>
<p>When I do npm uninstall grunt-babel, the preset files are removed but 91 folders of different dependencies remain in the node_modules folder.</p>
<p>Can I simply remove the folder instead of running npm uninstall 91 times?</p>
<p>This guy asked a similar question but none of the answers address his subquestion of just removing the folder: <a href="http://stackoverflow.com/questions/13066532/how-to-uninstall-npm-modules-in-node-js">how to uninstall npm modules in node js?</a></p>
| <ul>
<li>npm uninstall removes the module from node_modules, but not package.json. </li>
<li><p>npm uninstall --save to also delete the dependency from package.json.</p></li>
<li><p>npm rm remove the packages when uninstall not working</p></li>
<li><p><a href="https://docs.npmjs.com/cli/prune" rel="nofollow">npm prune</a> for extraneous packages are packages that are not listed on the parent package's dependencies list.</p></li>
</ul>
<p>But a good way for you should be sure the packages you uninstall is no more in the packages json and run <code>rm -rf node_modules && npm cache clean && npm install</code> if you don't want to uninstall one by one</p>
|
How to use patterns to ignore certain part of an input string in lua? <p><strong>Background Information</strong></p>
<p>I have a csv file with lines that look like this: </p>
<pre><code>+11231231234,13:00:00,17:00:00,1111100,12345,test.net
+11231231234,,,0000000,23456,test.net
+11231231234,18:00:00,19:00:00,1111100,09991,test.net
</code></pre>
<p>The lua pattern I have right now is this: </p>
<pre><code>local id, start_time, end_time, asd, int, domain = line:match("(%+%d+),([%d%d:]*),([%d%d:]*),(%d*),([%d%*%#]*),(%a*.*)")
</code></pre>
<p>And its working</p>
<p><strong>Question</strong></p>
<p>How would I change this pattern so that IF the start_time / end_time values exist, I want to extract ONLY the first two sets of numbers? So for example, from this input: </p>
<pre><code>+11231231234,18:00:00,19:00:00,1111100,09991,test.net
</code></pre>
<p>I would like to end up with these values: </p>
<pre><code>start_time = 18:00
end_time = 19:00
</code></pre>
<p>instead of </p>
<pre><code>start_time = 18:00:00
end_time = 19:00:00
</code></pre>
<p><strong>What I've Tried</strong></p>
<p>I've tried changing this: </p>
<pre><code>line:match("(%+%d+),([%d%d:]*),([%d%d:]*),(%d*),([%d%*%#]*),(%a*.*)")
</code></pre>
<p>to this: </p>
<pre><code>line:match("(%+%d+),([%d%d:%d%d]*),([%d%d:%d%d]*),(%d*),([%d%*%#]*),(%a*.*)")
</code></pre>
<p>But it was a no go</p>
<p><strong>EDIT 1</strong></p>
<p>I changed the pattern to this: </p>
<pre><code> line:match("(%+%d+),(%d*:?%d*)[%d:]*,(%d*:?%d*)[%d:]*,(%d*),([%d%*#]*),(%S*)")
</code></pre>
<p>And in some cases, its working... but in the following scenarios, it fails: </p>
<pre><code> +11231231234,00:00:00,00:00:00,1111100,12345,test.net
</code></pre>
<p>So when the timestamp is zero across the board, it doesn't correctly trim the seconds. I'm currently reviewing the code to make sure it's not a typo on my end.
Thanks. </p>
| <pre><code>local id, start_time, end_time, asd, int, domain =
line:match("(%+%d+),(%d*:?%d*)[%d:]*,(%d*:?%d*)[%d:]*,(%d*),([%d%*#]*),(%S*)")
</code></pre>
|
How Can i Import example application from developer.android.com into Android Studio <p>I have downloaded the CustomView.zip from <a href="https://developer.android.com/training/custom-views/index.html" rel="nofollow" title="developer android">developer android page</a>.
I've tried to import this into Android Studio 2.2.0.12. But I am NOT able to do it.</p>
<p>I have also tried to create a empty project in order to import only the sources and XML. It does´t work either, I get a lot of duplicates XML definitions and even after resolving the duplicates the App crashes with some inflate exception.</p>
<p>So, i´m wondering, How can I import this into Android Studio in order to have a working project and run it to see the behavior and also to debug it</p>
<p>Thanks in advance.</p>
| <p>Looking at the sample file, stupidly, it doesnt include any of the standard android framework files (gradle, manifest etc), so Android Studio will not be able to automatically import it.</p>
<p>To get round this you should create a new blank project, leave the mainactivity that is generated.</p>
<p>Then go in to the file structure of the new project and copy in the files from the sample in to the corresponding files. Make sure you overwrite the files in the new project.</p>
<p>Then go in to the code base in Android Studio and delete any imports that cant be found due to incorrect package names. Re import these (alt + enter on mac) with the correct package names and then build and you should be good to go.</p>
|
Spotfire: Date filtering with action control <p>I am working on a spotfire app and I am trying to create an action control that filters dates. I am new to ironpython and can't figure out what is wrong with my script:</p>
<pre><code>from Spotfire.Dxp.Application.Visuals import *
import datetime as dt
visual = viz.As[VisualContent]()
visual.Data.WhereClauseExpression = '[Agreement End Date] < dt.date.today()'
</code></pre>
<p>When the above script is run I get "The expression is not valid after '(' on line 1 character 34. Here Agreement End Date is the column I am trying to filter on. I have looked around and haven't been able to find an answer (I realize this probably a very simple task for someone experienced in such things). </p>
<p>Any help is greatly appreciated!</p>
| <p>I figured out what was going on here, you need to use spotfire functions inside of the WhereClauseExpression string. The following code fixes the issue:</p>
<pre><code>from Spotfire.Dxp.Application.Visuals import *
visual = viz.As[VisualContent]()
visual.Data.WhereClauseExpression = '[Agreement End Date] < DateTimeNow()'
</code></pre>
|
Plotting Curves from Data Frame Columns <p>i am facing a problem in plot ols estimations in a scatterplot:</p>
<p>I have this data frame: With 9 columns and 99 rows:</p>
<pre><code>structure(list(Y = c(-0.145442175, 0.291096141, 0.489923112,
-2.038363166, 1.180430664, 0.188114666, 0.850922634, 1.172142766,
-3.980837975, 0.285762444, 2.497040646, 0.658010994, -0.925171981,
0.37076995, -1.108211119, -0.409242669, -1.234583525, -0.385841816,
0.016744771, -0.584406288, 1.17224811, -0.746804388, -0.625028046,
0.257871468, -2.735845346, 2.619304857, -0.406825232, 0.323665151,
2.218951363, -0.821029648, -0.872854889, -2.663306158, -0.121976044,
0.881566376, -1.972706678, -3.855576256, 2.927421113, 1.314753531,
0.234296206, 0.828464757, -0.909318569, 0.616134903, -0.567630403,
0.624571064, -0.414112923, 0.642200314, -0.309421266, 0.195312598,
-0.519988256, 0, 0.081070175, 0.032446432, -0.534025032, -0.426783307,
-0.38495511, -0.207900219, -1.953789746, -0.616924355, -0.783222881,
-1.935420969, 0.638445535, 1.080925923, -1.598076681, 0.25063631,
-0.697183766, 0.188971653, -0.415267389, -4.154506044, 1.163226552,
0.036569698, -0.547147074, 1.11937374, 0.383311682, -0.875037781,
-0.372684863, 0.306816004, -1.250561544, -1.042237738, -1.757788446,
0.021079982, 1.844023775, 1.674645753, -0.428546132, -0.527705597,
0.542202572, -0.621479123, -0.050415867, -0.122332943, 0.468553764,
0.216998274, 3.088480781, 0.434099931, 2.114916704, -2.407018936,
-0.127060127, 0.546756422, 0.263207486, 0.63453915, 0.76832746
), X = c(0.009476137, -0.0236354, 0.0094081, 0.11715252, 0.032324021,
0.0461193, 0.050794971, 0.032372819, 0.202121874, 0.390821859,
-0.124492596, -0.127305193, -0.22233597, -0.081113713, 0.09952616,
0.22494711, 0.226621495, 0.411607624, 0.089200478, -0.013454832,
-0.013547165, -0.232366214, 0.03140992, -0.026798837, -0.084556341,
-0.091993172, -0.303730207, -0.236679148, -0.284235285, -0.355253166,
-0.179645537, -0.01381843, -0.022950244, -0.050065976, -0.032018504,
-0.087168055, -0.081865767, -0.253991077, -0.242882759, -0.150225053,
-0.16596575, -0.156887247, -0.071795146, -0.100408802, -0.067307731,
0.024006869, -0.019250912, -0.02399429, 0.038421097, 0.062320065,
0.07187025, 0.024019462, 0.038421097, 0.033539309, 0.014351457,
-0.009575137, 0.014343968, 0.028561284, 0.0404213, 0.026065697,
-0.004700435, -0.072739794, -0.042217496, -0.05889531, -0.130522139,
-0.136291869, -0.120099035, -0.091418565, -0.122040844, -0.124609029,
-0.096255449, -0.190338762, -0.11611752, -0.055598423, -0.065293448,
-0.038746326, -0.029090518, -0.067627348, -0.082097445, -0.215845836,
-0.389993696, -0.264371785, -0.126530291, -0.111840985, -0.094952196,
-0.136700196, -0.190968195, -0.156564122, -0.181077278, -0.15381292,
-0.122020692, -0.107867301, -0.068642333, -0.034348677, -0.073289926,
-0.063314884, -0.092537576, -0.165375956, -0.15042398), Null = c(-0.036795117836493,
0.0120555676565338, -0.0366906491623935, -0.22323992930528, -0.0728300398338213,
-0.0955073599141197, -0.103350601084975, -0.0729090354522075,
-0.400153521158964, -0.887015257107641, 0.1362666683468, 0.13919994231771,
0.221388292373518, 0.087380368104602, -0.189831042487278, -0.452154909992189,
-0.456044210600938, -0.948567833126862, -0.170785020294756, -0.00253939338337472,
-0.00240533038312774, 0.228145471304061, -0.0713518661553421,
0.0165138860659871, 0.0915102566139487, 0.100284493544177, 0.265652059802101,
0.230938443729295, 0.257246215885006, 0.281209408151878, 0.188533028671265,
-0.00201164134414489, 0.0110851592192505, 0.0481858583559124,
0.0237904823161768, 0.094614581053392, 0.0882862377341187, 0.241468070168396,
0.234837060900023, 0.162029971029324, 0.176601607696189, 0.168307425791361,
0.0759851164110966, 0.109970788582389, 0.0703849242291975, -0.059492586621119,
0.00581616568295407, 0.0125631925046972, -0.0827672867080164,
-0.123023227393077, -0.139691063870559, -0.0595125909296922,
-0.0827672867080164, -0.074799966578053, -0.044324863847201,
-0.00820062690976645, -0.0443132308515717, -0.0667648997869916,
-0.0860567642206439, -0.0627706942069095, -0.0153914247452083,
0.0771546773236518, 0.0377224646820258, 0.0596889425617937, 0.1425196179012,
0.148379247725525, 0.13162698340227, 0.0996137276510431, 0.133686233062275,
0.136388667637584, 0.105222539655097, 0.197385328960716, 0.127361748973716,
0.0554268640818151, 0.0678473149754353, 0.0330232883757411, 0.0197208677278167,
0.0707862239701058, 0.0885648870712001, 0.216820906265572, 0.286245951224793,
0.247258814186372, 0.138394666330137, 0.122716205945161, 0.103719679674083,
0.148789344619283, 0.197893429730301, 0.168006688568371, 0.189742414352596,
0.165430712615822, 0.133664933948451, 0.11833998959919, 0.0720581343490991,
0.0270069004188009, 0.077834296346802, 0.0653403280475977, 0.100918894574441,
0.176071877748707, 0.162219750035618), OLS_1 = c(-2.97674658085357,
-2.95792547866683, -2.97674412477729, -2.7937460366665, -2.96913739819288,
-2.95639989365184, -2.95069150171007, -2.96910314906723, -2.3856485268894,
-0.647452287114872, -2.68293610049662, -2.670570393744, -2.10297963546522,
-2.84137496711892, -2.84927190111917, -2.23638642750757, -2.22477621905134,
-0.385841816000001, -2.87715002139054, -2.96747293407547, -2.96740133507642,
-2.02609643038743, -2.9697648045679, -2.95427875550959, -2.8310157181346,
-2.80733412921436, -1.38551048535346, -1.99204069101103, -1.57679230211392,
-0.821029648, -2.39395151432173, -2.96718943992586, -2.95867282134313,
-2.9175506236826, -2.94755679517459, -2.82290206987746, -2.83914454134393,
-1.84931168689084, -1.94200482386918, -2.56030139156351, -2.4747687889082,
-2.52507434784403, -2.86749990988846, -2.77838660436577, -2.87908253396987,
-2.97385415360498, -2.96244666805069, -2.95752797222193, -2.96426392038595,
-2.93361303993881, -2.91621877029975, -2.97384869333029, -2.96426392038595,
-2.96826157356433, -2.97653443074828, -2.97023260580068, -2.97653534550966,
-2.9715473503959, -2.96240424133875, -2.97289412424858, -2.9730125951007,
-2.86497897723402, -2.93188917574701, -2.89904800305061, -2.6561144854951,
-2.62935195635151, -2.70174255054932, -2.80922741244202, -2.69350740105694,
-2.68242924921473, -2.79295820376613, -2.32657978700299, -2.718248099245,
-2.90625073580661, -2.88407071600265, -2.93759776247538, -2.95143559806685,
-2.87827902655775, -2.83845377816351, -2.15100018436527, -0.392139380784325,
-1.7590965971582, -2.67400272569948, -2.73540774982849, -2.79741598960129,
-2.62741730304073, -2.322499279269, -2.52681590220219, -2.38514457172383,
-2.541507865502, -2.6935934995898, -2.75082409521646, -2.87570553083222,
-2.94427256930162, -2.86349763526591, -2.88884317216564, -2.80553055841713,
-2.47811758528604, -2.55927025907886), OLS_2 = c(-2.83865555876367,
-2.82203271957637, -2.83865550287755, -2.66277932892391, -2.83073328950317,
-2.8182826854432, -2.81275284604234, -2.83069942358793, -2.27571536741022,
-0.632851535784811, -2.56646067709365, -2.55491098827374, -2.02364579120999,
-2.71420058960775, -2.71564453925406, -2.13442002502496, -2.12343285482248,
-0.385841816, -2.74223576659719, -2.83068449367348, -2.83062014186059,
-1.95158880862936, -2.83135434505306, -2.81870405841395, -2.70456098525177,
-2.68251016192609, -1.35080974869909, -1.91966655284606, -1.53026524143009,
-0.821029648, -2.29619548286091, -2.83042962848176, -2.82271365766308,
-2.78489427206998, -2.81254809712918, -2.69700817487578, -2.71212546804251,
-1.78585373408616, -1.87276085874404, -2.45184700668681, -2.37183555552258,
-2.41889982491589, -2.73848954857785, -2.65553364194069, -2.74924637290594,
-2.8354502300085, -2.82614423798244, -2.82167034953476, -2.82594242161564,
-2.7962902949221, -2.77959589724382, -2.83544467118397, -2.82594242161564,
-2.82986834510621, -2.83829410413293, -2.83315419155684, -2.83829521382395,
-2.83312719078141, -2.82412509152621, -2.83447802392599, -2.83561001727694,
-2.73614728712302, -2.79813447119318, -2.76776591170989, -2.54140667394362,
-2.5163996858597, -2.58402223424852, -2.68427373122372, -2.57633280462435,
-2.56598731123967, -2.66911582708562, -2.23311605677819, -2.59943103595799,
-2.7744383205277, -2.75387620457868, -2.80339428073398, -2.81610308322424,
-2.74850042856033, -2.71148276169435, -2.06864445166113, -0.418358709691658,
-1.7012556906544, -2.558117011201, -2.61544592452239, -2.67326984561107,
-2.5145916492569, -2.22929491666958, -2.42052887445801, -2.28795076147412,
-2.43427089501948, -2.57641320261571, -2.62982944259216, -2.74611100908034,
-2.80953310903525, -2.73477077084888, -2.75830410348864, -2.68083005992821,
-2.37496906485549, -2.4508827380889), OLS_3 = c(-2.58083646581942,
-2.5683178338716, -2.58084089114316, -2.41826149362172, -2.57232965672457,
-2.56041470241702, -2.55521822468909, -2.57229650627193, -2.0704676472292,
-0.605591599496051, -2.34899840070827, -2.33897223601076, -1.87552769159633,
-2.47676312148376, -2.46615920192222, -1.94404642215785, -1.9342224786085,
-0.385841816000001, -2.49034777076914, -2.57529735049815, -2.57524652934739,
-1.81248137667339, -2.57293885513887, -2.56558300171966, -2.46846711008925,
-2.44946096338359, -1.28602268062379, -1.78454238349805, -1.4433981562183,
-0.821029648, -2.11368273887782, -2.57509593622485, -2.56887479307252,
-2.53722183306237, -2.56048377359198, -2.46196139684977, -2.47497795642607,
-1.66737628649693, -1.7434807939705, -2.24936019247138, -2.17965685727221,
-2.22066956504207, -2.49762425675709, -2.42616435450559, -2.50683929408026,
-2.57704694280319, -2.57166448720316, -2.56802106429762, -2.56769302344379,
-2.53990559282486, -2.52451787208599, -2.57704119998386, -2.56769302344379,
-2.57148502596854, -2.58019625622877, -2.57722566059429, -2.58019772985789,
-2.57469359055957, -2.56595475982599, -2.57605200249485, -2.57907626550515,
-2.49561557851369, -2.54841138215235, -2.52265924802504, -2.32724456926626,
-2.30551521644622, -2.36423571438323, -2.45098235381054, -2.35756515622,
-2.3485875529132, -2.43789928063234, -2.05861713726078, -2.37759686441414,
-2.52834152993493, -2.51080007744427, -2.55283331443161, -2.56343418632904,
-2.50620082129485, -2.47442497328161, -1.91488441727801, -0.467310795744689,
-1.59326539683083, -2.34175573481226, -2.39147445613669, -2.44148615865099,
-2.30394357612981, -2.05528024243402, -2.22208856552246, -2.10648769733616,
-2.23405702128991, -2.35763491117015, -2.40392966200837, -2.50415507637054,
-2.55797145858227, -2.49443477420494, -2.51458468009137, -2.44801138045477,
-2.18238842077399, -2.24852076027753), OLS_4 = c(-2.4289478285331,
-2.41681903415288, -2.42895104301202, -2.27867081965274, -2.4213161496905,
-2.41038194422522, -2.40559515788832, -2.42128586809391, -1.95522949388955,
-0.590647453749078, -2.21077815389366, -2.20138321248198, -1.76758669368012,
-2.33060054299992, -2.32313500877883, -1.83755181381677, -1.82840597739465,
-0.385841816, -2.34557046847711, -2.42346978407977, -2.42342111188123,
-1.70861264386732, -2.42187239429871, -2.41422413566286, -2.32281181955877,
-2.30497392699143, -1.21632553238408, -1.68248005204524, -1.36346128591018,
-0.781669317752002, -1.99042352676657, -2.42327691796255, -2.41734804581689,
-2.38744248609079, -2.40939495374384, -2.31670510436427, -2.32892438647688,
-1.57289978140148, -1.64407512538075, -2.11744278294415, -2.05217911016675,
-2.09057710272701, -2.35019495754122, -2.28311871426765, -2.35885543710246,
-2.42560672084754, -2.42000135641999, -2.4165372393818, -2.41707097497419,
-2.39145946177805, -2.3772271125231, -2.42560153071694, -2.41707097497419,
-2.420544236609, -2.42841594588832, -2.4253216199613, -2.42841722040367,
-2.42347169955882, -2.41547562547196, -2.42470587973943, -2.4271143253132,
-2.34830761179908, -2.39799094116799, -2.37373288731684, -2.19039487337143,
-2.17003793409615, -2.22505776553193, -2.30640152341961, -2.21880622042115,
-2.21039315621698, -2.294126428977, -1.93888869626962, -2.23758086989921,
-2.37908034073483, -2.36257901260101, -2.4021644964107, -2.41218787827608,
-2.35825527028976, -2.3284051877118, -1.80440438182757, -0.451087514089169,
-1.50359480720157, -2.20399138892979, -2.25058992243427, -2.29749148286179,
-2.16856567860513, -1.93576601076367, -2.09190575790345, -1.98368936201681,
-2.10311255036163, -2.21887159162467, -2.26226743315126, -2.35633238493592,
-2.407018936, -2.34719820268328, -2.36613768370737, -2.30361375259329,
-2.05473632620086, -2.11665669129059), OLS_5 = c(-2.2911912568638,
-2.28123967681215, -2.29119683586224, -2.14805590207021, -2.28325670505768,
-2.27261386268403, -2.268006850245, -2.28322682471889, -1.84560662105751,
-0.576090713535621, -2.0945064647732, -2.0859234999636, -1.68828464788266,
-2.20368547406672, -2.18986194988925, -1.73587625378362, -1.72735189094969,
-0.385841816, -2.21101101562234, -2.28700200417098, -2.28696051646281,
-1.63411554699496, -2.28380625780731, -2.27896044246845, -2.19661244829441,
-2.18039652225164, -1.18146437845759, -1.6101070827248, -1.31682391434599,
-0.781364138557704, -1.89278224977018, -2.28683751979873, -2.28170279433502,
-2.25507742887343, -2.27469315563211, -2.19106352335337, -2.20216376634672,
-1.50940418054145, -1.57481865165838, -2.00915316980509, -1.94938461398854,
-1.98455653642811, -2.22145418758665, -2.1605019074557, -2.22929361026136,
-2.28754415075922, -2.28401553991566, -2.28099274980288, -2.2790962708342,
-2.25448944582185, -2.24095826297856, -2.28753886744317, -2.2790962708342,
-2.28249611688223, -2.29051254450738, -2.28856644852124, -2.29051401027405,
-2.28539476406181, -2.27754391464367, -2.28663199585719, -2.29003809100396,
-2.21974449731936, -2.26453458741267, -2.24273365564754, -2.0758820670505,
-2.05727208640147, -2.1075473897372, -2.18169509790509, -2.10183883759691,
-2.0941547862828, -2.17052540371127, -1.84552009498619, -2.11897925887711,
-2.2475539961602, -2.23266092019845, -2.26826235385205, -2.27716458812284,
-2.22875067319638, -2.20169236013157, -1.72209385129724, -0.476893951190187,
-1.44569200778405, -2.08830648613957, -2.13084935049209, -2.17358829667077,
-2.05592583172644, -1.84265559786228, -1.98577321824112, -1.88660772323127,
-1.99603456442263, -2.10189853669134, -2.14149931364702, -2.22701080101746,
-2.27258448425562, -2.21873931960315, -2.23587705524471, -2.17915915787995,
-1.95172754860073, -2.00843362344438), OLS_6 = c(-2.14615029819501,
-2.1274826763545, -2.14613692884822, -2.038363166, -2.14482079785526,
-2.13839956793073, -2.1352633011825, -2.14480554064275, -1.77137087834078,
-0.604458131512312, -1.92044345866761, -1.91142894340333, -1.5035051350835,
-2.03720410348948, -2.07364942604987, -1.67230210256299, -1.66457879312031,
-0.427523081653794, -2.09111249534671, -2.1358169999572, -2.13575175544593,
-1.44873737433719, -2.14509683128765, -2.12442374236989, -2.02946586195686,
-2.01185030632841, -0.994510606111227, -1.42450007218492, -1.12983335353955,
-0.596198212559954, -1.7115906309286, -2.13555900800151, -2.12811588444992,
-2.09509015766854, -2.11889016916752, -2.02341958358771, -2.03553614239934,
-1.32305159796573, -1.38891263096519, -1.83141440901763, -1.76969899713653,
-1.80596583024281, -2.05682837956465, -1.99043348930533, -2.06558998487816,
-2.14664801486533, -2.13135448546891, -2.1271468279034, -2.14250449627423,
-2.12545741758249, -2.11509475538252, -2.1466464083569, -2.14250449627423,
-2.14442504670383, -2.14684049810003, -2.13838680613343, -2.1468398441846,
-2.14583791450693, -2.14156460788614, -2.14633891192499, -2.14114136796206,
-2.05492693125432, -2.10632999229998, -2.08080895764288, -1.90090288083161,
-1.88144765246016, -1.93417313784094, -2.01325520240903, -1.9281579797124,
-1.92007377040746, -2.00120005643771, -1.66327168223962, -1.94624457366434,
-2.08634430885867, -2.06937728900294, -2.11086434271986, -2.12206882778948,
-2.06498074945642, -2.03501978622706, -1.5377512452434, -0.29431817292714,
-1.25902518147068, -1.91393009686737, -1.95881793980313, -2.00449939786682,
-1.88004274517372, -1.66034827254381, -1.80722288608151, -1.70526848086161,
-1.81783189921089, -1.92822084254891, -1.97013652098612, -2.0630309651189,
-2.1162243283256, -2.0538104595074, -2.07300962091288, -2.0105124912345,
-1.7721107506457, -1.83066883021211)), .Names = c("Y", "X", "Null",
"OLS_1", "OLS_2", "OLS_3", "OLS_4", "OLS_5", "OLS_6"), row.names = c(NA,
99L), class = "data.frame")
</code></pre>
<p>My scatter plot will consist of the first column (Y) and the second column (X).</p>
<p>The third column i will not use.</p>
<p>From the fourth column are the curves that are fitted values of OLS regressions.</p>
<p>How do I include them using the <code>plot</code> function?</p>
<p>i am doing this, but its not working</p>
<pre><code>plot(data[,2],data[,1])
for(i in 4:9){
lines(data[,i])
}
</code></pre>
<p>What am i doing wrong?</p>
| <p>Basically you want</p>
<pre><code>data <- data[order(data$X), ] ## reordering so that `X` is increasing
plot(data$X, data$Y)
for (i in 4:9) {
lines(data$X, data[,i], col = i) ## remember to set `x-coordinates`
}
legend("topright", legend = names(data)[4:9], col = 4:9, lty = 1) ## add legend
</code></pre>
<p><a href="http://i.stack.imgur.com/iHsJ8.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/iHsJ8.jpg" alt="enter image description here"></a></p>
|
SQL query doesn't select the data that I need with 'where' conditions <p>I am trying to get the records from my database where studentID, and lessonDate are equal to specific results. The StudentID seems to work fine, but lessonDate does not. Because of date formats, I have converted all dates to strings to be put into the database. I have set up database file so that the field is text field. I am trying to get the lesson name and rating that a student got for all exercises that they performed on a particular date. Database diagram: <a href="https://docs.google.com/drawings/d/16IqlDN2iqzVCeaUUGgeCe1R98yhUI7vQswH0tK39cAk/edit?usp=sharing" rel="nofollow">https://docs.google.com/drawings/d/16IqlDN2iqzVCeaUUGgeCe1R98yhUI7vQswH0tK39cAk/edit?usp=sharing</a></p>
<p>I am certain that the StudentID is correct, as I use it in other parts of this function. I am certain that the date is correct, as the 'date' variable used in the 4th line results in the correct output written to the file, and I originally had the date in the SQL query as this variable, but it didn't work. I have tried printing the lessons where this student is the foreign key, and the date is '8-10-2016'. I really have no idea why this is happening. Any suggestion or hypothesis from anyone would be greatly appreciated.</p>
<pre><code>template = ("{0:50}{1:50} \n")
print(lessonDateSet)
for date in list(lessonDateSet):
target.write("Lesson date: {} \n".format(date))
target.write("\n")
target.write(template.format("Exercise name:","rating:"))
self.cur.execute("""SELECT b.roadExerciseName, a.rating
FROM lessonExercises a LEFT JOIN roadExerciseInfo b ON a.roadExerciseID=b.roadExerciseID
LEFT JOIN lessons c ON c.lessonID=a.lessonID WHERE c.StudentID = {0} AND c.lessonDate = {1}""".format(studentInfo[0][0],"8-10-2016"))
fetch = self.cur.fetchall()
print(fetch, "fetch")
</code></pre>
<p>'fetch' is an empty list. after this.
I have double and tripple checked my data. my data is definitely correct.</p>
| <p>Your parameters are not being quoted correctly.</p>
<p>This is why you should not use string interpolation to add data into your queries. You should use the db-api's parameter substitution instead:</p>
<pre><code>self.cur.execute("""SELECT b.roadExerciseName, a.rating
FROM lessonExercises a LEFT JOIN roadExerciseInfo b ON a.roadExerciseID=b.roadExerciseID
LEFT JOIN lessons c ON c.lessonID=a.lessonID
WHERE c.StudentID = ? AND c.lessonDate = ?""",
[studentInfo[0][0], "8-10-2016"])
</code></pre>
|
Find element and see if its active/hasClass <p>I am trying to access a button in my leaflet map. The button is created using a plugin "easy-button".
My main goal is to see if the button has been clicked (is active), I will use it for validation in another function, not shown here. </p>
<p>This is how the html for the button looks like in the browser debugger (I believe the html is created by the plugin?).</p>
<p>Before it's clicked</p>
<pre><code><button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">
<span class="button-state state-add-markers add-markers-active">
<span class="fa fa-crosshairs fa-lg"></span>
</span>
</button>
</code></pre>
<p>After it's clicked</p>
<pre><code><button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">
<span class="button-state state-remove-markers remove-markers-active">
<span class="fa fa-undo"></span>
</span>
</button>
</code></pre>
<p>This click function access the button and show 'Button was clicked' but the if statement does not pass. I got to the button using Copy CSS path in the browser, but it seem really long.</p>
<pre><code>$("div.leaflet-bar.easy-button-container.leaflet-control > button > span").click(function(){
alert("Button was clicked");
if
($('span').hasClass('fa fa-crosshair fa-lg'))
{
alert('My button has active class')
}
});
</code></pre>
<p>Any advice on what I am doing wrong?</p>
| <p>This</p>
<pre><code>if($('span').hasClass('fa fa-crosshair fa-lg'))
</code></pre>
<p>Will not target the <code>span</code> you are expecting it to.</p>
<p>You wanted</p>
<pre><code>if($('span',this).hasClass('fa fa-crosshair fa-lg'))
</code></pre>
<p>To target the child span of the span you clicked on</p>
|
Design a multi client - server application, where client send messages infrequent <p>I have to design a server which can able to send a same objects to many clients. clients may send some request to the server if it wants to update something in the database. </p>
<p>Things which are confusing:</p>
<ol>
<li><p>My server should start the program (where I perform some operation and produce 'results' , this will be send to the client).</p></li>
<li><p>My server should listen to the incoming connection from the client, if any it should accept and start sending the âresultsâ. </p></li>
<li><p>Server should accept as many clients as possible (Not more than 100). </p></li>
<li><p>My âresult' should be secured. I donât want some one take my âresult' and see what my program logics look like. </p>
<p>I thought point 1. is one thread. And point 2. is another thread and it going to create multiple threads within its scope to serve point 3. Point 4 should be taken by my application logic while serialising the 'result' rather the server.</p>
<p>Is it a bad idea? If so where can i improve?</p></li>
</ol>
<p>Thanks</p>
| <p>Putting every connection on a thread is very bad, and is apparently a common mistake that beginners do. Every thread costs about 1 MB of memory, and this will overkill your program for no good reason. I did ask the very same question before, and I got <a href="http://stackoverflow.com/questions/31503638/c-boost-asio-start-ssl-server-session-in-a-new-thread">a very good answer</a>. I used boost ASIO, and the server/client project is finished since months, and it's a running project now beautifully.</p>
<p>If you use C++ and SSL (to secure your connection), no one will see your logic, since your programs are compiled. But you have to write your own communication protocol/serialization in that case.</p>
|
npm not finding a js file <p>Im making a little angular2 app, which uses the ng2-slugify package, and for some reason it doesn't find one of the slugify required files which is in the same folder (The file name is charmaps.js, and it's there 100%).</p>
<p><a href="http://i.stack.imgur.com/zutVV.png" rel="nofollow"><img src="http://i.stack.imgur.com/zutVV.png" alt="enter image description here"></a></p>
<p>The file is being imported like this, which seems to work for every other single file in the project, which includes files I've made myself, hence why I don't understand why it doesn't work.</p>
<p><code>import { Charmaps } from './charmaps';</code></p>
<p>I've tried using relative and absolute paths in the imports, adding it to the systemjs.config.js, but nothing.</p>
<p>One of the things that I've noticed when I run npm start is that when it gives the 404 code on the npm output on the console, it lists it as charmaps, and not charmaps.js like the rest of the files, which I find odd, because even when I map it in the systemjs as charmaps.js it still lists it as charmaps.</p>
<p>Anyway this is my first project from the groundup that uses node, so maybe there's something that's missing.</p>
<p><code>[1] 16.10.07 16:31:08 404 GET /node_modules/ng2-slugify/charmaps</code></p>
<p>This is the 404 on the npm output.</p>
<p><code>GET http://localhost:3000/node_modules/ng2-slugify/charmaps 404 (Not Found)</code></p>
<p>This is the error on the chrome console. Is there something I'm missing?</p>
| <p>You need to tell <strong>systemjs.config.ts</strong> to load <strong>slug</strong> module.</p>
<pre><code>map:{
"ng2-slugify": "node_modules/ng2-slugify/ng2-slugify.js"
}
</code></pre>
<p>Then,</p>
<pre><code>import {Slug} from 'ng2-slugify';
</code></pre>
|
Riak Search 2 not indexing bucket <p>I'm using Riak as a key-value store backend for a graph database implemented in Python.</p>
<p>I created a custom <a href="https://github.com/linkdd/link.graph/blob/master/etc/link/graph/schemas/node.xml" rel="nofollow">search schema</a> named <code>nodes</code>.
I created and activated a bucket type <code>nodes</code> with the <code>search_index</code> property set to <code>nodes</code> and the <code>datatype</code> property set to <code>map</code>.</p>
<p>I inserted the following data into the bucket <code>default</code> (with bucket type <code>nodes</code>):</p>
<pre><code>key: node1
value: {
"type_set": {"n1"},
"foo_set": {"bar", "baz"}
}
</code></pre>
<p><strong>NB:</strong> the data is automatically transformed into a Map datatype.</p>
<p>I can fetch the data correctly, but I tried the following fulltext searches and no document is returned:</p>
<pre><code>type_set:n1
type_set:*n1*
type_set:*
foo_set:*
_yz_rk:node1
_yz_rk:*
</code></pre>
<p>It seems that my document is not indexed.</p>
<p>I also tried to set the <code>search_type</code> property to <code>nodes</code> on the bucket <code>default</code>, but I got the same result.</p>
<p>The parameter <code>search</code> is set to <code>on</code> in the configuration file (<code>/etc/riak/riak.conf</code>) and the OpenJDK 7 is installed.</p>
<p>I have no idea what I'm doing wrong, if anyone can help me, thanks in advance.</p>
| <p>First, you should take into account that Riak automatically adds suffix <code>_set</code>, so that you don't have to name yours <code>type_set</code> but <code>type</code>. Otherwise you will have to query for <code>type_set_set:*</code> instead of <code>type_set:*</code>.</p>
<p>Second, according to <a href="https://docs.basho.com/riak/kv/2.0.0/developing/usage/searching-data-types/#data-type-schemas" rel="nofollow">Data Type Schemas</a>, embedded schemas (as opposed to top-level ones) must use dynamic fields. Apparently Riak prepends field names with some internal identifier of the top-level map. Unfortunately, this also means that you cannot index one set without indexing the other as well.</p>
<p>I've run some tests and found out that <code><dynamicField name="*_set" type="string" indexed="true" stored="true" multiValued="true"/></code> works fine, while <code><dynamicField name="*type_set" type="string" indexed="true" stored="true" multiValued="true"/></code> does not.</p>
|
Capybara: How to set files names and directory for save_and_open_page_path <p>I am trying to set the directory where all screens shots will be saved. Because currently it saves to the root folder, but I would like to save files (.img and .html) to another one folder. I tried to use</p>
<pre><code>CapybaraScreenshot.save_and_open_page_path = "../Reports"
</code></pre>
<p>or</p>
<pre><code>CapybaraScreenshot.save_and_open_page('../Reports')
</code></pre>
<p>But it still saves screenshots and .html files to root directory(((</p>
<p>Also may be it is possible to set screen shot name as TC name, because currently it is unclear which screen shot related to proper failed TC.</p>
<p>Here is my rails_helper.rb file:</p>
<pre><code>require 'test/unit'
require 'selenium-webdriver'
require 'capybara'
require 'rspec'
require "rails/all"
require 'capybara/rspec'
require "page-object"
require 'rspec/expectations'
require 'securerandom'
require '../Test_helpers/login_helper'
require 'capybara-screenshot/rspec'
require 'launchy'
RSpec.configure do |config|
config.include LoginHelper
config.include RSpec::Matchers
config.include Capybara::DSL
Selenium::WebDriver::Chrome.driver_path = '../Resources/chromedriver.exe'
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome)
end
config.after { |example_group| CapybaraScreenshot.save_and_open_page_path = '../Reports' if example_group.exception }
end
Capybara.default_max_wait_time = 15
</code></pre>
| <p>As documented in the capybara-screenshot README - <a href="https://github.com/mattheworiordan/capybara-screenshot#custom-screenshot-directory" rel="nofollow">https://github.com/mattheworiordan/capybara-screenshot#custom-screenshot-directory</a> and <a href="https://github.com/mattheworiordan/capybara-screenshot#custom-screenshot-filename" rel="nofollow">https://github.com/mattheworiordan/capybara-screenshot#custom-screenshot-filename</a> , you need to set Capybara.save_path (just specify it once, not in an after block) for the directory and use Capybara::Screenshot.register_filename_prefix_formatter to override the file name used</p>
|
How to control appearance of EditText box? <p>I intend to have an EditText box where a user can input data appear after a timer ends. To do this, I placed in in the onFinish section of my timer. This didn't work, because as soon as I access the screenview, the EditText box appears before the timer even starts (timer starts when a button is pressed). The box does go away when a user inputs their data and presses enter, as expected, but it appears before the timer even starts, which I do not want.</p>
<pre><code>new CountDownTimer(4000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
number.setVisibility(View.GONE);
final TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setText(" Enter the number");
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_ENTER:
Editable answer = input.getText();
input.setVisibility(View.GONE);
prompt.setVisibility(View.GONE);
if (answer.equals(loadG1)){
score[0]=+1;
}
return true;
default:
break;
}
}
return false;
}
});
}
}.start();
</code></pre>
<p>This is the only part of my program where the EditText box appears, thanks in advance for any help.</p>
| <p>As Justin said, you need to set the visibility of your EditText to android:visibility="gone"
in XML. You could get the reference of your EditText before the counter function and set input.setVisbility(View.GONE);</p>
<p>Just make sure this is done before the timer counts down to 0</p>
|
How can I keep the values in a column of 2 separate rows adjacent using the boostrap grid when they collapse? <p>I have a bootstrap grid that looks like this ( <a href="https://jsfiddle.net/h81jka6y/" rel="nofollow">jsfiddle</a> ):
<a href="http://i.stack.imgur.com/37CVR.png" rel="nofollow"><img src="http://i.stack.imgur.com/37CVR.png" alt="Wide Viewport"></a></p>
<p>When the columns collapse on a small viewport, it looks like this:
<a href="http://i.stack.imgur.com/vofmo.png" rel="nofollow"><img src="http://i.stack.imgur.com/vofmo.png" alt="enter image description here"></a></p>
<p>My desired output is this:</p>
<p><a href="http://i.stack.imgur.com/C5ifT.png" rel="nofollow"><img src="http://i.stack.imgur.com/C5ifT.png" alt="enter image description here"></a></p>
<p>I'm not sure what the best way is to make the columns stay together since bootstrap condenses them into individual rows</p>
<p>Code:</p>
<pre><code> <div class="list-group list-group-large list-group-background list-group-background-data settings">
<div class="list-group-header">
<div class="list-group-title">
<h3>Set Alerts</h3>
</div>
</div>
<div class="list-group list-group-large list-group-data">
<div class="top-row row">
<div class="col-md-3 col-sm-12"><span>Field</span></div>
<div class="col-md-3 col-sm-12"><span>Condition</span></div>
<div class="col-md-2 col-sm-12"><span>Value</span></div>
<div class="col-md-2 col-sm-12"><span>Units</span></div>
<div class="col-md-2 col-sm-12"><span>Save/Delete</span></div>
</div>
<div class="row" ng-repeat="alarm in alarms">
<div class="col-md-3 col-sm-12">
<select class="form-control">
<option>Roll</option>
<option>Pitch</option>
<option>Yaw</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control">
<option>is greater than</option>
<option>is less than</option>
</select>
</div>
<div class="col-md-2">
<input type="text">
</div>
<div class="col-md-2">
<span>deg</span>
</div>
<div class="col-md-2">
<button type="button"class="btn btn-success-outline">
<i class="fa fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
</code></pre>
| <p>You need to add </p>
<pre><code><label></label>
</code></pre>
<p>Checkout the JSFiddle below</p>
<p><a href="https://jsfiddle.net/sg05vdj8/1/" rel="nofollow">https://jsfiddle.net/sg05vdj8/1/</a></p>
|
VBA Type mismatch error on Do While ActiveCell.Value <> "" <p>Hey I've got code moving rows out to another sheet with the name of the cell, a loop until it hits a blank at the end of the data, an extract of the code here;</p>
<pre><code>Range("AF2").Select
Do While ActiveCell.Value <> ""
strDestinationSheet = ActiveCell.Value
ActiveCell.Offset(0, -31).Resize(1, ActiveCell.CurrentRegion.Columns.count).Select
Selection.Copy
Sheets(strDestinationSheet).Select
N = Cells(Rows.count, "AF").End(xlUp).Row
lastRow = N
Cells(lastRow + 1, 1).Select
Selection.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Sheets(strSourceSheet).Select
ActiveCell.Offset(0, 31).Select
ActiveCell.Offset(1, 0).Select
Loop
</code></pre>
<p>However while this part of the code worked fine before on the latest instance of running it now throws up an error on the second line Do While ActiveCell.Value <> "", saying type mismatch. I'm unsure of what's changed to stop this working suddenly, any ideas? Many thanks.</p>
| <p>I personally do not like Do Loops to iterate through a group of cells. I prefer the For Each loop.</p>
<p>Also as was stated by @bruceWayne, avoid using Select as is slows down the code.</p>
<p>Proper indentation makes the code easier to read and avoid simple mistakes.</p>
<pre><code>Dim cel As Range
With Sheets(strSourceSheet)
For Each cel In .Range("AF2", .Range("AF2").End(xlDown))
If Not IsError(cel) Then
strDestinationSheet = cel.Value
cel.Offset(0, -31).Resize(1, cel.CurrentRegion.Columns.Count).Copy
N = Sheets(strDestinationSheet).Cells(Sheets(strDestinationSheet).Rows.Count, "AF").End(xlUp).Row
Sheets(strDestinationSheet).Cells(N + 1, 1).PasteSpecial xlPasteValues
End If
Next cel
End With
</code></pre>
|
TFS / Visual Studio 2015 : how to compare file changes between 2 commits <p>We're currently testing git as source control for our new projects. We're using TFVC for many years and we're used to the way it works. So far, pretty much everything works as expected but there's something really simple I cannot figure out : in TFVC, it's really easy to get the list of files changed between 2 not consecutive commits :</p>
<p><a href="http://i.stack.imgur.com/tM9ov.png" rel="nofollow"><img src="http://i.stack.imgur.com/tM9ov.png" alt="Commit history TFVC"></a></p>
<p><a href="http://i.stack.imgur.com/8WITI.png" rel="nofollow"><img src="http://i.stack.imgur.com/8WITI.png" alt="Files changed between 2 commits"></a></p>
<p>But I found no way to do this with a git repository in VS2015 or with the web interface of TFS2015 update 2 : </p>
<p><a href="http://i.stack.imgur.com/z6EeD.png" rel="nofollow"><img src="http://i.stack.imgur.com/z6EeD.png" alt="Commit history git"></a></p>
<p>I only can compare a commit with his parent commit :</p>
<p><a href="http://i.stack.imgur.com/0kLOW.png" rel="nofollow"><img src="http://i.stack.imgur.com/0kLOW.png" alt="git compare to parent commit"></a></p>
<p>I also found a way to compare an individual file between 2 commits but not the whole repository :</p>
<p><a href="http://i.stack.imgur.com/L7T6m.png" rel="nofollow"><img src="http://i.stack.imgur.com/L7T6m.png" alt="git compare individual file between commits"></a></p>
<p>Is it just me not looking at the right place and if not, why such a basic feature is not implemented ? It's the kind of operation we use daily for review or bug hunting. </p>
<p>I know there's other ways with external tools (GUI and command line) to achieve that but I would want to stay is VS/TFS as much as possible to reduce friction for everybody in the team.</p>
<p>Thanks. </p>
| <p>The reason for this is that git is designed around many different branches and combining them back into coherent code, while tfvc is designed around having a coherent history of modifications. If you develop a project with enough collaborators using git, you will have a branch that starts at one commit on the main branch, and, while it is being developed, more commits are made on the main branch. That branch's last commit can be modified to fit the code on the main branch, or the branch can be modified starting at its first commit to look like it was branched off the latest commit in the main branch. The second scenario is called rebasing, and it's what makes it hard to have a coherent history of modifications in git. </p>
|
Apache POI - reading modifies excel file <p>Whenever I open a excel file using the Apatche POI the file gets modified, even though I'm just reading the file and not making any modification.</p>
<p>Take for instance such test code.</p>
<pre><code>public class ApachePoiTest {
@Test
public void readingShouldNotModifyFile() throws Exception {
final File testFile = new File("C:/work/src/test/resources/Book2.xlsx");
final byte[] originalChecksum = calculateChecksum(testFile);
Assert.assertTrue("Calculating checksum modified file",
MessageDigest.isEqual(originalChecksum, calculateChecksum(testFile)));
try (Workbook wb = WorkbookFactory.create(testFile)) {
Assert.assertNotNull("Reading file with Apache POI", wb);
}
Assert.assertTrue("Reading file with Apache POI modified file",
MessageDigest.isEqual(originalChecksum, calculateChecksum(testFile)));
}
@Test
public void readingInputStreamShouldNotModifyFile() throws Exception {
final File testFile = new File("C:/work/src/test/resources/Book2.xlsx");
final byte[] originalChecksum = calculateChecksum(testFile);
Assert.assertTrue("Calculating checksum modified file",
MessageDigest.isEqual(originalChecksum, calculateChecksum(testFile)));
try (InputStream is = new FileInputStream(testFile); Workbook wb = WorkbookFactory.create(is)) {
Assert.assertNotNull("Reading file with Apache POI", wb);
}
Assert.assertTrue("Reading file with Apache POI modified file",
MessageDigest.isEqual(originalChecksum, calculateChecksum(testFile)));
}
private byte[] calculateChecksum(final File file) throws Exception {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
try (InputStream is = new FileInputStream(file)) {
final byte[] bytes = new byte[2048];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
md.update(bytes, 0, numBytes);
}
return md.digest();
}
}
}
</code></pre>
<p>Test <code>readingShouldNotModifyFile</code> always fails, because the file gets always modified by Apache POI. More to it when testing on a blank excel file freshly created with MS Office, Apache POI cuts the file from 8.1 kb to 6.2 kb and corrupts the file.</p>
<p>Tested with:</p>
<pre><code><dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
</code></pre>
<p>and also with version 3.12</p>
<p>Can I prevent Apache POI from modifying my files by other means then passing <code>InputStream</code> instead of <code>File</code>. I don't want to pass <code>InputStream</code> because I'm concerned about Apache's warning that it takes more memory and has some specific requirements to the <code>InputStream</code>.</p>
| <p>Your problem is that you're not passing in the readonly flag, so Apache POI is defaulting to opening the file read/write.</p>
<p>You need to use the <a href="http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html#create(java.io.File,%20java.lang.String,%20boolean)" rel="nofollow">overloaded WorkbookFactory.create method which takes a readonly flag</a> + set that readonly flag to true</p>
<p>Change the line</p>
<pre><code>try (InputStream is = new FileInputStream(testFile); Workbook wb = WorkbookFactory.create(is)) {
</code></pre>
<p>to</p>
<pre><code>try (IWorkbook wb = WorkbookFactory.create(testFile,null,true)) {
</code></pre>
<p>and your file will be opened read-only with no changes</p>
|
Type mismatch error returned due to different type of messages being returned in Mule <p>I have a Mule workflow that can either receive a response message or an business error message as input into the transform message connector.</p>
<p>When it moves from the transform message connector to object to string it hits this error:</p>
<pre><code>ERROR 2016-10-07 18:08:40,187 [[userprocess].userprocess-httpListenerConfig.worker.01] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Exception while executing:
}) when ((payload[0].userResponse != null and payload[0].userResponse.category == "SUCCESS")) and
^
Type mismatch
found :name, :string
required :name, :object
Type : com.mulesoft.weave.mule.exception.WeaveExecutionException
Code : MULE_ERROR--2
********************************************************************************
Exception stack is:
1. Type mismatch
found :name, :string
required :name, :object (com.mulesoft.weave.engine.ast.dynamic.DynamicDispatchException)
com.mulesoft.weave.engine.ast.dynamic.DynamicDispatchNode:65 (null)
2. Exception while executing:
}) when ((payload[0].userResponse != null and payload[0].userResponse.category == "SUCCESS")) and
^
Type mismatch
found :name, :string
required :name, :object (com.mulesoft.weave.mule.exception.WeaveExecutionException)
com.mulesoft.weave.mule.WeaveMessageProcessor$WeaveOutputHandler:166 (null)
********************************************************************************
Root Exception stack trace:
com.mulesoft.weave.engine.ast.dynamic.DynamicDispatchException: Type mismatch
found :name, :string
required :name, :object
</code></pre>
<p>I think it is because when the message is processed by transform message it performs logic based on different fields so what I need to do to fix this is to ignore any response message logic if a business error message is returned and vice versa.</p>
<p>How can I do this? </p>
<p>Dataweave code (JSON to XML): </p>
<pre><code>%dw 1.0
%output application/xml
---
{
(Data: {
userId: flowVars.queryParams.userId,
Message: "User created successfully"
}) when (payload[0].userResponse.category == "SUCCESS") and
(payload[1].userResponse.category == "SUCCESS"),
(Exception: {
userId: flowVars.queryParams.userId,
Message: payload[1].exception.message
}) when (payload.exception?) and
(payload[1].exception.action == "createUser") and
(payload[0].exception.code != "-1"),
(Exception: {
userId: flowVars.queryParams.userId,
Message: payload[0].exception.message
}) when (payload.exception?) and
(payload[0].exception.action == "amendUser") and
(payload[1].exception.replyStatus.code != "-1"),
}
</code></pre>
| <p>You can use when/otherwise in this situation. You were close, just use <em>{</em> and <em>}</em> instead of parens. Something along the lines of:</p>
<pre><code>%dw 1.0
%input payload application/json
%output application/xml
---
{
Data: {
userId: flowVars.queryParams.userId,
Message: "User created successfully"
}
}
when (payload[0].userResponse.category == "SUCCESS") and
(payload[1].userResponse.category == "SUCCESS"))
otherwise
{
Exception: {
userId: flowVars.queryParams.userId,
Message: payload[1].exception.message
}
}
</code></pre>
|
http get request returns different values in curl than it does in ionic2/angular2 <p>When I do a get request with curl like this:</p>
<pre><code>curl https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token
</code></pre>
<p>I am returned the correct information:</p>
<pre><code>{"totalRows":2,"data":[{"__metadata":{"id":"1","fields":{"id":{"type":"int","unique":true},"content":{"type":"string"}},"descriptives":{},"dates":{}},"id":1,"content":"the first todo!"},{"__metphilipphpphilipphilip"}]}
</code></pre>
<p>but when I do the same request in angular 2 like this:</p>
<pre><code>this.http.get('https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token').map(res => {
return res.json();
});;
</code></pre>
<p>I am returned a strange object called observable that looks something like this:</p>
<p><a href="http://i.stack.imgur.com/08Pce.png" rel="nofollow"><img src="http://i.stack.imgur.com/08Pce.png" alt="enter image description here"></a></p>
<p>Why isn't the request working in angular?</p>
| <p>I know nothing about Curl, but HTTP calls in Angular 2 return <strong>observables</strong>, so you need to use RxJS methods to operate on them. In order to get the response, you need to subscribe to it so that you can <em>observe</em> values that are returned.</p>
<pre><code> this.http.get('https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token')
.map(res => res.json())
.subscribe(
data => this.myData = data,
err => this.logError(err),
() => console.log('Request Complete')
);
</code></pre>
|
Form submission doesn't work - PHP <p>I'm working on a form validation and I'm currently doing some debugging on my code. I'll insert the necessary code snippets below:</p>
<p>Form code:</p>
<pre><code>echo '<h1> Seismic Recording </h1>
<div>
<form action="validate2.php" method="POST">';
echo "Latitude: <input type='text' name='latitude'>";
echo "Longitude: <input type='text' name='longitude'required>";
echo 'Wave Type: <select id="wave_type" name="wave_type" required>
<option selected value="s">S</option>
<option value="p">P</option>
<option value="surface_wave">Surface Wave</option>
</select>';
echo "Wave Value: <input type='text' name='wave_value' required>";
echo 'Upload CSV File: <input type="file" name="file">';
echo " <input type='submit' name='submit' value='submit'>";
echo "</form>
</div> ";
</code></pre>
<p>Validation code:</p>
<pre><code>echo "w";
if (isset($_POST['submit'])) {
echo "t";
$latitude = $_POST['latitude'];
if ($latitude == NULL) {
echo "Please insert a latitude . <br>";
$error = $error + 1;
}
}
echo "q";
</code></pre>
<p>The form validations that I've put within the if statement doesn't work. I tried debugging the code by inserting the 'echo "q"' and 'echo "w"' to see where the problem lies. Those statements work (they output the characters). But the 'echo "t"' within the if statement doesn't work. Why is that so?</p>
<p>Result of var_dump($_POST):</p>
<blockquote>
<p>array(5) { ["latitude"]=> string(0) "" ["longitude"]=> string(1) "g"
["wave_type"]=> string(1) "s" ["wave_value"]=> string(1) "g"
["file"]=> string(0) "" }</p>
</blockquote>
<p>My issue isn't so much in getting the latitude to validate but why doesn't the 'echo t' work?</p>
| <p>Why check for a 'submit' post variable when you're working with latitude?</p>
<pre><code>if(isset($_POST['latitude']))
{
echo "t";
$latitude=$_POST['latitude'];
}
else
{
echo "Please insert a latitude . <br>";
$error = $error + 1;
}
</code></pre>
<p>Also there is no need for a name on the submit button</p>
<pre><code><input type="submit" value="Submit">
</code></pre>
|
Unable to set context when rendering child components <p>I'm trying to test a custom <a href="https://github.com/callemall/material-ui" rel="nofollow">Material-ui</a> React component with Enzyme but getting the following error:</p>
<p><code>ERROR: 'Warning: Failed context type: Required context 'muiTheme' was not specified in 'ChildComponent'.</code></p>
<p>What I've tried is to set a context according to <a href="http://stackoverflow.com/questions/38264715/how-to-pass-context-down-to-the-enzyme-mount-method-to-test-component-which-incl">this</a>. The component that I want to reach and test is a child component.</p>
<pre><code>const root = shallow(<RootComponent />, {context: {muiTheme}, childContextTypes: {muiTheme: React.PropTypes.object}})
const child = root.find(ChildComponent)
child.render() // <--- this line is throwing the error
</code></pre>
<p>update: <a href="https://github.com/callemall/material-ui/issues/5330" rel="nofollow">this is related</a></p>
| <p>I'm not sure this is the solution but it's one step closer to the goal.</p>
<pre><code>const root = mount(<RootComponent />, {
context: {muiTheme},
childContextTypes: {muiTheme: React.PropTypes.object}
})
const child = root.find(ChildComponent)
</code></pre>
<p>Notice, I use <code>mount</code> instead of <code>shallow</code>. The issue is with this I can't use <code>child.find({prop: 'value'})</code> any longer - return 0 items...</p>
|
How to adjust web layout along with header, navigation etc to maximum width using css? <p>As I was looking at websites, I've noticed that when you zoom out in your browser. The design of the header, navigation, content area and footer expands along with the layout. I've also found out that most of the website follow that model like pcworld, microsoft, facebook etc. Just like example below:</p>
<p><strong>This is Zoom 100%:</strong>
<a href="http://i.stack.imgur.com/NyQfI.png" rel="nofollow"><img src="http://i.stack.imgur.com/NyQfI.png" alt="enter image description here"></a></p>
<p><strong>Then, this is Zoom 50%. Notice how the header and navigation also expands:</strong></p>
<p><a href="http://i.stack.imgur.com/g0QDR.png" rel="nofollow"><img src="http://i.stack.imgur.com/g0QDR.png" alt="enter image description here"></a></p>
<p><strong>Rather than this one, which is boxed and you can see alot of these in tutorials:</strong></p>
<p><a href="http://i.stack.imgur.com/iJ7xU.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJ7xU.png" alt="enter image description here"></a></p>
<p><strong>I would like to know how to do it by providing an example of how to write it in css, similar to techcrunch website is highly appreciated.</strong></p>
| <p>I assume you are talking about responsive web design </p>
<p><a href="http://www.w3schools.com/html/html_responsive.asp" rel="nofollow">http://www.w3schools.com/html/html_responsive.asp</a></p>
<p><a href="https://www.youtube.com/watch?v=BIz02qY5BRA" rel="nofollow">https://www.youtube.com/watch?v=BIz02qY5BRA</a>
(I learned a lot from here)</p>
<p>This basiclly makes the website respond to the window/device size. You can do this by making a website then using media queries. For example</p>
<p>Html file</p>
<pre><code><p class="color"> Hello </p>
</code></pre>
<p>CSS file</p>
<pre><code>color {color: blue;}
@media only screen and (min-width: 800px) {
color {color: red;}
}
</code></pre>
<p>This would make it so when the width of device/window will reach 800px it will change "Hello" to red instead of blue.
But this is just a small example, you can do much more after knowing the basics!</p>
|
Redirecting output of a script to a file as a background job does not output anything <p>I have a line:</p>
<p><code>RAILS_ENV=production bundle exec rake mentions:stream > mention.log</code></p>
<p>It outputs text to <code>mention.log</code> file.</p>
<p>When I try to run it as background job:</p>
<p><code>RAILS_ENV=production bundle exec rake mentions:stream > mention.log &</code></p>
<p>it does not output anything to this file.</p>
<p>Can someone explain me why ?</p>
| <p>have you tried to run it while its part of a script:</p>
<p>a_script:</p>
<pre><code>RAILS_ENV=production bundle exec rake mentions:stream > mention.log
</code></pre>
<p>then run:</p>
<pre><code>a_script &
</code></pre>
|
Wordpress: Strange permission issue <p>all I struggle with one permission problem with my wordpress.
As you can see </p>
<pre><code>ls -la wp-content/themes/impreza/
total 144
drwxr-xr-x 9 root root 4096 Oct 7 16:49 .
drwxr-xr-x 4 root root 4096 Oct 7 11:21 ..
-rwxr-xr-x 1 root root 330 Oct 7 10:33 404.php
-rwxr-xr-x 1 root root 340 Oct 7 10:33 archive.php
-rwxr-xr-x 1 root root 339 Oct 7 10:33 author.php
-rwxr-xr-x 1 root root 349 Oct 7 10:33 comments.php
drwxr-xr-x 2 root root 4096 Oct 7 16:48 config
drwxr-xr-x 2 root root 4096 Oct 7 10:33 css
drwxr-xr-x 10 root root 4096 Oct 7 10:33 demo-import
-rwxr-xr-x 1 root root 337 Oct 7 10:33 footer.php
-rwxr-xr-x 1 root root 355 Oct 7 10:33 forum.php
drwxr-xr-x 15 root root 4096 Oct 7 10:34 framework
drwxr-xr-x 3 root root 4096 Oct 7 10:34 functions
-rwxr-xr-x 1 root root 1105 Oct 7 10:33 functions.php
-rwxr-xr-x 1 root root 337 Oct 7 10:33 header.php
-rwxr-xr-x 1 root root 359 Oct 7 10:33 header-shop.php
-rwxr-xr-x 1 root root 361 Oct 7 10:33 index.php
drwxr-xr-x 2 root root 4096 Oct 7 10:33 js
-rwxr-xr-x 1 root root 325 Oct 7 10:33 page.php
-rwxr-xr-x 1 root root 18970 Oct 7 10:33 screenshot.png
-rwxr-xr-x 1 root root 388 Oct 7 10:33 searchform.php
-rwxr-xr-x 1 root root 344 Oct 7 10:33 search.php
-rwxr-xr-x 1 root root 645 Oct 7 10:33 single.php
-rwxr-xr-x 1 root root 365 Oct 7 10:33 single-us_portfolio.php
-rwxr-xr-x 1 root root 288 Oct 7 10:33 style.css
-rwxr-xr-x 1 root root 15056 Oct 7 16:49 us-logo.png
drwxr-xr-x 3 root root 4096 Oct 7 10:34 vendor
-rwxr-xr-x 1 root root 4341 Oct 7 10:33 wpml-config.xml
</code></pre>
<p>in my themes folder everything is with equals permissions but I can't access them all. For example </p>
<p>NOT VISIBLE - <a href="http://www.aniabuchi.com/wp-content/themes/impreza/us-logo.png" rel="nofollow">http://www.aniabuchi.com/wp-content/themes/impreza/us-logo.png</a></p>
<p>VISIBLE - <a href="http://www.aniabuchi.com/wp-content/themes/impreza/screenshot.png" rel="nofollow">http://www.aniabuchi.com/wp-content/themes/impreza/screenshot.png</a></p>
<p>The theme itself has activeted, but when I've try to active the plugins it say also "Please adjust file permissions to allow plugins installation".
This is my second wordpress installation and the only difference I've made is to use only one wp-contents folder </p>
<pre><code>/* Default value for some constants if they have not yet been set
by the host-specific config files */
if (!defined('ABSPATH'))
define('ABSPATH', '/var/www/aniabuchi/');
if (!defined('WP_CORE_UPDATE'))
define('WP_CORE_UPDATE', false);
define('DB_HOST', 'localhost');
if (!defined('WP_CONTENT_DIR') && !defined('DONT_SET_WP_CONTENT_DIR'))
define('WP_CONTENT_DIR', '/var/www/aniabuchi/wp-content');
</code></pre>
| <ol>
<li><p>try to make images 777 to see if you can access them.</p></li>
<li><p>for plugin, you should check your "wp-content/plugins" folder permission, not themes.</p></li>
</ol>
|
Dockerfile: Permission denied during build when running ssh-agent on /tmp <p>So I'm trying to create an image, which adds a SSH private key to /tmp, runs ssh-agent on it, does a git clone and then deletes the key again.</p>
<p><a href="http://blog.cloud66.com/pulling-git-into-a-docker-image-without-leaving-ssh-keys-behind/" rel="nofollow">This is the idea I'm trying to accomplish</a></p>
<p>Dockerfile:</p>
<pre><code>FROM node:4.2.4
MAINTAINER Me
CMD ["/bin/bash"]
ENV GIT_SSL_NO_VERIFY=1
ENV https_proxy="httpsproxy"
ENV http_proxy="httpproxy"
ENV no_proxy="exceptions"
ADD projectfolder/key /tmp/
RUN ssh-agent /tmp
WORKDIR /usr/src/app
RUN git clone git@gitlab.private.address:something/target.git
RUN rm /tmp/key
WORKDIR /usr/src/app/target
RUN npm install
EXPOSE 3001
</code></pre>
<p>Now the problem lies within the build-process. I use the following command to build:</p>
<pre><code>docker build -t samprog/targetimage:4.2.4 -f projectfolder/dockerfile .
</code></pre>
<p>The layers up to "ADD projectfolder/key /tmp/" work just fine, though the "RUN ssh-agent /tmp" layer doesn't want to cooperate.</p>
<p>Error code:</p>
<pre><code>Step 9 : RUN ssh-agent /tmp/temp
---> Running in d2ed7c8870ae
/tmp: Permission denied
The command '/bin/sh -c ssh-agent /tmp' returned a non-zero code: 1
</code></pre>
<p>Any ideas? Since I thought it was a permission issue, where the directory was already created by the parent image, I created a /tmp/temp and put the key in there. Doesn't work either, same error.</p>
<p>I'm using Docker version 1.10.3 on SLES12 SP1</p>
| <p>I did it. What I did is, I got rid of ssh-agent. I simply copied the <code>~/.ssh</code>- directory of my docker-host into the <code>/root/.ssh</code> of the image and it worked. </p>
<p>Do not use the <code>~</code> though, copy the <code>~/.ssh</code>-directory inside the projectfolder first and then with the dockerfile inside the container.</p>
<p>Final dockerfile looked as follows:</p>
<pre><code>FROM node:4.2.4
MAINTAINER me
CMD["/bin/bash"]
ENV GIT_SSL_NO_VERIFY=1
ENV https_proxy="httpsproxy"
ENV http_proxy="httpproxy"
ENV no_proxy="exceptions"
ADD projectfolder/.ssh /root/.ssh
WORKDIR /usr/src/app
RUN git clone git@gitlab.private.address:something/target.git
RUN rm -r /root/.ssh
WORKDIR /urs/src/app/target
RUN npm set registry http://local-npm-registry
RUN npm install
EXPOSE 3001
</code></pre>
<p>The dockerfile still has to be improved on efficiency and stuff, but it works! Eureka!</p>
<p>The image now has to be squashed and it should be safe to use, though we only use it in our local registry.</p>
|
NSNotification for all views at once <p>I am trying to <code>addObserver</code> to all my views, when I start my application.
When there is a post coming I want to display a Modal View on top of the current <code>ViewController</code>.</p>
<p>Is there a way to install it directly on every View or do I need to do the</p>
<pre><code>viewWillAppear : add
viewDidDisappear : remove
</code></pre>
<p>workaround each time ?</p>
| <ol>
<li>You could have created one superclass for all you view controllers and override viewWillAppear/viewDidDisappear there.</li>
<li>If there is no exception and you want to present a modal view controller no matter what view controller is currently on screen, you can present it over self.window.rootViewController in AppDelegate's didReceiveRemoteNotification method.</li>
</ol>
|
WSO2 MB an exception after admin psw change <p>I tried to make a production set up (WSO2 MB 3.1.0 and WSO2 ESB 4.9.0) on the same VM.
in order to secure my production environment I changed the default admin psw for the admin user to more secure one. At the same time I created a new MB user (ESB) which I used as "a technical user" in ESB jndi.properties </p>
<p>when I restarted my server I started receiving the following exception in the ESB which tried to connect to the MB:
[2016-10-07 16:47:31,427] ERROR - AMQStateManager Notifying Waiters([org.wso2.andes.client.state.StateWaiter@654a6148]) for error:not allowed
[2016-10-07 16:47:31,427] INFO - AMQConnection Unable to connect to broker at tcp://localhost:5673
org.wso2.andes.client.AMQAuthenticationException: not allowed [error code 530: not allowed]
at org.wso2.andes.client.handler.ConnectionCloseMethodHandler.methodReceived(ConnectionCloseMethodHandler.java:79)
at org.wso2.andes.client.handler.ClientMethodDispatcherImpl.dispatchConnectionClose(ClientMethodDispatcherImpl.java:192)
at org.wso2.andes.framing.amqp_0_91.ConnectionCloseBodyImpl.execute(ConnectionCloseBodyImpl.java:140)
at org.wso2.andes.client.state.AMQStateManager.methodReceived(AMQStateManager.java:111)
at org.wso2.andes.client.protocol.AMQProtocolHandler.methodBodyReceived(AMQProtocolHandler.java:517)</p>
<p>I back-traced the problem to the change of the ADMIN psw. When I set it back to the default ADMIN:ADMIN all is working again fine.</p>
<p>any idea why? apparently the psw is not changed on all the places
I followed this article <a href="https://docs.wso2.com/display/MB220/Changing+User+Passwords" rel="nofollow">https://docs.wso2.com/display/MB220/Changing+User+Passwords</a><br>
my configuration xmls does not contain the admin psw however.</p>
<p>thank you very much in advance.</p>
| <p>AFAIU, Following are the steps you have followed.</p>
<ol>
<li>Changed MB default username/password.</li>
<li>Created new user("a technical user") in MB and add these username/password in ESB "jndi.properties" file.</li>
<li>Restarted servers and ESB start throwing auth exceptions.</li>
</ol>
<p>Things would have gone wrong(at least what I can think of) is as follows :</p>
<ol>
<li>Somehow you have entered spaces in middle of the username "a technical user"(even it's validated in MB management console)
Solution : Don't use spaces in of usernames.</li>
<li><p>Even you have created a new user in MB(and added it correctly in jndi.properties file in ESB) you haven't assigned a role which have permission to subscribe to a topic/queue. (This is what most likely you have messed up :)) </p>
<p>If you haven't assigned a role which has subscribe permissions to queues/topics ESB won't be able to subscribe with given credentials during transport startup which leads to authentication exceptions. </p>
<p>MB has a role based permission model and if you haven't assigned a user to a role with sufficient permissions user won't be able to authenticate to MB. To verify this theory you can assign "admin" role to newly created user from MB management console under("
Home > Configure > Accounts & Credentials > Users and Roles > Users") and restart ESB server.
Please go through following documentations[1] carefully for more permission/users/user roles related information.</p>
<p>[1]
<a href="https://docs.wso2.com/display/MB310/Managing+Queues" rel="nofollow">https://docs.wso2.com/display/MB310/Managing+Queues</a></p>
<p><a href="https://docs.wso2.com/display/MB310/Configuring+Users" rel="nofollow">https://docs.wso2.com/display/MB310/Configuring+Users</a></p>
<p><a href="https://docs.wso2.com/display/MB310/Role-Based+Permissions" rel="nofollow">https://docs.wso2.com/display/MB310/Role-Based+Permissions</a></p></li>
</ol>
|
API (curl)Command to Approve a promoted build Job in Jenkins <p>Is there any way can an Approver approve a specific build using curl command?</p>
<p>I am using Promoted Builds Plugin for manual approval for builds. </p>
<p>when i am trying below curl command it is giving "Error 400 Nothing is submitted". I searched everywhere but couldn't get proper answer. Please help</p>
<p>curl <a href="http://admin:XXXXXXXXXXXX@JENKINS_URL/job/JOB_NAME/129/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve?token=abcde1234" rel="nofollow">http://admin:XXXXXXXXXXXX@JENKINS_URL/job/JOB_NAME/129/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve?token=abcde1234</a></p>
<p>When i tried to pass JSON data, It is throwing "Error 403 No valid crumb was included in the request"</p>
<p>the command is
curl <a href="http://admin:XXXXXXXXXXXX@JENKINS_URL/job/JOB_NAME/129/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve?token=abcde1234" rel="nofollow">http://admin:XXXXXXXXXXXX@JENKINS_URL/job/JOB_NAME/129/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve?token=abcde1234</a> --data-urlencode json='{&Submit=Approve}'</p>
<p>I followed this <a href="http://stackoverflow.com/questions/25383766/api-support-for-manual-approval-of-promoted-builds-in-jenkins/36783114#36783114">API support for manual approval of promoted builds in Jenkins?</a> post as a reference but no luck</p>
| <p>Yeah finally got a solution after much plug n play.. thought to share as it could help others.
First of all the Json Values i am passing are not correct and it doesn't have all the parameters the promotion expecting. Second as i have enabled CSRF protection the HTTP request should have a valid crumb. So What i did was i manually approved some dummy job and got the JSON of the successful promoted job. It contain all the passed parameters. So it helped me to get all the parameters that should be passed from CURL command. So finally the working URL is below. You can pass/remove any additional parameters to the JSON DATA as per your requirement.</p>
<p>Please Note: the crumb field name is changed from what much answers provided in many stackoverflow answers. Now the Filed name is not ".crumb" but "Jenkins-Crumb"</p>
<p>curl -v -H "Jenkins-Crumb:XXXXXXXXXXX" -X POST <a href="http://USER:TOKEN@JENKINS_URL/job/JOB_NAME/JOB_NUMBER/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve" rel="nofollow">http://USER:TOKEN@JENKINS_URL/job/JOB_NAME/JOB_NUMBER/promotion/promotionProcess/PromoteForTesting/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve</a> --data-urlencode json='{"parameters":[{"_class":"hudson.model.StringParameterValue","name":"PARAMETER","value":""},{"_class":"hudson.model.StringParameterValue","name":"Job","value":"Deploy(ZettaDevelopment)"},{"_class":"hudson.model.StringParameterValue","name":"BuildSelection","value":"PARAMETER"},{"_class":"hudson.model.StringParameterValue","name":"PARAMETER","value":"PARAMETER"}]}'</p>
<p>The Parameter Values passed are found using <a href="http://USER:TOKEN@JENKINS_URL/job/JOB_NAME/JOB_NUMBER/promotion/promotionProcess/PromoteForTesting/promotionBuild/Build_NUMBER/api/json" rel="nofollow">http://USER:TOKEN@JENKINS_URL/job/JOB_NAME/JOB_NUMBER/promotion/promotionProcess/PromoteForTesting/promotionBuild/Build_NUMBER/api/json</a></p>
<p>Here Build_NUMBER is the build i manually approved. From the output you can easily get the required parameters to be passed.</p>
<p>Hope This can help as at least it worked for me :-)</p>
|
using phantomjs to get jscript output <p>I have an internal webpage that I want to pull a piece of data from at time intervals.</p>
<p>I used curl to scrape the page but discovered the data i want is in a jscript. So now I am trying to automate the jscript so i can get the output to text file, i can then parse the text file to get the figure I want.</p>
<p>I am a low level programmer, my higher level programming skills aren't great and I am at the limits of my knowledge.</p>
<pre><code> <script language="javascript" type="text/javascript" src="https://x-x--x-x-x-x-x-x-x-x.com/igraph/chart?GraphType=zoomer&SchemaName1=Service&DataSet1=Prod&Marketplace1=LTN4-ShippingRouterController&HostGroup1=ALL&Host1=ALL&ServiceName1=WarehouseControlService&MethodName1=SortationOrchestrator.divert&Client1=ALL&MetricClass1=NONE&Instance1=NONE&Metric1=RECIRC&Period1=OneMinute&Stat1=n&Label1=SortationOrchestrator.divert%20RECIRC&SchemaName2=Service&MethodName2=SortationOrchestrator.scan&Metric2=Time&Label2=SortationOrchestrator.scan%20Time&DecoratePoints=true&TZ=Europe%2FLondon@TZ%3A%20London&UpperValueLeft=150&LowerValueLeft=0&StartTime1=-PT2M&EndTime1=-PT1M&FunctionExpression1=M1%20%2F%20M2%20*%20100&FunctionLabel1=Recirc%20%25%20%5Bval%3A%20%7Bsum%7D%5D&FunctionYAxisPreference1=left&ChartLegend=true&WidthInPixels=400&HeightInPixels=400&Action=GetGraph&Version=2007-07-07&iGHrefresh=1475844553&Jsonp=MP.ChartController.loaded('chartdiv0'%2C"></script>
</code></pre>
<p>and I want the output of the Jsonp=MP.ChartController.loaded</p>
<p>which when you use firebug the output is </p>
<pre><code> MP.ChartController.loaded('chartdiv0',
{
error: '',
width: 400,
height: 400
, summaryData: [
{ id: 0,
label: 'Recirc % [val: 26.19]',
</code></pre>
<p>recirc val is what i'm after.</p>
<p>can i use phantomjs to run the jscript and output the json to txt file?</p>
| <p>Not phantomjs but nodejs. PhantomJS is a headless browser and I dont think it would help much. Following code can demonstrate in better way: <a href="https://runkit.com/pankaj/periodic-ajax" rel="nofollow">https://runkit.com/pankaj/periodic-ajax</a></p>
<p>Or if you wanna do it on a HTML page with jQuery then following code demonstrates that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i = 0;
var intervalID = setInterval(function(){
$.get( 'https://mocknode.herokuapp.com/id/', function (data) {
console.log(i++, data)
})
}, 5000);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
|
If you have a string of characters, is it possible to substract each one? Java <pre><code>for (int i= length-1;i>=0; i--){//reverses order of string.
password_2 = password_2 + password.charAt(i);//store in new string
System.out.print(password.charAt(i));
</code></pre>
<p>basically after I inverse the order, I need to subtract 7 from each character. So lets say i input: "kflre". I need to subtract 7 from the k, from the l etc..and I wanted to do it within my for loop. Is it possible or do I have to convert everything into ints before? </p>
| <p>Do you want to subtract 7 from the location of the letter i the alphabet and then produce that? for example h - 7 = a.</p>
<p>You could fill an <code>map<int, String></code> with the alphabet and then use <code>.equals(theLetterEntered)</code> in a loop to get the location, then just do addition on the maps key to get the new letter? </p>
<p>a quick example:</p>
<pre><code> HashMap<Integer, String> alphabetMap = new HashMap();
String strToCompare;
alphabetMap.put(1, "a");
alphabetMap.put(2, "b");
//etc.
for (int i=0; 1<26;i++){
if (alphabetMap.get(i).equals(strToCompare)){
//code
}
</code></pre>
|
Find/Delete and Update record MongoDB using C# <p>This my doument</p>
<pre><code>{ "_id" : ObjectId("57f65ed25ced690b5408a9d1"), "fbId" : "7854", "Name" : "user1", "pass" : "user1", "Watchtbl" : [ { "wid" : "745", "name" : "azs", "Symboles" : [ { "Name" : "nbv" } ] }, { "wid" : "8965", "name" : "bought stock1", "Symboles" : [ { "Name" : "AAA" }, { "Name" : "BSI" }, { "Name" : "EXXI" }, { "Name" : "AMD" } ] }, { "wid" : "9632", "name" : "bought stock3", "Symboles" : [ { "Name" : "AAA" }, { "Name" : "AMD" } ] } ] }
</code></pre>
<p>I want to find and update this record with a specific find, like I want to search by <strong>_id</strong> and <strong>wid</strong> and update the <strong>name</strong> and the <strong>Symboles</strong> of ths <strong>Watchtbl</strong>
But it look <strong>_id</strong> and <strong>wid</strong> are not recognized when I try to do this filtre</p>
<pre><code>var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("_id", id) & builder.Eq("wid", wid);
</code></pre>
<p>it retrun 0.<br></p>
<p>So the idea<a href="http://i.stack.imgur.com/yCMpQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/yCMpQ.png" alt="enter image description here"></a> is the same for Delete function</p>
| <p>You will want to use builder.And to join clauses for your filter</p>
<pre><code>var filter = builder.And(builder.Eq("_id", id), builder.Eq("wid", wid))
</code></pre>
<p>For updating the individual fields, you can achieve this using the </p>
<pre><code>Builders<BsonDocument>.Update.Set
</code></pre>
<p>I hope this helps</p>
|
Variable i cannot be read at compile time <p>I have this code:</p>
<pre><code>class Set(T){
private T[] values;
T get(uint i){
return ((i < values.length) ? T[i] : null);
}
...
</code></pre>
<p>And when I try use this class this way:</p>
<pre><code>set.Set!(int) A;
</code></pre>
<p>compiler gives error at the <code>return</code> line: <code>set.d|9|error: variable i cannot be read at compile time</code></p>
<p>Can somebody explain, what's wrong in my code? Thanks.</p>
| <p>That is the answer: the code simply referenced the wrong variable. The reason it gave the error it did is that T[i] is trying to get an index out of a compile-time list of types... which needs i to be available at compile time too. However, since i is a regular variable, it isn't. (You can have compile time variables btw - the result of a function may be CT evaled, or the index on a foreach over a static list, or an enum value.) However, what was wanted here was a runtime index into the array... so the values is the right symbol since it is the data instead of the type.</p>
<p>By Adam D. Ruppe</p>
|
Guice CreationException due to missing implementation for java.util.Optional <p>I'm upgrading an application written for Java 7 to version 8. It uses Guice to inject config values into the constructor of an object. However, after the upping the Java version, I'm now getting this mysterious error when running unit tests:</p>
<pre><code>java.lang.RuntimeException: com.google.inject.CreationException: Guice creation errors:
1) No implementation for java.util.Optional<java.lang.Boolean> annotated with @Config(value=AsyncHttpClientConfigProvider.allowPoolingConnection) was bound.
while locating java.util.Optional<java.lang.Boolean> annotated with @Config(value=AsyncHttpClientConfigProvider.allowPoolingConnection)
for field at AsyncHttpClientConfigProvider.allowPoolingConnection(AsyncHttpClientConfigProvider.java:212)
at Module.configure(Module.java:24)
...
13 errors
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:435)
at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:154)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:106)
at com.google.inject.Guice.createInjector(Guice.java:95)
at com.google.inject.Guice.createInjector(Guice.java:72)
at com.google.inject.Guice.createInjector(Guice.java:62)
at org.jukito.JukitoRunner.ensureInjector(JukitoRunner.java:105)
at org.jukito.JukitoRunner.computeTestMethods(JukitoRunner.java:233)
... 19 more
</code></pre>
<p>What might I be missing that would cause this error?</p>
| <p>Trivially, you're missing a binding of <code>@Config(AsyncHttpClientConfigProvider.allowPoolingConnection) Optional<Boolean></code>, which is different from <code>@Config(AsyncHttpClientConfigProvider.allowPoolingConnection) Boolean</code>. For a more specific answer, we'll need to see more of your previous working injection point and current failing injection point, but given that java.util.Optional didn't exist before Java 8, it's likely that you added that yourself and thus changed the Guice Key used to look up the binding.</p>
<p>Support for <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="nofollow">Java 8's <code>Optional<T></code></a>, like the rest of Java 8 support, came out in <a href="https://github.com/google/guice/wiki/Guice40" rel="nofollow">Guice 4.0 (Apr 2015)</a>, and only when using the <a href="http://google.github.io/guice/api-docs/4.0/javadoc/com/google/inject/multibindings/OptionalBinder.html" rel="nofollow">Multibindings <code>OptionalBinder</code></a>. Without that, or in previous versions of Guice, your Injector will treat Optional like any other generic type when used as a Key.</p>
<p>Guice 3.0's "optional" bindings were restricted to method and field injections with <code>@Inject(optional=true)</code>, which still works, but nothing in Guice 4.0's upgrades automatically supports Optional types outside of the Multibindings case.</p>
|
esc_url on WordPress ACF oEmbed <p>I'm using the <a href="https://www.advancedcustomfields.com" rel="nofollow">ACF</a> WordPress plugin to create an oEmbed field. The field accepts a URL from Vimeo and outputs an iframe on the front end.</p>
<p>I usually escape urls and attributes within my theme like so:</p>
<pre><code><a href="<?= esc_url( get_field('link') ); ?>" title="<?= esc_attr( get_field('title') ); ?>">
</code></pre>
<p>When I try and escape the oEmbed, nothing shows up:</p>
<pre><code><?= esc_url( get_field('video') ); ?>
</code></pre>
<p>If I test XSS with the following script, the ACF field completely breaks with a JS error.</p>
<pre><code><script>alert('hello')</script>
</code></pre>
<p>Do I need to escape this field? I assume that WordPress takes care of the escaping through the oEmbed function?</p>
| <p>Have you tried using the_field() instead of get_field()?</p>
<pre><code><?= esc_url( the_field('video') ); ?>
</code></pre>
<p>The oEmbed actually returns more than just a url so that could be the issue as well. I haven't worked with esc_url() much in the past but it could be breaking because whatever is getting passed through is not only a url. </p>
<p>As stated here, <a href="https://www.advancedcustomfields.com/resources/oembed/" rel="nofollow">https://www.advancedcustomfields.com/resources/oembed/</a>, "The oEmbed field will return a string containing the embed HTML".</p>
|
Merging rows with shared information <p>I have a data.frame with several rows which come from a merge which are not completely merged:</p>
<pre><code>b <- read.table(text = "
ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
68 HA-09 16 <NA> <NA> <NA> 5 NA
69 HA-09 16 <33% no/occasional <NA> NA 1")
</code></pre>
<p>How can I merge them by a column ?</p>
<p>Expected output :</p>
<pre><code> ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
69 HA-09 16 <33% no/occasional <NA> 5 1
</code></pre>
<p>Note that some columns (other than ID) have the same value on both rows. These columns aren't part of the "primary key" of the database (AFAIK). So if there are several different values shouldn't be merged. Things I tried:</p>
<pre><code> merge(b[1, ], b[2, ], all = T) # Doesn't merge the rows, just the data.frames
cast(b, ID ~ .) # I can count them but not merging them into a single row
aggregate(b, by = list("ID", "Age"), c) # Error
</code></pre>
| <p>While I'm sure that it's possible with <code>dplyr</code> or <code>tidyr</code>, here's a <code>data.table</code> solution:</p>
<pre><code>b <- read.table(text = "
ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
68 HA-09 16 <NA> <NA> <NA> 5 NA
69 HA-09 16 <33% no/occasional <NA> NA 1",
na.strings = c("NA", "<NA>"))
keycols <- c("ID", "Age")
library(data.table)
b_dt <- data.table(b)
filter_nas <- function(x){
if(all(is.na(x))){
return(unique(x))
}
return(unique(x[!is.na(x)]))
}
b_dt[, lapply(.SD, filter_nas ), by = mget(keycols)]
ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
1: HA-09 16 <33% no/occasional NA 5 1
</code></pre>
<p>Note, this only works if the keys are unique.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.