input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Getting an SQL Exception 'NaN' is not a valid numeric or approximate numeric value <p>I'm having an SQL exception while i'm trying to parse a JSON object. Here's my code snippet. </p>
<pre><code>public JSONArray paymentMode(String stringObjects) throws SQLException {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
//JSONOBJECT RETURN
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONArray array = JSONFactoryUtil.createJSONArray();
Session session = null;
Connection conn = null;
CallableStatement callableStatement = null;
try {
// test
BeanLocator beanLocator = PortletBeanLocatorUtil
.getBeanLocator("Mrcos-services-portlet");
BasicDataSource bds = (BasicDataSource) beanLocator
.locate("mrcosDataSourceTarget");
conn = (Connection) bds.getConnection();
jsonObject = JSONFactoryUtil.createJSONObject(stringObjects);
JSONArray jsonArray = jsonObject.getJSONArray("dataArray");
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);
callableStatement = (CallableStatement) conn
.prepareCall("{call PaymentModeSPv2(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
callableStatement.setString(1, jsonObject.getString("mode"));
callableStatement.setString(2, jsonObject.getString("num1"));
callableStatement.setString(3, jsonObject.getString("date1"));
callableStatement.setString(4, jsonObject.getString("num2"));
callableStatement.setString(5, jsonObject.getString("date2"));
callableStatement.setString(6, jsonObject.getString("remarks"));
callableStatement.setDouble(7, jsonObject.getDouble("amount"));
callableStatement.setString(8, jsonObject.getString("receipt"));
callableStatement.setString(9, jsonObject.getString("algo"));
callableStatement.setString(10, jsonObject.getString("code"));
callableStatement.setString(11, jsonObject.getString("address"));
callableStatement.setString(12, jsonObject.getString("status"));
callableStatement.registerOutParameter(13, Types.INTEGER);
callableStatement.executeQuery();
String xreturn = callableStatement.getString(13);
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("xreturn", xreturn);
array.put(jsonObjectReturn);
System.out.println("jsonObjectReturn : " + jsonObjectReturn);
}
return array;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (callableStatement != null) {
callableStatement.close();
}
if (conn != null) {
conn.close();
}
closeSession(session);
}
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("result", "NO RESULTS FOUND!");
return array;
}
</code></pre>
<p>I'm having an error at <strong>callableStatement.setDouble(7, jsonObject.getDouble("amount"));</strong> saying <strong>java.sql.SQLException: 'NaN' is not a valid numeric or approximate numeric value</strong>.</p>
<p>The <strong>amount</strong> is decimal in my database. I also tried to use float instead of double but still gives the same error message. I also tried to pass an integer and a decimal number but still the same error occurs. Please help I'm stuck for a while now. Thank you!</p>
| <p>You're getting a <code>javascript</code> <code>[NaN][1]</code> in <code>jsonObject.getDouble("amount")</code>. So you need to deal with it somehow. E.g. you can replace it with <code>0</code> or <code>Double.NaN</code>:</p>
<pre><code>String amt = jsonObject.getString("amount");
Double amount = "NaN".equals(amt) ? Double.NaN : Double.parseDouble(amt);
callableStatement.setDouble(7, amount);
</code></pre>
|
Saving images with pixels in django <p>I want to save images with specific pixels, when someone uploads image on django models it will be resized and then save according to id. I want them to be saved in path product/medium/id. I have tried defining path in it which saves image but not on the path I want. </p>
<p><strong>Here is my models.py</strong></p>
<pre><code>class Product(models.Model):
product_name = models.CharField(max_length=100)
product_description = models.TextField(default=None, blank=False, null=False)
product_short_description = models.TextField(default=None,blank=False,null=False,max_length=120)
product_manufacturer = models.CharField(choices=MANUFACTURER,max_length=20,default=None,blank=True)
product_material = models.CharField(choices=MATERIALS,max_length=20,default=None,blank=True)
No_of_days_for_delivery = models.IntegerField(default=0)
product_medium = models.ImageField(upload_to='product/id/medium',null=True,blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.product_name)
super(Product, self).save(*args, **kwargs)
</code></pre>
<p>Now on this, I want to resize the image get it's id and save in path <code>product/medium/id/image.jpg</code></p>
| <pre><code>from PIL import Image
import StringIO
import os
from django.core.files.uploadedfile import InMemoryUploadedFile
class Product(models.Model):
pass # your model description
def save(self, *args, **kwargs):
"""Override model save."""
if self.product_medium:
img = Image.open(self.image)
size = (500, 600) # new size
image = img.resize(size, Image.ANTIALIAS) #transformation
try:
path, full_name = os.path.split(self.product_medium.name)
name, ext = os.path.splitext(full_name)
ext = ext[1:]
except ValueError:
return super(Product, self).save(*args, **kwargs)
thumb_io = StringIO.StringIO()
if ext == 'jpg':
ext = 'jpeg'
image.save(thumb_io, ext)
# Add the in-memory file to special Django class.
resized_file = InMemoryUploadedFile(
thumb_io,
None,
name,
'image/jpeg',
thumb_io.len,
None)
# Saving image_thumb to particular field.
self.product_medium.save(name, resized_file, save=False)
super(Product, self).save(*args, **kwargs)
</code></pre>
|
filter data in Kendo grid by connect to a method asp.net MVC <p>I am making a code using ASP.NET MVC with kendo grid.
I want to bring the data from database to Kendo grid which equal to specific date or by default "today". </p>
<p>I want to make a datepicker and a button at the toolbar and everytime I click the button it send a request to the control and filter the data in LINQ and send the request for all the data in one day. I wrote this code:</p>
<p>Controller class: </p>
<pre><code>//main method
public ActionResult LogAdminList()
{
return View();
}
//submethod for grid
public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "id")] string date)
{
DateTime _temp;
if (!DateTime.TryParse(date, out _temp))
_temp = DateTime.Now;
return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))
.Select(l => new LogAdminInfo
{
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp,
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,
})
.ToDataSourceResult(request));
}
</code></pre>
<p>the kendo code is : </p>
<pre><code>@(Html.Kendo().Grid<LogAdminInfo>()
.BindTo(Model)
.Name("LogAdminList")
.Sortable()
.Columns(columns =>
{
columns.Bound(p => p.Message).Width(50).Title(WebResources.LogListMessage);
columns.Bound(p => p.MessageTemplate).Width(50).Title(WebResources.LogListMessageTemplate);
columns.Bound(p => p.Level).Title(WebResources.LogListLevel);
columns.Bound(p => p.TimeStamp).Title(WebResources.LogListTimeStamp).Format("{0:dd.MM.yyyy H:mm}");
columns.Bound(p => p.Exception).Width(50).Title(WebResources.LogListException);
columns.Bound(p => p.Properties).Width(50).Title(WebResources.LogListProperties);
columns.Bound(p => p.LogEvent).Title(WebResources.LogListLogEvent);
})
.Pageable(pageable => pageable
.Refresh(true)
.ButtonCount(5))
.HtmlAttributes(new { @class = "grd_UpcomingMilestone" })
.ToolBar(toolbar =>
{
toolbar.Template(@<text>
<div class="toolbar">
<label class="category-label" for="category">@WebResources.LogFilterMessage</label>
@(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(DateTime.Today)
.Format("dd.MM.yyyy")
)
@(Html.Kendo().Button()
.Name("filterButton")
.Icon("filter")
.Content("Filter")
.HtmlAttributes(new { type = "button" })
)
</div>
</text>);
})
.DataSource(source => source
.Ajax()
.Batch(true)
.ServerOperation(false)
.PageSize(100)
.Read(read => read.Action("Grid_ReadLogAdminList", "LogAdmin").Data("getFilterDate"))
))
</code></pre>
<p>I don't know what to do exactly in the javascript. the code works fine in the first request but not when I filter.</p>
<p>what should I write as a javascript? </p>
<p>thank you very much. </p>
| <p>You have to pass data from client to server using <code>getFilterDate</code> function specified in you Kendo Grid Read <code>Data</code> method. Implement a function like this. The return type must be an object with fields with the same name you defined in your MVC Action, in this case <code>date</code>. Kendo will serialize them in order to build the get request:</p>
<pre><code>function getFilterDate() {
var mydate = $("#datepicker").data("kendoDatePicker").value();
return {
"date": mydate
}
}
</code></pre>
|
Visual Studio won't detect my device <p>Yes, yet again another question about connecting a device to Visual Studio... I know there are plenty of answers, but I couldn't make it work, hence this new topic.</p>
<hr>
<p>So I got a Visual Studio Community 2015.
I created a new Cordova Project, using Cordova 6.1.1
When I used the ripple emulator, everything works fine. (I got a error 404 about <em>favicon.ico</em> and <em>ripple.js</em>, but the application runs fine)</p>
<p>To test on Android device, I got a Galaxy Note 2 running on Android 4.4.2. Developper option is activated, as weel as "<em>enable USB degugging</em>". Moreover, I can access the phone using windows explorer just fine.</p>
<p>Problem is, when I set "<em>Debug</em>" mode and "<em>Android</em>" Platform, VS2015 doesn't list the device in the menu, I simply got "Device". And if I try to run it nevertheless, I got a popup saying "<em>deployment error, continue anyway ?</em>". If I click on "continue", I got an error popping : "<em>Failed to install apk to device: [ 9%] /data/local/tmp/android-debug.apk</em>"</p>
<p>Do you guys have any idea how to resolve this ?</p>
<p>By the way, in the sdk manager, I installed <em>Android SDK Tools 25.2.2</em>, <em>Android SDK Platform-tools 24.0.3</em>, <em>Android SDK Build-tools 24.0.3</em>, <em>Android 6.0 API</em> and <em>Google USB Driver</em>.</p>
<p>When trying to update the Note 2 driver on my computer, windows says it's already up to date. I even trined to uninstall/reinstall the Google USB Driver. </p>
| <p>Install a driver for your phone :)
currently i am using pdaNet to connect my phone for android dev.
check it here -> <a href="http://pdanet.co/a/" rel="nofollow">http://pdanet.co/a/</a></p>
<p>just for you to know how to check if you have driver for your phone <a href="http://www.junefabrics.com/android/driver.php" rel="nofollow">http://www.junefabrics.com/android/driver.php</a></p>
|
How to loop inside custom field group in WordPress <p>I want to emulate the following layout on WordPress pages. </p>
<p><a href="https://i.stack.imgur.com/fio4u.png" rel="nofollow"><img src="https://i.stack.imgur.com/fio4u.png" alt="enter image description here"></a></p>
<p>but how do I make the encircled city dynamic? The layout is set that under a specific state, all stores on that state is listed below it.</p>
<p>On SQL, this may mean:</p>
<pre><code>select city where address = "";
</code></pre>
<p>I just don't know how to translate my SQL knowledge into a WordPress dynamic page. </p>
<p>So far my WordPress page code is: </p>
<pre><code><section class="main-content">
<?php $loop = new WP_Query( array( 'post_type' => 'branches', 'orderby'=>'post_id', 'order'=>'ASC' ) ); ?>
<div class="resource-row clearfix">
<?php while( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$address = get_field('address');
?>
</div><!-- resource-row -->
</section><!-- main-content -->
</code></pre>
<p>EDIT:</p>
<p>As of now, based on the above image, what I can do is display the following:</p>
<blockquote>
<p>Cupertino
1 Infinite Loop
Cupertino, CA</p>
</blockquote>
<p>However, I cannot seem to display the state (eg. California) for which the address is under, as well as the other address on the row. </p>
<p>How do I make it such that for each State, the corresponding address is displayed under it? </p>
| <p>Well, it would have been of great help if you had shared the table structure. Assuming that there are three separate records for:</p>
<ol>
<li>Cupertino</li>
<li>Infinite Loop</li>
<li>Cupertino, CA</li>
</ol>
<p>We can do this:</p>
<pre><code>select group_concat(x separator ' ') address
from (select 'Cupertino 1' x union
select 'Infinite Loop' union
select 'Cupertino, CA') t;
</code></pre>
|
Kentico - Different transformations for hero banners <p>I've set up a custom page type for my hero banners (all are inside /hero/ folder on the content tree) and used a repeater to display the banners in form of a carousel. The current transformation I have centering all elements (text/buttons) inside all banners. However, in some situation, it looks better if the elements are left or right aligned. Is there a way to use more than one transformations for this kind of thing; even better, is it possible to manually specify which transformation will be applied to which item inside the /hero/ folder.</p>
<p>I noticed there's a field for <em>Alternating transformation</em>; however, looks like Kentico will automatically apply it to the even items. Thanks for your input!</p>
| <p>Probably the easiest way would be to add an extra field (or a couple of fiedls) to a page type, where editor could specify the position of elements or simply type in a class. E.g. drop down with otions right, left and center; each option value could be a class that you just include into your transformation. The rest is just implementation of appropriate CSS classes.</p>
|
SDWebImage blocking tableview title label <p>I need some help, I'm using SDWebImage to display my images in my Xcode app but I'm also trying to show text using the tableView's testLabel. But what is happening is the image is pushing the textLabel to the right, next to the image instead of being on top of the image. I'm not using a UIImageView or a label, I'm using the tableviews default imbedded imageView and textLabel. Any idea on how I can display this textLabel on top of sdwebimage's loaded image? I want to display the text at the bottom left of the cell, on top of the loaded image.</p>
<p>I can't post an image so I will try my best at describing what my problem looks like.</p>
<p><strong>Image Description:</strong>
In the cell, there is an image with a 7px margin on each side, to the right of the image there is the textLabel showing only 2-3 characters before the rest disappearing out of the screen.</p>
<p><strong>My Code:</strong></p>
<p><strong>Loading the image:</strong></p>
<pre><code>NSURL * imgURL = [[gamesArray objectAtIndex:indexPath.row] valueForKey:@"gameURL"];
[cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.imageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"placeholder.png"] options:SDWebImageRefreshCached];
</code></pre>
<p><strong>Loading the text:</strong></p>
<pre><code>cell.textLabel.text = gameObject.gameName;
[cell.textLabel setContentMode:UIViewContentModeScaleToFill];
cell.textLabel.textColor = [UIColor whiteColor];
</code></pre>
| <p>In default TableView cell image is always in centre and textLabel is right to imageView. So for this you have to design a custom TableView cell.</p>
|
Progress Bar in C# <p>My problem is I have a method which loading some datas. It took about 10-15 second until the website is loaded. I wanna add a progress bar to the site for the user to show him how long it takes to complete loading the website.</p>
<p>I made a progress bar with pace.js and added it to the .html. The problem is I need something in my controller because the html will start after my method is finished.
At the moment I start my website the datas loading and after that my progress bar appears for a second.
Could I add my script to a button or is there another solution?</p>
<p>Thanks</p>
| <p>The progress bar initializes after the load happened. In fact, the load happens on the server before aything is sent to the browser. I would solve the problem as follows:</p>
<ol>
<li><p>I would modify my code to make sure that the slow part of the code does not execute on the server before it responds to the browser and the slow part can be reached via POST requests.</p></li>
<li><p>I would have a loaded event in the browser, where I would initialize the progress bar.</p></li>
<li><p>After the progress bar is initialized, I would send a separate AJAX code for each subtask of the slow task (yes, I would partition the slow task if possible).</p></li>
<li><p>These async AJAX requests would have a callback which would refresh the progress bar's status according to the current situation. The last callback would close the door (finish the progress bar's life-cycle).</p></li>
</ol>
|
React typescript typings not working <p>After installing via typings I get the below error in terminal</p>
<p><strong>Terminal error</strong></p>
<pre><code>error TS2320: Interface 'Element' cannot simultaneously extend types 'ReactElement<any>' and 'ReactElement<any>'.
Named property 'type' of types 'ReactElement<any>' and 'ReactElement<any>' are not identical.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/typings/globals/react/index.d.ts
(2375,5): error TS1036: Statements are not allowed in ambient contexts.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/typings/globals/react-dom/index.d.ts
(69,5): error TS2309: An export assignment cannot be used in a module with other exported elements.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/node_modules/@types/react-dom/index.d.ts
(19,31): error TS2315: Type 'DOMAttributes' is not generic.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/node_modules/@types/react-dom/index.d.ts
(44,60): error TS2315: Type 'DOMAttributes' is not generic.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/node_modules/@types/react/index.d.ts
(2368,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'a' must be of type 'HTMLProps<HTMLAnchorElement>', but here has type 'HTMLProps<HTMLAnchorElement>'.
ERROR in /Users/ajvivek/Dev/ES6/motionize-code/node_modules/@types/react/index.d.ts
(2369,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'abbr' must be of type 'HTMLProps<HTMLElement>', but here has type 'HTMLProps<HTMLElement>'.
</code></pre>
<p><strong>index.d.ts</strong>
<code>
/// <reference path="globals/react/index.d.ts" />
/// <reference path="globals/react-dom/index.d.ts" />
</code></p>
<p><strong>tsconfig.json</strong></p>
<pre><code>{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"noImplicitAny": true,
"target": "es5",
"jsx": "react"
},
"files": [
"./app/app.tsx",
"./app/Hello.tsx",
"typings/index.d.ts"
],
"exclude": [
"node_modules"
]
}
</code></pre>
<p>I have followed the documentation provided in <a href="https://www.typescriptlang.org/docs/handbook/react-&-webpack.html" rel="nofollow">https://www.typescriptlang.org/docs/handbook/react-&-webpack.html</a></p>
<p>Not sure what I have missed? </p>
<p>Is anyone facing this issue? </p>
| <p>I figured out the issue finally. </p>
<p>I went on to install types once via <strong>tsd</strong> and then <strong>typings</strong> that led to duplicate typings. </p>
<p>Deleted the <strong>@types</strong> folder to resolve my issue.</p>
|
Cannot read property 'blur' of null at nightmarejs <p>I have been making simple code lately. however It's doesn't work.
why do that? I don't understand. I guess it didn't have error syntax.</p>
<p>but It occurred "Cannot read property 'blur' of null"</p>
<p>could you please help me?</p>
<pre><code>var Nightmare = require('nightmare');
nightmare = Nightmare({show: true});
nightmare.goto('https://www.google.com')
.type('form[action*="/search"] [name=f]', 'aa')
.click('form[action*="/search"] [type=submit]')
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log(err);
});
</code></pre>
| <p>There is a known issue where DOM elements that are changed or removed during typing events can cause a similar problem. It will be fixed in the next release of Nightmare. See <a href="https://github.com/segmentio/nightmare/pull/820" rel="nofollow">#820</a> for details. Quoting from the fix PR:</p>
<blockquote>
<p>If the element being typed or inserted into is removed from the DOM before the blur call is made (which can happen if the element is removed on a key event), an exception is raised. <code>blurSelector</code> now makes sure the element still exists before making the blur call. Also added a debug message if the selector does not exist after focusing.</p>
</blockquote>
<p>Your script also appears to not be valid on the current incarnation of Google - have you also double-checked your selectors?</p>
|
How to get the logout message in custom login page <p>I have to create a login module for my project using Spring Security where I have overridden the <code>configure(HttpSecurity http)</code> method of <code>WebSecurityConfigurerAdapter</code> and created a custom login page.</p>
<p><code>customLogin.jsp</code>:</p>
<pre><code><body>
<h3>Login Here</h3>
<font color="red">
${SPRING_SECURITY_LAST_EXCEPTION.message}
</font>
<form action="<%=request.getContextPath()%>/appLogin" method="POST">
Enter UserName: <input type="text" name="app_username"/><br/><br/>
Enter Password: <input type="password" name="app_password"/> <br/><br/>
<input type="submit" value="Login"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<body>
</code></pre>
<p>And here is my configure method:</p>
<pre><code>@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().
antMatchers("/secure/**").access("hasRole('ROLE_ADMIN')").
and().formLogin(). // login configuration
loginPage("/customLogin.jsp").
loginProcessingUrl("/appLogin").
usernameParameter("app_username").
passwordParameter("app_password").
defaultSuccessUrl("/secure/home").
and().logout(). // logout configuration
logoutUrl("/appLogout").
logoutSuccessUrl("/customLogin.jsp");
}
</code></pre>
<p>And where I have the logout button, I have included the following code (because Spring Security automatically enables CSRF, which automatically disables <code>GET</code> logouts):</p>
<pre><code> <form action="<%=request.getContextPath()%>/appLogout" method="POST">
<input type="submit" value="Logout"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</code></pre>
<p>When I click logout button, it redirects me to custom login page, but the default logout message is not being displayed. How can I get that message here?</p>
| <p>See <a href="http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-form" rel="nofollow">Spring Security Reference</a>:</p>
<blockquote>
<p>An example log in page implemented with JSPs for our current configuration can be seen below:</p>
<p>[..]</p>
<pre><code><c:url value="/login" var="loginUrl"/>
<form action="${loginUrl}" method="post"> 1
<c:if test="${param.error != null}"> 2
<p>
Invalid username and password.
</p>
</c:if>
<c:if test="${param.logout != null}"> 3
<p>
You have been logged out.
</p>
</c:if>
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username"/> 4
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/> 5
</p>
<input type="hidden" 6
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<button type="submit" class="btn">Log in</button>
</form>
</code></pre>
<p>1 A POST to the <code>/login</code> URL will attempt to authenticate the user<br>
2 If the query parameter <code>error</code> exists, authentication was attempted and failed<br>
3 If the query parameter <code>logout</code> exists, the user was successfully logged out</p>
</blockquote>
<p>Also you have to add a query parameter <code>logout</code> to your <code>logoutSuccessUrl</code>. </p>
<p>Your modified Java configuration is:</p>
<pre><code>@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().
antMatchers("/secure/**").access("hasRole('ROLE_ADMIN')").
and().formLogin(). // login configuration
loginPage("/customLogin.jsp").
loginProcessingUrl("/appLogin").
usernameParameter("app_username").
passwordParameter("app_password").
defaultSuccessUrl("/secure/home").
and().logout(). // logout configuration
logoutUrl("/appLogout").
logoutSuccessUrl("/customLogin.jsp?logout");
}
</code></pre>
|
str_replace php a string <p>I have a string</p>
<blockquote>
<p>X_HD003_0</p>
</blockquote>
<p>I have a function PHP</p>
<pre><code>str_replace()
</code></pre>
<p>Ugh......</p>
<p>My result that i want:</p>
<blockquote>
<p>HD003</p>
</blockquote>
<p>^^, some funny from PPAP song, but some string is: X_HD01_1, X_HD0003_2, X_HD12/12/2016/1_01, this string create by: </p>
<blockquote>
<p>"X_" + String + "_Number"</p>
</blockquote>
<p>I want to replace X_ and _Number with str_replace(). Hope everyone can help me! Thank you so much! </p>
| <pre><code>$parts=explode('_','X_HD003_0');
echo $parts[1]; //HD003
</code></pre>
<p>Or in newer versions</p>
<pre><code>echo explode('_','X_HD003_0')[1];
</code></pre>
<p>That should work just fine for all the use cases you mentioned</p>
|
How to access OpenXML content by page number? <p>Using OpenXML, can I read the document content by page number?</p>
<p><code>wordDocument.MainDocumentPart.Document.Body</code> gives content of full document.</p>
<pre><code> public void OpenWordprocessingDocumentReadonly()
{
string filepath = @"C:\...\test.docx";
// Open a WordprocessingDocument based on a filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Open(filepath, false))
{
// Assign a reference to the existing document body.
Body body = wordDocument.MainDocumentPart.Document.Body;
int pageCount = 0;
if (wordDocument.ExtendedFilePropertiesPart.Properties.Pages.Text != null)
{
pageCount = Convert.ToInt32(wordDocument.ExtendedFilePropertiesPart.Properties.Pages.Text);
}
for (int i = 1; i <= pageCount; i++)
{
//Read the content by page number
}
}
}
</code></pre>
<p><strong>MSDN <a href="https://msdn.microsoft.com/en-us/library/office/ff478541.aspx" rel="nofollow">Reference</a></strong></p>
<hr>
<p><strong>Update 1:</strong></p>
<p>it looks like page breaks are set as below</p>
<pre><code><w:p w:rsidR="003328B0" w:rsidRDefault="003328B0">
<w:r>
<w:br w:type="page" />
</w:r>
</w:p>
</code></pre>
<p>So now I need to split the XML with above check and take <code>InnerTex</code> for each, that will give me page vise text.</p>
<p>Now question becomes how can I split the XML with above check?</p>
<hr>
<p><strong>Update 2:</strong></p>
<p>Page breaks are set only when you have page breaks, but if text is floating from one page to other pages, then there is no page break XML element is set, so it revert back to same challenge how o identify the page separations.</p>
| <p><strong>You cannot reference OOXML content via page numbering</strong> at the OOXML data level alone.</p>
<ul>
<li><strong><em>Hard page breaks</em></strong> are not the problem; hard page breaks can be counted.</li>
<li><strong><em>Soft page breaks</em></strong> are the problem. These are calculated according to
line break and pagination algorithms which are implementation
dependent; it is not intrinsic to the OOXML data. There is nothing
to count.</li>
</ul>
<p>What about <code>w:lastRenderedPageBreak</code>, which is a record of the position of a soft page break at the time the document was last rendered? <strong>No, <code>w:lastRenderedPageBreak</code> does not help in general either because</strong>:</p>
<ul>
<li>By definition, <code>w:lastRenderedPageBreak</code> position is stale when content has
been changed since last opened by a program that paginates its
content.</li>
<li>In MS Word's implementation, <code>w:lastRenderedPageBreak</code> is known to be unreliable in various circumstances including
<ol>
<li><a href="https://forums.asp.net/t/1951556.aspx?Facing%20problem%20finding%20out%20page%20end%20in%20Ms%20Word%20Open%20XML%20SDK%20Asp%20net%20c%20We%20can%20t%20get%20a%20lastRenderedPageBreak" rel="nofollow">when table spans two pages</a></li>
<li><a href="https://forums.asp.net/t/1951556.aspx?Facing%20problem%20finding%20out%20page%20end%20in%20Ms%20Word%20Open%20XML%20SDK%20Asp%20net%20c%20We%20can%20t%20get%20a%20lastRenderedPageBreak" rel="nofollow">when next page starts with an empty paragraph</a></li>
<li><a href="https://social.msdn.microsoft.com/Forums/office/en-US/3d0a3027-3062-4ecf-9e74-50cea3ae9a60/lastrenderedpagebreak-and-columns-problem?forum=oxmlsdk" rel="nofollow">for
multi-column layouts with text boxes starting a new column</a></li>
<li><a href="https://social.msdn.microsoft.com/Forums/office/en-US/3d0a3027-3062-4ecf-9e74-50cea3ae9a60/lastrenderedpagebreak-and-columns-problem?forum=oxmlsdk" rel="nofollow">for
large images or long sequences of blank lines</a></li>
</ol></li>
</ul>
<p>If you're willing to accept a dependence on Word Automation, with all of its inherent <a href="https://support.microsoft.com/en-us/kb/257757" rel="nofollow">licensing and server operation limitations</a>, then you have a chance of determining page boundaries, page numberings, page counts, etc.</p>
<p>Otherwise, <strong>the only real answer is to move beyond page-based referencing frameworks that are dependent upon proprietary, implementation-specific pagination algorithms.</strong></p>
|
Large Icon Bitmap appears as white square in notification? <p>I am having this problem where I generate a <code>Bitmap</code> from a URL that I use in my notification. However, on my phone, the <code>Bitmap</code> shows up like a small white square. I looked into it and found many posts like so talking about it: <a href="http://stackoverflow.com/questions/30795431/icon-not-displaying-in-notification-white-square-shown-instead">Icon not displaying in notification: white square shown instead</a> </p>
<p>and I know for sure my <code>Small Icon</code> for the notification indeed is transparent. However, for the <code>Large Icon</code>, I realize that the <code>Large Icon</code> cannot be transparent because it is actually a <code>Bitmap</code> that I generate from a URL. How can I get around this then and make sure that the image renders properly instead of having the <code>Large Icon</code> show up as a white square? Here is my attempt:</p>
<p>NotificationService.java:</p>
<pre><code> NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setTicker(remoteMessage.getFrom() + " has responded!")
.setLargeIcon(AndroidUtils.getBitmapFromURL(remoteMessage.getNotification().getIcon()))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setSmallIcon(R.drawable.ic_tabs_notification_transparent);
</code></pre>
<p>AndroidUtils.java: </p>
<pre><code>public static Bitmap getBitmapFromURL(String userId) {
try {
URL imgUrl = new URL("https://graph.facebook.com/" + userId + "/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Bitmap output;
Rect srcRect;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
srcRect = new Rect((bitmap.getWidth()-bitmap.getHeight())/2, 0, bitmap.getWidth()+(bitmap.getWidth()-bitmap.getHeight())/2, bitmap.getHeight());
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
srcRect = new Rect(0, (bitmap.getHeight()-bitmap.getWidth())/2, bitmap.getWidth(), bitmap.getHeight()+(bitmap.getHeight()-bitmap.getWidth())/2);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, srcRect, rect, paint);
return output;
} catch (IOException e) {
FirebaseCrash.report(e);
return null;
}
</code></pre>
<p>Image showing my problem:</p>
<p><a href="https://i.stack.imgur.com/Fkszn.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/Fkszn.jpg" alt="enter image description here"></a></p>
<p>EDIT: Build.gradle file showing:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
defaultConfig {
applicationId '<ID>'
multiDexEnabled true
minSdkVersion 21
targetSdkVersion 23
versionCode 12
versionName ".12"
signingConfig signingConfigs.Tabs
}
buildTypes {
release {
minifyEnabled false
shrinkResources false
zipAlignEnabled true
debuggable false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.Tabs
}
debug {
applicationIdSuffix ".debug"
debuggable true
minifyEnabled false
signingConfig signingConfigs.Tabs
}
}
//DatabaseReference stuff
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
dexOptions {
javaMaxHeapSize "4g"
}
productFlavors {
}
}
</code></pre>
| <p>I think you have been downloading the image from an URL right?. So, please place an Asynctask to download the image from the url and then use the notification builder to show the notification as like this SO post: <a href="http://stackoverflow.com/a/24866080/6452886">http://stackoverflow.com/a/24866080/6452886</a></p>
|
How to sort content based on values in custom part? <p>I created a PersonPart and attached it to my Employee type. It contains a first name and a last name and implements <code>ITitleAspect</code> so that when I create a bunch of Employees, they don't all show up as "Employee" in the content list. Now I want to create a Projection that displays all employees ordered by their last name alphabetically. </p>
<p>How can I accomplish this? Is there any interface I can implement to make <code>FirstName</code> and <code>LastName</code> available as sort criteria?</p>
<pre class="lang-cs prettyprint-override"><code>public class PersonPart : ContentPart<PersonPartRecord>, ITitleAspect
{
[Required]
[DisplayName("First name")]
public string FirstName
{
get { return Retrieve(r => r.FirstName); }
set { Store(r => r.FirstName, value); }
}
[Required]
[DisplayName("Last name")]
public string LastName
{
get { return Retrieve(r => r.LastName); }
set { Store(r => r.LastName, value); }
}
public string Title
{
get { return LastName + " " + FirstName; }
}
}
</code></pre>
| <p>To add new bindings in Orchard to use in custom queries, you have to add these bindings as following:</p>
<ol>
<li>You should go to <code>Bindings</code> page as following:</li>
</ol>
<p><a href="https://i.stack.imgur.com/uht1W.png" rel="nofollow"><img src="https://i.stack.imgur.com/uht1W.png" alt="Bindings"></a></p>
<p>then press on <code>Add a New Binding</code> button.</p>
<ol start="2">
<li>In <code>Add a Binding</code> page, you will see all your records properties (it will not include your <code>ContentPart</code> properties if it's does not has a <code>ContentPartRecord</code>), which you can add new binding for them:</li>
</ol>
<p><a href="https://i.stack.imgur.com/PwBCV.png" rel="nofollow"><img src="https://i.stack.imgur.com/PwBCV.png" alt="Add a Binding"></a></p>
<p>Here, you can select the property you want to add binding for.</p>
<ol start="3">
<li>Then, You are free to enter the <code>Display</code> text and <code>Description</code> for your property binding:</li>
</ol>
<p><a href="https://i.stack.imgur.com/9jEgf.png" rel="nofollow"><img src="https://i.stack.imgur.com/9jEgf.png" alt="Binding"></a></p>
<ol start="4">
<li>Now, if you go to your query edit page, and try to add a new filter for it, you will see the new binding there (notice that the display name you entered in the previous step is very important here to describe your binding to be very clear for others):</li>
</ol>
<p><a href="https://i.stack.imgur.com/35AjI.png" rel="nofollow"><img src="https://i.stack.imgur.com/35AjI.png" alt="Add a Filter"></a></p>
<ol start="5">
<li>Finally, you will see the newly created binding in your <code>Edit Query</code> page:</li>
</ol>
<p><a href="https://i.stack.imgur.com/wD9iA.png" rel="nofollow"><img src="https://i.stack.imgur.com/wD9iA.png" alt="Edit Query"></a></p>
|
AngularAdal restrict AD users <p>I'm using AngularJS Adal plugin to handle login on my page, with Azure AD.
I got everything working and it's great, one problem I have is, I would like to restrict who in Azure AD can use the login, is this possible?
<br><br>
Thanks, <br>
Feeloor</p>
| <p>To restrict the users for the apps which protected by the Azure AD, we can config the app to enable the âUser assignment required to access appâ on the portal like figure below:
<a href="https://i.stack.imgur.com/svwVz.png" rel="nofollow"><img src="https://i.stack.imgur.com/svwVz.png" alt="enter image description here"></a></p>
<p>Then we can assign/remove the users who you doesnât want to use the app at the users tab like below:</p>
<p><a href="https://i.stack.imgur.com/uLcv8.png" rel="nofollow"><img src="https://i.stack.imgur.com/uLcv8.png" alt="enter image description here"></a></p>
|
How do I delete already merged local Git branches with TortoiseGit? <p>I would like to find solution for problem very well described <a href="http://stackoverflow.com/questions/7726949/remove-local-branches-no-longer-on-remote">here</a> - in short, this problem can be solved with <code>git branch -d $(git branch --merged)</code> when commandline used - question is, is there possibility to do the same in TortoiseGit?</p>
| <p>As of version 2.3 TortoiseGit only helps you for automatically cleaning up remote tracking branches.</p>
<p>You can do this automatically when you use the Pull/Fetch-dialog an check "Prune". Then all remote-tracking references which are not there on the remote are automatically removed. On Sync dialog select "Clean up stale remote branches" in the pull/fetch menu button.</p>
|
How can I default my spring boot application to application/xml without killing /health? <p>I'm working on a spring-boot (1.4.0-RELEASE) MVC Groovy app which will present an XML api. By default Spring seems to wire up Jackson which marshalls my response objects to JSON, however I want it to default to responding in XML without requiring any <code>Accept</code> header from clients, hence I configured the default content type as follows:</p>
<pre><code>@Configuration
class SpringWebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
</code></pre>
<p>This works just fine, however when running our tests I discovered that calling <code>/health</code> now returns a 406 status code and no content (it previously returned a 200 and a JSON response).</p>
<p>Having reverted the above change I thought perhaps I could force each controller to explicitly set the response content type via the use of a <code>ResponseEntity</code>, in doing so I tried the following in my controller method:</p>
<pre><code>@RequestMapping(value = "/blah",
method = RequestMethod.GET)
ResponseEntity<MyResponseObject> getProgrammeRestrictions(@PathVariable String coreNumber) {
// Generate response object (code snipped)...
new ResponseEntity<MyResponseObject>(myResponseObject,
new HttpHeaders(contentType: MediaType.APPLICATION_XML),
HttpStatus.OK)
}
</code></pre>
<p>However this doesn't seem to influence the response type, which still defaults to JSON.</p>
<p>In a nutshell it seems that setting a default non-json content type breaks the actuator healthcheck. Is there someway to force the healthcheck bits and bobs to disregard the default setting and always be generated in JSON?</p>
<p>Has anyone else experienced this? Grateful for any pointers as I'm a bit stuck here.</p>
<p>Many thanks,</p>
<p>Edd</p>
| <p>You need to add <code>jackson-dataformat-xml</code> dependency:</p>
<pre><code><dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
</code></pre>
<p>Then, make its <code>XmlMapper</code> available:</p>
<pre><code>@Autowired
private MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter;
@Bean
public ObjectMapper objectMapper(){
// this returns an XmlMapper, which is a subclass of ObjectMapper
return mappingJackson2XmlHttpMessageConverter.getObjectMapper();
}
</code></pre>
<p>It works when sending a request from the browser (<a href="http://localhost:8080/health" rel="nofollow">http://localhost:8080/health</a>), the returned result is in XML (chrome sends the header <code>Accept: */*</code>).</p>
<p>When sending the request programmatically, you still have to pass <code>Accept: application/json</code> in your header since the service expects this media type, but the returned result will be XML.</p>
|
Mysqli connection using object <p>I just started switching my project form the mysql to mysqli. So what i did is i just create a class db and function connect.how can i create objects and re use it</p>
<p>This is my code:</p>
<p><strong>class db:</strong></p>
<pre><code>class db {
//global var session
private $biz;
//constructor
function db (&$b) {
$this->biz = $b;
$this->connect();
}
function connect() {
mysqli_connect(
$this->biz->_db['host']
, $this->biz->_db['username']
, $this->biz->_db['password']
,$this->biz->_db['database']
) or die("Unable to connect to database");
//$cont=mysqli_select_db($con,$this->biz->_db['database']) or die("Unable to select database: {$this->biz->_db['database']}");
//return $connt;
}
/*
This function will perform a simple query and return all the results
@return object Object containing the rows, num_rows and result
@param string $sql The SQL query
*/
function query($sql) {
$result = new fetchQuery($sql);
return $result;
}
/*
This function will perform a query given the sql
@return object Object containing num rows affected and result
@param string $sql The SQL query
*/
function updateQuery($sql) {
return new updateQuery($sql);
}
/*
This function will perform a query given the sql
@return object Object containing num rows affected and result
@param string $sql The SQL query
*/
function insertQuery($sql) {
return new insertQuery($sql);
}
/*
This function will perform a query given the sql
@return object Object containing num rows affected and result
@param string $sql The SQL query
*/
function deleteQuery($sql) {
return new deleteQuery($sql);
}
/*
This function will automatically decide if data is being updated or inserted
@param array $data The post object, key/value pairs , already validated
@param string $table The table to be updated
*/
/*
This function will perform an update query from the post data that has the correct form - fields matching table field names
@return object Object containing num rows affected and result
@param array $data The post object, key/value pairs , already validated
@param string $table The table to be updated
*/
function autoUpdate($data, $table,$wheredata) {
//id is required, return false if not found
if (!isset($wheredata))
{
return false;
}
$sql = "
UPDATE
`$table`
SET
";
foreach ($data as $key => $value) {
$sql .= " `$key` = '$value' ,";
}
//remove extra comma
$sql = substr($sql, 0, (strlen($sql) - 1));
$sql .= " WHERE 0=0 ";
foreach ($wheredata as $key => $value) {
$sql .= " and `$key` = '$value' ";
}
return new updateQuery($sql);
}
/*
This function will perform an insert query from the matching form table
@return object Object containing num rows affected and result
@param array $data The post object, key/value pairs , already validated
@param string $table The table to be updated
*/
function autoInsert($data, $table, $validate = false)
{
$_fields = array();
$_values = array();
foreach ($data as $field => $value) {
$_fields[] = $field;
$_values[] = $value;
}
$sql = "
INSERT INTO
`$table`
(
";
foreach($_fields as $field) {
$sql .= "`$field` ,";
}
//remove extra comma
$sql = substr($sql, 0, (strlen($sql) - 1));
$sql .= "
) VALUES (
";
foreach($_values as $value) {
$sql .= "'$value' ,";
}
//remove extra comma
$sql = substr($sql, 0, (strlen($sql) - 1));
$sql .= "
)
";
return new insertQuery($sql);
}
/*
This function will perform an auto delete query from the matching form table
@return object Object containing num rows affected and result
@param int $id The related id
@param string $table The table to be affected
*/
function autoDelete($sql) {
return new deleteQuery($sql); }
}
</code></pre>
<p><strong>fetch query:</strong></p>
<pre><code>class fetchQuery {
public $result;
public $num = 0;
public $rows = array();
public $error = false;
function fetchQuery($sql) {
$this->result = mysql_query($sql);
if ($this->result) {
$this->num = mysql_num_rows($this->result);
if ($this->num) {
while($row = mysql_fetch_assoc($this->result)) {
$this->rows[] = $row;
}
} else {
$this->result = false;
}
} else {
$this->result = false;
$this->error = mysql_error();
}
}
</code></pre>
<p>please give me a solution for create fetch query using connect function.</p>
| <p>You can create a basic function like strategy to handle this type of Scenario. Hence if you include the function file alone your DB will be connected on the fly and you can use this using the variable that you connect to the DB.</p>
<p>You can have two files and then you can perform the scenario like this.</p>
<p><strong>db.php</strong></p>
<pre><code><?php
class DB {
function __construct(){
$username='root';
$password='';
$host='localhost';
$db='store';
$this->connection = mysqli_connect($username,$password,$host,$db);
if(mysqli_connect_errno){
echo "Failed to connect to MYSQL: " . mysqli_connect_error();
}
}
function fetchData(){
$get_query = "SELECT * FROM TABLE"
$result = mysqli_query($this->connection, $get_query);
}
}
?>
</code></pre>
<p>And you can call the function in the page as follows.</p>
<blockquote>
<p>Usage of the class that we have created</p>
</blockquote>
<p><strong>listpage.php</strong></p>
<pre><code><?php
include('db.php'); // Include the DB file over this line
$conn= new DB(); // Initialize the class that we have created
$conn->fetchData();// This query will select all the data and return it.
?>
</code></pre>
<p>I hope so my explanation over the code are clear and you can understand it well and continue your project codes on the fly.</p>
<p>Happy Coding :)</p>
|
Subtracting UTC and non-UTC DateTime in C# <p>I assumed that when subtracting 2 datetimes the framework will check their timezone and make the appropriate conversions.</p>
<p>I tested it with this code:</p>
<pre><code>Console.WriteLine(DateTime.Now.ToUniversalTime() - DateTime.UtcNow.ToUniversalTime());
Console.WriteLine(DateTime.Now.ToUniversalTime() - DateTime.UtcNow);
Console.WriteLine(DateTime.Now - DateTime.UtcNow);
</code></pre>
<p>Output:</p>
<pre><code>-00:00:00.0020002
-00:00:00.0020001
01:59:59.9989999
</code></pre>
<p>To my surprise, <code>DateTime.Now - DateTime.UtcNow</code> does not make the appropriate conversion automatically. At the same time, <code>DateTime.UtcNow</code> is the same as <code>DateTime.UtcNow.ToUniversalTime()</code>, so obviously there is some internal flag that indicates the time zone.</p>
<p>Is that correct, does that framework not perform the appropriate timezone conversion automatically, even if the information is already present? If so, is applying <code>ToUniversalTime()</code> safe for both UTC and non-UTC datetimes, i.e. an already UTC datetime will not be incorrectly corrected by <code>ToUniversalTime()</code>?</p>
| <p>The type <code>System.DateTime</code> does not hold time zone information, only a <code>.Kind</code> property that specifies whether it is Local or UTC. But before .NET 2.0, there was not even a <code>.Kind</code> property.</p>
<p>When you subtract (or do other arithmetic, like <code>==</code> or <code>></code>, on) two <code>DateTime</code> values, their "kinds" are not considered at all. Only the numbers of ticks are considered. This gives compatibility with .NET 1.1 when <a href="https://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx" rel="nofollow">no kinds existed</a>.</p>
<p>The functionality you ask for (and expect) is in the newer and richer <a href="https://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx" rel="nofollow">type <code>System.DateTimeOffset</code></a>. In particular, if you do the subtraction <code>DateTimeOffset.Now - DateTimeOffset.UtcNow</code> you get the result you want. The <code>DateTimeOffset</code> structure does not have a local/UTC flag; instead, it holds the entire time zone, such as +02:00 in your area.</p>
|
What is the TcpListener.BeginAcceptTcpClient I/O Model in DotnetCore 1.0.x <p>I already know the BeginXXX(AMP) or XXXAsync(TAP) use IOCP in .NetFramework , then now I want to construct httpServer build on dotnetcore . so I need to know the inner mechanism.</p>
<p>My pervious version in .NetworkFramework like the follow code:</p>
<pre><code>private void continueAccept(TcpListener tcpListener,Action<TcpClient> processConnection)
{
//IOCP
tcpListener.BeginAcceptTcpClient(ar =>
{
if (listening)
continueAccept(tcpListener, processConnection);
else
return;
try
{
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
acceptCount++;
tcpClient.SendTimeout = 300000;
tcpClient.ReceiveTimeout = 300000;
ConsoleHost1.trace(System.Diagnostics.TraceEventType.Verbose, $"Client Accept { tcpClient.Client.RemoteEndPoint.ToString()}");
ThreadPool.QueueUserWorkItem((o) => {
processConnection((TcpClient)o);
}, tcpClient);
}
catch (Exception e)
{
ConsoleHost1.trace(System.Diagnostics.TraceEventType.Error, $"acceptTD:{e.Message}");
}
}, null);
}
public void startListen(Action<TcpClient> processConnection)
{
tcpListener = new TcpListener(IPAddress.Parse("0.0.0.0"), port1);
tcpListener.Start(maxQueue1);
listening = true;
continueAccept(tcpListener, processConnection);
}
</code></pre>
| <p>I have just resolved. </p>
<p><strong>In windows:</strong></p>
<p>AcceptAsync use the AcceptEx+SocketAsyncEventArgs(IOCP)<br>
BeginAccept use the AcceptEx+SafeNativeOverlapped(IOCP)</p>
<p>Reference from:
<a href="https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs" rel="nofollow">https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs</a>
<a href="https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs" rel="nofollow">https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs</a></p>
<p><strong>In Unix-like OS:</strong></p>
<p>AcceptAsync Or AcceptAsync use Interop.Sys.Accept + ThreadPool in user mode.</p>
<p>Reference from:
https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs</p>
|
I wonder how does a computer inrernally shut down when we click on shut down option? Is there also something with binary system? <p>For example how a printer prints a page?
CPU transfers binary 8 bit codes to printer than...... so like this what happens with the computer internally when we start or shut down it?</p>
| <p>The original <a href="https://en.wikipedia.org/wiki/IBM_Personal_Computer/AT" rel="nofollow">AT computers</a> used the <a href="https://en.wikipedia.org/wiki/Power_supply_unit_(computer)#Original_IBM_PC.2C_XT_and_AT_standard" rel="nofollow">AT PSU</a> which had <em>only</em> a mechanical switch to turn the power on and off:</p>
<blockquote>
<p>An early microcomputer power supply was either fully on or off, controlled by the mechanical line-voltage switch, [...]. These power supplies were generally not capable of power saving modes such as standby or "soft off", or scheduled turn-on power controls.</p>
</blockquote>
<p>and thus were not powered off by the software.</p>
<p>In the 1994 the <a href="https://en.wikipedia.org/wiki/ATX" rel="nofollow">ATX</a> PSUbecome popular, such <a href="https://en.wikipedia.org/wiki/Power_supply_unit_(computer)#ATX_standard" rel="nofollow">PSU</a> introduced a pin called <em>Power ON</em> (henceforth <em>PWON</em>) that is pulled to +5V and that must be pulled down by the motherboard to activate the PSU<sup>1</sup>.</p>
<p>Since PWON is an electrical signal, the motherboard can implement different kinds of logic to switch the power on and off. </p>
<p>A front panel switch was introduced first, it was the only way to switch on/off the PC</p>
<p><a href="https://i.stack.imgur.com/DiyX8.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/DiyX8.jpg" alt="Windows 95, Turn off screen"></a></p>
<p>A "soft-off" mode were then introduced, this mode leaves some low-powered rails on for different devices to stay active and trigger a wake-up by pulling PWON down.<br>
For example: <a href="https://en.wikipedia.org/wiki/Wake-on-LAN" rel="nofollow">Wake-on-LAN</a>, <a href="https://en.wikipedia.org/wiki/Wake-on-ring" rel="nofollow">Wake-on-ring</a>, <a href="https://en.wikipedia.org/wiki/Real-time_clock_alarm" rel="nofollow">RTC alarm</a>. </p>
<p>Until the introduction of <a href="https://en.wikipedia.org/wiki/Advanced_Power_Management" rel="nofollow">APM</a> the software could not switch off the PC in a standard way. </p>
<p>APM however has been lately superseded by <a href="https://en.wikipedia.org/wiki/Advanced_Configuration_and_Power_Interface" rel="nofollow">ACPI</a> which is a very complex system. </p>
<p>It is not hard to image what could it take to power off a PC, thanks to the PWON signal, all that is needed is to tell the chip attached to it to release it back to +5V.<br>
There is not a standard way to do this, but the very purpose of ACPI is to overcome the differences among manufacturers. </p>
<p>In particular ACPI define that in order to power down the system, put it into state <em>S5</em>, the software need to perform a fixed sequence of steps.<br>
All the information can be found in the <a href="http://acpi.sourceforge.net/dsdt/" rel="nofollow">DSDT (Differential System Descriptor Table)</a> and the <a href="http://wiki.osdev.org/FADT" rel="nofollow">FACP (Fixed ACPi descriptor table)</a> tables exposed by the ACPI. </p>
<p>The first step is invoking a method called <code>\_S5._PTS</code> that in my system does nothing:</p>
<pre><code>Method (PTS, 1, NotSerialized)
{
If (Arg0) {}
}
</code></pre>
<p>This gives the motherboard designer a change to perform complex operations since this method is written by them. </p>
<p>The other step is fixed, it the actual step that turns the PC down, and it consist in <strong>writing a value into a register</strong>.<br>
The register of interest (actually there are two, but we don't discuss it here) is <code>PM1a_CNT</code>, in my system is advertised as</p>
<pre><code>[0ACh 0172 12] PM1A Control Block : [Generic Address Structure]
[0ACh 0172 1] Space ID : 01 [SystemIO]
[0ADh 0173 1] Bit Width : 10
[0AEh 0174 1] Bit Offset : 00
[0AFh 0175 1] Encoded Access Width : 02 [Word Access:16]
[0B0h 0176 8] Address : 0000000000001804
</code></pre>
<p>that tell us that is is located at <code>1804h</code> in the IO space<sup>2</sup>. </p>
<p>The value to write into this register is called <code>SLP_TYPa</code> and it is located in the <code>_S5</code> object, for my system:</p>
<pre><code>Name (_S5, Package (0x04) // _S5_: S5 System State
{
0x07,
Zero,
Zero,
Zero
})
</code></pre>
<p><code>SLP_TYPa</code> is the first number, <code>07h</code>.<br>
Before writing this number into <code>PM1a_CNT</code>, we need to set its bit13, so the actual value to write is <code>2007h</code>.</p>
<p>To turn the power down I just need to write <code>2007h</code> to the port <code>1804h</code><sup>3</sup>:</p>
<pre><code>mov ax, 2007h
mov dx, 1804h
out dx, ax
</code></pre>
<hr>
<p><sup>1</sup> You can use a paper clip to short PWON (green) to GND (black) and turn the PSU ON when not connected to a PC.<br>
<sup>2</sup> My system is an x86, x86s have tow address spaces: IO and memory.<br>
<sup>3</sup> Granted ACPI is enabled. </p>
|
php -f executes script from page but accessing web page does not? <p>My problem is that i don't have any proper explanation for this happening. </p>
<p>When i run the php file with the script in it using run command <code>php -f "file"</code> it executes properly.</p>
<p>When i run it via webpage, it does not, i have to manually run it via command line first to get web page results.</p>
<p>I have tried using the old and new <code>php</code> tags as i found such a suggestion but doesn't help, all other like pages run fine.</p>
<p>Do you have any suggestions ?</p>
| <p>stupid me, on server i had root privileges for file i was editing via script, on webpage i did not, gave the right permissions, all works )) </p>
|
vim creates swap file every exit, complains each future edit <p>I'm using vim 7.4 within cygwin on a Windows 10 OS. Every single time I edit a file with vim, it seems to leave a .swp file in the directory. The next edit of that file complains about an existing swap file. This is very annoying.</p>
<p>I know I can disable the creation of swap files, but I've used vim on many other machines and this is the only one that appears to have this issue. There must be some explanation for why vim isn't deleting these files?</p>
<p>FYI - I'm using <code>:wq</code> to save my edits and quit.</p>
| <p>You may find that you have another instance of VIM open with the file and it is the owner of the swap file. This can happen if you accidentally pressed "Ctrl+Z" which is fairly easy if you're a windows user (undo shortcut).</p>
<p>Run "ps -a" to see if there is another instance of vim running.</p>
|
Receive POST data from login on page, but form action goes to other page <p>Currently I have a login script with a form that goes login.php, on this page the user can login, and the server checks his/her email & password combination. </p>
<p>Now I have another page were users can enter a other form, called employees.php, in this page there is called a input field email, which is to disabled so users can only call them selves sick. </p>
<pre><code><form class="form" action="absent.php" method="get">
<p class="text">Email:</p>
<input type="text" maxlength="25" name="name" placeholder="<?php echo $email?>" disabled required>
<p class="text">Reason:</p>
<textarea style="width: 350px" maxlength="100" name="reason" required></textarea>
<p class="text">Date:</p>
<input type="date" name="date" required value="<?php echo date('Y-m-d'); ?>" / min="<?php echo date('Y-m-d'); ?>">
<br><br><br>
<input type="submit" value="Send">
<input type="hidden" name="email" value="<?php echo $email?>" />
</code></pre>
<p>This works good, the only problem that I am currently struggling with is that I can't make it work that the Email is connected to the users login email. </p>
<pre><code>session_start();
if( isset($_SESSION['user_id'])){
$email = 'placeholder@test.com';
}
else {
header("Location: nologin.php");
}
</code></pre>
<p>This is the code I am using at the top of employees.php. </p>
<p>And this is the form code I am using at login.php.</p>
<pre><code><form action="login.php" method="POST">
<input type="email" placeholder="Enter email" name="email" required>
<input type="password" placeholder="and password" name="password" required>
<input type="submit" value="Log In">
</form>
</code></pre>
<p>So how can I make it to work that when a user logs in with his/her account, the email address is automatically filled in, in a not editable inputfield at employees.php?</p>
<p>Thanks in advance!</p>
| <p>you have to grab the email from the database first and save it as a session variable. e.g</p>
<pre><code><?php
require_once 'inc/config.php';
if(isset($_POST['login'])) { //if the login button was clicked
$username = mysql_real_escape_string($_POST['username']); //
$password = mysql_real_escape_string($_POST['password']);
$selUser = "SELECT * FROM users WHERE login ='${login}' AND password = '${password}'";
$runUser = mysqli_query($conn, $selUser);
$checkUser = mysqli_num_rows($runUser);
while($row = $runUser) {
$_SESSION['email'] = $row['email']; //grabs the email from the database and stores it in a session variable
}
if($checkUser > 0) {
$_SESSION['user_id'] = $username;
echo "<script>window.open('employee.php?login=1','_self')</script>";
}
else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
header("Location: login.php?err=1");
}
}
?>
</code></pre>
<p>the other script will look like this</p>
<pre><code><?php
session_start();
if( isset($_SESSION['user_id'])){
$email = $_SESSION['email'];
}
else {
header("Location: nologin.php");
}
?>
</code></pre>
|
Can't load Django static files in view <p>I'm a new player in Django and Python. I want to load the static files from the project level static folder. The problem is I can't but I still can load the static of an app.
This is the structure of my project:</p>
<pre><code>Yaas
__init__.py
settings.py
urls.py
wsgi.py
templates
base.html
static
style.css
auction
templates
auction
index.html
static
auction
style.css
__init__.py
apps.py
models.py
urls.py
views.py
</code></pre>
<p>The thing is it works with static file of auction, like this in base.html:</p>
<pre><code>{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'auction/style.css' %}" />
</code></pre>
<p>But it returns 404 with the project static file:</p>
<pre><code>{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
</code></pre>
<p>settings.py</p>
<pre><code>STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
</code></pre>
<p>I tried other solutions and document on Django but it still didn't work. I am using Django 1.10.</p>
| <p>I made this work by adding the following:</p>
<pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
</code></pre>
<p>From the <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files" rel="nofollow">docs</a> (after point 4):</p>
<blockquote>
<p>Your project will probably also have static assets that arenât tied to
a particular app. In addition to using a static/ directory inside your
apps, you can define a list of directories (STATICFILES_DIRS) in your
settings file where Django will also look for static files.</p>
</blockquote>
<p>Please note that the <code>STATIC_ROOT</code> directory, where Django will output all collected static files found in each <code><app>/static</code> and <code>STATICFILES_DIRS</code> directories, must be different.</p>
<p>Hope that helps!</p>
|
PowershellScript ObjectNotFoundException CommandNotFoundException Path <p>I sign my Dlls with SNK-Files. This is done without problems through the visual studio build.</p>
<p>Now i want to validate the DLLs that I really gave them a strong name. I found <a href="http://practicethis.com/script-validate-assemblys-snk-using-powershell/" rel="nofollow">this powershell script</a>, but I think powershell hates my path.</p>
<pre><code>Clear-Host
$path="C:\Users\MyName\Desktop\BuildOutput\Debug"
$snPath = "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe"
foreach ($item in Get-ChildItem $path -Recurse -Include *.dll, *.exe)
{
$reportLine = $item.FullName + "," + $item.Extension
#validate integrity
$expression = $snPath + ' -vf "' + $item.FullName +'"'
$verify = Invoke-Expression $expression
$isValid = $verify | Select-String -Pattern "is valid"
if($isValid)
{
$reportLine = $reportLine + ",ist signiert"
}
else
{
$reportLine = $reportLine + ",ist nicht signiert"
}
#extract token
$expression = $snPath + ' -Tp "' + $item.FullName +'"'
$result = Invoke-Expression $expression
$tokenString = $result | Select-String -Pattern "key token is"
if($tokenString)
{
$token = $tokenString.Tostring().Substring(20)
$reportLine = $reportLine + "," +$token
}
$reportLine
}
</code></pre>
<p>And my error is</p>
<blockquote>
<p>In Line:1 Character:19</p>
<ul>
<li>C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 ...</li>
<li>~~~
<ul>
<li>CategoryInfo : ObjectNotFound: (x86:String) [], CommandNotFoundException</li>
<li>FullyQualifiedErrorId : CommandNotFoundException</li>
</ul></li>
</ul>
</blockquote>
<p>I translated more error information.</p>
<blockquote>
<p>The term "x86" was not recognized as the name of a cmdlet, function, script file, or executable.
Check the spelling of the name, or if the path is correct (if included), and retry.</p>
</blockquote>
<p>Do I have to escape the x86? And if yes - How can i do it? I tried <a href="http://www.jonathanmedd.net/2013/03/powershell-quick-tip-accessing-the-programfilesx86-environment-variable.html" rel="nofollow">this</a>.</p>
<p>I tried this with allways the same result.</p>
<pre><code>$snPath = "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe"
$snPath = ${env:CommonProgramFiles(x86)} + "\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe"
$snPath = ${env:ProgramFiles(x86)} + "\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe"
$snPath = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)") + + "\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe"
</code></pre>
<p>Powershell Version</p>
<p>Major: 5<br>
Minor: 1
Build: 14393
Revision: 103</p>
<p><strong>EDIT</strong></p>
<p>I fixed my snPath</p>
<p>I gave more examples</p>
<p>more error Information</p>
| <p>instead of </p>
<pre><code>$expression = $snPath + ' -vf "' + $item.FullName +'"'
$verify = Invoke-Expression $expression
</code></pre>
<p>you could do it like that: </p>
<p><code>$verify = & $snPath -vf $item.FullName</code></p>
|
Why does pandas dataframe indexing change axis depending on index type? <p>when you index into a pandas dataframe using a list of ints, it returns columns.</p>
<p>e.g. <code>df[[0, 1, 2]]</code> returns the first three columns.</p>
<p>why does indexing with a boolean vector return a list of rows?</p>
<p>e.g. <code>df[[True, False, True]]</code> returns the first and third rows. (and errors out if there aren't 3 rows.)</p>
<p>why? Shouldn't it return the first and third columns?</p>
<p>Thanks!</p>
| <p>Because if use:</p>
<pre><code>df[[True, False, True]]
</code></pre>
<p>it is called <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> by mask:</p>
<pre><code>[True, False, True]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9]})
print (df)
A B C
0 1 4 7
1 2 5 8
2 3 6 9
print (df[[True, False, True]])
A B C
0 1 4 7
2 3 6 9
</code></pre>
<p>Boolean mask is same as:</p>
<pre><code>print (df.B != 5)
0 True
1 False
2 True
Name: B, dtype: bool
print (df[df.B != 5])
A B C
0 1 4 7
2 3 6 9
</code></pre>
|
How can I delay a change to my model until I finish typing? <p>I have this field:</p>
<pre><code> <input ng-model="phs.englishRange"
style="width:6rem;"
type="text" />
</code></pre>
<p>The word is used in a filter so when I make any changes to it the filter changes while the changes are being made. Is there a way I can delay this to the model changes 1 second after I stop typing?</p>
| <p><strong>For your use-case</strong>, to trigger model update 1s after last character typed (model update timer will be reset each time): </p>
<pre><code>ng-model-options="{ updateOn: 'default', debounce: {'default': 1000} }"
</code></pre>
<p><strong>More options - update on blur:</strong></p>
<pre><code>ng-model-options="{ updateOn: 'blur' }"
</code></pre>
<p>Options are "default" (as you type) and/or "blur" (when you leave the input).</p>
<p>You can also use <code>debounce</code> inside model-options to control how fast to issue the model update. </p>
<pre><code>debounce: { 'default': 500, 'blur': 0 }
</code></pre>
|
Bootstrap dropdown hover transition <p>I'm trying to get a fade in transition on my Bootstrap dropdown menu on hover. So far I have tried the following with no luck.</p>
<p><strong>My attempt</strong></p>
<pre><code>.dropdown-menu {
display: block;
opacity: 0;
-moz-transition: all 1000ms ease;
-webkit-transition: all 1000ms ease;
-o-transition: all 1000ms ease;
-ms-transition: all 1000ms ease;
transition: all 1000ms ease;
}
.sidebar-nav li:hover .dropdown-menu {
display: block;
opacity: 1;
}
</code></pre>
<p>This didn't work. It delayed it by 1000ms, but didn't add any transition. I have also tried with jQuery, but without any luck aswell.</p>
<p><a href="https://jsfiddle.net/52hgLprm/1/" rel="nofollow">Here's a fiddle with the code</a> - The dropdown menu is on the first link "Arla nu" in the menu.</p>
| <p>You seem to have just left off telling what to transition.</p>
<pre><code>.dropdown-menu {
-webkit-transition: opacity 1000ms ease;
-moz-transition: opacity 1000ms ease;
-o-transition: opacity 1000ms ease;
transition: opacity 1000ms ease;
opacity: 0;
}
.sidebar-nav li:hover .dropdown-menu {
opacity: 1;
}
</code></pre>
|
How @Tested internally creates object for singleton class? <p>@Tested internally instantiates the class object. But in case of singleton class how @Tested internally creates instance because for singleton private constructor is there.</p>
| <p>Private constructors (or fields, methods, etc.) can always be executed/accessed through Reflection.</p>
<p>When <code>@Tested</code> is used, an instance gets created regardless of the constructor's accessibility. This is described in the <a href="http://jmockit.org/api1x/mockit/Tested.html" rel="nofollow">API documentation</a>:</p>
<blockquote>
<p>if there are multiple satisfiable constructors then the one with the most parameters and the widest accessibility (ie, first public, then protected, then package-private, and finally private) is chosen.</p>
</blockquote>
|
How to insert {{$index}} into an ng-class directive? <p>I have a directive that loops through a list and adds class upon <code>div</code> elements like this :</p>
<p><code><div ng-class="{'has-error' : error.degreeYear_{{$index}}} /></code></p>
<p>When I inspect the element, the source code shows the index being properly replaced</p>
<pre><code><div ng-class="{'has-error' : error.degreeYear_5} />
</code></pre>
<p>But, it gives an error, upon clicking which, the angularJS site shows this : </p>
<pre><code>Error: $parse:syntax
Syntax Error
Syntax Error: Token '{' is an unexpected token at column 18 of the expression [error.degreeYear_{{] starting at [{4}].].
</code></pre>
<p>I am assuming the angular braces around <code>$index</code> is the culprit because the entire <code>ng-class</code> expression has to be already enclosed in angular brackets. How should I handle this ?</p>
| <p>Like this:</p>
<pre><code><div ng-class="{'has-error' : error.degreeYear_ + $index} />
</code></pre>
<p>Since <code>ng-class</code> is already an expression there is no need for the double brackets. </p>
|
Add variable amount of trailing zeros based on input integer <p>There are a lot of questions regarding rounding decimal to 2 decimals points after the comma, or adding leading zeros. I'm unable however, to find one which adds trailing zeros with a variable amount of zeros.</p>
<p><strong>What I want to achieve:</strong><br>
With a positive integer <strong><em>n</em></strong>, I want to have the decimal 1/<strong><em>n</em></strong> with <strong><em>n</em></strong> amount of digits after the comma. So the first 10 would be:</p>
<pre><code>1/1 = 1 -> 1.0
1/2 = 0.5 -> 0.50
1/3 = 1.333... -> 1.333
1/4 = 0.25 -> 0.2500
1/5 = 0.2 -> 0.20000
1/6 = 0.666... -> 0.666666
1/7 = 0.142... -> 0.1428571
1/8 = 0.125 -> 0.12500000
1/9 = 0.111... -> 0.111111111
1/10 = 0.1 -> 0.1000000000
</code></pre>
<p>Preferably I have the result as a String and use code which is as short as possible. So no for-loops, or all kind of Formatter settings. Preferably something like <code>String.format(..., n);</code> or some other short solution.</p>
<p>I did try <code>String.format("%f0", 1./n);</code> to see what it would output, but this only adds up until 7 digits (no idea how this is set up and if this is configurable). So for <code>String.format("%f0", 1./8);</code> the output is <code>0.1250000</code> missing the 8th zero.</p>
| <p>Try the following:</p>
<pre><code>String.format("%." + n + "f", (1.0/n));
</code></pre>
|
Push notification codelab Uncaught SyntaxError: Unexpected identifier in curl request <p>I am following this tutorial <a href="https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/#send_a_request_from_the_command_line_for_fcm_to_push_a_message" rel="nofollow">https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/#send_a_request_from_the_command_line_for_fcm_to_push_a_message</a></p>
<p>And when I do this </p>
<pre><code>curl --header "Authorization: key=AIzaSyCQHb2t8c3N255bH_CVmGych5QcNntFxYg" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"APA91bE4RJ7_9m2eJ_zlg1F90bLjVX8ctVpCBN24ElAXF--4wS_nnxg4LzkbJWeTe-peMN_StmOaQTEoGeCCNZE5Mssux3T-KbfGRVmRWzeQZM8opfUyv7FVjI9iEfETHG3O7i1qkIb-\"]}"
</code></pre>
<p>I get Uncaught SyntaxError: Unexpected identifier</p>
<p>But I did everything as in the tutorial. And I put my api key there, my sender id is in the manifest.json as well, and I put the subscription endpoint url there as well. This is the endpoint <code>endpoint: https://android.googleapis.com/gcm/send/cl72SS1zE50:APA91bE4RJ7_9m2eJ_zlg1Fâ¦peMN_StmOaQTEoGeCCNZE5Mssux3T-KbfGRVmRWzeQZM8opfUyv7FVjI9iEfETHG3O7i1qkIb-</code></p>
<p>So why do I get this error, what identifier does it mean?</p>
| <p><code>curl --header etc etc</code> is a shell command. The tutorial you link to says <em>From your terminal, run the cURL command below</em></p>
<p><em>Uncaught SyntaxError: Unexpected identifier</em> is a JavaScript error message. You appear to be trying to enter that code in a JavaScript program (possibly by pasting it into a browser's Developer Tools Console or a Node.JS REPL). </p>
<p>You need to run the command on a shell (such as Bash or Windows Power Shell) not in a JS program.</p>
|
How to find exact value using xpath in selenium webdriver? <p>I am using <code>XPath</code> to find exact value:</p>
<p><code>//h5[@class='familyName productFamilyName'][contains(text(),'Dozers ')]</code></p>
<p>but it was failing because in my application there are 2 elements with text values <code>"Dozers "</code> and <code>"Dozers wheel"</code> which is come under same class.
I can't use id locators,because it is dynamically generating in my application like <code>//div[@id="482"]/div/div[1]/h5</code>.</p>
<p>Please suggest me any solution.</p>
| <p>If you want to match element with exact <code>innerHTML</code> value just use </p>
<pre><code>//h5[@class='familyName productFamilyName'][text()='Dozers')]
</code></pre>
<p>or </p>
<pre><code>//h5[@class='familyName productFamilyName'][text()='Dozers wheel')]
</code></pre>
<p>Depending on <code>HTML</code> structure you might need to use <code>[.='Dozers']</code> or </p>
<p><code>[normalize-space(.)='Dozers']</code> instead of <code>[text()='Dozers']</code></p>
|
Twitter Fabric TWTTweet image shrinks <p>I am using fabric for showing the <code>tweetView</code> everything is fine but sometimes some tweets has images with a wrong size</p>
<pre><code> self.tableView.register(TWTRTweetTableViewCell.self, forCellReuseIdentifier: "tweetCell")
TwitterOAuth.getTimelineTweets(String(self.count), completion: { (data) in
if let trendArr = data as? NSArray {
self.homeTweets = TWTRTweet.tweets(withJSONArray: trendArr as [AnyObject])
self.tableView.reloadData()
}
})
</code></pre>
<p><a href="https://i.stack.imgur.com/fsTYV.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/fsTYV.jpg" alt="enter image description here"></a></p>
<p>Any idea? Thanks</p>
| <p>Mike from Fabric here. This was a bug in version 2.4.0, version 2.5.0 has the fix. From the release notes <a href="https://docs.fabric.io/apple/changelog.html#id38" rel="nofollow">here</a>: </p>
<p>"Fixed bug where Retweets with photos did not layout correctly".</p>
<p>If you update to the latest version, the issue should be resolved. </p>
|
Get a default-initialized (NOT value/zero-initialized) POD as an rvalue <pre><code>#include <iostream>
struct A {
int x;
};
void foo(A a) {
std::cout << a.x << std::endl;
}
int main() {
A a;
foo(a); // -7159156; a was default-initialized
foo(A()); // 0; a was value-initialized
}
</code></pre>
<p>Is it possible to pass an rvalue of type <code>A</code> to <code>foo()</code> without value-initializing it? Do we have to use either value-initialization or an lvalue?</p>
<p>What's the point of avoiding value-initialization when it "costs" no more than ten nanoseconds, you may ask. How about a situation like this: we are hunting for a bug in an legacy app caused by an uninitialized memory access with valgrind, and zero is NOT considered as a valid value for the app. Value initialization will prevent valgrind to spot the location of uninitialized memory access.</p>
<p>You may say printing an uninitialized value is an UB but my "real" use case is not limited to printing. My question should remain valid without it.</p>
| <p>If i understand the question correctly you need a replacement for <code>foo(A());</code> or similar cases where <code>A()</code> is called so that you don't have default initialization of members.</p>
<p>In that case one here is what i came up with:</p>
<ul>
<li><p>First i tried to add <code>A() = default</code> (but this might not work with older c++ standards) and i had <a href="http://ideone.com/iVKoIA" rel="nofollow">interesting results</a>. The exact sample you provided works in reverse printing first 0 and then some random number.</p></li>
<li><p>Second i did not use <code>A() = default;</code> and just used a templated function</p>
<pre><code>template <class T> T make() { T tmp; return tmp; }
</code></pre>
<p>At the cost of a copy (or move) you can use it like <code>foo(make<A>())</code> and get the result you wanted.</p></li>
</ul>
|
C# tabbed MDI forms: Always last tab is closed <p>I was following the tabbed MDI forms example from <a href="http://www.codeproject.com/Articles/17640/Tabbed-MDI-Child-Forms" rel="nofollow">HERE</a>. I just copied the code into a test application.</p>
<p>The problem is, that if I press the "X" button to close a form, always the last tab closes and not the selected one.
But in the example solution it works perfectly. However I can't find any difference in code, properties or events to my test project.</p>
<p>I hope someone gives me a hint.</p>
| <pre><code> private void tabForms_SelectedIndexChanged(object sender, EventArgs e)
</code></pre>
<p>you may missed this code of , forgot the event binding with this </p>
|
how to get correct hight when we have some content on UIWebView in swift iOS? <p>I have disqusView(link) in UIWebView, I want to scroll webView as the size of disqusView, I don't want default scroll of webView</p>
<p>here is my code,in these I'm getting more height then actual height of webView content size.</p>
<pre><code>func webViewDidFinishLoad(webView: UIWebView) {
let cgfloat = web_discus.scrollView.contentSize.height as CGFloat
}
</code></pre>
<p>or </p>
<pre><code>web_discus.stringByEvaluatingJavaScriptFromString("document.hight")! as String
</code></pre>
<p>but both give more height then actual that`s why it show more blank space while scrolling down..</p>
<p>I also tried this one :</p>
<pre><code>web_discus.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")! as String
</code></pre>
<p>Is there any way to get perfect hight for webView content ?</p>
| <p>Seems you want the <code>contentSize</code> of the <code>webView</code>? If that is the case, then this other StackOverflow question should point you in the right direction <a href="http://stackoverflow.com/questions/3936041/how-to-determine-the-content-size-of-a-uiwebview">link</a></p>
<p>Essentially you'd do <code>webView.sizeThatFits(CGSizeZero)</code>. </p>
|
Sometimes "Content Download" takes too long in Chrome and other major browsers <p>When I refresh my website (Ctrl+F5), loading of <br/>
<code>/bundles/Script?v=kHj78R8CVSwiLFaq5EOrj6UALoxbJmoUCasHhdgb9EQ1</code> <br/>
<em>(this is the script bundle that contains few js files, 2kb, 2kb, 70kb and the biggest one is the "kendo.all.min.js" that weighs 2mb)</em> <br>
takes too long one time in two. It took me 47 seconds to download this (see picture below). <br>
What could be a problem?
<br>Thank you in advance !!</p>
<p><a href="https://i.stack.imgur.com/dFJdG.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/dFJdG.jpg" alt="Photo"></a></p>
| <blockquote>
<p>What could be a problème?</p>
</blockquote>
<hr>
<blockquote>
<p>that weighs 2mb</p>
</blockquote>
<p>You can utilize <code>localStorage</code> or <code>requestFileSystem</code> to download files once, at each subsequent load of page retrieve files from <code>storage</code> or <code>LocalFileSystem</code>, see <a href="http://stackoverflow.com/questions/39784514/how-to-cache-a-downloaded-javascript-fle-which-is-downloaded-using-script-tag/39784622#39784622">How to cache a downloaded javascript fle which is downloaded using script tag</a></p>
|
Symfony2 host matched route matches other routes too <p>Here is my routing.yml file</p>
<pre><code>admin:
path: /
host: "admin.devhostname.com"
defaults:
_controller: AdminBundle:Default:index
app:
resource: "@AppBundle/Controller/"
type: annotation
prefix: /
</code></pre>
<p>Everything works fine, except <code>admin.devhostname.com/contact_us</code> matches my <code>app</code> routing for <code>contact_us</code>. Because <code>app:</code> routing catches <code>ANY</code> host config. To get the result I want I need to add <code>host:</code> to every other route config. Is there any better way to achieve this?</p>
| <p>Here is what solution I figured out. So far is the best way. </p>
<p>I moved all site related routes in another file routing_site.yml and then included that routing with <code>host</code>.</p>
<pre><code>admin:
path: /
host: "admin.%domain%"
defaults:
_controller: AdminBundle:Default:index
app:
resource: routing_site.yml
host: "%domain%"
</code></pre>
|
umbraco cms I'm confused <p>I need information.
My company gave me to edit a site created with CMS Umbraco. I opened it with Visual Studio and it works correctly, but if I want to change the code is different from normal just because it has been used Umbraco.</p>
<p>They told me I have to open it directly in the CMS Umbraco.
I installed it but I can't import the project.
can you help me?</p>
| <p>You need to be a bit clearer.</p>
<p>Umbraco is a content management system, if you want to edit content then you will need to be running an instance of Umbraco, you will need to be logged in as an administrator and you will need to publish any changes.</p>
<p>The login URL should be <a href="http://yourdomain.com/umbraco" rel="nofollow">http://yourdomain.com/umbraco</a></p>
<p>So you shouldn't be importing anything, you just need the site up and running in IIS and a running version of the database.</p>
<p>The Umbraco user forum is a great place to start.</p>
|
python preserving output csv file column order <p>The issue is common, when I import a csv file and process it and finally output it, the order of column in the output csv file may be different from the original one,for instance:</p>
<pre><code>dct={}
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]
header = dct.keys()
rows=pd.DataFrame(dct).to_dict('records')
with open('outTest.csv', 'wb') as f:
f.write(','.join(header))
f.write('\n')
for data in rows:
f.write(",".join(str(data[h]) for h in header))
f.write('\n')
</code></pre>
<p>the original csv file is like:</p>
<pre><code>a,c,b
1,9,5
2,10,6
3,11,7
4,12,8
</code></pre>
<p>while I'd like to fixed the order of the column like the output:</p>
<pre><code>a,b,c
1,5,9
2,6,10
3,7,11
4,8,12
</code></pre>
<p>and the answers I found are mostly related to <code>pandas</code>, I wonder if we can solve this in another way.</p>
<p>Any help is appreciated, thank you.</p>
| <p>Instead of <code>dct={}</code> just do this:</p>
<pre><code>from collections import OrderedDict
dct = OrderedDict()
</code></pre>
<p>The keys will be ordered in the same order you define them.</p>
<p>Comparative test:</p>
<pre><code>from collections import OrderedDict
dct = OrderedDict()
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]
stddct = dict(dct) # create a standard dictionary
print(stddct.keys()) # "wrong" order
print(dct.keys()) # deterministic order
</code></pre>
<p>result:</p>
<pre><code>['a', 'c', 'b']
['a', 'b', 'c']
</code></pre>
|
What's the best way to separate each stone in an image with many stones (some above the others) <p>I need to make a study of the floor of a lake, and have to calculate the number and average size of the stones on the floor.</p>
<p>I have been studying morphological procedures to solve it in OpenCV but still need to find a way to try to separate the stones and make a binary image that precisely shows theirs contours.</p>
<p>I still didn't take the pictures, but the images will be something like the following:</p>
<p><a href="https://i.stack.imgur.com/tgeAf.png" rel="nofollow"><img src="https://i.stack.imgur.com/tgeAf.png" alt="enter image description here"></a></p>
<p>What is the best algorithm to separate each stone and get their contours?
And if this kind of image is too complex to properly separate the stones, what is the best method to have a size x number estimation? </p>
| <p>Wathershed is probably what will give you an approximation to the solution.</p>
<p>Other thing that you may do is try labelling images with the number of flakes and particles you can count and feed it to a deep neural net and let it findout how to count the flakes, if you have enough training cases you may endup with a good result in the output</p>
<p>information on whatershed can be found at this link
<a href="http://www.pyimagesearch.com/2015/11/02/watershed-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/11/02/watershed-opencv/</a></p>
|
How can I know how many elements does req.body holds? <p>I've been learning <em>express.js</em> and <em>node js</em> recently, and I'm developing a questionnaire form which posts the relevant parameters to the server. I'd like to know if my clients complete all questions. How can I check how many elements are in <code>req.body</code>.</p>
<p>Does <code>req.body</code> has the property <code>.length</code>?</p>
<p>Thanks a lot.</p>
| <p>You need to parse req.body for that. I recomend to use some kind of bodyparser middleware. Once you get it parsed, it should give an object, and there you can count the keys of that object. ie</p>
<pre><code>var count = Object.keys(myParsedBodyObject).length
</code></pre>
|
Math, something a bit complicated for me <p>so I have a math question, i need to use it in my code.
say this:</p>
<hr>
<pre><code>630 ---> 10000
125 ---> 1000
230 ---> ??
can anyone help me solve this?
with an explanation maybe...
</code></pre>
<hr>
| <p>It looks like multiplication by 5 on the left translates to multiplication by 10 on the right, as 125*5=625. I'd guess that you do not want a linear but an exponential connection, something like</p>
<pre><code>y=10^log5(x) = pow( 10, log(x)/log(5) )
= x*pow( 2, log(x)/log(5) )
= x*pow(x, log(2)/log(5) )
</code></pre>
|
How to include __build_class__ when creating a module in the python C API <p>I am trying to use the <a href="https://docs.python.org/3/c-api/" rel="nofollow">Python 3.5 C API</a> to execute some code that includes constructing a class. Specifically this:</p>
<pre><code>class MyClass:
def test(self):
print('test')
MyClass().test()
</code></pre>
<p>The problem I have is that it errors like this:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: __build_class__ not found
</code></pre>
<p>So somehow I need my module to include <code>__build_class__</code>, but I am not sure how (I guess that I would also miss other things you get by default when using <a href="https://www.python.org/" rel="nofollow">Python</a> too) - is there a way to include all this built-in stuff in my module?</p>
<p>Here is my code so far:</p>
<pre><code>#include <Python.h>
int main(void)
{
int ret = 0;
PyObject *pValue, *pModule, *pGlobal, *pLocal;
Py_Initialize();
pGlobal = PyDict_New();
pModule = PyModule_New("mymod");
pLocal = PyModule_GetDict(pModule);
pValue = PyRun_String(
"class MyClass:\n\tdef test(self):\n\t\tprint('test')\n\nMyClass().test()",
Py_file_input,
pGlobal,
pLocal);
if (pValue == NULL) {
if (PyErr_Occurred()) {
PyErr_Print();
}
ret = 1;
} else {
Py_DECREF(pValue);
}
Py_Finalize();
return ret;
}
</code></pre>
<p>so <code>pValue</code> is <code>NULL</code> and it is calling <code>PyErr_Print</code>.</p>
| <p>Their are (at least) two ways to solve this it seems...</p>
<h2>Way 1</h2>
<p>Instead of:</p>
<pre><code>pGlobal = PyDict_New();
</code></pre>
<p>You can import the <code>__main__</code> module and get it's globals dictionary like this:</p>
<pre><code>pGlobal = PyModule_GetDict(PyImport_AddModule("__main__"));
</code></pre>
<p>This way is described like so:</p>
<blockquote>
<p>BUT PyEval_GetGlobals will return null it it is not called from within
Python. This will never be the case when extending Python, but when Python
is embedded, it may happen. This is because PyRun_* define the global
scope, so if you're not somehow inside a PyRun_ thing (e.g. module called
from python called from embedder), there are no globals. </p>
<p>In an embedded-python situation, if you decide that all of your PyRun_*
calls are going to use <code>__main__</code> as the global namespace,
PyModule_GetDict(PyImport_AddModule("<code>__main__</code>")) will do it.</p>
</blockquote>
<p>Which I got from the question <a href="http://www.gossamer-threads.com/lists/python/python/8946#8946" rel="nofollow">embedding</a> I found over on this <a href="http://www.gossamer-threads.com/lists/python/python/" rel="nofollow">Python list</a>.</p>
<h2>Way 2</h2>
<p>Or as an alternative, which I personally prefer to importing the main module (and found <a href="http://stackoverflow.com/a/10684099/1039947">here</a>), you can do this to populate the new dictionary you created with the built-in stuff which includes <code>__build_class__</code>:</p>
<pre><code>pGlobal = PyDict_New();
PyDict_SetItemString(pGlobal, "__builtins__", PyEval_GetBuiltins());
</code></pre>
|
Nested for loop in unix shell scripting <p>I have two variables named A and B for files subject and Scores like below </p>
<pre><code>A=contents of file 'subject' which contains "English Hindi Telugu"
B=contents of file 'Scores' which contains "60 60 10"
</code></pre>
<p>i want to tag the subject with marks in respective way i.e</p>
<pre><code>english ==> 60 hindi ==> 60 telugu ===>10
</code></pre>
<p>i implemented as below but its showing weird results:</p>
<pre><code>English ==> 60 English ==> 60 English ==> 10 Hindi ==> 60
Hindi ==> 60 Hindi ==> 10 Telugu ==> 60 Telugu ==> 60 Telugu ==> 10
</code></pre>
<p>I want the results to be like below English ==> 60 Hindi ==> 60 Telugu ==> 10</p>
<pre><code>#!/bin/ksh
A=`cat subject`
B=`cat Scores`
for sub in $A
do
for score in $B
do
echo " $sub ==> $score "
done
done
</code></pre>
| <p>This would be somewhat easier if the words in the files appeared on separate lines, such as</p>
<pre><code>$ cat subject
English
Hindi
Telugu
$ cat Scores
60
60
10
</code></pre>
<p>Then use some nifty Unix philosophy:</p>
<pre><code>$ paste subject Scores | sed 's/\t/ ==> /'
English ==> 60
Hindi ==> 60
Telugu ==> 10
</code></pre>
<p>The <code>paste</code> utility takes care of opening multiple files and reading them line by line, in sync.</p>
<p>To convert your original files, use something like this:</p>
<pre><code>$ printf '%s\n' $(cat subject)
English
Hindi
Telugu
</code></pre>
|
Pandas: using groupby if values in columns are dictionaries <p>I have dataframe</p>
<pre><code>category dictionary
moto {'motocycle':10, 'buy":8, 'motocompetition':7}
shopping {'buy':200, 'order':20, 'sale':30}
IT {'iphone':214, 'phone':1053, 'computer':809}
shopping {'zara':23, 'sale':18, 'sell':20}
IT {'lenovo':200, 'iphone':300, 'mac':200}
</code></pre>
<p>I need groupby category and as result concatenate dictionaries and choose 3 keys with the biggest values. And next get dataframe, where at the column <code>category</code> I have unique category, and in the column <code>data</code> I have list with keys.</p>
<p>I know, that I can use <code>Counter</code> to concatenate dicts, but I don't know, how do that to categories.
Desire output</p>
<pre><code>category data
moto ['motocycle', 'buy', 'motocompetition']
shopping ['buy', 'sale', 'zara']
IT ['phone', 'computer', 'iphone']
</code></pre>
| <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>nlargest</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.tolist.html" rel="nofollow"><code>Index.tolist</code></a>:</p>
<pre><code>df = pd.DataFrame({
'category':['moto','shopping','IT','shopping','IT'],
'dictionary':
[{'motocycle':10, 'buy':8, 'motocompetition':7},
{'buy':200, 'order':20, 'sale':30},
{'iphone':214, 'phone':1053, 'computer':809},
{'zara':23, 'sale':18, 'sell':20},
{'lenovo':200, 'iphone':300, 'mac':200}]})
print (df)
category dictionary
0 moto {'motocycle': 10, 'buy': 8, 'motocompetition': 7}
1 shopping {'sale': 30, 'buy': 200, 'order': 20}
2 IT {'phone': 1053, 'computer': 809, 'iphone': 214}
3 shopping {'sell': 20, 'zara': 23, 'sale': 18}
4 IT {'lenovo': 200, 'mac': 200, 'iphone': 300}
import collections
import functools
import operator
def f(x):
#some possible solution for sum values of dict
#http://stackoverflow.com/a/3491086/2901002
return pd.Series(functools.reduce(operator.add, map(collections.Counter, x)))
.nlargest(3).index.tolist()
print (df.groupby('category')['dictionary'].apply(f).reset_index())
category dictionary
0 IT [phone, computer, iphone]
1 moto [motocycle, buy, motocompetition]
2 shopping [buy, sale, zara]
</code></pre>
|
Joda Time: Invalid format. Data is malformed <p>Trying to process this string with date and time:</p>
<pre><code>2015-10-23T00:00:00+03:00
</code></pre>
<p>By using this code: </p>
<pre><code>String transactionDateValue = getNodeValue(nodeList, i, "transactionDate");
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss ZZZ");
DateTime jodaTime = dateTimeFormatter.parseDateTime(transactionDateValue);
DateTimeFormatter resultFormat = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
</code></pre>
<p>This is the error:</p>
<pre><code>java.lang.IllegalArgumentException: Invalid format: "2015-10-23T00:00:00+03:00" is malformed at "T00:00:00+03:00"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
at repgen.service.PrepareExcelService.fillContent(PrepareExcelService.java:169)
at repgen.service.PrepareExcelService.prepareDocument(PrepareExcelService.java:44)
at repgen.service.PrepareExcelServiceTest.testPrepareExcelService(PrepareExcelServiceTest.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code></pre>
<p>I suspect my error is near the ZZZ parameter, but cannot solve it. I also tried the parameters ZZZZ, ZZ, but that didn't fix it. </p>
| <p>Your Format must be:</p>
<pre><code>DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
</code></pre>
<p>It must be exactly like the date string, with the fixed values escaped by single quotes and without additional blanks.
Also you have to use <code>HH</code>for 24 hours Format. hh is 12 hours Format and it starts at 1 and Ends on 12</p>
|
Dynamically loading stickers for iMessage <p>As we can create simple iMessage stickers by just dragging images in the new template(Sticker Pack Application) provided by XCode. Is there a way that rather than having images in XCode, we can have images on a server and the pack gets whatever is there on the server as users open the sticker pack on the devices. </p>
| <p>To do so, you will need a proper iMessage extension, not a simple sticker pack. This way you'll be able to handle all the logic to load the collection of stickers. But it's completely possible, just a bit more complicated as Apple don't handle that part.
You could also put your stickers into an in-app purchase and keep data on apple server, but you'll still need to handle the logic to show stickers. Also, by doing that way, it will be more tricky to show preview of stickers ;)</p>
|
Rails 4 Heroku Multi-tenancy app redirecting to heroku homepage <p>Ok so im really lost and not even too sure what to post here for information. </p>
<p>I am Brand new to multi tenancy, i have followed a tutorial on using the apartment gem. Everything is working perfectly on lvh.me:3000, however when I push the app to Heroku, it pushes up fine no errors, but when i attrmpt to go to my domain pv-development@herokuapp.com it redirects me to the heroku home page??? </p>
<p>Please help here.. Let me know what i need to post here for a possible solution.. I dont even know where this could be stemming from!</p>
<p>Thanks in advance for you patients!</p>
<p>EDIT #1 </p>
<p>This is what my log just gave me from heroku:</p>
<pre><code>Apartment::Tenant Not Found (One of the following schema(s) is invalid:
</code></pre>
| <p>This error might occur when you don't have the tenant in your database. Try after creating it.</p>
<p>Similar <a href="https://github.com/influitive/apartment/issues/196" rel="nofollow">issue</a> in Github</p>
|
Overwrite width only in CSS with an {if} rule <p>I'm working on adjusting a slider right now, when going from 2-3 images it changes class. Now i want 4 images, and it works alright, however the slider bullets (that changes between the slider images) isn't in center of the page anymore, it's aligned slightly right.</p>
<p>Here's the script i use in HTML for changing from 2-3 images.</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> <{if $category->getMetaValue('slider_link_two') || $category->getMetaValue('slider_link_three')}>
<ul class="glide__bullets">
</ul>
<{/if}></code></pre>
</div>
</div>
</p>
<p>Here's the CSS, i apologize for layout, only have the minified css.</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-css lang-css prettyprint-override"><code>.glide__bullets {
position: absolute;
bottom: 18px;
width: 97%;
text-align: center;
list-style: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none
}
.glide__bullets li {
display: inline-block;
background-color: gray;
width: 10px;
height: 10px;
margin: 0 5px;
cursor: pointer
}
.glide__bullets li.active {
background-color: white
}</code></pre>
</div>
</div>
</p>
<p>As you can see I made a temporary solution of changing the width to 97%, but once you switch back to 3 images it will look stupid. I tried making a class to overwrite the width to 97% when there's 4 categories, but it completely ruins the bullets, but maybe it's just because i suck at coding.</p>
<p>So how can i change the width to 97% only when there's 4 images, or even better - keep it aligned center once there's 4 images. I tried running another rule with three and four, but as mentioned above it seemed to completely ruin the layout.</p>
<p>If you need anymore let me know, thanks in advance!</p>
| <p>I tested your code and to me it seems fine unless i am not understanding what you are trying to achieve these are the results i got <a href="https://i.stack.imgur.com/qxQ7G.png" rel="nofollow">3 bullets</a> and <a href="https://i.stack.imgur.com/u6GW5.png" rel="nofollow">4 bullets</a> could you please explain better what it is you are trying to achieve. Thanks :)</p>
|
Combinations of array values using google appscript <p>Here is my JS 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 allArrays = new Array(['a', 'b'], ['c', 'z'], ['d', 'e', 'f']);
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function (result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
console.log(getPermutation(allArrays));</code></pre>
</div>
</div>
</p>
<p>Now when I convert the same to Google Appscript it doesnt seem to work at all. What am i missing?</p>
| <p>For a start console.log() doesn't work in GScript, replace it with Logger.log(). </p>
<p>Putting it into a GScript it seems to work fine:</p>
<pre><code>function test_getPermutation() {
var allArrays = new Array(['a', 'b'], ['c', 'z'], ['d', 'e', 'f']);
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function (result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
Logger.log(getPermutation(allArrays)); // [16-10-12 10:27:36:400 BST] [acd, ace, acf, azd, aze, azf, bcd, bce, bcf, bzd, bze, bzf]
}
</code></pre>
|
Html templates loaded asynch (JQuery/JavaScript asynch) <p>So I'm making a webpage with some code snippets loaded in from txt files. The information to paths and locations of the txt files are stored in a json file. First I'm loaing the json file looking like this </p>
<pre><code>[
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"},
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"}
]
</code></pre>
<p>After loaded I'm using templates from my index.html file and then inserting the templates. My problem is that its happening asynch so that the page never looks the same because of the asynch nature of js.
Here is what my jquery code for loading and inserting looks like:</p>
<pre><code>$(document).ready(function () {
var fullJson;
$.when(
$.get('/data/testHtml/data.json', function (json) {
fullJson=json;
})
).then(function(){
for(var i=0; i<fullJson.length; i++){
templefy(fullJson[i],i);
}
})
var templefy = function (data, number) {
//Fetches template from doc.
var tmpl = document.getElementById('schemeTemplate').content.cloneNode(true);
//Destination for template inserts
var place = document.getElementsByName('examples');
//Set name
tmpl.querySelector('.name').innerText = data.root;
//Next section makes sure that each tap pane has a unique name so that the system does not override eventlisteners
var htmlNav = tmpl.getElementById("html");
htmlNav.id += number;
var htmlLink = tmpl.getElementById('htmlToggle');
htmlLink.href += number;
var cNav = tmpl.getElementById('c');
cNav.id += number;
var cLink = tmpl.getElementById('cToggle');
cLink.href += number;
var bridgeNav = tmpl.getElementById('bridge');
bridgeNav.id += number;
var bridgeLink = tmpl.getElementById('bridgeToggle');
bridgeLink.href += number;
//Auto creates the sidebar with links using a link template from doc.
var elementLink = tmpl.getElementById('elementLink');
elementLink.name +=data.root;
var linkTemplate = document.getElementById('linkTemplate').content.cloneNode(true);
var linkPlacement = document.getElementById('linkListWVisuals');
var link = linkTemplate.getElementById('link');
link.href = "#"+data.root;
link.innerText = data.root;
linkPlacement.appendChild(linkTemplate);
//Fetches html, c# and bridge code. Then inserts it into template and finally inserts it to doc
$.get("/data/" + data.root + '/' + data.html, function (html) {
tmpl.querySelector('.preview').innerHTML = html;
tmpl.querySelector('.html-prev').innerHTML = html;
$.get('/data/' + data.root + '/' + data.c, function (c) {
tmpl.querySelector('.c-prev').innerHTML = c;
$.get('/data/' + data.root + '/' + data.bridge, function (bridge) {
console.log(bridge);
tmpl.querySelector('.bridge-prev').innerHTML = bridge;
place[0].appendChild(tmpl);
})
})
})
}
});
</code></pre>
<p>So yeah my problem is that it just fires in templates whenever they are ready and not in the order written in the json file.</p>
<p>I'll take whatever help I can get..Thank you :)</p>
| <p>To my knowledge, there is no golden method and i usually apply one of the following options:</p>
<p>1) Preload the files separately e.g. create key "body" for each entry in your json and then set the value of it to the contents of the file.</p>
<p>2) Do not display items until they are not fully loaded in the DOM and before you show them, sort them in the DOM by e.g. their position in the json array.</p>
<p>Hope it helps.</p>
|
Ghostscript won't convert PDF to PDF/A. Annotation Issue <p>I'm trying to convert a PDF to PDF/A. At every pass I'm getting the error "<code>GPL Ghostscript 9.19: Annotation set to non-printing, not permitted in PDF/A, reverting to normal PDF output</code>". </p>
<p>The PDF has previously been generated from HTML by <code>wkhtmltopdf</code>. With the error being quite vague I've done some research around PDF annotations. I've confirmed the PDF has no annotations, flattening annotations (though there isn't one) hasn't worked, I tried the <code>-dShowAnnots=false</code> switch. All to no avail. I've also tried it with a variety of different PDFs and I'm getting the same error on them all. </p>
<p>The command I'm using to do the conversion is "<code>gs -dPDFA=2 -dNOOUTERSAVE -sProcessColorModel=DeviceRGB -sDEVICE=pdfwrite -o output.pdf /Users/work/Documents/Projects/pdf-generator-service-tests/PDFA_def.ps -dPDFACompatibilityPolicy=1 input.pdf</code>"</p>
<p>I tried creating a basic PDF page from Google's homepage using <code>wkhtmltopdf https://google.com putput.pdf</code> and again, no joy (this is an example of the PDFs I've tried to convert, for people who may want to try and replicate the issue). </p>
| <p>I thought the error was quite specific; PDF/A does not permit annotations to be set to non-printing. You haven't included an actual example of the kind of file causing you a problem, so I can't possibly comment on the presence of any annotations, but I assure you that its not possible to get this message without having annotations.</p>
<p>Since you've already set PDFACompatibility to 1 there's not much else I can say. You could open a bug report and attach the file there, or post a link to one here. Without that I can't say much.</p>
<p>Oh and you don't say which version of Ghostscript you are using, or where you sourced it from. Occasionally packagers break things so it <strong>might</strong> be worth trying to build from source.</p>
<p>One point; You execute the PDFA_def.ps file before setting PDFACompatibility=1, that's probably not going to work, you'll want to switch those two around. You should set the controls before you do any input or stuff might go awry, trying to change midstream isn't really a good idea.</p>
|
How to test a java sql query that checks a values uniqueness <p>I have a number of Java methods that check for a values uniqueness against similar values in a database. Heres an example:</p>
<pre><code>public static boolean isNameUnique(String name){
Statement stmt;
try {
stmt = dbConnection.createStatement();
String sql = "SELECT name FROM model";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
String nameDatabase = rs.getString("name");
if(name.trim().equals(nameDatabase.trim())){
return false;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
</code></pre>
<p>However I am not sure how to test this, the project is a WAR File running on Tomcat 7. I've looked up about JUnit testing, Mockito and Arquillian but can't get a clear answer on which I should be using.</p>
<p>An example of a test I'd like to do is to insert a name value into the database then check the same name value to ensure false is returned for isNameUnique.</p>
<p>I have a number of methods similar to the one above where I require checking a value in a database against one passed in through the method.</p>
<p>So basically I'm looking for the most ideal way to test methods similar to this.</p>
<p><strong>EDIT: Could someone explain how my question is a duplicate of the one mentioned? I don't see any similarities.</strong></p>
<p><strong>EDIT2: Sorry if its not clear, I am looking for the best way to perform a test where I insert a name value into a database and then run a method to check another name value is unique or not. Do I need a test database? Do I need to mock objects or use something like arquillian to test name uniqueness or not?</strong></p>
| <p>Use the below query</p>
<p>String sql = "SELECT name FROM model where name != ?";</p>
<p>In Question mark, pass the value that you are getting by trimming that value.</p>
|
jQuery._data event handlers <p>I am trying to determine whether Twitter Bootstrap "tab.js" has been loaded. One way is to look at the events that it hooks.</p>
<p>If I dump the event handlers to the console:</p>
<pre><code>var ii;
var docEvents = jQuery._data(document, "events");
var docClickEvents = docEvents.click;
console.log("docEvents: %O", docEvents);
console.log("docClickEvents: %O", docClickEvents);
console.log("docClickEvents.length: %O", docClickEvents.length);
for (ii = 0; ii < 7; ii += 1) {
console.log("docClickEvents[%d].namespace=%O", ii, docClickEvents[ii].namespace);
}
</code></pre>
<p>Chrome's console shows:</p>
<p><a href="https://i.stack.imgur.com/Uc5fj.png" rel="nofollow">Chrome console output</a></p>
<p>As you can see the click Array[7] becomes an Array[5] but 7 objects are displayed, and then when I try to display the namespace of element [5], elements [5] and [6] have disappeared!</p>
<p>Anyone know what's happening here, and how to read the value of element [5], being </p>
<pre><code>namespace:"bs.data-api.tab"
</code></pre>
<p>Thanks
JC</p>
| <p>It was a timing problem. I was loading 'tab.js', appending it to the body, and assuming this process would complete immediately:</p>
<pre><code>ourScript = document.createElement("script");
ourScript.type = "text/javascript";
ourScript.src = sourceDir + "tab.js";
document.body.appendChild(ourScript);
</code></pre>
<p>There appears to be no callback from jquery appends, so I added a one second time delay before checking for 'tab.js' and all seems OK. I expect the Chrome console gets confused and shows strange effects.</p>
<p>Final code:</p>
<pre><code>// ---------------------------------
var eventNameSpaceLoaded = function (thisNamespace) {
var isLoaded = false;
var theseClickEvents = jQuery._data(document, "events").click;
Object.keys(theseClickEvents).forEach(function (key) {
if (theseClickEvents[key].namespace && (theseClickEvents[key].namespace === thisNamespace)) {
isLoaded = true;
return false; // stop the each
}
});
return isLoaded;
};
// check bootstrap tab.js is loaded
var ourScript;
if( !eventNameSpaceLoaded("bs.data-api.tab")) {
ourScript = document.createElement("script");
ourScript.type = "text/javascript";
ourScript.src = sourceDir + "tab.js";
document.body.appendChild(ourScript);
}
// has tab.js been loaded - try checking for 10 seconds
(function checkTabLoad( counter) {
if( !eventNameSpaceLoaded("bs.data-api.tab")) {
counter -= 1;
if(counter > 0){
setTimeout(function(){
checkTabLoad( counter);
}, 100);
}
} else {
// get tabs working
$('#SOME_ SELECTOR').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
console.log("tabs fired up");
}
}( 100));
</code></pre>
|
Using ion-list to display the sub-items of the selected item <p>I'm creating an app where there is a list of items displayed. when an item is selected it will be re-directed to another page where another set of items are listed with check box, so that the items can be check-boxed for further process. Im able to select the item from the list of first page but the problem is in the next page it doesn't display items related to the selected item and it remain blank.Please help me to resolve it.</p>
<p>html page1:</p>
<pre><code><ion-list>
<ion-item ng-model="carBrand" ng-repeat="name in carSelect" ng-click="selectItem(carBrand)">
<!--ion-item ng-click="selectItem(value)" ng-repeat="value in carSelect" ng-model="value.selected"-->
{{name.name}}
</ion-item>
</ion-list>
</code></pre>
<p>html page2:</p>
<pre><code><ion-checkbox ng-repeat="brandType in newCarList">
<div align="center"><span>{{brandType.types}}</span></div>
</ion-checkbox><br><br>
</code></pre>
<p>controller:</p>
<pre><code>carService.factory('carRepository',function(){
var brandList={};
brandList.data= [
{'name':'Benz', 'types':['Truck', 'Regular']},
{'name':'BMW', 'types':['Oversize', 'Motorcycle']},
{'name':'Bently','types':['Regular']},
{'name':'Honda','types':['SUV','Truck']},
{'name':'Lexus','types':['Oversize','Motorcycle','Truck']},
{'name':'Toyota','types':['SUV']}
];
{
return brandList;
}
});
carService.controller('carBrand',['$scope','carRepository','$rootScope','$state',function($scope,carRepository,$rootScope,$state){
$rootScope.carSelect= carRepository.data;
$scope.newCarList=[];
$scope.selectedItem = 'select';
$scope.selectItem = function (key) {
$scope.newCarList.push(key);
$state.go('app.CarDetails');
}
$scope.addEntry = function () {
$state.go('app.carEdit');
};
}])
</code></pre>
| <p>This would correctly:</p>
<p>Within your config of your application, should I set the state that v to receive the parameter as follows:</p>
<pre><code>carService.config(function($stateProvider, $urlRouterProvider) {
.state('html2', {
templateUrl: 'overview',
params: ['value'],
controller: 'HtmlCtrl2'
})
......
})
</code></pre>
<p>Here you say that you will receive a parameter called value.</p>
<p>From Html1Ctrl
In the first controller, that is, in html 1 according to your example, you define this:</p>
<pre><code>.controller('HomeCtrl1', function($state){
$scope.redirect = function(){
params = { 'value': 1 };
$state.go('view', params);
}
})
</code></pre>
<p>Here you say that when that function is called "redirect" arme value and send as parameter to reroute</p>
<p>In HtmlCtrl2 And in the controller 2 you get ...</p>
<pre><code>.controller('HtmlCtrl2', function($scope, $stateParams) {
var value= $stateParams[0];
});
</code></pre>
|
iOs Safari and Google Chrome SVG animation doesn't show up <p>I have been struggling with this for quite a bit now.</p>
<pre><code>.intro #intro-n,
.intro #intro-o,
.intro #intro-a2 {
stroke-dasharray: 400;
stroke-dashoffset: 400; }
.intro #intro-n {
/*-webkit-animation: intro-letters 0.9s linear;*/
-webkit-animation-name: intro-letters;
-webkit-animation-duration: 0.9s;
-webkit-animation-timing-function: linear;
-moz-animation: intro-letters 0.9s linear;
animation: intro-letters 0.9s linear;
animation-name: intro-letters;
animation-duration: 0.9s;
animation-timing-function: linear;
-webkit-animation-fill-mode: both;
-moz-animation-fill-mode: both;
animation-fill-mode: both;
-webkit-animation-delay: 0s;
-moz-animation-delay: 0s;
animation-delay: 0s; }
@-webkit-keyframes intro-letters {
0% {
}
100% {
stroke-dashoffset: 0; } }
@-moz-keyframes intro-letters {
0% {
}
100% {
stroke-dashoffset: 0; } }
@keyframes intro-letters {
0% {
}
100% {
stroke-dashoffset: 0; } }
</code></pre>
<p><a href="http://codepen.io/anon/pen/ORkZwG" rel="nofollow">http://codepen.io/anon/pen/ORkZwG</a></p>
<p>This code perfectly works on Windows(except IE) and Android devices, but when i try to launch it in iOS safari or even chrome SVG animations are blank.</p>
<p>Edit:
Yes, it works in iOS desktop Google Chrome version, but it doesn't work on iOS Tablet Chrome nor Safari</p>
| <p>After spending a fair amount of time on this issue, I finally cracked it down, it seems that the issue was in this bit of code:</p>
<pre><code>.intro svg {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%);
-webkit-transform: translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
width: 100%;
max-width: 250px;
/*-webkit-animation: intro-hide-element 0s linear;*/
-webkit-animation-name: intro-hide-element;
-webkit-animation-duration: 0s;
-webkit-animation-timing-function: linear;
-moz-animation: intro-hide-element 0s linear;
animation: intro-hide-element 0s linear;
-webkit-animation-fill-mode: both;
-moz-animation-fill-mode: both;
animation-fill-mode: both;
-webkit-animation-delay: 5.1s;
-moz-animation-delay: 5.1s;
animation-delay: 5.1s; }
</code></pre>
<p>Particularly here:</p>
<pre><code>-webkit-animation-duration: 0s;
-moz-animation: intro-hide-element 0s linear;
animation: intro-hide-element 0s linear;
</code></pre>
<p>Where after changing it to:</p>
<pre><code>-webkit-animation-duration: 0.001s;
-moz-animation: intro-hide-element 0.001s linear;
animation: intro-hide-element 0.001s linear;
</code></pre>
<p>The animations in safari tablet browser appeared, I'm not entirely sure why it works in chrome and not safari, but that was what did the trick for me, hopefully someone can explain a bit more in detail why this is happening but in the mean time hope it helps someone.</p>
|
Matrix Form Representation of Results <p>I have 7 csv files which has list of words. I have taken all the words from 7 csv and put in a new file called Total_Words_list. </p>
<p>The issue is that I need an output in the following matrix:</p>
<pre><code> APPLE BALL CAT DOG....
A 0 1 1 0
B 1 1 0 1
C 1 1 1 0
</code></pre>
<p>Here the words from the main list forms the rows and the 7 file names form the column. If a word is present in file A it turns 1 else 0, and so on. This goes on for all 7 csv files in a single run and i get the above result.</p>
<p>I am not sure how to approach the issue.</p>
| <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> for concating all <code>DataFrames</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow"><code>str.get_dummies</code></a>. Last need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by index (<code>level=0</code>) with aggregating <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>import pandas as pd
import numpy as np
import io
temp=u"""CAT;BALL
"""
#after testing replace io.StringIO(temp) to filename
df1 = pd.read_csv(io.StringIO(temp), sep=";", index_col=None, header=None)
print (df1)
temp=u"""DOG;BALL;APPLE
"""
#after testing replace io.StringIO(temp) to filename
df2 = pd.read_csv(io.StringIO(temp), sep=";", index_col=None, header=None)
print (df2)
temp=u"""DOG;BALL;APPLE;CAT
"""
#after testing replace io.StringIO(temp) to filename
df3 = pd.read_csv(io.StringIO(temp), sep=";", index_col=None, header=None)
print (df3)
df = pd.concat([df1,df2,df3], keys=['A','B','C'])
df.reset_index(1, drop=True, inplace=True)
print (df)
0 1 2 3
A CAT BALL NaN NaN
B DOG BALL APPLE NaN
C DOG BALL APPLE CAT
</code></pre>
<pre><code>print (df.stack().reset_index(1, drop=True).str.get_dummies())
APPLE BALL CAT DOG
A 0 0 1 0
A 0 1 0 0
B 0 0 0 1
B 0 1 0 0
B 1 0 0 0
C 0 0 0 1
C 0 1 0 0
C 1 0 0 0
C 0 0 1 0
print (df.stack().reset_index(1, drop=True).str.get_dummies().groupby(level=0).sum())
APPLE BALL CAT DOG
A 0 1 1 0
B 1 1 0 1
C 1 1 1 1
</code></pre>
<hr>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pandas.get_dummies</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by columns (<code>level=0</code>, axis=1) with aggregating <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>print (pd.get_dummies(df, dummy_na=False, prefix='', prefix_sep='')
.groupby(level=0, axis=1).sum())
APPLE BALL CAT DOG
A 0 1 1 0
B 1 1 0 1
C 1 1 1 1
</code></pre>
<p>EDIT by comment:</p>
<p>Another approach is get <code>dummies</code> from each dataframe separately and then <code>concat</code> output:</p>
<pre><code>df11 = pd.get_dummies(df1, dummy_na=False, prefix='', prefix_sep='')
.groupby(level=0, axis=1).sum()
#print (df11)
df21 = pd.get_dummies(df2, dummy_na=False, prefix='', prefix_sep='')
.groupby(level=0, axis=1).sum()
#print (df21)
df31 = pd.get_dummies(df3, dummy_na=False, prefix='', prefix_sep='')
.groupby(level=0, axis=1).sum()
#print (df31)
df = pd.concat([df11,df21,df31], keys=['A','B','C']).fillna(0).astype(int)
df.reset_index(1, drop=True, inplace=True)
print (df)
APPLE BALL CAT DOG
A 0 1 1 0
B 1 1 0 1
C 1 1 1 1
</code></pre>
|
how to change all elements id in div child <p>How I can change and add something to all ids in div child elements that have something like <code>bi_</code> in his first. like this example:</p>
<pre><code><script>
var opts = '1';
$('.mm > #bi_name').attr('id', 'bi_name_'+opts);
$('.mm > #bi_email').attr('id', 'bi_email_'+opts);
$('.mm > #bi_expire').attr('id', 'bi_expire_'+opts);
$('.ss > #bi_ohhh').attr('id', 'bi_ohhh_'+opts);
$('.ss > #bi_bala').attr('id', 'bi_bala_'+opts);
$('.ss > #bi_ola').attr('id', 'bi_ola_'+opts);
.....
</script>
<div id="lol" class="mm">
<!-----I want to change all id below----->
<div id="profile">
<div class="about text-center">
<h1 id="bi_name">Banned player name</h1> //change and this id="bi_name" to id="bi_name_1"
</div>
<ul class="personal-info">
<li><label><i class="fa fa-envelope fa-fw fa-lg"></i> Email</label><span id="bi_email">EMAIL</span></li> //change and this id="bi_email" to id="bi_email_1"
<li><label><i class="fa fa-calendar fa-fw fa-lg"></i> Expire Time</label>
<span>
<a href="" id="bi_expire" data-original-title="Select Date of ban expire">EXPIRE TIME</a> //change and this id="bi_expire" to id="bi_expire_1"
</span>
</li>
</ul>
</div>
<div id="content" class="ss">
.....
</div>
<div id="gallery" class="gg">
....
</div>
<!-----I want to change all id above----->
</div>
</code></pre>
| <p>You can use target all the elements using <a href="https://api.jquery.com/attribute-starts-with-selector/" rel="nofollow">Attribute Starts With Selector [name^=âvalueâ]</a> then use <a href="http://api.jquery.com/attr/#attr2" rel="nofollow"><code>.attr(attributeName, fn)</code></a> to set the <code>id</code></p>
<pre><code>var opts = '1';
$('.mm [id^=bi_]').attr('id', function(_, val){
return val + '_' + opts;
});
</code></pre>
|
Find similar items in mysql table when values are just a bit random <p>I have database of laboratory analysis results. Due to the nature of analysis, the results a just a bit random- it is normal in real world. All result are stored in database in integers (we keep results in ppm - part per million).
The problem is, that I want to find similar (maybe same) material analysed several times.
Database looks like this:</p>
<pre><code>id |v1 |v2 |v3 |v4 |... |vn
----|----|----|----|----|----|----
1 |4560|5600|3333| 56| |0
2 |4575|5583|3354| 67| |0
3 |4565|4333|3332| 60| |0
4 | 0|5583|3333| 60| |0
</code></pre>
<p>Material with id 1 and 2 is same, material 3 and 4 are unique.</p>
<p>I want to give tolerance +-30 or something to eliminate result randomines and find same material. It could be nice, that tolerance value could be individual for each column.</p>
<p>To simplify. How to ask mysql to return similar integers with value +- some error value?</p>
| <p>You really don't want to do this using SQL.</p>
<p>Essentially what you're doing is calculating the <a href="https://en.wikipedia.org/wiki/Connected_component_(graph_theory)" rel="nofollow">connected components</a> of the graph defined by your database, where two rows have an edge connecting them if they are within the tolerance you've defined.</p>
<p>Assuming that your dataset is small enough to fit in memory, which is likely if it's results of sample tests conducted in your laboratory, then your best bet is to read it all in and then use a suitable library to calculate the connected components. For instance, in Java, you could use <a href="http://jgrapht.org/" rel="nofollow">JGraphT</a>; if you need to do it in PHP then I'm sure there will be graph libraries available for that too.</p>
<p>At the high end, with massive datasets, there are libraries to do it on a Spark cluster...</p>
|
Devise skip reconfirmation <p>I need to skip, not the confirmation email, but REconfirmation emails.</p>
<p>Suppose I have a user with a confirmed email. I want to manually change its email for testing/support purposes</p>
<pre><code>u.email # => email1@example.com
u.email = 'email2@example.com'
u.save
u.email # => email1@example.com
u.unconfirmed_email # 'email2@example.com'
</code></pre>
<p>I tried <code>u.skip_confirmation!</code> before and after saving but it doesn't seem to help for reconfirmation emails... the unconfirmed email is not transferred to the email field</p>
<p>Is there any way to force the new unconfirmed email to switch to the normal email ?</p>
| <p>That method only skips sending of mail, that does not confirm the new mail which is stored in <code>unconfirmed_mail</code>. maybe you could just confirm the user manually like <code>u.confirm</code>.
<code>confirm</code> method works only after object is saved.</p>
<p>To skip reconfirmation email notification use : <code>skip_confirmation_notification!</code></p>
<p>Here is the <a href="https://github.com/plataformatec/devise/blob/88724e10adaf9ffd1d8dbfbaadda2b9d40de756a/lib/devise/models/confirmable.rb#L157" rel="nofollow">Code reference</a>.</p>
<p>Or try <code>skip_reconfirmation!</code> this may confirm new email and avoid sending email notification. I have not used it but I understand so from the comment in code reference above(next method of <code>skip_confirmation_notification!</code> defination). so try it and let me know.</p>
|
Show first 4 items inside div with class active rest without <p>I got some projects that use a template layout/slider. The slider works by wrapping the first 4 projects in a div with class <code>active</code> and the rest inside divs without <code>active</code> but still grouped per 4.</p>
<p>I tried the following:</p>
<pre><code>$tel = 1;
foreach($projectcr1 as $projects1) {
$projectimages = $projects1['images']; // Get image parameters of the article
$projectimgs = json_decode($projectimages); // Split the parameters apart
if($projectimgs->image_intro != ''){
$img = 'cms/'.$projectimgs->image_intro;
}else{
$img = 'cms/images/placeholder/placeholder.jpg';
}
if (strlen($projects1['introtext']) > 40){
$shortstrproj = substr($projects1['introtext'], 0, 40) . '...';
}else{
$shortstrproj = $projects1['introtext'];
}
if($projects1['id'] != ''){
if($tel == 1){
$projecten1 .= '<div class="carousel-item active">
<div class="row">';
}
//Here I need the first 4 projects ($projecten1 below is one project being looped)
$projecten1 .= '
<div class="col-xs-12 col-sm-6 col-lg-3 js-wpg-item" data-categories="'.$projects1['categorie_alias'].'">
<a class="card portfolio-grid__card js-wpg-card" href="project/'.$projects1['content_alias'].'.html">
<div class="imgwrapport">
<img width="360" height="180" src="'.$img.'" class="card-img-top portfolio-grid__card-img" alt="photo1" srcset="'.$img.' 360w, '.$img.' 300w, '.$img.' 768w, '.$img.' 540w, '.$img.' 830w"
sizes="(max-width: 360px) 100vw, 360px">
</div>
<div class="card-block portfolio-grid__card-block">
<h5 class="card-title ortfolio-grid__card-title">'.$projects1['title'].'</h5>
<p class="portfolio-grid__card-price">'.strip_tags($shortstrproj).'</p>
<div class="portfolio-grid__card-items">
<p class="portfolio-grid__card-item">
Bekijk project
</p>
</div>
</div>
</a>
</div>';
if(($tel % 4) == 0){
$projecten1 .= '</div></div><div class="carousel-item">
<div class="row">';
// Here I need the rest of the projects
$projecten1 .= '</div></div>';
}
$tel++;
}
}
echo $projecten1;
?>
</code></pre>
<p>If <code>$tel</code> = 1 wrap the div with active around the items. Then when <code>$tel</code> % 4 leaves 0 (4 divided by 4 leaves 0), close the divs and start new ones but this time without the active class.</p>
<p>This works fine, my only issue is how to seperate the data. How can I show the first 4 projects inside the first div, and the rest in the following divs without active class?</p>
<p>Example how I want the code in the end:</p>
<pre><code><div class="carousel-item active">
<div class="row">
project1
project2
project3
project4
</div>
</div>
<div class="carousel-item">
<div class="row">
project5
project6
project7
project8
</div>
</div>
<div class="carousel-item">
<div class="row">
project9
project10
project11
project12
</div>
</div>
</code></pre>
| <p>try this Code . if u have questions about the code just post under it.</p>
<pre><code><?php
$tel = 1;
$next_div = true;
$foreach_ended = 0;
// 2 New vars they are needed for the right output down
foreach($projectcr1 as $projects1) {
$projectimages = $projects1['images']; // Get image parameters of the article
$projectimgs = json_decode($projectimages); // Split the parameters apart
if($projectimgs->image_intro != ''){
$img = 'cms/'.$projectimgs->image_intro;
}else{
$img = 'cms/images/placeholder/placeholder.jpg';
}
if (strlen($projects1['introtext']) > 40){
$shortstrproj = substr($projects1['introtext'], 0, 40) . '...';
}else{
$shortstrproj = $projects1['introtext'];
}
if($projects1['id'] != '')
{
$foreach_ended=0;
// set to 0 when a DIV is Open.
if($tel == 1&&$next_div==true){ /* set the first ACTIVE div with $next_div */
$projecten1 .= '<div class="carousel-item active"><div class="row">';
$next_div=false; /* set it to false so every new 4xDIV is not Active */
}
elseif($tel == 1&&$next_div!=true)
{
$projecten1 .= '<div class="carousel-item"><div class="row">';
}else{}
$projecten1 .= '
<div class="col-xs-12 col-sm-6 col-lg-3 js-wpg-item" data-categories="'.$projects1['categorie_alias'].'">
<a class="card portfolio-grid__card js-wpg-card" href="project/'.$projects1['content_alias'].'.html">
<div class="imgwrapport">
<img width="360" height="180" src="'.$img.'" class="card-img-top portfolio-grid__card-img" alt="photo1" srcset="'.$img.' 360w, '.$img.' 300w, '.$img.' 768w, '.$img.' 540w, '.$img.' 830w"
sizes="(max-width: 360px) 100vw, 360px">
</div>
<div class="card-block portfolio-grid__card-block">
<h5 class="card-title ortfolio-grid__card-title">'.$projects1['title'].'</h5>
<p class="portfolio-grid__card-price">'.strip_tags($shortstrproj).'</p>
<div class="portfolio-grid__card-items">
<p class="portfolio-grid__card-item">
Bekijk project
</p>
</div>
</div>
</a>
</div>';
if(($tel % 4) == 0){
$tel=1; /* reset Tel */
$projecten1 .= '</div></div>'; /* End DIV when 4x is reached */
$foreach_ended=1; /* set DIV to closed */
}
else
{
$tel++;
}
}
}
if($foreach_ended==0){$projecten1 .= '</div></div>';} /* when the Foreach enden and the LAST div had less then 4 items its not marked as CLOSED . so this IF closes the last open DIV */
echo $projecten1;
?>
</code></pre>
|
Adding full .NET to .NET Core library <p>I am writting a .NET Core library I intend to publish on NuGet, full .NET compatible.</p>
<p>To do so, I set the project.json as follow:</p>
<pre><code>"frameworks": {
"netstandard1.1": {
"imports": "dnxcore50"
}
}
</code></pre>
<p>I want that library to use a full .NET library (let's call it <code>OtherLib</code>). I thought it could be possible as long as the .NET version of OtherLib would be compatible with the netstandard version of my library.</p>
<p>But it appears not... Here is the error:</p>
<pre><code>Package OtherLib X.Y.Z is not compatible with netstandard1.1 (.NETStandard,Version=v1.1). Package OtherLib X.Y.Z supports:
- net40 (.NETFramework,Version=v4.0)
- net45 (.NETFramework,Version=v4.5)
</code></pre>
<p>Here is my full project.json:</p>
<pre><code>{
"version": "1.0.0-*",
"dependencies": {
"NETStandard.Library": "1.6.0",
"OtherLib": "X.Y.Z"
},
"frameworks": {
"netstandard1.1": {
"imports": "dnxcore50"
}
}
}
</code></pre>
<p>I suspect there is some tricky stuff to do in it, to get it working, or may be it is simply not possible?</p>
<p>Thanks in advance.
(Excuse me for my english, I am not a native speaker)</p>
| <p>Try to modify your project.json by changing "netstandard1.1" to "net45":</p>
<pre><code>{
"version": "1.0.0-*",
"dependencies": {
"NETStandard.Library": "1.6.0",
"OtherLib": "X.Y.Z"
},
"frameworks": {
"net45": {
"imports": "dnxcore50"
}
}
}
</code></pre>
|
SAPUi5 Usage Grid and GridData <p>I'm trying to hide some controls on different screen sizes using a Grid and GridData Layout.</p>
<p>I want to use the properties visibleM, visibleS, visibleXL described in the documentation <a href="https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.layout.GridData.html" rel="nofollow">https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.layout.GridData.html</a>, but they don't seem to work.</p>
<p>Here is the JSBin Sample code, trying to hide a Button Control with visibleM, visibleS properties.
<a href="http://jsbin.com/nugiri/edit?html,console,output" rel="nofollow">http://jsbin.com/nugiri/edit?html,console,output</a></p>
<p>Something must be wrong.</p>
| <p>In your JS Bin, please add quotes to false --> "false".</p>
<pre><code>layoutData: new sap.ui.layout.GridData({
visibleM : "false",
</code></pre>
|
Task scheduler PowerShell Start-Process is not running <p>I have this simple script on Windows 10, which works fine when just executing, but fails to start notepad when running from task scheduler. <strong>Stop-Process works perfectly, Start-Process does not run.</strong> When I run it on demand, it closes the notepad and then keeps running without opening notepad, the task does not close also.</p>
<pre><code>Stop-Process -processname notepad
Start-Process "C:\Windows\system32\notepad.exe"
</code></pre>
<p>This is how it is configured to run.
<a href="https://i.stack.imgur.com/I87uc.png" rel="nofollow"><img src="https://i.stack.imgur.com/I87uc.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/vYBrj.png" rel="nofollow"><img src="https://i.stack.imgur.com/vYBrj.png" alt="enter image description here"></a>
Things I have tried, but still does not work.</p>
<ol>
<li>First of all, I am running under administrator account.</li>
<li>In task schduler, run with highest privileges is checked.</li>
<li>I have tried <code>-ExecutionPolicy Bypass</code> and <code>-ExecutionPolicy RemoteSigned</code></li>
<li>Under security policy have given my user <code>Logon as batch</code> job permission</li>
<li>Turn UAC off</li>
</ol>
| <p>The application was ran in background. To make it run on foreground, had to check the box <strong>Run only when user is logged on</strong>.</p>
<p><a href="https://i.stack.imgur.com/ahW9u.png" rel="nofollow"><img src="https://i.stack.imgur.com/ahW9u.png" alt="enter image description here"></a></p>
|
Windows: How to control the adaptive brightness? <p>I want to control(On/Off) the <strong>adaptive brightness</strong> like the Power Options</p>
<p>Enable adaptive brightness:</p>
<p><img src="https://i.stack.imgur.com/PvxUx.png" alt="Enable adaptive brightness"></p>
<p>by API in Win 10. I guess the API is included in the Power Management Functions: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa373163(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/aa373163(v=vs.85).aspx</a></p>
<p>But I cannot find the function... May someone provide me some suggestions or directions. Thanks a lot!</p>
| <p>I found the solution by myself, and I share the way to everyone who needs!</p>
<pre><code>GUID *guidScheme;
bool bResult = false;
byte enableFunction= 0x1; //Set 0x0 to disable
bResult = PowerGetActiveScheme(NULL, &guidScheme);
if (bResult != ERROR_SUCCESS){
//error message
}
GUID guidSubVideo = { 0x7516b95f, 0xf776, 0x4464, 0x8c, 0x53, 0x06, 0x16, 0x7f, 0x40, 0xcc, 0x99 };
GUID guidAdaptBright = { 0xfbd9aa66, 0x9553, 0x4097, 0xba, 0x44, 0xed, 0x6e, 0x9d, 0x65, 0xea, 0xb8 };
bResult = PowerWriteDCValueIndex(NULL, guidScheme, &guidSubVideo, &guidAdaptBright, enableFunction);
if (bResult != ERROR_SUCCESS){
//error message
}
</code></pre>
|
How can I make a volatile struct behave exactly like a volatile int during assignment? <p>When one assigns to a <code>volatile int</code> from a non-volatile <code>int</code>, the compiler. When one assigns from a <code>volatile struct</code> from a non-volatile <code>struct</code> of the same type, the compiler appears to be extremely unhappy.</p>
<p>Consider the following simple program.</p>
<pre><code>struct Bar {
int a;
};
volatile int foo;
int foo2;
volatile Bar bar;
Bar bar2;
int main(){
foo = foo2;
bar = bar2;
}
</code></pre>
<p>When I try to compile this code, I get an error on the second line of main but not the first.</p>
<pre><code>g++ Main.cc -o Main
Main.cc: In function âint main()â:
Main.cc:13:9: error: passing âvolatile Barâ as âthisâ argument discards qualifiers [-fpermissive]
bar = bar2;
^
Main.cc:1:8: note: in call to âBar& Bar::operator=(const Bar&)â
struct Bar {
</code></pre>
<p>It seems that the problem occurs because a <code>volatile Bar</code> is being passed to the left side of the assignment operator, although I am not sure why this is not a problem for <code>int</code>. </p>
<p>I looked at <a href="http://stackoverflow.com/a/4644322/391161">this answer</a> which suggested the following fix.</p>
<pre><code>struct Bar {
int a;
volatile Bar& operator= (const Bar& other) volatile {
*this = other;
}
};
</code></pre>
<p>Unfortunately, this resulted in the following two warnings.</p>
<pre><code>g++ Main.cc -o Main
Main.cc: In member function âvolatile Bar& Bar::operator=(const Bar&) volatileâ:
Main.cc:4:21: warning: implicit dereference will not access object of type âvolatile Barâ in statement
*this = other;
^
Main.cc: In function âint main()â:
Main.cc:16:15: warning: implicit dereference will not access object of type âvolatile Barâ in statement
bar = bar2;
</code></pre>
<p>I then looked at <a href="http://stackoverflow.com/a/13869669/391161">this answer</a>, which mentions that I should <em>cast the reference to an rvalue</em>, but I am not sure which reference to cast, and which cast syntax to use in this case.</p>
<p><strong>What is the correct incantation to make the assignment on the line 2 of <code>main</code> behave exactly as line 1 of <code>main</code> does, without warnings or errors?</strong></p>
| <p>Your initial problem is because the implicit assignment operator has signature</p>
<pre><code>Bar& operator=(const Bar& rhs);
</code></pre>
<p>... and that isn't callable for a <code>volatile</code> object. The warnings are because your updated function returns a volatile reference, but that reference is never used. GCC thinks that this might be a problem. The simplest way to fix this is to change the return type to void!</p>
<p>There is another problem: Your function will call itself in an infinite recursion. I suggest the following:</p>
<pre><code>struct Bar {
int a;
Bar& operator=(const Bar&rhs) = default;
void operator=(const volatile Bar& rhs) volatile // Note void return.
{
// Caution: This const_cast removes the volatile from
// the reference. This may lose the point of the original
// volatile qualification.
//
// If this is a problem, use "a = rhs.a;" instead - but this
// obviously doesn't generalize so well.
const_cast<Bar&>(*this) = const_cast<const Bar&>(rhs);
}
};
volatile Bar vbar;
Bar bar;
int main(){
vbar = bar; // All four combinations work.
bar = vbar;
vbar = vbar;
bar = bar;
return 0;
}
</code></pre>
<p>This means you won't be able to chain assignment operators when using volatile structs. I assert this is not a huge loss.</p>
<p>Final aside: Why are you using <code>volatile</code> - it's not very useful for multi-threaded code (it is useful for memory mapped IO).</p>
|
View controller in a tabbar is getting black while pushing another view controller in the navigation stack <p>I am having an application in which 4 view controllers are added to the tabbar. </p>
<p>The first view controller is landing page.
The view controller is added in to the tab bar by following way.</p>
<pre><code>SNZLandingViewController *landingViewController = [[UIStoryboard landingStoryboard] instantiateViewControllerWithIdentifier:SNZLandingIdentifier];
UINavigationController *landingNavigationController = [[UINavigationController alloc] initWithRootViewController:landingViewController];
[tabBarController addChildViewController:landingNavigationController];
</code></pre>
<p>Then from landing page when the user taps a button i am pushing a view controller </p>
<pre><code>ProductsDetailsViewController *detailsPage = [[UIStoryboard storyboardWithName:@"ProductsDetailsViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ProductsDetailsViewIdentifier"];
[self.navigationController pushViewController:detailsPage animated:YES];
</code></pre>
<p>Now the details page appears. But on tapping "back" in details page, the landing page appears and is completely black.</p>
<p>One weird scenario that is happening is that, the landing page is black while navigation animation is taking place. Am i missing some thing here.
any clue or suggestion is welcome.</p>
| <p>So you don't want the navigation bar at the landing page at all?</p>
<p>Put this to your landing Page:</p>
<pre><code>override func viewWillAppear(animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: animated)
super.viewWillAppear(animated)
}
</code></pre>
<p>and this to your followup viewcontroller:</p>
<pre><code>override func viewWillAppear(animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillAppear(animated)
}
</code></pre>
<p>taken from here: <a href="http://stackoverflow.com/questions/845583/iphone-hide-navigation-bar-only-on-first-page">iPhone hide Navigation Bar only on first page</a></p>
|
How to use Anaconda Python to execute a .py file? <p>I just downloaded and installed Anaconda on my Windows computer. However, I am having trouble executing .py files using the command prompt. How can I get my computer to understand that the python.exe application is in the Anaconda folder so it can execute my .py files?</p>
| <p>Anaconda should add itself to the PATH variable so you can start any .py file with "python yourpythonfile.py" and it should work from any folder. </p>
<p>Alternatively download pycharm community edition, open your python file there and run it. Make sure to have python.exe added as interpreter in the settings.</p>
|
Robot Framework - How to get text of an element that then use that text in another keyword <p>I have a test case where I register an account with a unique email address.</p>
<p>What I want to do is sign out and sign back into the account using the newly created email address.
I have a keyword that gets the text of the email from the My account section</p>
<p><strong>Get email address</strong></p>
<pre><code>${email} get text ${contact_email}
[Return] ${email}
</code></pre>
<p>I then have another keyword that signs into the account.</p>
<p><strong>Enter Newly Registrered Email</strong></p>
<pre><code>input text ${signin_email}
</code></pre>
<p>What I want to be able to do is pass the email address that I have gotten from the 'get text' into that test case.</p>
<p>Has anyone any idea how this can be done?</p>
| <p>Assign the value of <code>${email}</code> you get from <strong>Get Email Address</strong> to a variable (f.e. <code>${new_email}</code>) and use it as an argument for <strong>Enter Newly Registrered Email</strong>:</p>
<pre><code>${new_email}= Get Email Adress
Enter Newly Registrered Email ${new_email}
</code></pre>
<p>You have to define <strong>Enter Newly Registrered Email</strong> so that it uses an argument:</p>
<pre><code>Enter Newly Registrered Email
[Arguments] ${signing_email}
input text ${signing_email}
</code></pre>
<p>If you want to do it in different test case you have to make <code>${new_email}</code> a suite variable:</p>
<pre><code>Set Suite Variable ${new_email}
</code></pre>
<hr>
<p>Further readings: </p>
<ul>
<li><a href="http://robotframework.org/robotframework/3.0/RobotFrameworkUserGuide.html#user-keyword-arguments" rel="nofollow">User keyword arguments</a>.</li>
<li><a href="http://robotframework.org/robotframework/3.0/RobotFrameworkUserGuide.html#variable-priorities-and-scopes" rel="nofollow">Variable priorities and scopes</a></li>
</ul>
|
How to make a custom control in iOS using Objective C <p>Anyone who know the implementation shows how to make a custom control. Like this,</p>
<p><a href="https://i.stack.imgur.com/AN6kv.png" rel="nofollow"><img src="https://i.stack.imgur.com/AN6kv.png" alt="enter image description here"></a></p>
<p>Where you can set range of Age and UI control like a slider that has two knobs.</p>
<p>And also this,</p>
<p><a href="https://i.stack.imgur.com/Cti5N.png" rel="nofollow"><img src="https://i.stack.imgur.com/Cti5N.png" alt="enter image description here"></a></p>
<p>Same with the first.</p>
<p>Thank you in advance :)</p>
| <p>Please check below link, You may get what you need</p>
<p><a href="https://github.com/muZZkat/NMRangeSlider" rel="nofollow">https://github.com/muZZkat/NMRangeSlider</a></p>
|
Streaming more than one video at a time <p>I want to stream through Google Chrome
and Google Cast more than one video at a time.</p>
<p>For example, I selected 3 videos and send them to chromecast using Chrome Browser.</p>
<p>Any Suggestion on How to do this?</p>
| <p>As long as you are using Cast SDK, you can form a queue of media (video or audio, not images) and load the queue and have them be played one after the other. You can even manipulate the queue (reshuffle, go next/previous, etc). The APIs to create and manage a queue is available in all three sender platforms.</p>
|
What protocols are supported for VoIP on iOS? <p>My colleagues have developed a web-based (RTC) VoIP app and I am now going to develop the iOS counterpart. However, after researching the forums, I have found several limiting factors with the iOS:</p>
<p>-No support for RTC </p>
<p>-SIP must use Mac WiFi Solution DNS64/NAT64 <a href="https://forums.developer.apple.com/thread/47658" rel="nofollow">https://forums.developer.apple.com/thread/47658</a></p>
<p>Are there any other limitations that I should be aware of? What are the recommended protocols for developing a VoIP app for iOS?</p>
<p>Thanks!</p>
| <p>There is no limiting factor with iOS to develop VOIP based app.</p>
<p>Well, about notifying user ( iOS User ) about incoming VOIP call in background / kill state, you need to handle with push kit ( Silent push notification ).</p>
<p>About users are online / offline, it would be better to get flag from sockets, not from API call each time.</p>
<p>Let me know if i could help you any more in VOIP based app.</p>
|
Reading mobile data(strings and numbers) from file in C <p>I have a file with data in the following format:</p>
<pre><code>/*Number Date Time Status Call_duration(in minutes) */
9893575103 22-09-2016 12:32:01 incoming 2
9893575102 22-09-2016 12:44:05 outgoing 3
9893575101 22-09-2016 12:59:23 missed 0
9793575103 22-09-2016 13:30:32 outgoing 9
9723575103 22-09-2016 14:44:44 incoming 4
</code></pre>
<p>I want to be able to reliably read this data into a C program and then manipulate the data once it's been parsed.</p>
<p>I tried to store data in a linked list after reading it from file using scanf:</p>
<pre><code>struct Node {
struct node *queue;
struct node *front,*rear;
int num[10];
int dd,mm,yy,hr,min,sec;
float call_dur;
char status[15];
};
main()
{
node *rear=NULL;
node *front=NULL;
node *queue;
char ch;
FILE *fp;
fp=fopen("mobile_numbers.txt","r");
while((ch=getc(fp))!=EOF) {
fseek(fp,-1,1);
fscanf(fp,"%d %d-%d-%d %d:%d:%d %s %d", &queue->num, &queue->dd, &queue->mm, &queue->yy, &queue->hr, &queue->min, &queue->sec, queue->status, &queue->call_dur);
}
if(front==NULL)
front=queue;
else
rear->next=queue;
rear=queue;
queue->next=NULL;
}
fclose(fp);
while(queue!=NULL) {
printf("%d %d-%d-%d %d:%d:%d %s %d",queue->num, queue->dd, queue->mm, queue->yy, queue->hr, queue->min, queue->sec, queue->status, queue->call_dur);
queue=queue->next;
}
</code></pre>
<p>But this isn't giving required results? Can anyone suggest a better method or see what's wrong with my code?</p>
| <p>This works. Not sure what you want to do with the data, but this prints to screen.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
#define MAXARG 20
FILE *f1;
int main(int argc, char *argv[])
{
char FileName[MAXARG];
char line[MAXLINE];
if (argc <= 1) {
printf("Usage - reads FileName and prints\n");
return 0;
}
else {
strcpy(FileName, *++argv);
}
f1 = fopen(FileName, "r");
while (fgets(line, MAXLINE, f1)) {
printf("%s", line);
}
}
</code></pre>
<p>NB: to call it, you have to type the program name followed by the name of your file.</p>
<p>If instead you want to run through and save data for parsing, try this (re-appropriated version of <a href="http://stackoverflow.com/questions/18036686/c-read-space-separated-values-from-file">C read space-separated values from file</a>):</p>
<pre><code>#define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>
#include <string.h>
typedef struct
{
char status[9];
time_t timestamp;
long int number;
int duration_mins;
time_t call_time;
} Call;
void dump_call(FILE *fp, const char *tag, const Call *c);
int inputLine(FILE *fp, Call *c);
enum { MAXCALL = 100 };
int main(void)
{
char line[4096];
Call calls[MAXCALL];
if (fgets(line, sizeof(line), stdin) == 0)
return 1;
for (int i = 0; i < MAXCALL && inputLine(stdin, &calls[i]) != 0; i++)
dump_call(stdout, "Call", &calls[i]);
return 0;
}
int inputLine(FILE *fp, Call *c)
{
struct tm tm;
// time_t epoch;
int out;
char temp[20], date_temp[9], time_temp[9];;
if ((out = fscanf(fp, "%ld %s %s %s %d",
&c->number, date_temp, time_temp, c->status, &c->duration_mins)) == 5) {
sprintf(temp, "%s %s", date_temp, time_temp);
if ( strptime(temp, "%d-%m-%Y %H:%M:%S", &tm) != NULL )
c->timestamp = mktime(&tm);
return -1;
}
return 0;
}
void dump_call(FILE *fp, const char *tag, const Call *c)
{
char date_time[20];
strftime(date_time, 20, "%d-%m-%Y %H:%M:%S", localtime(&(c->timestamp)));
fprintf(fp, "%s: %-10ld %-24s %-17s %3d\n",
tag, c->number, date_time, c->status, c->duration_mins);
}
</code></pre>
<p>This time, to call it, type name of program followed by <code><</code> and then name of data file; i.e:</p>
<pre><code>read.exe < test_mobil.dat
</code></pre>
<p>Hope this helps mate - I've learnt quite a bit as well - so thanks for that.</p>
|
How to interpret this scala syntax "Class[_ >: Float with Int with Double]" <p>When I read Mxnet source code, I was confused in following statements:</p>
<pre><code>object NDArray {
private val logger = LoggerFactory.getLogger(classOf[NDArray])
private[mxnet] val DTYPE_NATIVE_TO_MX: Map[Class[_ >: Float with Int with Double], Int] = Map(
classOf[Float] -> 0,
classOf[Double] -> 1,
classOf[Int] -> 4
)
</code></pre>
<p>What does it mean for "Class[_ >: Float with Int with Double], Int]"?
I understand the scala keyword "with" could be used during class declaration, for example</p>
<pre><code>Class person with glass {
</code></pre>
<p>means the class 'person' has the trait of objdect 'glass'. </p>
<p>How to interpret the usage of 'with' in above code?</p>
| <p>The <code>with</code> keyword is used for expressing <a href="https://en.wikipedia.org/wiki/Type_system#Intersection_types" rel="nofollow">intersection types</a>. </p>
<p>The type <code>Float with Int with Double</code> is basically a subtype of <code>Float</code> and <code>Int</code> and <code>Double</code>. Of course you cannot have an actual value of this type because <code>Float</code>, <code>Int</code> and <code>Double</code> are all final classes. Here, in the type <code>Map[Class[_ >: Float with Int with Double], Int]</code>, it is used to express that every key of the <code>Map</code> has to be a <code>Class[T]</code> where <code>T</code> has to be a supertype of <code>Float with Int with Double</code>. And those supertypes are <code>Float</code>, <code>Int</code> and <code>Double</code> (and <code>AnyVal</code> and <code>Any</code>, if we go higher up the inheritance chain).</p>
|
Codeigniter only home page working on Live server <p>I am creating a website on localhost in xampp. It is working correctly with routes working as well. Path was 'localhost/mywebsite'.</p>
<p>I uploaded that website to live server. Path is 'www.mywebsite.com/beta/'. The website is not working. Only index page is working. When I click on any other link, It says 'File not found.'.</p>
<p>Any suggestions would be appreciated.</p>
<p>This is my routes.</p>
<pre><code>$route['default_controller'] = 'front/index';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*admin*/
$route['admin'] = 'user/admin';
$route['admin/login'] = 'user/admin';
$route['admin/logout'] = 'user/logout';
$route['admin/persons'] = 'person';
$route['admin/categories'] = 'category';
$route['admin/games'] = 'game';
$route['admin/login/validate_credentials'] = 'user/validate_credentials';
/*Front End*/
$route['category/(:num)'] = "front/category/$1";
$route['game/(:num)'] = "front/game/$1";
$route['search'] = "front/search";
</code></pre>
<p>This is my config.php</p>
<pre><code>$config['base_url'] = 'http://mywebsite.com/beta/';
$config['index_page'] = '';
</code></pre>
<p>And my .htaccess</p>
<pre><code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</code></pre>
| <pre><code>-Change your htaccess code and replace this code.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
</code></pre>
|
Interactive image AngularJs <p>I have created a Web site using <code>AngularJS</code> and HTML, I want to load a static image and to create interactive spots on this image.</p>
<p>When I hover mouse on this spot, I want some popup notification with some information.</p>
<p>Which library should I use? I checked OpenLayers but I dont know if it is the right choice for what i want to do</p>
<p>I think a solution like this:
<a href="https://i.stack.imgur.com/FkTvV.png" rel="nofollow"><img src="https://i.stack.imgur.com/FkTvV.png" alt="enter image description here"></a></p>
| <p>You can use html image map. Here's an example:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click on the sun or on one of the planets to watch it closer:</p>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
<script>
$( "area" ).hover(
function() {
alert('This is ' + $( this ).attr("alt"));
}
);
</script>
</body>
</html>
</code></pre>
<p>Source:
<a href="http://www.w3schools.com/tags/tag_map.asp" rel="nofollow">w3schools</a>
<a href="https://api.jquery.com/hover/" rel="nofollow">jQuery</a></p>
|
Create server using 'app' as request handler? <p>In simple NodeJS, we can create server using -</p>
<pre><code>http.createServer(function(req,res) { /* header etc. */});
</code></pre>
<p>but I started using express and server is created automatically.
Then I proceeded to learning sockets, but socket.io required an http server to be passed as parameter to create a socket connection. So now to create the server I used - </p>
<pre><code>http.createServer(app);
</code></pre>
<p>Does this mean that <code>app = require('express')();</code> actually returns a request handler function ? What is really going on ?</p>
| <p>Yes. It actually returns a function that takes <code>(request, response, next)</code> which is one of the middleware prototypes. Essentially the express module exports a function called <code>createApplictaion</code> which returns a middleware handler. <a href="https://github.com/expressjs/express/blob/master/lib/express.js#L27" rel="nofollow">Here is the current source</a> for express, you can freely browse it. </p>
<pre><code>exports = module.exports = createApplication;
/**
* Create an express application.
*
* @return {Function}
* @api public
*/
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
}
</code></pre>
|
Date filter formatting Angularjs <p>I want to show <code>date</code> and <code>time</code> on my app in this format,</p>
<pre><code>Date: 14 - 19 Sep
Time: 16:30 to 18:30
</code></pre>
<p>And I'm getting data from server in below format,</p>
<pre><code>"EventDate":"2015-09-14T16:30:00Z",
"EndDate":"2015-09-14T18:30:00Z",
</code></pre>
<p>I tried angualrjs <code>date</code> filter,</p>
<p>and now I'm getting date in below format,</p>
<pre><code>Sep 14, 2015 - Sep 19, 2015
</code></pre>
<p>I tried many examples from <strong>SO</strong> but didn't work for me,</p>
<p><a href="http://stackoverflow.com/questions/25845202/date-formatting-angularjs-to-display-only-the-day-and-month">Date formatting AngularJS to display only the day and month</a></p>
<p>How can I display my Date in following format,</p>
<pre><code>Event Date: 14 - 19 Sep
Event Time: 16:30 to 18:30
</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-js lang-js prettyprint-override"><code>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Evdate = {
"j": [{
"EventDate": "2015-09-14T16:30:00Z",
"EndDate": "2015-09-14T18:30:00Z"
}]
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
{{Evdate.j[0].EventDate | date}} - {{Evdate.j[0].EndDate | date}}
</div></code></pre>
</div>
</div>
</p>
| <p>For month. Try this.</p>
<pre><code>{{Evdate.j[0].EventDate | date : 'd'}} - {{Evdate.j[0].EndDate | date : 'd MMM'}}
</code></pre>
<p>For time</p>
<pre><code>{{Evdate.j[0].EventDate | date : 'HH:mm'}} - {{Evdate.j[0].EndDate | date : 'HH:mm'}}
</code></pre>
<p>Hope it helps. Notify me if it doesn't work.</p>
|
How to add the values of all the fields in a struct in matlab? <p>I have a struct lets say <code>ABC</code> with dimension "1*100" struct and it has a field called <code>EFG</code> which holds a value of <code>1.6</code> each.</p>
<p>I need to get <code>1.6+1.6+1.6+.......+1.6</code> 100 times by using MATLAB.</p>
<p>I tried using <code>sum</code>but it doesn't suit for this. How can this be done?</p>
<pre><code>Sum(ABC(:).EFG)
sum(ABC(:).EFG,2)
</code></pre>
<p>These did not work</p>
| <p>You need brackets:</p>
<pre><code>for ii = 1:100 % Just creating the struct
ABC(ii).EFG = 1.6; % 1x100 struct with the field EFG
end
sum([ABC(:).EFG])
ans =
160.0000
</code></pre>
<p>Notice the brackets around <code>[ABC(:).EFG]</code>.</p>
<p>The reason is because without it you get an output from <code>ABC(:).EFG</code> that can't be used in <code>sum</code>:</p>
<pre><code>ABC(:).EFG
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
</code></pre>
<p>Concatenate it, and you'll get something you can use:</p>
<pre><code>[ABC(:).EFG]
ans =
1.6000 1.6000 1.6000 1.6000 1.6000
</code></pre>
|
How do I create a query with greater than one date and not between some other dates? <p>So I need to pull back data that is after 1st jan 2017 but NOT between Oct 2016 and 31st dec 2016</p>
<p>This is my current code:</p>
<pre><code>SELECT [SequenceID]
,[AppointmentDate]
FROM dbo].[AmsAppointment]
where AppointmentDate >= Convert(datetime, '2017-01-01' ) and AppointmentDate <= Convert(datetime, '2016-10-01' )
</code></pre>
<p>I know the code is wrong so please help me.</p>
| <p>You can do this a number of ways, but I think a <code>not between</code> would work best:</p>
<pre><code>SELECT [SequenceID], [AppointmentDate]
FROM [dbo].[AmsAppointment]
where
AppointmentDate >= '2017-01-01' and
AppointmentDate not between '2016-10-01' and '2017-12-31'
</code></pre>
<p>And maybe your example just that, but in your scenario, since the ranges overlap, this really translates to:</p>
<pre><code> AppointmentDate >= '2017-12-31'
</code></pre>
|
Android Notifications cutom view and button press <p>I have notification with custom view that contains button. When user press the button in notification it should get some Toast mesage. However Toast never shows up because <code>onReceive</code> is never called. What I'm doing wrong? </p>
<pre><code> int icon = R.drawable.play;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, "Custom Notification", when);
RemoteViews notificationView = new RemoteViews(this.getPackageName(),R.layout.notification);
PendingIntent listenerIntent = PendingIntent.getService(this, 0, new Intent(this, AudioControlListener.class), 0);
notificationView.setOnClickPendingIntent(R.id.background, listenerIntent);
notification.contentView = notificationView;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
startForeground(1, notification);
</code></pre>
<p>my broadcast receiver class</p>
<pre><code> public static class AudioControlListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Button pressed", Toast.LENGTH_SHORT).show();
}
}
</code></pre>
| <p>You're using <code>PendingIntent.getService()</code> with an <code>Intent</code> that has a <code>BroadcastReceiver</code> target. You need to use <code>PendingIntent.getBroadcast()</code> instead. And make sure your Receiver is registered in the manifest.</p>
|
how to customize this stacked bar chart with d3 <p>I'm newbie with d3 library
I found this stacked bar chart I want to customize it to use it </p>
<p><a href="http://codepen.io/benlister/pen/bNeLQy" rel="nofollow">http://codepen.io/benlister/pen/bNeLQy</a>
thats the two lines that I wanna customize</p>
<pre><code> .attr("y", function (d) {return y(d.y1);})
.attr("height", function (d) {return y(d.y0) - y(d.y1);})
</code></pre>
<p>I tried to customize it's height but it's not working for me </p>
<ul>
<li><p>I want the left axis to have the actual numbers not percent </p></li>
<li><p>I want the height to differs from each one depending on it's total value </p></li>
</ul>
| <p>In</p>
<pre><code>d.y0 /= y0;;
d.y1 /= y0;;
</code></pre>
<p>You divide <code>d.y0</code> and <code>d.y1</code> with <code>y0</code> (which in this case is the sum of all rates and you get percentage instead. So step 1 is to remove this (delete these two rows).</p>
<p>Step 2 is to remove the '%-format for the y-axis. So change</p>
<pre><code>var yAxis = d3.svg.axis().scale(y).orient("left").tickFormat(d3.format(".0%"));
</code></pre>
<p>to</p>
<pre><code>var yAxis = d3.svg.axis().scale(y).orient("left");
</code></pre>
<p>Finally you have to set the domain for <code>y</code>to <code>[0,yMax]</code> instead of <code>[0,1]</code> which can be done by updating the <code>data.forEach</code> to (not most optimal way)</p>
<pre><code>var maxY = 0;
data.forEach(function (d) {
var y0 = 0;
d.rates = color.domain().map(function (name) {
console.log();;
return {
name: name,
y0: y0,
y1: y0 += +d[name],
amount: d[name]
};
});
d.rates.forEach(function (d) {
//d.y0 /= y0;
//d.y1 /= y0;
});
maxY = Math.max(y0,maxY);
console.log(data);
});
y.domain([0,maxY]);
</code></pre>
<p>See <a href="http://codepen.io/anon/pen/JRkjGE" rel="nofollow">http://codepen.io/anon/pen/JRkjGE</a></p>
|
C# auto fit to any screen resolution <p>I am working on a small project using MS Visual Studio C# 2010.</p>
<p>In my MainFormDesigner.cs file I have the following code. All it does is load a web page from my server. I need the app to fill the display which is 1080 x 1920. But when I save and build the app some the the sizes default to the resolution of the screen I am working on.</p>
<p>Is there a way to automatically size the app to fit the resoltion of any screen the app runs on.</p>
<pre><code>namespace Impa_Browser
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.browser = new System.Windows.Forms.WebBrowser();
this.connectLbl = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// browser
//
this.browser.Location = new System.Drawing.Point(0, 0);
this.browser.Margin = new System.Windows.Forms.Padding(0);
this.browser.MinimumSize = new System.Drawing.Size(20, 20);
this.browser.Name = "browser";
this.browser.ScrollBarsEnabled = false;
this.browser.Size = new System.Drawing.Size(1080, 1920); // THIS IS THE RESOLUTION OF THE DISPLAY THE APP WILL RUN ON
this.browser.TabIndex = 0;
this.browser.Url = new System.Uri("example.com", System.UriKind.Absolute);
this.browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.browser_DocumentCompleted);
//
// connectLbl
//
this.connectLbl.Dock = System.Windows.Forms.DockStyle.Fill;
this.connectLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.connectLbl.Location = new System.Drawing.Point(0, 0);
this.connectLbl.Name = "connectLbl";
this.connectLbl.Size = new System.Drawing.Size(1080, 1092); // THIS KEEPS CHANGING TO THE RESOLUTION OF THE SCREEN I AM WORKING ON
this.connectLbl.TabIndex = 1;
this.connectLbl.Text = " Trying to connect ...[20] Please check your Internet router";
this.connectLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1080, 1092); // THIS KEEPS CHANGING TO THE RESOLUTION OF THE SCREEN I AM WORKING ON
this.Controls.Add(this.browser);
this.Controls.Add(this.connectLbl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Impa";
this.Load += new System.EventHandler(this.MainForm_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser browser;
private System.Windows.Forms.Label connectLbl;
}
}
</code></pre>
<p>Many thanks for any help you can provide.</p>
| <p>If you are using WinForms you can set the WindowState to <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.formwindowstate%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396" rel="nofollow">FormWindowState</a> Maximized like this.</p>
<pre><code>this.WindowState = FormWindowState.Maximized;
</code></pre>
<p>For WPF user <a href="https://msdn.microsoft.com/de-de/library/system.windows.forms.form.windowstate(v=vs.110).aspx" rel="nofollow">WindowsState</a> Maximized</p>
<pre><code>this.WindowState = WindowState.Maximized;
</code></pre>
|
Getting all positions of bit 1 in javascript? <p>I have provided binary for example, <code>01001</code>, and would like to get positions of bit 1, so I expect it will return me <code>[0, 3]</code>.</p>
<p>Is there any function provided by javascript to get all positions of bit 1?</p>
| <p>If it's a number, convert it to a string before hand, if it is a string you can do:</p>
<pre><code>positionArray = [];
binary.split('');
for (i = 0; i < binary.length; i++){
if (binary[i] == "1"){
positionArray.push(i);
}
}
return positionArray;
</code></pre>
<p>What i'm essentially doing is converting the string to an array (or number to a string to an array) of characters and then going through each entry to find the positions of each '1'.</p>
<p>Not sure you can do it this way with numbers, which is why I suggested converting it to a string before hand. It's just a rough solution and I bet there are much better ways of doing it but hope it helps.</p>
|
What to use as hover effect for an image? <p>I want to achieve the following hover effect on my portfolio elements -
<a href="http://imgur.com/a/JGhLT" rel="nofollow">link with before and after</a>.</p>
<p>I am using Bootstrap with Masonry so the HTML for the original image is looking like that:</p>
<pre><code><div class="col-md-4 col-sm-6 item">
<img src="img/portfolio3.jpg">
</div>
</code></pre>
<p>I can use jQuery <code>.hover()</code> function to swap the image source and also I was thinking for the heading and button to have the two elements hidden before the hover event like following:</p>
<p>HTML</p>
<pre><code><div class="col-md-4 col-sm-6 item">
<img src="img/portfolio3.jpg">
<div class="captions">
<h3>AncaGV Blog</h3>
<button></button>
</div>
</div>
</code></pre>
<p>jQuery</p>
<pre><code>$('.item img').hover(function(){
$(this).attr('src','portfolio3b.jpg');
$(this).next().slideToggle('slow');
});
</code></pre>
<p>Please note that I've just write the code here, haven't tested yet because I want to ask if there is a possibility to use CSS for the shadow effect instead of swaping the image sources.</p>
<p>Also, if someone could suggest maybe a better aproach regarding the heading and the button I would be more than glad to try it out. For now I am thinking to hide the div and position it over the bottom of the image.</p>
| <p>Go with <code>:hover</code>. If anything can be done by CSS, don't turn to JavaScript. </p>
<p>For example: </p>
<pre><code>img {
background: url("img.png");
}
</code></pre>
<p>Ideally, you <strong>should</strong> use CSS sprites for icons, flags and/or any "smaller images", by setting the <code>background-position</code>.</p>
<p>More on <a href="http://www.w3schools.com/css/css_image_sprites.asp" rel="nofollow">CSS Sprites</a>.</p>
|
Subscribed topics <p>In my forum I'm showing all topics. It looks like this:</p>
<p><a href="https://i.stack.imgur.com/BjALF.png" rel="nofollow"><img src="https://i.stack.imgur.com/BjALF.png" alt="enter image description here"></a></p>
<p>So a user can subscribe by clicking on the red hearth. </p>
<p>I'm loading the topics with this json:</p>
<pre><code>{
"forum": {
"id": 1,
"slug": "test",
"name": "test",
"description": "test",
"created_at": null,
"updated_at": null
},
"topics": {
"total": 6,
"per_page": 5,
"current_page": 1,
"last_page": 2,
"next_page_url": "http://forum.dev/api/forum/test?page=2",
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 2,
"slug": "2",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 3,
"slug": "1",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 4,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 5,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
}
]
}
}
</code></pre>
<p>I'm returning that ^ like this:
<code>$forum->topics()->orderBy('created_at', 'DESC')->paginate(5);</code></p>
<p>So how do I get a subscribe value on every topic object?</p>
<p>So like this:</p>
<pre><code> "data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null,
"subscribed": true
},
</code></pre>
<p>I already made this on my <code>topic</code> model:</p>
<pre><code> /**
* @return mixed
*/
public function subscriptions()
{
return Topic::subscribedBy(Auth::user())->get();
}
</code></pre>
<p>And it's working. But how do I send that ^ with every topic. </p>
| <p>You can add an attribute (which is not present in the database) by creating an accessor.</p>
<pre><code>public function getSubscriptionsAttribute()
{
return Topic::subscribedBy(Auth::user())->get();
}
</code></pre>
<p>and then adding it to the <code>$append</code> property.</p>
<pre><code>protected $appends = ['subscriptions'];
</code></pre>
<p>If you're using the <code>$visible</code> whitelist you might have to add it to that property too.</p>
<p><a href="https://laravel.com/docs/5.0/eloquent#converting-to-arrays-or-json" rel="nofollow">Source</a> (Its all the way in the bottom.)</p>
|
Run RobotFramework tests with Sikuli Library with Jenkins on VM (RDC) <p>I have automation tests based on RobotFramework with SikuliLibrary, which are for Image Compare. I'm using Jenkins to run on external server (VM) the tests.
If I open the VM - image compare script works. The screenshot is created.</p>
<p>If I close the VM session and run the test, there is problem. Here is the log from keyword "Get Match Score":</p>
<p><code>INFO Could not find C:\Images\image.png
INFO ${scoreFromImage} = 0.0</code></p>
<p>Is look like, when the VM session is not active (opened), "Get Match Score" cannot take a snapshot from the browser for comparing.</p>
<p>Is there any idea, how to fix this?</p>
<p>The Code:</p>
<p><code>Compare Process Diagram Image
[Arguments] ${ImageName} ${ImageScore}
${scoreFromImage} = Get Match Score ${ImagesDirectory}${ImageName}.png
${scoreToString} = Convert To String ${scoreFromImage}
${scoreNumberPrecision} = Get Substring ${scoreToString} 0 6
Run Keyword If ${scoreNumberPrecision} == ${ImageScore} Log Successful ELSE Log Fail</code></p>
| <p>Running Sikuli Test on VM is possible but need to keep session open. We cannot run Sikuli script on locked PC. When you close VM , it get locked and Test fail to run. Sikuli needs images for comparing and clicking, if session is locked there are no images so Test fail to run.
So how we overcome this ? :
<a href="https://support.smartbear.com/viewarticle/85926/" rel="nofollow">https://support.smartbear.com/viewarticle/85926/</a></p>
<p>refer this URL for setting . By applying this you can run sikuli Test with minimized window of VM. (Still you cannot close WM window) </p>
|
translating sql to SSIS expression builder <p>How to do the below in SSIS expression?</p>
<pre><code>select REVERSE(LEFT(REVERSE(filename),CHARINDEX('\', REVERSE(filename), 1) - 1))
</code></pre>
<p>Just stuck getting the filename but would want to do it in a package from the source in SSIS expression</p>
| <p>If we assume we have a whole path of the file <code>(eg. C\folder\filename...)</code> in a user variable <code>(eg. @[User::Variable])</code>, yuo can try with:</p>
<pre><code>RIGHT( @[User::Variable], FINDSTRING(REVERSE( @[User::Variable] ) , "\\", 1) - 1)
</code></pre>
<p>I hope this help.</p>
|
xamarin forms How to pass enum value to XAML and use it in switch statement? <p>I declared enum with some values and I want to pass to my Formated parameter. Here is my C# code:</p>
<pre><code> public MyControllerView()
{
ContentEntry.TextChanged += Entry_TextChanged;
}
public string Formated
{
get
{
return formatedText;
}
set
{
formatedText = value;
}
}
public enum FomationType
{
NameValidation,
CardNrValidation,
ExpDate
};
// here I want to use my enum in switch statement, but I can't, because I can't modify my method parameters
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
FomationType FomationType;
switch (FomationType)
{
case FomationType.NameValidation:
ToUpper(ent);
break;
case FomationType.CardNrValidation:
CardNumberValidation(ent);
break;
case FomationType.ExpDate:
ExpDate(ent, e);
break;
}
}
</code></pre>
<p>And here is my XAML code with Formated parameter where I have to pass my enum value:</p>
<pre><code><ContentPage.Content>
<StackLayout Padding="7,7,7,7" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Spacing="0">
<cv:MyControllerView LabelText="some text 4" Placeholder="some text 4" Formated="" Keyboard="Text" >
</cv:MyControllerView>
<cv:MyControllerView LabelText="some text 3" Placeholder="some text 3" Formated="" Keyboard="Numeric" >
</cv:MyControllerView>
<cv:MyControllerView LabelText="some text 2" Placeholder="some text 2" Formated="" Keyboard="Numeric" >
</cv:MyControllerView>
</StackLayout>
</ContentPage.Content>
</code></pre>
<p>Now some how I should pass FormationType anum to Formated="" parameter. And should I assign my Formated string to enum values?</p>
| <p>Well, to solve this issue regarding <a href="http://forums.xamarin.com/discussion/46778/how-to-set-default-value-converter-for-a-custom-control" rel="nofollow">this</a> forum post helped for my to figure out everything. Here is my C# code:</p>
<pre><code>public enum FomationType
{
NameValidation,
CardNrValidation,
ExpDate
};
public FomationType Formated { get; set; }
</code></pre>
<p>and here my switch statment:</p>
<pre><code>var ent = sender as Entry;
switch (Formated)
{
case FomationType.NameValidation:
ToUpper(ent);
break;
case FomationType.CardNrValidation:
CardNumberValidation(ent);
break;
case FomationType.ExpDate:
ExpDate(ent, e);
break;
}
</code></pre>
<p>XAML property doesn't change:</p>
<pre><code><cv:MyControllerView LabelText="some text 4" Placeholder="some text 4" Formated="NameValidation" Keyboard="Text" >
</code></pre>
|
Rails combining RESTful methods in a new controller <p>I have a rails app where <code>users</code> create <code>projects</code>. Currently these are nested, and are completed as separate actions (A <code>user</code> registers, and then from the <code>project</code> dashboard creates a new <code>project</code>).</p>
<p>To improve conversions (as well as track conversions from adwords and facebook) I want to create a new view called <code>getting_started</code> whereby a <code>user</code> will register and create a <code>project</code> in one step from a single view.</p>
<p>In terms of best practice, should I create a new controller for this, rather than just slapping a new view in <code>users</code>?</p>
| <p>In my opinion better way is create another controller. Then you have better atomization of code. Which is easier to refactor. You can inherit this controller, and use <code>super</code> for creating user.</p>
|
Realm - mix models from different projects <p>I have a model in my Main project:</p>
<pre><code>public class A extends RealmObject{
private String var1;
private B var2;
//... more
}
</code></pre>
<p>Also, I have my class <code>B</code> in my library (different android-studio module)</p>
<pre><code>public class B extends RealmObject{
private String var1;
//... more
}
</code></pre>
<p>I cannot build this because of: </p>
<blockquote>
<p>Error:Error converting bytecode to dex: Cause:
com.android.dex.DexException: Multiple dex files define
Lio/realm/DefaultRealmModule;</p>
<p>Error:Execution failed for task ':Container:transformClassesWithDexForDebug'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException</p>
</blockquote>
<p>I'm setting my own module: </p>
<pre><code>@NonNull
public static RealmConfiguration getRealmConfiguration(String name) {
return new RealmConfiguration.Builder()
.name(name)
.deleteRealmIfMigrationNeeded()
.modules(new MyRealmModule())
.build();
}
@RealmModule(allClasses = true, library = true)
public static class MyRealmModule{
}
</code></pre>
<p>It should take my models from both projects, Am I right? </p>
<p>my gradle:</p>
<blockquote>
<p>classpath "io.realm:realm-gradle-plugin:2.0.2"</p>
</blockquote>
<p>and </p>
<blockquote>
<p>apply plugin: 'realm-android'</p>
</blockquote>
<p>in both projects</p>
<p>How to do it in right way?</p>
| <p>You have to use RealmModule to expose your schema in library project. </p>
<p>Check out the doc: <a href="https://realm.io/docs/java/latest/#sharing-schemas" rel="nofollow">https://realm.io/docs/java/latest/#sharing-schemas</a></p>
|
Expiry time for member in Redis <p>I'm using Jedis client to store geo coordinates in Redis.</p>
<p>Is there any way to set expiry time for member in Redis? I know, I can set the expiry time for a key.</p>
<p>For example, I added below three coordinates and now I want to expire "Bahn" member in 10 secs.</p>
<pre><code>redis.geoadd(key, 8.6638775, 49.5282537, "Weinheim");
redis.geoadd(key, 8.3796281, 48.9978127, "EFS9");
redis.geoadd(key, 8.665351, 49.553302, "Bahn");
</code></pre>
| <p>Behind the scene, GEOADD uses a ZSET to store its data.</p>
<p>You can store the same data (without geolocation) in a second ZSET, with a unix timestamp as score this time, using a regular ZADD command.</p>
<pre><code>ZADD expirationzset <expiration date> <data>
</code></pre>
<p>You can get the expired data from this second ZSET, using</p>
<pre><code>ZRANGEBYSCORE expirationzset -inf <current unix timestamp>
</code></pre>
<p>Then you have to remove them from both ZSETs, using ZREM for the geolocation ZSET, and ZREMRANGEBYSCORE for the expiration zset:</p>
<pre><code>ZREM geolocationzset <expired_data1> <expired_data3> <expired_data3>...
ZREMRANGEBYSCORE expirationzset -inf <current unix timestamp>
</code></pre>
|
Java : Sort String formatted as XML using attributes <p>I have a String formatted as XML which I need to sort using attribute key. The result should also be a sorted xml format of String. I am not able to do so.</p>
<p>The XML String format is:</p>
<pre><code><Main>
<Node>
<name>ABC</name>
<address>SFO</address>
<contact>John</contact>
<phone>(04115) 30514</phone>
</Node>
<Node>
.....
</Node>
<Node>
.....
</Node>
</Main>
</code></pre>
<p>I need to sort this on the basis of name, address, contact etc. Please help.</p>
<p><strong>UPDATE</strong></p>
<p>I am using <a href="http://www.jdom.org/" rel="nofollow">JDOM</a> library to try to sort the XML. I have creating a XML file from the XML String and trying to use comparator based on attribute key but am getting NUll Pointer on Comparator Object. Below is the code:</p>
<pre><code>File xmlFile = new File(filePath);
SAXBuilder builder = new SAXBuilder();
org.jdom2.Document document = null;
try {
document = (org.jdom2.Document) builder.build(xmlFile);
} catch (JDOMException e1) {
System.out.println(Constants.JDOM_ERROR+e1.getLocalizedMessage());
} catch (IOException e1) {
System.out.println(Constants.IO_EXCEPTION+e1.getMessage());
}
org.jdom2.Element rootElement = document.detachRootElement();
List<org.jdom2.Element> children = new ArrayList<org.jdom2.Element>(rootElement.getChildren());
rootElement.removeContent();
Comparator<org.jdom2.Element> comparator = new Comparator<org.jdom2.Element>() {
public int compare(org.jdom2.Element o1, org.jdom2.Element o2) {
return o2.getAttributeValue(key).compareTo(o1.getAttributeValue(key));
}
};
Collections.sort(children, comparator);
org.jdom2.Document newDocument = new org.jdom2.Document(rootElement);
rootElement.addContent(children);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
try {
xmlOutput.output(newDocument, new FileWriter("sorted.xml"));
} catch (IOException e) {
System.out.println(Constants.IO_EXCEPTION+e.getMessage());
}
</code></pre>
<p>Am getting NUll pointer at this line </p>
<blockquote>
<p>return o2.getAttributeValue(key).compareTo(o1.getAttributeValue(key));</p>
</blockquote>
<p>here is the stack trace:</p>
<pre><code>Exception in thread "main" java.lang.NullPointerException
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:351)
at java.util.TimSort.sort(TimSort.java:230)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.ArrayList.sort(ArrayList.java:1454)
at java.util.Collections.sort(Collections.java:175)
</code></pre>
| <p>The JDOM API offers sorting in the Element class: <a href="http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#sortChildren(java.util.Comparator)" rel="nofollow">http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#sortChildren(java.util.Comparator)</a></p>
|
Two fullscreen menus - how to show one and hide the other - using toggleclass <p>I'm using <code>jquery</code> <code>toggleclass</code> to show and hide a fullscreen menu. The problem arises because there are two fullscreen menus. If one is open, how do I hide it if the user clicks on the other one?</p>
<p>I'm guessing I need to toggle the show/hide class on both <code>divs</code>. So when one is 'show' the other is 'hide'. But how do I do this? I've worked out how to toggle a class on one <code>div</code>, but not two.</p>
<p><a href="https://jsfiddle.net/facnr6f9/" rel="nofollow">https://jsfiddle.net/facnr6f9/</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-js lang-js prettyprint-override"><code>$(document).ready(function(){
$(".projects_link").click(function(){
$(".projects_overlay").toggleClass("show_projects");
});
});
$(document).ready(function(){
$(".menu_link").click(function(){
$(".menu_overlay").toggleClass("show_menu");
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.projects_overlay {
display: none;
}
.show_projects {
display: block;
position: fixed;
top: 7.2rem;
left: 0;
width: 100%;
bottom: 0;
background-color: pink;
}
.menu_overlay {
display: none;
}
.show_menu {
display: block;
position: fixed;
top: 7.2rem;
left: 0;
width: 100%;
bottom: 0;
background-color: pink;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="projects_link">PROJECTS</span>
&nbsp;&nbsp;&nbsp;&nbsp;
<span class="menu_link">MENU</span>
<div class="projects_overlay">
<ul>
<li>Project 1</li>
<li>Project 2</li>
<li>Project 3</li>
<li>Project 4</li>
<li>Project 5</li>
</ul>
</div>
<div class="menu_overlay">
<ul>
<li>Page 1</li>
<li>Page 2</li>
<li>Page 3</li>
<li>Page 4</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
| <p>Ensure that the class is removed from the other menu when one is selected.</p>
<p>For example:</p>
<pre><code>$(".menu_link").click(function(){
$(".projects_overlay").removeClass("show_projects");
$(".menu_overlay").toggleClass("show_menu");
});
</code></pre>
<p><a href="https://jsfiddle.net/facnr6f9/1/" rel="nofollow">https://jsfiddle.net/facnr6f9/1/</a></p>
|
Filter minions by memory size <p>Is it possible in Salt Stack to filter minions by memory size, but indicating value that the memory size must be greater or less than, rather than equal to? So instead of this:</p>
<pre><code>salt -C 'G@mem_total:993' test.ping
</code></pre>
<p>I need somthing like this:</p>
<pre><code>salt -C 'G@mem_total > 993' test.ping
</code></pre>
| <p>I'm afraid you actually can't by using the <a href="https://docs.saltstack.com/en/latest/topics/targeting/" rel="nofollow">targeting feature</a> as it is.</p>
<p>First thing that comes in my mind is writing a <a href="https://docs.saltstack.com/en/latest/topics/grains/#writing-grains" rel="nofollow">custom grain</a>.</p>
<p>If you only need this in one place and the value does not change often this might be a workaround:</p>
<p><strong>untested example</strong>:</p>
<pre><code>#!/usr/bin/env python
from psutil import virtual_memory
def categorize_memory():
grains = {}
mem = virtual_memory()
total_mem = mem.total
if total_mem < 1024 * 999:
grains['memory_category'] = 'low_mem_minion'
else:
grains['memory_category'] = 'high_mem_minion'
return grains
</code></pre>
<p>Afterwards use it like that <code>salt -C 'G@memory_category:high_mem_minion' test.ping</code></p>
<p>The code for resolving memory from within python was taken from <a href="http://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python">Get total physical memory in Python</a></p>
|
AutoCAD Get Length from BlockReference. <p><strong>The Problem</strong></p>
<p>im struggling to get the Length from a BlockReference in AutoCAD.
I somehow being a math noob got the Widh & Height but i cannot get the Length
so far of a BlockReference.
Is there a way of getting the Length of a BlockReference. Ive looked through the AutoCad API but without succsess. Maybe someone can show me the Direction.</p>
<p><strong>What ive Done</strong></p>
<pre><code> public static double GetBlockWidthAndHeight(BlockReference blockReference) {
try {
var db = HostApplicationServices.WorkingDatabase;
var blockname = blockReference.Name;
double width = 0;
using (var tr = db.TransactionManager.StartTransaction()) {
var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!bt.Has(blockname)) {
return 0;
}
var btrec = (BlockTableRecord)tr.GetObject(bt[blockname], OpenMode.ForRead, false);
Extents3d? bounds;
bounds = btrec.Bounds;
if (bounds.HasValue) {
var ext = bounds.Value;
width = ext.MaxPoint.X - ext.MinPoint.X;
double height = ext.MaxPoint.Y - ext.MinPoint.Y;
}
else {
var bref = new BlockReference(Point3d.Origin, bt[blockname]);
bounds = bref.Bounds;
var ext = bounds.Value;
width = ext.MaxPoint.X - ext.MinPoint.X;
double height = ext.MaxPoint.Y - ext.MinPoint.Y;
bref.Dispose();
}
tr.Commit();
}
return width;
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
return 0;
}
</code></pre>
| <p>Is your block reference a 3D object? If so. I noticed that you currently get the bounds of the object along the X axis (Width) and Y Axis (Height) but you're missing utilizing the Z Axis. If the Block Reference is a 2D object, then going about the method you described won't work since that information simply isn't there.</p>
<p>You can also try looking at the properties of the Block Reference under the AutoCAD 'Properties' palette. Depending on how the block reference was made, there may already be values for it's dimensions that you can simply access via the API.</p>
<p>Here's a link to Kean Wamsley's blog giving some brief examples of how to utilize the API to access the block info directly - <a href="http://through-the-interface.typepad.com/through_the_interface/2009/03/accessing-the-properties-of-a-dynamic-autocad-block-using-net.html" rel="nofollow">http://through-the-interface.typepad.com/through_the_interface/2009/03/accessing-the-properties-of-a-dynamic-autocad-block-using-net.html</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.